classdef PTKSettings < CoreBaseClass
    % PTKSettings. Part of the internal gui for the TD MIM Toolkit.
    %
    %     You should not use this class within your own code. It is intended to
    %     be used internally within the gui of the TD MIM Toolkit.
    %
    %     PTKSettings stores gui application settings between sessions. This
    %     class is stored on disk so that settings persist betweek sessions.
    %
    %
    %     Licence
    %     -------
    %     Part of the TD MIM Toolkit. https://github.com/tomdoel
    %     Author: Tom Doel, Copyright Tom Doel 2014.  www.tomdoel.com
    %     Distributed under the MIT licence. Please see website for details.
    %

    properties
        OverlayOpacity = 50
        ImageInfo = []
        SliceNumber = [1 1 1]
        SaveImagePath = ''
        ShowTextLabels = true
        CurrentMarkerColour = 1
        ScreenPosition
        PatientBrowserScreenPosition
        DeveloperMode = false
        LastUidForPatientMap
        LastMarkerSetForPatientMap
    end

    properties (Transient, Access = private)
        SettingsFilename
    end

    methods (Static)
        function settings = LoadSettings(app_def, reporting)
            try
                settings_filename = app_def.GetSettingsFilePath;
                if exist(settings_filename, 'file')
                    settings_struct = MimDiskUtilities.Load(settings_filename);
                    settings = settings_struct.settings;
                else
                    reporting.Log('No settings file found. Will create new one on exit');
                    settings = PTKSettings;
                end
                settings.SettingsFilename = settings_filename;
                if isempty(settings.LastMarkerSetForPatientMap)
                    settings.LastMarkerSetForPatientMap = containers.Map;
                end
                if isempty(settings.LastUidForPatientMap)
                    settings.LastUidForPatientMap = containers.Map;
                end

            catch ex
                reporting.ErrorFromException('PTKSettings:FailedtoLoadSettingsFile', ['Error when loading settings file ' settings_filename '. Try deleting this file.'], ex);
            end

        end

    end

    methods
        function obj = PTKSettings
            obj.LastUidForPatientMap = containers.Map;
            obj.LastMarkerSetForPatientMap = containers.Map;
        end

        function ApplySettingsToGui(obj, gui, viewer_panel)
            gui.DeveloperMode = obj.DeveloperMode;
            viewer_panel.OverlayOpacity = obj.OverlayOpacity;
            viewer_panel.SliceNumber = obj.SliceNumber;
            viewer_panel.MarkerImageDisplayParameters.ShowLabels = obj.ShowTextLabels;
            viewer_panel.NewMarkerColour = obj.CurrentMarkerColour;
        end

        function UpdateSettingsFromGui(obj, gui, viewer_panel)
            obj.DeveloperMode = gui.DeveloperMode;
            obj.OverlayOpacity = viewer_panel.OverlayOpacity;
            obj.SliceNumber = viewer_panel.SliceNumber;
            obj.ShowTextLabels = viewer_panel.MarkerImageDisplayParameters.ShowLabels;
            obj.CurrentMarkerColour = viewer_panel.NewMarkerColour;
        end

        function SetLastImageInfo(obj, image_info, reporting)
            if ~isequal(image_info, obj.ImageInfo)
                obj.ImageInfo = image_info;
                obj.SaveSettings(reporting);
            end
        end

        function AddLastPatientUid(obj, patient_id, series_uid)
            if isempty(obj.LastUidForPatientMap)
                obj.LastUidForPatientMap = containers.Map;
            end
            obj.LastUidForPatientMap(patient_id) = series_uid;
        end

        function AddLastMarkerSet(obj, series_uid, marker_set_name)
            if isempty(obj.LastMarkerSetForPatientMap)
                obj.LastMarkerSetForPatientMap = containers.Map;
            end
            obj.LastMarkerSetForPatientMap(series_uid) = marker_set_name;
        end

        function RemoveLastMarkerSet(obj, series_uid, marker_set_name)
            if ~isempty(obj.LastMarkerSetForPatientMap) && obj.LastMarkerSetForPatientMap.isKey(series_uid) && strcmp(obj.LastMarkerSetForPatientMap(series_uid), marker_set_name)
                obj.LastMarkerSetForPatientMap.remove(series_uid);
            end
        end

        function series_uid = GetLastPatientUid(obj, patient_id)
            if obj.LastUidForPatientMap.isKey(patient_id)
                series_uid = obj.LastUidForPatientMap(patient_id);
            else
                series_uid = [];
            end
        end

        function marker_set_name = GetLastMarkerSetName(obj, series_uid)
            if isempty(obj.LastMarkerSetForPatientMap)
                obj.LastMarkerSetForPatientMap = containers.Map;
            end
            if obj.LastMarkerSetForPatientMap.isKey(series_uid)
                marker_set_name = obj.LastMarkerSetForPatientMap(series_uid);
            else
                marker_set_name = [];
            end
        end

        function RemoveLastPatientUid(obj, series_uids)
            for key = obj.LastUidForPatientMap.keys
                if any(strcmp(obj.LastUidForPatientMap(key{1}), series_uids))
                    obj.LastUidForPatientMap.remove(key{1});
                end
            end
            for key = obj.LastMarkerSetForPatientMap.keys
                if any(strcmp(obj.LastMarkerSetForPatientMap(key{1}), series_uids))
                    obj.LastMarkerSetForPatientMap.remove(key{1});
                end
            end

            if ~isempty(obj.ImageInfo) && any(strcmp(obj.ImageInfo.ImageUid, series_uids))
                obj.ImageInfo = [];
            end
        end

        function SetLastSaveImagePath(obj, image_path, reporting)
            if ~isempty(image_path) && ischar(image_path) && ~strcmp(image_path, obj.SaveImagePath)
                obj.SaveImagePath = image_path;
                obj.SaveSettings(reporting);
            end
        end

        function SetPosition(obj, main_screen_position, patient_browser_position)
            obj.ScreenPosition = main_screen_position;
            obj.PatientBrowserScreenPosition = patient_browser_position;
        end

        function SaveSettings(obj, reporting)

            settings_filename = obj.SettingsFilename;

            try
                value = [];
                value.settings = obj;
                if isempty(settings_filename)
                    reporting.ShowWarning('PTKSettings:NoSettingsFilename', 'The settings file could not be saved as the settings filename was not known.', []);
                else
                    MimDiskUtilities.Save(settings_filename, value);
                end
            catch ex
                reporting.ErrorFromException('PTKSettings:FailedtoSaveSettingsFile', ['Unable to save settings file ' settings_filename], ex);
            end
        end
    end
end


% THIS SOFTWARE AND ANY ACCOMPANYING DOCUMENTATION IS RELEASED "AS IS."  THE U.S. GOVERNMENT MAKES NO WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, CONCERNING THIS SOFTWARE AND ANY ACCOMPANYING DOCUMENTATION, INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.  IN NO EVENT WILL THE U.S. GOVERNMENT BE LIABLE FOR ANY DAMAGES, INCLUDING ANY LOST PROFITS, LOST SAVINGS OR OTHER INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE, OR INABILITY TO USE, THIS SOFTWARE OR ANY ACCOMPANYING DOCUMENTATION, EVEN IF INFORMED IN ADVANCE OF THE POSSIBILITY OF SUCH DAMAGES.
%
% change log:
%   040204 smw stub file
%
% file: get_ci_cs1_1s.m
%
function varargout = get_ci_cs1_1s(varargin)
  error('get_ci_cs1_1s is not part of current release.');
return;


function hRD = plugin_rd_rx
% Reference design definition

% Call the common reference design definition function
hRD = AnalogDevices.adrv9371x.common.plugin_rd('ZCU102', 'Rx');
AnalogDevices.adrv9371x.zcu102.add_io(hRD, 'Rx');


