% FT_POSTAMBLE_SAVEFIG is a helper script that optionally saves the output
% MATLAB figure to a *.fig and to a *.png file on disk. This is useful for
% batching and for distributed processing. This makes use of the
% cfg.outputfile variable.
%
% Use as
%   ft_postamble savefig
%
% See also FT_PREAMBLE, FT_POSTAMBLE, FT_POSTAMBLE_SAVEVAR

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

% the output data should be saved to a MATLAB file
if (isfield(cfg, 'outputfile') && ~isempty(cfg.outputfile)) || exist('Fief7bee_reproducescript', 'var')

  if isfield(cfg, 'outputlock') && ~isempty(cfg.outputlock)
    mutexlock(cfg.outputlock);
  end

  if exist('Fief7bee_reproducescript', 'var')
    % write the output figure to a MATLAB file
    iW1aenge_now = datestr(now, 30);
    cfg.outputfile = fullfile(Fief7bee_reproducescript, sprintf('%s_%s_output',...
      iW1aenge_now, FjmoT6aA_highest_ft)); % the file extension is added later

    % write the large configuration fields to a MATLAB file
    % this applies to layout, event, sourcemodel, headmodel, grad, etc.
    % note that this is here, rather than in the (seemingly more logical)
    % ft_preamble_loadvar, because this code depends on cfg.callinfo (which
    % is only present at postamble stage)
    cfg = save_large_cfg_fields(cfg, FjmoT6aA_highest_ft, Fief7bee_reproducescript, iW1aenge_now);

    % write a snippet of MATLAB code with the user-specified configuration and function call
    reproducescript(Fief7bee_reproducescript, fullfile(Fief7bee_reproducescript, 'script.m'),...
      FjmoT6aA_highest_ft, cfg, false);

  elseif (isfield(cfg, 'outputfile') && ~isempty(cfg.outputfile))
    % keep the output file as it is

  else
    % don't write to an output file
    cfg.outputfile = {};
  end

  % save the current figure to a MATLAB .fig and to a .png file
  if ~isempty(cfg.outputfile)
    [Fief7bee_p, Fief7bee_f, Fief7bee_x] = fileparts(cfg.outputfile);
    Fief7bee_outputfile = fullfile(Fief7bee_p, [Fief7bee_f, '.fig']);
    ft_info('writing output figure to file ''%s''\n', Fief7bee_outputfile);
    savefig(gcf, cfg.outputfile, 'compact')
    Fief7bee_outputfile = fullfile(Fief7bee_p, [Fief7bee_f, '.png']);
    ft_info('writing screenshot to file ''%s''\n', Fief7bee_outputfile);
    set(gcf, 'PaperOrientation', 'portrait');
    print(Fief7bee_outputfile, '-dpng');
  end

  if isfield(cfg, 'outputlock') && ~isempty(cfg.outputlock)
    mutexunlock(cfg.outputlock);
  end

end


function cullArriveDepartCombosPerCB(mainGUIHandle)
%cullArriveDepartCombosPerCB Summary of this function goes here
%   Detailed explanation goes here

    %Set up CB/Arrive/Depart combo boxes
    [cbBodyNames, arriveDepartNames] = genCBArriveDepartComboBoxStrs(mainGUIHandle);

    %Strings for CB combo boxes
    cbBodyNames = cap1stLetter(cbBodyNames);
    cbComboString = char(cbBodyNames);
    hCentralBodyCombo = findobj(mainGUIHandle,'Tag','centralBodyCombo');

    try
        set(hCentralBodyCombo,'String',cbComboString);
    catch
        hCentralBodyCombo.Items = cbBodyNames;
    end

    %Strings for Depart/Arrival combo boxes
    arriveDepartNames = cap1stLetter(arriveDepartNames);
    departArriveComboString = char(arriveDepartNames);

    if(size(departArriveComboString,1)>5)
        dBValue = 3;
        aBValue = 4;
    elseif(size(departArriveComboString,1)>=2)
        dBValue = 1;
        aBValue = 2;
    else
        dBValue = 1;
        aBValue = 1;
    end

    hDepartBodyCombo = findobj(mainGUIHandle,'Tag','departBodyCombo');
    try
        set(hDepartBodyCombo,'Value',dBValue);
        set(hDepartBodyCombo,'String',departArriveComboString);
    catch
        hDepartBodyCombo.Items = arriveDepartNames;
        if(numel(arriveDepartNames) > 0)
            hDepartBodyCombo.Value = arriveDepartNames{dBValue};
        end
    end

    hArriveBodyCombo = findobj(mainGUIHandle,'Tag','arrivalBodyCombo');
    try
        set(hArriveBodyCombo,'Value',aBValue);
        set(hArriveBodyCombo,'String',departArriveComboString);
    catch
        hArriveBodyCombo.Items = arriveDepartNames;
        if(numel(arriveDepartNames) > 0)
            hArriveBodyCombo.Value = arriveDepartNames{aBValue};
        end
    end
end


%PLUS Mapping overload


function watchdog

% WATCHDOG will trigger an exit() if the controller disappears or if the allowed time elapsed
%
% To enable the watchdog you should do
%   watchdog(controllerid, time)
% and to disable it again
%   clear watchdog

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

warning('could not locate mex file');


function [fnames, defaults] = mysubs_fields

% function [fnames, defaults] = mysubs_fields
% Additional fields for class cfg_menu. 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={'labels','values'};
defaults={{},{}};


function uid = root(tree)
% XMLTREE/ROOT Root Method
% FORMAT uid = root(tree)
%
% tree   - XMLTree object
% uid    - UID of the root element of tree
%__________________________________________________________________________
%
% Return the uid of the root element of the tree.
%__________________________________________________________________________
% Copyright (C) 2002-2008  http://www.artefact.tk/

% Guillaume Flandin
% $Id: root.m 4460 2011-09-05 14:52:16Z guillaume $

% Actually root is necessarily the element whos UID is 1, by
% construction. However, xml_parser should return a tree with a ROOT
% element with as many children as needed but only ONE *element* child
% who would be the real root (and this method should return the UID of
% this element).

uid = 1;

% Update:
% xml_parser has been modified (not as explained above) to handle the
% case when several nodes are at the top level of the XML.
% Example: <!-- beginning --><root>blah blah</root><!-- end -->
% Now root is the first element node of the tree.

% Look for the first element in the XML Tree
for i=1:length(tree)
    if strcmp(get(tree,i,'type'),'element')
        uid = i;
        break
    end
end


classdef DetectionEventHandle < handle
    properties
        detectedEvent;
        symbolHandle;
        textHandle;
    end

    properties (Access = private, Constant)
        visibleStringss = {'off','on'};
    end

    methods (Access = public)
        function obj = DetectionEventHandle(detectedEvent,symbolHandle, textHandle)
            if nargin > 0
                obj.detectedEvent = detectedEvent;
                obj.symbolHandle = symbolHandle;
                obj.textHandle = textHandle;
            end
        end

        function setVisible(obj,visible)
            obj.symbolHandle.Visible = obj.visibleStringss{visible+1};
            obj.textHandle.Visible = obj.visibleStringss{visible+1};
        end
    end
end


function [nam] = get_name(dat)

%   get_name(data)  returns the name of the object
  nam=dat.algorithm.name;

%%%% SGE support
if isdeferred(dat), nam = get_name(dat.algorithm.deferred, nam, 1); end
%%%%


% Run this file to build the needed mex-files on windows

% Build merResize
mex -lopencv_core242 -lopencv_imgproc242 -L./ -I./ mexResize.cpp MxArray.cpp

% Build setnonzeros from the lightspeed matlab toolbox
mex setnonzeros.c

