classdef RunClass < TreeNodeClass

    methods

        % ----------------------------------------------------------------------------------
        function obj = RunClass(varargin)
            %
            % Syntax:
            %   obj = RunClass()
            %   obj = RunClass(filename);
            %   obj = RunClass(filename, iGroup, iSubj, iSess, iRun);
            %   obj = RunClass(run);
            %
            % Example 1:
            %   run1     = RunClass('./s1/neuro_run01.nirs',1,1,1,1);
            %   run1copy = RunClass(run1);
            %
            obj@TreeNodeClass(varargin);

            obj.type  = 'run';
            if nargin==0
                obj.name  = '';
                return;
            end
            if isa(varargin{1}, 'RunClass')
                obj.Copy(varargin{1});
                return;
            elseif isa(varargin{1}, 'FileClass')
                [~, ~, ~, obj.name] = varargin{1}.ExtractNames();
                obj.path         = varargin{1}.GetFilesPath();  % Fix wrong root path
            elseif ischar(varargin{1}) && strcmp(varargin{1},'copy')
                return;
            elseif ischar(varargin{1})
                obj.name = varargin{1};
            end
            if nargin==5
                obj.iGroup = varargin{2};
                obj.iSubj  = varargin{3};
                obj.iSess  = varargin{4};
                obj.iRun   = varargin{5};
            end

            obj.LoadAcquiredData();
            if obj.acquired.Error()
                obj = RunClass.empty();
                return;
            end
            obj.procStream = ProcStreamClass(obj.acquired);
            obj.InitTincMan();
            if isa(varargin{1}, 'FileClass')
                varargin{1}.Loaded();
            end

        end

        % ----------------------------------------------------------------------------------
        function b = Error(obj)
            if isempty(obj)
                b = -1;
                return;
            end
            b = obj.acquired.Error();
        end

        % ----------------------------------------------------------------------------------
        function err = Load(obj)
            err = 0;
            err1 = obj.LoadAcquiredData();
            err2 = obj.LoadDerivedData();
            if ~(err1==0 && err2==0)
                err = -1;
            end
        end

        % ----------------------------------------------------------------------------------
        function err = LoadDerivedData(obj)
            err = 0;
            if isempty(obj)
                return;
            end
            err = obj.procStream.Load([obj.path, obj.GetOutputFilename]);
        end

        % ----------------------------------------------------------------------------------
        function err = LoadAcquiredData(obj)
            err = -1;
            if isempty(obj)
                return;
            end

            if isempty(obj.SaveMemorySpace(obj.name))
                % Storage scheme is memory: In this case load acquisition data unconditionally.
                dataStorageScheme = 'memory';
            else
                dataStorageScheme = 'files';
            end

            if isempty(obj.acquired)
                if obj.IsNirs()
                    obj.acquired = NirsClass([obj.path, obj.name], dataStorageScheme);
                else
                    obj.acquired = SnirfClass([obj.path, obj.name], dataStorageScheme);
                end
            else
                obj.acquired.Load([obj.path, obj.name]);
            end

            if obj.acquired.Error() < 0
                obj.logger.Write( sprintf('     **** Error: "%s" failed to load - %s\n', obj.name, obj.acquired.GetErrorMsg()) );
                return;
            elseif obj.acquired.Error() > 0
                obj.logger.Write( sprintf('     **** Warning: %s in file "%s"\n', obj.acquired.GetErrorMsg(), obj.name) );
            else
                %fprintf('    Loaded file %s to run.\n', obj.name);
            end
            err = 0;
        end

        % ----------------------------------------------------------------------------------
        function FreeMemory(obj)
            if isempty(obj)
                return;
            end

            % Unload derived data
            obj.procStream.FreeMemory([obj.path, obj.GetOutputFilename()]);

            % Unload acquired data
            obj.acquired.FreeMemory([obj.path, obj.GetFilename()]);
        end

        % ----------------------------------------------------------------------------------
        function SaveAcquiredData(obj)
            if isempty(obj)
                return;
            end
            obj.procStream.input.SaveAcquiredData()
        end

        % ----------------------------------------------------------------------------------
        function b = AcquiredDataModified(obj)
            b = obj.procStream.AcquiredDataModified();
            if b
                obj.logger.Write(sprintf('Acquisition data for run %s has been modified\n', obj.name));
            end
        end

        % ----------------------------------------------------------------------------------
        % Copy processing params (procInut and procResult) from
        % N2 to N1 if N1 and N2 are same nodes
        % ----------------------------------------------------------------------------------
        function Copy(obj, obj2, conditional)
            if nargin==3 && strcmp(conditional, 'conditional')
                if obj.Mismatch(obj2)
                    return
                end
                obj.Copy@TreeNodeClass(obj2, 'conditional');
            else
                obj.Copy@TreeNodeClass(obj2);
                if isempty(obj.acquired)
                    if obj.IsNirs()
                        obj.acquired = NirsClass();
                    else
                        obj.acquired = SnirfClass();
                    end
                end
                obj.acquired.Copy(obj2.acquired);
            end
        end

        % --------------------------------------------------------------
        function CopyStims(obj, obj2)
            obj.CondNames = obj2.CondNames;
            obj.procStream.CopyStims(obj2.procStream);
        end

        % ----------------------------------------------------------------------------------
        % Subjects obj1 and obj2 are considered equivalent if their names
        % are equivalent and their sets of runs are equivalent.
        % ----------------------------------------------------------------------------------
        function B = equivalent(obj1, obj2)
            B=1;
            [p1,n1] = fileparts(obj1.name);
            [p2,n2] = fileparts(obj2.name);
            if ~strcmp([p1,'/',n1],[p2,'/',n2])
                B=0;
                return;
            end
        end

        % ----------------------------------------------------------------------------------
        function b = IsEmpty(obj)
            b = true;
            if isempty(obj)
                return;
            end
            if obj.acquired.IsEmpty()
                return;
            end
            b = false;
        end

        % ----------------------------------------------------------------------------------
        function b = IsEmptyOutput(obj)
            b = true;
            if isempty(obj)
                return;
            end
            obj.LoadDerivedData();
            if obj.procStream.IsEmptyOutput()
                return;
            end
            b = false;
        end

    end

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    methods

        % ----------------------------------------------------------------------------------
        function b = IsNirs(obj)
            b = false;
            [~,~,ext] = fileparts(obj.name);
            if strcmp(ext,'.nirs')
                b = true;
            end
        end

        % ----------------------------------------------------------------------------------
        function varval = GetVar(obj, varname)
            varval = [];
            if isproperty(obj, varname)
                varval = eval( sprintf('obj.%s', varname) );
            end
            if isempty(varval)
                varval = obj.procStream.GetVar(varname);
            end
            if isempty(varval)
                varval = obj.acquired.GetVar(varname);
            end
        end

        % ----------------------------------------------------------------------------------
        function LoadInputVars(obj)

            % a) Find all variables needed by proc stream
            args = obj.procStream.GetInputArgs();

            % b) Find these variables in this run
            for ii = 1:length(args)
                eval( sprintf('obj.inputVars.%s = obj.GetVar(args{ii});', args{ii}) );
            end
        end

        % ----------------------------------------------------------------------------------
        function Calc(obj, options)
            if ~exist('options','var') || isempty(options)
                options = 'overwrite';
            end

            % Update call application GUI using it's generic Update function
            if ~isempty(obj.updateParentGui)
                obj.updateParentGui('DataTreeClass', [obj.iGroup, obj.iSubj, obj.iSess, obj.iRun]);
            end

            % Load acquired data
            obj.acquired.Load();

            if strcmpi(options, 'overwrite')
                % Recalculating result means deleting old results, if
                % option == 'overwrite'
                obj.procStream.output.Flush();
            end

            if obj.DEBUG
                fprintf('Calculating processing stream for group %d, subject %d, session %d, run %d\n', obj.iGroup, obj.iSubj, obj.iSess, obj.iRun);
            end

            % Find all variables needed by proc stream, find them in this run, and load them to proc stream input
            obj.LoadInputVars();

            Calc@TreeNodeClass(obj);

            if obj.DEBUG
                obj.logger.Write(sprintf('Completed processing stream for group %d, subject %d, session %d, run %d\n', obj.iGroup, obj.iSubj, obj.iSess, obj.iRun));
                obj.logger.Write('\n')
            end
        end

        % ----------------------------------------------------------------------------------
        function Print(obj, indent)
            if ~exist('indent', 'var')
                indent = 4;
            else
                indent = indent+4;
            end
            Print@TreeNodeClass(obj, indent);
        end

        % ---------------------------------------------------------------
        function PrintProcStream(obj)
            fcalls = obj.procStream.GetFuncCallChain();
            obj.logger.Write('Run processing stream:\n');
            for ii = 1:length(fcalls)
                obj.logger.Write('%s\n', fcalls{ii});
            end
        end

    end    % Public methods

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % Pubic Set/Get methods for acquired data
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    methods

        % ----------------------------------------------------------------------------------
        function t = GetTime(obj, iBlk)
            if nargin==1
                iBlk=1;
            end

            % Sometimes the caller is NOT the current element in which case we need to load
            % (when dataStorageScheme = 'file' mode) here explicitely.
            err = -1;
            if obj.acquired.IsEmpty()
                err = obj.acquired.LoadTime();
            end
            t = obj.acquired.GetTime(iBlk);
            if err==0
                obj.acquired.FreeMemory(obj.GetFilename());
            end
        end

        % ----------------------------------------------------------------------------------
        function t = GetTimeCombined(obj)
            % Sometimes the caller is NOT the current element in which case we need to load
            % (when dataStorageScheme = 'file' mode) here explicitely.
            err = -1;
            if obj.acquired.IsEmpty()
                err = obj.acquired.LoadTime();
            end
            t = obj.acquired.GetTimeCombined();
            if err==0
                obj.acquired.FreeMemory(obj.GetFilename());
            end
        end

        % ----------------------------------------------------------------------------------
        function t = GetAuxiliaryTime(obj)
            % Sometimes the caller is NOT the current element in which case we need to load
            % (when dataStorageScheme = 'file' mode) here explicitely. BUT this needs to be
            % optimized to NOT load the whole thing, just aux - see GetTime()/ GetTimeCombined().
            % TBD. jdubb, 08/17/2022
            err = -1;
            if obj.acquired.IsEmpty()
                obj.acquired.Load();
                err = obj.GetError();
            end
            t = obj.acquired.GetAuxiliaryTime();
            if err==0
                obj.acquired.FreeMemory(obj.GetFilename());
            end
        end

        % ----------------------------------------------------------------------------------
        function [d, t, ml] = GetRawData(obj, iBlk)
            if nargin<2
                iBlk = 1;
            end
            [d, t, ml] = obj.acquired.GetDataTimeSeries('', iBlk);
        end

        % ----------------------------------------------------------------------------------
        function [d, t, ml] = GetDataTimeSeries(obj, options, iBlk)
            if ~exist('options','var')
                options = '';
            end
            if ~exist('iBlk','var') || isempty(iBlk)
                iBlk = 1;
            end
            if isempty(options) || strcmp(options, 'reshape')
                [d, t, ml] = obj.acquired.GetDataTimeSeries(options, iBlk);
            else
                [d, t, ml] = obj.GetDataTimeSeries@TreeNodeClass(options, iBlk);
            end
        end

        % ----------------------------------------------------------------------------------
        function [iDataBlks, iCh] = GetDataBlocksIdxs(obj, iCh)
            if nargin<2
                iCh = [];
            end
            [iDataBlks, iCh] = obj.acquired.GetDataBlocksIdxs(iCh);
        end

        % ----------------------------------------------------------------------------------
        function n = GetDataBlocksNum(obj)
            n = obj.acquired.GetDataBlocksNum();
        end

        % ----------------------------------------------------------------------------------
        function SD = GetSDG(obj,option)
            % Sometimes the caller is NOT the current element in which case we need to load
            % (when dataStorageScheme = 'file' mode) here explicitely. BUT this needs to be
            % optimized to NOT load the whole thing, just SDG. TBD. jdubb, 08/17/2022
            err = -1;
            if obj.acquired.IsEmpty()
                obj.acquired.Load();
                err = obj.GetError();
            end
            SD.Lambda  = obj.acquired.GetWls();
            if exist('option','var')
                SD.SrcPos  = obj.acquired.GetSrcPos(option);
                SD.DetPos  = obj.acquired.GetDetPos(option);
            else
                SD.SrcPos  = obj.acquired.GetSrcPos();
                SD.DetPos  = obj.acquired.GetDetPos();
            end
            if err==0
                obj.acquired.FreeMemory(obj.GetFilename());
            end
        end

        % ----------------------------------------------------------------------------------
        function InitMlActMan(obj, iBlk)
            if ~exist('iBlk','var')
                iBlk = 1;
            end
            ml = obj.acquired.data.GetMeasListSrcDetPairs(iBlk);
            obj.procStream.input.SetMeasListActMan([ml, ones(size(ml, 1), 1)]);
        end

        % ----------------------------------------------------------------------------------
        function InitMlVis(obj, iBlk)
            if ~exist('iBlk','var')
                iBlk = 1;
            end
            ml = obj.acquired.data.GetMeasListSrcDetPairs(iBlk);
            obj.procStream.input.SetMeasListActMan([ml, ones(size(ml, 1), 1)]);
        end

        % ----------------------------------------------------------------------------------
        function ch = GetMeasList(obj, options, iBlk)
            if ~exist('iBlk','var') || isempty(iBlk)
                iBlk=1;
            end
            if ~exist('options','var')
                options = '';
            end

            ch = struct('MeasList',[], 'MeasListVis',[], 'MeasListActMan',[], 'MeasListActAuto',[]);

            % Sometimes the caller is NOT the current element in which case we need to load
            % (when dataStorageScheme = 'file' mode) here explicitely. BUT this needs to be
            % optimized to NOT load the whole thing, just SDG. TBD. jdubb, 08/17/2022
            err = -1;
            if obj.acquired.IsEmpty()
                obj.acquired.Load();
                err = obj.GetError();
            end

            ch.MeasList        = obj.acquired.GetMeasList(iBlk);
            ch.MeasListActMan  = obj.procStream.GetMeasListActMan(iBlk);
            ch.MeasListActAuto = obj.procStream.GetMeasListActAuto(iBlk);

            ch.MeasListActMan  = mlAct_Initialize(ch.MeasListActMan, ch.MeasList);
            ch.MeasListActAuto = mlAct_Initialize(ch.MeasListActAuto, ch.MeasList);
            if strcmp(options,'reshape')
                ch.MeasList = sortrows(ch.MeasList);
            end
            if err==0
                obj.acquired.FreeMemory(obj.GetFilename());
            end
        end

        % ----------------------------------------------------------------------------------
        function mlAct = GetActiveChannels(obj)
            % Load to memory if needed
            err = -1;
            if obj.procStream.output.IsEmpty()
                obj.Load();
                err = 0;
            end

            mlAct = obj.GetVar('mlActAuto');
            if ~isempty(mlAct)
                mlAct = mlAct{1};
            end

            % Free memory
            if err==0
                obj.FreeMemory();
            end
        end

        % ----------------------------------------------------------------------------------
        function SetStims_MatInput(obj, s, t, CondNames)
            obj.procStream.SetStims_MatInput(s, t, CondNames);
        end

        % ----------------------------------------------------------------------------------
        function ReloadStim(obj)
            % Update call application GUI using it's generic Update function
            if ~isempty(obj.updateParentGui)
                obj.updateParentGui('DataTreeClass', [obj.iGroup, obj.iSubj, obj.iSess, obj.iRun]);
            end
            if obj.DEBUG
                fprintf('group %d, subject %d, session %d, run %d\n', obj.iGroup, obj.iSubj, obj.iSess, obj.iRun);
            end
            obj.acquired.LoadStim(obj.acquired.GetFilename());
            obj.procStream.CopyStims(obj.acquired)
            pause(.5)
        end

        % ----------------------------------------------------------------------------------
        function s = GetStims(obj, t)
            % Proc stream output
            s_inp = obj.procStream.input.GetStims(t);
            s_out = obj.procStream.output.GetStims(t);

            k_inp_all  = find(s_inp~=0);
            k_out_edit = find(s_out~=0 & s_out~=1);

            % Select only those output stims which exist in the input
            b = ismember(k_out_edit, k_inp_all);

            s = s_inp;
            s(k_out_edit(b)) = s_out(k_out_edit(b));
        end

        % ----------------------------------------------------------------------------------
        function SetConditions(obj, CondNames)
            if nargin==2
                obj.procStream.SetConditions(CondNames);
            end
            obj.CondNames = unique(obj.procStream.GetConditions());
        end

        % ----------------------------------------------------------------------------------
        function CondNames = GetConditions(obj)
            CondNames = obj.procStream.GetConditions();
        end

        % ----------------------------------------------------------------------------------
        function CondNames = GetConditionsActive(obj)
            CondNames = obj.CondNames;
            t = obj.GetTime();
            s = obj.GetStims(t);
            for ii=1:size(s,2)
                if ismember(abs(1), s(:,ii))
                    CondNames{ii} = ['-- ', CondNames{ii}];
                end
            end
        end

        % ----------------------------------------------------------------------------------
        function wls = GetWls(obj)
            wls = obj.acquired.GetWls();
        end

        % ----------------------------------------------------------------------------------
        function bbox = GetSdgBbox(obj)
            if obj.acquired.IsEmpty()
                % No need to load whole of acquired data need only probe here
                obj.acquired.LoadProbe(obj.acquired.GetFilename());
            end
            bbox = obj.acquired.GetSdgBbox();
        end

        % ----------------------------------------------------------------------------------
        function aux = GetAux(obj)
            aux = obj.acquired.GetAux();
        end

        % ----------------------------------------------------------------------------------
        function aux = GetAuxiliary(obj)
            aux = obj.acquired.GetAuxiliary();
        end

        % ----------------------------------------------------------------------------------
        function tIncAuto = GetTincAuto(obj, iBlk)
            if nargin<2
                iBlk = 1;
            end
            tIncAuto = obj.procStream.output.GetTincAuto(iBlk);
        end

        % ----------------------------------------------------------------------------------
        function tIncAutoCh = GetTincAutoCh(obj, iBlk)
            if nargin<2
                iBlk = 1;
            end
            tIncAutoCh = obj.procStream.output.GetTincAutoCh(iBlk);
        end

        % ----------------------------------------------------------------------------------
        function tIncMan = GetTincMan(obj, iBlk)
            if nargin<2
                iBlk = 1;
            end
            tIncMan = obj.procStream.input.GetTincMan(iBlk);
            if isempty(tIncMan)  % If the Tinc array is unitialized TODO find a more sensical place to do this
               obj.InitTincMan();
               tIncMan = obj.procStream.input.GetTincMan(iBlk);
            end
        end

        % ----------------------------------------------------------------------------------
        function SetTincMan(obj, idxs, iBlk, excl_incl)
            if nargin<2
                return
            end
            if nargin<4
                excl_incl = 'exclude';
            end
            tIncMan = obj.procStream.GetTincMan(iBlk);
            if strcmp(excl_incl, 'exclude')
                tIncMan(idxs) = 0;
            elseif strcmp(excl_incl, 'include')
                tIncMan(idxs) = 1;
            end
            obj.procStream.SetTincMan(tIncMan, iBlk);
        end

        % ----------------------------------------------------------------------------------
        function InitTincMan(obj)
            iBlk = 1;  % TODO implement multiple data blocks
            while 1
                t = obj.acquired.GetTime(iBlk);
                if isempty(t)
                    break
                end
                tIncMan = ones(length(t),1);
                obj.procStream.SetTincMan(tIncMan, iBlk);
                iBlk = iBlk+1;
            end
        end
    end        % Public Set/Get methods

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % All other public methods for acquired data
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    methods

        % ----------------------------------------------------------------------------------
        function AddStims(obj, tPts, condition, duration, amp, more)
            if isempty(tPts)
                return;
            end
            if isempty(condition)
                return;
            end
            obj.procStream.AddStims(tPts, condition, duration, amp, more);
        end

        % ----------------------------------------------------------------------------------
        function DeleteStims(obj, tPts, condition)
            if ~exist('tPts','var') || isempty(tPts)
                return;
            end
            if ~exist('condition','var')
                condition = '';
            end
            obj.procStream.DeleteStims(tPts, condition);
        end

        % ----------------------------------------------------------------------------------
        function ToggleStims(obj, tPts, condition)
            if ~exist('tPts','var') || isempty(tPts)
                return;
            end
            if ~exist('condition','var')
                condition = '';
            end
            obj.procStream.ToggleStims(tPts, condition);
        end

        % ----------------------------------------------------------------------------------
        function MoveStims(obj, tPts, condition)
            if ~exist('tPts','var') || isempty(tPts)
                return;
            end
            if ~exist('condition','var')
                condition = '';
            end
            obj.procStream.MoveStims(tPts, condition);
        end

        % ----------------------------------------------------------------------------------
        function AddStimColumn(obj, name, initValue)
            if ~exist('name', 'var')
                return;
            end
            obj.procStream.AddStimColumn(name, initValue);
        end

        % ----------------------------------------------------------------------------------
        function DeleteStimColumn(obj, idx)
            if ~exist('idx', 'var') || idx <= 3
                return;
            end
            obj.procStream.DeleteStimColumn(idx);
        end

        % ----------------------------------------------------------------------------------
        function RenameStimColumn(obj, oldname, newname)
            if ~exist('oldname', 'var') || ~exist('newname', 'var')
                return;
            end
            obj.procStream.RenameStimColumn(oldname, newname);
        end

        % ----------------------------------------------------------------------------------
        function probe = GetProbe(obj)
            probe = obj.acquired.GetProbe();
        end

        % ----------------------------------------------------------------------------------
        function data = GetStimData(obj, icond)
            data = obj.procStream.GetStimData(icond);
        end

        % ----------------------------------------------------------------------------------
        function val = GetStimDataLabels(obj, icond)
            val = obj.procStream.GetStimDataLabels(icond);
        end

        % ----------------------------------------------------------------------------------
        function SetStimTpts(obj, icond, tpts)
            obj.procStream.SetStimTpts(icond, tpts);
        end

        % ----------------------------------------------------------------------------------
        function tpts = GetStimTpts(obj, icond)
            if ~exist('icond','var')
                icond=1;
            end
            tpts = obj.procStream.GetStimTpts(icond);
        end

        % ----------------------------------------------------------------------------------
        function SetStimDuration(obj, icond, duration, tpts)
            obj.procStream.SetStimDuration(icond, duration, tpts);
        end

        % ----------------------------------------------------------------------------------
        function duration = GetStimDuration(obj, icond)
            if ~exist('icond','var')
                icond=1;
            end
            duration = obj.procStream.GetStimDuration(icond);
        end

        % ----------------------------------------------------------------------------------
        function SetStimAmplitudes(obj, icond, amps, tpts)
            obj.procStream.SetStimAmplitudes(icond, amps, tpts);
        end

        % ----------------------------------------------------------------------------------
        function vals = GetStimAmplitudes(obj, icond)
            if ~exist('icond','var')
                icond=1;
            end
            vals = obj.procStream.GetStimAmplitudes(icond);
        end

        % ----------------------------------------------------------------------------------
        function RenameCondition(obj, oldname, newname)
            % Function to rename a condition. Important to remeber that changing the
            % condition involves 2 distinct well defined steps:
            %   a) For the current element change the name of the specified (old)
            %      condition for ONLY for ALL the acquired data elements under the
            %      currElem, be it run, subj, or group . In this step we DO NOT TOUCH
            %      the condition names of the run, subject or group .
            %   b) Rebuild condition names and tables of all the tree nodes group, subjects
            %      and runs same as if you were loading during Homer3 startup from the
            %      acquired data.
            %
            if ~exist('oldname','var') || ~ischar(oldname)
                return;
            end
            if ~exist('newname','var')  || ~ischar(newname)
                return;
            end
            newname = obj.ErrCheckNewCondName(newname);
            if obj.err ~= 0
                return;
            end
            obj.procStream.RenameCondition(oldname, newname);
        end

        % ----------------------------------------------------------------------------------
        function StimReject(obj, t, iBlk)
            obj.procStream.StimReject(t, iBlk);
        end

        % ----------------------------------------------------------------------------------
        function StimInclude(obj, t, iBlk)
            obj.procStream.StimInclude(t, iBlk);
        end

        % ----------------------------------------------------------------------------------
        function vals = GetStimValSettings(obj)
            vals = obj.procStream.input.GetStimValSettings();
        end

        % ----------------------------------------------------------------------------------
        function ExportStim(obj, options)
            global cfg
            if ~exist('options','var')
                options = '';
                if strcmpi(cfg.GetValue('Load Stim from TSV file'), 'no')
                    options = 'regenerate';
                end
            end
            SnirfFile2Tsv(obj.acquired, '', options);
        end

        % ----------------------------------------------------------------------------------
        function fname = DeleteExportStim(obj)
            fname = obj.acquired.GetStimTsvFilename();
            if ispathvalid(fname)
                try
                    fprintf('Delete  %s\n', fname)
                    delete(fname);
                catch
                end
            end
        end

    end

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    methods

        % ----------------------------------------------------------------------------------
        function nbytes = MemoryRequired(obj, option)
            if ~exist('option','var')
                option = 'memory';
            end
            nbytes = obj.procStream.MemoryRequired();
            if strcmp(option, 'file')
                return
            end
            if isempty(obj.acquired)
                return
            end
            nbytes = nbytes + obj.acquired.MemoryRequired();
        end

        % -----------------------------------------------------------------
        function [fn_error, missing_args, prereqs] = CheckProcStreamOrder(obj)
            % Returns index of processing stream function which is missing
            % an argument, and a cell array of the missing arguments.
            % fn_error is 0 if there are no errors.

            missing_args = {};
            fn_error = 0;
            prereqs = '';

            % Processing stream begins with inputs available
            available = obj.procStream.input.GetProcInputs();
            % Inputs which are usually optional or defined elsewhere
            extras = {'iRun' 'iSubj' 'iGroup' 'mlActAuto', 'tIncAuto', 'Aaux', 'rcMap'};
            available = [available, extras];

            % For all fcalls
            for i = 1:length(obj.procStream.fcalls)

                inputs = obj.procStream.fcalls(i).GetInputs();

                % Check that each input is available
                for j = 1:length(inputs)
                    if ~any(strcmp(available, inputs{j}))
                       fn_error = obj.procStream.fcalls(i);
                       missing_args{end+1} = inputs{j}; %#ok<AGROW>
                    end
                end

                if isa(fn_error, 'FuncCallClass')
                    entry = obj.procStream.reg.GetEntryByName(fn_error.name);
                    if isfield(entry.help.sections, 'prerequisites')
                       prereqs_list = splitlines(entry.help.sections.prerequisites.str);
                       for k = 1:length(prereqs_list)
                           if ~isempty(prereqs_list{k})
                               prereqs = [prereqs, sprintf('\n'), strtrim(prereqs_list{k})];
                           end
                       end
                    end
                   return;
                end

                % Add outputs of the function to available list
                outputs = obj.procStream.fcalls(i).GetOutputs();
                for j = 1:length(outputs)
                   available{end + 1} = outputs{j};  %#ok<AGROW>
                end
            end
        end

        % ----------------------------------------------------------------------------------
        function r = ListOutputFilenames(obj, options)
            if ~exist('options','var')
                options = '';
            end
            r = obj.GetOutputFilename(options);
            fprintf('    %s %s\n', obj.path, r);
        end

        % ----------------------------------------------------------------------------------
        function b = HaveOutput(obj)
            b1 = ~obj.procStream.output.IsEmpty();
            fname = obj.procStream.output.SetFilename([obj.path, obj.GetOutputFilename()]);
            b2 = false;
            if ispathvalid(fname)
                r = load(fname);
                b2 = ~r.output.IsEmpty();
            end
            b = b1 || b2;
        end

    end

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % Private methods
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    methods (Access = public)

    end  % Private methods

