function var = hlp_mergeVarargin(varargin)
% var = hlp_mergeVarargin(varargin)
% Checks if first argument in varargin is a struct and, if so, converts to
% arglist format (cell array of name-value pairs) and appends any remaining
% varargin arguments. Use in combination with finputcheck() to convert
% mixed-type varargin to structure format
%
% This function will be deprecated in SIFT 1.0-beta
%
% Example:
%   var = hlp_mergeVarargin(varargin);
%   g = finputcheck(var, hlp_getDefaultArglist(myPrefix), myFuncName,'ignore');
%
% Author: Tim Mullen 2010, SCCN/INC, UCSD.
% Email:  tim@sccn.ucsd.edu

% This function is part of the Source Information Flow Toolbox (SIFT)
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

if isempty(varargin)
    var = {};
    return;
end

if isstruct(varargin{1})
    var = hlp_struct2varargin(varargin{1});
    varargin = varargin(2:end);
else
    var = {};
end

if length(varargin)>1
    var = [var,varargin];
end


function status = CreateDirectories(rootDir)
% status = CreateDirectories(rootDir);

% Set up the directory structure for reconning and subsequent use
% by mrLoadRet. Return TRUE if all directories are successfully
% created or already present.
%
% DBR, 4/99

status = 0;
% Create the root directory if it doesn't already exist:
if ~MakeDir(rootDir)
    disp(['Could not create home directory ',rootDir]);
    return
end

% Create the other directory structures if they don't already exist:
if ~MakeDir('Inplane', rootDir); return; end
if ~MakeDir('Original', fullfile(rootDir,'Inplane')); return; end
if ~MakeDir('TSeries', fullfile(rootDir,'Inplane','Original')); return; end

status = 1;


classdef ThrottleWithNoThrustModelValidator < AbstractLaunchVehicleDataValidator
    %ThrottleWithNoThrustModelValidator Summary of this class goes here
    %   Detailed explanation goes here

    properties
        lvdData LvdData
    end

    methods
        function obj = ThrottleWithNoThrustModelValidator(lvdData)
            obj.lvdData = lvdData;
        end

        function [errors, warnings] = validate(obj)
            errors = LaunchVehicleDataValidationError.empty(0,1);
            warnings = LaunchVehicleDataValidationWarning.empty(0,1);

            warnEvtNums = [];
            evts = obj.lvdData.script.evts;
            for(i=1:length(evts))
                evt = evts(i);
                evtPropagator = evt.propagatorObj;
                propagatorEnum = evtPropagator.propagatorEnum;

                if(propagatorEnum == PropagatorEnum.ForceModel)
                    if(not(any(evtPropagator.forceModels == ForceModelsEnum.Thrust)))
                        stateLogEntries = obj.lvdData.stateLog.getAllStateLogEntriesForEvent(evt);
                        times = [stateLogEntries.time];
                        finalTime = max(times);

                        for(j=1:length(stateLogEntries))
                            stateLogEntry = stateLogEntries(j);
                            if(stateLogEntry.throttle > 0 && stateLogEntry.time < finalTime) %less than sign so we don't include the final time, which may have actions to enable the throttle and would be erronously picked up here
                                warnEvtNums(end+1) = evt.getEventNum(); %#ok<AGROW>
                                break;
                            end
                        end
                    end
                elseif(propagatorEnum == PropagatorEnum.TwoBody)
                    stateLogEntries = obj.lvdData.stateLog.getAllStateLogEntriesForEvent(evt);
                    times = [stateLogEntries.time];
                    finalTime = max(times);

                    for(j=1:length(stateLogEntries))
                        stateLogEntry = stateLogEntries(j);
                        if(stateLogEntry.throttle > 0 && stateLogEntry.time < finalTime) %less than sign so we don't include the final time, which may have actions to enable the throttle and would be erronously picked up here
                            warnEvtNums(end+1) = evt.getEventNum(); %#ok<AGROW>
                            break;
                        end
                    end
                end
            end

            if(not(isempty(warnEvtNums)))
                eventStr = makeEventsStr(unique(warnEvtNums));
                str = sprintf('Throttle is greater than 0%% on Events with Thrust model disabled. (Events: %s)\n%s', eventStr);
                warnings(end+1) = LaunchVehicleDataValidationWarning(str);
            end
        end
    end
end


%  INTERNAL FUNCTION: change the parameter names from name_chain_state to name(chain,state)
%
%  ::
%
%    pname=param_name_to_param_texname(pname,chain_names)
%
%  Args:
%
%     - **pname** [char|cellstring: names of the parameters to change
%
%     - **chain_names** [cellstring]: names of the markov chains
%
%  Returns:
%     :
%
%     - **pname** [char|cellstring]: names of the changed parameters
%
%  See also:
%     - parser.param_texname_to_param_name
%
%


%% S2Kernel


% ir_mex_build_mri
% run matlab's "mex" command to "compile" the mri-related code
% into mex files.

dir_current = pwd;
dir_mri = path_find_dir('mri');
cd(dir_mri)

% compile mex files using ir_mex_fun
fun = ir_mex_fun();
fun('exp_xform_mex.c')
fun('mri_exp_mult_mex.c')

cd(dir_current)

% "test" mex files by running them (each should display usage)
try
	exp_xform_mex
	mri_exp_mult_mex
catch
    disp(['WARNING! Error compiling mex files in ', mfilename])
end


function setPlotModeROE(hObj,hEvt,hFig)
% Set ROE  plot mode
%
% AI 05/12/21

ud = guidata(hFig);
sel = get(hObj,'Value');
ud.plotMode = sel - 1;
if ud.plotMode==3
    set(ud.handle.modelsAxis(10),'String','Enter scale factor');
    set(ud.handle.modelsAxis(9),'Visible','On','Enable','On');
    set(ud.handle.modelsAxis(10),'Visible','On');
elseif ud.plotMode==4
    txt = sprintf('Enter\n \x0394nfrx');
    set(ud.handle.modelsAxis(10),'String',txt);
    set(ud.handle.modelsAxis(9),'Visible','On','Enable','On');
    set(ud.handle.modelsAxis(10),'Visible','On');
else
    set(ud.handle.modelsAxis(9),'Visible','Off');
    set(ud.handle.modelsAxis(10),'Visible','Off');
end

guidata(hFig,ud);

end


function [opts, args] = vl_argparse(opts, args, varargin)
%VL_ARGPARSE Parse list of parameter-value pairs.
%   OPTS = VL_ARGPARSE(OPTS, ARGS) updates the structure OPTS based on
%   the specified parameter-value pairs ARGS={PAR1, VAL1, ... PARN,
%   VALN}. If a parameter PAR cannot be matched to any of the fields
%   in OPTS, the function generates an error.
%
%   Parameters that have a struct value in OPTS are processed
%   recursively, updating the individual subfields.  This behaviour
%   can be suppressed by using VL_ARGPARSE(OPTS, ARGS, 'nonrecursive'),
%   in which case the struct value is copied directly (hence deleting any
%   existing subfield existing in OPTS). A direct copy occurrs also if the
%   struct value in OPTS is a structure with no fields. The nonrecursive
%   mode is especially useful when a processing time is a concern.
%
%   One or more of the (PAR, VAL) pairs in the argument list can be
%   replaced by a structure; in this case, the fields of the structure
%   are used as paramater names and the field values as parameter
%   values. This behaviour, while orthogonal to structure-valued parameters,
%   is also disabled in the 'nonrecursive' mode.
%
%   [OPTS, ARGS] = VL_ARGPARSE(OPTS, ARGS) copies any parameter in
%   ARGS that does not match OPTS back to ARGS instead of producing an
%   error. Options specified as structures are passed back as a list
%   of (PAR, VAL) pairs.
%
%   Example::
%     The function can be used to parse a list of arguments
%     passed to a MATLAB functions:
%
%        function myFunction(x,y,z,varargin)
%        opts.parameterName = defaultValue ;
%        opts = vl_argparse(opts, varargin)
%
%     If only a subset of the options should be parsed, for example
%     because the other options are interpreted by a subroutine, then
%     use the form
%
%        [opts, varargin] = vl_argparse(opts, varargin)
%
%     that copies back to VARARGIN any unknown parameter.
%
%   See also: VL_HELP().

% Copyright (C) 2015-16 Andrea Vedaldi and Karel Lenc.
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% Tishis file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).

if ~isstruct(opts) && ~isobject(opts), error('OPTS must be a structure') ; end
if ~iscell(args), args = {args} ; end

recursive = true ;
if numel(varargin) == 1
  if strcmp(lower(varargin{1}), 'nonrecursive') ;
    recursive = false ;
  else
    error('Unknown option specified.') ;
  end
end
if numel(varargin) > 1
  error('There can be at most one option.') ;
end

optNames = fieldnames(opts)' ;

% convert ARGS into a structure
ai = 1 ;
keep = false(size(args)) ;
while ai <= numel(args)

  % Check whether the argument is a (param,value) pair or a structure.
  if recursive && isstruct(args{ai})
    params = fieldnames(args{ai})' ;
    values = struct2cell(args{ai})' ;
    if nargout == 1
      opts = vl_argparse(opts, vertcat(params,values)) ;
    else
      [opts, rest] = vl_argparse(opts, reshape(vertcat(params,values), 1, [])) ;
      args{ai} = cell2struct(rest(2:2:end), rest(1:2:end), 2) ;
      keep(ai) = true ;
    end
    ai = ai + 1 ;
    continue ;
  end

  if ~isstr(args{ai})
    error('Expected either a param-value pair or a structure.') ;
  end

  param = args{ai} ;
  value = args{ai+1} ;

  p = find(strcmpi(param, optNames)) ;
  if numel(p) ~= 1
    if nargout == 1
      error('Unknown parameter ''%s''', param) ;
    else
      keep([ai,ai+1]) = true ;
      ai = ai + 2 ;
      continue ;
    end
  end
  field = optNames{p} ;

  if ~recursive
    opts.(field) = value ;
  else
    if isstruct(opts.(field)) && numel(fieldnames(opts.(field))) > 0
      % The parameter has a  non-empty struct value in OPTS:
      % process recursively.
      if ~isstruct(value)
        error('Cannot assign a non-struct value to the struct parameter ''%s''.', ...
          field) ;
      end
      if nargout > 1
        [opts.(field), args{ai+1}] = vl_argparse(opts.(field), value) ;
      else
        opts.(field) = vl_argparse(opts.(field), value) ;
      end
    else
      % The parameter does not have a struct value in OPTS: copy as is.
      opts.(field) = value ;
    end
  end

  ai = ai + 2 ;
end

args = args(keep) ;


classdef LvdCaseMatrixParameterUIDataModel < matlab.mixin.SetGet
    %LvdCaseMatrixParameterUIDataModel Summary of this class goes here
    %   Detailed explanation goes here

    properties
        pluginVar LvdPluginOptimVarWrapper
        useTf(1,1) logical = false;
        lowerBnd(1,1) double
        upperBnd(1,1) double
        step(1,1) double
    end

    methods
        function obj = LvdCaseMatrixParameterUIDataModel(pluginVar, useTf, lowerBnd, upperBnd, step)
            obj.pluginVar = pluginVar;
            obj.useTf = useTf;
            obj.lowerBnd = lowerBnd;
            obj.upperBnd = upperBnd;
            obj.step = step;
        end
    end
end


function normalizeUnits(gdata,fontUnitsExcludeTags)
% normalizeUnits(gdata)
% Change 'Units' properties of all handles contained in gdata to
% 'Normalized' (the 'FontUnits' property is unaffected). gdata is a
% structure with fields whose values are handles to GUI components (eg as
% returned by guidata).

if nargin < 2
    fontUnitsExcludeTags = cell(0,1);
end

comps = fieldnames(gdata);
for c = 1:numel(comps)
    tag = comps{c};
    h = gdata.(tag);
    if isprop(h,'Units')
        set(h,'Units','Normalized');
    end
    if isprop(h,'FontUnits') && ~any(strcmp(tag,fontUnitsExcludeTags))
        set(h,'FontUnits','Normalized');
    end
end

end