% Build gradientMex from Piotrs toolbox
mex gradientMex.cpp -I./

% Build mtimesx
mtimesx_build


function tf=mocov_is_absolute_path(fn)
% indicate whether a path is absolute
%
% tf=mocov_is_absolute_path(fn)
%
% Input:
%   fn          filename or path
%
% Output:
%   tf          true if fn is an absolute path, false otherwise
%

    n=numel(fn);
    if ispc()
        tf=n>=2 && fn(2)==':';
    else
        tf=n>=1 && (fn(1)=='/' || fn(1)=='~');
    end


function [output,status] = urlwrite(urlChar,location,method,params)
%URLWRITE Save the contents of a URL to a file.
%   URLWRITE(URL,FILENAME) saves the contents of a URL to a file.  FILENAME
%   can specify the complete path to a file.  If it is just the name, it will
%   be created in the current directory.
%
%   F = URLWRITE(...) returns the path to the file.
%
%   F = URLWRITE(...,METHOD,PARAMS) passes information to the server as
%   part of the request.  The 'method' can be 'get', or 'post' and PARAMS is a
%   cell array of param/value pairs.
%
%   [F,STATUS] = URLWRITE(...) catches any errors and returns the error code.
%
%   Examples:
%   urlwrite('http://www.mathworks.com/',[tempname '.html'])
%   urlwrite('ftp://ftp.mathworks.com/README','readme.txt')
%   urlwrite(['file:///' fullfile(prefdir,'history.m')],'myhistory.m')
%
%   From behind a firewall, use the Preferences to set your proxy server.
%
%   See also URLREAD.

%   Matthew J. Simoneau, 13-Nov-2001
%   Copyright 1984-2011 The MathWorks, Inc.
%   $Revision: 1.4.4.14 $ $Date: 2011/09/03 22:43:01 $

% This function requires Java.
if ~usejava('jvm')
   error(message('MATLAB:urlwrite:NoJvm'));
end

import com.mathworks.mlwidgets.io.InterruptibleStreamCopier;

% Be sure the proxy settings are set.
com.mathworks.mlwidgets.html.HTMLPrefs.setProxySettings

% Check number of inputs and outputs.
if ~ischar(urlChar)
    error('MATLAB:urlwrite:InvalidInput','The first input, the URL, must be a character array.');
end
if ~ischar(location)
    error('MATLAB:urlwrite:InvalidInput','The second input, a filename, must be a character array.');
end
if (nargin > 2) && ~strcmpi(method,'get') && ~strcmpi(method,'post')
    error('MATLAB:urlwrite:InvalidInput','Second argument must be either "get" or "post".');
end

% Do we want to throw errors or catch them?
if nargout == 2
    catchErrors = true;
else
    catchErrors = false;
end

% Set default outputs.
output = '';
status = 0;

% GET method.  Tack param/value to end of URL.
if (nargin > 2) && strcmpi(method,'get')
    if mod(length(params),2) == 1
        error('MATLAB:urlwrite:InvalidInput','Invalid parameter/value pair arguments.');
    end
    for i=1:2:length(params)
        if (i == 1), separator = '?'; else separator = '&'; end
        param = char(java.net.URLEncoder.encode(params{i}));
        value = char(java.net.URLEncoder.encode(params{i+1}));
        urlChar = [urlChar separator param '=' value];
    end
end

% Create a urlConnection.
[urlConnection,errorid,errormsg] = plugin_urlreadwrite(mfilename,urlChar);
if isempty(urlConnection)
    if catchErrors, return
    else error(errorid,errormsg);
    end
end

pluginSize = 2*plugin_urlsize(urlChar)/1000000;
timeOut = max(round(pluginSize*1000), 5000);
urlConnection.setReadTimeout(timeOut); % timeout in 5 seconds

% POST method.  Write param/values to server.
if (nargin > 2) && strcmpi(method,'post')
    try
        urlConnection.setDoOutput(true);
        urlConnection.setRequestProperty( ...
            'Content-Type','application/x-www-form-urlencoded');
        printStream = java.io.PrintStream(urlConnection.getOutputStream);
        for i=1:2:length(params)
            if (i > 1), printStream.print('&'); end
            param = char(java.net.URLEncoder.encode(params{i}));
            value = char(java.net.URLEncoder.encode(params{i+1}));
            printStream.print([param '=' value]);
        end
        printStream.close;
    catch
        if catchErrors, return
        else error('MATLAB:urlwrite:ConnectionFailed','Could not POST to URL.');
        end
    end
end

% Specify the full path to the file so that getAbsolutePath will work when the
% current directory is not the startup directory and urlwrite is given a
% relative path.
file = java.io.File(location);
if ~file.isAbsolute
   location = fullfile(pwd,location);
   file = java.io.File(location);
end

% Make sure the path isn't nonsense.
try
   file = file.getCanonicalFile;
catch
   error('MATLAB:urlwrite:InvalidOutputLocation','Could not resolve file "%s".',char(file.getAbsolutePath));
end

% Open the output file.
try
    fileOutputStream = java.io.FileOutputStream(file);
catch
    error('MATLAB:urlwrite:InvalidOutputLocation','Could not open output file "%s".',char(file.getAbsolutePath));
end

% Read the data from the connection.
try
    inputStream = urlConnection.getInputStream;
    % This StreamCopier is unsupported and may change at any time.
    isc = InterruptibleStreamCopier.getInterruptibleStreamCopier;
    isc.copyStream(inputStream,fileOutputStream);
    inputStream.close;
    fileOutputStream.close;
    output = char(file.getAbsolutePath);
catch
    fileOutputStream.close;
    delete(file);
    if catchErrors, return
    else error('MATLAB:urlwrite:ConnectionFailed','Error downloading URL. Your network connection may be down or your proxy settings improperly configured.');
    end
end

status = 1;


% The COBRAToolbox: testAddKeyToKnownHosts.m
%
% Purpose:
%     - test if a key can be added to known hosts
%
% Authors:
%     - Laurent Heirendt, February 2018
%

global CBTDIR

% save the current path
currentDir = pwd;

% test for a failure of an unknown host
assert(verifyCobraFunctionError('addKeyToKnownHostsCT','inputs',{'github123.co'}));

% find the keyscan
[status_keyscan, result_keyscan] = system('ssh-keyscan');

if status_keyscan == 1 && contains(result_keyscan, 'usage:')
    % get the user directory
    if ispc
        homeDir = getenv('userprofile');
    else
        homeDir = getenv('HOME');
    end

    % define the name of the file
    khFile = [homeDir, filesep, '.ssh', filesep, 'known_hosts'];
    khFile_bk = [khFile, '_bk'];

    % backup the existing known hosts file if it exists
    [status, ~, ~] = copyfile(khFile, khFile_bk);

    % remove the key first from the known hosts file
    [status, result] = system('ssh-keygen -R github.com');

    % run the function to add the github.com key
    statusAddKey = addKeyToKnownHostsCT();

    % check if the key has been added succesfully
    assert(statusAddKey);

    % verify that the key has been added to the known hosts file
    [~, result_grep] = system(['grep "^github.com " ', khFile]);

    % test whether the resulting string is not empty (site has been found)
    assert(~strcmp(result_grep, ''))

    % test if the host is already known
    assert(addKeyToKnownHostsCT('github.com'));

    % remove the old host file generated by running ssh-keygen -R
    delete([khFile '.old']);

    % remove the changed file and restore the backup file
    delete(khFile);
    [status, ~, ~] = movefile(khFile_bk, khFile);
    if status
        fprintf(' > Original known hosts file restored.\n');
    end

    % print a success message
    fprintf(' > Test to add a key passed.\n');
end

% change the directory
cd(currentDir)