function cn=adodbcn(cnstr,cto)
% cn = adodbcn(cnstr,[cto])
%
% Connects to ADO OLEDB using the Microsoft ActiveX Data Source Control
%
% Inputs:
%   cnstr,  str containing information for connecting to data source
%   cto,    CommandTimeout in seconds (default=60 seconds if unspecified)
%
% Output:
%   cn,     connection
%
% Notes: Refer to adodb_demo.m and adodbcnstr.m for example connection
% strings for Oracle, SQL, and MS Access databases
%
% This code basis on Tim Myers code (oledb*.m) and use ADO OLE DB instead
% of OWC - Office Web Component
%
% Martin Furlan
% martin.furlan@iskra-ae.com
% January 2007

%create activeX control
cn = actxserver('ADODB.Connection');
set(cn,'CursorLocation',3);

%Open connection
invoke(cn,'Open', cnstr);

%Specify connection timeout if provided
if nargin>1
    set(cn,'CommandTimeout',cto);
else
    set(cn,'CommandTimeout',60);    %default
end


function B = tocstruct(A)
    if iscstruct(A)
        B = A;
    elseif isnumeric(A)
        B.real = real(A);
        B.imag = imag(A);
    else
        error('Input does not have the expected format.');
    end
end


% ----------------------------------------------------------------------------
% function hfssInsertDesign(fid, designName, [designType = 'driven modal'])
%
% Description :
% -------------
% Create the necessary VB Script to insert an HFSS Design into the Project
% and set it as the active design.
%
% Parameters :
% ------------
% fid        - file identifier of the HFSS script file.
% designName - name of the new design to be inserted.
% designType - (Optional String) choose from the following:
%              1. 'driven modal' (default)
%			   2. 'driven terminal'
%			   3. 'eigenmode'
%
% Note :
% ------
% This function is usually called after a call to either hfssNewProject()
% or hfssOpenProject(), but this is not necessary.
%
% Example :
% ---------
% fid = fopen('myantenna.vbs', 'wt');
% ...
% hfssInsertDesign(fid, 'Dipole_SingleElement');
% ----------------------------------------------------------------------------

% ----------------------------------------------------------------------------
% This file is part of HFSS-MATLAB-API.
%
% HFSS-MATLAB-API is free software; you can redistribute it and/or modify it
% under the terms of the GNU General Public License as published by the Free
% Software Foundation; either version 2 of the License, or (at your option)
% any later version.
%
% HFSS-MATLAB-API 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
% Foobar; if not, write to the Free Software Foundation, Inc., 59 Temple
% Place, Suite 330, Boston, MA  02111-1307  USA
%
% Copyright 2004, Vijay Ramasami (rvc@ku.edu)
% ----------------------------------------------------------------------------
function hfssInsertDesign(fid, designName, designType)

% arguments processor.
if (nargin < 2)
	error('Insufficient number of arguments !');
elseif (nargin < 3)
	designType = [];
end

% default arguments.
if isempty(designType)
	designType = 'driven modal';
end

% create the necessary script.
fprintf(fid, '\n');
fprintf(fid, 'oProject.InsertDesign "HFSS", ');
fprintf(fid, '"%s", ', designName);
switch (lower(designType))
	case 'driven terminal'
		fprintf(fid, '"DrivenTerminal", ""\n');
	case 'driven modal'
		fprintf(fid, '"DrivenModal", ""\n');
	case 'eigenmode'
		fprintf(fid, '"Eigenmode", ""\n');
end
fprintf(fid, 'Set oDesign = oProject.SetActiveDesign("%s")\n', designName);
fprintf(fid, 'Set oEditor = oDesign.SetActiveEditor("3D Modeler")\n');


function cj = del_in_source(tdeps, cj)

% function cj = del_in_source(tdeps, cj)
% delete foreign target dependencies from own source dependencies.
%
% 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: del_in_source.m 1716 2008-05-23 08:18:45Z volkmar $

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

for k = 1:numel(tdeps)
    sitem = subsref(cj, tdeps(k).src_exbranch); % Source item to deal with
    stind = false(1,numel(sitem.sdeps));
    for l = 1:numel(sitem.sdeps)
        stind(l) = ~(isequaltarget(tdeps(k), sitem.sdeps(l)) && ...
                     isequalsource(tdeps(k), sitem.sdeps(l)));
    end;
    sitem.sdeps = sitem.sdeps(stind);
    cj = subsasgn(cj, tdeps(k).src_exbranch,sitem);
end;


%MIN Dataset overload


function MRSIStruct = setFov(MRSIStruct, dimension, value)
    switch(lower(dimension))
        case('x')
            MRSIStruct.fov.x = value;
        case('y')
            MRSIStruct.fov.y = value;
        case('z')
            MRSIStruct.fov.z = value;
    end
end


function value = get_option(option_list,option,default,type)
% extract option from option list
%
% In case the option occurs more than one time in the option list the first
% value that meets the type condition is returned.
%
% Syntax
%   value = get_option(option_list,option_name,default_option,option_type)
%
% Input
%  option_list   - Cell Array
%  option_name   - String
%  option_default- default value
%  option_type   - class name or list of class names
% Output
%  value         - option value
%
% See also
% check_option set_option delete_option

if nargin <= 2, value = [];else, value = default;end
if isempty(option_list), return;end
if nargin <= 3, type = [];end

pos = find_option(option_list,option,type);

if pos, value = option_list{pos};end


%-----------------------------------------------------------------------
% Job configuration created by cfg_util (rev $Rev: 4899 $)
%-----------------------------------------------------------------------
matlabbatch{1}.menu_cfg.menu_struct.conf_choice.type = 'cfg_choice';
matlabbatch{1}.menu_cfg.menu_struct.conf_choice.name = 'Dir Operations';
matlabbatch{1}.menu_cfg.menu_struct.conf_choice.tag = 'dir_ops';
matlabbatch{1}.menu_cfg.menu_struct.conf_choice.values = {
                                                          '<UNDEFINED>'
                                                          '<UNDEFINED>'
                                                          '<UNDEFINED>'
                                                          }';
matlabbatch{1}.menu_cfg.menu_struct.conf_choice.check = [];
matlabbatch{1}.menu_cfg.menu_struct.conf_choice.help = {''};


% compile mex file
mex mex/perform_moment_transform.cpp mex/perform_moment_transform_mex.cpp


function compiler()

mex -g Seg2_Stim.c levelset.c Img_new.c gauss_seg.c gauss_vect_part_seg.c gauss_vect_seg.c gamma_seg.c ker_part_seg.c ker_seg.c levelutil.c mean_clust_seg.c mean_part_seg.c mean_seg.c mean_vect_seg.c;


function context = document_context(name, varargin)
% document_context Create report context structure
%
% Creates a new report context structure that can be used to generate
% report documents.
%
% Input:
% - name (string): Name of the report. Is used to name a directory where the report is stored in.
% - varargin[Title] (string): A human-friendly name of the report. May be more verbose than report name.
% - varargin[FigureEPS] (boolean): Should the report also generate formaps in Encapsulated PostScript (for LaTeX).
% - varargin[FigureRaw] (boolean): Should internal raw figures and data also be saved for future processing.
% - varargin[Standalone] (boolean): If true (default), the JavaScript and CSS resources are copied to the report.
% - varargin[Cache] (boolean): Should cache be used.
%
% Output:
% - context (structure): A report context structure.
%

title = name;
figure_eps = false;
figure_raw = false;
standalone = true;
cache = false;

for i = 1:2:length(varargin)
    switch lower(varargin{i})
        case 'title'
            title = varargin{i+1};
        case 'figureeps'
            figure_eps = varargin{i+1};
        case 'figureraw'
            figure_raw = varargin{i+1};
        case 'standalone'
            standalone = varargin{i+1};
        case 'cache'
            cache = varargin{i+1};
        otherwise
            error(['Unknown switch ', varargin{i}, '!']) ;
    end
end

context.root = fullfile(get_global_variable('directory'), 'reports', name);
context.images = fullfile(context.root, 'images');
context.raw = fullfile(context.root, 'raw');
context.data = fullfile(context.root, 'data');
context.exporteps = figure_eps;
context.exportraw = figure_raw;
context.standalone = standalone;
context.prefix = '';
context.imagesurl = 'images';
context.rawurl = 'raw';
context.dataurl = 'data';
context.title = title;
context.cache = cache;