function varargout = scl_slope(varargin)
% file_array's scl_slope property
% For getting the value
% dat = scl_slope(obj)
%
% For setting the value
% obj = scl_slope(obj,dat)
%__________________________________________________________________________
% Copyright (C) 2005-2017 Wellcome Trust Centre for Neuroimaging

%
% $Id: scl_slope.m 7147 2017-08-03 14:07:01Z spm $

if nargin==2
    varargout{1} = asgn(varargin{:});
elseif nargin==1
    varargout{1} = ref(varargin{:});
else
    error('Wrong number of arguments.');
end

%==========================================================================
% function dat = ref(obj)
%==========================================================================
function dat = ref(obj)
dat = obj.scl_slope;

%==========================================================================
% function obj = asgn(obj,dat)
%==========================================================================
function obj = asgn(obj,dat)
if isnumeric(dat) % && numel(dat)<=1,
    obj.scl_slope = double(dat);
else
    error('"scl_slope" must be numeric.');
end


function sts = isequaltarget(dep1, dep2)

% function sts = isequaltarget(dep1, dep2)
% Compare source references of two dependencies and return true if both
% point to the same object. If multiple dependencies are given, the
% number and order of dependencies must match.
% This code is part of a batch job configuration system for MATLAB. See
%      help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging

% Volkmar Glauche
% $Id: isequaltarget.m 1716 2008-05-23 08:18:45Z volkmar $

rev = '$Rev: 1716 $'; %#ok
sts = numel(dep1) == numel(dep2);
if sts
    for k = 1:numel(dep1)
        sts = sts && isequal(dep1.tgt_exbranch, dep2.tgt_exbranch) && ...
              isequal(dep1.tgt_input, dep2.tgt_input);
        if ~sts
            break;
        end;
    end;
end;


function val = get_params_kernel(K, name)
% GET_PARAMS_KERNEL Accessor function for a field (tabular_kernel)
% val = get_params_kernel(K, name)
%
% e.g., get_params_kernel(K, 'table')

switch name
 case 'table', val = K.table;
 otherwise,
  error(['invalid field name ' name]);
end


function [seriesC, typeC] = extract_all_series(dcmdir_PATIENT)
%"extract_all_series"
%   Returns a cell array of all series contained within a dcmdir.PATIENT
%   datastructure, regardless of parent study.  Also returns an optional
%   type cell, containing strings describing the type of each series in
%   seriesC.
%
%JRA 06/15/06
%YWU modified 03/03/08
%
%Usage:
%   seriesC = extract_all_scan_series(dcmdir_PATIENT);
%
% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.
%
% This file is part of The Computational Environment for Radiotherapy Research (CERR).
%
% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.
%
% CERR has been financially supported by the US National Institutes of Health under multiple grants.
%
% CERR is distributed under the terms of the Lesser GNU Public License.
%
%     This version of CERR is free software: you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation, either version 3 of the License, or
%     (at your option) any later version.
%
% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
% See the GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with CERR.  If not, see <http://www.gnu.org/licenses/>.

seriesC     = {};
typeC       = {};

for studyNum = 1:length(dcmdir_PATIENT.STUDY)

    study = dcmdir_PATIENT.STUDY(studyNum); %wy {} --> ()

    for seriesNum = 1:length(study.SERIES)

        seriesC{end+1} = study.SERIES(seriesNum); %wy {} --> ()

        %Remove the info field, leaving only the field describing what type
        %of series this is.
       % disp(study.SERIES(seriesNum));
        tmp = rmfield(study.SERIES(seriesNum), 'info'); %wy {} --> ()
        tmpFields = fieldnames(tmp);
        if length(tmpFields) == 2; %wy 1-->2
            imgModality = tmp.Modality;
            imgModality = parseModality(imgModality);
            typeC{end+1} = imgModality;
            %typeC{end+1} = tmp.Modality; % wy tmpFields{:};
        else
           error('Improperly formed dcmdir_PATIENT structure passed to extract_all_series.');
        end

    end

end

return;

function imgModality = parseModality(imgModality)
%function imgModality = parseModality(imgModality)
%
% This function parses image modality and returns valid DICOM modality. For
% example, "CT SCAN", "M_CT" will be considered as belonging to modality "CT"

imgModality = upper(imgModality);

indStruct = strfind(imgModality,'STRUCT');
indDose = strfind(imgModality,'DOSE');
indPlan = strfind(imgModality,'PLAN');

if ~isempty([indStruct indDose indPlan])
    return;
end
indCT = strfind(imgModality,'CT');
indPT = strfind(imgModality,'PT');
indPET = strfind(imgModality,'PET');

if ~isempty(indCT) && isempty([indPT indPET])
    imgModality = 'CT';
elseif ~isempty(indPT) && isempty([indCT indPET])
    imgModality = 'PT';
elseif ~isempty(indPET) && isempty([indCT indPT])
    imgModality = 'PT';
end

return;


%kputanimate 'Non-Interactive Animation of Image Sequence'
% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros putanimate.pane file
%
% Parameters:
% InputFile: i 'Input File', required: 'File containing image sequence'
% InputFile: cmap 'Input Colormap ', optional: 'File containing alternate colormap filename'
% InputFile: clip 'Input Clip Gate', optional: 'File containing clip mask'
% Integer: x 'X Placement', default: -1: 'X location for GUI autoplacement'
% Integer: width 'Window Width ', default: 256: 'Window width'
% Integer: y 'Y Placement', default: -1: 'Y location for GUI autoplacement'
% Integer: height 'Window Height', default: 256: 'Window height'
% Double: update 'Update time', default: 2: 'How often to check input file for modification'
%
% Example: kputanimate({i, cmap, clip}, {'i','';'cmap','';'clip','';'x',-1;'width',256;'y',-1;'height',256;'update',2})
%
% Khoros helpfile follows below:
%
%  PROGRAM
% putanimate - Non-Interactive Animation of Image Sequence
%
%  DESCRIPTION
% Putanimate is a visualization program that displays animated
% sequences of data.  It is expected that the input data has multiple
% frames organized in the Khoros Polymorphic Data Model along either
% depth, time, or elements.
%
% The input file containing the data to be animated is monitored by
% default; the file is checked every 2 seconds for change, and if it has
% been modified, the visualization display is updated accordingly.  The
% interval at which the input file is checked for modification may be
% specified using the [-update] argument.
%
% A clip mask may be used to dictate the portion of the data that is
% displayed in the animation using the [-clip] argument.
%
% An alternate input color map may be used to change the current color map
% using the [-cmap] argument.
%
% An animate direction value may be provided which specifies the direction
% in which images are sequenced using the [-dir] argument.  There are five
% different direction values which are as follows:
%
%  "" 5
% 1  -  "<<" Causes the animation to sequence in a backward direction.
% 2  -  "<"  Advances a single frame in a backwards direction (frame N to N-1).
% 3  -  "Stop"  Causes the animation to stop.
% 4  -  ">"  Advances a single frame in a forward direction (frame N to N+1)
% 5  -  ">>"  Causes the animation to sequence in a forward direction.
%
% An animate control value may be provided which controls how animation
% sequencing is performed when the animation is in motion using the [-control]
% argument.  Animation is considered "in motion" when the animation direction is
% sequencing forward or backward.  The animation may be performed once
% completely, repeated indefinitely, or performed in one direction then reversed
% and repeated in the other direction.  There are three different control values
% which are as follows:
%
%  "" 5
% 1  -  "Single" Does a single complete sequence of the animation in the
% current direction, and then stops.
% 2  -  "Loop"  Does a full sequence through the animation in the current
% animation direction.  As soon as the sequence is finished, it is started
% again, so that the animation is put into a loop.  This procedure will
% repeat until the animation is stopped.
% 3  -  "Autoreverse"  Does a single complete sequence of the animation, in the
% current animation direction, then reverses the direction and sequences back.
% This procedure will repeat until the animation is stopped.
%
% An animation speed value may be provided which controls how fast the frames
% in the image are to be sequenced using the [-speed] argument.  The speed is a
% value in seconds ranging between 0 and 5, where 0.0 is the fastest possible
% on a given machine, and 5.0 is very slow.  Note that 1/60 sec (0.016 sec)
% corresponds to the normal frame rate for television.  It is "NOT"
% recommended that the frame speed be set to 0.0 for most situations since this
% is an intensive operation that may make it difficult to re-gain control of
% the graphical user interface.
%
% By default, the visualization display will share its colormap will all
% other applications running at the same time; that is, it does not not use a
% .I private colormap,
% but rather makes use of the
% .I default colormap.
% It is possible to specify that the visualization display allocate its
% own private colormap or "grab" all available colors for its own use.
% This is done using the [-priv] argument.  When [-priv] is specified,
% moving the mouse pointer into the display window will cause the display
% to have its private colormap installed; moving the pointer out of the
% display window will cause the private colormap to be de-installed.  This
% results in the "technoflashing" phenomenon characteristic of private
% colormap installation.
%
% Color allocation can also be controlled and set to either
% .I  Read Only
% or
% .I Read Write
% using the [-alloc] argument.  When set to
% .I read only,
% once a color cell has been allocated, it can have its color set only once;
% from then on, the color cell can be shared by multiple applications, but
% not changed.  If the visualization display requires the color displayed
% to change, it must re-allocate the color cell, forcing a re-display of
% data.  This can be an expensive procedure.  In contrast, after a
% .I read/write
% color cell is allocated, it can have its color changed at any time
% without re-allocation; the data being displayed does not need to be
% redisplayed, and the color update process is much more efficient.
% However, the colors used in the visualization display cannot be shared by
% other applications.
%
% On creation, the animation display window may be placed manually (the
% default method), or placed automatically.  For automatic placement of the
% animation display window, specify the desired location in device (screen)
% coordinates, using the [-x] and [-y] arguments.
%
% While the animation display window should be created with a default size
% that is appropriate to display the data, a width and height for the window
% can be specified explicitly using the [-width] and [-height] arguments.
% Note that interactive resizing of the animate window using the window manager
% is currently NOT supported.
%
%
%
%  EXAMPLES
% % putanimate -i sequence:baby
% % putanimate -i sequence:bushes
%
%  "SEE ALSO"
% putdata(1)
%
%  RESTRICTIONS
%
%  REFERENCES
%
%  COPYRIGHT
% Copyright (C) 1993 - 1997, Khoral Research, Inc. ("KRI")  All rights reserved.
%

function varargout = kputanimate(varargin)
if nargin ==0
  Inputs={};arglist={'',''};
elseif nargin ==1
  Inputs=varargin{1};arglist={'',''};
elseif nargin ==2
  Inputs=varargin{1}; arglist=varargin{2};
else error('Usage: [out1,..] = kputanimate(Inputs,arglist).');
end
if size(arglist,2)~=2
  error('arglist must be of form {''ParameterTag1'',value1;''ParameterTag2'',value2}')
 end