%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% TEMPLATE FOR THE COMPILEMODEL FCN (TO BE USED WITH THE STATIC GUI)

% Compile the Simulink model through Matlab command line.

%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
disp('Compiling the Simulink model...')

pause(1.5)

try
    SIMULINK_MODEL_NAME([], [], [], 'compile')
    SIMULINK_MODEL_NAME([], [], [], 'term')

catch ME

    errorMessages = ME;
end

clc

disp('Compilation done.')

% warning about Simulink timing
warning('The model will anyways start with FEW SECONDS OF DELAY after pressing the ''Start Model'' button.')


function foundHandles = find(obj, nameClass, varargin)
% Finds all (handle) object properties whose class and property
% values match given values
%
%   foundHandles = obj.find(nameClass, 'PropertyName',
%                           'PropertyValue', ...)
%
%
% IN
%   nameClass       string with class name (default: MrCopyData)
%   PropertyName/   pairs of string containing name of property
%   PropertyValue   and value (or pattern) that has to be matched
%                   NOTE: if cells of values are given, all
%                   objects are returned that match any of the
%                   entries,
%                   e.g. 'name', {'mean', 'snr'} will return
%                   objects if they are named 'mean OR 'snr'
%
% OUT
%   foundHandles    cell(nHandles,1) of all object handles for
%                   objects that match the properties
%
%                   NOTE: function also returns handle to
%                   calling object, if its class and properties
%                   fulfill the given criteria
%
% EXAMPLE:
%   Y = MrCopyData();
%   Y.find('MrCopyData', 'name', 'coolCopy');
%
%   See also MrCopyData

% Author:   Saskia Bollmann & Lars Kasper
% Created:  2016-04-19
% Copyright (C) 2016 Institute for Biomedical Engineering
%                    University of Zurich and ETH Zurich
%
% This file is part of the TAPAS UniQC Toolbox, which is released
% under the terms of the GNU General Public License (GPL), version 3.
% You can redistribute it and/or modify it under the terms of the GPL
% (either version 3 or, at your option, any later version).
% For further details, see the file COPYING or
%  <http://www.gnu.org/licenses/>.

foundHandles = {};
if nargin
    searchPropertyNames = varargin(1:2:end);
    searchPropertyValues = varargin(2:2:end);
    nSearchProperties = numel(searchPropertyNames);

else
    nSearchProperties = 0;
end

% check whether object itself fulfills criteria
if isa(obj, nameClass)

    doesMatchProperties = true;
    iSearchProperty = 1;

    % Check search properties as long as matching to values
    while doesMatchProperties && ...
            iSearchProperty <= nSearchProperties

        searchProperty = searchPropertyNames{iSearchProperty};
        searchValue = searchPropertyValues{iSearchProperty};
        if isa(obj.(searchProperty), 'MrCopyData')
            % recursive comparison for MrCopyData-properties
            doesMatchProperties = obj.(searchProperty).comp(...
                searchValue);
        else

            doesMatchProperties = isequal(obj.(searchProperty), ...
                searchValue);

            % allow pattern matching for strings or cell of
            % strings (matching any entry of cell)
            if ischar(obj.(searchProperty))
                cellSearchValue = cellstr(searchValue);
                nCellEntries = numel(cellSearchValue);
                iCellEntry = 1;

                % check for each entry in cell whether it
                % matches the string value of this object's
                % property
                while iCellEntry <= nCellEntries && ~doesMatchProperties
                    currentSearchValue = ...
                        cellSearchValue{iCellEntry};

                    % check whether pattern expression given, i.e.
                    % * in search value
                    isSearchPattern = ~isempty(strfind(currentSearchValue, ...
                        '*'));
                    if isSearchPattern
                        doesMatchProperties = ~isempty(regexp( ...
                            obj.(searchProperty), currentSearchValue, 'once'));
                    else
                        doesMatchProperties = isequal(obj.(searchProperty), ...
                            currentSearchValue);
                    end
                    iCellEntry = iCellEntry + 1;
                end
            end

        end

        iSearchProperty = iSearchProperty + 1;
    end

    if doesMatchProperties
        foundHandles = [foundHandles; {obj}];
    end
end

[sel, mobj] = get_properties_to_update(obj);
for k = sel(:)'
    pname = mobj.Properties{k}.Name;

    % Continue to check properties recursively for MrCopyData-properties
    if isa(obj.(pname), 'MrCopyData') % recursive comparison
        newFoundHandles = obj.(pname).find(nameClass, varargin{:});
        foundHandles = [foundHandles;newFoundHandles];
    else
        % cell of MrCopyData also treated
        if iscell(obj.(pname)) && length(obj.(pname)) ...
                && isa(obj.(pname){1}, 'MrCopyData')
            for c = 1:length(obj.(pname))
                newFoundHandles = obj.(pname){c}.find(nameClass, varargin{:});
                foundHandles = [foundHandles;newFoundHandles];
            end
        end
    end
end
% remove duplicate entries, if sub-object itself was returned and
% as a property of super-object
% foundHandles = unique(foundHandles);
end


learnLoc = which('startLearning.m');
parentDir = fileparts(learnLoc);
% ADD PATHS
addpath(genpath(parentDir));

% SAVE CONSTANTS (SEE medalConstants.m)
root = parentDir;
data = fullfile(parentDir,'data');
modules = fullfile(parentDir,'modules');
save(fullfile(parentDir,'.config.mat'));


%POWER Mapping overload


classdef(Abstract) AbstractIntegrationTerminationCause < matlab.mixin.SetGet & matlab.mixin.Heterogeneous
    %AbstractIntegrationTerminationCause Summary of this class goes here
    %   Detailed explanation goes here

    properties

    end

    methods
        tf = shouldRestartIntegration(obj)

        newStateLogEntry = getRestartInitialState(obj, stateLogEntry)
    end

    methods(Static, Access=protected)
        function defaultObject = getDefaultScalarElement()
            defaultObject = SoITransitionDownIntTermCause();
        end
    end
end


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

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

% Last Modified by GUIDE v2.5 28-Oct-2010 04:42:36

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

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

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

% Choose default command line output for gui_eventinsertion
handles.output = {};

% Update handles structure
guidata(hObject, handles);

% invoke the callback to init the dialog
edit1_Callback(handles.edit1,{},guidata(hObject));

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

% --- Outputs from this function are returned to the command line.
function varargout = gui_eventinsertion_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)
% hack to get the guipanel to render on Macs...
if ismac
    p=get(handles.uipanel1,'Position');
    set(handles.uipanel1,'Position',p.*[ 1 1 0.99 1]);
    set(handles.uipanel1,'Position',p.*[ 1 1 1/0.99 1]);
end
uiwait(handles.figure1);
handles = guidata(hObject);

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

% --- set number of insertion operations!

function edit1_Callback(hObject, eventdata, handles)
gui_check_scalar(hObject,'1');
num = max(1,round(str2num(get(hObject,'String'))));
set(hObject,'String',num2str(num));

if ~isfield(handles,'tabpanel1') || length(get(handles.tabpanel1,'Title')) ~= num
    % generate titles
    title = {};
    for k=1:num
        title{end+1} = ['Step ' num2str(k)]; end
    % save old parameters
    if ~isfield(handles,'opgrids')
        handles.opgrids = {}; end
    parameters = cell(1,num);
    for h=1:min(num,length(handles.opgrids))
        parameters{h} = arg_tovals(handles.opgrids{h}.GetPropertySpecification(),false); end
    % delete old propertygrids
    for h=1:length(handles.opgrids)
        delete(handles.opgrids{h}); end
    % (re-) create tabpanel
    if isfield(handles,'tabpanel1')
        item = num;
        delete(handles.tabpanel1);
    else
        item = 1;
    end
    handles.tabpanel1 = uitabpanel('active',item,'parent',handles.uipanel2,'title',title,'TitleBackgroundColor',[0.93,0.91,0.85]*0.66,'PanelBackgroundColor',[0.93,0.91,0.85],'frameBackgroundColor',[0.66,0.76,1],'TitleForegroundColor',[0 0 0]);
    %set(handles.tabpanel1,'SelectedItem',item);
    subhandles = getappdata(handles.tabpanel1,'panels');
    % create new propertygrids
    handles.opgrids = {};
    for h=1:length(subhandles)
        handles.opgrids{h} = arg_guipanel(subhandles(h), 'Function',@set_insert_markers, 'Parameters',parameters(h)); end
