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

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

% Last Modified by GUIDE v2.5 19-Jan-2020 15:12:54

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

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

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

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

    centerUIFigure(hObject);

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

    lvdData = varargin{2};
    setappdata(hObject,'lvdData',lvdData);

	populateGUI(handles, constraint, lvdData);

    % Update handles structure
    guidata(hObject, handles);

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

function populateGUI(handles, constraint, lvdData)
    handles.constraintTypeLabel.String = constraint.getConstraintType();
    handles.constraintTypeLabel.TooltipString = constraint.getConstraintType();

    handles.scaleFactorText.String = fullAccNum2Str(constraint.getScaleFactor());

    handles.eventCombo.String = lvdData.script.getListboxStr();
    evtNum = lvdData.script.getNumOfEvent(constraint.event);
    if(not(isempty(evtNum)))
        handles.eventCombo.Value = evtNum;
    else
        handles.eventCombo.Value = 1;
    end

    evtNum = lvdData.script.getNumOfEvent(constraint.constraintEvent);
    if(not(isempty(evtNum)))
        handles.constraintEventCombo.Value = evtNum;
    else
        handles.constraintEventCombo.Value = 1;
    end

    handles.constraintEventCombo.String = lvdData.script.getListboxStr();

    handles.constActiveCheckbox.Value = constraint.active;

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

% Get default command line output from handles structure
    if(isempty(handles))
        varargout{1} = false;
    else
        constraint = getappdata(hObject, 'constraint');
        lvdData = getappdata(hObject,'lvdData');

        constraint.setScaleFactor(str2double(handles.scaleFactorText.String));

        numEvents = lvdData.script.getTotalNumOfEvents();
        if(numEvents > 0)
            eventNum = handles.eventCombo.Value;
            constraint.event = lvdData.script.getEventForInd(eventNum);

            eventNum = handles.constraintEventCombo.Value;
            constraint.constraintEvent = lvdData.script.getEventForInd(eventNum);
        else
            constraint.event = LaunchVehicleEvent.empty(1,0);
            constraint.constraintEvent = LaunchVehicleEvent.empty(1,0);
        end

        constraint.active = logical(handles.constActiveCheckbox.Value);

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

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

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

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

    sf = str2double(get(handles.scaleFactorText,'String'));
    enteredStr = get(handles.scaleFactorText,'String');
    numberName = 'Scale Factor';
    lb = 1E-12;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(sf, numberName, lb, ub, isInt, errMsg, enteredStr);

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

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

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