narglist={'i', '__input';'cmap', '__input';'clip', '__input';'x', -1;'width', 256;'y', -1;'height', 256;'update', 2};
maxval={0,1,1,1000,1000,1000,1000,1};
minval={0,1,1,-1,-1,-1,-1,1};
istoggle=[0,1,1,1,1,1,1,1];
was_set=istoggle * 0;
paramtype={'InputFile','InputFile','InputFile','Integer','Integer','Integer','Integer','Double'};
% identify the input arrays and assign them to the arguments as stated by the user
if ~iscell(Inputs)
Inputs = {Inputs};
end
NumReqOutputs=0; nextinput=1; nextoutput=1;
  for ii=1:size(arglist,1)
  wasmatched=0;
  for jj=1:size(narglist,1)
   if strcmp(arglist{ii,1},narglist{jj,1})  % a given argument was matched to the possible arguments
     wasmatched = 1;
     was_set(jj) = 1;
     if strcmp(narglist{jj,2}, '__input')
      if (nextinput > length(Inputs))
        error(['Input ' narglist{jj,1} ' has no corresponding input!']);
      end
      narglist{jj,2} = 'OK_in';
      nextinput = nextinput + 1;
     elseif strcmp(narglist{jj,2}, '__output')
      if (nextoutput > nargout)
        error(['Output nr. ' narglist{jj,1} ' is not present in the assignment list of outputs !']);
      end
      if (isempty(arglist{ii,2}))
        narglist{jj,2} = 'OK_out';
      else
        narglist{jj,2} = arglist{ii,2};
      end

      nextoutput = nextoutput + 1;
      if (minval{jj} == 0)
         NumReqOutputs = NumReqOutputs - 1;
      end
     elseif isstr(arglist{ii,2})
      narglist{jj,2} = arglist{ii,2};
     else
        if strcmp(paramtype{jj}, 'Integer') & (round(arglist{ii,2}) ~= arglist{ii,2})
            error(['Argument ' arglist{ii,1} ' is of integer type but non-integer number ' arglist{ii,2} ' was supplied']);
        end
        if (minval{jj} ~= 0 | maxval{jj} ~= 0)
          if (minval{jj} == 1 & maxval{jj} == 1 & arglist{ii,2} < 0)
            error(['Argument ' arglist{ii,1} ' must be bigger or equal to zero!']);
          elseif (minval{jj} == -1 & maxval{jj} == -1 & arglist{ii,2} > 0)
            error(['Argument ' arglist{ii,1} ' must be smaller or equal to zero!']);
          elseif (minval{jj} == 2 & maxval{jj} == 2 & arglist{ii,2} <= 0)
            error(['Argument ' arglist{ii,1} ' must be bigger than zero!']);
          elseif (minval{jj} == -2 & maxval{jj} == -2 & arglist{ii,2} >= 0)
            error(['Argument ' arglist{ii,1} ' must be smaller than zero!']);
          elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} < minval{jj})
            error(['Argument ' arglist{ii,1} ' must be bigger than ' num2str(minval{jj})]);
          elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} > maxval{jj})
            error(['Argument ' arglist{ii,1} ' must be smaller than ' num2str(maxval{jj})]);
          end
        end
     end
     if ~strcmp(narglist{jj,2},'OK_out') &  ~strcmp(narglist{jj,2},'OK_in')
       narglist{jj,2} = arglist{ii,2};
     end
   end
   end
   if (wasmatched == 0 & ~strcmp(arglist{ii,1},''))
        error(['Argument ' arglist{ii,1} ' is not a valid argument for this function']);
   end
end
% match the remaining inputs/outputs to the unused arguments and test for missing required inputs
 for jj=1:size(narglist,1)
     if  strcmp(paramtype{jj}, 'Toggle')
        if (narglist{jj,2} ==0)
          narglist{jj,1} = '';
        end;
        narglist{jj,2} = '';
     end;
     if  ~strcmp(narglist{jj,2},'__input') && ~strcmp(narglist{jj,2},'__output') && istoggle(jj) && ~ was_set(jj)
          narglist{jj,1} = '';
          narglist{jj,2} = '';
     end;
     if strcmp(narglist{jj,2}, '__input')
      if (minval{jj} == 0)  % meaning this input is required
        if (nextinput > size(Inputs))
           error(['Required input ' narglist{jj,1} ' has no corresponding input in the list!']);
        else
          narglist{jj,2} = 'OK_in';
          nextinput = nextinput + 1;
        end
      else  % this is an optional input
        if (nextinput <= length(Inputs))
          narglist{jj,2} = 'OK_in';
          nextinput = nextinput + 1;
        else
          narglist{jj,1} = '';
          narglist{jj,2} = '';
        end;
      end;
     else
     if strcmp(narglist{jj,2}, '__output')
      if (minval{jj} == 0) % this is a required output
        if (nextoutput > nargout & nargout > 1)
           error(['Required output ' narglist{jj,1} ' is not stated in the assignment list!']);
        else
          narglist{jj,2} = 'OK_out';
          nextoutput = nextoutput + 1;
          NumReqOutputs = NumReqOutputs-1;
        end
      else % this is an optional output
        if (nargout - nextoutput >= NumReqOutputs)
          narglist{jj,2} = 'OK_out';
          nextoutput = nextoutput + 1;
        else
          narglist{jj,1} = '';
          narglist{jj,2} = '';
        end;
      end
     end
  end
end
if nargout
   varargout = cell(1,nargout);
else
  varargout = cell(0);
end
global KhorosRoot
if exist('KhorosRoot') && ~isempty(KhorosRoot)
w=['"' KhorosRoot];
else
if ispc
  w='"C:\Program Files\dip\khorosBin\';
else
[s,w] = system('which cantata');
w=['"' w(1:end-8)];
end
end
callKhoros([w 'putdata"  -animate'],Inputs,narglist);


%--- help for dsge_solver_h ---
%
%  H1 line
%
%  ::
%
%
%  Args:
%
%  Returns:
%     :
%
%  Note:
%
%  Example:
%
%     See also:
%
%    Other functions named dsge_solver_h
%
%       dsge/dsge_solver_h
%