end


function varargout = DSeg(varargin)
% DSEG MATLAB code for DSeg.fig
%      DSEG, by itself, creates a new DSEG or raises the existing
%      singleton*.
%
%      H = DSEG returns the handle to a new DSEG or the handle to
%      the existing singleton*.
%
%      DSEG('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in DSEG.M with the given input arguments.
%
%      DSEG('Property','Value',...) creates a new DSEG or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before DSeg_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to DSeg_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 DSeg

% Last Modified by GUIDE v2.5 14-Jun-2011 16:56:58

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @DSeg_OpeningFcn, ...
                   'gui_OutputFcn',  @DSeg_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 DSeg is made visible.
function DSeg_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 DSeg (see VARARGIN)

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

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes DSeg wait for user response (see UIRESUME)
% uiwait(handles.figure1);

% --- Outputs from this function are returned to the command line.
function varargout = DSeg_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
varargout{1} = handles.output;

function edit1_Callback(hObject, eventdata, handles)
% hObject    handle to edit1 (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 edit1 as text
%        str2double(get(hObject,'String')) returns contents of edit1 as a double

% --- Executes during object creation, after setting all properties.
function edit1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit1 (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

% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

[filename, pathname] = uigetfile({'*.*'},'Open Directory');
if isequal(filename,0) || isequal(pathname,0)
    return
end

set(handles.edit1,'String',strcat(pathname,filename));

function edit2_Callback(hObject, eventdata, handles)
% hObject    handle to edit2 (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 edit2 as text
%        str2double(get(hObject,'String')) returns contents of edit2 as a double

% --- Executes during object creation, after setting all properties.
function edit2_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit2 (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 edit3_Callback(hObject, eventdata, handles)
% hObject    handle to edit3 (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 edit3 as text
%        str2double(get(hObject,'String')) returns contents of edit3 as a double

% --- Executes during object creation, after setting all properties.
function edit3_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit3 (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 edit4_Callback(hObject, eventdata, handles)
% hObject    handle to edit4 (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 edit4 as text
%        str2double(get(hObject,'String')) returns contents of edit4 as a double

% --- Executes during object creation, after setting all properties.
function edit4_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit4 (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

% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

Im=get(handles.edit1,'String');
if length(Im)>3
flag=str2double(get(handles.edit2,'String'));
open=str2double(get(handles.edit3,'String'));
EdHist=str2double(get(handles.edit4,'String'));

[Segmented, Array]=DS(Im,flag,open,EdHist);
imwrite(Segmented,'Segmented.tif')
set(handles.listbox1,'String',num2str(Array));
end
% --- Executes on selection change in listbox1.
function listbox1_Callback(hObject, eventdata, handles)
% hObject    handle to listbox1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns listbox1 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from listbox1

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

% Hint: listbox 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


%GT Datafile overload


function self = gui_test_result(progress_bar, text_runs, error_listbox, max_number_of_tests)
%gui_test_result contructor.
%  The constructor creates an object of the class gui_test_result with the
%  following parameters:
%    progress_bar: handle of the progess bar.
%    text_runs: handle of the text area, which shows the number of test ran,
%               errors and failures.
%    error_listbox: handle of the listbox, which contains the list of
%                   all errors and failures.
%    max_number_of_tests: the number of tests.
%
%  Class Info
%  ==========
%  The class gui_test_result is inherited from test_result and shows
%  the test results and the progress at the mlUnit gui. Normally an
%  instance of the class is only created by gui_test_runner, but not by the
%  user.
%
%  Example
%  =======
%  A gui_test_result is created in gui_test_runner/gui:
%         result = gui_test_result(handles.gui_progress_bar, ...
%             handles.gui_text_runs, ...
%             handles.gui_error_list, ...
%             0);
%
%  See also TEST_RESULT, GUI_TEST_RESULT, GUI_TEST_RUNNER/GUI.

self.progress_bar = progress_bar;
self.text_runs = text_runs;
self.error_listbox = error_listbox;
self.max_number_of_tests = max_number_of_tests;
result = test_result;
self = class(self, 'gui_test_result', result);
reset_progress_bar(self);
reset_texts(self);


function varargout = delLinks(varargin)
% DELLINKS M-file for delLinks.fig
%      DELLINKS, by itself, creates a new DELLINKS or raises the existing
%      singleton*.
%
%      H = DELLINKS returns the handle to a new DELLINKS or the handle to
%      the existing singleton*.
%
%      DELLINKS('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in DELLINKS.M with the given input arguments.
%
%      DELLINKS('Property','Value',...) creates a new DELLINKS or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before delLinks_OpeningFunction gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to delLinks_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 delLinks

% Last Modified by GUIDE v2.5 26-Oct-2006 13:44:29

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @delLinks_OpeningFcn, ...
                   'gui_OutputFcn',  @delLinks_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin & isstr(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 delLinks is made visible.
function delLinks_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 delLinks (see VARARGIN)

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

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes delLinks wait for user response (see UIRESUME)
% uiwait(handles.figure1);

% --- Outputs from this function are returned to the command line.
function varargout = delLinks_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
varargout{1} = handles.output;

% --- Executes during object creation, after setting all properties.
function EdSelectedSubsystem_CreateFcn(hObject, eventdata, handles)
% hObject    handle to EdSelectedSubsystem (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
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

function EdSelectedSubsystem_Callback(hObject, eventdata, handles)
% hObject    handle to EdSelectedSubsystem (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 EdSelectedSubsystem as text
%        str2double(get(hObject,'String')) returns contents of EdSelectedSubsystem as a double

% --- Executes on button press in PbSelectSubsystem.
function PbSelectSubsystem_Callback(hObject, eventdata, handles)
% hObject    handle to PbSelectSubsystem (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.EdSelectedSubsystem,'String', gcb);

% --- Executes on button press in PbDeleteLinks.
function PbDeleteLinks_Callback(hObject, eventdata, handles)
% hObject    handle to PbDeleteLinks (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

NumDelLinks=0;

if (strcmp(get(handles.EdSelectedSubsystem,'String'),'No Selection')==1)
    errordlg('Select a Subsystem first!','No Subsystem Selected');
    return
else
    answer = questdlg('All links in the selected subsystem will be broken! Continue?',...
        get(handles.EdSelectedSubsystem,'String'),'Yes','No','No');

    if strcmp (answer,'Yes')
        libs={'dummy'};

        while isempty(libs)==0
            libs=find_system(gcb,'LookUnderMasks','all','LinkStatus','resolved');
            libStruct=cell2struct(libs,'libPath',2);
            cntLibPath=size(libStruct);

            for i=1:cntLibPath(1)
                set_param(libStruct(i).libPath,'LinkStatus','none');
                NumDelLinks=NumDelLinks+1;
            end
        end
        warndlg([num2str(NumDelLinks) ,' link(s) broken. Changes take effect after you have saved the model!'],'Links broken');
        return;
    else
        return ;
    end;
end;
%if needed:
%LinkStatus 'resolved' = Library Link active
%LinkStatus 'inactive' = Library Link disabled
%LinkStatus 'none' = Library Link broken


function handle_wrapcallbacktrycatch = ncorr_util_wrapcallbacktrycatch(handle_callback,handle_figure)
% This function is a wrapper that wraps the callback in a try-catch
% statement. If an error is thrown after the figure handle is closed, then
% disregard the error; if not, then rethrow it. The reason for this function
% is that closing a figure always interrupts a function, which can cause it
% to throw an error. Make sure to only throw the error if the figure which
% the function is attached to is still open.
%
% Inputs -----------------------------------------------------------------%
%   handle_callback - function handle;
%   handle_figure - figure handle;
%
% Outputs ----------------------------------------------------------------%
%   handle_wrapcallbacktrycatch - function handle;

    handle_wrapcallbacktrycatch = @wrapcallbacktrycatch;

    function wrapcallbacktrycatch(varargin)
        try
            handle_callback(varargin{:});
        catch err
            if (ishandle(handle_figure))
                rethrow(err);
            end
        end
    end
end


function Value = GetArg(S, Name, Default)

try
    Value = S.(Name);
catch
    error('GetArg: unknown parameter ''%s''.',Name);
end

if isempty(Value)
    if nargin < 3
        error('Parameter ''%s'' must be assigned a value.',Name);
    end
    Value = Default;
end


classdef MivDefaultStyleSheet
    % MivDefaultStyleSheet. Defines the default styles for GUI components.
    %
    %
    %
    %     Licence
    %     -------
    %     Part of the TD MIM Toolkit. https://github.com/tomdoel
    %     Author: Tom Doel, Copyright Tom Doel 2014.  www.tomdoel.com
    %     Distributed under the MIT licence. Please see website for details.
    %

    properties (Constant)
        SelectedBackgroundColour = [1.0 0.694 0.392]
        TextPrimaryColour = [1.0 1.0 1.0]
        BackgroundColour = [0, 0, 0]
        TextSecondaryColour = [1.0 0.694 0.392]
        TextContrastColour = [0, 0.129, 0.278]
        IconHighlightColour = [0.7 0.7 0.7]
        IconSelectedColour = [0.6 0.6 0]
        IconHighlightSelectedColour = [1 1 0]
        Font = 'Helvetica'
    end
end


function varargout = lvd_EditVehiclePointGUI(varargin)
% LVD_EDITVEHICLEPOINTGUI MATLAB code for lvd_EditVehiclePointGUI.fig
%      LVD_EDITVEHICLEPOINTGUI, by itself, creates a new LVD_EDITVEHICLEPOINTGUI or raises the existing
%      singleton*.
%
%      H = LVD_EDITVEHICLEPOINTGUI returns the handle to a new LVD_EDITVEHICLEPOINTGUI or the handle to
%      the existing singleton*.
%
%      LVD_EDITVEHICLEPOINTGUI('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in LVD_EDITVEHICLEPOINTGUI.M with the given input arguments.
%
%      LVD_EDITVEHICLEPOINTGUI('Property','Value',...) creates a new LVD_EDITVEHICLEPOINTGUI or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before lvd_EditVehiclePointGUI_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to lvd_EditVehiclePointGUI_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 lvd_EditVehiclePointGUI

% Last Modified by GUIDE v2.5 12-Jan-2021 17:14:15

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @lvd_EditVehiclePointGUI_OpeningFcn, ...
                   'gui_OutputFcn',  @lvd_EditVehiclePointGUI_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 lvd_EditVehiclePointGUI is made visible.
function lvd_EditVehiclePointGUI_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 lvd_EditVehiclePointGUI (see VARARGIN)

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

    centerUIFigure(hObject);

    point = varargin{1};
    setappdata(hObject, 'point', point);

	populateGUI(handles, point);

    % Update handles structure
    guidata(hObject, handles);

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

function populateGUI(handles, point)
    set(handles.pointNameText,'String',point.getName());

% --- Outputs from this function are returned to the command line.
function varargout = lvd_EditVehiclePointGUI_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
    if(isempty(handles))
        varargout{1} = false;
    else
        point = getappdata(hObject, 'point');

        point.setName(handles.pointNameText.String);

        varargout{1} = true;
        close(handles.lvd_EditVehiclePointGUI);
    end

% --- Executes on button press in saveAndCloseButton.
function saveAndCloseButton_Callback(hObject, eventdata, handles)
% hObject    handle to saveAndCloseButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    errMsg = validateInputs(handles);

    if(isempty(errMsg))
        uiresume(handles.lvd_EditVehiclePointGUI);
    else
        msgbox(errMsg,'Invalid Point Inputs','error');
    end

function errMsg = validateInputs(handles)
    errMsg = {};

    if(isempty(strtrim(handles.pointNameText.String)))
        errMsg = {'Point name must contain more than white space and must not be empty.'};
    end

% --- Executes on button press in cancelButton.
function cancelButton_Callback(hObject, eventdata, handles)
% hObject    handle to cancelButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    close(handles.lvd_EditVehiclePointGUI);

function pointNameText_Callback(hObject, eventdata, handles)
% hObject    handle to pointNameText (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 pointNameText as text
%        str2double(get(hObject,'String')) returns contents of pointNameText as a double

% --- Executes during object creation, after setting all properties.
function pointNameText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to pointNameText 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

% --- Executes on key press with focus on lvd_EditVehiclePointGUI or any of its controls.
function lvd_EditVehiclePointGUI_WindowKeyPressFcn(hObject, eventdata, handles)
% hObject    handle to lvd_EditVehiclePointGUI (see GCBO)
% eventdata  structure with the following fields (see MATLAB.UI.FIGURE)
%	Key: name of the key that was pressed, in lower case
%	Character: character interpretation of the key(s) that was pressed
%	Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed
% handles    structure with handles and user data (see GUIDATA)
    switch(eventdata.Key)
        case 'return'
            saveAndCloseButton_Callback(handles.saveAndCloseButton, [], handles);
        case 'enter'
            saveAndCloseButton_Callback(handles.saveAndCloseButton, [], handles);
        case 'escape'
            close(handles.lvd_EditVehiclePointGUI);
    end


classdef (Abstract) MimStorageClass  < handle

    methods (Abstract)
        [metaData, dataStream] = getStream(obj)
    end
end


function stepfwd(H)
%STEPFWD Step forward one frame of movie in movie player

feval(H.fcns.step_fwd,[],[],H.hfig);


function GUI = sessionGUI_helpMenu(GUI);
% Attach a Help Menu to the session GUI figure.
%
% GUI = sessionGUI_helpMenu(GUI);
%
%
% ras, 07/06.
GUI.menus.help = uimenu('Label', 'Help', 'Separator', 'on');

cb = 'web http://white.stanford.edu/newlm';
uimenu(GUI.menus.help, 'Label', 'mrVista Home / Wiki', ...
       'Separator', 'off', 'Callback', cb);

cb = 'web http://white.stanford.edu/newlm -browser';
uimenu(GUI.menus.help, 'Label', 'mrVista Home / Wiki (external browser)', ...
       'Separator', 'off', 'Callback', cb);

uimenu(GUI.menus.help, 'Label', 'Identify Callback for a Menu Item', ...
        'Separator', 'on', 'Callback', 'helpFindCallback; ');

return


%ReactionProcessTestCase
% Base class for whole cell reaction process test classes. Currently does
% not provide anything beyond the ProcessTestCase class.
%
% Author: Jonathan Karr, jkarr@stanford.edu
% Affiliation: Covert Lab, Department of Bioengineering, Stanford University
% Last updated: 7/13/2010
classdef ReactionProcessTestCase < edu.stanford.covert.cell.sim.ProcessTestCase
    %constructor
    methods
        function this = ReactionProcessTestCase(name)
            this = this@edu.stanford.covert.cell.sim.ProcessTestCase(name);
        end
    end
end


classdef FWModes
    enumeration
        FAT32_ZIP, DISK_IMAGE
    end
end


function [fileInfo] = getFileInfo(fileStr, varargin)
	% Gets file information for subject based on the file path, returns a structure with various information.
	% Biafra Ahanonu
	% started: 2013.11.04 [12:38:42]
	% inputs
		% fileStr - character string
	% options
		% assayList
	% outputs
		%

	[fileInfo] = ciapkg.io.getFileInfo(fileStr,'passArgs', varargin);
end


mex ind2subv.c
mex subv2ind.c
mex normalise.c
mex -c mexutil.c
if ~isunix
  mex repmatC.c mexutil.obj
else
  mex repmatC.c mexutil.o
end


function x = subsasgn( x, S, y )
error( 'Subscripted assignment not allowed for cvx problem objects.' );

% 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.


function varargout = ft_warning(varargin)

% FT_WARNING prints a warning message on screen, depending on the verbosity
% settings of the calling high-level FieldTrip function. This function works
% similar to the standard WARNING function, but also features the "once" mode.
%
% Use as
%   ft_warning(...)
% with arguments similar to fprintf, or
%   ft_warning(msgId, ...)
% with arguments similar to warning.
%
% You can switch of all warning messages using
%   ft_warning off
% or for specific ones using
%   ft_warning off msgId
%
% To switch them back on, you would use
%   ft_warning on
% or for specific ones using
%   ft_warning on msgId
%
% Warning messages are only printed once per timeout period using
%   ft_warning timeout 60
%   ft_warning once
% or for specific ones using
%   ft_warning once msgId
%
% You can see the most recent messages and identifier using
%   ft_warning last
%
% You can query the current on/off/once state for all messages using
%   ft_warning query
%
% See also FT_ERROR, FT_WARNING, FT_NOTICE, FT_INFO, FT_DEBUG, ERROR, WARNING

% Copyright (C) 2012-2017, Robert Oostenveld, J?rn M. Horschig
%
% 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 nargout
  varargout{:} = ft_notification(varargin{:});
elseif isequal(varargin, {'last'})
  % return an answer anyway
  varargout{1} = ft_notification(varargin{:});
else
  ft_notification(varargin{:});
end


% setup_paths() sets up paths for the matlabserver code to include subdirectories, etc.
% This file is sourced by the serverInit() and slaveInit() functions.  You can add your
% own paths here if you like to ensure that they're added to the server and slaves.
%
% The returned variable 'rootpath' is the path of the setup_paths.m file
% (i.e., the matlabserver/ directory) which can be used to reference other
% internal paths by the caller.
function rootpath = setup_paths()
p=which('setup_paths');
i=strfind(p, 'setup_paths.m');

if (isempty(i))
  error('Couldn''t determine path of setup_paths.m');
end

p=p(1:i-1);
addpath(p); % add root path in case cwd changes.

rootpath=p;


function clear(logger)
% Removes all logfiles from the list.  Files that were added using
% their name (i.e. not their fid) are closed.

logger.fidlist = [];
logger.fidlevels = [];
for ii=1:length(logger.filenamefids)
    fclose(logger.filenamefids(ii));
end
logger.filenamelist = {};
logger.filenamefids = [];
logger.filenamelevels = [];

assert(logger.validate())


classdef MimMemoryCacheItem < handle
    % MimMemoryCacheItem. Part of the internal framework of the TD MIM Toolkit.
    %
    %     You should not use this class within your own code. It is intended to
    %     be used internally within the framework of the TD MIM Toolkit.
    %
    %     Used to hold a cached value and metadata in the memory cache.
    %
    %     Licence
    %     -------
    %     Part of the TD MIM Toolkit. https://github.com/tomdoel
    %     Author: Tom Doel, Copyright Tom Doel 2014.  www.tomdoel.com
    %     Distributed under the MIT licence. Please see website for details.
    %

    properties (SetAccess = private)
        Value
        Info
    end

    methods

        function obj = MimMemoryCacheItem(value, info)
            obj.Value = value;
            obj.Info = info;
        end
    end
end


function dtiResetMouseImage(handles)
% Reset callbacks on the image planes in the main window
%
%    dtiResetMouseImage(handles)
%
% When the image is redrawn, matlab resets the callbacks.  So, we reset
% them again
%
% See also:  dtiRefreshFigure
%
% Brian (c) Stanford VISTASOFT Team, 2012

set(handles.x_cut_img,'HitTest','off');
set(handles.x_cut,'ButtonDownFcn','dtiFiberUI(''x_cut_click_Callback'',gcbo,[],guidata(gcbo))');

set(handles.y_cut_img,'HitTest','off');
set(handles.y_cut,'ButtonDownFcn','dtiFiberUI(''y_cut_click_Callback'',gcbo,[],guidata(gcbo))');

set(handles.z_cut_img,'HitTest','off');
set(handles.z_cut,'ButtonDownFcn','dtiFiberUI(''z_cut_click_Callback'',gcbo,[],guidata(gcbo))');

end


classdef MimConnectionCacheMap < CoreBaseClass

    properties
        ConnectionCacheDictionary
    end

    methods
        function obj = MimConnectionCacheMap()
            obj.ConnectionCacheDictionary = containers.Map('KeyType', 'int32', 'ValueType', 'any');
        end

        function clear(obj)
            for connection = obj.ConnectionCacheDictionary.values
                connection{1}.clear();
            end
        end

        function addConnection(obj, connection)
            if ~obj.ConnectionCacheDictionary.isKey(connection.HashCode)
                obj.ConnectionCacheDictionary(connection.HashCode) = MimModelCache();
            end
        end

        function deleteConnection(obj, connection)
            if obj.ConnectionCacheDictionary.isKey(connection.HashCode)
                obj.ConnectionCacheDictionary.remove(connection.HashCode);
            end
        end

        function connections = getAllConnections(obj)
            connections = obj.ConnectionCacheDictionary.values;
        end

        function connectionCache = getConnection(obj, connection)
            if ~obj.ConnectionCacheDictionary.isKey(connection.HashCode)
                obj.ConnectionCacheDictionary(connection.HashCode) = MimConnectionCache();
            end
            connectionCache = obj.ConnectionCacheDictionary(connection.HashCode);
        end
    end
end


%  Copyright (C) 2004 Yokogawa Electric Corporation, All Rights Reserved.
%
%  usage:
%    patient_info = GetMeg160PatientInfoM( fid )
%
%  arguments:
%    fid             : file ID
%
%  return values:
%    patient_info        : structure of patient information.
%                        .patient_id         : patient id
%                        .patient_name       : patient name
%                        .patient_birthday   : patient birthday
%                        .patient_sex        : patient sex
%                        .patient_handed     : patient handed
%
%  confirmation of revision:
%   GetMeg160PatientInfoM( Inf ) will show and return revision of this function.
%


classdef (ConstructOnLoad) CoreEventData < event.EventData
    % CoreEventData. Encapsulate data to be passed when an event occurs.
    %
    %     Use this class when you trigger an event which needs to provide data
    %     to its listeners.
    %
    %     Example
    %     -------
    %
    %     This example triggers a MouseClick event and passes the image coordiates
    %
    %         coords = GetImageCoordinates;
    %         notify(obj, 'MouseClick', CoreEventData(coords));
    %
    %
    %     Licence
    %     -------
    %     Part of CoreMat. https://github.com/tomdoel/coremat
    %     Author: Tom Doel, 2013.  www.tomdoel.com
    %     Distributed under the MIT licence. Please see website for details.
    %

    properties
        Data
    end

    methods
        function obj = CoreEventData(data)
            obj.Data = data;
        end
    end
end


function rts_clearInputBuffer(obj, event)
%UNTITLED Summary of this function goes here
%   Detailed explanation goes here

    flushinput(obj);
end


function configCMatrix()
path = fileparts(mfilename('fullpath'));
addpath(fullfile(path, '..'));
config;

addpath(fullfile(path, 'include'));


function handles = setCurrentSimGraphProperties(hObject, handles)
% setCurrentSimGraphProperties Updates the current similarity graph
% information

handles.currentSimGraphType      = handles.SimGraphType;
handles.currentSimGraphNeighbors = get(handles.edtSimGraphNeighbors, 'String');
handles.currentSimGraphEps       = get(handles.edtSimGraphEps, 'String');
handles.currentSimGraphSigma     = get(handles.edtSimGraphSigma, 'String');

guidata(hObject, handles);


function dep = cfg_vout_gzip_files(job)

% Define virtual outputs for "Gzip Files". File names can either be
% assigned to a cfg_files input or to a evaluated cfg_entry.
%
% 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: cfg_vout_gzip_files.m 6627 2015-12-04 08:20:49Z volkmar $

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

dep            = cfg_dep;
dep.sname      = 'Gzipped Files';
dep.src_output = substruct('()',{':'});
dep.tgt_spec   = cfg_findspec({{'class','cfg_files', 'strtype','e'}});


function sedumi_binary_error()
%Throw an error indicating the sedumi binaries are not available

if exist('OCTAVE_VERSION','builtin'),
    software = 'Octave';
else
    software = 'Matlab';
end

fs = filesep;
mpath = mfilename('fullpath');
temp = strfind( mpath, fs );
mpath = mpath( 1 : temp(end) - 1 );

error( 'SeDuMi:NoBinaries', ...
    [ 'The SeDuMi binaries for your platform are not installed.\n', ...
      'To rectify, run the following commands from the %s command line:\n\n', ...
      '   cd %s\n', ...
      '   install_sedumi\n\n', ...
      'For more information, read %s%sInstall.txt.' ], ...
    software, mpath, mpath, fs );


%SETTYPE Set TYPE datafile field


function hRD = plugin_rd_tx
% Reference design definition

% Call the common reference design definition function
hRD = AnalogDevices.adrv9364z7020.common.plugin_rd('ccbob_cmos','Tx');
AnalogDevices.adrv9364z7020.common.add_io(hRD, 'Tx');


function varargout = prtUiPlot(varargin)
% obj = prtUiPlot(input, arguments, to, plot, ...)
%   obj is a prtUiPlotManager

obj = prtUiManagerPlot;
obj.plot(varargin{:});

if nargout
    varargout = {obj};
else
    varargout = {};
end


%  clears the page
%
%  ::
%
%     document.clearpage();
%
%  Args:
%     none
%
%


%--- help for check_property ---
%
%  INTERNAL FUNCTION
%
%
%    Other functions named check_property
%
%       dsge/check_property    generic/check_property
%


function varargout = HELP2(varargin)
% HELP2 M-file for HELP2.fig
%      HELP2, by itself, creates a new HELP2 or raises the existing
%      singleton*.
%
%      H = HELP2 returns the handle to a new HELP2 or the handle to
%      the existing singleton*.
%
%      HELP2('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in HELP2.M with the given input arguments.
%
%      HELP2('Property','Value',...) creates a new HELP2 or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before HELP2_OpeningFunction gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to HELP2_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 HELP2

% Last Modified by GUIDE v2.5 06-Feb-2008 23:04:44

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @HELP2_OpeningFcn, ...
                   'gui_OutputFcn',  @HELP2_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 HELP2 is made visible.
function HELP2_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 HELP2 (see VARARGIN)

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

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes HELP2 wait for user response (see UIRESUME)
% uiwait(handles.figure1);

% --- Outputs from this function are returned to the command line.
function varargout = HELP2_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
varargout{1} = handles.output;


classdef MimWSDataset < MimModel
    methods (Access = protected)
        function value = run(obj)
            seriesUid = obj.Parameters.seriesUid;
            value = obj.Callback.getMim().CreateDatasetFromUid(seriesUid);
        end
    end
end


classdef (Sealed) MimGuiSingleton < handle
    % MimGuiSingleton. The singleton used by all instances of MimGui
    %
    %     You should not use this class within your own code. It is intended to
    %     be used internally within the TD MIM Toolkit.
    %
    %     MimGuiSingleton ensures there is only a single instance for writing
    %     settings to disk, allowing multiple GUI windows to exist simultaneously.
    %
    %     MimGuiSingleton is a singleton. It cannot be created using the
    %     constructor; instead call MimGuiSingleton.GetGuiSingleton;
    %
    %
    %     Licence
    %     -------
    %     Part of the TD MIM Toolkit. https://github.com/tomdoel
    %     Author: Tom Doel, Copyright Tom Doel 2014.  www.tomdoel.com
    %     Distributed under the MIT licence. Please see website for details.
    %

    properties (Access = private)
        Settings
    end

    methods (Static)
        function gui_singleton = GetGuiSingleton(app_def, reporting)
            persistent GuiSingleton
            if isempty(GuiSingleton) || ~isvalid(GuiSingleton)
                GuiSingleton = MimGuiSingleton(app_def, reporting);
            end
            gui_singleton = GuiSingleton;
        end
    end

    methods
        function settings = GetSettings(obj)
            settings = obj.Settings;
        end
    end

    methods (Access = private)
        function obj = MimGuiSingleton(app_def, reporting)
            obj.Settings = PTKSettings.LoadSettings(app_def, reporting);
        end
    end

end


function shortcutUtils = GetShortcutUtils()
%GETSHORTCUTUTILS Gets an instance of ShortcutUtils.
%
%  SHORTCUTUTILS = GETSHORTCUTUTILS() gets an instance of ShortcutUtils.
%
% Examples:
%
% shortcutUtils = GetShortcutUtils();
% methods(shortcutUtils)
% methodsview(shortcutUtils)

% $Author: rcotton $	$Date: 2010/08/23 14:35:09 $	$Revision: 1.1 $
% Copyright: Health and Safety Laboratory 2010

CheckForJVM();
shortcutUtils = com.mathworks.mlwidgets.shortcuts.ShortcutUtils;

end


mex tamEStepInnerMex.c 3rd-party/util.c;
cd utils;
mex termCountsToWordListMex.c;
cd ..;
cd 3rd-party/fastfit
install_fastfit;
cd ../lightspeed
install_lightspeed;
cd ../..


function parser = m2tInputParser()
%MATLAB2TIKZINPUTPARSER   Input parsing for matlab2tikz..
%   This implementation exists because Octave is lacking one.

%   Copyright (c) 2008--2014 Nico Schlömer
%   All rights reserved.
%
%   Redistribution and use in source and binary forms, with or without
%   modification, are permitted provided that the following conditions are
%   met:
%
%       * Redistributions of source code must retain the above copyright
%         notice, this list of conditions and the following disclaimer.
%       * Redistributions in binary form must reproduce the above copyright
%         notice, this list of conditions and the following disclaimer in
%         the documentation and/or other materials provided with the distribution
%
%   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
%   AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
%   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
%   ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
%   LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
%   CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
%   SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
%   INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
%   CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
%   ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
%   POSSIBILITY OF SUCH DAMAGE.
% =========================================================================
  % Initialize the structure.
  parser = struct ();
  % Public Properties
  parser.Results = {};
  % Enabel/disable parameters case sensitivity.
  parser.CaseSensitive = false;
  % Keep parameters not defined by the constructor.
  parser.KeepUnmatched = false;
  % Enable/disable warning for parameters not defined by the constructor.
  parser.WarnUnmatched = true;
  % Enable/disable passing arguments in a structure.
  parser.StructExpand = true;
  % Names of parameters defined in input parser constructor.
  parser.Parameters = {};
  % Names of parameters not defined in the constructor.
  parser.Unmatched = struct ();
  % Names of parameters using default values.
  parser.UsingDefaults = {};
  % Names of deprecated parameters and their alternatives
  parser.DeprecatedParameters = struct();

  % Handles for functions that act on the object.
  parser.addRequired    = @addRequired;
  parser.addOptional    = @addOptional;
  parser.addParamValue  = @addParamValue;
  parser.deprecateParam = @deprecateParam;
  parser.parse          = @parse;

  % Initialize the parser plan
  parser.plan = {};
end
% =========================================================================
function p = parser_plan (q, arg_type, name, default, validator)
  p = q;
  plan = p.plan;
  if (isempty (plan))
    plan = struct ();
    n = 1;
  else
    n = numel (plan) + 1;
  end
  plan(n).type      = arg_type;
  plan(n).name      = name;
  plan(n).default   = default;
  plan(n).validator = validator;
  p.plan = plan;
end
% =========================================================================
function p = addRequired (p, name, validator)
  p = parser_plan (p, 'required', name, [], validator);
end
% =========================================================================
function p = addOptional (p, name, default, validator)
  p = parser_plan (p, 'optional', name, default, validator);
end
% =========================================================================
function p = addParamValue (p, name, default, validator)
  p = parser_plan (p, 'paramvalue', name, default, validator);
end
% =========================================================================
function p = deprecateParam (p, name, alternatives)
  if isempty(alternatives)
      alternatives = {};
  elseif ischar(alternatives)
      alternatives = {alternatives}; % make cellstr
  elseif ~iscellstr(alternatives)
      error('m2tInputParser:BadAlternatives',...
            'Alternatives for a deprecated parameter must be a char or cellstr');
  end
  p.DeprecatedParameters.(name) = alternatives;
end
% =========================================================================
function p = parse (p, varargin)
  plan = p.plan;
  results = p.Results;
  using_defaults = {};
  if (p.CaseSensitive)
    name_cmp = @strcmp;
  else
    name_cmp = @strcmpi;
  end
  if (p.StructExpand)
    k = find (cellfun (@isstruct, varargin));
    for m = numel(k):-1:1
      n = k(m);
      s = varargin{n};
      c = [fieldnames(s).'; struct2cell(s).'];
      c = c(:).';
      if (n > 1 && n < numel (varargin))
        varargin = horzcat (varargin(1:n-1), c, varargin(n+1:end));
      elseif (numel (varargin) == 1)
        varargin = c;
      elseif (n == 1);
        varargin = horzcat (c, varargin(n+1:end));
      else % n == numel (varargin)
        varargin = horzcat (varargin(1:n-1), c);
      end
    end
  end
  if (isempty (results))
    results = struct ();
  end
  type = {plan.type};
  n = find( strcmp( type, 'paramvalue' ) );
  m = setdiff (1:numel( plan ), n );
  plan = plan ([n,m]);
  for n = 1 : numel (plan)
    found = false;
    results.(plan(n).name) = plan(n).default;
    if (~ isempty (varargin))
      switch plan(n).type
      case 'required'
        found = true;
        if (strcmpi (varargin{1}, plan(n).name))
          varargin(1) = [];
        end
        value = varargin{1};
        varargin(1) = [];
      case 'optional'
        m = find (cellfun (@ischar, varargin));
        k = find (name_cmp (plan(n).name, varargin(m)));
        if (isempty (k) && validate_arg (plan(n).validator, varargin{1}))
          found = true;
          value = varargin{1};
          varargin(1) = [];
        elseif (~ isempty (k))
          m = m(k);
          found = true;
          value = varargin{max(m)+1};
          varargin(union(m,m+1)) = [];
        end
      case 'paramvalue'
        m = find( cellfun (@ischar, varargin) );
        k = find (name_cmp (plan(n).name, varargin(m)));
        if (~ isempty (k))
          found = true;
          m = m(k);
          value = varargin{max(m)+1};
          varargin(union(m,m+1)) = [];
        end
      otherwise
        error( sprintf ('%s:parse', mfilename), ...
               'parse (%s): Invalid argument type.', mfilename ...
             )
      end
    end
    if (found)
      if (validate_arg (plan(n).validator, value))
        results.(plan(n).name) = value;
      else
        error( sprintf ('%s:invalidinput', mfilename), ...
               '%s: Input argument ''%s'' has invalid value.\n', mfilename, plan(n).name ...
             );
      end
      p.Parameters = union (p.Parameters, {plan(n).name});
    elseif (strcmp (plan(n).type, 'required'))
      error( sprintf ('%s:missinginput', mfilename), ...
             '%s: input ''%s'' is missing.\n', mfilename, plan(n).name ...
           );
    else
      using_defaults = union (using_defaults, {plan(n).name});
    end
  end

  if ~isempty(varargin)
    % Include properties that do not match specified properties
      for n = 1:2:numel(varargin)
        if ischar(varargin{n})
          if p.KeepUnmatched
            results.(varargin{n}) = varargin{n+1};
          end
          if p.WarnUnmatched
            warning(sprintf('%s:unmatchedArgument',mfilename), ...
                    'Ignoring unknown argument "%s"', varargin{n});
          end
          p.Unmatched.(varargin{n}) = varargin{n+1};
        else
          error (sprintf ('%s:invalidinput', mfilename), ...
                 '%s: invalid input', mfilename)
        end
      end
  end

  % Store the results of the parsing
  p.Results = results;
  p.UsingDefaults = using_defaults;

  warnForDeprecatedParameters(p);
end
% =========================================================================
function result = validate_arg (validator, arg)
  try
    result = validator (arg);
  catch %#ok
    result = false;
  end
end
% =========================================================================
function warnForDeprecatedParameters(p)
  usedDeprecatedParameters = intersect(p.Parameters, fieldnames(p.DeprecatedParameters));

  for iParam = 1:numel(usedDeprecatedParameters)
      oldParameter = usedDeprecatedParameters{iParam};
      alternatives = p.DeprecatedParameters.(oldParameter);

      switch numel(alternatives)
          case 0
              replacements = '';
          case 1
              replacements = ['''' alternatives{1} ''''];
          otherwise
              replacements = deblank(sprintf('''%s'' and ',alternatives{:}));
              replacements = regexprep(replacements,' and$','');
      end
      if ~isempty(replacements)
          replacements = sprintf('From now on, please use %s to control the output.\n',replacements);
      end

      message = ['\n===============================================================================\n', ...
                  'You are using the deprecated parameter ''%s''.\n', ...
                  '%s', ...
                  '==============================================================================='];
      warning('matlab2tikz:deprecatedParameter', ...
                message, oldParameter, replacements);

  end
end


cur_dir = pwd;
cd(fileparts(mfilename('fullpath')));

try
    fprintf('Downloading model_ResNet-101L...\n');
    urlwrite('https://onedrive.live.com/download?resid=F371D9563727B96F!91963&authkey=!AM-EuzuUJelv9Po', ...
        'models_ResNet-101L.zip');

    fprintf('Unzipping...\n');
    unzip('models_ResNet-101L.zip', '..');

    fprintf('Done.\n');
    delete('models_ResNet-101L.zip');
catch
    fprintf('Error in downloading, please try links in README.md https://github.com/daijifeng001/R-FCN');
end

cd(cur_dir);


function str = showdetail(item)

% function str = showdetail(item)
% Display details for a cfg_choice and all of its options.
%
% 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: showdetail.m 4867 2012-08-30 13:04:51Z volkmar $

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

str = showdetail(item.cfg_item);
str{end+1} = 'Set the options listed as a struct:';
% Display detailed help for each cfg_choice value item
tags = tagnames(item, true);
for k = 1:numel(tags)
    str{end+1} = sprintf('.%s', tags{k});
end;


classdef MimScript < handle
    % MimScript. Base class for an API script used by the Pulmonary Toolkit.
    %
    %     MimScript are classes you create to run routines using the
    %     Pulmonary Toolkit API. Whereas Plugins execute for a single
    %     dataset and produce a deterministic result, Scripts can load and
    %     operate over multiple datasets. Unike Gui Plugins, Scripts do not
    %     access the user interface, so they can be run from the command
    %     window using the API's RunScript method.
    %
    %
    %     Licence
    %     -------
    %     Part of the TD MIM Toolkit. https://github.com/tomdoel
    %     Author: Tom Doel, Copyright Tom Doel 2014.  www.tomdoel.com
    %     Distributed under the MIT licence. Please see website for details.
    %

    properties (Abstract = true)

        % This specifies the version of Script interface implemented by this script
        InterfaceVersion

        % A version number for this script implementation
        Version

        % Set to an apropriate value for grouping related scripts
        Category
    end

    methods (Abstract, Static)

        % Called when the user has clicked the button for this gui plugin.
        % Implement this method with the code you with to run.
        output = RunScript(ptk_obj, parameters)
    end
end