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

% Last Modified by GUIDE v2.5 25-Apr-2014 11:25:51

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

handles.fSelect = 1;
movegui('center'); % Moves GUI to center of screen

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

% Update handles structure
guidata(hObject, handles);

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

% --- Outputs from this function are returned to the command line.
function varargout = Data_Analyzer_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 on button press in loadButton.
function loadButton_Callback(hObject, eventdata, handles)
% hObject    handle to loadButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

evalin('base','clear all');
uiopen('load');

if exist('Seconds')
assignin('base', 'Seconds', Seconds);
assignin('base', 'Throttle', Throttle);
assignin('base', 'RPM', RPM);

if exist('gramsMeas')
assignin('base', 'gramsMeas', gramsMeas);
end

end

% --- Executes on selection change in analysisType.
function analysisType_Callback(hObject, eventdata, handles)
% hObject    handle to analysisType (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 analysisType contents as cell array
%        contents{get(hObject,'Value')} returns selected item from analysisType

handles.fSelect = get(hObject,'Value');

guidata(hObject,handles);

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

% Hint: popupmenu 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 bedit_Callback(hObject, eventdata, handles)
% hObject    handle to bedit (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 bedit as text
%        str2double(get(hObject,'String')) returns contents of bedit as a double

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

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

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

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

% --- Executes during object creation, after setting all properties.
function inputValues_CreateFcn(hObject, eventdata, handles)
% hObject    handle to inputValues (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 runButton.
function runButton_Callback(hObject, eventdata, handles)
% hObject    handle to runButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

Seconds = evalin('base', 'Seconds');
Throttle = evalin('base', 'Throttle');
RPM = evalin('base', 'RPM');
existCheck = 'exist(''gramsMeas'',''var'')'; % String to evaluate from context of base workspace
if evalin('base',existCheck)
gramsMeas = evalin('base', 'gramsMeas');
end

% Check to see if the user inputs low/high cutoffs:
inputCheck = get(handles.lowCutoff, 'String');

% If the user doesn't input anything:
if isempty(inputCheck)

    LowCutoff = min(Throttle);
    HighCutoff = max(Throttle);

% Or, if they manually input the low/high cutoffs:
else
    LowCutoff = str2num(get(handles.lowCutoff, 'String'));
    HighCutoff = str2num(get(handles.highCutoff, 'String'));
end

b = str2num(get(handles.bedit, 'String')); % assumed inches
h = str2num(get(handles.hedit, 'String')); % assumed inches
L = str2num(get(handles.Ledit, 'String')); % assumed inches, converted within function
switch handles.fSelect % Get Tag of selected object
    case 1

        calculate_CR_B(Seconds, Throttle, RPM, LowCutoff, HighCutoff);

    case 2

        calculate_CR_B(Seconds, Throttle, RPM, LowCutoff, HighCutoff);
        calculate_CT(Seconds, Throttle, RPM, b, h, gramsMeas, LowCutoff, HighCutoff);

    case 3

        calculate_CR_B(Seconds, Throttle, RPM, LowCutoff, HighCutoff);
        calculate_CQ(Seconds, Throttle, RPM, L, gramsMeas, LowCutoff, HighCutoff);

    case 4

        calculate_TC(Seconds, Throttle, RPM);
end

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

github-repos/MATLAB/dch33-Quad-Sim/Quad-Sim-961bc69d4939c8d0661eeb9820de668994262f65/Quadcopter Dynamic Modeling and Simulation/Data Acquisition & Analysis/MATLAB Data Analysis/Data_Analyzer.m


function savefigs(imageResultRepository, imageFileType)
% This function allows you to quickly save all currently open figures with
% a custom filename for each in multiple formats.  To use the function
% simply call savefigs with no arguments, then follow the prompts
%
% Upon execution this function will one-by-one bring each currently open
% figure to the foreground.  Then it will supply a text prompt in the main
% console window asking you for a filename.  It will save that figure to
% that filename in the .fig, .emf, .png, and .eps formats.
%
% The formats that it saves in can be changed by commenting out or adding
% lines below.
%
% Copyright 2010 Matthew Guidry
% matt.guidry ATT gmail DOTT com  (Email reformatted for anti-spam)

mkdir(imageResultRepository); % ensure that the repository exist

hfigs = get(0, 'children');                          %Get list of figures

for m = 1:length(hfigs)
    figure(hfigs(m))                                %Bring Figure to foreground
    % filename = input('Filename? (0 to skip)\n', 's')%Prompt user
    filename = num2str(hfigs(m));
    filename = strcat(imageResultRepository, '\', filename);

    if strcmp(filename, '0')                        %Skip figure when user types 0
        continue
    else
        saveas(hfigs(m), [filename imageFileType]);
        %saveas(hfigs(m), [filename '.fig']) %Matlab .FIG file
        %saveas(hfigs(m), [filename '.emf']) %Windows Enhanced Meta-File (best for powerpoints)
        %saveas(hfigs(m), [filename '.png']) %Standard PNG graphics file (best for web)
        %eval(['print -depsc2 ' filename])   %Enhanced Postscript (Level 2 color) (Best for LaTeX documents)
    end
end


function [tKuka,flag]=connectToKuka( jPos)
% Copy right: Mohammad SAFEEA
% 16th-Oct-2017

cDir = pwd;
cDir=getTheKSTDirectory(cDir);
addpath(cDir);

warning('off');
ip='172.31.1.147'; % The IP of the controller
% start a connection with the server
tKuka=net_establishConnection( ip );

if ~exist('tKuka','var') || isempty(tKuka)
  warning('Connection could not be establised, script aborted');
  flag=false;
  return;
end
 % Move robot to home position
      setBlueOff(tKuka); % turn Off blue light

      relVel=0.15;
      movePTPJointSpace( tKuka , jPos, relVel); % move to initial configuration

       flag=true;
end


function s = convert(tree,uid,varargin)
% XMLTREE/CONVERT Convert an XML tree into a structure
%
% tree     - XMLTree object
% uid      - uid of the root of the subtree, if provided.
%            Default is root
% s        - converted structure
%__________________________________________________________________________
%
% Convert an XMLTree into a structure, when possible.
% When several identical tags are present, a cell array is used.
% The root tag is not saved in the structure.
% If provided, only the structure corresponding to the subtree defined
% by the uid UID is returned.
%
% Example:
% xml = 'field1<c>field2</c>field3';
% tree = convert(xmltree(xml));
% <=> tree = struct('b',{{'field1', 'field3'}},'c','field2')
%__________________________________________________________________________
% Copyright (C) 2002-2019  https://www.artefact.tk/

% Guillaume Flandin
% $Id: convert.m 7623 2019-06-26 09:34:46Z guillaume $

% Get the root uid of the output structure
if nargin == 1 || isempty(uid)
    % Get the root uid of the XML tree
    uid = root(tree);
end

% Get optional parameters
sub_options({'attributes',false,'str2num',false});
if nargin > 2
    sub_options(varargin);
end

% Build the output structure
s = struct();
s = sub_convert(tree,s,uid,{}); % {get(tree,root_uid,'name')}

%==========================================================================
function s = sub_convert(tree,s,uid,arg)
    type = get(tree,uid,'type');
    switch type
        case 'element'
            child = children(tree,uid);
            l = {};
            ll = {};
            for i=1:length(child)
                if isfield(tree,child(i),'name')
                    ll = [ll, get(tree,child(i),'name')];
                end
            end
            for i=1:length(child)
                if isfield(tree,child(i),'name')
                    name = get(tree,child(i),'name');
                    nboccur = sum(ismember(l,name));
                    nboccur2 = sum(ismember(ll,name));
                    l = [l, name];
                    if nboccur || nboccur2 > 1
                        arg2 = [arg, name, {{nboccur+1}}];
                    else
                        arg2 = [arg, name];
                    end
                else
                    arg2 = arg;
                end
                s = sub_convert(tree,s,child(i),arg2);
            end
            if isempty(child)
                s = sub_setfield(s,arg{:},'');
            end
            if sub_options('attributes')
                attrb = attributes(tree,'get',uid);
                if ~isempty(attrb)
                    arg2 = [arg, 'attributes'];
                    if ~isstruct(attrb), attrb = [attrb{:}]; end
                    try
                        % Saving attributes will work with <c>b</c>
                        % but not with b
                        s = sub_setfield(s,arg2{:},...
                            cell2struct({attrb.val},{attrb.key},2));
                    end
                end
            end
        case 'chardata'
            s = sub_setfield(s,arg{:},get(tree,uid,'value'));
            if sub_options('str2num')
                % Convert strings into their numerical equivalent when possible
                % e.g. string '3.14159' becomes double scalar 3.14159
                v = get(tree,uid,'value');
                cv = str2num(v);
                if isempty(cv)
                    s = sub_setfield(s,arg{:},v);
                else
                    s = sub_setfield(s,arg{:},cv);
                end
            end
        case 'cdata'
            s = sub_setfield(s,arg{:},get(tree,uid,'value'));
        case 'pi'
            % Processing instructions are evaluated if possible
            app = get(tree,uid,'target');
            switch app
                case {'matlab',''}
                    s = sub_setfield(s,arg{:},eval(get(tree,uid,'value')));
                case 'unix'
                    s = sub_setfield(s,arg{:},unix(get(tree,uid,'value')));
                case 'dos'
                    s = sub_setfield(s,arg{:},dos(get(tree,uid,'value')));
                case 'system'
                    s = sub_setfield(s,arg{:},system(get(tree,uid,'value')));
                otherwise
                    try
                        s = sub_setfield(s,arg{:},feval(app,get(tree,uid,'value')));
                    catch
                        warning('[XMLTree] Unknown target application');
                    end
            end
        case 'comment'
            % Comments are ignored
        otherwise
            warning(sprintf('Type %s unknown : not saved',get(tree,uid,'type')));
    end

%==========================================================================
function s = sub_setfield(s,varargin)
% Same as setfield but using '{}' rather than '()'

subs = varargin(1:end-1);
types = repmat({'{}'},1,numel(subs));
types(cellfun(@ischar,subs)) = {'.'};
s = builtin('subsasgn', s, struct('type',types,'subs',subs), varargin{end});

%==========================================================================
function o = sub_options(opt)
persistent opts
if isempty(opts), opts = struct; end
if iscell(opt)
    for i=1:2:numel(opt)
        opts.(lower(opt{i})) = opt{i+1};
    end
else
    o = opts.(lower(opt));
end


% sets directories

dataset = 'labelme';
alg = 'occw';

switch(lower(dataset))

    case 'bsds'
        bsdsdir = '~dhoiem/data/datasets/BSDS300/';
        imdir = fullfile(bsdsdir, 'images/all/');

        basedir = '~/data/occlusion/bsds';
        gtdir = fullfile(basedir, 'gt');
        occdir = fullfile(basedir, 'occlusion');
        pbdir = fullfile(basedir, 'pb');
        pb2dir = fullfile(basedir, 'pb2');
        traindir = fullfile(basedir, 'train');

    case 'labelme'
        basedir = '~/data/occlusion/labelme';
        imdir_train = fullfile(basedir, 'train/Images');
        imdir_test = fullfile(basedir, 'test/Images');
        gtdir = fullfile(basedir, 'labels2');
        occdir = fullfile(basedir, 'occlusion');
        pbdir = fullfile(basedir, 'pb');
        pb2dir = fullfile(basedir, 'pb2');
        traindir = fullfile(basedir, 'train');

    otherwise
        error('invalid dataset')
end


%kkbitset 'Set All Bits to One'
% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros kbitset.pane file
%
% Parameters:
% InputFile: i 'Input ', required: 'Input data object'
% OutputFile: o 'Output', required: 'Resulting output data object'
%
% Example: o = kkbitset(i, {'i','';'o',''})
%
% Khoros helpfile follows below:
%
%  PROGRAM
% kbitset - Set All Bits to One
%
%  DESCRIPTION
% The "SET" operator sets all bits to one for each data
% point in the input data object, \fBInput".
%
% Executing "SET" runs the program \fIkarith1\fP with the -set flag.
%
%
%  "\fBData Type"" 5
% .cI $DATAMANIP/repos/shared/man/sections/value_type_1input
%
%  "\fBMap Data"" 5
% .cI $DATAMANIP/repos/shared/man/sections/map_1input
%
%  "\fBValidity Mask"" 5
% .cI $DATAMANIP/repos/shared/man/sections/mask_1input
%
%  "\fBExplicit Location and Time Data"" 5
% .cI $DATAMANIP/repos/shared/man/sections/loc_and_time_1input
%
%  "\fBFailure Modes""
% .cI $DATAMANIP/repos/shared/man/sections/fail_1input
%
%
%
%  EXAMPLES
%
%  "SEE ALSO"
% DATAMANIP::karith1
%
%  RESTRICTIONS
% Operations on complex data are not supported at this time.
% For the bitwise operations (not, set, clear), if the source data is
% floating point, it is cast to long integer before processing.  This
% may result in loss of precision.
%
%  REFERENCES
%
%  COPYRIGHT
% Copyright (C) 1993 - 1997, Khoral Research, Inc. ("KRI")  All rights reserved.
%

function varargout = kkbitset(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,..] = kkbitset(Inputs,arglist).');
end
if size(arglist,2)~=2
  error('arglist must be of form {''ParameterTag1'',value1;''ParameterTag2'',value2}')
 end
narglist={'i', '__input';'o', '__output'};
maxval={0,0};
minval={0,0};
istoggle=[0,0];
was_set=istoggle * 0;
paramtype={'InputFile','OutputFile'};
% identify the input arrays and assign them to the arguments as stated by the user
if ~iscell(Inputs)
Inputs = {Inputs};
end
NumReqOutputs=1; 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(1,1);
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
[varargout{:}]=callKhoros([w 'karith1"  -set'],Inputs,narglist);


erplabver = '9.10';                  % current erplab version
erplabrel = '16-Feb-2023';             % DOB
erplabdeveloper = 'Simmons&Zhang';
%ColorB = [170 180 195]/255;          % old background color (until version 3)
%ColorB = [0.9216 0.8353 0.6078];     % background color for version 4
%ColorB = [0.7020 0.7647 0.8392];     % background color since version 4.0.0.3
%ColorB = [0.9804 0.8118 0.5529];     % background color since version 4.0.0.11
ColorB       = [0.7020 0.77 0.85];     % background color since version 4.0.0.12
ColorF       = [0.02 0.02 0.02];       % foreground color since version 4.0.2.0
errorColorF  = [0 0 0];                % foreground color for error window
errorColorB  = [0.6824 1 0.6353];      % background color for error window
fontunitsGUI = 'pixels';

set(0,'Units','pixels')
thisscreen = get(0, 'ScreenSize');
if thisscreen(4)>=1440
    fontsizeGUI = 12; % high resolution display (eg Retina)
else
    fontsizeGUI = 11;
end


function settings = meshSettingsList(msh)
% Load a list of settings from the MeshSettings.mat file for a given mesh,
% updating any GUI listboxes as well.
%
% USAGE:
%	settings = meshSettingsList([msh=cur mesh of cur view]);
%
%
% ras, 07/07.
if notDefined('msh')
	msh = viewGet(getSelectedVolume, 'CurMesh');
end

% if there is no mesh, then clear the settings and return
if isempty(msh)
    settings = [];
    return
end

meshDir = fileparts(msh.path);
settingsFile = fullfile(meshDir, 'MeshSettings.mat');

if ~exist(settingsFile, 'file')
	fprintf('[%s]: No Settings File Found: %s.\n', mfilename, settingsFile);
	settings = [];
	return
end

load(settingsFile, 'settings');

%% check for GUI listboxes; update them if found
allH = findobj('Tag', 'MeshSettingsList');
for h = allH(:)'
	if isequal( get(h, 'Type'), 'uicontrol' )
		%% uicontrol listbox: set list name
		% make sure the selected entry (value) is within the range
		% of available settings
		n = get(h, 'Value');
		n = min(n, length(settings)); %#ok<*NODEF>

		set(h, 'String', {settings.name}, 'Value', n);

	elseif isequal( get(h, 'Type'), 'uimenu' )
		%% uimenu (gray menu)
		vw = getSelectedGray;

		% if several of these menus are found, find the one belonging to
		% the current view
		if length(h) > 1
			h = vw.ui.menus.meshSettings;
		end

		% if previous submenus exist, get rid of 'em
		a = get(h, 'Children');
		delete(a(1:end-4));

		% add a series of menu items to retrieve each stored setting
		for ii = 1:length(settings)
			if ii==1, sep = 'on';	else sep = 'off'; 	end

			cb = sprintf('meshRetrieveSettings(viewGet(%s, ''CurMesh''), ''%s''); ', ...
						 vw.name, settings(ii).name);

			uimenu(h, 'Label', settings(ii).name, 'Separator', sep, ...
				   'Callback', cb);
		end
	end
end

return


function doseProfileFigure(command, varargin)
%"doseProfileFigure"
%   Given a start point and end point (startPt, endPt) as [x,y,z]
%   coordinates, create a figure containing a plot doses along the line
%   connecting startPt to endPt.  This figure has controls to activate
%   plots of any or all existing CT scans or doses along the same line, but
%   defaults to the dose passed in initialDoseV and initialScanV.
%
%JRA 1/11/05
%AI  80/04/16  Added scrolling/pagination to handle large number of scans and dose distributions.
%Usage:
%   function doseProfileFigure('init', initialDoseV, initialScanV);
%   function doseProfileFigure('new_points', startPt, endPt);
%   function doseProfileFigure('refresh');
%
% 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/>.

global planC
global stateS
indexS = planC{end};
%persistent drawing;

initialDoseV = [];
initialScanV = [];

if isnumeric(command) && length(command) == 3
    startPt = command;
    endPt = varargin{1};
    command = 'init';
elseif ischar(command) && strcmpi(command, 'init')
    startPt = [];
    endPt = [];
    if nargin > 2
        initialDoseV = varargin{1};
        initialScanV = varargin{2};
    end
elseif ischar(command)
else
    error('Invalid call to doseProfileFigure. Help doseProfileFigure for details.');
end

switch upper(command)
    case 'INIT'
        stateS.doseDiffScale = 'Abs';
        drawing = 0;
        %oldFigs = findobj('tag', 'CERR_DoseLineProfile');
        if isfield(stateS.handle,'doseProfileFigure') && ...
                ~isempty(ishandle(stateS.handle.doseProfileFigure)) && ...
                ishandle(stateS.handle.doseProfileFigure)
            delete(stateS.handle.doseProfileFigure);
        end

        units = 'pixels';
        screenSize = get(0,'ScreenSize');
        % APA: Commented
        % w = 500; h = 500;
        % APA: Commented
        w = 510; h = 650;

        %Initial size of figure in pixels. Figure scales fairly well.
        hFig = figure('name', 'Dose Line Profile', 'units', units, 'position',[(screenSize(3)-w) 35 w h], 'MenuBar', 'none', 'NumberTitle', 'off', 'resize', 'off', 'Tag', 'CERR_DoseLineProfile', 'DeleteFcn', 'doseProfileFigure(''CLOSE'')');
        stateS.handle.doseProfileFigure = hFig;

        nDoses = length(planC{indexS.dose});
        nScans = length(planC{indexS.scan});

        %nScans = min(nScans,20); % 20 scans max allowed. Add pagination in future.

        %Draw frames.
        yFrameSize = 110;
        yStart = 100;
        hDoseFrame = uipanel(hFig, 'units', units, 'position', [10 10 235 yFrameSize]);
        hScanFrame = uipanel(hFig, 'units', units, 'position', [255 10 235 yFrameSize]);
        uicontrol(hFig, 'style', 'text', 'units', units, 'position', [10 yFrameSize-10 50 20], 'string', 'Doses', 'fontweight', 'bold');
        uicontrol(hFig, 'style', 'text', 'units', units, 'position', [255 yFrameSize-10 50 20], 'string', 'Scans', 'fontweight', 'bold');

        %AI: Changed
        %Create dose & scan uicontrols.
        doseUI = uitable(hFig,'RowName',[],'ColumnName',[],'Position',[20 20 215 80],'visible','off','Tag','doseUI');
        scanUI = uitable(hFig,'RowName',[],'ColumnName',[],'Position',[265 20 215 80],'visible','off','tag','scanUI');

        %Get dose list
        colors = stateS.optS.colorOrder;
        outString = cell(nDoses+1,1);
        outString{1} = 'Pick Reference Dose';
        chkvaldoseC = cell(nDoses,1);
        chkvaldoseC(:) = {false};
        doseStringC = cell(nDoses,1);
        colorDose3M = zeros(nDoses,3);
        for i=1:nDoses
            if ismember(i, initialDoseV)
                chkvaldoseC{i} = true;
            else
                chkvaldoseC{i} = false;
            end
            outString{i+1} = planC{indexS.dose}(i).fractionGroupID;
            colorDose3M(i,:) = getColor(i, colors, 'loop');
            if ~isLocal(planC{indexS.dose}(i).doseArray)
                doseStringC{i} = [num2str(i) '. ' planC{indexS.dose}(i).fractionGroupID,'(R)'];
            else
                doseStringC{i} = [num2str(i) '. ' planC{indexS.dose}(i).fractionGroupID];
            end
        end

        %Get scan list
        chkvalscanC = cell(nScans,1);
        chkvalscanC(:) = {false};
        scanStringC = cell(nScans,1);
        colorScan3M = zeros(nDoses,3);
        for i=1:nScans
            if ismember(i, initialScanV);
                chkvalscanC{i} = true;
            else
                chkvalscanC{i} = false;
            end

            colorScan3M(i,:) = getColor(i+nDoses, colors, 'loop');
            if ~isLocal(planC{indexS.scan}(i).scanArray)
                scanStringC{i} = [num2str(i) '. ' planC{indexS.scan}(i).scanType,'(R)'];
            else
                scanStringC{i} = [num2str(i) '. ' planC{indexS.scan}(i).scanType];
            end
        end

        %Display dose uicontrols.
        doseDataC = cat(2,chkvaldoseC,doseStringC);
        set(doseUI, 'data', doseDataC, 'visible', 'on','BackgroundColor',colorDose3M,'cellSelectionCallback',@objCheck);

        %Display scan uicontrols.
        scanDataC = cat(2,chkvalscanC,scanStringC);
        set(scanUI, 'data', scanDataC,'visible', 'on','BackgroundColor',colorScan3M,'cellSelectionCallback',@objCheck);

        %AI: End changed

        %Store UI handles and other info for later use.
        ud.doseUI = doseUI;
        ud.baseDose = [];
        ud.scanUI = scanUI;
        ud.nDoses = nDoses;
        ud.nScans = nScans;
        ud.startPt = startPt;
        ud.endPt = endPt;
        ud.hDoseProfPlotV = [];

        % APA: Commented
        %         %Create axes.
        %         ud.doseaxis = axes('units', 'pixels', 'position', [50 yStart+100 400 h-yStart-150], 'parent', hFig, 'tickdir', 'out');
        %         xlabel('Distance along line');
        %         ylabel('Dose Value');
        %         ud.scanaxis = axes('units', 'pixels', 'position', [50 yStart+100 400 h-yStart-150], 'parent', hFig, 'tickdir', 'out', 'Color','none','YAxisLocation','right', 'xtick', []);
        %         ylabel('Scan Value');
        % APA: Commented ends

        % APA: try
        %Create axes.
        % ud.doseaxis = axes('units', 'pixels', 'position', [50 yStart+100+170 400 h-yStart-330], 'parent', hFig, 'tickdir', 'out','fontSize',8);
        ud.doseaxis = axes('units', 'pixels', 'position', [50 yStart+270+25 400 h-yStart-300], 'parent', hFig, 'tickdir', 'out','fontSize',8);
        % xlabel('\bfDistance along line','fontSize',10);
        xlabel({});
        ylabel('\bfDose Value','fontSize',10);
        % ud.scanaxis = axes('units', 'pixels', 'position', [50 yStart+100+170 400 h-yStart-330], 'parent', hFig, 'tickdir', 'out', 'Color','none','YAxisLocation','right', 'xtick', [],'fontSize',8);
        ud.scanaxis = axes('units', 'pixels', 'position', [50 yStart+270+25 400 h-yStart-300], 'parent', hFig, 'tickdir', 'out', 'Color','none','YAxisLocation','right', 'xtick', [],'fontSize',8);
        ylabel('\bfScan Value','fontSize',10);

        % APA: try ends

        % DK Radio button for selecting absolute or normalized scale
        clrBg = get(hFig,'color');

        radioToolTip = 'Choose Absolute(ABS) or Normalized (NOR) Scale for Dose Difference';
        h = uibuttongroup('parent',hFig,'units', 'pixels', 'visible','off','Position',[60 yStart+240 100 25]);
        u0 = uicontrol('Style','radiobutton','String','Abs',...
            'position',[5 5 40 15],'parent',h,'HandleVisibility','off');
        u1 = uicontrol('Style','radiobutton','String','Rel',...
            'position',[50 5 40 15],'parent',h,'HandleVisibility','off');
        set(h,'selectionchangedfcn',@d_ct_profRadio);
        set(h,'SelectedObject',u0);  % No selection
        set(h,'Visible','on')

        % DK Drop down list to select the primary dose
        uicontrol('parent',hFig,'Style','Text','Units','Pixels','Position',[170 yStart+230 120 30],...
            'String','Select Base Dose','backgroundcolor',clrBg);

        refDoseToolTip = 'Select the reference/Base Dose from which all doses will be subtracted';

        ud.refDoseSelect = uicontrol('parent',hFig,'Style','popupmenu', 'Units','Pixels','Position',[300 yStart+220 100 40],'Tag','refDoseSelect',...
            'callback', 'doseProfileFigure(''selectrefDose'')','String',outString,'TooltipString',refDoseToolTip);

        % APA: Create  difference axis
        % ud.diffaxis = axes('units', 'pixels', 'position', [50 yStart+90 400 yStart+100+5], 'parent', hFig, 'tickdir', 'out','fontSize',8);
        ud.diffaxis = axes('units', 'pixels', 'position', [50 yStart+100 400 120], 'parent', hFig, 'tickdir', 'out','fontSize',8);
        xlabel('\bfDistance along line','fontSize',10);
        ylabel('\bfDifference','fontSize',10);
        ud.htext = [];

        % APA: Create  slider axis
        ud.slideraxis = axes('units', 'pixels', 'position', [40 yStart+220 420 15], 'parent', hFig,'visible','off');
        %         udS.xL = patch([0.025 0 0], [0.5 0 1], 'w', 'edgecolor', 'k', 'buttondownfcn', 'doseProfileFigure(''RANGERCLICKED'', ''xL'')', 'userdata', ud.slideraxis, 'parent', ud.slideraxis, 'erasemode', 'xor');
        %         udS.xR = patch([0.975 1 1], [0.5 0 1], 'w', 'edgecolor', 'k', 'buttondownfcn', 'doseProfileFigure(''RANGERCLICKED'', ''xR'')', 'userdata', ud.slideraxis, 'parent', ud.slideraxis, 'erasemode', 'xor');
        udS.xL = patch([0.025 0.025 0], [0 1 1], 'w', 'edgecolor', 'k', 'buttondownfcn', 'doseProfileFigure(''RANGERCLICKED'', ''xL'')', 'userdata', ud.slideraxis, 'parent', ud.slideraxis);
        udS.xR = patch([0.975 0.975 1], [0 1 1], 'w', 'edgecolor', 'k', 'buttondownfcn', 'doseProfileFigure(''RANGERCLICKED'', ''xR'')', 'userdata', ud.slideraxis, 'parent', ud.slideraxis);

        % Display initial text on difference axis
        grid(ud.diffaxis,'off')
        set(ud.diffaxis,'xLim',[0 1]);
        set(ud.diffaxis,'yLim',[0 1]);
        htextInit = text(0.1,0.5,'Select More than one dose to display difference','parent', ud.diffaxis,'HorizontalAlignment','left','FontWeight','bold');
        ud.htextInit = htextInit;
        set(hFig, 'userdata',ud);

        %Save userdata.
        set(hFig, 'userdata', ud);
        set(ud.slideraxis, 'userdata', udS);

    case 'SELECTREFDOSE'

        %hFig = findobj('tag', 'CERR_DoseLineProfile');
        hFig = stateS.handle.doseProfileFigure;

        ud = get(hFig, 'userdata');

        %doseUI  = ud.doseUI;

        value = get(ud.refDoseSelect,'value')-1;

        if value ~=0
            ud.baseDose = value;
            %set(doseUI(ud.baseDose), 'FontWeight','bold');
        end

        set(hFig,'Userdata',ud);

    case 'RANGERCLICKED'
        %hFig = findobj('tag', 'CERR_DoseLineProfile');
        hFig = stateS.handle.doseProfileFigure;
        ud    = get(hFig, 'userdata');
        udS   = get(ud.slideraxis, 'userdata');

        %Suspend figure while motion is going on, restore later.
        udS.UISTATE = uisuspend(hFig);

        %Determine which triangle is clicked.
        switch upper(varargin{1})
            case 'XL'
                udS.handle.movingObject = udS.xL;
                RangeMax = get(udS.xR, 'xData');
                udS.motionbounds = [0.025 RangeMax(1)];
            case 'XR'
                udS.handle.movingObject = udS.xR;
                RangeMin = get(udS.xL, 'xData');
                udS.motionbounds = [RangeMin(1) 0.975];
        end
        %Prepare object/figure for motion.
        %set(udS.handle.movingObject, 'erasemode', 'xor');
        set(hFig, 'windowbuttonmotionfcn', 'doseProfileFigure(''INDICATORMOVING'')')
        set(hFig, 'windowbuttonupfcn', 'doseProfileFigure(''MOTIONDONE'');')
        set(ud.slideraxis, 'userdata', udS);

    case 'INDICATORMOVING'
        %hFig = findobj('tag', 'CERR_DoseLineProfile');
        hFig = stateS.handle.doseProfileFigure;
        ud    = get(hFig, 'userdata');
        hAxis = ud.slideraxis;
        udS   = get(ud.slideraxis, 'userdata');
        hObj  = udS.handle.movingObject;
        xData = get(hObj, 'xData');
        hAxis = ud.slideraxis;
        cp = get(hAxis, 'currentpoint');
        mB = udS.motionbounds;
        if cp(2,1) > udS.motionbounds(2)
            cp(2,1) = udS.motionbounds(2);
        elseif cp(2,1) < udS.motionbounds(1)
            cp(2,1) = udS.motionbounds(1);
        end
        delta = cp(2,1) - xData(1);
        %Move both the object and text string to new position.
        set(hObj, 'xData', xData+delta);
        doseProfileFigure('refresh');

    case 'MOTIONDONE'
        %hFig = findobj('tag', 'CERR_DoseLineProfile');
        hFig = stateS.handle.doseProfileFigure;
        ud    = get(hFig, 'userdata');
        udS   = get(ud.slideraxis, 'userdata');

        %Restore the figure to pre-motion state.
        uirestore(udS.UISTATE);

        %Match position of arrow with rounded text value.
        %         hObj  = udS.handle.movingObject;
        %         xData = get(hObj, 'xData');
        %         cP    = str2num(get(ud.associatedText, 'string'));
        %         delta = cP - xData(1);
        %         set(hObj, 'xData', xData+delta);

        %set(udS.handle.movingObject, 'erasemode', 'xor');
        doseProfileFigure('refresh');

    %AI : Removed 'DOSE_CHECK','SCAN_CHECK'

    case 'NEW_POINTS'
        %New points specified for the profile line.
        %hFig = findobj('tag', 'CERR_DoseLineProfile');
        hFig = stateS.handle.doseProfileFigure;
        ud = get(hFig, 'userdata');
        ud.startPt = varargin{1};
        ud.endPt = varargin{2};
        set(hFig, 'userdata', ud);

    case 'REFRESH'
        %Make sure only the most recent calls are drawn.
        %global CERR_doseProfileLastCallTime;
        %thisCallTime = now;
        %if isempty(CERR_doseProfileLastCallTime)
        %    CERR_doseProfileLastCallTime = thisCallTime;
        %else
        %    if thisCallTime > CERR_doseProfileLastCallTime
        %        CERR_doseProfileLastCallTime = thisCallTime;
        %    end
        %end
        %clear CERR_doseProfileLastCallTime;

        %Make dose profile figure the foreground.
        %hFig = findobj('tag', 'CERR_DoseLineProfile');
        hFig = stateS.handle.doseProfileFigure;
        if isempty(hFig)
            return;
        end
        ud = get(hFig, 'userdata');
        udS   = get(ud.slideraxis, 'userdata');
        xDataL = get(udS.xL,'xData');
        x1 = xDataL(1);
        xDataR = get(udS.xR,'xData');
        x2 = xDataR(1);

        delete(ud.htext)
        ud.htext = [];

        if ~isequal(gcf,hFig)
            figure(hFig);
        end

        %delete(findobj(hFig, 'Tag', 'CERR_DOSEPROFILE_PLOT'));
        delete(ud.hDoseProfPlotV)

        nSamples = stateS.optS.numDoseProfileSamples;
        ptsDel = 1:nSamples;
        ptsL = nSamples/0.95*(x1-0.025);
        ptsR = nSamples/0.95*(x2-0.025);
        ptsDel = unique([1:floor(ptsL) ceil(ptsR+1e-6):nSamples]);

        %Get UD stored variables.
        doseUI  = ud.doseUI;
        baseDose = ud.baseDose;
        scanUI  = ud.scanUI;
        nDoses  = ud.nDoses;
        nScans  = ud.nScans;
        startPt = ud.startPt;
        endPt   = ud.endPt;

        if isempty(startPt) || isempty(endPt)
            return;
        end

        colors = stateS.optS.colorOrder;
        %AI: Changed
        drawDoses = get(doseUI,'Data');
        drawDoses = [drawDoses{:,1}];
        drawScans = get(scanUI,'Data');
        drawScans = [drawScans{:,1}];
        %AI: End changed

        drawDoses = find(drawDoses);
        drawScans = find(drawScans);

        %Get x,y,z coords of samples and distance from first pt.
        xV = linspace(startPt(1), endPt(1), nSamples);
        yV = linspace(startPt(2), endPt(2), nSamples);
        zV = linspace(startPt(3), endPt(3), nSamples);
        %distV = sqrt(sepsq(startPt', [xV;yV;zV]));
        len = sqrt(sum((startPt - endPt).^2));
        distV = 0:len/(nSamples-1):len;
        %max(abs(distV - dist1V))

        for i=1:length(drawDoses)
            set(ud.doseaxis, 'nextplot', 'add', 'tickdir', 'out');
            doseNum = drawDoses(i);
            transM = getTransM('dose', doseNum, planC);
            if ~isempty(transM)
                [xV1, yV1, zV1] = applyTransM(inv(transM), xV, yV, zV);
            else
                xV1 = xV; yV1 = yV; zV1 = zV;
            end
            dV{i} = getDoseAt(doseNum, xV1, yV1, zV1, planC);
            dV{i}(ptsDel) = NaN;
        end

        for i=1:length(drawScans)
            set(ud.scanaxis, 'nextplot', 'add', 'tickdir', 'out');
            scanNum = drawScans(i);
            transM = getTransM('scan', scanNum, planC);
            if ~isempty(transM)
                [xV1, yV1, zV1] = applyTransM(inv(transM), xV, yV, zV);
            else
                xV1 = xV; yV1 = yV; zV1 = zV;
            end
            scanV = getScanAt(scanNum, xV1, yV1, zV1, planC);
            offset = planC{indexS.scan}(scanNum).scanInfo(1).CTOffset;
            sV{i} = single(scanV) - offset;
            sV{i}(ptsDel) = NaN;
        end

        %persistent CERR_doseProfileLastCallTime
        hDoseProfPlotV = [];
        %if isequal(CERR_doseProfileLastCallTime, thisCallTime)
            for i=1:length(drawDoses)
                doseNum = drawDoses(i);
                hDoseProfPlotV(end+1) = plot(distV, dV{i}, 'parent', ud.doseaxis, ...
                    'color', getColor(doseNum, colors, 'loop'),...
                    'Tag', 'CERR_DOSEPROFILE_PLOT','linewidth',2);
            end
            axis(ud.doseaxis,'tight')
            for i=1:length(drawScans)
                scanNum = drawScans(i);
                hDoseProfPlotV(end+1) = plot(distV, sV{i}, 'parent', ud.scanaxis,...
                    'color', getColor(scanNum+nDoses, colors, 'loop'),...
                    'Tag', 'CERR_DOSEPROFILE_PLOT','linewidth',2);
            end
            axis(ud.scanaxis,'tight')
            ud.hDoseProfPlotV = hDoseProfPlotV;

            if exist('dV','var') && length(dV)>1 && ~isempty(ud.baseDose)
                delete(ud.htextInit)
                ud.htextInit = [];
                set(ud.diffaxis,'XTickLabelMode','auto','YTickLabelMode','auto')
                set(ud.diffaxis,'nextplot','add')
                otherDoses = drawDoses;
                baseDoseInd = find(otherDoses==baseDose);
                otherDosesInd = 1:length(otherDoses);
                otherDosesInd(baseDoseInd) = [];
                otherDoses(baseDoseInd) = [];

                for i=1:length(otherDosesInd)
                    ddV{i} = dV{otherDosesInd(i)}-dV{baseDoseInd};
                    if max(ddV{i})== 0
                        nddV{i} = ddV{i};
                    else
                        nddV{i} = ddV{i}/max(dV{baseDoseInd});
                    end
                end

                for i=1:length(ddV)
                    ddoseNum = otherDoses(i);
                    if strcmpi(stateS.doseDiffScale, 'Abs')
                        hDoseProfPlotV(end+1) = plot(distV, ddV{i}, 'parent', ud.diffaxis, 'color', ...
                            getColor(ddoseNum, colors, 'loop'),...
                            'Tag', 'CERR_DOSEPROFILE_PLOT','linewidth',2);
                    elseif strcmpi(stateS.doseDiffScale, 'Rel')
                        hDoseProfPlotV(end+1) = plot(distV, nddV{i}, 'parent', ud.diffaxis, 'color', ...
                            getColor(ddoseNum, colors, 'loop'),...
                            'Tag', 'CERR_DOSEPROFILE_PLOT','linewidth',2);
                    end

                end
                axis(ud.diffaxis,'tight')
                grid(ud.diffaxis,'on')
                ax = axis(ud.diffaxis);
                %text1 = get(doseUI(baseDose),'String');
                %dispText = [text1,' - other doses'];
                dispText = ['Dose - Ref'];
                htext = text(ax(2)-(ax(2)-ax(1))*0.03,ax(4)-(ax(4)-ax(3))*0.1,dispText,'parent', ud.diffaxis,'HorizontalAlignment','right','FontWeight','bold');
                ud.htext = htext;
                set(hFig, 'userdata',ud);
                xlabel(ud.diffaxis,'\bfDistance along line','fontSize',10);
                ylabel(ud.diffaxis,'\bfDifference','fontSize',10);
            else
                grid(ud.diffaxis,'off')
                set(ud.diffaxis,'xLim',[0 1]);
                set(ud.diffaxis,'yLim',[0 1]);
                set(ud.diffaxis,'XTickLabelMode','manual','YTickLabelMode','manual','XTickLabel',[],'YTickLabel',[]);
                delete(ud.htextInit)
                htextInit = text(0.1,0.5,'Select More than one dose to display difference','parent', ud.diffaxis,'HorizontalAlignment','left','FontWeight','bold');
                ud.htextInit = htextInit;
                ud.htext =[];
                %ud.hDoseProfPlotV = [];
                set(hFig, 'userdata',ud);
            end

        %end

    case 'CLOSE'
        if stateS.doseProfileState
            sliceCallBack('TOGGLEDOSEPROFILE');
        end
end

% AI: Added
function objCheck(hObj,hEvent)
%Dose/scan has been checked/unchecked
if ~isempty(hEvent.Indices)
hFig = get(hObj,'Parent');
if isempty(hFig)
    return
end
ud = get(hFig,'UserData');
delete(ud.htext)

if strcmp(get(hObj,'Tag'), 'doseUI')
    objUI  = ud.doseUI;
else
    objUI  = ud.scanUI;
end

selectedRowsV = hEvent.Indices(:,1);
objDataC = get(objUI,'Data');
drawObjV = get(objUI,'Data');
drawObjV = [drawObjV{:,1}];
drawObjV(selectedRowsV) = ~drawObjV(selectedRowsV);
objDataC(:,1) = num2cell(drawObjV);
set(objUI,'Data',objDataC);
%objUI.Data = objDataC;

if strcmp(get(hObj,'Tag'), 'doseUI')
    ud.doseUI = objUI;
else
    ud.scanUI = objUI;
end
ud.htext = [];
set(hFig, 'userdata',ud);
doseProfileFigure('refresh');
end


%                                                    cpx = whichcpx(K)
% WHICHCPX  yields structure cpx.{f,q,r,x}
%
% ******************** INTERNAL FUNCTION OF SEDUMI ********************
%
% See also sedumi

function cpx = whichcpx(K) %#ok
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA  (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
%   Dept. Econometrics & O.R., Tilburg University, the Netherlands.
%   Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
%   Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
%   CRL, McMaster University, Canada.
%   Supported by the Netherlands Organization for Scientific Research (NWO).
%
% 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 2 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.,  51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA
%

disp('The SeDuMi binaries are not installed.')
disp('In Matlab, launch "install_sedumi" in the folder you put the SeDuMi files.')
disp('For more information see the file Install.txt.')
error(' ')


function s=getStatisticsStr(obj, format)
    format2printer=struct();
    format2printer.text=@obj2stat_str_text;
    format2printer.xml=@obj2stat_str_xml;

    f=format2printer.(format);
    s=f(obj);

function s=obj2stat_str_xml(obj)
    % do not return any stats
    s='';

function status=obj2stat_str_text(obj)
    label_verbosity=2;
    label2count=struct();

    for i=1:countTestOutcomes(obj)
        test_outcome=getTestOutcome(obj,i);

        if isSuccess(test_outcome)
            % no need to report statistics for successes
            continue;
        end

        test_label=getOutcomeStr(test_outcome,label_verbosity);

        if ~isfield(label2count,test_label);
            label2count.(test_label)=0;
        end

        label2count.(test_label)=label2count.(test_label)+1;
    end

    if wasSuccessful(obj)
        status='OK';
    else
        status='FAILED';
    end

    labels=fieldnames(label2count);
    n_labels=numel(labels);

    if n_labels>0
        parts=cell(1,n_labels);
        for k=1:n_labels
            label=labels{k};
            parts{k}=sprintf('%s=%d',label,label2count.(label));
        end

        status=sprintf('%s (%s)',status,moxunit_util_strjoin(parts,', '));
    end


function test_suite = testSetupExample
initTestSuite;

function fh = setup
fh = figure;

function teardown(fh)
delete(fh);

function testColormapColumns(fh)
assertEqual(size(get(fh, 'Colormap'), 2), 3);

function testPointer(fh)
assertEqual(get(fh, 'Pointer'), 'arrow');


function [] = fig2u3d(ax, fname, imgtype, addaxes, varargin)
%FIG2U3D   Convert figure to U3D file.
%   FIG2U3D saves the current axes as a U3D file for inclusion as an
%   interactive 3-dimensional figure within a PDF. Either LaTeX or Adobe
%   Acrobat can be used to embed the U3D file in the PDF.
%
%   A VWS file is also created, which contains the current camera view of
%   the axes saved. This file can be used to set the figure's default view
%   in the PDF to be the same with the open figure window in MATLAB.
%
%   The media9 LaTeX package can import U3D files with their associated VWS
%   files in a PDF document. It can be found here:
%       http://www.ctan.org/tex-archive/macros/latex/contrib/media9
%
%   For PDF readers which do not render 3D figures, it is possible to
%   include an alternative 2D image as a substitute to the 3D object.
%   For conveniency, the script saves a 2D image together with U3D file.
%   File type and other options for exporting this 2D image can be
%   specified as additional arguments.
%
%   Either export_fig (if available) or the standard print function are
%   used for 2D export. Arguments defining 2D export options need conform
%   to the export function used.
%
%   The IDTF2U3D executables are needed from:
%       http://sourceforge.net/projects/u3d/
%   To obtain them download:
%       http://www.mathworks.com/matlabcentral/fileexchange/25383-matlab-mesh-to-pdf-with-3d-interactive-object
%   and place the "bin" directory in the "idtf2u3d" directory of the
%   fig2u3d distribution.
%
% usage
%   FIG2U3D
%   FIG2U3D(ax, fname, imgtype, addaxes, varargin)
%
% optional input
%   ax = axes object handle to export (default = gca)
%   fname = file name string, e.g. 'myfigure' (default = 'surface')
%           Note: Filename extensions are appended automatically.
%   imgtype = save axes also as an image, to be used as a substitute in
%             PDF readers which cannot render the interactive 3D figure.
%           = 'filetype' | 'none'
%             where:
%                   filetype = any file format supported by the export_fig
%                              or print function (whichever is used)
%                   'none' = in this case a 2D image is not saved
%   addaxes = show axes in u3d file (default = 0)
%           = 0 | 1 (do not show/ show, respectively)
%             (depending on which one is available and used).
%   varargin = additional options to be passed to print or export_fig
%              functions, depending on which one is used for saving the
%              2D image for PDF viewers without 3D support. These must
%              conform to the inputs accepted by the export function used.
%
% output
%   This M-function does not return any data.
%   It saves a U3D file containing the axes object with handle ax.
%
% examples
%   peaks
%   FIG2U3D(gca, 'peaks', '-dpdf') % if using print
%   FIG2U3D(gca, 'peaks', '-dpng', 0, '-r300') % if using print
%
%   FIG2U3D(gca, 'peaks', '-pdf') % if using export_fig
%   FIG2U3D(gca, 'peaks', '-png') % if using export_fig
%
% remark
%   When the axes are unequal, the exporter maintains the aspect ratio by
%   changing the exported coordinates to achieve the same view as in the
%   MATLAB plot window. To avoid this, edit the "fix_daspect = 1;" line in
%   fig2u3d to "fix_daspect = 0;".
%
% dependency
%   IDTF2U3D executables, download:
%       http://www.mathworks.com/matlabcentral/fileexchange/25383-matlab-mesh-to-pdf-with-3d-interactive-object
%   and place the "bin" directory within the "idtf2u3d" directory of the
%   fig2u3d distribution.
%
% optional dependency
%   export_fig, for saving an accompanying 2D image to substitute the 3D
%   inetractive figure in PDF readers which do not render it.
%   This can be downloaded from the MATLAB Central File Exchange:
%       http://www.mathworks.com/matlabcentral/fileexchange/23629
%   Otherwise, the print function is used for the 2D image.
%
% reference
%   IDTF (Intermediate Data Text File) Format Description, Version 100,
%   Intel Corporation, 2005, available at:
%       http://u3d.svn.sourceforge.net/viewvc/u3d/releases/Gold12Update/Docs/IntermediateFormat/IDTF%20Format%20Description.pdf
%
% See also EXAMPLE_FIG2U3D, FIG2PDF3D, FIG2IDTF, IDTF2U3D, VIEW2VWS, PRINT,
%          EXPORT_FIG.
%
% File:      fig2u3d.m
% Author:    Ioannis Filippidis, jfilippidis@gmail.com
% Date:      2012.06.10 - 2012.07.26
% Language:  MATLAB R2012a
% Purpose:   convert figure to U3D file format (lines, surfaces, points)
% Copyright: Ioannis Filippidis, 2012-

% depends
%   u3d_pre_surface, u3d_pre_line, u3d_pre_quivergroup, u3d_pre_contourgroup
%   fig2idtf, idtf2u3d, view2vws
%   axes_extremal_xyz, takehold, restorehold, quivermd, check_file_extension

% optional depends
%   export_fig

% known limitations
%   surface texturemapping not exported
%   filled contourplots not exported

% todo
%   use viewmtx

%% input
if nargin < 1
    ax = gca;
else
    % not a handle ?
    if ~ishandle(ax)
        warning('fig2u3d:handle',...
                'AX argument is not a handle. Exporting current axes.')
        ax = gca;
    end

    % not axes handle ?
    handle_type = get(ax, 'Type');
    if strcmp(handle_type, 'figure')
        warning('fig2u3d:handle',...
               ['AX argument is a figure handle.',...
                'Exporting the first axes child of this figure.'] )
        ax = get(ax, 'Children');
    end
end

% no axes object ?
if isempty(ax)
    warning('fig2u3d:emptyaxes',...
            'AX axes handle is empty. Noting to export.')
    return
end

% filename provided ?
if nargin < 2
    fname = 'surface';
elseif ~ischar(fname) || isempty(fname)
    fname = 'surface';
end

% save image substitute ?
saveimg = 1;
if nargin < 3
    imgtype = '-png';
elseif strcmp(imgtype, 'none') || isempty(imgtype)
    saveimg = 0;
elseif ~ischar(imgtype)
    imgtype = '-png';
else
    imgtype = '-pdf';
end

% show axes ?
if nargin < 4
    addaxes = 0;
elseif isempty(addaxes)
    addaxes = 0;
elseif (addaxes ~= 1) && (addaxes ~= 0)
    error('fig2u3d:addaxes', 'Argument "addaxes" can be 0 or 1.')
end

plot_axes(ax, addaxes)
delete_idtf = 1; % delete intermediate IDTF file

% nothing in the plot ?
obj = get(ax, 'Children');
if isempty(obj)
    warning('axes:empty', 'Nothing in the plot. U3D file not exported.')
    return
end

% are the axes equal ?
dar = daspect(ax);
dar = dar /dar(1);
if any(dar ~= 1)
    msg = 'Axis aspect ratio unequal. Exported U3D will look different.';
    warning('axes:aspect', msg)
end

fix_daspect = 1; % when axes are unequal, change aspect ratio of exported
                 % graphics, so that the exported figure has the same view

%% convert graphics objects to meshes, line_sets and point_sets
[surf_vertices, surf_faces, surf_facevertexcdata, surf_renderers] = u3d_pre_surface(ax);
[patch_vertices, patch_faces, patch_facevertexcdata, patch_renderers] = u3d_pre_patch(ax);
[line_vertices, line_edges, line_colors,...
                line_points, line_point_colors] = u3d_pre_line(ax);
[quiver_vertices, quiver_edges, quiver_colors] = u3d_pre_quivergroup(ax);
[contour_vertices, contour_edges, contour_colors] = u3d_pre_contourgroup(ax);

%% group meshes, line_sets and point_sets
% aggregate meshes
mesh_vertices = [surf_vertices, patch_vertices];
mesh_faces = [surf_faces, patch_faces];
mesh_colors = [surf_facevertexcdata, patch_facevertexcdata];

% aggregate lines
line_vertices = [line_vertices, quiver_vertices, contour_vertices];
line_edges = [line_edges, quiver_edges, contour_edges];
line_colors = [line_colors, quiver_colors, contour_colors];

% aggregate pointsets
pointset_points = line_points;
pointset_colors = line_point_colors;

%% fix axis aspect ratio
if fix_daspect == 1
    dar = daspect(ax);

    if ~isequal(dar, ones(1, 3) )
        msg = ['Unequal axes data aspect ratio, to be fixed by ',...
               'scaling the axes. To change this behavior, edit ',...
               '"fix_daspect = 1;" in fig2u3d to "fix_daspect = 0;"'];
        warning('fig2u3d:daspect', msg)
    end

    mesh_vertices = axis_rescale(mesh_vertices, dar);
    line_vertices = axis_rescale(line_vertices, dar);
    pointset_points = axis_rescale(pointset_points, dar);
end

%% export
fig2idtf(fname,...
          mesh_vertices, mesh_faces, mesh_colors,...
          line_vertices, line_edges, line_colors,...
          pointset_points, pointset_colors)

idtf2u3d(fname)
rm_idtf(fname, delete_idtf)

part_renderers = [surf_renderers, patch_renderers];
view2vws(ax, fname, part_renderers, fix_daspect)

save_png_substitute(ax, fname, saveimg, imgtype, varargin{:} )

function rm_idtf(fname, yesno)
if yesno == 0
    return
end

% fname extensions ok ?
fname = check_file_extension(fname, '.idtf');
fname  = fullfile(cd, fname);

system(['rm ', fname] )

function plot_axes(ax, addaxes)
if addaxes == 0
    return
end

[xyz_minmax, dim] = axes_extremal_xyz(ax);
xyz_minmax = 1.3 *xyz_minmax;

x0 = [0, 0, 0].';
vx = [xyz_minmax(2), 0, 0].';
vy = [0, xyz_minmax(4), 0].';

if dim == 3
    vz = [0, 0, xyz_minmax(6) ].';
end

held = takehold(ax);
    quivermd(ax, x0, vx, 'k')
    quivermd(ax, x0, vy, 'k')
    quivermd(ax, x0, vz, 'k')
restorehold(ax, held)

function [] = save_png_substitute(ax, fname, saveimg, imgtype, varargin)
% save image substitute ?
if saveimg == 0
    return
end

% export_fig available ?
fighandle = get(ax, 'Parent');
if exist('export_fig', 'file') == 2
    col = get(fighandle, 'Color'); % current fig background color

    % set white background for png ?
    if strcmp(imgtype, '-png')
        set(fighandle, 'Color', 'w')
    end

    export_fig(ax, imgtype, varargin{:}, fname)

    set(fighandle, 'Color', col) % restore color
else
    if strfind(imgtype, 'pdf')
        imgtype = '-dpdf';
    elseif strfind(imgtype, 'png')
        imgtype = '-dpng';
    end
    print(fighandle, imgtype, varargin{:}, fname)
end

function [a] = axis_rescale(a, dar)
if isempty(a)
   return
end

a = cellfun(@(x) cell_divider(x, dar), a, 'UniformOutput', false);

function [x] = cell_divider(x, dar)
x = [x(1, :)/dar(1);
     x(2, :)/dar(2);
     x(3, :)/dar(3) ];


function images = get_stimulusimages(username, accessKey)
% get_stimulusimages    Get stimulus images from ImageNet
%
% Note:
%
% This script is for downloading all 1200 training and 50 test images of
% experimental stimulus used in Horikawa and Kamitani 2017
% "Generic decoding of seen and imagined objects using hierarchical visual features".
% It will take about one day to complete all processes with single computer,
% but you can accerelate by using multiple computers in parallel.
%
% This function requires `websave`, which is equipped in MATLAB >= 2014b.
%
% Inputs:
%
% - username  [char] : ImageNet user name
% - accessKey [char] : ImageNet access key
%
% Outputs:
%
% - images [struct] : A structure contains image information
%
% Settings:
%
% - imageListFiles    : List of CSV files which contains image IDs and image file names
% - imageType         : List of strings representing image types
% - imageDir          : Directory in which images will be saved
% - imageSize         : The images will be trimmed down with this size (pixel)
% - deleteOriginalImg : If true, remove the downloaded original image files
%

%% Settings %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% List of CSV files which contains image IDs and image file names
imageListFiles = {'./imageID_training.csv', ...
                  './imageID_test.csv'};

% Type of images ('training' or 'test')
% This should correspond to 'imageListFiles'
imageType = {'training', ...
             'test'};

% The directory in which images will be saved
imageDir = './images';

% Image trimming size (500 px)
imageSize = 500;

% Delete the downloaded original images or not
deleteOriginalImg = false;

% Misc options for downloading (websave)
options = weboptions;
options.Timeout = 100;

%% Main %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

fprintf('%s started\n', mfilename);

urlImageNet = 'http://image-net.org/download/synset';

%% Check inputs ----------------------------------------------------------------
if ~exist('username','var')
    error('Please give your ImageNet username name.');
end

if ~exist('accessKey','var')
    error('Please give your ImageNet access key.');
end

%% Get image lists -------------------------------------------------------------
for i = 1:length(imageListFiles)
    fid = fopen(imageListFiles{i}, 'r');
    imageList = textscan(fid, '%n%s', 'delimiter', ',');
    fclose(fid);

    % Remove quotations from file names
    for j = 1:length(imageList{2})
        imageList{2}{j} = imageList{2}{j}(2:end-1);
    end

    images(i).type     = imageType{i};
    images(i).listFile = imageListFiles{1};
    images(i).id       = imageList{1};
    images(i).files    = imageList{2};

    %% Get image files for each synset
    images(i).synsets = [];
    synsetList = {};
    for j = 1:length(images(i).files)
        imgFileName = images(i).files{j};
        synsetId = regexp(imgFileName, '^(n\d+)_\d+\.JPEG$', 'tokens');
        synsetId = synsetId{1}{1};

        [ismem, ind] = ismember(synsetId, synsetList);

        if ismem
            images(i).synsets(ind).files{end+1} = imgFileName;
        else
            images(i).synsets(end+1).name = synsetId;
            images(i).synsets(end).files{1} = imgFileName;

            synsetList{end+1} = synsetId;
        end
    end

    images(i).synsetList = unique(synsetList);
end

%% Download and convert images -------------------------------------------------
for i = 1:length(images)
for j = 1:length(images(i).synsets)

    %% Multiprocessing
    imgType = images(i).type;
    synsetId = images(i).synsets(j).name;

    lockFile = sprintf('%s_%s_%s.lock', mfilename, imgType, synsetId);
    if exist(lockFile,'file')
        continue;
    end
    fclose(fopen(lockFile, 'w'));

    fprintf('Image type:\t%s\n', imgType);
    fprintf('Synset:\t\t%s\n', synsetId);

    %% Prepare directories
    synsetDir = fullfile(imageDir, imgType, synsetId);
    if ~exist(synsetDir, 'dir')
        fprintf('Create %s\n', synsetDir);
        mkdir(synsetDir);
    end

    dlDir = fullfile(imageDir, 'download', synsetId);
    dlFile = fullfile(dlDir, [synsetId '.tar']);

    if exist(dlFile,'file');
        fprintf('%s already exists. Download was skipped.\n', dlFile);
    else
        if ~exist(dlDir, 'dir')
            fprintf('Create %s\n', dlDir);
            mkdir(dlDir);
        end

        %% Download synset images
        fprintf('Downloading %s...', synsetId);
        tic;
        res = websave(dlFile, urlImageNet, ...
                      'wnid', synsetId, ...
                      'username', username, ...
                      'accesskey', accessKey, ...
                      'release', 'latest', ...
                      'src', 'stanford', ...
                      options);
        elapsedTime = toc;
        fprintf('done (%f sec)\n', elapsedTime);

        fprintf('Extracting image files...');
        untar(dlFile, dlDir)
        fprintf('done\n');
    end

    %% Copy and trim images
    for k = 1:length(images(i).synsets(j).files)
        imgFile = images(i).synsets(j).files{k};
        sourceFile = fullfile(imageDir, 'download', synsetId, imgFile);
        targetFile = fullfile(synsetDir, imgFile);

        if exist(targetFile,'file')
            continue;
        end

        fprintf('Converting %s\n', imgFile);

        while ~exist(sourceFile,'file')
            % Wait until 'sourceFile' is created by another process
            pause(1);
        end

        img = imread(sourceFile);

        imgTrim = trimImgCenter(img);
        imgResize = imresize(imgTrim, [imageSize, imageSize]);

        imwrite(imgResize, targetFile);

        fprintf('%s saved\n', targetFile);
    end

    delete(lockFile);
end
end

%% Remove the downloaded original images
if deleteOriginalImg
    rmdir(fullfile(imageDir, 'download'), 's');
end

fprintf('Finished\n');

end

%% Subfunctions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function [trimmed] = trimImgCenter(img)
% trimimgCenter    Trims an image on the center
%
% Input:
%
% - img: image
%
% Output:
%
% - trimmed: trimmed image

[r, c, d] = size(img);
trimSize = min([r, c]);
lr = floor((c - trimSize) / 2);
ud = floor((r - trimSize) / 2);

trimmed = img((1:min([(trimSize), r - ud])) + ud, ...
              (1:min([(trimSize), c - lr])) + lr, :);

end


function [mapStruct] = modifyReactionsMetabolites(map, rxnList, metList, newColor, newAreaWidth)
% Modifies the color and areaWidth of reactions from a given list as input
% and the color of the corresponding metabolites from a given list as
% input. The colors and areaWidth are given as inputs and only metabolites
% present in the given reactions list will be colored.
%
% USAGE:
%
%   [mapStruct] = modifyReactionsMetabolites(map, rxnList, metList, newColor, newAreaWidth)
%
% INPUTS:
%   map:            Matlab structure of the map obtained from the
%                   function "transformXML2Map".
%   rxnList:        List of reaction names as a string array
%   metList:        List of metabolite names as a string array
%   newColor:       Color chosen for reaction lines and metabolites
%                   given as a string with the corresponding real name.
%                   Possible names can be found in the function
%                   "createColorsMap.m".
%   newAreaWidth:   Width size for the reaction lines. Can be given as
%                   a string or a double.
%
% OUTPUT:
%   mapStruct:      Updated map structure with the changed areaWidth and
%                   color of the reactions and their corresponding
%                   metabolites.
%
% .. Author: - N.Sompairac - Institut Curie, Paris, 25/07/2017

    colors = createColorsMap;  % Create a Color map with corresponding colors names and their HTML code

    mapStruct = map;

    % Get the indexes of the needed reactions to color
    rxnIndexList = find(ismember(mapStruct.rxnName, rxnList));

    % Initialise a list that will contain aliases of molecules implicated in
    % all the needed reactions
    rxnAliasList = {};

    % Loop over reactions and change the corresponding values
    for rxn = rxnIndexList'

        % Change de color of the reaction
        mapStruct.rxnColor{rxn} = colors(newColor);

        % Change de areaWidth of the reaction
        mapStruct.rxnWidth{rxn} = newAreaWidth;

        % Get the list of aliases involved in this reaction
        % Loop over base reactants
        for x = 1:length(mapStruct.rxnBaseReactantID{rxn})
            rxnAliasList = [rxnAliasList, mapStruct.rxnBaseReactantAlias{rxn}{x}];
        end

        % Loop over reactants
        for x = 1:length(mapStruct.rxnReactantID{rxn})
            rxnAliasList = [rxnAliasList, mapStruct.rxnReactantAlias{rxn}{x}];
        end

        % Loop over base products
        for x = 1:length(mapStruct.rxnBaseProductID{rxn})
            rxnAliasList = [rxnAliasList, mapStruct.rxnBaseProductAlias{rxn}{x}];
        end

        % Loop over products
        for x = 1:length(mapStruct.rxnProductID{rxn})
            rxnAliasList = [rxnAliasList, mapStruct.rxnProductAlias{rxn}{x}];
        end
    end

    % Get the indexes of the needed molecules to color
    % Get the corresponding IDs of the species based on their Names
    specIdList = mapStruct.specID(ismember(mapStruct.specName, metList));
    % Get the correspoding Aliases of the molecules based on the species IDs
    mapAliasList = mapStruct.molAlias(ismember(mapStruct.molID, specIdList));
    % Get only the Aliases of the molecules implicated in the needed reactions
    neededAliasList = mapAliasList(ismember(mapAliasList, rxnAliasList));
    % Get the corresponding Indexes of the molecules in the needed reactions
    molIndexList = find(ismember(mapStruct.molAlias, neededAliasList));

    % Loop over molecules and change the color
    for x = molIndexList'
        mapStruct.molColor{x} = colors(newColor);
    end

end


function roidb = roidb_from_ilsvrc14(imdb,varargin)
% roidb = roidb_from_ilsvrc14(imdb)
%   Builds an regions of interest database from imdb image
%   database. Uses precomputed selective search boxes available
%   in the R-CNN data package.
%
%   Inspired by Andrea Vedaldi's MKL imdb and roidb code.

ip = inputParser;
ip.addRequired('imdb', @isstruct);
ip.addParameter('exclude_difficult_samples',       false,   @islogical);
ip.addParameter('with_selective_search',           false,  @islogical);
ip.addParameter('with_edge_box',                   false,  @islogical);
ip.addParameter('with_self_proposal',              false,  @islogical);
ip.addParameter('rootDir',                         '.',    @ischar);
ip.addParameter('extension',                       '',     @ischar);
ip.addParameter('roidb_name_suffix',               '',     @isstr);
ip.addParameter('regions_file_sp',               '',     @isstr);

ip.parse(imdb, varargin{:});
opts = ip.Results;

cacheDir = fullfile(opts.rootDir, 'imdb' , 'cache' , 'ilsvrc');
if ~exist(cacheDir, 'dir')
    mkdir(cacheDir);
end

try
    flip = imdb.flip;
catch
    flip = false;
end

if isempty(opts.roidb_name_suffix)
   opts.roidb_name_suffix = '';
end
if flip == false
    cache_file = [cacheDir '/roidb_' imdb.name opts.roidb_name_suffix '_unflip.mat'];
else
    cache_file = [cacheDir '/roidb_' imdb.name opts.roidb_name_suffix '_flip.mat'];
end

%%
try
   load(cache_file);
catch
    addpath(fullfile(imdb.details.devkit_path, 'evaluation'));

    roidb.name = imdb.name;
    % wsh  regions_file = fullfile('data', 'selective_search_data', [roidb.name '.mat']);
    regions = [];
    if opts.with_selective_search
        fprintf('Loading SS region proposals...');
        regions = load_proposals(regions_file_ss, regions);
        fprintf('done\n');
    end
    if opts.with_edge_box
        regions = load_proposals(regions_file_eb, regions);
    end
    if opts.with_self_proposal
        regions = load_proposals(opts.regions_file_sp, regions);
        regions = renameStructField(regions,'roi', 'boxes');
        regions = renameStructField(regions,'list', 'images');

    end

    if isempty(regions)
        fprintf('Warrning: no ADDITIONAL windows proposal is loaded!\n');
        regions.boxes = cell(length(imdb.image_ids), 1);
        if flip
            regions.images = imdb.image_ids(1:2:end);
        else
            regions.images = imdb.image_ids;
        end
    end

    hash = make_hash(imdb.details.meta_det.synsets);
    WNIDs = {imdb.details.meta_det.synsets.WNID};
    if ~flip

        for i = 1:length(imdb.image_ids)
            if ~mod(i,100)
              tic_toc_print('roidb (%s): %d/%d\n', roidb.name, i, length(imdb.image_ids));
            end
            try
                anno_file = fullfile(imdb.details.bbox_path, [imdb.image_ids{i} '.xml']);
                if strfind(anno_file, '_flip'),
                  flipthat = true;
                  anno_file = strrep(anno_file, '_flip', '');
                else
                  flipthat = false;
                end
                if ~ispc,         anno_file(anno_file == '\') = '/'; end
                if strcmp(imdb.name(1:12),'ilsvrc15_vid')
                  rec = VOCreadrecTrackxml(anno_file, hash);
                else
                  rec = VOCreadrecxml(anno_file, hash);
                end
            catch
                warning('GT(xml) file empty/broken: %s\n', imdb.image_ids{i});

                rec = [];
            end
          if ~isempty(regions)
            if numel(regions.images) ~= numel(imdb.image_ids) %smaller imdb due to subsampling -> find right regions
              j = find(strcmp(regions.images,[imdb.image_ids{i} '.' imdb.extension])) ;
            else
              j = i;
            end
                [~, image_name1] = fileparts(imdb.image_ids{i});
                [~, image_name2] = fileparts(regions.images{j});
                assert(strcmp(image_name1, image_name2));
          end
            roidb.rois(i) = attach_proposals(rec, regions.boxes{j}, WNIDs, opts.exclude_difficult_samples, flipthat);
        end

    else
        % flip case
        for i = 1:length(imdb.image_ids)/2

            tic_toc_print('roidb (%s): %d/%d\n', roidb.name, i, length(imdb.image_ids)/2);
            try
                anno_file = fullfile(imdb.details.bbox_path, [imdb.image_ids{2*i-1} '.xml']);
                if strcmp(imdb.name(1:12),'ilsvrc15_vid')
                  rec = VOCreadrecTrackxml(anno_file, hash);
                else
                  rec = VOCreadrecxml(anno_file, hash);
                end
            catch
                warning('GT(xml) file empty/broken: %s\n', imdb.image_ids{2*i-1});
                rec = [];
            end
            if ~isempty(regions)
                [~, image_name1] = fileparts(imdb.image_ids{i*2-1});
                [~, image_name2] = fileparts(regions.images{i});
                assert(strcmp(image_name1, image_name2));
            end
            roidb.rois(i*2-1) = attach_proposals(rec, regions.boxes{i*2-1}, WNIDs, opts.exclude_difficult_samples, false);
            roidb.rois(i*2) = attach_proposals(rec, regions.boxes{i*2}, WNIDs, opts.exclude_difficult_samples, true);
        end
    end

    rmpath(fullfile(imdb.details.devkit_path, 'evaluation'));

    fprintf('Saving roidb to cache...');
    save(cache_file, 'roidb', '-v7.3');
    fprintf('done\n');
end

% ------------------------------------------------------------------------
function rec = attach_proposals(ilsvrc_rec, boxes, WNIDs, exclude_difficult_samples, flip)

if size(boxes,2) > 4
  boxes = boxes(:,1:4);
end

if isfield(ilsvrc_rec, 'objects') && ~isempty(ilsvrc_rec.objects)
    if exclude_difficult_samples
        valid_objects = ~cat(1, ilsvrc_rec.objects(:).difficult);
    else
        valid_objects = 1:length(ilsvrc_rec.objects(:));
    end
    gt_boxes = cat(1, ilsvrc_rec.objects(valid_objects).bbox);

    %%% ============ NOTE ==============
    % coordinate starts from 0 in ilsvrc
    gt_boxes = gt_boxes + 1;

    if flip
        gt_boxes(:, [1, 3]) = ilsvrc_rec.imgsize(1) + 1 - gt_boxes(:, [3, 1]);
    end
    all_boxes = cat(1, gt_boxes, boxes);
    gt_classes = zeros(length(valid_objects),1);
    for i = 1:length(valid_objects)
      gt_classes(i) = find(strcmp(WNIDs,ilsvrc_rec.objects(valid_objects(i)).class));
    end
    num_gt_boxes = size(gt_boxes, 1);

else
    gt_boxes = [];
    all_boxes = boxes;
    gt_classes = [];
    num_gt_boxes = 0;
end

num_boxes = size(boxes, 1);
rec.boxes = single(all_boxes);
rec.feat = [];
rec.class = uint8(cat(1, gt_classes, zeros(num_boxes, 1)));
if ~isempty(ilsvrc_rec.objects) && isfield(ilsvrc_rec.objects,'trackid')
  rec.trackids = uint8(cat(1, ilsvrc_rec.objects(:).trackid));
  rec.occluded = logical(cat(1, ilsvrc_rec.objects(:).occluded));
  rec.generated = logical(cat(1, ilsvrc_rec.objects(:).generated));
else
  rec.trackids = [];
  rec.occluded = [];
  rec.generated =[];
end
rec.gt = cat(1, true(num_gt_boxes, 1), false(num_boxes, 1));
rec.overlap = zeros(num_gt_boxes+num_boxes, length(WNIDs), 'single');
for i = 1:num_gt_boxes
    rec.overlap(:, gt_classes(i)) = ...
        max(rec.overlap(:, gt_classes(i)), boxoverlap(all_boxes, gt_boxes(i, :)));
end

% ------------------------------------------------------------------------
function regions = load_proposals(proposal_file, regions)
% ------------------------------------------------------------------------
if isempty(regions)
    regions = load(proposal_file);
else
    regions_more = load(proposal_file);
    if ~all(cellfun(@(x, y) strcmp(x, y), regions.images(:), regions_more.images(:), 'UniformOutput', true))
        error('roidb_from_ilsvrc: %s is has different images list with other proposals.\n', proposal_file);
    end
    regions.boxes = cellfun(@(x, y) [double(x); double(y)], regions.boxes(:), regions_more.boxes(:), 'UniformOutput', false);
end

function rec = VOCreadrecTrackxml(path,hash)

x=VOCreadxml(path);
x=x.annotation;

rec.folder=x.folder;
rec.filename=x.filename;
rec.source.database=x.source.database;

rec.size.width=str2double(x.size.width);
rec.size.height=str2double(x.size.height);

rec.imgname=[x.folder x.filename];
rec.imgsize=str2double({x.size.width x.size.height});
rec.database=rec.source.database;

if isfield(x,'object')
    for i=1:length(x.object)
        rec.objects(i)=xmlobjtopas(x.object(i),hash);
    end
else
    rec.objects = [];
end

function p = xmlobjtopas(o,hash)

p.class=o.name;

p.label= get_class2node( hash, p.class );

p.bbox=str2double({o.bndbox.xmin o.bndbox.ymin o.bndbox.xmax o.bndbox.ymax});

p.trackid = str2double(o.trackid);
p.occluded = str2double(o.occluded);
p.generated = str2double(o.generated);


function name = getComputerName()
% GETCOMPUTERNAME returns the name of the computer (hostname)
% name = getComputerName()
%
% WARN: output string is converted to lower case
%
%
% See also SYSTEM, GETENV, ISPC, ISUNIX
%
% m j m a r i n j (AT) y a h o o (DOT) e s
% (c) MJMJ/2007
%

[ret, name] = system('hostname');

if ret ~= 0,
   if ispc
      name = getenv('COMPUTERNAME');
   else
      name = getenv('HOSTNAME');
   end
end
name = lower(name);


function obj = viewSubjectMovieFrames(obj)
	% Creates frame snippets from movies of a subject, used to get a sense of how well cross-session alignment should work.
	% Biafra Ahanonu
	% branched from controllerAnalysis
	% started: 2014.08.01 [16:09:16] (2015.09.14 14:40)
	% inputs
		%
	% outputs
		%

	% changelog
		% 2021.06.18 [21:41:07] - added modelVarsFromFilesCheck() to check and load signals if user hasn't already.
		% 2021.08.10 [09:57:36] - Updated to handle CIAtah v4.0 switch to all functions inside ciapkg package.
		% 2022.03.16 [08:45:40] - Update code standards.
	% TODO
		%

	import ciapkg.api.* % import CIAtah functions in ciapkg package API.

	% fileFilterRegexp = 'concat';
	display(repmat('#',1,21))
	display('computing signal peaks...')
	nFiles = length(obj.rawSignals);

	[fileIdxArray idNumIdxArray nFilesToAnalyze nFiles] = obj.getAnalysisSubsetsToAnalyze();
	subjectList = unique(obj.subjectStr(fileIdxArray));

	movieSettings = inputdlg({...
			'regexp for movies',...
			'group by (1) subject, (2) folder, (3) all montage, or (4) cell extraction max proj',...
			'video save directory',...
			'normalize movie',...
			'start:end frames (do not leave blank)'...
		},...
		'movie frames settings',1,...
		{...
			'concat',...
			'1',...
			obj.videoSaveDir,...
			'0',...
			'100:101'...
		}...
	);
	setNo = 1;
	fileFilterRegexp = movieSettings{setNo};setNo = setNo+1;
	usrIdxChoiceType = str2num(movieSettings{setNo});setNo = setNo+1;
	obj.videoSaveDir = movieSettings{setNo};setNo = setNo+1;
	normalizeMovieSwitch = str2num(movieSettings{setNo});setNo = setNo+1;
	frameList = str2num(movieSettings{setNo});setNo = setNo+1;

	% Miji;
	% MIJ.start;
	manageMiji('startStop','start');

	switch usrIdxChoiceType
		case 1
			for thisSubjectStr=subjectList
				validFoldersIdx = find(strcmp(thisSubjectStr,obj.subjectStr));
				% validManualIdx = find(arrayfun(@(x) isempty(x{1}),obj.validManual));
				% classifyFoldersIdx = intersect(validFoldersIdx,validManualIdx);
				movieList = getFileList({obj.inputFolders{validFoldersIdx}}, fileFilterRegexp);
				movieList
				subjectMovieFrames = loadMovieList(movieList,'convertToDouble',0,'frameList',frameList);
				% movieFrame = squeeze(movieFrame(:,:,1));
				subjectMovieFrames = subjectMovieFrames(:,:,1:2:end);
				if normalizeMovieSwitch==1
					[subjectMovieFrames] = normalizeVector(single(subjectMovieFrames),'normRange','zeroToOne');
					[subjectMovieFrames] = normalizeMovie(subjectMovieFrames,'normalizationType','meanSubtraction');
				end

				if ~isempty(obj.videoSaveDir)
					movieSavePathBase = strcat(obj.videoSaveDir,filesep,'subjectMovieFrames');
					if (~exist(movieSavePathBase,'dir')) mkdir(movieSavePathBase); end;
					movieSavePath = strcat(movieSavePathBase,filesep,thisSubjectStr{1},'.h5');
					[output] = writeHDF5Data(subjectMovieFrames,movieSavePath);
					movieSavePath = strcat(movieSavePathBase,filesep,thisSubjectStr{1},'.tiff');
					options.comp = 'no';
					options.overwrite = true;
					movieSavePath
					saveastiff(subjectMovieFrames, movieSavePath, options);
				end

				MIJ.createImage(thisSubjectStr{1}, subjectMovieFrames, true);
				% pause
			end
			uiwait(ciapkg.overloaded.msgbox('press OK to finish','Success','modal'));
			% MIJ.run('Close All Without Saving');
			manageMiji('startStop','closeAllWindows');
		case 2
			[fileIdxArray idNumIdxArray nFilesToAnalyze nFiles] = obj.getAnalysisSubsetsToAnalyze();
			for thisFileNumIdx = 1:nFilesToAnalyze
				try
					thisFileNum = fileIdxArray(thisFileNumIdx);
					obj.fileNum = thisFileNum;
					display(repmat('=',1,21))
					% display([num2str(thisFileNum) '/' num2str(length(fileIdxArray)) ': ' obj.fileIDNameArray{obj.fileNum}]);
					dispStr = [num2str(thisFileNumIdx) '/' num2str(nFilesToAnalyze) ' (' num2str(thisFileNum) '/' num2str(nFiles) '): ' obj.folderBaseSaveStr{obj.fileNum}];
					display(dispStr);
					% validManualIdx = find(arrayfun(@(x) isempty(x{1}),obj.validManual));
					% classifyFoldersIdx = intersect(validFoldersIdx,validManualIdx);
					movieList = getFileList({obj.inputFolders{obj.fileNum}}, fileFilterRegexp);
					cellfun(@display,movieList);
					subjectMovieFrames = loadMovieList(movieList,'convertToDouble',0,'frameList',frameList);
					% movieFrame = squeeze(movieFrame(:,:,1));
					subjectMovieFrames = subjectMovieFrames(:,:,1:2:end);

					if normalizeMovieSwitch==1
						[subjectMovieFrames] = normalizeVector(single(subjectMovieFrames),'normRange','zeroToOne');
						[subjectMovieFrames] = normalizeMovie(subjectMovieFrames,'normalizationType','meanSubtraction');
					end

					if ~isempty(obj.videoSaveDir)
						movieSavePathBase = strcat(obj.videoSaveDir,filesep,'subjectMovieFrames');
						if (~exist(movieSavePathBase,'dir')) mkdir(movieSavePathBase); end;
						movieSavePath = strcat(movieSavePathBase,filesep,obj.folderBaseSaveStr{obj.fileNum},'.h5');
						[output] = writeHDF5Data(subjectMovieFrames,movieSavePath);
						movieSavePath = strcat(movieSavePathBase,filesep,obj.folderBaseSaveStr{obj.fileNum},'.tiff');
						options.comp = 'no';
						display(['saving: ' movieSavePath])
						saveastiff(subjectMovieFrames, movieSavePath, options);
					end
					dispStr = [' (' num2str(thisFileNum) '/' num2str(nFiles) '): ' obj.folderBaseSaveStr{obj.fileNum}];
					MIJ.createImage(dispStr, subjectMovieFrames, true);
					for foobar=1:3; MIJ.run('In [+]'); end
				catch err
					display(repmat('@',1,7))
					disp(getReport(err,'extended','hyperlinks','on'));
					display(repmat('@',1,7))
				end
				% pause
			end
			uiwait(ciapkg.overloaded.msgbox('press OK to finish','Success','modal'));
			% MIJ.run('Close All Without Saving');
			manageMiji('startStop','closeAllWindows');
		case 3
			[fileIdxArray idNumIdxArray nFilesToAnalyze nFiles] = obj.getAnalysisSubsetsToAnalyze();
			movieListAll = {};
			primaryMovie = {};
			for thisFileNumIdx = 1:nFilesToAnalyze
				thisFileNum = fileIdxArray(thisFileNumIdx);
				obj.fileNum = thisFileNum;
				display(repmat('=',1,21))
				identifyingText{thisFileNumIdx} = obj.subjectStr{obj.fileNum};
				movieList = getFileList({obj.inputFolders{obj.fileNum}}, fileFilterRegexp);
				primaryMovie{thisFileNumIdx} = single(loadMovieList(movieList,'convertToDouble',0,'frameList',frameList));

				% movieListAll = {movieListAll{:} movieList{:}};
			end
			% subjectMovieFrames
			[primaryMovie] = createMontageMovie(primaryMovie,'identifyingText',identifyingText,'normalizeMovies', zeros([length(primaryMovie) 1]),'singleRowMontage',0);
			if ~isempty(obj.videoSaveDir)
				movieSavePathBase = strcat(obj.videoSaveDir,filesep,'subjectMovieFrames');
				if (~exist(movieSavePathBase,'dir')) mkdir(movieSavePathBase); end;
				movieSavePath = strcat(movieSavePathBase,filesep,obj.folderBaseSaveStr{obj.fileNum},'.h5');
				[output] = writeHDF5Data(primaryMovie,movieSavePath);
				movieSavePath = strcat(movieSavePathBase,filesep,obj.folderBaseSaveStr{obj.fileNum},'.tiff');
				options.comp = 'no';
				display(['saving: ' movieSavePath])
				saveastiff(primaryMovie, movieSavePath, options);
			end
			disp(identifyingText)
			MIJ.createImage('Montage', primaryMovie, true);
			% for foobar=1:3; MIJ.run('In [+]'); end
			uiwait(ciapkg.overloaded.msgbox('press OK to finish','Success','modal'));
			% MIJ.run('Close All Without Saving');
			manageMiji('startStop','closeAllWindows');
		case 4
			[fileIdxArray, idNumIdxArray, nFilesToAnalyze, nFiles] = obj.getAnalysisSubsetsToAnalyze();
			for thisSubjectStr = subjectList
				try
					disp(repmat('=',1,7))
					fprintf('Subject %s', thisSubjectStr{1});
					validFoldersIdx = find(strcmp(thisSubjectStr,obj.subjectStr));
					validFoldersIdx = intersect(fileIdxArray,validFoldersIdx);
					if isempty(validFoldersIdx)
						disp('Skipping...')
						continue;
					end
					subjectMovieFrames = single([]);
					for folderNo = 1:length(validFoldersIdx)
						disp('===')
						thisFileNum = validFoldersIdx(folderNo);
						obj.fileNum = thisFileNum;

						% Check that signal extraction information is loaded.
						obj.modelVarsFromFilesCheck(thisFileNum);

						[inputSignals, inputImages, signalPeaks, signalPeakIdx, valid] = modelGetSignalsImages(obj,'returnType','raw');
						if isempty(inputSignals);disp('no input signals');continue;end

						inputImages = thresholdImages(inputImages,'binary',0,'getBoundaryIndex',0,'threshold',0.4,'imageFilter','none');

						goodImages = inputImages(:,:,logical(valid));
						goodImages = max(goodImages,[],3,'omitnan');

						badImages = inputImages(:,:,~logical(valid));
						badImages = max(badImages,[],3,'omitnan');
						disp(num2str([sum(valid) size(goodImages) NaN size(inputImages)]))
						goodImages = goodImages + 0.5*badImages;

						% [goodImages] = viewAddTextToMovie(goodImages,obj.assay{obj.fileNum},12);
						try
							size(subjectMovieFrames)
							size(goodImages)
							subjectMovieFrames(:,:,folderNo) = goodImages;
						catch err
							subjectMovieFrames(:,:,folderNo) = NaN;
							display(repmat('@',1,7))
							disp(getReport(err,'extended','hyperlinks','on'));
							display(repmat('@',1,7))
						end

						try
							[subjectMovieFrames(:,:,folderNo)] = viewAddTextToMovie(subjectMovieFrames(:,:,folderNo),obj.assay{obj.fileNum},12);
						catch err
							display(repmat('@',1,7))
							disp(getReport(err,'extended','hyperlinks','on'));
							display(repmat('@',1,7))
						end
					end

					% subjectMovieFrames

					% validManualIdx = find(arrayfun(@(x) isempty(x{1}),obj.validManual));
					% classifyFoldersIdx = intersect(validFoldersIdx,validManualIdx);
					% movieList = getFileList({obj.inputFolders{validFoldersIdx}}, fileFilterRegexp);
					% movieList
					% subjectMovieFrames = loadMovieList(movieList,'convertToDouble',0,'frameList',frameList);
					% movieFrame = squeeze(movieFrame(:,:,1));
					% subjectMovieFrames = subjectMovieFrames(:,:,1:2:end);
					% if normalizeMovieSwitch==1
					% 	[subjectMovieFrames] = normalizeVector(single(subjectMovieFrames),'normRange','zeroToOne');
					% 	[subjectMovieFrames] = normalizeMovie(subjectMovieFrames,'normalizationType','meanSubtraction');
					% end

					if ~isempty(obj.videoSaveDir)
						movieSavePathBase = strcat(obj.videoSaveDir,filesep,'subjectMovieFrames');
						if (~exist(movieSavePathBase,'dir')) mkdir(movieSavePathBase); end;

						movieSavePath = strcat(movieSavePathBase,filesep,thisSubjectStr{1},'.h5');
						[success] = saveMatrixToFile(subjectMovieFrames,movieSavePath);

						movieSavePath = strcat(movieSavePathBase,filesep,thisSubjectStr{1},'.tiff');
						[success] = saveMatrixToFile(subjectMovieFrames,movieSavePath);
					end

					MIJ.createImage(thisSubjectStr{1}, subjectMovieFrames, true);
					% pause
				catch err
					display(repmat('@',1,7))
					disp(getReport(err,'extended','hyperlinks','on'));
					display(repmat('@',1,7))
				end
			end
			uiwait(ciapkg.overloaded.msgbox('press OK to finish','Success','modal'));
			% MIJ.run('Close All Without Saving');
			manageMiji('startStop','closeAllWindows');
		otherwise
			% body
	end
	% MIJ.exit;
	manageMiji('startStop','exit');
end


function res = chanlabels(this, varargin)
% Method for getting/setting the channel labels
% FORMAT res = chanlabels(this, ind, label)
% _______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging

% Vladimir Litvak
% $Id: chanlabels.m 1373 2008-04-11 14:24:03Z spm $

if nargin == 3
    ind = varargin{1};
    label = varargin{2};

    if iscell(label) && length(label)>1
        if ~isempty(ind) && length(ind)~=length(label)
            error('Indices and values do not match');
        end

        if length(label)>1
            for i = 1:length(label)
                for j = (i+1):length(label)
                    if strcmp(label{i}, label{j})
                        error('All labels must be different');
                    end
                end
            end
        end

    end
end

res = getset(this, 'channels', 'label', varargin{:});