% --- Executes during object creation, after setting all properties.
function eventCombo_CreateFcn(hObject, eventdata, handles)
% hObject    handle to eventCombo (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 scaleFactorText_Callback(hObject, eventdata, handles)
% hObject    handle to scaleFactorText (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 scaleFactorText as text
%        str2double(get(hObject,'String')) returns contents of scaleFactorText as a double
    newInput = get(hObject,'String');
    newInput = attemptStrEval(newInput);
    set(hObject,'String', newInput);

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

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

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

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

% Hint: get(hObject,'Value') returns toggle state of constActiveCheckbox

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

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


clear;
clc;
close all;

genJSON('LEEDS');


function isRenamed = db_rename_protocol(newName)
% DB_RENAME_PROTOCOL: Rename current protocol

% @=============================================================================
% This function is part of the Brainstorm software:
% https://neuroimage.usc.edu/brainstorm
%
% Copyright (c) University of Southern California & McGill University
% This software is distributed under the terms of the GNU General Public License
% as published by the Free Software Foundation. Further details on the GPLv3
% license can be found at http://www.gnu.org/copyleft/gpl.html.
%
% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE
% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY
% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY
% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.
%
% For more information type "brainstorm license" at command prompt.
% =============================================================================@
%
% Authors: Francois Tadel, 2019

global GlobalData;
isRenamed = 0;

% Get protocol to rename
iProtocol = bst_get('iProtocol');
ProtocolInfo = bst_get('ProtocolInfo');
if isempty(iProtocol) || (iProtocol < 1)
    bst_error('No protocol selected.', 'Rename protocol', 0);
    return;
end

% Get new protocol name
if (nargin < 1) || isempty(newName)
    newName = java_dialog('input', 'Enter new protocol name:', 'Rename protocol', [], ProtocolInfo.Comment);
end
if isempty(newName) || isequal(newName, ProtocolInfo.Comment)
    return;
elseif ~isequal(newName, file_standardize(newName))
    bst_error('Invalid protocol name.', 'Rename protocol', 0);
    return;
elseif any(strcmpi(newName, {GlobalData.DataBase.ProtocolInfo.Comment}))
    bst_error(['A protocol named "' newName '" already exists in your database.'], 'Rename protocol', 0);
    return;
end

% New protocol folder
[oldPathAnat, anatName] = bst_fileparts(ProtocolInfo.SUBJECTS);
[oldPathData, dataName] = bst_fileparts(ProtocolInfo.STUDIES);
[basePath, oldName] = bst_fileparts(oldPathData);
newPath = bst_fullfile(basePath, newName);

% Check that anat and data folders are in the same folder
if ~isequal(oldPathData, oldPathAnat)
    bst_error('Only protocols with anat and data folders in the same folder can be renamed.', 'Rename protocol', 0);
    return;
end
% Check if folder already exists
if file_exist(newPath)
    bst_error(['This folder already exists:' 10 newPath], 'Rename protocol', 0);
    return;
end

% Rename protocol folder
isMoved = file_move(oldPathData, newPath);
if ~isMoved
    bst_error(['Could not rename protocol folder.' 10 'Source: ' oldPathData 10 'Destination: ' newPath], 'Rename protocol', 0);
    return;
end

% Change protocol folders
ProtocolInfo.Comment = newName;
ProtocolInfo.SUBJECTS = bst_fullfile(newPath, anatName);
ProtocolInfo.STUDIES = bst_fullfile(newPath, dataName);
db_edit_protocol('edit', ProtocolInfo, iProtocol);

isRenamed = 1;

% Refresh protocols list
gui_brainstorm('UpdateProtocolsList');


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

% Last Modified by GUIDE v2.5 24-May-2013 14:12:48

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

handles.Simuh=varargin{1};
Category=dir([handles.Simuh.MRiLabPath filesep 'Config' filesep 'Grad']);
ind=1;
for i=1:length(Category)
    if ~strcmp(Category(i).name,'.') & ~strcmp(Category(i).name,'..') & Category(i).isdir
        handles.CategoryDir{ind,1}=Category(i).name;
        ind=ind+1;
    end
end
set(handles.Category_listbox,'String',handles.CategoryDir);

handles.accept = 0;
% Choose default command line output for GradList_figure
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

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

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

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

if ~isempty(get(handles.GradPath_text,'String'))
    return;
end

if strcmp(handles.GradList,'Empty')
    return;
end

handles.GradXMLFile=[handles.Simuh.MRiLabPath filesep ...
                    'Config' filesep ...
                    'Grad' filesep ...
                    handles.CategoryDir{get(handles.Category_listbox,'Value')} filesep ...
                    handles.GradList{get(handles.Grad_listbox,'Value')} filesep...
                    handles.GradList{get(handles.Grad_listbox,'Value')} '.xml'];

handles.GradXMLDir=[handles.Simuh.MRiLabPath filesep ...
                    'Config' filesep ...
                    'Grad' filesep ...
                    handles.CategoryDir{get(handles.Category_listbox,'Value')} filesep ...
                    handles.GradList{get(handles.Grad_listbox,'Value')}];

guidata(hObject, handles);

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

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

% --- Executes on selection change in Category_listbox.
function Category_listbox_Callback(hObject, eventdata, handles)
% hObject    handle to Category_listbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

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

if ~isempty(get(handles.GradPath_text,'String'))
    return;
end

if strcmp(handles.CategoryDir,'Empty')
    return;
end

set(handles.Grad_listbox,'Enable','on');

Grad=dir([handles.Simuh.MRiLabPath filesep ...
          'Config' filesep ...
          'Grad' filesep ...
          handles.CategoryDir{get(handles.Category_listbox,'Value')}]);
ind=1;
handles.GradList=[];
for i=1:length(Grad)
    if ~strcmp(Grad(i).name,'.') & ~strcmp(Grad(i).name,'..')
        handles.GradList{ind,1}=Grad(i).name;
        ind=ind+1;
    end
end
if ind==1
    handles.GradList='Empty';
end
set(handles.Grad_listbox,'String',handles.GradList);
set(handles.Grad_listbox,'Value',1);

guidata(hObject, handles);

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

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

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

if isempty(get(handles.GradPath_text,'String'))
    try
        if strcmp(handles.GradList{get(handles.Grad_listbox,'Value')},'Empty')
            DoUpdateInfo(handles.Simuh,'No gradient is selected!');
            return;
        end
    catch me
        DoUpdateInfo(handles.Simuh,'No gradient is selected!');
        return;
    end
end

%----update gradient selection
handles.Simuh.GradXMLFile=handles.GradXMLFile;
handles.Simuh.GradXMLDir=handles.GradXMLDir;
Grad=DoParseXML(handles.GradXMLFile);
handles.Simuh.GradStruct=Grad;
Grad_text=uicontrol(handles.Simuh.GradSel_uipanel,'Style','text');
set(Grad_text,'FontWeight','bold','FontSize',10,'Position',[0,0,140,18],...
    'String', Grad.Attributes(1).Value,'TooltipString',handles.GradXMLFile);
%----end
guidata(handles.Simuh.SimuPanel_figure,handles.Simuh);
DoUpdateInfo(handles.Simuh,'Grad file was successfully loaded!');
handles.accept = 1;
guidata(hObject, handles);
close(handles.GradList_figure);

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

% --- Executes when user attempts to close GradList_figure.
function GradList_figure_CloseRequestFcn(hObject, eventdata, handles)
% hObject    handle to GradList_figure (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

DoDisableButton([],[],handles.Simuh);
if handles.accept == 0
    DoUpdateInfo(handles.Simuh,'Grad file loading was cancelled!');
end
% Hint: delete(hObject) closes the figure
delete(handles.GradList_figure);

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

[filename,pathname,filterindex]=uigetfile({'Grad*.xml','XML-files (*.xml)'},'MultiSelect','off');
if filename~=0
    handles.GradXMLFile=[pathname filename];
    handles.GradXMLDir=pathname(1:end-1);
    set(handles.GradPath_text,'String',[pathname filename]);
    % Add searchig path
    path(path,handles.GradXMLDir);

else
    errordlg('No Grad was loaded!');
    return;
end
guidata(hObject, handles);

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

if isfield(handles.Simuh,'GradXMLFile')
    handles.Simuh=rmfield(handles.Simuh,'GradXMLFile');
    delete(get(handles.Simuh.GradSel_uipanel,'Children'));
    guidata(handles.Simuh.SimuPanel_figure,handles.Simuh);
end
DoUpdateInfo(handles.Simuh,'Use default Gradient!');
handles.accept = 1;
guidata(hObject, handles);
close(handles.GradList_figure);


function r = emptyfh()
r = @(varargin)[];


classdef Rx < adi.AD9361.Rx
    % adi.AD9364.Rx Receive data from the AD9364 transceiver
    %   The adi.AD9361.Rx System object is a signal source that can receive
    %   complex data from the AD9364.
    %
    %   rx = adi.AD9364.Rx;
    %   rx = adi.AD9364.Rx('uri','192.168.2.1');
    %
    %   AD9364 Datasheet
    %
    %   See also adi.FMComms4.Rx

    methods
        %% Constructor
        function obj = Rx(varargin)
            % Returns the matlabshared.libiio.base object
            coder.allowpcode('plain');
            obj = obj@adi.AD9361.Rx(varargin{:});
        end
    end

end


function X = ncvar(X)
X = ncvar(struct(X));


%{
    Copyright (c) 2015, Philipp Krähenbühl
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:
        * Redistributions of source code must retain the above copyright
        notice, this list of conditions and the following disclaimer.
        * Redistributions in binary form must reproduce the above copyright
        notice, this list of conditions and the following disclaimer in the
        documentation and/or other materials provided with the distribution.
        * Neither the name of the Stanford University nor the
        names of its contributors may be used to endorse or promote products
        derived from this software without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY Philipp Krähenbühl ''AS IS'' AND ANY
    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
    DISCLAIMED. IN NO EVENT SHALL Philipp Krähenbühl BE LIABLE FOR ANY
    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
	 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
	 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
	 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
%}
addpath( genpath('../build') )


function startHandGuiding( t )
%% About:
% This function is used to start KUKA's off-the-shelf hand guiding

%% Syntax:
% startHandGuiding( t )

%% Areguments:
% t: is the TCP/IP connection object

% Copyright, Mohammad SAFEEA, 9th of June 2017

theCommand='handGuiding';
fprintf(t, theCommand);

fprintf('Hand gudining functionality is started \n');
fprintf('1- Press white button to activate the hand guiding \n');
fprintf('2- Release the white button so the robot stops in its configuration \n');
fprintf('3- Release the white button so the robot stops in its configuration \n');
fprintf('4- To reactivate the handguding functionality, press the green button once, for less than 1 sec  \n');
fprintf('5- Repeat from 1  \n');
fprintf('5- To terminate the hand guding function, press the green button for more than 1.5 sec \n keep pressing until the red light starts to flicker then release your hand, \n the hand guiding mode will be terminated ');
    message='';
    w = warning ('off','all');
    readingFlag=false;
    while readingFlag==false
        message=fgets(t);

        if checkAcknowledgment(message)
            readingFlag=true;
        end
    end
     w = warning ('on','all');
    fprintf('Hand gudining was terminated by user at robot side \n');
end


function gui_popup( jPopup, jParent, x, y )
% GUI_POPUP: Show a JPopupMenu at the current location of the mouse cursor.

% @=============================================================================
% This function is part of the Brainstorm software:
% https://neuroimage.usc.edu/brainstorm
%
% Copyright (c) University of Southern California & McGill University
% This software is distributed under the terms of the GNU General Public License
% as published by the Free Software Foundation. Further details on the GPLv3
% license can be found at http://www.gnu.org/copyleft/gpl.html.
%
% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE
% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY
% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY
% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.
%
% For more information type "brainstorm license" at command prompt.
% =============================================================================@
%
% Authors: Francois Tadel, 2008-2014

% Parse inputs
if (nargin < 2) || isempty(jParent)
    jParent = jPopup;
end
if (nargin < 4) || isempty(x) || isempty(y)
    mouseInfo = java.awt.MouseInfo.getPointerInfo();
    mouseLoc  = mouseInfo.getLocation();
else
    mouseLoc = java.awt.Point(x,y);
end
jPopup.pack();

% If parent is a figure handle
if ~isjava(jParent) && ~isempty(jParent)
    % Fix stupid bug in some older Matlab versions
    if any(bst_get('MatlabVersion') == [709, 710, 711])
        jParent = jPopup;
    % Matlab >= 2019b deprecated the JavaFrame property, impossible to attach JPopupMenu to a figure
    elseif (bst_get('MatlabVersion') >= 907)
        jParent = jPopup;
    else
        % Get the handle of the java figure
        jParent = bst_get('JFrame', jParent);
        % If the call crashed
        if isempty(jParent)
            jParent = jPopup;
        end
    end
end
% Show popup
jPopup.setLocation(mouseLoc);
jPopup.setInvoker(jPopup);
jPopup.setVisible(1);
drawnow;


function my_save_file(cache_file, data_obj, force_overide, be_quite)

if nargin<3
    force_overide=false;
end

if nargin<4
    be_quite=false;
end

finished=false;
while ~finished
    try

        if ~force_overide && exist(cache_file, 'file')
            disp('file exist, save to new name.');

            [f1, f2, f3]=fileparts(cache_file);
            while exist(cache_file, 'file')
                f2=[f2 '_new'];
                cache_file=[f1 '/' f2 f3];
            end

        end

        tmp_dir=fileparts(cache_file);
        mkdir_notexist(tmp_dir);

        if ~be_quite
            fprintf('save_file:%s\n',cache_file);
        end

        save(cache_file, 'data_obj', '-v7.3');
        finished=true;
    catch err_info
        disp(err_info);
        pause_sec=60+60*rand(1);
        fprintf('save_file failed, retry in %.f seconds, file:%s\n', pause_sec, cache_file);
        pause(pause_sec);
    end
end

end


function [inchiString] = getInchiStringFromHMDB(HMDBID)
% This function retrieves the inchiString from HMDB (online) for a given
% HMDB ID.
%
% INPUT
% HMDBID    Human metabolome database (HMDB) ID
%
% OUTPUT
% inchiString   Retrieved inchiString
%
% Ines Thiele, 09/2021
%

% get inchi from HMDB
try
    url=strcat('https://hmdb.ca/metabolites/',HMDBID);
    syst = urlread(url);
    [tok] = split(syst,'InChI=1S');
    tok2= split(tok{2},'INCHI_KEY');
    tok3 = regexprep(tok2{1},'\n\n\> \<','');
    inchiString = ['InChI=1S' tok3];
catch
    inchiString =[];
end


% --------------------------------------------------------
% MDP Tracking
% Copyright (c) 2015 CVGL Stanford
% Licensed under The MIT License [see LICENSE for details]
% Written by Yu Xiang
% --------------------------------------------------------
function MOT_copy_images

% test sequences
seqs = {'TUD-Crossing', 'PETS09-S2L2', 'ETH-Jelmoli', ...
    'ETH-Linthescher', 'ETH-Crossing', 'AVG-TownCentre', 'ADL-Rundle-1', ...
    'ADL-Rundle-3', 'KITTI-16', 'KITTI-19', 'Venice-1'};

indexes = {{31, 107}, {68, 111}, {82, 215}, {51, 78}, {97}, {52, 220} ...
    {232}, {183}, {90}, {281}, {235}};

for i = 1:numel(seqs)
    seq_name = seqs{i};
    index = indexes{i};

    for j = 1:numel(index)
        ind = index{j};
        file_src = sprintf('results_MOT/results_MOT_1/%s/%06d.png', seq_name, ind);
        disp(file_src);
        file_dst = sprintf('figures/%s_%06d.png', seq_name, ind);
        copyfile(file_src, file_dst);
    end

end


function r = zerofun(varargin)
r = 0;


% EEG_GLOBAL - declare global EEGLAB variables. These variables are
%                used only as global by the main function EEGLAB,
%                the function POP_REJMENU and the history EEGH function.
%
% Global variables:
%  EEG        - structure containing the current dataset
%  ALLEEG     - array of structures containing all the loaded datasets
%  CURRENTSET - index of the current dataset in the ALLEEG array
%  LASTCOM    - most recent command run by EEGLAB
%  ALLCOM     - cell array containing the EEGLAB session command history
%               See the history (h) function for more details.
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: EEGLAB

% Copyright (C) 2001 Arnaud Delorme, Salk Institute, arno@salk.edu
%
% This file is part of EEGLAB, see http://www.eeglab.org
% for the documentation and details.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are met:
%
% 1. Redistributions of source code must retain the above copyright notice,
% this list of conditions and the following disclaimer.
%
% 2. Redistributions in binary form must reproduce the above copyright notice,
% this list of conditions and the following disclaimer in the documentation
% and/or other materials provided with the distribution.
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
% THE POSSIBILITY OF SUCH DAMAGE.

% global variables
% ----------------
globalvars = who('global');
if ~isempty(strmatch('ALLCOM', globalvars, 'exact')) || exist('ALLCOM') ~= 1
    tmpEEG = whos('EEG');
    % avoid overwritting variable in the current space
    % in case it is not global
    if ~isempty(tmpEEG) && ~tmpEEG.global
        TMPEEG = EEG;
        clear EEG;
        global EEG;
        EEG = TMPEEG;
    else
        global EEG;		% current dataset
    end
    global ALLEEG;		% all datasets
    global CURRENTSET;	% current set index

    %global W_MAIN;		% main window
    %global H_MAIN;		% main window
    %global EEGMENU;		% main menu
    global ALLCOM;		% all commands (history)
    global LASTCOM;		% last command
    global STUDY;
    global CURRENTSTUDY;
    global PLUGINLIST;

    if exist('eegplugin_erplab.m')
        global ALLERP; % Javier Lopez-Calderon for ERPLAB
    end
end


% ONLY FOR DEBUGGING PURPOSE (Javier)
%
%

function dispcond(cond,text,storecode, storesign, storetime, storeflag, storewrite)
% Despliega texto en el command window si cond=1
% Pensado para ocupar mensajes durante debbugin.
% Author: Javier
if nargin==2
        if cond
                disp(text)
        end
elseif nargin==7
        if cond
                disp(text)
                storecode %#ok<NOPRT>
                storesign %#ok<NOPRT>
                storetime %#ok<NOPRT>
                storeflag %#ok<NOPRT>
                storewrite %#ok<NOPRT>
        end
else
        return
end


% @authors:     Ahmad Humayun
% @contact:     ahumayun@cc.gatech.edu
% @affiliation: Georgia Institute of Technology
% @date:        Fall 2013 - Summer 2014

function prep_deploy()
    % to be run to set the directory up for deployment
    u = userpath;
    matlab_path = u(1:end-1);

    code_root_dir = fullfile(fileparts(which(mfilename)), '..');
    extern_src_rel_dst = 'extern_src';
    algos_dir_dst = fullfile(code_root_dir, extern_src_rel_dst);
    utils_dir_dst = fullfile(code_root_dir, 'utils');
    algos_dir_src = fullfile(code_root_dir, '..', 'extern_src');

    % delete old directories & files (as a result of previous run of this script)
    if_exist_del(fullfile(code_root_dir, 'data'));
    if_exist_del(fullfile(algos_dir_dst, 'fuxin_lib_src'));
    if_exist_del(fullfile(algos_dir_dst, 'segmentation'));
    if_exist_del(fullfile(algos_dir_dst, 'stein_boundaryprocessing'));
    if_exist_del(fullfile(algos_dir_dst, 'toolboxes'));
    if_exist_del(fullfile(algos_dir_dst, 'utils'));
    if_exist_del(fullfile(utils_dir_dst, 'drawFigFrames.m'));
    if_exist_del(fullfile(utils_dir_dst, 'timerTicks.m'));
    if_exist_del(fullfile(utils_dir_dst, 'compute_error_metric.m'));
    if_exist_del(fullfile(utils_dir_dst, 'duplicateElems.m'));

    % copy files needed from matlab user directory
    copyfile(fullfile(matlab_path, 'drawFigFrames.m'), utils_dir_dst);
    copyfile(fullfile(matlab_path, 'timerTicks.m'), utils_dir_dst);
    copyfile(fullfile(matlab_path, 'duplicateElems.m'), utils_dir_dst);

    % copy necessary files from fuxin library
    mkdir(fullfile(algos_dir_dst, 'fuxin_lib_src'));
    copyfile(fullfile(code_root_dir, '..', 'fuxin_lib_src', 'boosting'), fullfile(algos_dir_dst, 'fuxin_lib_src', 'boosting'));
    copyfile(fullfile(code_root_dir, '..', 'fuxin_lib_src', 'myqueue_1.1'), fullfile(algos_dir_dst, 'fuxin_lib_src', 'myqueue_1.1'));
    copyfile(fullfile(code_root_dir, '..', 'fuxin_lib_src', '@classregtree_fuxin'), fullfile(algos_dir_dst, 'fuxin_lib_src', '@classregtree_fuxin'));

    % copy stein boundary processing
    copyfile(fullfile(algos_dir_src, 'segmentation', 'stein_boundaryprocessing'), fullfile(algos_dir_dst, 'stein_boundaryprocessing'));

    copyfile(fullfile(algos_dir_src, 'compute_error_metric.m'), utils_dir_dst);
end

function if_exist_del(delpath)
    if exist(delpath, 'dir')
        rmdir(delpath, 's');
    elseif exist(delpath, 'file')
        delete(delpath);
    end
end


function results = traverseDirectoryStructure(rootPath, style, functionName, varargin)
%"traverseDirectoryStructure"
%   Given a path, <rootPath>, execute the function given by functionname
%   string <functionName> in rootPath and all of its subdirectories. Compile
%   the output of functionName's call in a datastructure. Must specify 'pre'
%   or 'post' in the style field for pre or post evaluation. varargin contains
%   any arguments for the function <functionname>.
%
%   JRA 11/7/03
%
% Usage: results = traverseDirectoryStructure(rootPath, style, functionName, varargin)
%
% 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/>.

oldpwd = pwd;
try
	cd(rootPath);
    rootPath = pwd;
	numArgs = nargout(functionName);

	%Establish result's struct fields but clear it of data.
	results.dir = '';
	results.data = '';
	results(1) = [];

	if strcmpi(style,'pre')
        [outputs{1:numArgs}] = feval(functionName, varargin{:});
        results(1).dir = rootPath;
        results(1).data = outputs;
	end

	dirContents = dir;
	for i = 1:length(dirContents)
        fileInfo = dirContents(i);
        if (strcmpi(fileInfo.name,'.') | strcmpi(fileInfo.name,'..'))
            continue
        end

        if fileInfo.isdir
            if nargin > 3
                output = traverseDirectoryStructure(fullfile(rootPath, fileInfo.name), style, functionName, varargin);
            else
                output = traverseDirectoryStructure(fullfile(rootPath, fileInfo.name), style, functionName);
            end
            results(end+1:end+length(output)) = output;
        end
	end

	if strcmpi(style,'post')
        [outputs{1:numArgs}] = feval(functionName,varargin{:});
        results(end+1).dir = rootPath;         %Add to end of array.
        results(end).data = outputs;           %Just end since array grew from last step.
    end
    cd(oldpwd);
catch
   cd(oldpwd)
   error(['Error in traverseDirectoryStructure: ' lasterr '.']);
end


function oldPath = ezPath(varargin)
%EZPATH add path more easier.
%USAGE
% ezPath folder1 folder2 ...

%SEE ALSO addpath rmpath savepath
%
%COPYRIGHT Zhenqiang Ying <yingzhenqiang-at-gmail-dot-com>

oldPath = path;

cfg.SavePath = true;
cfg.FullPath = true;

if isstruct(varargin{1})
	cfg = loaddefault(varargin{1}, cfg, true); % time-consuming
    varargin = varargin(2:end);
end

inputPath = strjoin(varargin, ';');
pathList = strsplit(inputPath, ';');

try
    caller = callerFile;
    defaultPath = caller.path;
catch
    defaultPath = cd;
end

if cfg.FullPath
    for pathStr = pathList
        [p, func] = strsplit(pathStr{1}, '>');p = p{1};
        if ~ismember(':', p) % is not fullpath
            p = [defaultPath filesep p];
        end
        if isempty(func) || ~exist(func{1}, 'file')
            if p(end) == '*'
                genpath(p(1:end-1))
                addpath(genpath(p(1:end-1)));
            else
                addpath(p);
            end
            %this.path{end+1} = p;
        end
    end
else
    addpath(inputPath);
end

if cfg.SavePath
	savepath
end


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

    % Last Modified by GUIDE v2.5 28-Jun-2015 14:21:02

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

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

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

    pos = get(handles.dispAxes,'Position');
    set(handles.displayAtmoRadio,'UserData',pos);

    setupCelBodyListbox(handles, celBodyData);
    catalogListbox_Callback(handles.catalogListbox, [], handles);

    % Update handles structure
    guidata(hObject, handles);

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

function setupCelBodyListbox(handles, celBodyData)
    bodiesStr = ma_getSortedBodyNames(celBodyData);

    set(handles.catalogListbox, 'String', bodiesStr);
    if(length(bodiesStr) >= 1)
        set(handles.catalogListbox, 'value', 1);
    end

    % --- Outputs from this function are returned to the command line.
function varargout = ma_CelBodyCatalogGUI_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 selection change in catalogListbox.
function catalogListbox_Callback(hObject, eventdata, handles)
    % hObject    handle to catalogListbox (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 catalogListbox contents as cell array
    %        contents{get(hObject,'Value')} returns selected item from catalogListbox
    contents = cellstr(get(hObject,'String'));
    selected = contents{get(hObject,'Value')};

    celBodyData = getappdata(handles.ma_CelBodyCatalogGUI,'celBodyData');
    bodyInfo = celBodyData.(strtrim(lower(selected)));
    parentBodyInfo = bodyInfo.getParBodyInfo(celBodyData);
    bodyInfoStr = generateBodyInfoStr(bodyInfo, celBodyData);
    set(handles.infoLabel,'String',bodyInfoStr);

    dispBodyValue = get(handles.displayBodyRadio, 'Value');
    dispOrbValue = get(handles.displayOrbitRadio, 'Value');
    dispAtmoValue = get(handles.displayAtmoRadio, 'Value');

    if(bodyInfo.atmohgt == 0)
        set(handles.displayAtmoRadio, 'Enable', 'off');
        if(dispAtmoValue==1)
            set(handles.displayAtmoRadio, 'Value', 0);
            set(handles.displayBodyRadio, 'Value', 1);

            dispBodyValue = get(handles.displayBodyRadio, 'Value');
            dispAtmoValue = get(handles.displayAtmoRadio, 'Value');
        end
    else
        set(handles.displayAtmoRadio, 'Enable', 'on');
    end

    cla(handles.dispAxes);
    xlabel('');
    ylabel('');
    if(dispBodyValue==1)
        plotBody(handles.ma_CelBodyCatalogGUI,handles.dispAxes,bodyInfo);
        set(handles.dispAxes,'Position',get(handles.displayAtmoRadio,'UserData'));
    elseif(dispOrbValue==1)
        if(~isempty(parentBodyInfo))
            plotBodyOrbit(bodyInfo, 'r', getParentGM(bodyInfo, celBodyData));
            plotBody(handles.ma_CelBodyCatalogGUI,handles.dispAxes,parentBodyInfo);
        else
            plotBody(handles.ma_CelBodyCatalogGUI,handles.dispAxes,bodyInfo);
        end
        set(handles.dispAxes,'Position',get(handles.displayAtmoRadio,'UserData'));
    elseif(dispAtmoValue==1)
        plotAtmoCurve(handles.dispAxes, bodyInfo, celBodyData);
        set(handles.dispAxes,'OuterPosition',get(handles.displayAtmoRadio,'UserData'));
    end

function plotAtmoCurve(orbitDispAxes, bodyInfo, celBodyData)
    atmoHgt = bodyInfo.atmohgt;

    if(atmoHgt > 0)
        hArr = linspace(0,atmoHgt,100);
        density = zeros(size(hArr));
        for(i=1:length(hArr))
            density(i) = getAtmoDensityAtAltitude(bodyInfo, hArr(i), deg2rad(45), 0, 0);
        end

        plot(orbitDispAxes,hArr,density,'r-','LineWidth',2);
        v = ylim(orbitDispAxes);
        grid on;
        xlim(orbitDispAxes, [min(hArr), max(hArr)]);
        ylim(orbitDispAxes, [0, v(2)]);
        xlabel('Altitude [km]');
        ylabel('Density [kg/m^3]');
    end

function plotBody(hFig,orbitDispAxes, bodyInfo)
    ma_initOrbPlot(hFig, orbitDispAxes, bodyInfo);

function bodyInfoStr = generateBodyInfoStr(bodyInfo, celBodyData)
    hrule = '-----------------------------------';

    [year, day, hour, minute, sec] = convertSec2YearDayHrMnSec(bodyInfo.epoch);
    [dateStr] = formDateStr(year, day, hour, minute, sec);

    parentBodyInfo = bodyInfo.getParBodyInfo(celBodyData);
    if(bodyInfo.sma > 0 && ~isempty(parentBodyInfo))
        [~, ~, secInDay, ~] = getSecondsInVariousTimeUnits();
        period = computePeriod(bodyInfo.sma, getParentGM(bodyInfo, celBodyData));
        periodStr = [num2str(period/secInDay), ' days'];

        [rAp, rPe] = computeApogeePerigee(bodyInfo.sma, bodyInfo.ecc);
        rApStr = [num2str(rAp), ' km'];
        rPeStr = [num2str(rPe), ' km'];
    else
        periodStr = 'N/A';

        [~, rPe] = computeApogeePerigee(bodyInfo.sma, bodyInfo.ecc);
        rApStr = 'N/A';
        rPeStr = [num2str(rPe), ' km'];
    end

    if(bodyInfo.sma == 0)
        rPeStr = 'N/A';
    end

    if(isempty(bodyInfo.parent))
        parentStr = 'N/A';
        rSOIStr = 'N/A';
        rSOI = Inf;
    else
        parentStr = bodyInfo.parent;

        rSOI = getSOIRadius(bodyInfo, parentBodyInfo);
        rSOIStr = [num2str(rSOI), ' km'];
    end

    sPhr = floor(bodyInfo.rotperiod/3600);
    sPmin = floor((bodyInfo.rotperiod - 3600*sPhr)/60);
    sPsec = bodyInfo.rotperiod - 3600*sPhr - 60*sPmin;
    sPStr = sprintf('%02.0f:%02.0f:%07.4f',sPhr,sPmin,sPsec);

    syncSMA = computeSMAFromPeriod(bodyInfo.rotperiod, bodyInfo.gm);
    if(syncSMA > rSOI)
        syncNotPoss = '*';
    else
        syncNotPoss = '';
    end

    bodyInfoStr{1} = ['Name: ', bodyInfo.name];
    bodyInfoStr{end+1} = ['ID: ', num2str(bodyInfo.id)];
    bodyInfoStr{end+1} = ['Parent: ', parentStr];
    bodyInfoStr{end+1} = hrule;

    bodyInfoStr{end+1} = 'Orbit';
    bodyInfoStr{end+1} = [' Epoch = ', dateStr];
    bodyInfoStr{end+1} = [' SMA = ', num2str(bodyInfo.sma), ' km'];
    bodyInfoStr{end+1} = [' Ecc = ', num2str(bodyInfo.ecc)];
    bodyInfoStr{end+1} = [' Inc = ', num2str(bodyInfo.inc), ' deg'];
    bodyInfoStr{end+1} = [' RAAN = ', num2str(bodyInfo.raan), ' deg'];
    bodyInfoStr{end+1} = [' Arg = ', num2str(bodyInfo.arg), ' deg'];
    bodyInfoStr{end+1} = [' Mean = ', num2str(bodyInfo.mean), ' deg'];
    bodyInfoStr{end+1} = hrule;

    bodyInfoStr{end+1} = 'Physical Properties';
    bodyInfoStr{end+1} = [' GM = ', num2str(bodyInfo.gm), ' km^3/s^2'];
    bodyInfoStr{end+1} = [' Radius = ', num2str(bodyInfo.radius), ' km'];
    bodyInfoStr{end+1} = [' Atmo Height = ', num2str(bodyInfo.atmohgt), ' km'];
    bodyInfoStr{end+1} = [' Atmo SL Press = ', num2str(getPressureAtAltitude(bodyInfo, 0)), ' kPa'];
    bodyInfoStr{end+1} = [' Sidereal Day = ', num2str(bodyInfo.rotperiod), ' sec'];
    bodyInfoStr{end+1} = ['              = ', sPStr];
    bodyInfoStr{end+1} = hrule;

    bodyInfoStr{end+1} = 'Derived';
    bodyInfoStr{end+1} = [' Orbit Period = ', periodStr];
    bodyInfoStr{end+1} = [' Orbit RPe = ', rPeStr];
    bodyInfoStr{end+1} = [' Orbit RAp = ', rApStr];
    bodyInfoStr{end+1} = [' SoI Radius = ', rSOIStr];
    bodyInfoStr{end+1} = [' Sync. SMA = ', num2str(syncSMA), ' km',syncNotPoss];

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

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

    % --- Executes when selected object is changed in dispAxesButtonGrp.
function dispAxesButtonGrp_SelectionChangeFcn(hObject, eventdata, handles)
    % hObject    handle to the selected object in dispAxesButtonGrp
    % eventdata  structure with the following fields (see UIBUTTONGROUP)
    %	EventName: string 'SelectionChanged' (read only)
    %	OldValue: handle of the previously selected object or empty if none was selected
    %	NewValue: handle of the currently selected object
    % handles    structure with handles and user data (see GUIDATA)
    catalogListbox_Callback(handles.catalogListbox, [], handles);

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


classdef (Abstract) extension < handle

%   MATPOWER
%   Copyright (c) 2022, Power Systems Engineering Research Center (PSERC)
%   by Ray Zimmerman, PSERC Cornell
%
%   This file is part of MATPOWER.
%   Covered by the 3-clause BSD License (see LICENSE file for details).
%   See https://matpower.org for more info.

%     properties
%     end     %% properties

    methods
        function task_class = task_class(obj, task_class, mpopt)
        end

        function dmc_class = dm_converter_class(obj, dmc_class, fmt, mpopt)
        end

        function dm_class = data_model_class(obj, dm_class, task_tag, mpopt)
        end

        function nm_class = network_model_class(obj, nm_class, task_tag, mpopt)
        end

        function mm_class = math_model_class(obj, mm_class, task_tag, mpopt)
        end

        function dmc_elements = dmc_element_classes(obj, dmc_class, fmt, mpopt)
            dmc_elements = {};      %% no modifications
        end

        function dm_elements = dm_element_classes(obj, dm_class, task_tag, mpopt)
            dm_elements = {};       %% no modifications
        end

        function nm_elements = nm_element_classes(obj, nm_class, task_tag, mpopt)
            nm_elements = {};       %% no modifications
        end

        function mm_elements = mm_element_classes(obj, mm_class, task_tag, mpopt)
            mm_elements = {};       %% no modifications
        end
    end     %% methods
end         %% classdef


function obj = meas(varargin)

% Constructor for meas class object.
% You must always pass one argument if you want to create a new object.

if nargin==0 % Used when objects are loaded from disk
  obj = init_fields;
  obj = class(obj, 'meas');
  return;
end

firstArg = varargin{1};
if isa(firstArg, 'meas') %  used when objects are passed as arguments
  obj = firstArg;
  return;
end

% We must always construct the fields in the same order,
% whether the object is new or loaded from disk.
% Hence we call init_fields to do this.
obj = init_fields;

% attach class name tag, so we can call member functions to
% do any initial setup
obj = class(obj, 'meas');

% Now the real initialization begins
obj.value = varargin{1};
obj.error = varargin{2};

return;
%%%%%%%%%

function obj = init_fields()
% Initialize all fields to dummy values
obj.value = [];
obj.error = [];


function varargout = process_select_tag( varargin )
% PROCESS_SELECT_TAG: Keep only the files within the current selection that have the specified tag in their filename.
%
% USAGE:  sProcess = process_select_tag('GetDescription')
%                    process_select_tag('Run', sProcess, sInputs)

% @=============================================================================
% This function is part of the Brainstorm software:
% https://neuroimage.usc.edu/brainstorm
%
% Copyright (c) University of Southern California & McGill University
% This software is distributed under the terms of the GNU General Public License
% as published by the Free Software Foundation. Further details on the GPLv3
% license can be found at http://www.gnu.org/copyleft/gpl.html.
%
% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE
% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY
% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY
% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.
%
% For more information type "brainstorm license" at command prompt.
% =============================================================================@
%
% Authors: Francois Tadel, 2012-2016

eval(macro_method);
end

%% ===== GET DESCRIPTION =====
function sProcess = GetDescription() %#ok<DEFNU>
    % Description the process
    sProcess.Comment     = 'Select files: By tag';
    sProcess.Category    = 'Custom';
    sProcess.SubGroup    = 'File';
    sProcess.Index       = 1013;
    sProcess.Description = 'https://neuroimage.usc.edu/brainstorm/SelectFiles';
    % Definition of the input accepted by this process
    sProcess.InputTypes  = {'raw', 'data', 'results', 'timefreq', 'matrix', 'pdata', 'presults', 'ptimefreq', 'pmatrix'};
    sProcess.OutputTypes = {'raw', 'data', 'results', 'timefreq', 'matrix', 'pdata', 'presults', 'ptimefreq', 'pmatrix'};
    sProcess.nInputs     = 1;
    sProcess.nMinFiles   = 1;
    sProcess.isSeparator = 0;
    % Definition of the options
    % === TARGET
    sProcess.options.tag.Comment = 'Search: ';
    sProcess.options.tag.Type    = 'text';
    sProcess.options.tag.Value   = '';
    % === FILENAME / COMMENT
    sProcess.options.label1.Comment = 'Where to look for:';
    sProcess.options.label1.Type    = 'label';
    sProcess.options.search.Comment = {'Search the file paths', 'Search the file names', 'Search the names of the parent file'};
    sProcess.options.search.Type    = 'radio';
    sProcess.options.search.Value   = 2;
    % === SELECT / IGNORE
    sProcess.options.label2.Comment = 'What to do with these files:';
    sProcess.options.label2.Type    = 'label';
    sProcess.options.select.Comment = {'Select only the files with the tag', 'Ignore the files with the tag'};
    sProcess.options.select.Type    = 'radio';
    sProcess.options.select.Value   = 1;
end

%% ===== FORMAT COMMENT =====
function Comment = FormatComment(sProcess) %#ok<DEFNU>
    % Option: Tag
    tag = strtrim(sProcess.options.tag.Value);
    if isempty(tag)
        tag = 'Not defined';
    end
    % Option: Filename/comment
    if isfield(sProcess.options, 'search') && isfield(sProcess.options.search, 'Value') && ~isempty(sProcess.options.search.Value)
        switch (sProcess.options.search.Value)
            case 1,  Method = 'filename';
            case 2,  Method = 'comment';
            case 3,  Method = 'parent';
        end
    else
        Method = 'comment';
    end
    % Option: Ignore/select
    if isfield(sProcess.options, 'select') && isfield(sProcess.options.select, 'Value') && ~isempty(sProcess.options.select.Value)
        isSelect = isequal(sProcess.options.select.Value, 1);
    else
        isSelect = 1;
    end
    % Assemble comment
    if isSelect
        Comment = 'Select';
    else
        Comment = 'Ignore';
    end
    switch (Method)
        case 'filename',  Comment = [Comment ' file paths with tag: ' tag];
        case 'comment',   Comment = [Comment ' file names with tag: ' tag];
        case 'parent',    Comment = [Comment ' parent names with tag: ' tag];
    end
end

%% ===== RUN =====
function OutputFiles = Run(sProcess, sInputs) %#ok<DEFNU>
    % Get new tag
    tag = sProcess.options.tag.Value;
    if isempty(tag)
        bst_report('Error', sProcess, [], 'Tag is not defined.');
        OutputFiles = {};
        return
    end
    % Error: no input files
    if isempty(sInputs)
        bst_report('Error', sProcess, [], 'No input files.');
        OutputFiles = {};
        return;
    end
    % Option: Filename/comment
    if isfield(sProcess.options, 'search') && isfield(sProcess.options.search, 'Value') && ~isempty(sProcess.options.search.Value)
        switch (sProcess.options.search.Value)
            case 1,  Method = 'filename';
            case 2,  Method = 'comment';
            case 3,  Method = 'parent';
        end
    else
        Method = 'comment';
    end
    % Option: Ignore/select
    if isfield(sProcess.options, 'select') && isfield(sProcess.options.select, 'Value') && ~isempty(sProcess.options.select.Value)
        isSelect = isequal(sProcess.options.select.Value, 1);
    else
        isSelect = 0;
    end

    % Search filenames/comments
    switch (Method)
        case 'filename'
            isTag = ~cellfun(@(c)isempty(strfind(upper(c),upper(tag))), {sInputs.FileName});
        case 'comment'
            isTag = ~cellfun(@(c)isempty(strfind(upper(c),upper(tag))), {sInputs.Comment});
        case 'parent'
            isTag = zeros(1, length(sInputs));
            upTag = upper(tag);
            % Search all the parent files one by one
            for i = 1:length(sInputs)
                % Do not go further if there is no parent
                if isempty(sInputs(i).DataFile)
                    continue;
                end
                % What to check depends on the file type
                switch (file_gettype(sInputs(i).DataFile))
                    case 'data'
                        % Find the file in database
                        [sStudy, iStudy, iData] = bst_get('DataFile', sInputs(i).DataFile, sInputs(i).iStudy);
                        % Check the comment
                        isTag(i) = ~isempty(strfind(upper(sStudy.Data(iData).Comment), upTag));
                    case {'results', 'link'}
                        % Find the file in database
                        [sStudy, iStudy, iResult] = bst_get('ResultsFile', sInputs(i).DataFile, sInputs(i).iStudy);
                        % Check the comment
                        isTag(i) = ~isempty(strfind(upper(sStudy.Result(iResult).Comment), upTag));
                        % If the file is not found but there is another parent level
                        if ~isTag(i) && ~isempty(sStudy.Result(iResult).DataFile) && strcmpi(file_gettype(sStudy.Result(iResult).DataFile), 'data')
                            [sStudy, iStudy, iData] = bst_get('DataFile', sStudy.Result(iResult).DataFile, sInputs(i).iStudy);
                            isTag(i) = ~isempty(strfind(upper(sStudy.Data(iData).Comment), upTag));
                        end
                    case 'matrix'
                        % Find the file in database
                        [sStudy, iStudy, iMatrix] = bst_get('MatrixFile', sInputs(i).DataFile, sInputs(i).iStudy);
                        % Check the comment
                        isTag(i) = ~isempty(strfind(upper(sStudy.Matrix(iMatrix).Comment), upTag));
                end
            end
    end
    % Ignore or select
    if isSelect
        iFiles = find(isTag);
    else
        iFiles = find(~isTag);
    end
    % Warning: nothing found
    if isempty(iFiles)
        bst_report('Error', sProcess, [], ['No files found for tag: ' tag]);
        OutputFiles = {};
        return;
    end
    % Report information
    strReport = sprintf('Files selected for tag "%s": %d/%d', tag, length(iFiles), length(sInputs));
    bst_report('Info', sProcess, [], strReport);
    % Return only the filenames that have the specific tag
    OutputFiles = {sInputs(iFiles).FileName};
end


%  INTERNAL FUNCTION
%
%  See also: UTILS.CODE.CODE2VECTOR
%


function okay = vgg_mexcompile(funcName, varargin)
%VGG_MEXCOMPILE  Mex compile helper function
%
%   okay = vgg_mexcompile(funcName)
%   okay = vgg_mexcompile(..., sourceList)
%   okay = vgg_mexcompile(..., lastCompiled)
%
% Compile mexed function, given an optional list of source files. Can
% optionally check if source files have been modified since the last
% compilation, and only compile if they have.
%
%IN:
%   funcName - string containg the name of the function to compile
%   sourceList - cell array of source files to be compiled. Default:
%                {[funcName '.cxx']}.
%   lastCompiled - datenum of the current mex file. Default: 0 (i.e. force
%                  compilation).
%
%OUT:
%   okay - 1: function compiled; 0: up-to-date, no need to compile; -1:
%          compilation failed.

% $Id: vgg_mexcompile.m,v 1.3 2009/09/13 20:34:58 ojw Exp $

% Set defaults for optional inputs
sourceList = [funcName '.cxx'];
lastCompiled = 0;
% Parse inputs
for a = 1:numel(varargin)
   if iscell(varargin{a}) && ischar(varargin{a}{1})
       sourceList = varargin{a};
   elseif isnumeric(varargin{a}) && isscalar(varargin{a})
       lastCompiled = varargin{a};
   end
end

% Go to the directory containing the file
currDir = cd;
sourceDir = fileparts(which(funcName));
cd(sourceDir);

if lastCompiled
    compile = false;
    okay = 0;
    % Compile if current mex file is older than any of the source files
    for a = 1:numel(sourceList)
        dirSource = dir(sourceList{a});
        if ~isempty(dirSource) && datenum(dirSource.date) > lastCompiled
            compile = true;
            break;
        end
    end
else
    compile = true;
end

% Compile if we need to
if compile
    % Set the compiler flags
    flags = ['-O -I"' sourceDir '"'];
    switch mexext
        case 'mexsol'
            flags = [flags ' CC=gcc CFLAGS=-fPIC'];
        case {'mexglx', 'mexa64'}
            str = '"-O3 -ffast-math -funroll-loops"';
            flags = sprintf('%s CXXOPTIMFLAGS=%s LDCXXOPTIMFLAGS=%s LDOPTIMFLAGS=%s', flags, str, str, str);
        otherwise
    end

    % Call mex to compile the code
    cmd = sprintf('mex %s%s', flags, sprintf(' "%s"', sourceList{:}));
    disp(cmd);
    try
        eval(cmd);
        okay = 1;
    catch
        okay = -1;
        fprintf('ERROR while compiling %s\n', funcName);
    end
end

% Return to the original directory
cd(currDir);
return


function obj = modelBatchCopyFiles(obj)
	% Copies files from folders to a specific other folder.
	% Biafra Ahanonu
	% 2015.09.01 [21:36:38]
	%
	% inputs
		%
	% outputs
		%

	% changelog
		% 2021.08.10 [09:57:36] - Updated to handle CIAtah v4.0 switch to all functions inside ciapkg package.
	% TODO
		%

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

	% get user input
	movieSettings = inputdlg({...
			'start:end frames (leave blank for all)',...
			'file regexp:',...
			'copy to specific folder (leave blank to copy to same folder)',...
			'input HDF5 dataset name',...
			'output HDF5 dataset name',...
			'analyzing movie files (1 = yes, 0 = no):',...
			'back-up directory name (if copying into same folder)',...
			'name of new extension for movie (include leading dot, leave blank if keep the same)',...
			'append folder base string (blank if no)'...
		},...
		'copy files to /archive/ folder',1,...
		{...
			'1:4000',...
			obj.fileFilterRegexp,...
			'',...
			obj.inputDatasetName,...
			obj.inputDatasetName,...
			'1',...
			'archive',...
			'',...
			''...
		}...
	);
	setNo = 1;
	frameList = str2num(movieSettings{setNo});setNo = setNo+1;
	fileFilterRegexp = movieSettings{setNo};setNo = setNo+1;
	saveSpecificFolder = movieSettings{setNo};setNo = setNo+1;
	inputDatasetName =  movieSettings{setNo};setNo = setNo+1;
	outputDatasetName =  movieSettings{setNo};setNo = setNo+1;
	analyzeMovieFiles =  str2num(movieSettings{setNo});setNo = setNo+1;
	backupDirName =  movieSettings{setNo};setNo = setNo+1;
	newExtensionName =  movieSettings{setNo};setNo = setNo+1;
	useBaseFolderName =  movieSettings{setNo};setNo = setNo+1;

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

	% loop over all directories and copy over a specified chunk of the movie file
	for thisFileNumIdx = 1:nFilesToAnalyze
			thisFileNum = fileIdxArray(thisFileNumIdx);
			obj.fileNum = thisFileNum;
			display(repmat('=',1,21))
			display([num2str(thisFileNumIdx) '/' num2str(nFilesToAnalyze) ' (' num2str(thisFileNum) '/' num2str(nFiles) '): ' obj.fileIDNameArray{obj.fileNum}]);
			% =====================
			switch analyzeMovieFiles
				case 1
					% load the movie
					movieList = getFileList(obj.inputFolders{obj.fileNum}, fileFilterRegexp);
					% movieList = movieList{1};
					nMovies = length(movieList);
					for movieNo = 1:nMovies
						moviePath = movieList{movieNo};
						if isempty(frameList)
							frameListTmp = frameList;
						else
							movieDims = loadMovieList(moviePath,'convertToDouble',0,'frameList',[],'inputDatasetName',inputDatasetName,'treatMoviesAsContinuous',1,'loadSpecificImgClass','single','getMovieDims',1);
							frameListTmp = frameList;
							% remove frames that are too large
							frameListTmp(frameListTmp>=movieDims.z) = [];
						end

						% create directory in other root
						if isempty(saveSpecificFolder)
							% move movie to archive folder if copying to the same folder then move file
							archivePath = [obj.inputFolders{obj.fileNum} filesep backupDirName];
							mkdir(archivePath);
							[PATHSTR,NAME,EXT] = fileparts(moviePath);
							archivePathFile = [archivePath filesep NAME EXT];
							display(['moving' num2str(movieNo) '/' num2str(nMovies) ': ' moviePath ' TO ' archivePathFile]);
							% movefile(moviePath,archivePathFile);
							if ispc
								dos(['move ' moviePath ' ' archivePathFile]);
							elseif isunix
								unix(['mv ' moviePath ' ' archivePathFile]);
							end
							newPathFile = moviePath;
							moviePath = archivePathFile;
						else
							[PATHSTR,NAME,EXT] = fileparts(obj.inputFolders{obj.fileNum});
							newPath = [saveSpecificFolder filesep NAME];
							mkdir(newPath)
							[PATHSTR,NAME,EXT] = fileparts(moviePath);
							newPathFile = [newPath filesep NAME EXT];
						end

						[primaryMovie] = loadMovieList(moviePath,'convertToDouble',0,'frameList',frameListTmp(:),'inputDatasetName',inputDatasetName);

						if ~isempty(newExtensionName)
							[PATHSTR,NAME,EXT] = fileparts(newPathFile);
							newPathFile = [PATHSTR filesep NAME newExtensionName];
						end

						if ~isempty(useBaseFolderName)
							[PATHSTR,NAME,EXT] = fileparts(newPathFile);
							newPathFile = [PATHSTR filesep obj.folderBaseSaveStr{obj.fileNum} '_' NAME EXT];
						end

						% save the file in the new location
						[output] = writeHDF5Data(primaryMovie,newPathFile,'datasetname',outputDatasetName);
					end
					% body
				case 0
					% load the movie
					fileList = getFileList(obj.inputFolders{obj.fileNum}, fileFilterRegexp);
					nFiles = length(fileList);
					for fileNo = 1:nFiles
						filePath = fileList{fileNo};
						% create directory in other root
						if isempty(saveSpecificFolder)
							% move files to folder in current directory
							archivePath = [obj.inputFolders{obj.fileNum} filesep backupDirName];
							mkdir(archivePath);
							[PATHSTR,NAME,EXT] = fileparts(filePath);
							archivePathFile = [archivePath filesep NAME EXT];
							display(['moving' num2str(fileNo) '/' num2str(nFiles) ': ' filePath ' TO ' archivePathFile]);
							% movefile(filePath,archivePathFile);
							if ispc
								dos(['move ' filePath ' ' archivePathFile]);
							elseif isunix
								unix(['mv ' filePath ' ' archivePathFile]);
							end
							newPathFile = filePath;
							filePath = archivePathFile;
						else
							[PATHSTR,NAME,EXT] = fileparts(obj.inputFolders{obj.fileNum});
							newPath = [saveSpecificFolder filesep NAME];
							mkdir(newPath)
							[PATHSTR,NAME,EXT] = fileparts(filePath);
							newPathFile = [newPath filesep NAME EXT];
							display(['copying' num2str(fileNo) '/' num2str(nFiles) ': ' filePath ' TO ' newPathFile]);
							if ispc
								dos(['copy ' filePath ' ' newPathFile]);
							elseif isunix
								unix(['cp ' filePath ' ' newPathFile]);
							end
						end
					end
				otherwise
					% body
			end
	end

end


classdef SettingsLevelSetHorizontalFibers < SettingsLevelSetCreator

    properties (Access = public)
        levelOfFibers
        volume
    end

    methods (Access = public)

        function obj = SettingsLevelSetHorizontalFibers(varargin)
            obj.loadParams('paramsLevelSetCreator_HorizontalFibers.json')
            if nargin == 1
                obj.loadParams(varargin{1})
            end
        end

    end

end


fprintf('** building frne mex file\n');

mex frne.c ne.c vmath.c