end
guidata(hObject,handles);

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

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

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

% get the parameter specification for all steps
handles.output = {};
for h=1:length(handles.opgrids)
    handles.output{h} = arg_tovals(handles.opgrids{h}.GetPropertySpecification(),false); end
guidata(hObject,handles);
uiresume(handles.figure1);

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

handles.output = {};
guidata(hObject,handles);
uiresume(handles.figure1);

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

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


% (this is just an interface)
function varargout = mydatestr_inv (varargin)
    [varargout{1:nargout}] = mydatestri (varargin{:});
end

%!test
%! % just check whether it runs:
%! mydatestr_inv('2000', 'YYYY');


% run_exiftool_demo
% Demonstration of functions
%    getexif
%    putexif
% Peter Burns, 28 May 2013
%              22 July fixed minor mistake calling putexif

[f,p] = uigetfile({'*.jpg';'*.tif'}, ...
'Select image file');

% Read Exif data
exifdata = getexif([p,f]);
disp(exifdata)

dat = imread([p,f]);
imagesc(dat), axis image

%
% Do processing image data here ...
% (For this demo. we save the original data)
%

[f1,p1] = uiputfile({'*.jpg';'*.tif'},'Save as');

% Save image with original Exif data
status = putexif(dat,[p1,f1], [p,f]);

% Check
[exifdata1, nf1] = getexif([p,f]);
disp(exifdata1)
[exifdata2, nf2] = getexif([p1,f1]);
disp(exifdata2)


%TestRunMonitor Abstract base class for monitoring a running test suite
%   The abstract TestRunMonitor class defines an object that can observe and
%   record the results of running a test suite.  The run() method of a
%   TestComponent object takes a TestRunMonitor object as an input argument.
%
%   Different test suite logging or reporting functionality can be achieved by
%   subclassing TestRunMonitor.  For example, see the TestRunLogger and the
%   CommandWindowTestRunDisplay classes.
%
%   TestRunMonitor methods:
%       TestRunMonitor        - Constructor
%       testComponentStarted  - Called at beginning of test component run
%       testComponentFinished - Called when test component run finished
%       testCaseFailure       -   Called when a test case fails
%       testCaseError         - Called when a test case causes an error
%
%   See also CommandWindowTestRunDisplay, TestRunLogger, TestCase, TestSuite

%   Steven L. Eddins
%   Copyright 2008-2009 The MathWorks, Inc.

classdef TestRunMonitor < handle

    methods (Abstract)

        testComponentStarted(self, component)

        testComponentFinished(self, component, did_pass)

        testCaseFailure(self, test_case, failure_exception)

        testCaseError(self, test_case, error_exception)

    end
end


classdef GemLabelButton < GemVirtualPanel
    % GemLabelButton GEM class for a button image with label text below
    %
    %
    %
    %     Licence
    %     -------
    %     Part of GEM. https://github.com/tomdoel/gem
    %     Author: Tom Doel, 2013.  www.tomdoel.com
    %     Distributed under the MIT licence. Please see website for details.
    %

    properties (Access = protected)
        Button
        Text
        Tag
    end

    properties
        DefaultButtonWidth = 50
        DefaultButtonHeight = 50
        TextHeight = 25
        VerticalSpacing = 2
        ButtonHorizontalSpacing = 0
        LabelFontSize = 9
    end

    properties (Dependent)
        ButtonWidth
        ButtonHeight
    end

    events
        ButtonClicked
    end

    methods
        function obj = GemLabelButton(parent, text, tooltip, tag, icon)
            obj = obj@GemVirtualPanel(parent);
            obj.Button = GemButton(parent, text, tooltip, tag, @obj.ButtonClickedCallback);
            obj.Button.ButtonWidth = obj.DefaultButtonWidth;
            obj.Button.ButtonHeight = obj.DefaultButtonHeight;
            obj.Button.UnSelectedColour = [50, 50, 50];
            obj.Button.ShowTextOnButton = false;
            obj.Button.AddAndResizeImageWithHighlightMask(icon, [0, 0, 0]);
            obj.Button.AutoUpdateStatus = true;

            obj.Button.UnSelectedColour = uint8(255*(obj.StyleSheet.BackgroundColour));
            obj.Button.SelectedColour = uint8(255*(obj.StyleSheet.IconSelectedColour));
            obj.Button.HighlightColour = uint8(255*(obj.StyleSheet.IconHighlightColour));
            obj.Button.HighlightSelectedColour = uint8(255*(obj.StyleSheet.IconHighlightSelectedColour));

            obj.AddChild(obj.Button);
            obj.Text = GemText(parent, text, tooltip, tag);
            obj.Text.HorizontalAlignment = 'center';
            obj.Text.FontSize = obj.LabelFontSize;
            obj.Tag = tag;
            obj.AddChild(obj.Text);
        end

        function Resize(obj, new_position)
            Resize@GemVirtualPanel(obj, new_position);

            button_x_pos = new_position(1) + obj.ButtonHorizontalSpacing;
            button_width = obj.Button.ButtonWidth;
            text_width = button_width + 2*obj.ButtonHorizontalSpacing;
            button_y_pos = new_position(2) + obj.TextHeight + obj.VerticalSpacing;
            button_height = obj.Button.ButtonHeight;
            obj.Button.Resize([button_x_pos, button_y_pos, button_width, button_height]);
            obj.Text.Resize([new_position(1), new_position(2), text_width, obj.TextHeight]);
        end

        function set.ButtonWidth(obj, width)
            obj.Button.ButtonWidth = width;
        end

        function width = get.ButtonWidth(obj)
            width = obj.Button.ButtonWidth;
        end

        function set.ButtonHeight(obj, height)
            obj.Button.ButtonHeight = height;
        end

        function height = get.ButtonHeight(obj)
            height = obj.Button.ButtonHeight;
        end

        function width = GetWidth(obj)
            width = obj.Button.ButtonWidth + 2*obj.ButtonHorizontalSpacing;
        end

        function height = GetRequestedHeight(obj, width)
            height = obj.Button.ButtonHeight + obj.TextHeight + obj.VerticalSpacing;
        end

        function Enable(obj)
            Enable@GemVirtualPanel(obj);
            obj.Button.Enable;
            obj.Text.Enable;
        end

        function Disable(obj)
            Disable@GemVirtualPanel(obj);
            obj.Button.Disable;
            obj.Text.Disable;
        end

        function Select(obj, is_selected)
            obj.Button.Select(is_selected);
        end
    end

    methods (Access = protected)
        function ButtonClickedCallback(obj, tag)
            notify(obj, 'ButtonClicked', CoreEventData(tag));
        end
    end
end


%TestSuiteInDir Test suite requiring temporary directory change
%   The TestSuiteInDir class defines a test suite that has to be run by first
%   changing to a specified directory.
%
%   The setUp method adds the starting directory to the path and then uses cd to
%   change into the specified directory.  The tearDown method restores the
%   original path and directory.
%
%   TestSuiteInDir methods:
%       TestSuiteInDir  - Constructor
%       gatherTestCases - Add test cases found in the target directory
%
%   See also TestSuite