mkpath(context.root);
mkpath(context.images);
mkpath(context.data);
mkpath(context.raw);

context.cachedir = fullfile(context.root, 'cache');
mkpath(context.cachedir);


classdef (Abstract) TagGeneratorX < BaseX
% TagGeneratorX abstract class
%
% Summary of TagGeneratorX:
%   This is the base class for all Tag Generators

    methods (Abstract)
        generate(this); % Generate new tag(s)
%         forget(this);   % Remove tag(s) from list of allocated tags
    end

end


function [isfound, foundvalue, properties] = getproperty(desiredproperty,properties,defaultvalue)
%GETPROPERTY returns a property value from a property list, or a default
%  value if none is available
%[isfound, foundvalue, properties] =
%      getproperty(desiredproperty,properties,defaultvalue)
%
% returns a property value (if found) from a property list, removing that
% property pair from the list.  only removes the first encountered property
% name.
%
%see also waveform/private/parseargs, waveform/private/property2varargin

pmask = strcmpi(desiredproperty,properties.name);
isfound = any(pmask);
if isfound
  foundlist = find(pmask);
  foundidx = foundlist(1);
  foundvalue = properties.val{foundidx};
  properties.name(foundidx) = [];
  properties.val(foundidx) = [];
else
  if exist('defaultvalue','var')
    foundvalue = defaultvalue;
  else
    foundvalue = [];
  end
  % do nothing to properties...
end


function pasteLossConvertFromClipboard(hFigWithLossConvertAppData)
%pasteLossConvertFromClipboard Summary of this function goes here
%   Detailed explanation goes here
    global GLOBAL_LossConvertClipboard;

    if(~isempty(GLOBAL_LossConvertClipboard))
        setappdata(hFigWithLossConvertAppData,'lossConverts',GLOBAL_LossConvertClipboard);
    else
        GLOBAL_LossConvertClipboard = [];
        warndlg('Could not paste Loss/Convert settings.  Clipboard contents are either empty or invalid.  Try copying mass loss/conversion settings to the clipboard first.','Could not paste loss/convert settings.');
    end
end


%AND Mapping overload


function serverStarted = mrmCheckServer(host)
%Test whether the server has been started.
%
%     serverStarted = mrmCheckServer(host)
%
% There should be a way to test without creating a new window.  But I am
% not sure how.
%
% (c) Stanford Vista Team, 2008

if ieNotDefined('host'), host = 'localhost'; end

% Try opening a window
stat = mrMesh(host, 999, 'refresh');

% If the server is not started, the window won't open and we get a return
% of -1000. Otherwise, the window was properly opened.
if stat ~= -1000
    % Window was opened properly by server.  So close it and return.
    serverStarted = 1;
    mrMesh(host,999,'close');
    return;
else
    % Tell 'em that the call didn't work, so the server isn't running.
    serverStarted = 0;
end

return;


classdef GemSeparator < GemPanel
    % GemSeparator GEM class for a separator line and label between panels
    %
    %     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
        TitleLeftPadding = 5
        TitleHeight = 15
        SeparatorHeight = 20
        TitleWidth = 80
        TitleFontSize = 11
        Bold = true
    end

    properties (Access = protected)
        TitlePanel
    end

    methods
        function obj = GemSeparator(parent_handle, title_text)
            obj = obj@GemPanel(parent_handle);
            obj.TopBorder = true;
            obj.TitlePanel = GemText(obj, upper(title_text), title_text, title_text);
            obj.TitlePanel.FontSize = obj.TitleFontSize;
            obj.TitlePanel.Bold = obj.Bold;
            obj.AddChild(obj.TitlePanel);
        end

        function Resize(obj, position)
            Resize@GemPanel(obj, position);
            title_panel_position = [1 + obj.TitleLeftPadding, 1, position(3) - obj.TitleLeftPadding, obj.TitleHeight];
            obj.TitlePanel.Resize(title_panel_position);
        end

        function height = GetRequestedHeight(obj, width)
            height = obj.SeparatorHeight;
        end

    end
end


function validatedir(status, mess, messid, filename)
    % check success of directory creation
    if (status == 0)
        if(~strcmp(messid, 'MATLAB:MKDIR:DirectoryExists'))
            error(['Error saving %s folder: ' mess ', ' messid ...
                   '. Please contact support@plot.ly for assistance.'], ...
                   filename);
        end
    end
end


%% EBSD
%
%%


function fig()
figure


% Copyright 2019 Jonas Koenemann, Moritz Diehl, University of Freiburg
% Redistribution is permitted under the 3-Clause BSD License terms. Please
% ensure the above copyright notice is visible in any derived work.
%
function warning(msg)
  warning(msg)
  global oclHasWarnings
  oclHasWarnings = true;


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

% Last Modified by GUIDE v2.5 08-Dec-2013 14:01:25

