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

% Last Modified by GUIDE v2.5 21-Jan-2019 11:37:06

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

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

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

    populateGUI(handles, lvdData);

    % Update handles structure
    guidata(hObject, handles);

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

function populateGUI(handles, lvdData)
    set(handles.connsListBox,'String',lvdData.launchVehicle.getTankToTankConnectionsListBoxStr());

% --- Outputs from this function are returned to the command line.
function varargout = lvd_EditTankToTankConnsGUI_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} = [];
    else
        close(handles.lvd_EditTankToTanksConnsGUI);
    end

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

% --- Executes on selection change in connsListBox.
function connsListBox_Callback(hObject, eventdata, handles)
% hObject    handle to connsListBox (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 connsListBox contents as cell array
%        contents{get(hObject,'Value')} returns selected item from connsListBox
    if(strcmpi(get(handles.lvd_EditTankToTanksConnsGUI,'SelectionType'),'open'))
        lvdData = getappdata(handles.lvd_EditTankToTanksConnsGUI,'lvdData');
        lv = lvdData.launchVehicle;

        [~,t2TConns] = lvdData.launchVehicle.getTankToTankConnectionsListBoxStr();

        if(~isempty(t2TConns))
            selT2TConn = get(handles.connsListBox,'Value');
            t2TConn = lv.getTankToTankForInd(selT2TConn);

            lvd_EditTankToTankConnGUI(t2TConn);

            lvState = lvdData.initStateModel.lvState;
            connState = lvState.getTank2TankConnStateForConn(t2TConn);
            connState.flowRate = t2TConn.initFlowRate;

            set(handles.connsListBox,'String',lvdData.launchVehicle.getTankToTankConnectionsListBoxStr());
        end
    end

% --- Executes during object creation, after setting all properties.
function connsListBox_CreateFcn(hObject, eventdata, handles)
% hObject    handle to connsListBox (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 addConnButton.
function addConnButton_Callback(hObject, eventdata, handles)
% hObject    handle to addConnButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    lvdData = getappdata(handles.lvd_EditTankToTanksConnsGUI,'lvdData');

    tempSrcTank = lvdData.launchVehicle.getTankForInd(1);
    tempTgtTank = LaunchVehicleTank.empty(1,0);

    t2TConn = TankToTankConnection(tempSrcTank, tempTgtTank);
    useT2TConn = lvd_EditTankToTankConnGUI(t2TConn);

    if(useT2TConn)
        lvdData.launchVehicle.addTankToTankConnection(t2TConn);

        lvState = lvdData.initStateModel.lvState;
        connState = TankToTankConnState(t2TConn);
        connState.flowRate = t2TConn.initFlowRate;
        lvState.addT2TConnState(connState);

        set(handles.connsListBox,'String',lvdData.launchVehicle.getTankToTankConnectionsListBoxStr());
    end

% --- Executes on button press in removeConnButton.
function removeConnButton_Callback(hObject, eventdata, handles)
% hObject    handle to removeConnButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    lvdData = getappdata(handles.lvd_EditTankToTanksConnsGUI,'lvdData');
    lv = lvdData.launchVehicle;

    selConn = get(handles.connsListBox,'Value');
    conn = lv.getTankToTankForInd(selConn);

    tf = conn.isInUse();

    if(tf == false)
        lvState = lvdData.initStateModel.lvState;
        lvState.removeT2TConnStateForConn(conn);

        lv.removeTankToTankConnection(conn);

        listBoxStr = lvdData.launchVehicle.getTankToTankConnectionsListBoxStr();
        set(handles.connsListBox,'String',listBoxStr);

        numConns = length(listBoxStr);
        if(numConns == 0)
            handles.connsListBox.String = ' ';
            set(handles.connsListBox,'Value',1);
        elseif(selConn > numConns)
            set(handles.connsListBox,'Value',numConns);
        end
    else
        warndlg(sprintf('Could not delete the "%s" connection because it is in use as part of an event termination condition, event action, objective function, or constraint.  Remove the dependencies before attempting to delete the connection.', conn.getName()),'Cannot Delete Connection','modal');
    end

% --- Executes on key press with focus on lvd_EditTankToTankConnsGUI or any of its controls.
function lvd_EditTankToTanksConnsGUI_WindowKeyPressFcn(hObject, eventdata, handles)
% hObject    handle to lvd_EditTankToTankConnsGUI (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'
            uiresume(handles.lvd_EditTankToTanksConnsGUI);
        case 'enter'
            uiresume(handles.lvd_EditTankToTanksConnsGUI);
        case 'escape'
            uiresume(handles.lvd_EditTankToTanksConnsGUI);
    end


function hRD = plugin_rd_rxtx
% Reference design definition

%   Copyright 2014-2015 The MathWorks, Inc.

% Call the common reference design definition function
hRD = AnalogDevices.fmcomms5.common.plugin_rd('ZC702', 'Rx & Tx');
AnalogDevices.fmcomms5.zc702.add_io(hRD,'Rx & Tx');


%GetNextItem - Get next item from a Batch object (iterator mode).
%
% This is a helper class to easily read and parse batch files.
%
%  USAGE
%
%    [b,item,line] = GetNextItem(b);
%
%    b              batch object

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

function [b,item,line] = GetNextItem(b)

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

b.currentItem = b.currentItem+1;
b.currentField = 0;
if b.currentItem > size(b.field,1),
	item = [];
	line = [];
else
	item = b.currentItem;
	line = b.line(item);
end


function value = get_field_value(structure, name, default)

if ~isstruct(structure) || ~isfield(structure, name)
    value = default;
    return;
end;

value = structure.(name);


function panel = BstPanel( varargin )
% Constructor for object BstPanel.
% A BstPanel object holds mainly a java Swing container to be displayed in the
% Brainstorm main window.
%
% Constructor call :
%     BstPanel(name, jHandle, sControls)
%     BstPanel() : just to have a data template
%
% Data structure
%   - jHandle    : java handle to a javax.swing.JComponent object (panel handle)
%   - name       : string identifier to index and display this panel
%   - container  : string identifier of the panel container in which it should be displayed
%   - sControls  : list of the useful controls of the panel

% @=============================================================================
% 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-2010

% Parse inputs
if (nargin == 0)
    % Create an empty object (template to create structures)
    panel.jHandle    = [];
    panel.name       = '';
    panel.container  = struct('type',   '', ...
                              'handle', {});
    panel.sControls  = [];
    panel = class(panel, 'BstPanel');
    panel = repmat(panel, 0);
    return;
elseif (nargin == 3)
    name       = varargin{1};
    jHandle    = varargin{2};
    sControls  = varargin{3};
else
    error('Usage : BstPanel(name, jHandle, sControls)');
end

% Check inputs
if (~isa(jHandle, 'javax.swing.JComponent'))
    error('First argument ''jHandle'' must be a javax.swing.JComponent object');
elseif (~ischar(name))
    error('Second argument ''name'' must be a Matlab string');
elseif (~isstruct(sControls) && ~isempty(sControls))
    error('Third argument ''sControls'' must be a structure of Java Swing controls');
end
% Check intergrity of the structure sControls
if (isempty(sControls))
    sControls = struct();
end

% Create data structure
panel.jHandle          = jHandle;
panel.name             = name;
panel.container.type   = '';
panel.container.handle = {};
panel.sControls        = sControls;
% Set object class
panel = class(panel, 'BstPanel');


function DoEditValue(handles,parent_handle,Attributes,AttrhNumber,dims)

% Create Editbox for adjusting attributes at the frame given by parent_handle
% special mark
% '$value' ----popupmenu
% '^value' ----checkbox
% '@' ----static text

TextW=dims(1);
EditW=dims(2);
SpaceW=dims(3);
TextH=dims(4);
EditH=dims(5);
SpaceH=dims(6);

%--old schema
% switch get(parent_handle,'Type')
%     case 'uitab'
%         Position=get(get(get(parent_handle,'Parent'),'Parent'),'Position');
%     case 'uipanel'
%         Position=get(parent_handle,'Position');
% end
% Hpair=floor(Position(4)/(TextH+SpaceH));
% Wpair=floor(Position(3)/(TextW+SpaceW));
%--end

Hpair=floor(1/(TextH+SpaceH));
Wpair=floor(1/(TextW+SpaceW));
ind=1;
for j=1:Wpair
    for i=1:Hpair
        if ind<=length(Attributes)
            Attrh.([Attributes(ind).Name 'Text'])=uicontrol(parent_handle,'Style', 'text', 'String', Attributes(ind).Name,'FontWeight','bold','Units','normalized',...
                                                                    'Position', [(j-1)*(TextW+SpaceW+EditW) (i-1)*(TextH+SpaceH) TextW TextH],...
                                                                    'TooltipString', DoTellMeInfo(Attributes(ind).Name));
            eval(['handles.Attrh' num2str(AttrhNumber) '.' Attributes(ind).Name 'Text=Attrh.' Attributes(ind).Name 'Text;']);
            if ~isempty(Attributes(ind).Value)
                switch Attributes(ind).Value(1)
                    case '$'
                        eval(['AttributeOpt={' Attributes(ind).Value(3:end) '};']);
                        Attrh.(Attributes(ind).Name)=uicontrol(parent_handle,'Style', 'popupmenu', 'String', AttributeOpt,'BackgroundColor',[1 1 1],...
                                                                        'Value',str2double(Attributes(ind).Value(2)),'Units','normalized',...
                                                                        'Position', [(j-1)*(TextW+SpaceW+EditW)+TextW (i-1)*(TextH+SpaceH) EditW EditH],...
                                                                        'TooltipString',['Default: ' Attributes(ind).Value(2:end)]);
                        eval(['handles.Attrh' num2str(AttrhNumber) '.' Attributes(ind).Name '=Attrh.' Attributes(ind).Name ';']);
                    case '^'
                        Attrh.(Attributes(ind).Name)=uicontrol(parent_handle,'Style', 'checkbox', 'String',[],'BackgroundColor',[1 1 1],...
                                                                        'Value',str2double(Attributes(ind).Value(2)),'Units','normalized',...
                                                                        'Position', [(j-1)*(TextW+SpaceW+EditW)+TextW (i-1)*(TextH+SpaceH) EditW EditH],...
                                                                        'TooltipString',['Default: ' Attributes(ind).Value(2:end)]);
                        eval(['handles.Attrh' num2str(AttrhNumber) '.' Attributes(ind).Name '=Attrh.' Attributes(ind).Name ';']);
                    case '@'
                        eval(['AttributeOpt=' Attributes(ind).Value(2:end) ';']);
                        Attrh.(Attributes(ind).Name)=uicontrol(parent_handle,'Style', 'text', 'String',AttributeOpt,'Units','normalized',...
                                                                        'Position', [(j-1)*(TextW+SpaceW+EditW)+TextW (i-1)*(TextH+SpaceH) EditW EditH],...
                                                                        'TooltipString',['Default: ' AttributeOpt]);
                        eval(['handles.Attrh' num2str(AttrhNumber) '.' Attributes(ind).Name '=Attrh.' Attributes(ind).Name ';']);
                    otherwise
                        Attrh.(Attributes(ind).Name)=uicontrol(parent_handle,'Style', 'edit', 'String', Attributes(ind).Value,'Units','normalized','BackgroundColor',[1 1 1],...
                                                                    'Position', [(j-1)*(TextW+SpaceW+EditW)+TextW (i-1)*(TextH+SpaceH) EditW EditH],...
                                                                    'TooltipString',['Default: ' Attributes(ind).Value]);
                        eval(['handles.Attrh' num2str(AttrhNumber) '.' Attributes(ind).Name '=Attrh.' Attributes(ind).Name ';']);
                end
            else
                Attrh.(Attributes(ind).Name)=uicontrol(parent_handle,'Style', 'edit', 'String', Attributes(ind).Value,'Units','normalized','BackgroundColor',[1 1 1],...
                                                                    'Position', [(j-1)*(TextW+SpaceW+EditW)+TextW (i-1)*(TextH+SpaceH) EditW EditH],...
                                                                    'TooltipString',['Default: ' Attributes(ind).Value]);
                eval(['handles.Attrh' num2str(AttrhNumber) '.' Attributes(ind).Name '=Attrh.' Attributes(ind).Name ';']);
            end
        end
        ind=ind+1;
    end
end
guidata(parent_handle,handles);
end


function lbl = loadLbl(lbl_file)

tname = tempname;
mkdir(tname);
try
  fprintf('Untarring project into %s\n',tname);
  untar(lbl_file,tname);
  fprintf('... done with untar.\n');
  rawLblFile = fullfile(tname,'label_file.lbl');
catch ME
  if strcmp(ME.identifier,'MATLAB:untar:invalidTarFile') || ...
      strcmp(ME.identifier,'MATLAB:io:archive:untar:invalidTarFile')
    warningNoTrace('Label file %s is not bundled. Using it in raw (mat) format.',lbl_file);
    rawLblFile = lbl_file;
  else
    ME.rethrow();
  end
end

warning('off','MATLAB:load:classNotFound');
warning('off','MATLAB:load:cannotInstantiateLoadedVariable');
lbl = load(rawLblFile,'-mat');
warning('on','MATLAB:load:classNotFound');
warning('on','MATLAB:load:cannotInstantiateLoadedVariable');

[success, message, ~] = rmdir(tname,'s');
if ~success
  error('Could not clear the temp directory %s\n',message);
else
  fprintf('Cleared out temp directory %s\n',tname);
end


function copyFolderContents(pnamesrc, pnamedst)

copyfile([pnamesrc, '/*'], pnamedst);
copyfile([pnamesrc, '/*.*'], pnamedst);
copyfile([pnamesrc, '/.*'], pnamedst);


function [fnames, defaults] = mysubs_fields

% function [fnames, defaults] = mysubs_fields
% Additional fields for class cfg_branch. See help of
% @cfg_item/subs_fields for general help about this function.
%
% This code is part of a batch job configuration system for MATLAB. See
%      help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging

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

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

fnames={};
defaults={};


function varargout = ft_version(command)

% FT_VERSION returns the version of FieldTrip and the path where it is installed
%
% FieldTrip is not released with version numbers as "2.0", "2.1", etc. Instead, we
% share our development version on http://github.com/fieldtrip/fieldtrip. You can use
% git to make a local clone of the development version. Furthermore, we make
% more-or-less daily releases of the code available on
% https://github.com/fieldtrip/fieldtrip/releases and as zip file on our FTP server.
%
% If you use git with the development version, the version is labeled with the hash
% of the latest commit like "128c693". You can access the specific version "XXXXXX"
% at https://github.com/fieldtrip/fieldtrip/commit/XXXXXX.
%
% If you download the daily released version from our FTP server, the version is part
% of the file name "fieldtrip-YYYYMMDD.zip", where YYY, MM and DD correspond to year,
% month and day.
%
% Use as
%   ft_version
% to display the latest revision number on screen, or
%   [ftver, ftpath] = ft_version
% to get the version and the installation root directory.
%
% When using git with the development version, you can also get additional information with
%   ft_version revision
%   ft_version branch
%   ft_version clean
%
% See also FT_PLATFORM_SUPPORTS, VERSION, VER, VERLESSTHAN

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

persistent issvn
persistent isgit
persistent ftver
persistent ftpath
persistent is_pc

if isempty(is_pc)
  is_pc = ispc;
end

if isempty(ftpath)
  ftpath = fileparts(mfilename('fullpath'));
  ftpath = ftpath(1:end-10); % strip away '/utilities' where this function is located
end

% set the defaults
clean = 'no';
branch = 'unknown';

if is_pc
  % this requires a file extension
  ext = '.exe';
else
  ext = '';
end

if isempty(issvn)
  % are we dealing with an SVN working copy of FieldTrip?
  issvn = isfolder(fullfile(ftpath, '.svn'));
end

if isempty(isgit)
  % are we dealing with an GIT working copy of FieldTrip?
  isgit = exist(fullfile(ftpath, '.git'), 'file');
  % is the git command line executable available?
  if isgit
    [status, output] = system(sprintf('git%s --version', ext));
    if status>0
      if ~is_pc
        % the git command line executable will probably not be available on windows
        ft_warning('you seem to have an GIT development copy of FieldTrip, yet ''git'' does not work as expected');
      end
      isgit = false;
    end
  end
end

if nargin<1
  % this is only supported for git
  command = 'revision';
end

if ~isempty(ftver) && ~isempty(ftpath) && nargin<1
  % use the previously determined values

elseif issvn
  % use svn system call to determine latest revision
  [status, output] = system(sprintf('cd %s && svn%s info', ftpath, ext));
  if status > 0
    if ~is_pc
      % the command line tools will probably not be available on windows
      ft_warning('you seem to have an SVN development copy of FieldTrip, yet ''svn info'' does not work as expected');
    end
    ftver = 'unknown';
  else
    rev = regexp(output, 'Revision: (.*)', 'tokens', 'dotexceptnewline');
    rev = rev{1}{1};
    ftver = ['r' rev];
  end

elseif isgit
  % use git system call to determine latest revision
  switch command
    case 'revision'
      [status, output] = system(sprintf('cd %s && git%s rev-parse --short HEAD', ftpath, ext));
      ftver = strtrim(output); % remove trailing newline character
    case 'branch'
      [status, output] = system(sprintf('cd %s && git%s rev-parse --abbrev-ref HEAD', ftpath, ext));
      branch = strtrim(output); % remove trailing newline character
    case 'clean'
      [status, output] = system(sprintf('cd %s && git%s diff --quiet --exit-code', ftpath, ext));
      if status
        clean = 'no';
      else
        clean = 'yes';
      end
    otherwise
      ft_error('unsupported command "%s"', command);
  end % switch command

elseif isequal(regexp(ftpath, ['.*\' filesep '[fF]ieldtrip-fieldtrip-[[0-9][a-z]]{7}']), 1)
  % this corresponds with being downloaded from the Mathworks file exchange link to github
  % which results in a ftpath like /Users/robert/matlab/fieldtrip-fieldtrip-851478d
  ftver = ftpath(end-6:end);

elseif isequal(regexp(ftpath, ['.*\' filesep '[fF]ieldtrip-20[0-9]{6}']), 1)
  % this corresponds with the daily version from the ftp server
  % which results in a ftpath like /Users/robert/matlab/fieldtrip-20160317
  ftver = ftpath(end-7:end);

elseif isequal(regexp(ftpath, ['.*\' filesep '[fF]ieldtrip-lite20[0-9]{6}']), 1)
  % this corresponds with the daily version from the ftp server
  % which results in a ftpath like /Users/robert/matlab/fieldtrip-20160317
  ftver = ftpath(end-7:end);

else
  % get it from the Contents.m file in the FieldTrip directory
  if ~isdeployed
    tmp = ver(ftpath);
    ftver = tmp.Version;
  else
    ftver = 'deployed';
  end
end % if issvn, isgit or otherwise

if ~nargout
  switch command
    case 'revision'
      fprintf('\nThis is FieldTrip, revision %s.\n\n', ftver);
    case 'branch'
      fprintf('\nThis is FieldTrip, branch %s.\n\n', branch);
    case 'clean'
      fprintf('\nThis is FieldTrip, clean %s.\n\n', clean);
  end
else
  switch command
    case 'revision'
      varargout = {ftver, ftpath};
    case 'branch'
      varargout = {branch};
    case 'clean'
      varargout = {clean};
  end
end


function ok = all_set_item(item)

% function ok = all_set_item(item)
% Perform within-item all_set check. For generic items, this is the same
% as all_set.
%
% This code is part of a batch job configuration system for MATLAB. See
%      help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging

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

rev = '$Rev: 1716 $'; %#ok
ok = all_set(item);


function cfg = save_large_cfg_fields(cfg, highest_ft, reproducescript_dir, nowtime)

% SAVE_LARGE_CFG_FIELDS is a helper function for ft_postamble_savevar and ft_postamble_savefig, and
% is used for the cfg.reproducescript functionality.

fn = ignorefields('recursesize');
for i=1:numel(fn)
  if isfield(cfg.callinfo.usercfg, fn{i}) && isstruct((cfg.callinfo.usercfg.(fn{i})))
    outputfile = make_or_fetch_inputfile(reproducescript_dir,...
      sprintf('%s_%s_input_%s.mat', nowtime, highest_ft, ...
      fn{i}), fn{i}, cfg.callinfo.usercfg.(fn{i}));
    cfg.callinfo.usercfg.(fn{i})  = outputfile;
  end
end

end


function styleLabelAsValid(hLabel,validStr)
%styleLabelAsValid Summary of this function goes here
%   Detailed explanation goes here
    lblStr = strWrapForLabel(hLabel, validStr);

    set(hLabel,'Visible','on');
    set(hLabel,'BackgroundColor',[34,139,34]/255);
    set(hLabel,'ForegroundColor',[1,1,1]);
    set(hLabel,'String',lblStr);
    set(hLabel,'TooltipString','');
    set(hLabel,'FontWeight','bold');

    setappdata(hLabel,'tooltipstring',validStr);
end


classdef SettingsElementalDensity < AbstractSettings
    properties
        filterParams = SettingsFilterP0()
        levelSetCreatorParams = SettingsLevelSetCreator()
    end
    methods
    end
end


function hDataTip = createDataTipROE(hFig,target)
% Create new datatip or expand existing one.
%
% AI 10/15/21

ud = guidata(hFig);
cMode = datacursormode(hFig);
cursorInfoS = getCursorInfo(cMode);
%target = protS(pNum).(selTypeC{k})(selNum);

%Check if datatip exists
if ~isfield(ud.handle,'datatips')
    ud.handle.datatips = [];
end

evt.Target = target;
evt.Position = [evt.Target.XData(1),evt.Target.YData(1)];

existing = 0;
for c = 1:length(cursorInfoS)
    if isequal(get(cursorInfoS(c).Target,'userdata'),...
            get(evt.Target,'userdata'))
        hDataTip = ud.handle.datatips(c);
        guidata(hFig,ud);
        expandDataTipROE(hDataTip,evt,hFig);
        existing = 1;
        break
    end
end
if ~existing
    hDataTip = cMode.createDatatip(target);
    set(hDataTip,'Marker','^','OrientationMode','Manual',...
        'Tag','criteria','userdata',get(target,'userdata'),'UpdateFcn',...
        @(hObj,hEvt)expandDataTipROE(hObj,hEvt,hFig)); %'MarkerSize,',7,
    ud.handle.datatips = [ud.handle.datatips,hDataTip];
    guidata(hFig,ud);
    expandDataTipROE(hDataTip,evt,hFig);
end

end


function [statusBoxMsg] = setINIStatusBoxMsg()
%setINIStatusBoxMsg Summary of this function goes here
%   Detailed explanation goes here

    statusBoxMsg = {['KSP Trajectory Optimization Tool v', getKSPTOTVersionNumStr(), sprintf(' (R%s)', version('-release'))], 'Written By Arrowstar (C) 2022', statusBoxHR()};
end


classdef InstallDriverBase < matlab.hwmgr.internal.hwsetup.TemplateBase

%   Copyright 2017 The MathWorks, Inc.

  properties
    InfoText1
    InfoText2
    InfoText3
  end

  methods
    function obj = InstallDriverBase(varargin)
      obj@matlab.hwmgr.internal.hwsetup.TemplateBase(varargin{:});

      obj.Workflow.InstallDriverWorkflow = true;

      parentContainer = obj.ContentPanel;

      obj.InfoText1 = matlab.hwmgr.internal.hwsetup.Label.getInstance(parentContainer);
      obj.InfoText1.Position = [20 290 400 80];
      obj.InfoText1.Text = '';
      obj.InfoText1.Color = matlab.hwmgr.internal.hwsetup.util.Color.WHITE;

      obj.InfoText2 = matlab.hwmgr.internal.hwsetup.Label.getInstance(parentContainer);
      obj.InfoText2.Position = [20 230 400 50];
      obj.InfoText2.Text = '';
      obj.InfoText2.Color = matlab.hwmgr.internal.hwsetup.util.Color.WHITE;

      obj.InfoText3 = matlab.hwmgr.internal.hwsetup.Label.getInstance(parentContainer);
      obj.InfoText3.Position = [20 170 400 50];
      obj.InfoText3.Text = '';
      obj.InfoText3.Color = matlab.hwmgr.internal.hwsetup.util.Color.WHITE;

      obj.HelpText.AboutSelection = '';
      obj.HelpText.WhatToConsider = '';

      if strcmp(obj.Workflow.FirstScreenID, class(obj))
        obj.BackButton.Visible = 'off';
        obj.BackButton.Enable = 'off';
      end
    end

    function restoreScreen(obj)
      obj.enableScreen();
    end
  end

  methods (Access = protected, Abstract)
    status = installDriverImpl(obj)
  end

  methods (Access = protected)
    function installDriver(obj)
      obj.disableScreen();
      restoreOnCleanup = onCleanup(@obj.restoreScreen);

      p = matlab.hwmgr.internal.hwsetup.Panel.getInstance(obj.ContentPanel);
      p.Title = '';
      b = matlab.hwmgr.internal.hwsetup.BusyOverlay.getInstance(p);
      b.Text = 'Installing USB driver...';
      b.show();
      deleteOverlayOnCleanup = onCleanup(@()delete(p));

      [status,msg] = installDriverImpl(obj);

      if status
        error(message('plutoradio:hwsetup:DriverInstallFailed', msg));
      end

      refocus(obj.Workflow);
    end

    function out = getNextScreenIDImpl(obj)
      out = 'adi.ConnectHardware';
      installDriver(obj);
    end
  end
end


function biosigpathlast

str2doublepath = fileparts( which('str2double') );
sopenpath      = fileparts( which('sopen') );
if strcmp(str2doublepath,sopenpath)
    rmpath(str2doublepath);
    str2doublepat2 = fileparts( which('str2double') );
    addpath(str2doublepath,'-begin');
    addpath(str2doublepat2,'-begin');
end


function  bzip2Matlab

% This function prompts the user to select a file via gui method
%   If the file ends with *.bz2 suffix
 %      function assumes the file is compressed and will uncompress it
 %      using bzip2
%   Else if the file ends with any other suffix
 %      function attempts to compress it using bzip2
 %  The objective is easier handlng of compressed files in Matlab
%  LM AIB 11/24/2002

% copyright (c) 2001-2006, Washington University in St. Louis.
% Permission is granted to use or modify only for non-commercial,
% non-treatment-decision applications, and further only if this header is
% not removed from any file. No warranty is expressed or implied for any
% use whatever: use at your own risk.  Users can request use of CERR for
% institutional review board-approved protocols.  Commercial users can
% request a license.  Contact Joe Deasy for more information
% (radonc.wustl.edu@jdeasy, reversed).

[fname, pathname] = uigetfile('*.*', ...
    'Select a file you wish to compress or decompress');
tic
oldDir = pwd;
if isdeployed
    pathStr = fullfile(getCERRPath,'bin','Compression');
else
    pathStr = fullfile(getCERRPath,'Compression');
end
cd(pathname);
l = length(fname);
fmat = ''; outstr = '';
fmat = (strcat('"',oldDir, '\', fname,'"'));
if (~strcmpi(midstring(fname,l-2,l),'bz2')) % compress file
        cd(pathStr);
        outstr = ['bzip2-102-x86-win32.exe -vv9 ', fmat];
        system(outstr);
        cd(oldDir);
elseif (strcmpi(midstring(fname,l-2,l),'bz2')) % uncompress file
        cd(pathStr);
        outstr = ['bzip2-102-x86-win32.exe -dvv ', fmat];
        system(outstr);
        cd(oldDir);
else
    error('Incorrect filename chosen. Exiting bzip2Matlab.')
end

toc

return


function [varargout] = styleguide(varargin)
% STYLEGUIDE Open or search the MATLAB Programming Style Guide Wiki
%   STYLEGUIDE by itself opens the MATLAB Programming Style Guide Wiki in
%   the MATLAB web browser.
%
%   STYLEGUIDE SEARCHTERM1 SEARCHTERM2 SEARCHTERM3 ... searches the style
%   guide for any number of provided search terms and opens the search
%   results page in the MATLAB web browser.
%
%   STYLEGUIDE uses similar syntax to the WEB function with the exception
%   that it does not expect a URL. Rather, any number of search terms may
%   be used. All other inputs and outputs for WEB work for STYLEGUIDE, e.g.
%   [STAT, BROWSER, URL] = STYLEGUIDE(SEARCHTERM,'-NOTOOLBAR','-NEW').
%
%   To request permission to edit the wiki, use the contact form at
%   http://www.mathworks.com/matlabcentral/fileexchange/authors/contact/101715
%
%   Examples:
%      styleguide naming conventions
%         searches the style guide for "naming+conventions."
%
%      styleguide -browser
%         opens the style guide in the system web browser
%
%      [stat,h] = styleguide;
%         opens the style guide. Use close(h) to close the browser window.
%
%   See also WEB, HELP.

%   Author: Sky Sartorius
%           www.mathworks.com/matlabcentral/fileexchange/authors/101715

validWebArgs = {'-browser' '-display' '-helpbrowser' '-new' ...
    '-notoolbar' '-noaddressbox' '1'};

searchTerms = '';
isaWebArg = false(1,nargin);
for i = 1:nargin
    arg = strtrim(varargin{i});
    isWebArg = strcmpi({arg},validWebArgs);
    if any(isWebArg)
        isaWebArg(i) = true;
    else
        searchTerms = [searchTerms '+' arg]; %#ok<AGROW>
    end
end
if ~isempty(searchTerms)
    searchTerms(1) = '';
end

link = 'https://sites.google.com/site/matlabstyleguidelines/';

if ~isempty(searchTerms)
    searchStr = 'system/app/pages/search?scope=search-site&q=';
    link = [link searchStr searchTerms];
end

jnk = lower(varargin(isaWebArg));
[varargout{1:nargout}] = web(link,jnk{:});

% Revision history
%{
2013-03-13 first version
%}


function d = delta(a)

d = a.delta;


function bst_set( varargin )
% BST_SET: Set a Brainstorm structure.
%
% DESCRIPTION:  This function is used to abstract the way that these structures are stored.
%
% USAGE:
% ====== DIRECTORIES ==================================================================
%    - bst_set('BrainstormHomeDir', BrainstormHomeDir)
%    - bst_set('BrainstormTmpDir',  BrainstormTmpDir)
%    - bst_set('BrainstormDbDir',   BrainstormDbDir)
%    - bst_set('LastUsedDirs',      sDirectories)
%    - bst_set('BrainSuiteDir',     BrainSuiteDir)
%    - bst_set('PythonExe',         PythonExe)
%    - bst_set('PluginCustomPath',  PluginCustomPath)
%
% ====== PROTOCOLS ====================================================================
%    - bst_set('iProtocol',         iProtocol)
%    - bst_set('ProtocolInfo',      sProtocolInfo)
%    - bst_set('ProtocolSubjects',  ProtocolSubjects)
%    - bst_set('isProtocolLoaded',  isProtocolLoaded)
%    - bst_set('isProtocolModified',isProtocolModified)
%    - bst_set('ProtocolStudies',   ProtocolStudies)
%    - bst_set('Study',   iStudy,   sStudy)    : Set a study in current protocol
%    - bst_set('Subject', iSubject, sSubject)  : Set a subject in current protocol
%
% ====== GUI =================================================================
%    - bst_set('Layout',    sLayout)
%    - bst_set('Layout',    PropName, PropValue)
%    - bst_set('Clipboard', Nodes, isCut)  : Copy operation from the tree
%
% ====== CONFIGURATION =================================================================
%    - bst_set('Version',      Version)
%    - bst_set('ByteOrder',    value)        : 'b' for big endian, 'l' for little endian
%    - bst_set('AutoUpdates',  isAutoUpdates)
%    - bst_set('ExpertMode',   isExpertMode)
%    - bst_set('DisplayGFP',   isDisplayGFP)
%    - bst_set('DownsampleTimeSeries',  isDownsampleTimeSeries)
%    - bst_set('GraphicsSmoothing',     isGraphicsSmoothing)
%    - bst_set('ForceMatCompression',   isForceCompression)
%    - bst_set('IgnoreMemoryWarnings',  isIgnoreMemoryWarnings)
%    - bst_set('SystemCopy',            isSystemCopy)
%    - bst_set('DisableOpenGL',         isDisableOpenGL)
%    - bst_set('InterfaceScaling',      InterfaceScaling)
%    - bst_set('TSDisplayMode',         TSDisplayMode)    : {'butterfly','column'}
%    - bst_set('ElectrodeConfig',       ElectrodeConfig, Modality)
%    - bst_set('ElecInterpDist',        ElecInterpDist, Modality)
%    - bst_set('DefaultFormats'         defaultFormats)
%    - bst_set('BFSProperties',         [scalpCond,skullCond,brainCond,scalpThick,skullThick])
%    - bst_set('ImportEegRawOptions',   ImportEegRawOptions)
%    - bst_set('BugReportOptions',      BugReportOptions)
%    - bst_set('DefaultSurfaceDisplay', displayStruct)
%    - bst_set('MagneticExtrapOptions', extrapStruct)
%    - bst_set('TimefreqOptions_morlet',  Options)
%    - bst_set('TimefreqOptions_fft',     Options)
%    - bst_set('TimefreqOptions_psd',     Options)
%    - bst_set('TimefreqOptions_hilbert', Options)
%    - bst_set('TimefreqOptions_plv',     Options)
%    - bst_set('OpenMEEGOptions',         Options)
%    - bst_set('DuneuroOptions',         Options)
%    - bst_set('GridOptions_headmodel',   Options)
%    - bst_set('GridOptions_dipfit',      Options)
%    - bst_set('UniformizeTimeSeriesScales', isUniform)
%    - bst_set('FlipYAxis',             isFlipY)
%    - bst_set('AutoScaleY',            isAutoScaleY)
%    - bst_set('FixedScaleY',           Modality,  Value)
%    - bst_set('XScale',                XScale)
%    - bst_set('YScale',                YScale)
%    - bst_set('ShowXGrid',             isShowXGrid)
%    - bst_set('ShowYGrid',             isShowYGrid)
%    - bst_set('ShowZeroLines',         isShowZeroLines)
%    - bst_set('ShowEventsMode',        ShowEventsMode)
%    - bst_set('Resolution',            [resX,resY])
%    - bst_set('UseSigProcToolbox',     UseSigProcToolbox)
%    - bst_set('RawViewerOptions',      RawViewerOptions)
%    - bst_set('TopoLayoutOptions',     TopoLayoutOptions)
%    - bst_set('StatThreshOptions',     StatThreshOptions)
%    - bst_set('ContactSheetOptions',   ContactSheetOptions)
%    - bst_set('ProcessOptions',        ProcessOptions)
%    - bst_set('MriOptions',            MriOptions)
%    - bst_set('CustomColormaps',       CustomColormaps)
%    - bst_set('DigitizeOptions',       DigitizeOptions)
%    - bst_set('ReadOnly',              ReadOnly)
%    - bst_set('LastPsdDisplayFunction', LastPsdDisplayFunction)
%    - bst_set('PlotlyCredentials',     Username, ApiKey, Domain)
%    - bst_set('KlustersExecutable',    ExecutablePath)
%    - bst_set('ExportBidsOptions'),    ExportBidsOptions)
%
% SEE ALSO bst_get

% @=============================================================================
% 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-2021
%          Martin Cousineau, 2017

global GlobalData;

%% ==== PARSE INPUTS ====
if ((nargin >= 1) && ischar(varargin{1}))
    contextName  = varargin{1};
    if (nargin >= 2)
        contextValue = varargin{2};
    else
        contextValue = [];
    end
else
    error('Usage : bst_set(contextName, contextValue)');
end

% Get required context structure
switch contextName
%% ==== BRAINSTORM CONFIGURATION ====
    case 'Version'
        GlobalData.Program.Version = contextValue;
    case 'BrainstormHomeDir'
        GlobalData.Program.BrainstormHomeDir = contextValue;
    case 'BrainstormDbDir'
        GlobalData.DataBase.BrainstormDbDir = contextValue;
    case 'BrainstormTmpDir'
        GlobalData.Preferences.BrainstormTmpDir = contextValue;

%% ==== PROTOCOL ====
    case 'iProtocol'
        if isnumeric(contextValue)
            GlobalData.DataBase.iProtocol = contextValue;
        else
            error('iProtocol should be a number.');
        end
    case {'ProtocolSubjects', 'ProtocolStudies'}
        for structField = fieldnames(contextValue)'
            GlobalData.DataBase.(contextName)(GlobalData.DataBase.iProtocol).(structField{1}) = contextValue.(structField{1});
        end
        GlobalData.DataBase.isProtocolModified(GlobalData.DataBase.iProtocol) = 1;
    case 'ProtocolInfo'
        for structField = fieldnames(contextValue)'
            GlobalData.DataBase.(contextName)(GlobalData.DataBase.iProtocol).(structField{1}) = contextValue.(structField{1});
        end
    case 'isProtocolLoaded'
        GlobalData.DataBase.isProtocolLoaded(GlobalData.DataBase.iProtocol) = contextValue;
    case 'isProtocolModified'
        GlobalData.DataBase.isProtocolModified(GlobalData.DataBase.iProtocol) = contextValue;

%% ==== SUBJECT ====
    case 'Subject'
        % Get subjects list
        ProtocolSubjects = bst_get('ProtocolSubjects');
        iSubject = varargin{2};
        sSubject = varargin{3};
        % If default subject
        if (iSubject == 0)
            ProtocolSubjects.DefaultSubject = sSubject;
        else
            ProtocolSubjects.Subject(iSubject) = sSubject;
        end
        % Update DataBase
        bst_set('ProtocolSubjects', ProtocolSubjects);

%% ==== STUDY ====
    case 'Study'
        % Get studies list
        ProtocolStudies = bst_get('ProtocolStudies');
        iStudies = varargin{2};
        sStudies = varargin{3};
        iAnalysisStudy = -2;
        iDefaultStudy  = -3;
        for i = 1:length(iStudies)
            % Normal study
            if (iStudies(i) > 0)
                ProtocolStudies.Study(iStudies(i)) = sStudies(i);
            % Inter-subject analysis study
            elseif (iStudies(i) == iAnalysisStudy)
                ProtocolStudies.AnalysisStudy = sStudies(i);
            % Default study
            elseif (iStudies(i) == iDefaultStudy)
                ProtocolStudies.DefaultStudy = sStudies(i);
            end
        end
        % Update DataBase
        bst_set('ProtocolStudies', ProtocolStudies);

%% ==== GUI ====
    % USAGE: bst_set('Layout', sLayout)
    %        bst_set('Layout', PropName, PropValue)
    case 'Layout'
        if (nargin == 2) && isstruct(contextValue)
            GlobalData.Preferences.Layout = contextValue;
            isUpdateScreens = 0;
        elseif (nargin == 3) && ischar(contextValue) && isfield(GlobalData.Preferences, 'Layout') && isfield(GlobalData.Preferences.Layout, contextValue)
            GlobalData.Preferences.Layout.(contextValue) = varargin{3};
            isUpdateScreens = strcmpi(contextValue, 'DoubleScreen');
        else
            error('Invalid call to bst_set.');
        end
        % Update screen configuration
        GlobalData.Program.ScreenDef = gui_layout('GetScreenClientArea');
        % Update layout right now
        gui_layout('Update');
        % If the number of screen was changed: update the maximum size of the Brainstorm window
        if isUpdateScreens
            gui_layout('UpdateMaxBstSize');
        end

    % USAGE: bst_set('FixedScaleY', [])
    %        bst_set('FixedScaleY', Modality, Value)
    case 'FixedScaleY'
        if (nargin == 3) && ~isempty(contextValue) && ~isempty(varargin{3})
            GlobalData.Preferences.FixedScaleY.(contextValue) = varargin{3};
        elseif (nargin == 2) && isempty(contextValue)
            GlobalData.Preferences.FixedScaleY = struct();
        end

    case 'ByteOrder'
        switch(contextValue)
            case {'b','ieee-le','n'}
                GlobalData.Preferences.ByteOrder = 'b';
            case {'l','ieee-be'}
                GlobalData.Preferences.ByteOrder = 'l';
            otherwise
                error('Invalid byte order.');
        end

    case 'Clipboard'
        if (length(varargin) >= 3)
            isCut = varargin{3};
        else
            isCut = 0;
        end
        GlobalData.Program.Clipboard.Nodes = contextValue;
        GlobalData.Program.Clipboard.isCut = isCut;

    case 'ElectrodeConfig'
        Modality = varargin{2};
        ElectrodeConf = varargin{3};
        if isequal(Modality, 'ECOG+SEEG')
            Modality = 'ECOG_SEEG';
        elseif ~ismember(Modality, {'EEG','SEEG','ECOG','MEG'})
            error(['Invalid modality: ' Modality]);
        end
        GlobalData.Preferences.(contextName).(Modality) = ElectrodeConf;

    case 'ElecInterpDist'
        Modality = varargin{2};
        ElecInterpDist = varargin{3};
        if isequal(Modality, 'ECOG+SEEG')
            Modality = 'ECOG_SEEG';
        elseif ~ismember(Modality, {'EEG','SEEG','ECOG','MEG'})
            error(['Invalid modality: ' Modality]);
        end
        GlobalData.Preferences.(contextName).(Modality) = ElecInterpDist;

    case {'UniformizeTimeSeriesScales', 'XScale', 'YScale', 'FlipYAxis', 'AutoScaleY', 'ShowXGrid', 'ShowYGrid', 'ShowZeroLines', 'ShowEventsMode', ...
          'Resolution', 'AutoUpdates', 'ExpertMode', 'DisplayGFP', 'ForceMatCompression', 'GraphicsSmoothing', 'DownsampleTimeSeries', ...
          'DisableOpenGL', 'InterfaceScaling', 'TSDisplayMode', 'UseSigProcToolbox', 'LastUsedDirs', 'DefaultFormats', ...
          'BFSProperties', 'ImportDataOptions', 'ImportEegRawOptions', 'RawViewerOptions', 'MontageOptions', 'TopoLayoutOptions', ...
          'StatThreshOptions', 'ContactSheetOptions', 'ProcessOptions', 'BugReportOptions', 'DefaultSurfaceDisplay', ...
          'MagneticExtrapOptions', 'MriOptions', 'ConnectGraphOptions', 'NodelistOptions', 'IgnoreMemoryWarnings', 'SystemCopy', ...
          'TimefreqOptions_morlet', 'TimefreqOptions_hilbert', 'TimefreqOptions_fft', 'TimefreqOptions_psd', 'TimefreqOptions_plv', ...
          'OpenMEEGOptions', 'DuneuroOptions', 'DigitizeOptions', 'CustomColormaps', 'PluginCustomPath', 'BrainSuiteDir', 'PythonExe', ...
          'GridOptions_headmodel', 'GridOptions_dipfit', 'LastPsdDisplayFunction', 'KlustersExecutable', 'ExportBidsOptions'}
        GlobalData.Preferences.(contextName) = contextValue;

    case 'ReadOnly'
        GlobalData.DataBase.isReadOnly = contextValue;

    case 'PlotlyCredentials'
        if length(varargin) ~= 4
            error('Invalid call to bst_set.');
        end
        [username, apiKey, domain] = varargin{2:4};
        % Default domain: plot.ly
        if isempty(domain)
            domain = 'https://plot.ly';
        end
        % Plotly needs a URL with HTTP and no trailing slash.
        if strfind(domain, 'https://')
            domain = strrep(domain, 'https://', 'http://');
        elseif isempty(strfind(domain, 'http://'))
            domain = ['http://', domain];
        end
        if domain(end) == '/'
            domain = domain(1:end-1);
        end
        % Save credentials
        saveplotlycredentials(username, apiKey);
        saveplotlyconfig(domain);

%% ==== ERROR ====
    otherwise
        error('Invalid context : ''%s''', contextName);

end


classdef (Abstract) BaseWidget < matlab.ui.componentcontainer.ComponentContainer & ...
        wt.mixin.ErrorHandling
    % Base class for a graphical widget

    % Copyright 2020-2021 The MathWorks Inc.

    %% Internal properties
    properties (AbortSet, Transient, NonCopyable, ...
            Access = {?wt.abstract.BaseWidget, ?wt.test.BaseWidgetTest} )

        % List of graphics controls that BackgroundColor should apply to
        BackgroundColorableComponents (:,1) matlab.graphics.Graphics

    end %properties

    properties (Transient, NonCopyable, Access = {?wt.test.BaseWidgetTest})

        % Used internally to indicate when setup has finished
        SetupFinished_I (1,1) logical = false

    end %properties

    properties (Transient, NonCopyable, UsedInUpdate, Access = {?wt.test.BaseWidgetTest})

        % Used internally to request update call
        RequestUpdate_I (1,1) logical = false

    end %properties

    %% Debugging Methods
    methods

        function forceUpdate(obj)
           % Forces update to run (For debugging only!)

            obj.update();

        end %function

    end %methods

    %% Setup
    properties ( Transient, NonCopyable, ...
            Access = {?wt.abstract.BaseWidget, ?wt.test.BaseWidgetTest} )

        % The internal grid to manage contents
        Grid matlab.ui.container.GridLayout

    end %properties

    methods (Access = protected)

        function setup(obj)
            % Configure the widget

            % Use CreateFcn to tell when setup finishes
            obj.CreateFcn = @(src,evt)obj.toggleSetupFinished_I();

            % Grid Layout to manage building blocks
            obj.Grid = uigridlayout(obj);
            obj.Grid.ColumnWidth = {'1x'};
            obj.Grid.RowHeight = {'1x'};
            obj.Grid.RowSpacing = 2;
            obj.Grid.ColumnSpacing = 2;
            obj.Grid.Padding = [0 0 0 0];

            % Listen to BackgroundColor changes
            addlistener(obj,'BackgroundColor','PostSet',...
                @(h,e)obj.updateBackgroundColorableComponents());

        end %function

    end %methods

    %% Protected Methods
    methods (Access = protected)

        function updateBackgroundColorableComponents(obj)
            % Update components that are affected by BackgroundColor

            obj.Grid.BackgroundColor = obj.BackgroundColor;
            hasProp = isprop(obj.BackgroundColorableComponents,'BackgroundColor');
            set(obj.BackgroundColorableComponents(hasProp),...
                "BackgroundColor",obj.BackgroundColor);

        end %function

        function requestUpdate(obj)
            % Request update method to run

            if ~obj.SetupFinished_I
                % Do nothing
            elseif verLessThan('matlab','9.10')
                % g228243 Force a call to update
                obj.update();
            else
                % Trigger set of a UsedInUpdate property to request update
                % during next drawnow. (for optimal efficiency)
                obj.RequestUpdate_I = true;
            end

        end %function

    end %methods

    %% Private Methods
    methods (Access = private)

        function toggleSetupFinished_I(obj)
            % Indicate setup is complete

            obj.SetupFinished_I = true;
            obj.CreateFcn = '';

        end %function

    end %methods

    %% Display customization
    methods (Hidden, Access = protected)

        function groups = getPropertyGroups(obj)
            % Customize how the properties are displayed

            % Ignore most superclass properties for default display
            persistent superProps
            if isempty(superProps)
                superProps = properties('matlab.ui.componentcontainer.ComponentContainer');
            end

            % Get the relevant properties
            allProps = properties(obj);
            propNames = setdiff(allProps, superProps, 'stable');

            % Remove props we don't need to see
            propNames( startsWith(propNames, "Font") ) = [];
            propNames( matches(propNames, "Enable") ) = [];

            % Split out the callbacks, fonts
            isCallback = endsWith(propNames, "Fcn");
            isColor = endsWith(propNames, "Color");
            normalProps = propNames(~isCallback & ~isColor);
            callbackProps = propNames(isCallback & ~isColor);

            % Define the groups
            groups = [
                matlab.mixin.util.PropertyGroup(callbackProps)
                matlab.mixin.util.PropertyGroup(normalProps)
                matlab.mixin.util.PropertyGroup(["Position", "Units"])
                ];

            % Ignore empty groups
            groups(~[groups.NumProperties]) = [];

        end %function

    end %methods

    %% Accessors
    methods

        function set.BackgroundColorableComponents(obj,value)
            obj.BackgroundColorableComponents = value;
            obj.updateBackgroundColorableComponents()
        end

    end %methods

end %classdef


classdef CoreErrorUtilities < handle
    % CoreErrorUtilities. Error-related utility functions.
    %
    %
    %     Licence
    %     -------
    %     Part of CoreMat. https://github.com/tomdoel/coremat
    %     Author: Tom Doel, 2013.  www.tomdoel.com
    %     Distributed under the MIT licence. Please see website for details.
    %

    methods (Static)

        % Obtain the name of the function which signalled the error (useful in
        % error reporting)
        function [calling_function, stack] = GetCallingFunction(levels_to_ignore)
            caller_found = false;
            max_levels = 10;
            calling_function = [];

            while ~caller_found
                % Get the call stack, excluding the call to this function and the
                % caller of this function
                [stack, ~] = dbstack(levels_to_ignore, '-completenames');
                if isempty(stack)
                    caller_found = true;
                else
                    stack_top = stack(1);
                    calling_function = stack_top.name;
                    if length(calling_function) < 11 || ~strcmp(calling_function(1:11), 'CoreReporting')
                        caller_found = true;
                    end
                    levels_to_ignore = levels_to_ignore + 1;
                end
            end
        end

        function ThrowException(id, message)
            [stack, ~] = dbstack(2, '-completenames');

            msgStruct = [];
            msgStruct.message = message;
            msgStruct.identifier = id;
            msgStruct.stack = stack;
            error(msgStruct);
        end
    end
end


%% Import/Export
%
%%


%% Transformation Texture
%
%%


function directories_added=moxunit_set_path()
% sets the search path for MOxUnit
%
% directories_added=moxunit_set_path()
%
% Output:
%    directories_added          Cell string with directories that were
%                               added to the search path. If no
%                               directories were added to the search path
%                               (i.e., all functions for MOxUnit were
%                               already in the search path), then this is
%                               an empty cell array.
% Note:
%   - This adds directory in which this function resides, as well as the
%     'util' sub-directory to the search path

    return_directories_added=nargout>=1;

    root_dir=fileparts(mfilename('fullpath'));

    sub_dirs={'','util'};

    % Cannot use moxunit_util_strjoin because it may not be in the path.
    % Instead construct the path to be added by adding the pathsep() after
    % each subdirectory
    make_full_path_with_sep=@(sub_dir)[fullfile(root_dir,sub_dir) ...
                                        pathsep()];

    full_dirs=cellfun(make_full_path_with_sep,sub_dirs,...
                        'UniformOutput',false);

    if return_directories_added
        % store original path elements
        orig_path_cell=get_path_cell();
    end

    addpath(cat(2,full_dirs{:}));

    if return_directories_added
        new_path_cell=get_path_cell();
        directories_added=setdiff(new_path_cell, orig_path_cell);
    end

function pc=get_path_cell()
    pc=regexp(path(), pathsep(), 'split');


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

    enumeration
        Arrive('Arrival Manifold');
        Depart('Departure Manifold');
    end

    properties
        name char = '';
    end

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

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

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

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


function WindowButtonDownFcnCallback(a, b)

global h configFile selections current files imgId;

buttonPressed = get(h, 'SelectionType');

if(strcmp(buttonPressed, 'normal'))
  %Left click
  selections = [selections; current];
elseif(strcmp(buttonPressed, 'alt'))
  %Right click
  imgId = imgId + 1;
  if(imgId > numel(files))
    imgId = 1;
  end
  InteractiveCenterDemo(configFile);
end

end


function fignum = xsec_fig()
    % XSEC_FIG returns the handle to the cross-section figure
    fignum=findobj('Type','Figure','-and','Name','Cross -Section');
    if isempty(fignum)
        fignum=figure('Name','Cross -Section');
    end


function reportResults(status)
global logger
global testidx
global procStreamStyle

logger.Write('\n');

for iTest = 1:length(status)
    if status(iTest)~=0
        logger.Write(sprintf('Unit test #%d FAILED.\n', iTest));
    else
        logger.Write(sprintf('Unit test #%d PASSED.\n', iTest));
    end
end
logger.Write('\n');

testidx=[];
procStreamStyle=[];


function h_out= axis_getQuietly(varargin)
%AXIS_GETQUIETLY - Make an axis the current axis without interfering the
% 'Visible' property

vis= get(gcf, 'Visible');
if nargin==1,
  axes(varargin{:});
else
  out= axes(varargin{:});
end
set(gcf, 'Visible',vis);

if nargout>0,
  h_out= out;
end


function setFigureDefaults()
	% Sets preferred figure defaults.
	% Biafra Ahanonu
	% started: 2013.10.29
	% inputs
		%
	% outputs
		%

	% changelog
		%
	% TODO
		%

	ciapkg.view.setFigureDefaults();
end


classdef CompositeResultsPrinter < ResultsPrinter

    properties (Access = protected)
        hasGaussData
        printers
        simulationStr
    end

    methods (Access = public)

        function  printResults(obj,iter,fileID)
            obj.setSimulationStrToPrinters()
            for iprinter = 1:numel(obj.printers)
                p = obj.printers{iprinter};
                p.printResults(iter,fileID);
            end
        end

    end

    methods (Access = protected)

        function init(obj,d)
            obj.init@ResultsPrinter(d);
            obj.createPrinters(d);
            obj.obtainHasGaussData();
        end

        function createHeadPrinter(obj,d,dh)
            for iprinter = 1:numel(obj.printers)
                p = obj.printers{iprinter};
                p.createHeadPrinter(d,dh);
                if p.getHasGaussData()
                    h = p.getHeadPrinter();
                    obj.headPrinter = h;
                    return
                else
                    h = p.getHeadPrinter();
                    obj.headPrinter = h;
                end
            end
        end

        function storeFieldsToPrint(obj,d)
            for iprinter = 1:numel(obj.printers)
                p = obj.printers{iprinter};
                p.storeFieldsToPrint(d);
            end
        end

    end

    methods (Access = private)

        function obtainHasGaussData(obj)
            obj.hasGaussData = false;
            for iprinter = 1:numel(obj.printers)
                p = obj.printers{iprinter};
                hG = p.getHasGaussData();
                obj.hasGaussData = hG || obj.hasGaussData;
            end
        end

        function setSimulationStrToPrinters(obj)
            s = obj.simulationStr;
            for iprinter = 1:numel(obj.printers)
                p = obj.printers{iprinter};
                p.setSimulationStr(s);
            end
        end
    end

    methods (Access = protected, Abstract)
        createPrinters(obj,d)
    end

end


function fatrix2_block_free(arg)
%printm 'freeing fatrix2_block object static memory'
for mm=1:length(arg.blocks)
	try
		free(blocks{mm})
	catch
	end
end


function DoUpdateBatch(Simuh)

global VSeq
global VObj
global VCtl
global VMag
global VCoi
global VMot
global VVar
global VSig

eval(['VSeq' num2str(Simuh.ScanSeriesInd) '=VSeq;']);
eval(['VObj' num2str(Simuh.ScanSeriesInd) '=VObj;']);
eval(['VCtl' num2str(Simuh.ScanSeriesInd) '=VCtl;']);
eval(['VMag' num2str(Simuh.ScanSeriesInd) '=VMag;']);
eval(['VCoi' num2str(Simuh.ScanSeriesInd) '=VCoi;']);
eval(['VMot' num2str(Simuh.ScanSeriesInd) '=VMot;']);
eval(['VVar' num2str(Simuh.ScanSeriesInd) '=VVar;']);
eval(['VSig' num2str(Simuh.ScanSeriesInd) '=VSig;']);

if ~exist([Simuh.MRiLabPath filesep 'Tmp' filesep 'BatchData.mat'],'file')
    Notes='temporary file used for batch process';
    save([Simuh.MRiLabPath filesep 'Tmp' filesep 'BatchData'], 'Notes');
end

save([Simuh.MRiLabPath filesep 'Tmp' filesep 'BatchData'], ...
    ['VSeq' num2str(Simuh.ScanSeriesInd)], ...
    ['VObj' num2str(Simuh.ScanSeriesInd)], ...
    ['VCtl' num2str(Simuh.ScanSeriesInd)], ...
    ['VMag' num2str(Simuh.ScanSeriesInd)], ...
    ['VCoi' num2str(Simuh.ScanSeriesInd)], ...
    ['VMot' num2str(Simuh.ScanSeriesInd)], ...
    ['VVar' num2str(Simuh.ScanSeriesInd)], ...
    ['VSig' num2str(Simuh.ScanSeriesInd)], ...
    '-append');

Simuh.BatchList{end+1,1}=Simuh.ScanSeriesInd;
Simuh.BatchList{end,2}=Simuh.SimName;
Simuh.BatchList{end,3}=Simuh.Engine;
Simuh.BatchList{end,4}='Dx';
Simuh.BatchListIdx(end+1)=Simuh.ScanSeriesInd;

guidata(Simuh.SimuPanel_figure,Simuh);

end


function this = rmfield(this, vals);

    this.EEG = rmfield(this.EEG, vals);