%   Steven L. Eddins
%   Copyright 2009 The MathWorks, Inc.

classdef TestSuiteInDir < TestSuite & TestComponentInDir

    methods
        function self = TestSuiteInDir(testDirectory)
            %TestCaseInDir Constructor
            %   TestCaseInDir(testName, testDirectory) constructs a test case
            %   using the specified name and located in the specified directory.
            self = self@TestComponentInDir(testDirectory);

            if strcmp(testDirectory, '.')
                self.Name = pwd;
                self.Location = pwd;
            else
                [pathstr, name] = fileparts(testDirectory);
                self.Name = name;
                self.Location = testDirectory;
            end
        end

        function gatherTestCases(self)
            %gatherTestCases Add test cases found in the target directory
            %   suite.gatherTestCases() automaticall finds all the test cases in
            %   the directory specified in the constructor call and adds them to
            %   the suite.
            current_dir = pwd;
            c = onCleanup(@() cd(current_dir));

            cd(self.TestDirectory);
            tmp = TestSuite.fromPwd();
            self.TestComponents = tmp.TestComponents;
        end
    end
end


function ffwd(H)
%FFWD Fast forward movie in movie player

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


function paths = searchFiles(submodules, options)
%
% Syntax:
%    paths = searchFiles(submodules, options)
%
% Usage:
%    paths = searchFiles()
%    paths = searchFiles(submodules)
%    paths = searchFiles(submodules, options)
%
% Examples:
%    paths = searchFiles()
%    paths = searchFiles({}, 'update')
%
%
global paths  %#ok<REDEFGI>

if ~exist('submodules','var') || isempty(submodules)
    submodules = parseGitSubmodulesFile();
end
if ~exist('options','var')
    options = '';
end
paths = {};

submodulenames = {};
submodulepaths = {};
urls = {};
kk = 1;
for ii = 1:size(submodules,1)
    urls{ii}            = submodules{ii,1};
    submodulepaths{ii}  = submodules{ii,3};
    if optionExists_startup(options,'update')
        removeFolderContents(submodulepaths{ii});
    elseif ~isemptyFolder(submodulepaths{ii})
        continue;
    end
    [~, submodulenames{kk}] = fileparts(urls{ii});
    kk = kk+1;
end
if isempty(submodulenames)
    return;
end

hf = figure('numbertitle', 'off', 'menubar','none', 'toolbar','none', 'name','Files Paths');
p = get(hf, 'position');
set(hf, 'position',[p(1), p(2), 1.5*p(3), p(4)]);

xpos  = .01;
ypos  =  .70;
xsize =  .20;
ysize =  .07;
xgapsize = .02;
ygapsize = .03;

xpos0 = 12*xpos;
ypos0 = ypos+.1*ypos;
xsize0 = 3.5*xsize;
ysize0 = 2*ysize;
fprintf('Display instructions at [%1.f, %1.f, %1.f, %1.f]\n', [xpos0, ypos0, xsize0, ysize0]);
uicontrol('parent',hf, 'style','text', 'string','Provide paths of downloaded submodules', 'units','normalized', 'position',[xpos0, ypos0, xsize0, ysize0], ...
    'fontsize',11, 'fontweight','bold', 'horizontalalignment','center');

for ii = 1:length(submodulenames)
    fprintf('%d. File %s\n', ii, submodulenames{ii});

    yposi = ypos - (ii-1)*(ysize+ygapsize);
    if yposi<0
        break;
    end

    xpos1 = .7*xpos;
    xsize1 = xsize;
    ysize1 = ysize;
    k = .98;
    fprintf('Display label at [%1.f, %1.f, %1.f, %1.f]\n', [xpos1, k*yposi, xsize1, ysize1]);
    htxt(ii)  = uicontrol('parent',hf, 'style','text',       'string',[submodulenames{ii}, ' :'], 'units','normalized', 'position',[xpos1, k*yposi, xsize1, ysize1], ...
        'fontsize',10, 'fontweight','bold', 'horizontalalignment','right');

    xpos2 = xpos1+xsize1+xgapsize/2;
    xsize2 = 2.5*xsize;
    ysize2 = ysize;
    fprintf('Display edit box at [%1.f, %1.f, %1.f, %1.f]\n', [xpos2, yposi, xsize2, ysize2]);
    hedit(ii) = uicontrol('parent',hf, 'style','edit',       'string','',        'units','normalized', 'position',[xpos2, yposi, xsize2, ysize2], ...
        'fontsize',9, 'fontweight','normal', 'horizontalalignment','left', 'tag',sprintf('edit%sPath',submodulenames{ii}));

    xpos3 = xpos2+xsize2+xgapsize;
    xsize3 = .8*xsize;
    ysize3 = ysize;
    fprintf('Display browse pushbutton at [%1.f, %1.f, %1.f, %1.f]\n', [xpos3, yposi, xsize3, ysize3]);
    hbttn(ii) = uicontrol('parent',hf, 'style','pushbutton', 'string','Browse',  'units','normalized', 'position',[xpos3, yposi, xsize3, ysize3], ...
        'fontsize',10, 'fontweight','bold','callback',{@browseBttnCallback, hedit(ii), submodulenames{ii}});

    fprintf('\n');
end

yposi = ypos - 2*ii*(ysize+ygapsize);
if yposi<0
    return;
end
xpos4  = .35;
xsize4 = 1.2*xsize;
ysize4 = 1.5*ysize;
fprintf('Display SUBMIT button [%1.f, %1.f, %1.f, %1.f]\n', [xpos4, yposi, xsize4, ysize4]);
uicontrol('parent',hf, 'style','pushbutton', 'string','SUBMIT', 'units','normalized', 'position',[xpos4, yposi, xsize4, ysize4], ...
    'fontsize',11, 'fontweight','bold', 'callback',{@submitBttnCallback, hedit, submodules});

waitForGui_startup(hf);

% ------------------------------------------------------
function pname = browseBttnCallback(~, ~, hEdit, submodulename)
pname = '';
[filename, pathname] = uigetfile('*.zip', sprintf('Select file for submodule "%s"', submodulename));
if filename==0
    return
end
pause(.01)

pname = filesepStandard_startup([pathname, '/', filename]);
if isempty(strfind(pname, submodulename)) %#ok<*STREMP>
    msgbox(sprintf('Selected file  "%s"  does not match the submodule  "%s". Please download and provide the path name for submodule  "%s"...', ...
        filename, submodulename, submodulename))
    return;
end
set(hEdit, 'string',pname)

% ------------------------------------------------------
function submitBttnCallback(hObject, ~, hEdits, submodules)
global paths

hf = get(hObject,'parent');

for ii = 1:length(hEdits)
    filepath = get(hEdits(ii), 'string');
    if ~ispathvalid_startup(filepath)
        continue;
    end
    [p,f,e] = fileparts(filepath);
    filenameUnziped = filesepStandard_startup([p,'/',f], 'nameonly:dir');

    if strcmp(e,'.zip')
        if ~ispathvalid_startup(filepath,'file')
            continue
        end
        try
            if ispathvalid_startup(filenameUnziped,'dir')
                rmdir(filenameUnziped,'s')
            end
            unzip(filepath, fileparts(filenameUnziped(1:end-1)));
        catch
        end
    end

    if ~ispathvalid_startup(filenameUnziped,'dir')
        continue
    end

    % Copy downloaded and unzipped submodule folder contents to
    % corresponding submodule folder in the parent repo
    for jj = 1:size(submodules,1)
        submodulepath = submodules{jj,3};
        [~, submodulename] = fileparts(submodules{jj,1});
        if isempty(strfind(filenameUnziped, submodulename))
            continue
        end
        fprintf('Copying %s to %s\n', [filenameUnziped, '/*'], submodulepath);
        copyFolderContents(filenameUnziped, submodulepath);
        rmdir(filenameUnziped,'s');
        paths{ii,1} = filenameUnziped;
        break;
    end