% Begin initialization code - DO NOT EDIT
    gui_Singleton = 1;
    gui_State = struct('gui_Name',       mfilename, ...
                       'gui_Singleton',  gui_Singleton, ...
                       'gui_OpeningFcn', @rts_OrbOpsConsole_OpeningFcn, ...
                       'gui_OutputFcn',  @rts_OrbOpsConsole_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
end

% --- Executes just before rts_OrbOpsConsole is made visible.
function rts_OrbOpsConsole_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 rts_OrbOpsConsole (see VARARGIN)
    % Choose default command line output for rts_OrbOpsConsole
    handles.output = hObject;

    hRtsMainGUI = varargin{1};
    vesselGUID = varargin{2};
    handles.mainGUI = hRtsMainGUI;
    handles.vesselGUID = vesselGUID;

    %Initialize OrbOps panel
    rts_initRTSOrbOpsPanel(hRtsMainGUI, handles.rts_OrbOpsConsole, handles.clockLabel, handles.connStatusLabel, vesselGUID, handles.orbitTextDispLabel, ...
                            handles.orbitDispAxes, handles.targetOrbitTextDispLabel, handles.maneuversTextDispLabel, handles.rendInfoTextDispLabel);

    % Update handles structure
    guidata(hObject, handles);

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

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

% Get default command line output from handles structure
    varargout{1} = handles.output;
end

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

% Hint: delete(hObject) closes the figure

    rts_pageCloseStopTimers(hObject);
    delete(hObject);
end

% --- Executes on button press in prevManButton.
function prevManButton_Callback(hObject, eventdata, handles)
% hObject    handle to prevManButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    set(handles.maneuversTextDispLabel, 'UserData', max(get(handles.maneuversTextDispLabel,'UserData')-1,0));
end

% --- Executes on button press in nextManButton.
function nextManButton_Callback(hObject, eventdata, handles)
% hObject    handle to nextManButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    set(handles.maneuversTextDispLabel, 'UserData', max(get(handles.maneuversTextDispLabel,'UserData')+1,0));
end


% Copyright 2019 Jonas Koenemann, Moritz Diehl, University of Freiburg
% Redistribution is permitted under the 3-Clause BSD License terms. Please
% ensure the above copyright notice is visible in any derived work.
%
function deprecation(msg)
  ocl.utils.warning(msg);


% THIS SOFTWARE AND ANY ACCOMPANYING DOCUMENTATION IS RELEASED "AS IS."  THE U.S. GOVERNMENT MAKES NO WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, CONCERNING THIS SOFTWARE AND ANY ACCOMPANYING DOCUMENTATION, INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.  IN NO EVENT WILL THE U.S. GOVERNMENT BE LIABLE FOR ANY DAMAGES, INCLUDING ANY LOST PROFITS, LOST SAVINGS OR OTHER INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE, OR INABILITY TO USE, THIS SOFTWARE OR ANY ACCOMPANYING DOCUMENTATION, EVEN IF INFORMED IN ADVANCE OF THE POSSIBILITY OF SUCH DAMAGES.
%
% change log:
%   040204 tdr stub file
%
% file: get_ci_ribp_1s.m
%
function varargout = get_ci_ribp_1s(varargin)
  error('get_ci_ribp_1s is not part of current release.');
return;


function fullErrMsg = bst_error(errMsg, errTitle, isStack)
% BST_ERROR: Process an error (Display error message, and send a bug report)
%
% Usage : bst_error()                          : Display lasterror
%         bst_error(errMsg, errTitle, isStack) : Report an error
%         bst_error(errMsg, errTitle)          : Report an error (stack is displayed)
%         bst_error(errMsg)                    : Report an error (errTitle is the name of the calling script)
%         fullErrMsg = bst_error(...)          : Do not display anything, just return the full error message

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

global GlobalData;

% Display lasterror
if (nargin == 0)
    e = lasterror;
    % If no error available: create an empty error
    if isempty(e)
        try
            error('Brainstorm:NoError', 'NoError');
        catch
        end
        e = lasterror;
    end
    % Catch OUT OF MEMORY errors
    if strcmpi(e.identifier, 'MATLAB:nomem')
        errStack = e.stack;
        errMsg   = ['Out of memory. ' 10 10 'Please unload some datasets (or restart Matlab) an try again.'];
        errTitle = '';
        isStack  = 1;
    % Get lasterror stack and error message
    else
        % If error stack is empty, use current call stack
        if isempty(e.stack)
            % Get current stack trace
            errStack = dbstack();
            % Remove call to bst_error() from stack
            errStack(1) = [];
        else
            errStack = e.stack;
        end
        errMsg   = e.message;
        errTitle = '';
        isStack  = 1;
        % Remove HTML tags
        errMsg = str_striptag(errMsg);
        % Remove "Error using"
        errMsg = strrep(errMsg, 'Error using ==>', '');
        errMsg = strrep(errMsg, 'Error using', '');
    end
% Else : display bst_error line
else
    % Get current stack trace
    errStack = dbstack();
    % Remove call to bst_error() from stack
    errStack(1) = [];
    % Get error title if not defined
    if (nargin < 2)
        errTitle = '';
    end
    % If isStack not defined : set default to 1
    if (nargin < 3)
        isStack = 1;
    end
end

if isempty(errStack)
    return
end

% Set default default title
if isempty(errTitle)
    [tmp__, errFile] = fileparts(errStack(1).file);
    errTitle = ['Error in ' errFile '.m'];
end

% Print line number
strLine = [];
if isStack
    strLine = sprintf('Line %d: ', errStack(1).line);
end
% Print stack trace
strStack = [];
if isStack
    % For each stack level
    for i = 1:length(errStack)
        % Get filename
        [tmp__, errFile] = fileparts(errStack(i).file);
        errFile = [errFile, '.m']; %#ok<AGROW>
        % If s.name = s.file : do not display name
        if strcmpi(errFile, [errStack(i).name '.m'])
            strStack = sprintf('%s>%s at %d\n', strStack, errFile, errStack(i).line);
        else
            strStack = sprintf('%s>%s>%s at %d\n', strStack, errFile, errStack(i).name, errStack(i).line);
        end
    end
    strStack = sprintf('\n_______________________________________________\nCall stack:\n%s_______________________________________________\n', strStack);
end

% Full dialog error message
fullErrMsg = sprintf('%s%s\n%s', strLine, errMsg, strStack);
% Full console error message
consoleMsg = strrep(fullErrMsg(1:end-1), '_______________________________________________', '');
consoleMsg = strrep(consoleMsg, char([10 10]), char(10));
consoleMsg = strrep(consoleMsg, char(10), [10 '** ']);
consoleMsg = [10 '***************************************************************************' 10 ...
              '** Error: ' consoleMsg ...
              10 '***************************************************************************' 10];

% If no text output: display messages
if (nargout == 0)
    % Do not display java dialog in case of server mode
    if isempty(GlobalData) || ~isfield(GlobalData, 'Program') || ~isfield(GlobalData.Program, 'GuiLevel') || (GlobalData.Program.GuiLevel >= 0)
        % Hide progress bar
        bst_progress('stop');
        % If there are too many lines, truncate the message
        MAX_LINES = 30;
        if (nnz(fullErrMsg == 10) > MAX_LINES)
            iCut = find(fullErrMsg == 10, MAX_LINES);
            fullErrMsgDlg = [fullErrMsg(1:iCut(end)-1) 10 '...' 10 '[See command window for full error message]'];
        else
            fullErrMsgDlg = fullErrMsg;
        end
        % Display error message window
        java_dialog('errorhelp', fullErrMsgDlg, errTitle);
    end
    % Display error message in Matlab console
    disp(consoleMsg);
    % Close all the open files
    fclose all;
end

% %% ===== SENDING BUG REPORT =====
% % Send email only if error is not a known error (arguments are given to the function)
% if (nargin == 0)
%     % Send bug report (if configuration is ok...)
%     panel_bug('SendBugReport', consoleMsg);
% end

% Close all files
%fclose('all');


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

% Last Modified by GUIDE v2.5 08-Aug-2017 13:59:53

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @p300_paradigm_OpeningFcn, ...
                   'gui_OutputFcn',  @p300_paradigm_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

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% if you want to edit, edit from below this line
% Oyeon Kwon, 2017.08
% oy_kwon@korea.ac.kr
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% --- Executes just before p300_paradigm is made visible.
function p300_paradigm_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 p300_paradigm (see VARARGIN)
set(gcf,'units','points','position',[500 150 495 460])
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Initialization
set(handles.spellerText,'String','KOREA_UNIVERSITY');
set(handles.NumberOfSeq  ,'String','10');
set(handles.screenNumber ,'String','2');
set(handles.stimulusTime ,'String','0.135');
set(handles.IntervalTime ,'String','0.05');
set(handles.portNumber ,'String','D010');
set(handles.tcpiptxt ,'String','12300');
% set(handles.testText,'text40','off');
% set(handles.testText,'visible','off');
% set(handles.testText,'String','OPENBMI_SPELLER');
set(handles.notiontxt,'String','You have to start with selecting the p300 spller type');
scrPanelOn(handles,'off');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Choose default command line output for p300_paradigm
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);
% UIWAIT makes p300_paradigm wait for user response (see UIRESUME)
% uiwait(handles.figure1);

function initialize_gui(fig_handle, handles, isreset)
% If the metricdata field is present and the reset flag is false, it means
% we are we are just re-initializing a GUI by calling it from the cmd line
% while it is up. So, bail out as we dont want to reset the data.
if isfield(handles, 'metricdata') && ~isreset
    return;
end
% RESET(handles, true);
% Update handles structure
guidata(handles.figure1, handles);

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

% Get default command line output from handles structure
varargout{1} = handles.output;

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

set(handles.notiontxt,'String','Executing paradigm...'); drawnow;
% get offline or online
if get(handles.offbtn,'Value')
    exp_type = -1;
elseif get(handles.onbtn,'Value')
    exp_type = 0;
end

% get screensize info
ScreenSize = cellstr(get(handles.screenSize,'String'));
selectScreenSize = ScreenSize{get(handles.screenSize,'Value')};
if strcmp(cellstr(selectScreenSize),'Full screen')
    selectScreenSizeFirst = 'Full screen';   selectScreenSizeEnd=[];
elseif strcmp(cellstr(selectScreenSize),'1920 x 1200')
    selectScreenSizeFirst = 1920; selectScreenSizeEnd = 1200;
elseif strcmp(cellstr(selectScreenSize),'1920 x 1080')
    selectScreenSizeFirst = 1920; selectScreenSizeEnd = 1080;
elseif strcmp(cellstr(selectScreenSize),'1280 x 1024')
    selectScreenSizeFirst = 1280; selectScreenSizeEnd = 1024;
elseif strcmp(cellstr(selectScreenSize),' 800 x  600')
    selectScreenSizeFirst = 800; selectScreenSizeEnd = 600;
elseif strcmp(cellstr(selectScreenSize),'Write direct')
    selectScreenSizeFirst = str2double(get(handles.writeScreenSizeFirst,'String'));
    selectScreenSizeEnd = str2double(get(handles.writeScreenSizeEnd,'String'));
end