function varargout = gui_splashscreen(varargin)
%
% GUI_SPLASHSCREEN M-file for gui_splashscreen.fig
%      GUI_SPLASHSCREEN, by itself, creates a new GUI_SPLASHSCREEN or raises the existing
%      singleton*.
%
%      H = GUI_SPLASHSCREEN returns the handle to a new GUI_SPLASHSCREEN or the handle to
%      the existing singleton*.
%
%      GUI_SPLASHSCREEN('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in GUI_SPLASHSCREEN.M with the given input arguments.
%
%      GUI_SPLASHSCREEN('Property','Value',...) creates a new GUI_SPLASHSCREEN or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before gui_splashscreen_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to gui_splashscreen_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help gui_splashscreen

% Last Modified by GUIDE v2.5 28-Jun-2012 15:16:11

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @gui_splashscreen_OpeningFcn, ...
                   'gui_OutputFcn',  @gui_splashscreen_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before gui_splashscreen is made visible.
function gui_splashscreen_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to gui_splashscreen (see VARARGIN)

% Choose default command line output for gui_splashscreen
handles.output = hObject;

axes(handles.axLogo);
path = which('splashlogo.jpg');
im = imread(path);
image(im);
axis image
axis off

% SLASH = fastif(isunix,'/','\');

% fid = fopen([fileparts(which('StartSIFT.m')) filesep 'resources' filesep 'version.txt']);
% version = fscanf(fid,'%s');
% fclose(fid);

splashTextFile = [fileparts(which('StartSIFT.m')) filesep 'Readme.txt'];

set(handles.txtSplashText,'String',...
    importdata(splashTextFile,'\n'));

% set(handles.txtSplashText,'String',...
%     {sprintf('Welcome to the Source Information Flow Toolbox version %s',version), ...
%      'Author: Tim Mullen (tim@sccn.ucsd.edu)' ...
%      'With important contributions from Arnaud Delorme and Christian Kothe' ...
%      '    ' ...
%      'DISCLAIMER:  THIS IS AN EXPERIMENTAL *ALPHA* VERSION OF SIFT. THIS VERSION IS NOT A SUPPORTED RELEASE AND IS INTENDED FOR EDUCATIONAL PURPOSES. USE AT YOUR OWN RISK! CHECK http://sccn.ucsd.edu/wiki/SIFT FOR UPDATES ON THE OFFICIAL BETA RELEASE.' ...
%      '    ' ...
%      'If you find this toolbox useful for your research, PLEASE include the following citations with any publications and/or presentations which make use of SIFT:' ...
%      '    ' ...
%      '(1) Mullen, T, Delorme, A. Kothe, C, Makeig, S (2010) "An Electrophysiological Information Flow Toolbox for EEGLAB" Society for Neuroscience 2010, San Diego, CA' ...
%      '    ' ...
%      '(2) Delorme, A., Mullen, T., Kothe C., Akalin Acar, Z., Bigdely Shamlo, N., Vankov, A., Makeig, S. (2011) "EEGLAB, SIFT, NFT, BCILAB, and ERICA: New tools for advanced EEG/MEG processing." Computational Intelligence and Neuroscience vol. 2011, Article ID 130714, 12 pages.' ...
%      });

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes gui_splashscreen wait for user response (see UIRESUME)
uiwait(handles.gui_splash);

% --- Outputs from this function are returned to the command line.
function varargout = gui_splashscreen_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
try,
varargout{1} = handles.output;
close(hObject);
catch
varargout{1} = [];
end

function gui_splash_CreateFcn(hObject, eventdata, handles)

function cmdOK_Callback(hObject, eventdata, handles)

uiresume(handles.gui_splash);

% --- Executes during object creation, after setting all properties.
function txtSplashText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to txtSplashText (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

function txtSplashText_Callback(hObject, eventdata, handles)
% hObject    handle to txtSplashText (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of txtSplashText as text
%        str2double(get(hObject,'String')) returns contents of txtSplashText as a double

% --- Executes during object creation, after setting all properties.
function txtSplashScreen_CreateFcn(hObject, eventdata, handles)
% hObject    handle to txtSplashText (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function d = rows(X)
warning('This function is deprecated')

d = size(X,1);


function [currSelectedId,selTypeC] = dispSelCriteriaROE(hObj,hEvt,hFig,varargin)
%Display selected constraints
% AI 05/12/21

%cMode = datacursormode(hFig);
%cMode.removeAllDataCursors;

ud = guidata(hFig);
legH = ud.handle.legend;

if isempty(hEvt)  %Prog call

    %Get handles to constraints
    protS = ud.Protocols;
    type = varargin{1};
    idxV = varargin{2};
    pNum = varargin{3};

    %Turn off currently displayed limits
    hCrit = protS(pNum).criteria;
    hGuide = protS(pNum).guidelines;
    for k = 1:numel(hCrit)
        set(hCrit(k),'Visible','Off')
    end
    for k = 1:numel(hGuide)
        set(hGuide(k),'Visible','Off')
    end
    protS(pNum).criteria = hCrit;
    protS(pNum).guidelines = hGuide;

    %Turn on selected limit
    if strcmp(type,'criteria')
        hCrit = [protS(pNum).criteria];
        set(hCrit(idxV),'Visible','On');
        %numElements = [0,cumsum(arrayfun(@(x)numel(x.criteria),protS))];
        %for pNum = 1:numel(protS)
        %protS(pNum).criteria = hCrit(numElements(pNum)+1:numElements(pNum+1));
        %end
        protS(pNum).criteria = hCrit;

        drawnow;
        legH.EntryContainer.NodeChildren(2).Label.Color = [0,0,0];
        legH.EntryContainer.NodeChildren(1).Label.Color = [0.65,0.65,0.65];
    else
        hGuide = [protS(pNum).guidelines];
        set(hGuide(idxV),'Visible','On');
        %numElements = [0,cumsum(arrayfun(@(x)numel(x.guidelines),protS))];
        %for pNum = 1:numel(protS)
        %protS(pNum).guidelines = hGuide(numElements(pNum)+1:numElements(pNum+1));
        %end
        protS(pNum).guidelines = hGuide;

        drawnow;
        legH.EntryContainer.NodeChildren(1).Label.Color = [0,0,0];
        legH.EntryContainer.NodeChildren(2).Label.Color = [0.65,0.65,0.65];
    end

    ud.Protocols = protS;
    set(hFig,'userdata',ud);

else %Checkbox selection

    %Get handles to constraints
    protS = ud.Protocols;

    %Get slelected constraint
    currSelectedId = hEvt.Indices(:,1);
    stateV = cell2mat(hObj.Data(currSelectedId,1));
    stateC = {'Off','On'};

    if currSelectedId==1  %'All'
        for pNum = 1:numel(protS)
            hCrit = protS(pNum).criteria;
            hGuide = protS(pNum).guidelines;
            %Criteria
            for k = 1:numel(hCrit)
                set(hCrit(k),'Visible',stateC{stateV+1});
            end
            %Guidelines
            for k = 1:numel(hGuide)
                set(hGuide(k),'Visible',stateC{stateV+1});
            end
        end

        drawnow;
        legH.EntryContainer.NodeChildren(1).Label.Color = [0,0,0];
        legH.EntryContainer.NodeChildren(2).Label.Color = [0,0,0];

    elseif currSelectedId==2 %'None'
        if stateV == 1
            %Criteria
            for pNum = 1:numel(protS)
                hCrit = protS(pNum).criteria;
                hGuide = protS(pNum).guidelines;
                for k = 1:numel(hCrit)
                    set(hCrit(k),'Visible','Off');
                end
                %Guidelines
                for k = 1:numel(hGuide)
                    set(hGuide(k),'Visible','Off');
                end
            end
        end
        hObj.Data(:,1) = {false};

        drawnow;
        legH.EntryContainer.NodeChildren(1).Label.Color = [0.65,0.65,0.65];
        legH.EntryContainer.NodeChildren(2).Label.Color = [0.65,0.65,0.65];

    else

        protS = ud.Protocols;
        currProtocol = ud.foreground;
        gNum = numel(protS(currProtocol).guidelines);

        currSelectedId = currSelectedId-2;
        type =  get(hObj,'userdata');
        selTypeC = type(currSelectedId);

        for pNum = 1:numel(protS)
            for k = 1:numel(currSelectedId)
                if strcmp(selTypeC(k),'guidelines') %guidelines
                    selNum = currSelectedId(k);
                    if strcmp(stateC{stateV+1},'On')
                        drawnow;
                        legH.EntryContainer.NodeChildren(1).Label.Color = [0,0,0];
                    else
                        drawnow;
                        legH.EntryContainer.NodeChildren(1).Label.Color = [0.65,0.65,0.65];
                    end
                else                               %criteria
                    selNum = currSelectedId(k)- gNum;
                    if strcmp(stateC{stateV+1},'On')
                        drawnow;
                        legH.EntryContainer.NodeChildren(2).Label.Color = [0,0,0];
                    else
                        drawnow;
                        legH.EntryContainer.NodeChildren(2).Label.Color = [0.65,0.65,0.65];
                    end
                end
                %Toggle display on/off
                set(protS(pNum).(selTypeC{k})(selNum),'Visible',stateC{stateV(k)+1});
                %Expand tooltip if on
                if strcmp(stateC{stateV+1},'On')
                    %Check if datatip exists
                    if ~isfield(ud.handle,'datatips')
                        ud.handle.datatips = [];
                    end

                    target = protS(pNum).(selTypeC{k})(selNum);
                    guidata(hFig,ud);
                    createDataTipROE(hFig,target);
                end

            end
        end

    end

end

ud.Protocols = protS;
ud.handle.legend = legH;

end


function [val, status] = ft_findcfg(cfg, var)

% FT_FINDCFG searches for an element in the cfg structure
% or in the nested previous cfgs
%
% Use as
%   val = ft_findcfg(cfg, var)
% where the name of the variable should be specified as string.
%
% e.g.
%   trl   = ft_findcfg(cfg, 'trl')
%   event = ft_findcfg(cfg, 'event')
%
% See also FT_GETOPT, FT_CFG2KEYVAL

% Copyright (C) 2006, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% for the documentation and details.
%
%    FieldTrip is free software: you can redistribute it and/or modify
%    it under the terms of the GNU General Public License as published by
%    the Free Software Foundation, either version 3 of the License, or
%    (at your option) any later version.
%
%    FieldTrip is distributed in the hope that it will be useful,
%    but WITHOUT ANY WARRANTY; without even the implied warranty of
%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%    GNU General Public License for more details.
%
%    You should have received a copy of the GNU General Public License
%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id$

% if var(1)~='.'
%   var = ['.' var];
% end
val    = [];
depth  = 0;
status = 0;

while ~status
  depth = depth + 1;
  if ~isempty(cfg)
    if issubfield(cfg,  var)
      val = getsubfield(cfg, var);
      status = 1;
    elseif issubfield(cfg, 'previous')
      [val, status] = ft_findcfg(cfg.previous, var);
      if status, break; end
    elseif iscell(cfg)
      for i=1:length(cfg)
        [val, status] = ft_findcfg(cfg{i}, var);
        if status, break; end
      end
    else
      status = -1;
      break
    end
  else
    status = -1;
    break
  end
end


function checkFieldNames(structure, field_names)
%CHECKFIELDNAMES   Checks structure field names for existance.
%
% DESCRIPTION:
%       checkFieldNames checks the field names of a MATLAB structure
%       against a cell array of allowable field names. If a field name is
%       found within the structure that is not contained within the cell
%       array, an error is thrown with the field name given in the error
%       message. The function is useful for checking for spelling errors in
%       field names for structure inputs.
%
% USAGE:
%       checkFieldNames(structure, field_names)
%
% INPUTS:
%       structure   - MATLAB structure
%       field_names - cell array of allowable field names
%
% ABOUT:
%       author      - Bradley Treeby
%       date        - 13th October 2009
%       last update - 13th October 2009
%
% This function is part of the k-Wave Toolbox (http://www.k-wave.org)
% Copyright (C) 2009-2014 Bradley Treeby and Ben Cox
%
% See also fieldnames

% This file is part of k-Wave. k-Wave is free software: you can
% redistribute it and/or modify it under the terms of the GNU Lesser
% General Public License as published by the Free Software Foundation,
% either version 3 of the License, or (at your option) any later version.
%
% k-Wave is distributed in the hope that it will be useful, but WITHOUT ANY
% WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
% FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for
% more details.
%
% You should have received a copy of the GNU Lesser General Public License
% along with k-Wave. If not, see <http://www.gnu.org/licenses/>.

names = fieldnames(structure);
for names_index = 1:length(names)
    name_found = false;
    for field_index = 1:length(field_names)
        if strcmp(names{names_index}, field_names{field_index})
            name_found = true;
        end
    end
    if ~name_found
    	error([names{names_index} ' is not a valid field for the structure ' inputname(1)]);
    end
end


function val = isOctave()
%
%
%        val = isOctave()
%
%
%        Description: it checks if the running environment is MATLAB
%                     or Octave.
%
%        Input:
%
%        Output:
%           -val: a boolean value: 1 if the environment is Octave, otherwise 0.
%
%     Copyright (C) 2015  Francesco Banterle
%
%     This program is free software: you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation, either version 3 of the License, or
%     (at your option) any later version.
%
%     This program is distributed in the hope that it will be useful,
%     but WITHOUT ANY WARRANTY; without even the implied warranty of
%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%     GNU General Public License for more details.
%
%     You should have received a copy of the GNU General Public License
%     along with this program.  If not, see <http://www.gnu.org/licenses/>.
%

tmp = ver();

val = 0;

if(isfield(tmp, 'Name'))
    try
        val = (strcmp(tmp(1).Name, 'Octave') == 1);
    catch expr
        disp(expr);
    end
end

end


function jsubs = cfg2jobsubs(item, subs)

% function jsubs = cfg2jobsubs(item, subs)
% Return the subscript into the job tree for a given subscript vector into
% the val part of the cfg tree. This generic function should be called only
% for leafs (cfg_entry, cfg_file, cfg_menu) of the cfg tree. It returns the
% subscripts that remain after item.val{1} has been addressed.
%
% This code is part of a batch job configuration system for MATLAB. See
%      help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging

% Volkmar Glauche
% $Id: cfg2jobsubs.m 1862 2008-06-30 14:12:49Z volkmar $

rev = '$Rev: 1862 $'; %#ok

% Only de-reference subscripts into .val{1} field
if isequal(subs(1:2), substruct('.','val','{}',{1}))
    % return possible indices into .val{1} field
    jsubs = subs(3:end);
else
    cfg_message('matlabbatch:cfg2jobsubs:wrongsubs', 'Inappropriate subscript reference in item ''%s''.', item.tag);
    jsubs = struct('type',{},'subs',{});
end;


function newnonl( prob, ncones, arg ) %#ok
error( nargchk( 2, 3, nargin ) );
global cvx___
cones = cvx___.cones;
if nargin == 3,
    ncones = struct( 'type', ncones, 'indices', arg );
end
for k = 1 : length( ncones ),
    ncone = ncones(k);
    if any( cvx___.reserved( ncone.indices( : ) ) ),
        error( 'Variables placed in nonlinearities must be free.' );
    else
        cvx___.reserved( ncone.indices ) = 1;
    end
    if isequal( ncone.type, 'nonnegative' ),
        ncone.indices = ncone.indices(:)';
    end
    if isempty( cones ),
        cones = ncone;
    else
        match = find( strcmp( { cones.type }, ncone.type ) );
        if ~isempty( match ),
            nlsiz = size( ncone.indices, 1 );
            match = match( cellfun( 'size', { cones(match).indices }, 1 ) == nlsiz );
            if isempty( match ),
                cones = [ cones, ncone ];
            else
                match = match(1);
                cones(match).indices = [ cones(match).indices, ncone.indices ];
            end
        else
            cones = [ cones, ncone ];
        end
    end
end
cvx___.cones = cones;

% Copyright 2010 Michael C. Grant and Stephen P. Boyd.
% See the file COPYING.txt for full copyright information.
% The command 'cvx_where' will show where this file is located.


%==============================================================================
% This code is part of the Matlab-based toolbox
% FAIR - Flexible Algorithms for Image Registration.
% For details see
% - https://github.com/C4IR and
% - http://www.siam.org/books/fa06/
%==============================================================================
% finishes a test run, nice output, small break, close all
%==============================================================================

function testEnd

caller = dbstack; % identify the name of the calling function
caller = caller(min(length(caller),2)).name;
caller = which(caller);

str = {
  sprintf('%% %s\n',char(ones(1,78)*'#'))
  sprintf('    file <%s> terminated\n',caller)
  sprintf('%% %s\n',char(ones(1,78)*'#'))
};

fprintf('%s\n',str{:});

builtin('pause',2);
close all

%==============================================================================


function S=capitalize(S,skipset)
%function S=capitalize(S)
% Capitalize the first character in every word (excluding short words) in input
% string S, or in every word in every string in input cell array S.  The first word
% is always capitalized.
%
% Default set of words to skip is {'a','an','and','or','in','the'}
%
% function S=capitalize(S,skipset)
% User-supplied cell array of words to skip

if nargin<2
    skipset={'a','an','and','or','in','the'};
end
skipset=lower(skipset);

if iscell(S)
    S=cellfun(@(x) capitalize(x, skipset),S,'uniformoutput',false);
else
    skip=0;
    Sw=regexp(S,'[ \t]','split');
    skip(2:length(Sw))=ismember(lower(Sw(2:end)),skipset); %skip(1) is always 0
    Sw(~skip)=cellfun(@(x) [upper(x(1)) x(2:end)],Sw(~skip),'uniformoutput',false);
    S=sprintf('%s ',Sw{:});
    S(end)='';
end


%PRPROGRESS Report progress of some PRTools iterative routines
%
%  PRPROGRESS ON
%
% All progress of all routines will be written to the command window.
%
%  PRPROGRESS(FID)
%
% Progress reports will be written to the file with file descriptor FID.
%
%  PRPROGRESS(FID,FORMAT,...)
%
% Writes progress message to FID. If FID == [], the predefined destination
% (command window or file) is used.
%
%  PRPROGRESS OFF
%  PRPROGRESS(0)
%
% Progress reporting is turned off.
%
%  PRPROGRESS
%
% Toggles between PRPROGRESS ON and PRPROGRESS OFF
%
%  FID = PRPROGRESS
%
% Retrieves the status of PRPROGRESS
%
% Some routines (e.g. CLEVAL)  have a switch in the function call by which
% progress reporting for that routine only can be initiated.
%
% By default, PRPROGRESS is switched off. Interactive progress tracing can
% be best following by PRWAITBAR
%
% SEE ALSO (PRTools Guide)
% PRWAITBAR

% Copyright: R.P.W. Duin, r.p.w.duin@37steps.com
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands

function fid = prprogress(par,varargin)

	persistent GLOBALPRPROGRESS
  mlock; % prevents GLOBALPRPROGRESS being cleared by CLEAR ALL

	if isempty(GLOBALPRPROGRESS)
		GLOBALPRPROGRESS = 0;
	end

	if nargin == 0

		if nargout == 0
			if GLOBALPRPROGRESS ~= 0,
				GLOBALPRPROGRESS = 0;
			else
				GLOBALPRPROGRESS = 1;
			end
		else
			fid = GLOBALPRPROGRESS;
		end

	elseif nargin == 1 & nargout == 0

		if isstr(par)
			switch par
			case {'on','ON'}
				GLOBALPRPROGRESS = 1;
			case {'off','OFF'}
				GLOBALPRPROGRESS = 0;
			otherwise
				error('Illegal input for PRPROGRESS')
			end
		else
			GLOBALPRPROGRESS = par;
		end

	elseif (GLOBALPRPROGRESS > 0) & (~isempty(par)) & (par>0)  %DXD, fid=0 means no printing...

		s = sprintf(varargin{:});
		n = fprintf(par,s);

		if nargout > 0
			fid = length(s);
		end

	elseif GLOBALPRPROGRESS > 0

		s = sprintf(varargin{:});
		n = fprintf(GLOBALPRPROGRESS,s);

		if nargout > 0
			fid = length(s);
		end

	else

		if nargout > 0
			fid = 0;
		end

	end

return


% Build a distribution of RTB

!make clean
!make
matlab.addons.toolbox.packageToolbox('RTB.prj', '~/Desktop/RTB')


classdef Container < handle
    %uix.mixin.Container  Container mixin
    %
    %  uix.mixin.Container is a mixin class used by containers to provide
    %  various properties and template methods.

    %  Copyright 2009-2016 The MathWorks, Inc.
    %  $Revision: 1778 $ $Date: 2019-01-23 23:08:35 +0000 (Wed, 23 Jan 2019) $

    properties( Dependent, Access = public )
        Contents % contents in layout order
    end

    properties( Access = public, Dependent, AbortSet )
        Padding % space around contents, in pixels
    end

    properties( Access = protected )
        Contents_ = gobjects( [0 1] ) % backing for Contents
        Padding_ = 0 % backing for Padding
    end

    properties( Dependent, Access = protected )
        Dirty % needs redraw
    end

    properties( Access = private )
        Dirty_ = false % backing for Dirty
        FigureObserver % observer
        FigureListener % listener
        ChildObserver % observer
        ChildAddedListener % listener
        ChildRemovedListener % listener
        SizeChangedListener % listener
        ActivePositionPropertyListeners = cell( [0 1] ) % listeners
    end

    methods

        function obj = Container()
            %uix.mixin.Container  Initialize
            %
            %  c@uix.mixin.Container() initializes the container c.

            % Create observers and listeners
            figureObserver = uix.FigureObserver( obj );
            figureListener = event.listener( figureObserver, ...
                'FigureChanged', @obj.onFigureChanged );
            childObserver = uix.ChildObserver( obj );
            childAddedListener = event.listener( ...
                childObserver, 'ChildAdded', @obj.onChildAdded );
            childRemovedListener = event.listener( ...
                childObserver, 'ChildRemoved', @obj.onChildRemoved );
            sizeChangedListener = event.listener( ...
                obj, 'SizeChanged', @obj.onSizeChanged );

            % Store observers and listeners
            obj.FigureObserver = figureObserver;
            obj.FigureListener = figureListener;
            obj.ChildObserver = childObserver;
            obj.ChildAddedListener = childAddedListener;
            obj.ChildRemovedListener = childRemovedListener;
            obj.SizeChangedListener = sizeChangedListener;

            % Track usage
            obj.track()

        end % constructor

    end % structors

    methods

        function value = get.Contents( obj )

            value = obj.Contents_;

        end % get.Contents

        function set.Contents( obj, value )

            % For those who can't tell a column from a row...
            if isrow( value )
                value = transpose( value );
            end

            % Check
            [tf, indices] = ismember( value, obj.Contents_ );
            assert( isequal( size( obj.Contents_ ), size( value ) ) && ...
                numel( value ) == numel( unique( value ) ) && all( tf ), ...
                'uix:InvalidOperation', ...
                'Property ''Contents'' may only be set to a permutation of itself.' )

            % Call reorder
            obj.reorder( indices )

        end % set.Contents

        function value = get.Padding( obj )

            value = obj.Padding_;

        end % get.Padding

        function set.Padding( obj, value )

            % Check
            assert( isa( value, 'double' ) && isscalar( value ) && ...
                isreal( value ) && ~isinf( value ) && ...
                ~isnan( value ) && value >= 0, ...
                'uix:InvalidPropertyValue', ...
                'Property ''Padding'' must be a non-negative scalar.' )

            % Set
            obj.Padding_ = value;

            % Mark as dirty
            obj.Dirty = true;

        end % set.Padding

        function value = get.Dirty( obj )

            value = obj.Dirty_;

        end % get.Dirty

        function set.Dirty( obj, value )

            if value
                if obj.isDrawable() % drawable
                    obj.redraw() % redraw now
                else % not drawable
                    obj.Dirty_ = true; % flag for future redraw
                end
            end

        end % set.Dirty

    end % accessors

    methods( Access = private, Sealed )

        function onFigureChanged( obj, ~, eventData )
            %onFigureChanged  Event handler

            % Call template method
            obj.reparent( eventData.OldFigure, eventData.NewFigure )

            % Redraw if possible and if dirty
            if obj.Dirty_ && obj.isDrawable()
                obj.redraw()
                obj.Dirty_ = false;
            end

        end % onFigureChanged

        function onChildAdded( obj, ~, eventData )
            %onChildAdded  Event handler

            % Do nothing if add is internal tree surgery
            if isTreeSurgery( eventData.Child ), return, end

            % Call template method
            obj.addChild( eventData.Child )

        end % onChildAdded

        function onChildRemoved( obj, ~, eventData )
            %onChildRemoved  Event handler

            % Do nothing if container is being deleted
            if strcmp( obj.BeingDeleted, 'on' ), return, end

            % Do nothing if remove is internal tree surgery
            if isTreeSurgery( eventData.Child ), return, end

            % Call template method
            obj.removeChild( eventData.Child )

        end % onChildRemoved

        function onSizeChanged( obj, ~, ~ )
            %onSizeChanged  Event handler

            % Mark as dirty
            obj.Dirty = true;

        end % onSizeChanged

        function onActivePositionPropertyChanged( obj, ~, ~ )
            %onActivePositionPropertyChanged  Event handler

            % Mark as dirty
            obj.Dirty = true;

        end % onActivePositionPropertyChanged

    end % event handlers

    methods( Abstract, Access = protected )

        redraw( obj )

    end % abstract template methods

    methods( Access = protected )

        function addChild( obj, child )
            %addChild  Add child
            %
            %  c.addChild(d) adds the child d to the container c.

            % Add to contents
            obj.Contents_(end+1,:) = child;

            % Add listeners
            if isa( child, 'matlab.graphics.axis.Axes' )
                obj.ActivePositionPropertyListeners{end+1,:} = ...
                    event.proplistener( child, ...
                    findprop( child, 'ActivePositionProperty' ), ...
                    'PostSet', @obj.onActivePositionPropertyChanged );
            else
                obj.ActivePositionPropertyListeners{end+1,:} = [];
            end

            % Mark as dirty
            obj.Dirty = true;

        end % addChild

        function removeChild( obj, child )
            %removeChild  Remove child
            %
            %  c.removeChild(d) removes the child d from the container c.

            % Remove from contents
            contents = obj.Contents_;
            tf = contents == child;
            obj.Contents_(tf,:) = [];

            % Remove listeners
            obj.ActivePositionPropertyListeners(tf,:) = [];

            % Mark as dirty
            obj.Dirty = true;

        end % removeChild

        function reparent( obj, oldFigure, newFigure ) %#ok<INUSD>
            %reparent  Reparent container
            %
            %  c.reparent(a,b) reparents the container c from the figure a
            %  to the figure b.

        end % reparent

        function reorder( obj, indices )
            %reorder  Reorder contents
            %
            %  c.reorder(i) reorders the container contents using indices
            %  i, c.Contents = c.Contents(i).

            % Reorder contents
            obj.Contents_ = obj.Contents_(indices,:);

            % Reorder listeners
            obj.ActivePositionPropertyListeners = ...
                obj.ActivePositionPropertyListeners(indices,:);

            % Mark as dirty
            obj.Dirty = true;

        end % reorder

        function tf = isDrawable( obj )
            %isDrawable  Test for drawability
            %
            %  c.isDrawable() is true if the container c is drawable, and
            %  false otherwise.  To be drawable, a container must be
            %  rooted.

            tf = ~isempty( obj.FigureObserver.Figure );

        end % isDrawable

        function track( obj )
            %track  Track usage

            persistent TRACKED % single shot
            if isempty( TRACKED )
                v = ver( 'layout' );
                try %#ok<TRYNC>
                    % Disable tracking it's too hidden in the code
                    % it does not allow users to know it is happening
                    % (even if it is anonymous)
                    % uix.tracking( 'UA-82270656-2', v(1).Version, class( obj ) )
                end
                TRACKED = true;
            end

        end % track

    end % template methods

end % classdef

function tf = isTreeSurgery( child )
%isTreeSurgery  Test for internal tree surgery
%
%  Certain internal operations perform tree surgery, removing a child
%  temporarily and adding it back under an additional node.

if ~isa( child, 'matlab.graphics.axis.Axes' ) % only certain types
    tf = false;
elseif verLessThan( 'MATLAB', '9.5' ) % only certain versions
    tf = false;
else % check stack
    s = dbstack();
    tf = any( strcmp( 'ScribeStackManager.createLayer', {s.name} ) );
end

end % isTreeSurgery


function out = contains(str,pattern,~,ignoreCase)

if nargin == 4 && ignoreCase
  str = lower(str);
  pattern = lower(pattern);
end

out = any(strfind(str,pattern));


function status_out = mlstripcommentsfid(ifid, ofid)
%MLSTRIPCOMMENTSFID Strip comments from code read from file identifier.
%
%   STATUS = MLSTRIPCOMMENTSFID(IFID, OFID) reads MATLAB code, line by line,
%   from the file identifier IFID, strips all MATLAB comments, and writes the
%   result on the output file identifier OFID.  For instance, setting OFID to 1
%   (standard output) will print the result on the screen.  STATUS is 0 if all
%   output was written successfully, and -1 if an error occurred.
%
%   See also MLSTRIPCOMMENTSFILE, MLSTRIPCOMMENTSSTR.

%   Author:      Peter J. Acklam
%   Time-stamp:  2004-03-18 08:23:19 +0100
%   E-mail:      pjacklam@online.no
%   URL:         http://home.online.no/~pjacklam

   % Status is 0 if all output was written successfully, and -1 otherwise.
   status = 0;

   while 1

      % Read input line.
      line = fgetl(ifid);
      if ~ischar(line)
         break;
      end

      % Strip MATLAB comments.
      line = mlstripcommentsstr(line);

      % Write output line.
      count = fprintf(ofid, '%s\n', line);

      % See if an error occurred while writing.
      if count < length(line)
         status = -1;
         break;
      end

   end

   % Only set output variable if it is wanted.
   if nargout
      status_out = status;
   end


function ncopies = checkworkspace(obj);

stack = dbstack;
stack(1:2) = [];
stack      = rmfield(stack, 'line');
ncopies = 0;
if ~isempty(stack)
    % empty stack means the base workspace
    % check if we are in a different workspace
    if ~isequal(stack, obj.workspace)
        % is the current stack a subset of the obj workspace?
        % if yes, it means that the object was created in a subfunction
        % and that it is OK to modify it (because it does not exist in the
        % subfunction any more)
        subFlag = false;
        for index = 1:length(obj.workspace)
            if isequal(obj.workspace(index), stack(1))
                subFlag = true;
                if length(stack) > 1
                    for index2 = 1:length(obj.workspace)-index
                        if length(stack) < index2+1
                            subFlag = false;
                        elseif ~isequal(obj.workspace(index+index2), stack(index2+1))
                            subFlag = false;
                        end;
                    end;
                end;
                if subFlag, return; end;
            end;
        end;

        % if subfunction, must be a copie
        if ~isempty(obj.workspace) && strcmpi(stack(end).file, obj.workspace(end).file) && ...
                ~strcmpi(stack(end).name, obj.workspace(end).name)
            % We are within a subfunction. The MMO must have
            % been passed as an argument (otherwise the current
            % workspace and the workspace variable would be
            % equal).
            ncopies = 2;
        else
            if ~isscript(stack(1).file)
                ncopies = 2;
                % we are within a function. The MMO must have
                % been passed as an argument (otherwise the current
                % workspace and the workspace variable would be
                % equal).
            else
                % we cannot be in a function with 0 argument
                % (otherwise the current workspace and the workspace
                % variable would be equal). We must assume that
                % we are in a script.
                while ~isempty(stack) && ~isequal(stack, obj.workspace)
                    stack(1) = [];
                end;
                if ~isequal(stack, obj.workspace)
                    ncopies = 2;
                end;
            end;
        end;
    end;
end;


function h=semilogy(varargin)
%PREAL/PLOT  Overloaded semilogy function for class PREAL.

global useUnitsFlag

for k=1:length(varargin)
    if isa(varargin{k},'preal'), varargin{k}=double(varargin{k}); end
end
if nargout==0
    semilogy(varargin{:});
else
    h=semilogy(varargin{:});
end


function menu_fieldtrip(handle, cfg, allowsubplot)

% MENU_FIELDTRIP adds a FieldTrip-specific menu to a figure.
%
% See also MENU_VIEWPOINT

if nargin<2
  cfg = [];
end

if nargin<3
  allowsubplot = true;
end

if ~allowsubplot && numel(findobj(gcf, 'type', 'axes')) > 1
  % do not add a menu if there are multiple axes, i.e. subplots
  % these may contain different data structures
  return
end

if ft_platform_supports('uimenu')
  % delete any possibly existing previous menu, this is safe because delete([]) does nothing
  delete(findobj(handle, 'type', 'uimenu', 'label', 'FieldTrip'));

  % add the menu with callbacks
  ftmenu = uimenu(handle, 'Label', 'FieldTrip');
  if ~isempty(cfg)
    uimenu(ftmenu, 'Label', 'Show pipeline', 'Callback', {@cb_pipeline, cfg});
  end
  uimenu(ftmenu, 'Label', 'About', 'Callback', @cb_about);
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cb_pipeline(handle, eventdata, varargin)
ft_analysispipeline([], varargin{1});

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cb_about(handle, eventdata, varargin)
msgbox( {
  'FieldTrip is the MATLAB toolbox for MEG and EEG analysis that is being developed at the Centre for Cognitive Neuroimaging of the Donders Institute for Brain, Cognition and Behaviour together with collaborating institutes. The FieldTrip software is released as open source under the GNU general public license.'
  ''
  sprintf('This is FieldTrip, version %s', ft_version)
  } );


%BrickIO Abstract class definition for brick input output
%
% Methods::
%  open         Open the connection to the brick
%  close        Close the connection to the brick
%  read         Read data from the brick
%  write        Write data to the brick
%
% Notes::
% - handle is the connection object
% - The read function should return a uint8 datatype
% - The write function should be given a uint8 datatype as a parameter

classdef BrickIO
    properties (Abstract)
        % connection handle
        handle
    end

    methods (Abstract)
        % open the brick connection
        open(BrickIO)
        % close the brick connection
        close(BrickIO)
        % read data from the brick
        read(BrickIO)
        % write data to the brick
        write(BrickIO)
    end
end


classdef ActionExecNodeEnum < matlab.mixin.SetGet
    %ActionExecNodeEnum Summary of this class goes here
    %   Detailed explanation goes here

    enumeration
        BeforeProp('Execute Actions Before Propagation')
        AfterProp('Execute Actions After Propagation');
    end

    properties
        name char = '';
    end

    methods
        function obj = ActionExecNodeEnum(name)
            obj.name = name;
        end
    end

    methods(Static)
        function [listBoxStr, enums] = getListBoxStr()
            m = enumeration('ActionExecNodeEnum');
            [~,I] = sort({m.name});
            listBoxStr = {m(I).name};
            enums = m;
        end

        function [ind, enum] = getIndForName(name)
            m = enumeration('ActionExecNodeEnum');
            [~,I] = sort({m.name});
            m = m(I);
            ind = find(ismember({m.name},name),1,'first');
            enum = m(ind);
        end

        function [enum, ind] = getEnumForListboxStr(nameStr)
            m = enumeration('ActionExecNodeEnum');
            ind = find(ismember({m.name},nameStr),1,'first');
            enum = m(ind);
        end
    end
end


% Display Model headers (MR protocol, model detail, fitting parameters, options)
% Example:
%   qMRinfo('mwf'); % display help for Myelin Water Fraction
%
% This function is to provide Octave compatibility for help text.
% Octave accepts a different convention for help documentation.
% Until we find a through solution for Octave help, we will skip this for
% Octave.

% This is the reason why this function will be used instead of 'help'

function varargout = qMRinfo(varargin)
if nargin==0, varargin{1}='Display Model headers (MR protocol, model detail, fitting parameters, options)'; end
if moxunit_util_platform_is_octave || isdeployed
    hh = load('iqmr_gethelp.mat');
    if ischar(varargin{1})
        varargout{1} = hh.(varargin{1});
    else
        varargout{1} = hh.(class(varargin{1}));
    end
else
    [varargout{1:nargout}] = help(varargin{:});
end


function preprocessing()
cd matconvnet;
complienn;
cd ..
end


%% gviridis
% Below is a demonstration of the features of the |gviridis| function

%%
clear; close all; clc;

%% Syntax
% |[cMap]=gviridis(varargin);|

%% Description
% UNDOCUMENTED
%% Examples
%
%%
%
% <<gibbVerySmall.gif>>
%
% _*GIBBON*_
% <www.gibboncode.org>
%
% _Kevin Mattheus Moerman_, <gibbon.toolbox@gmail.com>
%%
% _*GIBBON footer text*_
%
% License: <https://github.com/gibbonCode/GIBBON/blob/master/LICENSE>
%
% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for
% image segmentation, image-based modeling, meshing, and finite element
% analysis.
%
% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.


function rename_brainvision_files(varargin)

    % RENAME_BRAINVISION_FILES renames a BrainVision EEG dataset, which consists of a vhdr header
    % file, vmrk marker file and a data file that usually has the extension dat, eeg or seg.
    %
    % Use as
    % rename_brainvision_files(oldname, newname, 'rmf', 'on')
    % where both the old and the new filename should be strings corresponding to the
    % header file, for instance: including the vhdr extension.
    % 'rmf' option indicates to remove old files and can be turned 'on' of 'off' (default)
    %
    % See also http://www.fieldtriptoolbox.org/ and https://sccn.ucsd.edu/wiki/EEGLAB for
    % open source software to process BrainVision EEG data.
    %
    % Robert Oostenveld https://gist.github.com/robertoostenveld/e31637a777c514bf1e86272e1092316e
    % Cyril Pernet - fixed few bugs here and there https://gist.github.com/CPernet/e037df46e064ca83a49fb4c595d4566a

    %% deal with inputs

    rmf = 'off'; % by default do not delete files
    if nargin >= 3
        if strcmpi(varargin{3}, 'rmf')
            if nargin == 3
                disp('no value associated to the remove file option, assuming off');
            else
                rmf = varargin{4};
            end
        else
            error(['unrecognized option argument ''' varargin{3} '''']);
        end
    end

    oldheaderfile = varargin{1};
    newheaderfile = varargin{2};
    clear varargin;

    % determine whether the file extensions should be in lower or upper case
    if ~isempty(regexp(newheaderfile, 'VHDR$', 'once'))
        switchcase = @upper;
    else
        switchcase = @lower;
    end

    % determine the filename without extension
    [~, f, ~] = fileparts(newheaderfile);

    %% do the renaming

    % deal with the header file
    assert(exist(oldheaderfile, 'file') ~= 0, 'the file %s does not exists', oldheaderfile);
    assert(exist(newheaderfile, 'file') == 0, 'the file %s already exists', newheaderfile);
    fid1 = fopen(oldheaderfile, 'r'); % read old
    fid2 = fopen(newheaderfile, 'w'); % write new

    while ~feof(fid1)
        line = fgetl(fid1);
        if ~isempty(regexp(line, '^MarkerFile', 'once'))
            [~, rem] = strtok(line, '=');
            oldmarkerfile = rem(2:end);
            [~, ~, x] = fileparts(oldmarkerfile);
            newmarkerfile = [f switchcase(x)];
            line = sprintf('MarkerFile=%s', newmarkerfile);
        elseif ~isempty(regexp(line, '^DataFile', 'once'))
            [~, rem] = strtok(line, '=');
            olddatafile = rem(2:end);
            [~, ~, x] = fileparts(olddatafile);
            newdatafile = [f switchcase(x)];
            line = sprintf('DataFile=%s', newdatafile);
        end
        fprintf(fid2, '%s\r\n', line);
    end
    fclose(fid1);
    fclose(fid2);

    % deal with the marker file
    if exist(oldmarkerfile, 'file') == 0
        [~, ~, ext] = fileparts(oldmarkerfile);
        [~, ff, ~] = fileparts(oldheaderfile); % re-reading as sometimes weird names comes up
        if exist([ff ext], 'file')
            oldmarkerfile = [ff ext];
        else
            error('the file %s does not exists', oldmarkerfile);
        end
    end
    assert(exist(newmarkerfile, 'file') == 0, 'the file %s already exists', newmarkerfile);
    fid1 = fopen(oldmarkerfile, 'r');
    fid2 = fopen(newmarkerfile, 'w');

    while ~feof(fid1)
        line = fgetl(fid1);
        if ~isempty(regexp(line, '^HeaderFile', 'once'))
            [~, rem] = strtok(line, '=');
            oldheaderfile = rem(2:end);
            [~, ~, x] = fileparts(oldheaderfile);
            newheaderfile = [f switchcase(x)];
            line = sprintf('HeaderFile=%s', newheaderfile);
        elseif ~isempty(regexp(line, '^DataFile', 'once'))
            [~, rem] = strtok(line, '=');
            olddatafile = rem(2:end);
            [~, ~, x] = fileparts(olddatafile);
            newdatafile = [f switchcase(x)];
            line = sprintf('DataFile=%s', newdatafile);
        end
        fprintf(fid2, '%s\r\n', line);
    end
    fclose(fid1);
    fclose(fid2);

    % deal with the data file
    if exist(olddatafile, 'file') == 0
        [~, ~, ext] = fileparts(olddatafile);
        [~, ff, ~] = fileparts(oldheaderfile); % re-reading as sometimes weird names comes up
        if exist([ff ext], 'file')
            olddatafile = [ff ext];
        else
            error('the file %s does not exists', oldmarkerfile);
        end
    end
    assert(exist(newdatafile, 'file') == 0, 'the file %s already exists', newdatafile);
    status = copyfile(olddatafile, newdatafile);
    if ~status
        error('failed to copy data from %s to %s', olddatafile, newdatafile);
    end

    %% delete old files *try* in case of user restriction
    if strcmpi(rmf, 'on')
        try
            delete(oldheaderfile);
        end
        try
            delete(oldmarkerfile);
        end
        try
            delete(olddatafile);
        end
    end


function YamlStruct = ReadYaml(yaml_file)
% This function reads Yaml file into struct
% Example
% >> yaml_file = 'EnaspolMain.yaml';
% >> YamlStruct = ReadYaml(yaml_file)
%
%  %======================================================================
%{
		Copyright (c) 2011
		This program is a result of a joined cooperation of Energocentrum
		PLUS, s.r.o. and Czech Technical University (CTU) in Prague.
        The program is maintained by Energocentrum PLUS, s.r.o. and
        licensed under the terms of MIT license. Full text of the license
        is included in the program release.

        Author(s):
		Jiri Cigler, Dept. of Control Engineering, CTU Prague
		Jan  Siroky, Energocentrum PLUS s.r.o.

        Implementation and Revisions:

        Auth  Date        Description of change
        ----  ---------   -------------------------------------------------
        jc    01-Mar-11   First implementation
        jc    02-Mar-11   .jar package initialization moved to external fun
        jc    18-Mar-11   Warning added when imported file not found
%}
%======================================================================

InitYaml();

import('org.yaml.snakeyaml.Yaml');

yamlreader = Yaml();
yml = fileread(yaml_file);
jymlobj = yamlreader.load(yml);

Data = Hash2Struct(jymlobj);
work_folder=fileparts(yaml_file);
if isfield(Data,'import')
    yml = '';
    for i=1:numel(Data.import)
        fToImport=[work_folder filesep Data.import{i}];
        try
            fxx=fileread(fToImport);
            yml=sprintf('%s\n%s',yml,  fxx);
        catch
            warning('YAMLMatlab:FileNotFoundException','YAMLMatlab: File %s not found',fToImport);
        end
    end
    jymlobj = yamlreader.load(yml);
    YamlStruct = Hash2Struct(jymlobj);
else
    YamlStruct  =Data;
end
end % end of function


%  Save NIFTI dataset. Support both *.nii and *.hdr/*.img file extension.
%  If file extension is not provided, *.hdr/*.img will be used as default.
%
%  Usage: save_nii(nii, filename, [old_RGB])
%
%  nii.hdr - struct with NIFTI header fields (from load_nii.m or make_nii.m)
%
%  nii.img - 3D (or 4D) matrix of NIFTI data.
%
%  filename - NIFTI file name.
%
%  old_RGB    - an optional boolean variable to handle special RGB data
%       sequence [R1 R2 ... G1 G2 ... B1 B2 ...] that is used only by
%       AnalyzeDirect (Analyze Software). Since both NIfTI and Analyze
%       file format use RGB triple [R1 G1 B1 R2 G2 B2 ...] sequentially
%       for each voxel, this variable is set to FALSE by default. If you
%       would like the saved image only to be opened by AnalyzeDirect
%       Software, set old_RGB to TRUE (or 1). It will be set to 0, if it
%       is default or empty.
%
%  Tip: to change the data type, set nii.hdr.dime.datatype,
%	and nii.hdr.dime.bitpix to:
%
%     0 None                     (Unknown bit per voxel) % DT_NONE, DT_UNKNOWN
%     1 Binary                         (ubit1, bitpix=1) % DT_BINARY
%     2 Unsigned char         (uchar or uint8, bitpix=8) % DT_UINT8, NIFTI_TYPE_UINT8
%     4 Signed short                  (int16, bitpix=16) % DT_INT16, NIFTI_TYPE_INT16
%     8 Signed integer                (int32, bitpix=32) % DT_INT32, NIFTI_TYPE_INT32
%    16 Floating point    (single or float32, bitpix=32) % DT_FLOAT32, NIFTI_TYPE_FLOAT32
%    32 Complex, 2 float32      (Use float32, bitpix=64) % DT_COMPLEX64, NIFTI_TYPE_COMPLEX64
%    64 Double precision  (double or float64, bitpix=64) % DT_FLOAT64, NIFTI_TYPE_FLOAT64
%   128 uint RGB                  (Use uint8, bitpix=24) % DT_RGB24, NIFTI_TYPE_RGB24
%   256 Signed char            (schar or int8, bitpix=8) % DT_INT8, NIFTI_TYPE_INT8
%   511 Single RGB              (Use float32, bitpix=96) % DT_RGB96, NIFTI_TYPE_RGB96
%   512 Unsigned short               (uint16, bitpix=16) % DT_UNINT16, NIFTI_TYPE_UNINT16
%   768 Unsigned integer             (uint32, bitpix=32) % DT_UNINT32, NIFTI_TYPE_UNINT32
%  1024 Signed long long              (int64, bitpix=64) % DT_INT64, NIFTI_TYPE_INT64
%  1280 Unsigned long long           (uint64, bitpix=64) % DT_UINT64, NIFTI_TYPE_UINT64
%  1536 Long double, float128  (Unsupported, bitpix=128) % DT_FLOAT128, NIFTI_TYPE_FLOAT128
%  1792 Complex128, 2 float64  (Use float64, bitpix=128) % DT_COMPLEX128, NIFTI_TYPE_COMPLEX128
%  2048 Complex256, 2 float128 (Unsupported, bitpix=256) % DT_COMPLEX128, NIFTI_TYPE_COMPLEX128
%
%  Part of this file is copied and modified from:
%  http://www.mathworks.com/matlabcentral/fileexchange/1878-mri-analyze-tools
%
%  NIFTI data format can be found on: http://nifti.nimh.nih.gov
%
%  - Jimmy Shen (jimmy@rotman-baycrest.on.ca)
%  - "old_RGB" related codes in "save_nii.m" are added by Mike Harms (2006.06.28)
%
function save_nii(nii, fileprefix, old_RGB)

   if ~exist('nii','var') | isempty(nii) | ~isfield(nii,'hdr') | ...
	~isfield(nii,'img') | ~exist('fileprefix','var') | isempty(fileprefix)

      error('Usage: save_nii(nii, filename, [old_RGB])');
   end

   if isfield(nii,'untouch') & nii.untouch == 1
      error('Usage: please use ''save_untouch_nii.m'' for the untouched structure.');
   end

   if ~exist('old_RGB','var') | isempty(old_RGB)
      old_RGB = 0;
   end

   v = version;

   %  Check file extension. If .gz, unpack it into temp folder
   %
   if length(fileprefix) > 2 & strcmp(fileprefix(end-2:end), '.gz')

      if ~strcmp(fileprefix(end-6:end), '.img.gz') & ...
	 ~strcmp(fileprefix(end-6:end), '.hdr.gz') & ...
	 ~strcmp(fileprefix(end-6:end), '.nii.gz')

         error('Please check filename.');
      end

      if str2num(v(1:3)) < 7.1 | ~usejava('jvm')
         error('Please use MATLAB 7.1 (with java) and above, or run gunzip outside MATLAB.');
      else
         gzFile = 1;
         fileprefix = fileprefix(1:end-3);
      end
   end

   filetype = 1;

   %  Note: fileprefix is actually the filename you want to save
   %
   if findstr('.nii',fileprefix) & strcmp(fileprefix(end-3:end), '.nii')
      filetype = 2;
      fileprefix(end-3:end)='';
   end

   if findstr('.hdr',fileprefix) & strcmp(fileprefix(end-3:end), '.hdr')
      fileprefix(end-3:end)='';
   end

   if findstr('.img',fileprefix) & strcmp(fileprefix(end-3:end), '.img')
      fileprefix(end-3:end)='';
   end

   write_nii(nii, filetype, fileprefix, old_RGB);

   %  gzip output file if requested
   %
   if exist('gzFile', 'var')
      if filetype == 1
         gzip([fileprefix, '.img']);
         delete([fileprefix, '.img']);
         gzip([fileprefix, '.hdr']);
         delete([fileprefix, '.hdr']);
      elseif filetype == 2
         gzip([fileprefix, '.nii']);
         delete([fileprefix, '.nii']);
      end;
   end;

   if filetype == 1

      %  So earlier versions of SPM can also open it with correct originator
      %
      M=[[diag(nii.hdr.dime.pixdim(2:4)) -[nii.hdr.hist.originator(1:3).*nii.hdr.dime.pixdim(2:4)]'];[0 0 0 1]];
      save([fileprefix '.mat'], 'M');
   end

   return					% save_nii

%-----------------------------------------------------------------------------------
function write_nii(nii, filetype, fileprefix, old_RGB)

   hdr = nii.hdr;

   if isfield(nii,'ext') & ~isempty(nii.ext)
      ext = nii.ext;
      [ext, esize_total] = verify_nii_ext(ext);
   else
      ext = [];
   end

   switch double(hdr.dime.datatype),
   case   1,
      hdr.dime.bitpix = int16(1 ); precision = 'ubit1';
   case   2,
      hdr.dime.bitpix = int16(8 ); precision = 'uint8';
   case   4,
      hdr.dime.bitpix = int16(16); precision = 'int16';
   case   8,
      hdr.dime.bitpix = int16(32); precision = 'int32';
   case  16,
      hdr.dime.bitpix = int16(32); precision = 'float32';
   case  32,
      hdr.dime.bitpix = int16(64); precision = 'float32';
   case  64,
      hdr.dime.bitpix = int16(64); precision = 'float64';
   case 128,
      hdr.dime.bitpix = int16(24); precision = 'uint8';
   case 256
      hdr.dime.bitpix = int16(8 ); precision = 'int8';
   case 511,
      hdr.dime.bitpix = int16(96); precision = 'float32';
   case 512
      hdr.dime.bitpix = int16(16); precision = 'uint16';
   case 768
      hdr.dime.bitpix = int16(32); precision = 'uint32';
   case 1024
      hdr.dime.bitpix = int16(64); precision = 'int64';
   case 1280
      hdr.dime.bitpix = int16(64); precision = 'uint64';
   case 1792,
      hdr.dime.bitpix = int16(128); precision = 'float64';
   otherwise
      error('This datatype is not supported');
   end

   hdr.dime.glmax = round(double(max(nii.img(:))));
   hdr.dime.glmin = round(double(min(nii.img(:))));

   if filetype == 2
      fid = fopen(sprintf('%s.nii',fileprefix),'w');

      if fid < 0,
         msg = sprintf('Cannot open file %s.nii.',fileprefix);
         error(msg);
      end

      hdr.dime.vox_offset = 352;

      if ~isempty(ext)
         hdr.dime.vox_offset = hdr.dime.vox_offset + esize_total;
      end

      hdr.hist.magic = 'n+1';
      save_nii_hdr(hdr, fid);

      if ~isempty(ext)
         save_nii_ext(ext, fid);
      end
   else
      fid = fopen(sprintf('%s.hdr',fileprefix),'w');

      if fid < 0,
         msg = sprintf('Cannot open file %s.hdr.',fileprefix);
         error(msg);
      end

      hdr.dime.vox_offset = 0;
      hdr.hist.magic = 'ni1';
      save_nii_hdr(hdr, fid);

      if ~isempty(ext)
         save_nii_ext(ext, fid);
      end

      fclose(fid);
      fid = fopen(sprintf('%s.img',fileprefix),'w');
   end

   ScanDim = double(hdr.dime.dim(5));		% t
   SliceDim = double(hdr.dime.dim(4));		% z
   RowDim   = double(hdr.dime.dim(3));		% y
   PixelDim = double(hdr.dime.dim(2));		% x
   SliceSz  = double(hdr.dime.pixdim(4));
   RowSz    = double(hdr.dime.pixdim(3));
   PixelSz  = double(hdr.dime.pixdim(2));

   x = 1:PixelDim;

   if filetype == 2 & isempty(ext)
      skip_bytes = double(hdr.dime.vox_offset) - 348;
   else
      skip_bytes = 0;
   end

   if double(hdr.dime.datatype) == 128

      %  RGB planes are expected to be in the 4th dimension of nii.img
      %
      if(size(nii.img,4)~=3)
         error(['The NII structure does not appear to have 3 RGB color planes in the 4th dimension']);
      end

      if old_RGB
         nii.img = permute(nii.img, [1 2 4 3 5 6 7 8]);
      else
         nii.img = permute(nii.img, [4 1 2 3 5 6 7 8]);
      end
   end

   if double(hdr.dime.datatype) == 511

      %  RGB planes are expected to be in the 4th dimension of nii.img
      %
      if(size(nii.img,4)~=3)
         error(['The NII structure does not appear to have 3 RGB color planes in the 4th dimension']);
      end

      if old_RGB
         nii.img = permute(nii.img, [1 2 4 3 5 6 7 8]);
      else
         nii.img = permute(nii.img, [4 1 2 3 5 6 7 8]);
      end
   end

   %  For complex float32 or complex float64, voxel values
   %  include [real, imag]
   %
   if hdr.dime.datatype == 32 | hdr.dime.datatype == 1792
      real_img = real(nii.img(:))';
      nii.img = imag(nii.img(:))';
      nii.img = [real_img; nii.img];
   end

   if skip_bytes
      fwrite(fid, zeros(1,skip_bytes), 'uint8');
   end

   fwrite(fid, nii.img, precision);
%   fwrite(fid, nii.img, precision, skip_bytes);        % error using skip
   fclose(fid);

   return;					% write_nii


% open binary files to write registered tiffs to
% takes ops, ops1, and red_binary (if 1 then write red channel to binary)
function [ops1, fid, fidRED, fidIntpol] = openBinFiles(ops, ops1, red_binary)
numPlanes = numel(ops.planesToProcess);
fid    = cell(numPlanes, size(ops1,2));
fidRED = cell(numPlanes, size(ops1,2));
fidIntpol = [];
if ops.interpolateAcrossPlanes == 1 && ~isempty(ops.RegFileBinLocation)
    fidIntpol = cell(numPlanes, size(ops1,2));
end

for i = 1:numPlanes
    for j = 1:size(ops1,2)
        ops1{i,j}.RegFile = fullfile(ops.RegFileRoot, ...
            sprintf('%s_%s_%s_plane%d.bin', ops.mouse_name, ops.date, ...
            ops.CharSubDirs, i + (j-1)*numPlanes));
        regdir = fileparts(ops1{i,j}.RegFile);
        if ~exist(regdir, 'dir')
            mkdir(regdir);
        end

        % open bin file for writing
        fid{i,j}              = fopen(ops1{i,j}.RegFile, 'w');

        if red_binary
            ops1{i,j}.RegFile2 = fullfile(ops.RegFileRoot, ...
                sprintf('%s_%s_%s_plane%d_RED.bin', ops.mouse_name, ops.date, ...
                ops.CharSubDirs, i + (j-1)*numPlanes));
            fidRED{i,j}              = fopen(ops1{i,j}.RegFile2, 'w');
        end

        if ops.interpolateAcrossPlanes && ~isempty(ops.RegFileBinLocation)
            % open separate files for result after averaging across
            % neighbouring planes
            str = sprintf('%d_',ops1{i,j}.expts);
            str(end) = [];
            folder = fullfile(ops1{i,j}.RegFileBinLocation, ops1{i,j}.mouse_name, ...
                ops1{i,j}.date, str, 'interpolated');
            if ~exist(folder, 'dir')
                mkdir(folder);
            end
            fidIntpol{i,j} = fopen(fullfile(folder, ...
                sprintf('%s_%s_%s_plane%d.bin', ops.mouse_name, ops.date, ...
                ops.CharSubDirs, i + (j-1)*numPlanes)), 'w');
        end
    end
end


function DBExportGallery(name,query,varargin)

%DBExportGallery - Create figure gallery from current database.
%
% Select figures and create an HTML gallery (although not required, installing
% export_fig will yield better PNG images).
%
%  USAGE
%
%    DBExportGallery(name,query,<options>)
%
%    name           gallery name
%    query          optional figure list query (WHERE clause; see Example)
%    <options>      optional list of property-value pairs (see table below)
%
%    =========================================================================
%     Properties    Values
%    -------------------------------------------------------------------------
%     'size'        horizontal and vertical thumbnail size
%                   (default = [240 240])
%     'nColumns'    number of columns (default = 3)
%     'info'        display detailed info with thumbnails (default = 'off')
%     'code'        create generation code pages (default = 'off')
%    =========================================================================
%
%  EXAMPLES
%
%    % Export entire gallery with extensive information
%    DBExportGallery('Complete Gallery','info','on');
%
%    % Export only figures for the session named 'SESSION1'
%    DBExportGallery('Partial Gallery','eid="SESSION1"');
%
%    % Export figures for all sessions with names starting with 'SLEEP'
%    DBExportGallery('Sleep Gallery','eid like "SLEEP%"');

% Copyright (C) 2007-2013 by Michaël Zugaro
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 3 of the License, or
% (at your option) any later version.

% Make sure MyM is installed and functional
CheckMyM;

% Default values
hSize = 240;
vSize = 240;
nColumns = 3;
showInfo = 'off';
showCode = 'off';

% Check number of parameters
if nargin < 1,
	error('Incorrect number of parameters (type ''help DBExportGallery'' for details).');
end

% Optional query provided?
if nargin == 1,
	query = '';
elseif isstring_FMAT(query,'size','ncolumns','info','code'),
	varargin = {query varargin{:}};
	query = '';
end

% Edit query
query = strtrim(query);
query = regexprep(query,'^where','');
if ~isempty(query), query = [' where ' query]; end

% Parse parameter list
for j = 1:2:length(varargin),
	if ~ischar(varargin{j}),
		error(['Parameter ' num2str(j+7) ' is not a property (type ''help DBExportGallery'' for details).']);
	end
	switch(lower(varargin{j})),
		case 'size',
			sizes = varargin{j+1};
			if ~isivector(sizes,'>0','#2'),
				error('Incorrect value for ''size'' (type ''help DBExportGallery'' for details).');
			end
			hSize = sizes(1);
			vSize = sizes(2);

		case 'ncolumns',
			nColumns = varargin{j+1};
			if ~isiscalar(nColumns,'>0'),
				error('Incorrect value for ''ncolumns'' (type ''help DBExportGallery'' for details).');
			end

		case 'info',
			showInfo = lower(varargin{j+1});
			if ~isstring_FMAT(showInfo,'on','off'),
				error('Incorrect value for ''info'' (type ''help DBExportGallery'' for details).');
			end

		case 'code',
			showCode = lower(varargin{j+1});
			if ~isstring_FMAT(showCode,'on','off'),
				error('Incorrect value for ''code'' (type ''help DBExportGallery'' for details).');
			end

		otherwise,
			error(['Unknown property ''' num2str(varargin{j}) ''' (type ''help DBExportGallery'' for details).']);

	end
end

showInfo = strcmp(showInfo,'on');
showCode = strcmp(showCode,'on');

% Edit query
query = strtrim(query);
fullQuery = regexprep(query,'^where','');
if ~isempty(fullQuery), fullQuery = [' where ' fullQuery]; end

% Query database
f = mym(['select png,eid,name,parameters,comments,mfiles,code,date,user from figures' fullQuery]);
if isempty(f.eid),
	warning(['No figures match ''' query '''.']);
end

% Reformat code
code = {};
for i = 1:length(f.code),
	for j = 1:length(f.code{i}),
		code{i}{j} = char(f.code{i}{j})';
	end
end
f.code = code;

% Correct eids and names: replace / with _ to avoid conflicts with filesystem
nFigures = length(f.png);
for i = 1:nFigures,
	f.eid{i} = strrep(f.eid{i},'/','_');
        f.name{i} = strrep(f.name{i},'/','_');
end

% Create root directory
try
	mkdir(name);
	mkdir([name '/images']);
	mkdir([name '/thumbs']);
	if showCode,
		mkdir([name '/code']);
	end
catch
	error('Cannot create gallery (check file access permissions).');
end
[path,name] = fileparts(name);

% Export png images + thumbnails (and code pages if required)
for i = 1:nFigures,
	% png image
	figureName{i} = [f.eid{i} '-' f.name{i} '.png'];
	file = fopen([path name '/images/' figureName{i}],'wb');
	if file == -1,
		error(['Could not create figure ' figureName{i} '.']);
	end
	fwrite(file,f.png{i});
	fclose(file);

	% Thumbnail
	pngData = imread([path name '/images/' figureName{i}],'png');
   [height,width,nz] = size(pngData);
   hScale = width/hSize;
   vScale = height/vSize;
	x = floor(1:hScale:width);
	y = floor(1:vScale:height);
   thumbnail = pngData(y,x,:);
   imwrite(thumbnail,[path name '/thumbs/' figureName{i}],'png');

	% Code
	if showCode && ~isempty(f.code) && ~isempty(f.code{i}),
		file = fopen([path name '/code/' figureName{i}(1:end-4) '.m'],'w');
		if file == -1,
			error('Could not create code output.');
		end
		nFunctions = size(f.code{i},2);
		for j = 1:nFunctions,
			if j > 1, fprintf(file,'\n\n'); end
			fprintf(file,'%% =======================================================================================================\n');
			fprintf(file,['%%     ' f.mfiles{i}{j} '\n']);
			fprintf(file,'%% =======================================================================================================\n\n\n');
			fprintf(file,'%s',f.code{i}{j});
		end
%  		if isempty(j), j = 1; end
%  		fprintf(file,'%s',f.code{i}{j});
		fclose(file);
	end
end

% Output HTML code
% Header...
fid = fopen([path name '/index.html'],'w');
fprintf(fid,'<?xml version="1.0" encoding="UTF-8" ?>\n');
fprintf(fid,'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">\n');
fprintf(fid,'\n');
fprintf(fid,' \n');
fprintf(fid,'  <title>%s</title>\n',name);
fprintf(fid,'  <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>\n');
fprintf(fid,'  <meta name="GENERATOR" content="FMAToolbox"/>\n');
fprintf(fid,'  \n');
fprintf(fid,' \n');
fprintf(fid,' \n');
fprintf(fid,'
%s
\n',name);
fprintf(fid,'
%d images (%s)

\n',nFigures,datestr(now));
fprintf(fid,'
\n');
fprintf(fid,'
\n');

% ... figure table...
nLines = ceil(nFigures/nColumns);
i = 1;
for line = 1:nLines,
	fprintf(fid,'
\n');
	for column = 1:nColumns,
		if i > nFigures, break; end
		fprintf(fid,'    \n');
		fprintf(fid,'     \n',figureName{i},figureName{i},hSize,vSize);
		fprintf(fid,'
\n');
		fprintf(fid,'
\n');
		fprintf(fid,'       \n');
		fprintf(fid,'        EID\n');
		fprintf(fid,'       	\n');
		fprintf(fid,'       \n');
		fprintf(fid,'
%s
\n',f.eid{i});
		fprintf(fid,'       	\n');
		fprintf(fid,'
\n');
		fprintf(fid,'
\n');
		fprintf(fid,'       \n');
		fprintf(fid,'        Name\n');
		fprintf(fid,'       	\n');
		fprintf(fid,'       \n');
		fprintf(fid,'
%s
\n',f.name{i});
		fprintf(fid,'       	\n');
		fprintf(fid,'
\n');
		if showInfo,
			fprintf(fid,'
\n');
			fprintf(fid,'       \n');
			fprintf(fid,'        Comments\n');
			fprintf(fid,'       	\n');
			fprintf(fid,'       \n');
			fprintf(fid,'
%s
\n',f.comments{i});
			fprintf(fid,'       	\n');
			fprintf(fid,'
\n');
			fprintf(fid,'
\n');
			fprintf(fid,'       \n');
			fprintf(fid,'        Parameters\n');
			fprintf(fid,'       	\n');
			fprintf(fid,'       \n');
			fprintf(fid,'
%s
\n',f.parameters{i});
			fprintf(fid,'       	\n');
			fprintf(fid,'
\n');
		end
		if showCode && ~isempty(f.code) && ~isempty(f.code{i}),
			codeName = [figureName{i}(1:end-4) '.m'];
			fprintf(fid,'
\n');
			fprintf(fid,'       \n');
			fprintf(fid,'        Code\n');
			fprintf(fid,'       	\n');
			fprintf(fid,'       \n');
			fprintf(fid,'        [M-File]\n',codeName);
			fprintf(fid,'       	\n');
			fprintf(fid,'
\n');
		end
		if showInfo,
			fprintf(fid,'
\n');
			fprintf(fid,'       \n');
			fprintf(fid,'        Date\n');
			fprintf(fid,'       	\n');
			fprintf(fid,'       \n');
			fprintf(fid,'
%s
\n',f.date{i});
			fprintf(fid,'       	\n');
			fprintf(fid,'
\n');
			fprintf(fid,'
\n');
			fprintf(fid,'       \n');
			fprintf(fid,'        User\n');
			fprintf(fid,'       	\n');
			fprintf(fid,'       \n');
			fprintf(fid,'
%s
\n',f.user{i});
			fprintf(fid,'       	\n');
			fprintf(fid,'
\n');
		end
		fprintf(fid,'
\n');
		fprintf(fid,'    	\n');
		i = i+1;
	end
	fprintf(fid,'
\n');
end

% ... and footer
fprintf(fid,'
\n');
fprintf(fid,' \n');
fprintf(fid,'\n');