end

delete(hf)


function basename = bz_BasenameFromBasepath(basepath)
% gets basename from a basepath input to a function.  Uses name of the last
% directory on the path to give basename.  Takes care of the problem of the
% fact that if a fileseparator is on the end of the basepath, you have to
% take it off first.
%
% INPUTS
% basepath  is assumed to be a directory containing all data for a given
%           recording session.  It is assumed organization is
%           /whateverdirectory/basename/basename.xml and basepath is
%           equivalent to whateverdirectory/basename/.
%
% OUTPUTS
% basename  as specified above
%
% Brendon Watson, 2017

if strcmp(basepath(end),filesep);
    basepath = basepath(1:end-1);
end
[~,basename] = fileparts(basepath);


function bool = isOctave(varargin)
%ISOCTAVE Determines whether (a certain) version of Octave is being used
%
% See also: isEnvironment, isMATLAB
bool = isEnvironment('Octave', varargin{:});


function mvnx = load_mvnx(filename)
% mvnx = load_mvnx(filename)
% loads a mvnx file
% filename is name of file (including path)
% mvnx is result struct containing all data of the mvnx file
% Xsens Technologies BV 28-05-2015

%% check filename
if isempty(strfind(filename,'mvnx'))
    filename = [filename '.mvnx'];
end
if ~exist(filename,'file')
    error([mfilename ':xsens:filename'],['No file with filename: ' filename ', file is not present or file has wrong format (function only reads .mvnx)'])