% get parameters info
spellerText = get(handles.spellerText,'String');
NumberOfSeq = str2double(get(handles.NumberOfSeq,'String'));
screenNumber = str2double(get(handles.screenNumber,'String'));
stimulusTime = str2double(get(handles.stimulusTime,'String'));
IntervalTime = str2double(get(handles.IntervalTime,'String'));
portNumber = get(handles.portNumber,'String');

% warning box
if isempty(portNumber), error('No input port information'), end

% play paradigm
if ischar(selectScreenSizeFirst) && strcmp(selectScreenSizeFirst,'Full screen')
    if get(handles.random_sp,'Value')
                 gg =   random_speller({'exp_type',exp_type; 'port',portNumber;...
    'text',spellerText;'nSequence',NumberOfSeq;'screenNum',screenNumber;'sti_Times',stimulusTime;...
    'sti_Interval',IntervalTime});
    elseif get(handles.face_sp,'Value')
                     gg = face_speller({'exp_type',exp_type; 'port',portNumber;...
    'text',spellerText;'nSequence',NumberOfSeq;'screenNum',screenNumber;'sti_Times',stimulusTime;...
    'sti_Interval',IntervalTime});
    elseif get(handles.RC_sp,'Value')
                    gg = rc_speller({'exp_type',exp_type; 'port',portNumber;...
    'text',spellerText;'nSequence',NumberOfSeq;'screenNum',screenNumber;'sti_Times',stimulusTime;...
    'sti_Interval',IntervalTime});
    end
else
    if get(handles.random_sp,'Value')
                 gg =   random_speller({'exp_type',exp_type;  'port',portNumber;...
    'text',spellerText;'nSequence',NumberOfSeq;'screenNum',screenNumber;'sti_Times',stimulusTime;...
    'sti_Interval',IntervalTime;'screenSize',[selectScreenSizeFirst,selectScreenSizeEnd]});
    elseif get(handles.face_sp,'Value')
              gg = face_speller({'exp_type',exp_type; 'port',portNumber;...
    'text',spellerText;'nSequence',NumberOfSeq;'screenNum',screenNumber;'sti_Times',stimulusTime;...
    'sti_Interval',IntervalTime;'screenSize',[selectScreenSizeFirst,selectScreenSizeEnd]});
    elseif get(handles.RC_sp,'Value')
                   gg = rc_speller({'exp_type',exp_type; 'port',portNumber;...
    'text',spellerText;'nSequence',NumberOfSeq;'screenNum',screenNumber;'sti_Times',stimulusTime;...
    'sti_Interval',IntervalTime;'screenSize',[selectScreenSizeFirst,selectScreenSizeEnd]});
    end
end

set(handles.notiontxt,'String',gg);

initialize_gui(hObject, handles, false);