end
%% read data
fid = fopen(filename, 'r', 'n', 'UTF-8');
content = char(fread(fid,'char')');
fclose(fid);
%% get data into a cell array, one cell per line
lines = find(content == 10);
cellContent = cell(1,length(lines));

hWaitbar = waitbar(0, 'MVNX import: importing data...');
for n=1:length(lines)
    if n==1
        cellContent{n} = content(1:lines(n)-1);
    else
        cellContent{n} = content(lines(n-1)+1:lines(n)-1);
    end
end

% set file comments on one line
beginComment = find(cellfun(@(x) ~isempty(strfind(x, '<comment>')), cellContent));
endComment = find(cellfun(@(x) ~isempty(strfind(x, '</comment>')), cellContent));

if ~all(beginComment == endComment)
    for i=1:length(beginComment)
        cellContent{beginComment(i)} = [sprintf('%s ',cellContent{beginComment(i):endComment(i)-1}) cellContent{endComment(i)}];
        [cellContent{beginComment(i)+1:endComment(i)}] = deal('<!>');
    end
end
% look for comment lines and remove them
cellContent(cellfun(@(x) x(1)=='-' || (x(1)=='<' && (x(2)=='?' || x(2)=='!')),cellContent)) = [];
% get start of text and clean up some
index = cellfun(@(x) find(x==60,1),cellContent); % lines with only comments on them won't have this mark
openandclose = cellfun(@(x) sum(x==60)==2,cellContent); % lines with have an opening and closing statement in one line
cellContent = cellfun(@(x, y) x(y:end), cellContent, num2cell(index),'UniformOutput',false);

%% get start and end words
n = 0;clear value name
iWord = 0;
word = cell(1,length(cellContent));
wordindex = cell(1,length(cellContent));
wordvalue = cell(1,length(cellContent));
wordfields = cell(1,length(cellContent));
while n < length(cellContent)
    n=n+1;
    line = cellContent{n};oneword = false;
    hooks = find(line == 62);
    iWord = iWord+1;
    wordindex{iWord} = index(n);
    if any(line == 32) && ~openandclose(n)
        if ~isempty(hooks) && hooks(1) < find(line==32,1)
            word{iWord} = line(2:hooks(1)-1);
            iLine = hooks(1)+1;
        else
            word{iWord} = line(2:find(line==32,1)-1);
            iLine = find(line==32,1)+1;
        end
    elseif ~isempty(hooks) && length(line)>=8 && strcmp('comment',line(2:8))
        % add exception for comment
        word{iWord} = line(2:hooks(1)-1);
        iLine = hooks(1)+1;
    elseif openandclose(n)
        word{iWord} = line(2:find(line==62,1)-1);
        iLine = find(line==62,1)+1;
    else
        word{iWord} = line(2:end-1);
        oneword = true;
    end
    if word{iWord}(1) ~= '/'
        if ~oneword && ~openandclose(n)
            k = find(line == 34);
            k = reshape(k,2,length(k)/2)';
            l = [iLine find(line(iLine:end) == 61)+iLine-2];
            fieldname = cell(1,length(l)-1); value = cell(1,length(l)-1);
            if ~isempty(k)
                for il=1:size(k,1)
                    fieldname{il} = line(iLine:find(line(iLine:end) == 61,1)+iLine-2);
                    if size(k,1) > 1 && il < size(k,1)
                        a = strfind(line(iLine:end),'" ')+iLine+1;
                        iLine = a(1);
                    end
                    value{il} = line(k(il,1)+1:k(il,2)-1);
                end
            else
                value = []; fieldname =[];
                value = line(find(line == 62,1)+1:end);
            end
        elseif ~oneword && openandclose(n)
            value = []; fieldname =[];
            value = line(find(line == 62,1)+1:find(line==60,1,'last')-1);
        else
            value = NaN;fieldname = [];
        end
        wordvalue{iWord} = value;
        wordfields{iWord} = fieldname;
    end
end
isendword = cellfun(@(x) x(1) == '/',word);
endwords = cellfun(@(x) x(2:end),word(isendword),'UniformOutput',false);
kindofendwords = unique(endwords);
placeoffirststartword = zeros(1,length(kindofendwords));
placeofallendwords = cell(1,length(kindofendwords));
placeofallstartwords = cell(1,length(kindofendwords));
for n=1:length(kindofendwords)
    lengthWord = length(cell2mat(kindofendwords(n)));
    placeoffirststartword(n) = find(strncmp(word,kindofendwords(n),lengthWord),1);
    placeofallstartwords{n} = find(strncmp(word,kindofendwords(n),lengthWord));
    placeofallendwords{n} = find(strncmp(word,['/' kindofendwords{n}],lengthWord+1));
end
[a b] = sort(placeoffirststartword);
startwords = kindofendwords;
for n=1:length(startwords)
    obj.(startwords{n}).number = length(placeofallstartwords{n});
    obj.(startwords{n}).index = index(a(n));
    obj.(startwords{n}).count = 0;
end

%% get values
for n=1:length(wordvalue)
    if mod(n,5000) == 0
        waitbar((n/length(wordvalue))/2, hWaitbar);
    end

    if iscell(wordvalue{n})
        if length(wordvalue{n}) == 1
            B = [];
            try
                B = str2num(wordvalue{n}{1});
            end
            if ~isempty(B)
                wordvalue{n} = B;
            else
                wordvalue{n} = wordvalue{n}{1};
            end
        else
            for m=1:length(wordvalue{n})
                try
                    B = str2num(wordvalue{n}{m});
                    if ~isempty(B)
                        wordvalue{n}{m} = B;
                    end
                end
            end
        end
    else
        try
            B = str2num(wordvalue{n});
            if ~isempty(B)
                wordvalue{n} = B;
            end
        end
    end
end
%% put everything in struct
firstFramesFound = false;
nFramesToBeFound = 5;
nFramesFound = 0;
nFrames = length(cell2mat(placeofallendwords(strcmp(kindofendwords,'frame'))));
lastwordisendword = false;lastendword = '';
superstruct = struct;name = cell(1,max(index)+1);namecounter = ones(1,max(index));endplace = inf(1,max(index));
for iWord=1:length(word)
    if mod(iWord,5000) == 0
        waitbar(iWord/length(word) + 0.5, hWaitbar);
    end
    if word{iWord}(1)=='/'
        startword = word{iWord}(2:end);
        if any(strcmp(startword,name))
            name(find(strcmp(startword,name),1):end) = [];
        end
        if lastwordisendword
            obj.(lastendword).count = 0;
        end
        lastendword = startword;
        lastwordisendword = true;
    else
        lastwordisendword = false;
        try
            if ~isempty(wordfields{iWord})
                wordfields{iWord} = cellfun(@(x) x(x~=32), wordfields{iWord},'UniformOutput',false);
            end
            word(iWord) = checkText(word(iWord));
            wordfields{iWord} = checkText(wordfields{iWord});

            if any(strncmp(startwords,word{iWord},length(startwords)))
                if strcmp(word{iWord},'frame')
                    nFramesFound = nFramesFound + 1;
                    if ~firstFramesFound && nFramesFound >= nFramesToBeFound
                        firstFramesFound = true;
                        % preallocate frames in superstruct
                        % Assume remainder of the file contains frames,
                        % with exception of security code at the end
                        frames(1:nFrames,1) = superstruct.mvnx.subject.frames.frame(end);
                        frames(1:nFramesFound-1) = superstruct.mvnx.subject.frames.frame(1:nFramesFound-1);
                    end
                    if firstFramesFound
                        fields = wordfields{iWord};
                        for il = 1:length(fields)
                            frames(nFramesFound).(fields{il}) = wordvalue{iWord}{il};
                        end
                    end
                end
                if isfield(obj, word{iWord})
                    obj.(word{iWord}).count = obj.(word{iWord}).count + 1;
                else
                    obj.(word{iWord}).count = 1;
                end
                name{index(iWord)} = word{iWord};
                namecounter(index(iWord)) = obj.(word{iWord}).count;
                if ~firstFramesFound && (iscell(wordvalue{iWord}) || ~isempty(wordvalue{iWord}) && all(~isnan(wordvalue{iWord})))
                    superstruct = setvalue(superstruct,index(iWord),wordvalue{iWord},name(1:index(iWord)),wordfields{iWord},namecounter);
                end
            elseif iWord > 1 && strcmp(word{iWord},word{iWord-1})
                name{index(iWord)} = word{iWord};
                namecounter(index(iWord)) = namecounter(index(iWord))+1;
                superstruct = setvalue(superstruct,index(iWord),wordvalue{iWord},name(1:index(iWord)),wordfields{iWord},namecounter);
            else
                name{index(iWord)} = word{iWord};
                namecounter(index(iWord)) = 1;
                if firstFramesFound && ~strcmp(word{iWord},'securityCode')
                    frames(nFramesFound).(word{iWord}) = wordvalue{iWord};
                else
                    superstruct = setvalue(superstruct,index(iWord),wordvalue{iWord},name(1:index(iWord)),wordfields{iWord},namecounter);
                end
            end
        catch e
            disp(getReport(e))
        end
    end
end
if firstFramesFound
    superstruct.mvnx.subject.frames.frame = frames';
    if obj.frame.number > nFramesFound
        superstruct.mvnx.subject.frames.frame(nFramesFound+1:end) = [];
    end
end

%% get output
mvnx = superstruct.mvnx;

delete(hWaitbar);
end
function superstruct = setvalue(superstruct,index,value,name,fields,namecounter)
%superstruct = setvalue(superstruct,index,value,name,fields,namecounter)
% add values to a very big struct
if ~isempty(fields) && (~iscell(fields) || ~isempty(fields{1}))
    if length(fields) == 1
        name(end+1) = fields;
    else
        name{end+1} = fields;
    end
    index = index+1;
end
switch index
    case 1
        if ~iscell(name{1})
            superstruct.(name{1}) = value;
        else
            for il = 1:length(name{1})
                superstruct.(name{1}{il}) = value{il};
            end
        end
    case 2
        if ~iscell(name{2})
            superstruct.(name{1})(namecounter(1)).(name{2}) = value;
        else
            for il = 1:length(name{2})
                superstruct.(name{1})(namecounter(1)).(name{2}{il}) = value{il};
            end
        end
    case 3
        if ~iscell(name{3})
            superstruct.(name{1})(namecounter(1)).(name{2})(namecounter(2)).(name{3})...
                = value;
        else
            for il = 1:length(name{3})
                superstruct.(name{1})(namecounter(1)).(name{2})(namecounter(2)).(name{3}{il}) = value{il};
            end
        end
    case 4
        if ~iscell(name{4})
            superstruct.(name{1})(namecounter(1)).(name{2})(namecounter(2)).(name{3})(namecounter(3))....
                .(name{4}) = value;
        else
            for il = 1:length(name{4})
                superstruct.(name{1})(namecounter(1)).(name{2})(namecounter(2)).(name{3})(namecounter(3))...
                    .(name{4}{il}) = value{il};
            end
        end
    case 5
        if ~iscell(name{5})
            superstruct.(name{1})(namecounter(1)).(name{2})(namecounter(2)).(name{3})(namecounter(3))....
                .(name{4})(namecounter(4)).(name{5}) = value;
        else
            for il = 1:length(name{5})
                superstruct.(name{1})(namecounter(1)).(name{2})(namecounter(2)).(name{3})(namecounter(3))....
                    .(name{4})(namecounter(4)).(name{5}{il}) = value{il};
            end
        end
    case 6
        if ~iscell(name{6})
            superstruct.(name{1})(namecounter(1)).(name{2})(namecounter(2)).(name{3})(namecounter(3))....
                .(name{4})(namecounter(4)).(name{5})(namecounter(5)).(name{6}) = value;
        else
            for il = 1:length(name{6})
                superstruct.(name{1})(namecounter(1)).(name{2})(namecounter(2)).(name{3})(namecounter(3))....
                    .(name{4})(namecounter(4)).(name{5})(namecounter(5)).(name{6}{il}) = value{il};
            end
        end
    case 7
        if ~iscell(name{7})
            superstruct.(name{1})(namecounter(1)).(name{2})(namecounter(2)).(name{3})(namecounter(3))....
                .(name{4})(namecounter(4)).(name{5})(namecounter(5)).(name{6})(namecounter(6))...
                .(name{7}) = value;
        else
            for il = 1:length(name{7})
                superstruct.(name{1})(namecounter(1)).(name{2})(namecounter(2)).(name{3})(namecounter(3))....
                    .(name{4})(namecounter(4)).(name{5})(namecounter(5)).(name{6})(namecounter(6))...
                    .(name{7}{il}) = value{il};
            end
        end
    case 8
        if ~iscell(name{8})
            superstruct.(name{1})(namecounter(1)).(name{2})(namecounter(2)).(name{3})(namecounter(3))....
                .(name{4})(namecounter(4)).(name{5})(namecounter(5)).(name{6})(namecounter(6))...
                .(name{7})(namecounter(7)).(name{8}) = value;
        else
            for il = 1:length(name{7})
                superstruct.(name{1})(namecounter(1)).(name{2})(namecounter(2)).(name{3})(namecounter(3))....
                    .(name{4})(namecounter(4)).(name{5})(namecounter(5)).(name{6})(namecounter(6))...
                    .(name{7})(namecounter(7)).(name{8}{il}) = value{il};
            end
        end
end
end

function word = checkText(word)
%word = checkText(word)
% make sure the field name is just text and allowed symbols.
if ~isempty(word)
    if ~iscell(word)
        error('should get cells')
    end
    for i=1:length(word)
        if length(word{i})>1
            word{i}(word{i}=='!') = [];
            word{i}(word{i}==':') = '_';
            if word{i}(end) == '/'
                word{i}(end) = [];
            end
            while (word{i}(1) < 65 || word{i}(1) > 122 || (word{i}(1)> 90 && word{i}(1) < 97))
                word{i}(1)=[];
            end
        end
    end
end
end


function [s,success] = dmc_xml2struct(file)

%Convert xml file into a MATLAB structure
%  [S,SUCCESS]= DMC_XML2STRUCT(SOURCE) Reads xml-formatted SOURCE and returns a
%  structure S. S contains the attributes in SOURCE, nested to reflect the
%  xml children as appropriate. If SOURCE cannot be parsed for any reason
%  the s is returned as an empty matrix [] and SUCCESS is set to 0.
%  Otherwise SUCCESS is 1.
%
%  EXAMPLE
%  A file containing:
%    <XMLname attrib1="Some value">
%      <Element>Some text</Element>
%      <DifferentElement attrib2="2">Some more text</Element>
%      <DifferentElement attrib3="2" attrib4="1">Even more text</DifferentElement>
%    </XMLname>
%
%  Will produce:
%    s.XMLname.Attributes.attrib1 = "Some value";
%    s.XMLname.Element.Text = "Some text";
%    s.XMLname.DifferentElement{1}.Attributes.attrib2 = "2";
%    s.XMLname.DifferentElement{1}.Text = "Some more text";
%    s.XMLname.DifferentElement{2}.Attributes.attrib3 = "2";
%    s.XMLname.DifferentElement{2}.Attributes.attrib4 = "1";
%    s.XMLname.DifferentElement{2}.Text = "Even more text";
%
%  Note the characters : - and . are not supported in structure fieldnames and
%  are replaced by _

%  Modified from function xml2struct (Matlab exchange File ID: #28518)
%  Copyright by W. Falkena. distributed under BSD license.
%  Last accessed Feb. 3, 2011
%  Modifications here allow xml loading from URLs and return null
%  result when file or URL is invalid.
%
%  MODIFIED BY: Michael West, Geophysical Institute, Univ. of Alaska Fairbanks
%  $Date$
%  $Revision$

%check for URL for file name
if (nargin~=1)
    error('xml2struct:IncorrectNumberOfArguments','Incorrect number of arguments');
end
% VALID = 0;
% if strfind(file,'http://')
%     VALID = 1;
% elseif exist(file,'file')
%     VALID = 1;
% elseif exist([file '.xml'],'file')
%     VALID = 1;
% else
%     warning('xml2struct:argumentIsNotFileOrURL',['URL or filename not recognized: ' file]);
% end

try
    xDoc = xmlread(file);
    s = parseChildNodes(xDoc);
    success = 1;
catch
    %warning('xml2struct:InvalidFileOrURL',['No xml code could be parsed from URL (or filename): ' file]);
    s = [];
    success = 0;
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   Subfunction parseChildNodes
function [children,ptext] = parseChildNodes(theNode)
% Recurse over node children.
children = struct;
ptext = [];
if theNode.hasChildNodes
    childNodes = theNode.getChildNodes;
    numChildNodes = childNodes.getLength;

    for count = 1:numChildNodes
        theChild = childNodes.item(count-1);
        [text,name,attr,childs] = getNodeData(theChild);

        if (~strcmp(name,'#text') && ~strcmp(name,'#comment'))
            %XML allows the same elements to be defined multiple times,
            %put each in a different cell
            if (isfield(children,name))
                if (~iscell(children.(name)))
                    %put existsing element into cell format
                    children.(name) = {children.(name)};
                end
                index = length(children.(name))+1;
                %add new element
                children.(name){index} = childs;
                if(~isempty(text))
                    children.(name){index}.('Text') = text;
                end
                if(~isempty(attr))
                    children.(name){index}.('Attributes') = attr;
                end
            else
                %add previously unkown new element to the structure
                children.(name) = childs;
                if(~isempty(text))
                    children.(name).('Text') = text;
                end
                if(~isempty(attr))
                    children.(name).('Attributes') = attr;
                end
            end
        elseif (strcmp(name,'#text'))
            %this is the text in an element (i.e. the parentNode)
            if (~isempty(regexprep(text,'[\s]*','')))
                if (isempty(ptext))
                    ptext = text;
                else
                    %what to do when element data is as follows:
                    %<element>Text <!--Comment--> More text</element>

                    %put the text in different cells:
                    % if (~iscell(ptext)) ptext = {ptext}; end
                    % ptext{length(ptext)+1} = text;

                    %just append the text
                    ptext = [ptext text];
                end
            end
        end
    end
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% GET NODE DATA
function [text,name,attr,childs] = getNodeData(theNode)
% Create structure of node info.

%make sure name is allowed as structure name
name = regexprep(char(theNode.getNodeName),'[-:.]','_');

attr = parseAttributes(theNode);
if (isempty(fieldnames(attr)))
    attr = [];
end

%parse child nodes
[childs,text] = parseChildNodes(theNode);

if (isempty(fieldnames(childs)))
    %get the data of any childless nodes
    try
        %faster then if any(strcmp(methods(theNode), 'getData'))
        text = char(theNode.getData);
    catch
        %no data
    end
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% PARSE THE ATTRIBURES
function attributes = parseAttributes(theNode)
% Create attributes structure.

attributes = struct;
if theNode.hasAttributes
    theAttributes = theNode.getAttributes;
    numAttributes = theAttributes.getLength;

    for count = 1:numAttributes
        attrib = theAttributes.item(count-1);
        attr_name = regexprep(char(attrib.getName),'[-:.]','_');
        attributes.(attr_name) = char(attrib.getValue);
    end
end


function obj = checkToolboxes(obj)
	% Biafra Ahanonu
	% Started: 2021.03.25 [22:11:25] (branched from ciatah.m)

	license('inuse')
end


function clean()

clear all;

setenv('ACADOS_INSTALL_DIR', '');

ocl_path  = fileparts(which('ocl'));

% clean export
if exist(fullfile(ocl_path,'Workspace','export'), 'dir')
  addpath(fullfile(ocl_path,'Workspace','export'));
  rmpath(fullfile(ocl_path,'Workspace','export'));

  success = rmdir(fullfile(ocl_path,'Workspace','export'), 's');
  if ~success
    error('Could not remove export folder. Restart Matlab and run clean again.');
  end
end

% clean acados lib
if exist(fullfile(ocl_path,'Lib','acados'), 'dir')
  addpath(fullfile(ocl_path,'Lib','acados'));
  rmpath(fullfile(ocl_path,'Lib','acados'));

  success = rmdir(fullfile(ocl_path,'Lib','acados'), 's');
  if ~success
    error('Could not remove acados binaries folder. Restart Matlab and run clean again.');
  end
end


function sitem = cfg2struct(item)

% function sitem = cfg2struct(item)
% Return a struct containing all fields of item plus a field type. This is
% the method suitable for cfg_choice and repeat classes. It descends down
% the values field to convert the cfg_items in this field into structs.
%
% 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: cfg2struct.m 1716 2008-05-23 08:18:45Z volkmar $

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

% Get parent struct, re-classify as field 'type'
sitem = cfg2struct(item.cfg_item);
sitem.type = class(item);

% Need to cycle through added fields
fn = mysubs_fields;
for k = 1:numel(fn)
    sitem.(fn{k}) = item.(fn{k});
end;

% Treat values{:} fields
if numel(item.values) > 0
    for k = 1:numel(item.values)
        sitem.values{k} = cfg2struct(item.values{k});
    end;
end;