% --- Executes on button press in RC_sp.
function RC_sp_Callback(hObject, eventdata, handles)
% hObject    handle to RC_sp (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
if(get(handles.RC_sp,'Value'))
    set(handles.random_sp,'Value',0)
    set(handles.face_sp,'Value',0)
end
set(handles.notiontxt,'String','Now you should make your p300 paradigm then start');
% Hint: get(hObject,'Value') returns toggle state of RC_sp

% --- Executes on button press in random_sp.
function random_sp_Callback(hObject, eventdata, handles)
% hObject    handle to random_sp (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
if(get(handles.random_sp,'Value'))
    set(handles.RC_sp,'Value',0)
    set(handles.face_sp,'Value',0)
end
set(handles.notiontxt,'String','Now you should make your p300 paradigm then start');
% Hint: get(hObject,'Value') returns toggle state of random_sp

% --- Executes on button press in face_sp.
function face_sp_Callback(hObject, eventdata, handles)
% hObject    handle to face_sp (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
if(get(handles.face_sp,'Value'))
    set(handles.random_sp,'Value',0)
    set(handles.RC_sp,'Value',0)
end
set(handles.notiontxt,'String','Now you should make your p300 paradigm then start');
% Hint: get(hObject,'Value') returns toggle state of face_sp

function scrPanelOn(handles, onoff)
set(handles.writeScreenSizeFirst,'visible',onoff);
set(handles.text29,'visible',onoff);
set(handles.writeScreenSizeEnd,'visible',onoff);
set(handles.screenSizeComplete,'visible',onoff);

% --- Executes on selection change in screenSize.
function screenSize_Callback(hObject, eventdata, handles)
% hObject    handle to screenSize (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
switch get(handles.screenSize,'value')
    case 1
        scrPanelOn(handles, 'off');
    case 2
        scrPanelOn(handles, 'off');
    case 3
        scrPanelOn(handles, 'off');
    case 4
        scrPanelOn(handles, 'off');
    case 5
       scrPanelOn(handles, 'off');
    case 6
        scrPanelOn(handles, 'on');
end

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

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

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

function writeScreenSizeEnd_Callback(hObject, eventdata, handles)
% hObject    handle to writeScreenSizeEnd (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of writeScreenSizeEnd as text
%        str2double(get(hObject,'String')) returns contents of writeScreenSizeEnd as a double
input = get(handles.writeScreenSizeEnd,'string');
if regexp(input, '[^0-9]')
    set(handles.notiontxt,'String','Screen size input format should be checked');
else
        set(handles.notiontxt,'String','Set');
end

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

function writeScreenSizeFirst_Callback(hObject, eventdata, handles)
% hObject    handle to writeScreenSizeFirst (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of writeScreenSizeFirst as text
%        str2double(get(hObject,'String')) returns contents of writeScreenSizeFirst as a double
input = get(handles.writeScreenSizeFirst,'string');
if regexp(input, '[^0-9]')
    set(handles.notiontxt,'String','Screen size input format should be checked');
else
        set(handles.notiontxt,'String','Set');
end

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

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

function spellerText_Callback(hObject, eventdata, handles)
% hObject    handle to spellerText (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of spellerText as text
%        str2double(get(hObject,'String')) returns contents of spellerText as a double
input = get(handles.spellerText,'string');
if regexp(input, '[^A-Z.,0-9._ ;]')
    set(handles.notiontxt,'String','Text input format should be checked');
else
        set(handles.notiontxt,'String','Set');
end

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

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

function NumberOfSeq_Callback(hObject, eventdata, handles)
% hObject    handle to NumberOfSeq (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of NumberOfSeq as text
%        str2double(get(hObject,'String')) returns contents of NumberOfSeq as a double
input = get(handles.NumberOfSeq,'string');
if regexp(input, '[^0-9]')
    set(handles.notiontxt,'String','Sequence input format should be checked');
else
        set(handles.notiontxt,'String','Set');
%         set(handles.NumberOfSeq  ,'String','10');
end

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

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

function screenNumber_Callback(hObject, eventdata, handles)
% hObject    handle to screenNumber (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of screenNumber as text
%        str2double(get(hObject,'String')) returns contents of screenNumber as a double
input = get(handles.screenNumber,'string');
if regexp(input, '[^0-9]')
    set(handles.notiontxt,'String','Screen number input format should be checked');
else
        set(handles.notiontxt,'String','Set');
end

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

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

function stimulusTime_Callback(hObject, eventdata, handles)
% hObject    handle to stimulusTime (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of stimulusTime as text
%        str2double(get(hObject,'String')) returns contents of stimulusTime as a double
input = get(handles.stimulusTime,'string');
if regexp(input, '[^0-9.,;]')
    set(handles.notiontxt,'String','Stimulus time input format should be checked');
else
        set(handles.notiontxt,'String','Set');
end

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

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

function IntervalTime_Callback(hObject, eventdata, handles)
% hObject    handle to IntervalTime (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of IntervalTime as text
%        str2double(get(hObject,'String')) returns contents of IntervalTime as a double
input = get(handles.IntervalTime,'string');
if regexp(input, '[^0-9.,;]')
    set(handles.notiontxt,'String','Interval time input format should be checked');
else
        set(handles.notiontxt,'String','Set');
end

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

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

function portNumber_Callback(hObject, eventdata, handles)
% hObject    handle to portNumber (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of portNumber as text
%        str2double(get(hObject,'String')) returns contents of portNumber as a double
% input = get(handles.IntervalTime,'string');
% if regexp(input, '[!@#$%^&*()-=~+]')
%     set(handles.notiontxt,'String','Interval time input format should be checked');
% else
%         set(handles.notiontxt,'String','Set');
% end

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

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

function edit29_Callback(hObject, eventdata, handles)
% hObject    handle to edit29 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit29 as text
%        str2double(get(hObject,'String')) returns contents of edit29 as a double

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

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

function edit30_Callback(hObject, eventdata, handles)
% hObject    handle to edit30 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit30 as text
%        str2double(get(hObject,'String')) returns contents of edit30 as a double

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

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

if(get(handles.offbtn,'Value'))
    set(handles.onbtn,'Value',0)
end
set(handles.text41,'visible','off');
set(handles.tcpiptxt,'visible','off');
set(handles.servercheck,'visible','off');
set(handles.pushbutton12,'visible','on');
set(handles.notiontxt,'String','Set up for offline paradigm');
% Hint: get(hObject,'Value') returns toggle state of offbtn

% --- Executes on button press in onbtn.
function onbtn_Callback(hObject, eventdata, handles)
% hObject    handle to onbtn (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
if(get(handles.onbtn,'Value'))
    set(handles.offbtn,'Value',0)
end
set(handles.spellerText,'String','OPENBMI_SPELLER');
% Hint: get(hObject,'Value') returns toggle state of onbtn
set(handles.text41,'visible','on');
set(handles.tcpiptxt,'visible','on');
set(handles.servercheck,'visible','on');
set(handles.pushbutton12,'visible','on');
set(handles.notiontxt,'String','Set up for online paradigm');

function testText_Callback(hObject, eventdata, handles)
% hObject    handle to testText (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of testText as text
%        str2double(get(hObject,'String')) returns contents of testText as a double

% --- Executes during object creation, after setting all properties.
function testText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to testText (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 servercheck.
function servercheck_Callback(hObject, eventdata, handles)
% hObject    handle to servercheck (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global sock IO_LIB IO_ADD

% if isequal(get(handles.pushbutton12, 'string'), 'Brainvision check')
%     set(handles.notiontxt,'String','have to set up brainvision port first...'); drawnow;
%     return;
% end
% set(handles.notiontxt,'String','waiting check connection of TCPIP');
% bbci_acquire_bv('close');
set(handles.notiontxt,'String','Waiting check TCPIP connection...'); drawnow;
port = get(handles.portNumber ,'String');
IO_LIB=which('inpoutx64.dll');
IO_ADD=hex2dec(port);
tcpipp = str2double(get(handles.tcpiptxt,'String'));
% param = struct;
% state = bbci_acquire_bv('Init',param);
sock = tcpip('0.0.0.0',tcpipp ,'NetworkRole','server','timeout',3);  %
fopen(sock);
disp(1);
flushinput(sock);
while(true)
    a = fread(sock,19);
    if ~isempty(a)
        break;
    end
end

ppWrite(IO_ADD,a);  % 19 check
set(handles.notiontxt,'String','Check connection and start paradigm');

function tcpiptxt_Callback(hObject, eventdata, handles)
% hObject    handle to tcpiptxt (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of tcpiptxt as text
%        str2double(get(hObject,'String')) returns contents of tcpiptxt as a double

% --- Executes during object creation, after setting all properties.
function tcpiptxt_CreateFcn(hObject, eventdata, handles)
% hObject    handle to tcpiptxt (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 selection change in popupmenu4.
function popupmenu4_Callback(hObject, eventdata, handles)
% hObject    handle to popupmenu4 (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 popupmenu4 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupmenu4

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

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

function edit33_Callback(hObject, eventdata, handles)
% hObject    handle to edit33 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit33 as text
%        str2double(get(hObject,'String')) returns contents of edit33 as a double

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

function edit34_Callback(hObject, eventdata, handles)
% hObject    handle to edit34 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit34 as text
%        str2double(get(hObject,'String')) returns contents of edit34 as a double

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

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

function edit35_Callback(hObject, eventdata, handles)
% hObject    handle to edit35 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit35 as text
%        str2double(get(hObject,'String')) returns contents of edit35 as a double

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

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

function edit36_Callback(hObject, eventdata, handles)
% hObject    handle to edit36 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit36 as text
%        str2double(get(hObject,'String')) returns contents of edit36 as a double

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

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

function edit37_Callback(hObject, eventdata, handles)
% hObject    handle to edit37 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit37 as text
%        str2double(get(hObject,'String')) returns contents of edit37 as a double

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

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

function edit38_Callback(hObject, eventdata, handles)
% hObject    handle to edit38 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit38 as text
%        str2double(get(hObject,'String')) returns contents of edit38 as a double

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

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

function edit39_Callback(hObject, eventdata, handles)
% hObject    handle to edit39 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit39 as text
%        str2double(get(hObject,'String')) returns contents of edit39 as a double

% --- Executes during object creation, after setting all properties.
function edit39_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit39 (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 offbtn.
% function offlinebtn_Callback(hObject, eventdata, handles)
% % hObject    handle to offbtn (see GCBO)
% % eventdata  reserved - to be defined in a future version of MATLAB
% % handles    structure with handles and user data (see GUIDATA)
%
% % Hint: get(hObject,'Value') returns toggle state of offbtn
% set(handles.text41,'visible','off');
% set(handles.tcpiptxt,'visible','off');
% set(handles.servercheck,'visible','off');
%
%
% % --- Executes on button press in onbtn.
% function onlinebtn_Callback(hObject, eventdata, handles)
% % hObject    handle to onbtn (see GCBO)
% % eventdata  reserved - to be defined in a future version of MATLAB
% % handles    structure with handles and user data (see GUIDATA)
%
% % Hint: get(hObject,'Value') returns toggle state of onbtn
% set(handles.text41,'visible','on');
% set(handles.tcpiptxt,'visible','on');
% set(handles.servercheck,'visible','on');
%

% --- Executes on button press in finishbtn.
function finishbtn_Callback(hObject, eventdata, handles)
% hObject    handle to finishbtn (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.notiontxt,'String','Check brainvison port (or TCPIP for online access)');

% --- Executes on button press in pushbutton12.
function pushbutton12_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton12 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global IO_LIB IO_ADD
% bbci_acquire_bv('close');
port = get(handles.portNumber ,'String');
IO_LIB=which('inpoutx64.dll');
IO_ADD=hex2dec(port);
ppWrite(IO_ADD,19);  % 19 check
set(handles.notiontxt,'String','Check trigger... "19" in your brainvision');

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

function RESET(handles, init)
if ~init
    a = [500 150 495 460];
else
    a = get(handles.figure1,'Position');
end
% a(4) = 450;
set(handles.notiontxt,'String','Reset all parameters...'); drawnow;
pause(2);
set(handles.figure1,'Position',a);
set(handles.spellerText,'String','KOREA_UNIVERSITY');
set(handles.NumberOfSeq  ,'String','10');
set(handles.screenNumber ,'String','2');
set(handles.stimulusTime ,'String','0.135');
set(handles.IntervalTime ,'String','0.05');
set(handles.portNumber ,'String','D010');
set(handles.tcpiptxt ,'String','12300');
% set(handles.testText,'text40','off');
% set(handles.testText,'visible','off');
% set(handles.testText,'String','OPENBMI_SPELLER');
scrPanelOn(handles,'off');
set(handles.RC_sp,'Value',0);
set(handles.random_sp,'Value',0);
set(handles.face_sp,'Value',0);
set(handles.offbtn,'Value',0);
set(handles.onbtn,'Value',0);
set(handles.text41,'visible','on');
set(handles.tcpiptxt,'visible','on');
set(handles.servercheck,'visible','on');
set(handles.pushbutton12,'visible','on');
set(handles.notiontxt,'String','You have to start with selecting the p300 spller type');
set(handles.screenSize,'value',1);

global state sock
bbci_acquire_bv('close');
params = struct;
state = bbci_acquire_bv('init', params);
disp('will close to connection');
try
    fclose(sock);
catch
end


function command = generate_python_command(script, paths)
% generate_python_command Generate command line for a Python tracker
%
% This function generates the appropritate command string that will
% run the python executable and execute the given script that includes your
% tracker implementation.
%
% Input:
% - script (string): Name of the tracker script to be executed.
% - paths (cell): An array of strings that denote directories to be added to Matlab path.
%
% Output:
% - command (string): Generated command string.
%

trax_python = get_global_variable('trax_python');
python_exec = get_global_variable('python');

% If path to python trax implementation is set then we attempt to export it to tracker
if ~isempty(trax_python)
    paths = cat(1, {trax_python}, paths(:));
end

path_string = strjoin(cellfun(@(p) sprintf('sys.path.append(''%s'');', p), paths, 'UniformOutput', false), '');

% Attempt to locate python interpreter
if isempty(python_exec)
    if ispc()
	    path_separator = ';';
	    exec_name = 'python.exe';
    else
	    path_separator = ':';
	    exec_name = 'python';
    end

    system_paths = strsplit(getenv('PATH'), path_separator);

    for i = 1:numel(system_paths)
        if exist(fullfile(system_paths{i}, exec_name), 'file') == 2
            python_exec = fullfile(system_paths{i}, exec_name);
	    break;
        end
    end

end

if isempty(python_exec)
    error('Unable to locate Python interpreter, please set the "python" global variable manually.');
end

if ispc()
	python_executable = ['"', python_exec, '"'];
	python_flags = {};
else
	python_executable = python_exec;
	python_flags = {};
end

argument_string = strjoin(python_flags, ' ');

python_script = sprintf('import sys; %s import %s', path_string, script);

command = sprintf('%s %s -c "%s"', python_executable, argument_string, python_script);


function this = unlink(this)
% Unlinks the object from the data file
% FORMAT this = unlink(this)
% _________________________________________________________________________
% Copyright (C) 2011 Wellcome Trust Centre for Neuroimaging

% Vladimir Litvak
% $Id: unlink.m 5025 2012-10-31 14:44:13Z vladimir $

this.data = [];
this      = check(this);


% remove all path with a given parent path

% varargin contains a list of path to exclude
function removepath(parentpath, varargin)

if isempty(parentpath), return; end;
folder = path;
if ispc, sep = ';'; else sep = ':'; end;
indSep = find(folder == sep);

indSep = [ 0 indSep length(folder)+1 ];
for iSep = 1:length(indSep)-1
    curPath = folder(indSep(iSep)+1:indSep(iSep+1)-1);
    if ~isempty(strfind(curPath, parentpath)) && ~any(strmatch(curPath, varargin, 'exact'))
        rmpath(curPath);
    end;
end;


function OUT = lt(varargin)

funname = 'lt';
narginchk(2,2)
OUT = builtincaller(funname,varargin{:});


addpath(genpath('BasicFuncPano'));
addpath(genpath('DDSampling'));
addpath(genpath('GroundTruth'));
addpath(genpath('ObjectHypothesisGeneration'));
addpath(genpath('RoomHypothesisSampling'));
addpath(genpath('Toolbox'));
addpath(genpath('VpEstimation'));
addpath(genpath('ResultVisualization'));


function varargout = xmkdir(varargin)
% VL_XMKDIR  Create a directory recursively.
%   VL_XMKDIR(PATH) creates all directory specified by PATH if they
%   do not exist (existing directories are skipped).
%
%   The function accepts the following options:
%
%   Pretend:: [false]
%     Set to true to avoid creating any directory but print which
%     directories would be created (implies 'Verbose',true).
%
%   Verbose:: [false]
%     Set to true to print the operations performed.
%
%   See also: VL_HELP().
[varargout{1:nargout}] = vl_xmkdir(varargin{:});


%MEDIAN Datafile overload


function ns_RESULT = ns_CloseFile(hFile);

%ns_CloseFile   Closes a neural data file
%
%   Usage:
%      ns_RESULT = ns_CloseFile(hFile)
%
%   Description:
%       Closes a previously opened file specified by the file handle hFile.
%
%   Parameters:
%       hFile	    Handle/Indentification number to an open file.
%
%   Return Values:
%       ns_RESULT   This function returns ns_OK if the file is successfully
%                   opened. Otherwise one of the following error codes is
%                   generated:
%
%                       ns_BADFILE	Invalid file handle passed to function.
%
%   Copyright (C) 2003 Neuroshare Project
%   Author: Almut Branner
%   Last modification: 2/4/2003

ns_RESULT = mexprog(14, hFile);


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

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

% Last Modified by GUIDE v2.5 20-Jan-2019 16:28:47

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

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

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

% Choose default command line output for ma_InsertDocking
handles.output = hObject;
handles.ma_MainGUI = varargin{1};

% Update handles structure
guidata(hObject, handles);

numOsc = populateOtherSCCombo(handles, handles.dockingOtherScCombo);
if(numOsc == 0)
    warndlg({'There are no other spacecraft available to dock to.', ...
             'To dock, please add an "Other Spacecraft" via the ', ...
             'Spacecraft -> Other Spacecraft menu.'},'No Other S/C','modal');
    close(handles.ma_InsertDocking);
    return;
end

if(length(varargin)>1)
    event = varargin{2};
    setappdata(hObject,'lossConverts',event.massloss.lossConvert);
    populateGUIWithEvent(handles, event);
    set(hObject,'UserData',event);
else
    set(hObject,'UserData',[]);
    setappdata(hObject,'lossConverts',getDefaultLossConvert(handles));
end

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

function populateGUIWithEvent(handles, event)
    set(handles.titleLabel, 'String', 'Edit Docking');
    set(handles.ma_InsertDocking, 'Name', 'Edit Docking');
    set(handles.dockingNameText, 'String', event.name);

    colorStr = getStringFromLineSpecColor(event.lineColor);
    colorValue = findValueFromComboBox(colorStr, handles.coastLineColorCombo);
    set(handles.coastLineColorCombo,'value',colorValue);

    styleStr = getLineStyleFromString(event.lineStyle);
    styleValue = findValueFromComboBox(styleStr, handles.dockingLineStyleCombo);
 	set(handles.dockingLineStyleCombo,'Value',styleValue);

    contents = handles.lineWidthCombo.String;
    contentsDouble = str2double(contents);
    ind = find(contentsDouble == event.lineWidth);
    set(handles.lineWidthCombo,'Value',ind);

    undockTime = event.undockTime;
    set(handles.undockAfterText, 'String', fullAccNum2Str(undockTime));

    set(handles.massLossCheckbox,'Value',event.massloss.use);
    massLossCheckbox_Callback(handles.massLossCheckbox, [], handles);

% --- Outputs from this function are returned to the command line.
function varargout = ma_InsertDocking_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
        maData = getappdata(handles.ma_MainGUI,'ma_data');

        name = get(handles.dockingNameText, 'String');

        contents = cellstr(get(handles.coastLineColorCombo,'String'));
        colorStr = contents{get(handles.coastLineColorCombo,'Value')};
        lineSpecColor = getLineSpecColorFromString(colorStr);

        contents = cellstr(get(handles.dockingLineStyleCombo,'String'));
        lineStyleStr = contents{get(handles.dockingLineStyleCombo,'Value')};
        lineStyle = getLineStyleStrFromText(lineStyleStr);

        contents = handles.lineWidthCombo.String;
        contentsDouble = str2double(contents);
        contensInd = get(handles.lineWidthCombo,'Value');
        lineWidth = contentsDouble(contensInd);

        oScIndex = get(handles.dockingOtherScCombo,'Value');
        otherSC = maData.spacecraft.otherSC{oScIndex};
        oScId = otherSC.id;

        undockTime = str2double(get(handles.undockAfterText,'String'));

        massLoss = struct('use',logical(get(handles.massLossCheckbox,'Value')), 'lossConvert',getappdata(handles.dockingOtherScCombo,'lossConverts'));

        varargout{1} = ma_createDocking(name, oScId, undockTime, lineSpecColor, lineStyle, lineWidth, massLoss);
        close(handles.ma_InsertDocking);
    end

function dockingNameText_Callback(hObject, eventdata, handles)
% hObject    handle to dockingNameText (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of dockingNameText as text
%        str2double(get(hObject,'String')) returns contents of dockingNameText as a double

% --- Executes during object creation, after setting all properties.
function dockingNameText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to dockingNameText (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 saveCloseButton.
function saveCloseButton_Callback(hObject, eventdata, handles)
% hObject    handle to saveCloseButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    errMsg = validateInputs(handles);

    if(isempty(errMsg))
        uiresume(handles.ma_InsertDocking);
    else
        msgbox(errMsg,'Errors were found while inserting a docking event.','error');
    end

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

function undockAfterText_Callback(hObject, eventdata, handles)
% hObject    handle to undockAfterText (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of undockAfterText as text
%        str2double(get(hObject,'String')) returns contents of undockAfterText as a double
    newInput = get(hObject,'String');
    newInput = attemptStrEval(newInput);
    set(hObject,'String', newInput);

% --- Executes during object creation, after setting all properties.
function undockAfterText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to undockAfterText (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 selection change in dockingOtherScCombo.
function dockingOtherScCombo_Callback(hObject, eventdata, handles)
% hObject    handle to dockingOtherScCombo (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 dockingOtherScCombo contents as cell array
%        contents{get(hObject,'Value')} returns selected item from dockingOtherScCombo

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

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

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

% Hint: get(hObject,'Value') returns toggle state of massLossCheckbox
    if(get(hObject,'Value')==1)
        set(handles.editLossConvertButton,'Enable','on');
    else
        set(handles.editLossConvertButton,'Enable','off');
    end

% --- Executes on button press in editLossConvertButton.
function editLossConvertButton_Callback(hObject, eventdata, handles)
% hObject    handle to editLossConvertButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    event = get(handles.ma_InsertDocking,'UserData');
    eventLossConvert = getappdata(handles.ma_InsertDocking,'lossConverts');
    if(~isempty(event) && isstruct(eventLossConvert) && ~isequal(eventLossConvert, getDefaultLossConvert(handles)))
        lossConverts = ma_MassLossesConversionsGUI(handles.ma_MainGUI, eventLossConvert);
    else
        lossConverts = ma_MassLossesConversionsGUI(handles.ma_MainGUI);
    end

    if(~isempty(lossConverts))
        setappdata(handles.ma_InsertDocking,'lossConverts',lossConverts);
    end

    setEditLossConvertButtonTooltipString(handles);

function setEditLossConvertButtonTooltipString(handles)
    maData = getappdata(handles.ma_MainGUI,'ma_data');
    names = maData.spacecraft.propellant.names;

	lossConverts = getappdata(handles.ma_InsertDocking,'lossConverts');
    if(~isempty(lossConverts))
        maxNumRes = max(horzcat(lossConverts.resLost, lossConverts.resConvert));
        resRates = zeros(1,maxNumRes);

        for(i=1:length(lossConverts)) %#ok<*NO4LP>
            lossConvert = lossConverts(i);
            resRates(lossConvert.resLost) = resRates(lossConvert.resLost) - lossConvert.resLostRates(lossConvert.resLost);

            sumRates = sum(lossConvert.resLostRates);
            resRates(lossConvert.resConvert) = resRates(lossConvert.resConvert) + sumRates*lossConvert.resConvertPercent(lossConvert.resConvert);
        end

        str = 'Right Click for Copy/Paste\n\nTotal Resource Losses & Conversions\n-----------------------\n';
        for(i=1:length(resRates))
            str = [str, ...
                   sprintf('%s: %1.6f mT/Hr\n', names{i}, resRates(i)*3600)];
        end
    else
        str = 'Right Click for Copy/Paste\n\nTotal Resource Losses & Conversions\n-----------------------\nNone!';
    end

    str = sprintf(str);
    set(handles.editLossConvertButton,'TooltipStr',str);

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

    revs = str2double(get(handles.undockAfterText,'String'));
    enteredStr = get(handles.undockAfterText,'String');
    numberName = 'Undock After Time';
    lb = 0;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(revs, numberName, lb, ub, isInt, errMsg, enteredStr);

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

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

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

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

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

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

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

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

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

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


function x = gather_try(x)
try
    x = gather(x);
catch
end
end


%  Internal Function
%
%


function HDF5_DatasetWriteStrings(fname, location, data)

if ~exist(fname, 'file')
    fid = H5F.create(fname, 'H5F_ACC_TRUNC', 'H5P_DEFAULT', 'H5P_DEFAULT');
else
    fid = H5F.open(fname,'H5F_ACC_RDWR','H5P_DEFAULT');
end
data = cell2str_new(data);

filetype = H5T.copy('H5T_FORTRAN_S1');
H5T.set_size(filetype, size(data,2));
memtype = H5T.copy('H5T_C_S1');
H5T.set_size(memtype, size(data,2));

% Create dataspace. Setting maximum size to [] sets the maximum
% size to be the current size.
space = H5S.create_simple(1, size(data,1), []);

% Create the dataset and write the string data to it.
dset = H5D.create(fid, location, filetype, space, 'H5P_DEFAULT');

% Transpose the data to match the layout in the H5 file to match C
% generated H5 file.
H5D.write(dset, memtype, 'H5S_ALL', 'H5S_ALL', 'H5P_DEFAULT',  data');

% Close and release resources.
H5D.close(dset);
H5S.close(space);
H5T.close(filetype);
H5T.close(memtype);
H5F.close(fid);


%% createGoToWBC.m
%
%  Run this script once create the goToWholeBodyControllers.m script in your userpath.

clc
fprintf('\n## whole-body-controllers ##\n');
fprintf('\nCreating "goToWholeBodyControllers.m" in your userpath...\n\n');

% Path to the Matlab userpath
pathToUserpath        = userpath;
pathSeparatorLocation = strfind(pathToUserpath, pathsep);

if isempty(pathToUserpath)

    answer = input('Empty userpath. Do you want to reset the userpath? Y/N ','s');

    if strcmpi(answer,'Y')

       userpath('reset');
       disp('Resetting userpath..');
       pathToUserpath        = userpath;
       pathSeparatorLocation = strfind(pathToUserpath, pathsep);
    else
       error('Please set the userpath before running this script');
    end

elseif size(pathSeparatorLocation, 2) > 1

    answer = input('Multiple userpath. Do you want to reset the userpath? Y/N ','s');

    if strcmpi(answer,'Y')

       userpath('reset');
       disp('Resetting userpath..');
       pathToUserpath        = userpath;
       pathSeparatorLocation = strfind(pathToUserpath, pathsep);
    else
       error('Please set a single userpath before running this script');
    end
end

% check again the userpath
if isempty(pathToUserpath)

    error('userpath is still empty. Please set the userpath before running this script');

elseif size(pathSeparatorLocation, 2) > 1

    error('There are still multiple userpath. Please set a single userpath before running this script');
end

% save a script named "goToWholeBodyControllers" inside the pathdef folder,
% to facilitate the user to reach the WBC working folder

% get the WBC path
[~, currentFolderName, ~] = fileparts(pwd);
currentPath               = pwd;
wbcPath                   = currentPath(1:end-length(currentFolderName));

% note: exist returns 2 if a .m file with the specified name is found
if exist([pathToUserpath, filesep, 'goToWholeBodyControllers.m'],'file') == 2

    fprintf('\n')
    warning(['A goToWholeBodyControllers.m file exists already in your ',pathToUserpath, ' folder,' ...
             ' and therefore it won''t be created.'])
else
    % create the script and write inside the cd command
    fid = fopen([pathToUserpath, filesep, 'goToWholeBodyControllers.m'],'w');
    fprintf(fid, ['cd ', wbcPath, ';']);
    fclose(fid);

    fprintf('\n')
    fprintf(['A file called goToWholeBodyControllers.m has been created in your %s folder.\n', ...
             'This will help to quickly reach the WBC-project folder after ', ...
             'Matlab is launched.\n'], pathToUserpath);
end