% The COBRAToolbox: testSbmlTestModelToMat.m
%
% Purpose:
%     - tests the batch conversion of SBML models to .mat files.
%
% Authors:
%     - Original file: Jacek Wachowiak
%     - Updated to check models for similarity: Thomas Pfau - Sept 2017
%

global CBTDIR

% save the current path
currentDir = pwd;

% initialize the test
fileDir = fileparts(which('testSbmlTestModelToMat.m'));
cd(fileDir);

%Create Temporary Folders
SBMLFolder = tempname;
mkdir(SBMLFolder);

MATFolder = tempname;
mkdir(MATFolder);

%copy all xml files from the models to the temp folder
modeldir = getDistributedModelFolder('iIT341.xml');

modelfiles = dir(modeldir);

modelNames = cell(0);
models = cell(0);
%We will use up to 3 model files for the test.
for i = 1:size(modelfiles)
     if numel(models) >= 3
        break;
    end
    if ~isempty(regexp(modelfiles(i).name,'.*\.xml$'))
        copyfile([modeldir filesep, modelfiles(i).name],SBMLFolder);
        models{end+1} = readCbModel([modeldir filesep modelfiles(i).name]);
        modelNames{end+1} = modelfiles(i).name;
    end
end
sbmlTestModelToMat(SBMLFolder,MATFolder)
matModels = cell(0);
for i = 1:size(models,2)
    %We load them, as otherwise the ID would change to the mat file and
    %they would no longer be equivalent.
    load([MATFolder filesep strrep(modelNames{i},'.xml','.mat')]);
    matModels{end+1} = model;

end

%Test that the models are the same
assert(numel(matModels) == numel(models));
for i = 1:numel(matModels)
    assert(isSameCobraModel(matModels{i},models{i}));
end

%clear all the xml files from the temporary dir.
delete([SBMLFolder filesep '*.xml'])
delete([MATFolder filesep '*.mat'])

%create an invalid xml file (and test with the defaults)
tempfolder = tempname;
mkdir(tempfolder);
cd(tempfolder);
defaultname = 'm_model_collection';
mkdir(defaultname);

invalidFile = fopen([defaultname filesep 'Invalid.xml'],'w');
fprintf(invalidFile,'Not a vlid XML\n');
fclose(invalidFile);
%Test with defaults, and nothing works
sbmlTestModelToMat()
defaultfoldercontent = dir(defaultname);

% the invalid file, '.' and '..'
assert(size(defaultfoldercontent,1) == 3);

cd(fileDir);

%Clean up the folders. (In a try/catch for windows)
%Even if this does not work, those folders are just temporary folders.
try
   rmdir(MATFolder,'s');
   rmdir(SBMLFolder,'s');
   rmdir([tempfolder filesep defaultname],'s');
   isdeleted = true;
catch

end

cd(currentDir)


function varargout = importerpGUI(varargin)

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

% -------------------------------------------------------------------------
function importerpGUI_OpeningFcn(hObject, eventdata, handles, varargin)

handles.output   = [];
handles.fulltext = [];
handles.iniftype = [];

%{filename, pathname, ftype,includetime,timeunit,elabel,transpose,fs,xlim});
try
      def = varargin{1};
catch
      def = {'','','',0,1,0,0,1000,[-200 800]};
end

filename     = def{1};
pathname     = def{2};
ftype        = def{3};
includetime  = def{4};
timeunit     = def{5};
elabel       = def{6};
transpose    = def{7};
fs           = def{8};
xlim         = def{9};

%
% Set objects
%
nfile = length(filename);
fulltext = cell(1);

if nfile>0
      for i=1:nfile
            fulltext{i} = fullfile(pathname{i},filename{i});
      end
      fulltext  = cat(1, fulltext', {'new erpset'});
      set(handles.listbox_erpnames, 'String', fulltext');
else
      set(handles.listbox_erpnames, 'String', {'new erpset'});
end

set(handles.checkbox_time, 'Value', includetime) % time exists by default
set(handles.edit_srate,'String', num2str(fs))
set(handles.edit_xlim,'String', num2str(xlim))
if includetime && timeunit==1
      set(handles.radiobutton_time_sec,'Value',1)
      set(handles.radiobutton_time_msec,'Value',0)
elseif includetime && timeunit==1E-3
      set(handles.radiobutton_time_sec,'Value',0)
      set(handles.radiobutton_time_msec,'Value',1)
elseif ~includetime
      set(handles.radiobutton_time_sec,'Value',0)
      set(handles.radiobutton_time_msec,'Value',0)
      set(handles.radiobutton_time_sec,'Enable', 'off')
      set(handles.radiobutton_time_msec,'Enable', 'off')
else
      msgboxText =  ['No valid time unit.\n'...
            'Only 1 (sec) and 1E-3 (msec) are allowed.'];
      title = 'ERPLAB: importerpGUI() -> wrong input';
      errorfound(sprintf(msgboxText), title);
      return
end

set(handles.checkbox_elabels, 'Value', elabel) % time exists by default

if transpose==1
      set(handles.radiobutton_er_pc,'Value',0)
      set(handles.radiobutton_pr_ec,'Value',1)
else
      set(handles.radiobutton_er_pc,'Value',1)
      set(handles.radiobutton_pr_ec,'Value',0)
end

%
% Name & version
%
version = geterplabversion;
set(handles.gui_chassis,'Name', ['ERPLAB ' version '   -   IMPORT AVERAGED ERP DATA GUI'])

%
% Color GUI
%
handles = painterplab(handles);

%
% Set font size
%
handles = setfonterplab(handles);

% Update handles structure
guidata(hObject, handles);

% help
helpbutton

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

% -------------------------------------------------------------------------
function varargout = importerpGUI_OutputFcn(hObject, eventdata, handles)

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

% The figure can be deleted now
delete(handles.gui_chassis);
pause(0.1)

% -------------------------------------------------------------------------
function listbox_erpnames_Callback(hObject, eventdata, handles)

% -------------------------------------------------------------------------
function listbox_erpnames_CreateFcn(hObject, eventdata, handles)

if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
      set(hObject,'BackgroundColor','white');
end

% -------------------------------------------------------------------------
function pushbutton_adderpfile_Callback(hObject, eventdata, handles)

% [erpfname, erppathname, findex] = uigetfile({'*.txt','Universal text format(*.txt)'; ...
%       '*.avg','Neuroscan AVG format (*.avg)'; ...
%       '*.txt','ERPSS text format (*.txt)'; ...
%       '*.*',  'All Files (*.*)'}, ...
%       'Select an edited file', ...
%       'MultiSelect', 'on');

[erpfname, erppathname, findex] = uigetfile({'*.txt','Universal text format(*.txt)'; ...
      '*.*',  'All Files (*.*)'}, ...
      'Select an edited file', ...
      'MultiSelect', 'on');

if isequal(erpfname,0)
      disp('User selected Cancel')
      return
else
      iniftype = handles.iniftype;
      if ~isempty(iniftype)
            if findex~= iniftype
                  fprintf('\nWARNING: You are putting together different formats of averaged files.\n\n')
            end
      else
            handles.iniftype = findex;
      end

      if ~iscell(erpfname)
            erpfname = {erpfname};
      end

      nerpn = length(erpfname);

      for i=1:nerpn

            newline  = fullfile(erppathname, erpfname{i});      % new member
            currline = get(handles.listbox_erpnames, 'Value');  % current position at the list
            fulltext = get(handles.listbox_erpnames, 'String'); % current list
            indxline = length(fulltext); % last line (virtual)

            if currline==indxline % is the current line the last line?
                  % extra line forward
                  fulltext  = cat(1, fulltext, {'new erpset'});
                  set(handles.listbox_erpnames, 'Value', currline+1)
            else
                  set(handles.listbox_erpnames, 'Value', currline)
                  resto = fulltext(currline:indxline);
                  fulltext  = cat(1, fulltext, {'new erpset'});
                  set(handles.listbox_erpnames, 'Value', currline+1)
                  [fulltext{currline+1:indxline+1}] = resto{:};
            end

            fulltext{currline} = sprintf('Bin %g\t@\t%s',currline, newline);
            set(handles.listbox_erpnames, 'String', fulltext)
      end

      indxline = length(fulltext);
      handles.indxline = indxline;
      handles.fulltext = fulltext;
      handles.listname = [];
      %set(handles.edit_filelist,'String','');
      % Update handles structure
      guidata(hObject, handles);
end

% -------------------------------------------------------------------------
function pushbutton_delerpset_Callback(hObject, eventdata, handles)

fulltext = get(handles.listbox_erpnames, 'String'); % current list
indxline = length(fulltext); % last line
fulltext = char(fulltext); % string matrix
currline = get(handles.listbox_erpnames, 'Value'); % current pos

if currline>=1 && currline<indxline

      fulltext(currline,:) = [];
      fulltext = cellstr(fulltext); % cell string
      nfile = length(fulltext);

      if nfile>1
            fulltext = regexprep(fulltext,'Bin.*?@','', 'ignorecase');
            fulltext = strtrim(fulltext);

            for i=1:nfile-1;
                  fulltext{i} = sprintf('Bin %g\t@\t%s',i, fulltext{i});
            end
      else
            handles.iniftype = [];
      end

      set(handles.listbox_erpnames, 'String', fulltext);
      listbox_erpnames_Callback(hObject, eventdata, handles)

      handles.fulltext = fulltext;
      %indxline = length(fulltext);
      %handles.listname = [];
      %set(handles.edit_filelist,'String','');

      % Update handles structure
      %guidata(hObject, handles);
end

% -------------------------------------------------------------------------
function pushbutton_up_Callback(hObject, eventdata, handles)

fulltext = get(handles.listbox_erpnames, 'String'); % current list
indxline = length(fulltext); % last line
currline = get(handles.listbox_erpnames, 'Value'); % current pos

if currline>1 && currline<indxline

      auxft = fulltext{currline -1};
      fulltext{currline-1} = fulltext{currline};
      fulltext{currline}   = auxft;
      fulltext = regexprep(fulltext,'Bin.*?@','', 'ignorecase');% remove bin prefix
      fulltext = strtrim(fulltext);

      for i=1:length(fulltext)-1;
            fulltext{i} = sprintf('Bin %g\t@\t%s',i, fulltext{i}); % add bin prefix
      end

      set(handles.listbox_erpnames, 'String', fulltext);
      listbox_erpnames_Callback(hObject, eventdata, handles)
      set(handles.listbox_erpnames, 'Value', currline-1);
      handles.fulltext = fulltext;
      %indxline = length(fulltext);
      %handles.listname = [];
      %set(handles.edit_filelist,'String','');

      % Update handles structure
      %guidata(hObject, handles);
end

% -------------------------------------------------------------------------
function pushbutton_down_Callback(hObject, eventdata, handles)

fulltext = get(handles.listbox_erpnames, 'String'); % current list
indxline = length(fulltext); % last line
currline = get(handles.listbox_erpnames, 'Value'); % current pos

if currline>=1 && currline<indxline-1

      auxft = fulltext{currline + 1};
      fulltext{currline+1} = fulltext{currline};
      fulltext{currline}   = auxft;
      fulltext = regexprep(fulltext,'Bin.*?@','', 'ignorecase');% remove bin prefix
      fulltext = strtrim(fulltext);

      for i=1:length(fulltext)-1;
            fulltext{i} = sprintf('Bin %g\t@\t%s',i, fulltext{i});% add bin prefix
      end

      set(handles.listbox_erpnames, 'String', fulltext);
      listbox_erpnames_Callback(hObject, eventdata, handles)
      set(handles.listbox_erpnames, 'Value', currline+1);
      handles.fulltext = fulltext;
      %indxline = length(fulltext);
      %handles.listname = [];
      %set(handles.edit_filelist,'String','');

      % Update handles structure
      %guidata(hObject, handles);
end

% -------------------------------------------------------------------------
function ok_Callback(hObject, eventdata, handles)

fulltext = get(handles.listbox_erpnames, 'String'); % current list
fulltext = fulltext(1:end-1);
fulltext = regexprep(fulltext,'Bin.*?@','', 'ignorecase'); % remove bin prefix
fulltext = strtrim(fulltext);
filename = cell(1);
pathname = cell(1);
filetype = zeros(1, length(fulltext));

for i=1:length(fulltext)
      [pathstr, name, ext] = fileparts(fulltext{i});
      pathname{1,i} = pathstr;
      filename{1,i} = [name ext];

      if strcmpi(ext,'.txt')
            filetype(1,i) = 1; % text
      elseif strcmpi(ext,'.avg')
            filetype(1,i) = 2; % neuroscan
      else
            filetype(1,i) = 1; % text by default
      end
end

istime = get(handles.checkbox_time,'Value');

if get(handles.radiobutton_time_sec,'Value') && ~get(handles.radiobutton_time_msec,'Value')
      tunit = 1;
elseif ~get(handles.radiobutton_time_sec,'Value') && get(handles.radiobutton_time_msec,'Value')
      tunit = 1E-3;
elseif ~get(handles.radiobutton_time_sec,'Value') && ~get(handles.radiobutton_time_msec,'Value')
      tunit = [];
else
      msgboxText =  'Please, choose one option.';
      title = 'ERPLAB: importerpGUI() -> missing input';
      errorfound(sprintf(msgboxText), title);
      return
end

iselabel = get(handles.checkbox_elabels,'Value');

if get(handles.radiobutton_er_pc,'Value');
      transpose = 0;
end
if get(handles.radiobutton_pr_ec,'Value');
      transpose = 1;
end
srate = str2num(get(handles.edit_srate, 'String'));
xlim  = str2num(get(handles.edit_xlim, 'String'));

if (isempty(srate) || isempty(xlim)) && istime==0
      msgboxText =  ['Since there is not time info, you must specify\n'...
            'sampling rate in Hz, and time range (xmin xmax) in msec.'];
      title = 'ERPLAB: importerpGUI() -> missing input';
      errorfound(sprintf(msgboxText), title);
      return
end
if ~isempty(srate)
      if numel(srate)>1
            msgboxText =  'You must specify a unique value for sampling rate in Hz';
            title = 'ERPLAB: importerpGUI() -> wrong input';
            errorfound(sprintf(msgboxText), title);
            return
      end
      if srate<=0
            msgboxText =  'You must specify a positive integer (no zero) value for sampling rate in Hz';
            title = 'ERPLAB: importerpGUI() -> wrong input';
            errorfound(sprintf(msgboxText), title);
            return
      end
end
if ~isempty(xlim)
      if numel(xlim)~=2
            msgboxText =  'You must specify two values for time range [xmin xmax] in msec';
            title = 'ERPLAB: importerpGUI() -> wrong input';
            errorfound(sprintf(msgboxText), title);
            return
      end
      if xlim(1)>=xlim(2)
            msgboxText =  ['Time range is incorrect.\n'...
                  'xmin must be lesser than xmax'];
            title = 'ERPLAB: importerpGUI() -> wrong input';
            errorfound(sprintf(msgboxText), title);
            return
      end
      if xlim(1)>0 || xlim(2)<0
            msgboxText =  'time zero must be included within the time range.';
            title = 'ERPLAB: importerpGUI() -> wrong input';
            errorfound(sprintf(msgboxText), title);
            return
      end
end

handles.output = {filename pathname filetype istime tunit iselabel transpose srate xlim};
% Update handles structure
guidata(hObject, handles);
uiresume(handles.gui_chassis);

% -------------------------------------------------------------------------
function cancel_Callback(hObject, eventdata, handles)
handles.output = [];
% Update handles structure
guidata(hObject, handles);
uiresume(handles.gui_chassis);

% -------------------------------------------------------------------------
function edit1_Callback(hObject, eventdata, handles)

% -------------------------------------------------------------------------
function edit1_CreateFcn(hObject, eventdata, handles)

if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
      set(hObject,'BackgroundColor','white');
end

% -------------------------------------------------------------------------
function edit2_Callback(hObject, eventdata, handles)

% -------------------------------------------------------------------------
function edit2_CreateFcn(hObject, eventdata, handles)

if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
      set(hObject,'BackgroundColor','white');
end

% -------------------------------------------------------------------------
function pushbutton_CL_Callback(hObject, eventdata, handles)

fulltext = get(handles.listbox_erpnames, 'String'); % current list
indxline = length(fulltext); % last line

if indxline>1
      BackERPLABcolor = [1 0.9 0.3];    % yellow
      question = ['Current list will be deleted.\n\n'...
                  'Are you sure?'];
      title = 'List of averaged files for importing';
      oldcolor = get(0,'DefaultUicontrolBackgroundColor');
      set(0,'DefaultUicontrolBackgroundColor',BackERPLABcolor)
      button = questdlg(sprintf(question), title,'Cancel','Yes', 'Cancel');
      set(0,'DefaultUicontrolBackgroundColor',oldcolor)

      if ~strcmpi(button,'Yes')
            return
      end

      set(handles.listbox_erpnames, 'Value', 1);
      set(handles.listbox_erpnames, 'String', {'new erpset'});
      handles.fulltext = [];
      handles.iniftype = [];

      % Update handles structure
      guidata(hObject, handles);
end

% -------------------------------------------------------------------------
function radiobutton_er_pc_Callback(hObject, eventdata, handles)
if get(hObject,'Value')
      set(handles.radiobutton_pr_ec,'value', 0)
else
      set(handles.radiobutton_er_pc,'value', 1)
end

% -------------------------------------------------------------------------
function radiobutton_pr_ec_Callback(hObject, eventdata, handles)
if get(hObject,'Value')
      set(handles.radiobutton_er_pc,'value', 0)
else
      set(handles.radiobutton_pr_ec,'value', 1)
end

% -------------------------------------------------------------------------
function checkbox_elabels_Callback(hObject, eventdata, handles)

% -------------------------------------------------------------------------
function checkbox_time_Callback(hObject, eventdata, handles)

if get(hObject,'Value')
      %set(handles.edit_srate,'Enable','off')
      %set(handles.edit_xlim,'Enable','off')
      set(handles.radiobutton_time_sec,'Enable','on')
      set(handles.radiobutton_time_msec,'Enable','on')
      set(handles.edit_srate, 'Enable', 'off')
      set(handles.edit_xlim, 'Enable', 'off')
else
      %set(handles.edit_srate,'Enable','on')
      %set(handles.edit_xlim,'Enable','on')
      set(handles.radiobutton_time_sec,'Enable','off')
      set(handles.radiobutton_time_msec,'Enable','off')
      set(handles.edit_srate, 'Enable', 'on')
      set(handles.edit_xlim, 'Enable', 'on')
end

% -------------------------------------------------------------------------
function edit_srate_Callback(hObject, eventdata, handles)

% -------------------------------------------------------------------------
function edit_srate_CreateFcn(hObject, eventdata, handles)

if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% -------------------------------------------------------------------------
function edit_xlim_Callback(hObject, eventdata, handles)

% -------------------------------------------------------------------------
function edit_xlim_CreateFcn(hObject, eventdata, handles)

if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% -------------------------------------------------------------------------
function radiobutton_time_sec_Callback(hObject, eventdata, handles)

if get(hObject,'Value')
      set(handles.radiobutton_time_msec,'value',0)
else
      set(handles.radiobutton_time_sec,'value',1)
end

% -------------------------------------------------------------------------
function radiobutton_time_msec_Callback(hObject, eventdata, handles)
if get(hObject,'Value')
      set(handles.radiobutton_time_sec,'value',0)
else
      set(handles.radiobutton_time_msec,'value',1)
end

% -------------------------------------------------------------------------
function pushbutton_take_a_look_Callback(hObject, eventdata, handles)

fulltext = get(handles.listbox_erpnames, 'String'); % current list
indxline = length(fulltext); % last line
currline = get(handles.listbox_erpnames, 'Value'); % current pos

if currline>=1 && currline<indxline
      filename = fulltext{currline};
      filename = regexprep(filename,'Bin.*?@','', 'ignorecase');% remove bin prefix
      filename = strtrim(filename);

      [pathstr, name, ext] = fileparts(filename) ;

      if ismember_bc2({ext},{'.txt' '.asc' '.ascii' '.csv' '.csa' '.dat' ''})
            uiopen(filename,1)
      else
            msgboxText =  'Current line does not refer a text file.';
            title = 'ERPLAB: importerpGUI() -> wrong input';
            errorfound(sprintf(msgboxText), title);
            return
      end
else
      msgboxText =  'Current line does not contain a valid filename.';
      title = 'ERPLAB: importerpGUI() -> wrong input';
      errorfound(sprintf(msgboxText), title);
      return
end

% -------------------------------------------------------------------------
function pushbutton_help_Callback(hObject, eventdata, handles)
web https://github.com/lucklab/erplab/wiki/Manual -browser % pending

% -------------------------------------------------------------------------
function button_clearfile_Callback(hObject, eventdata, handles)
set(handles.edit5,'String','');
set(handles.button_savelist, 'Enable', 'off')
handles.listname = [];
% Update handles structure
guidata(hObject, handles);

function button_savelistas_Callback(hObject, eventdata, handles)
fulltext = char(get(handles.listbox_erpnames,'String'));

if length(fulltext)>1

        fullname = savelist(hObject, eventdata, handles);

        if isempty(fullname)
                return
        end

        set(handles.edit5, 'String', fullname )
        set(handles.button_savelist, 'Enable', 'on')
        handles.listname = fullname;
        % Update handles structure
        guidata(hObject, handles);
else
        set(handles.button_savelistas,'Enable','off')
        msgboxText =  'You have not specified any erpset!';
        title = 'ERPLAB: averager GUI few inputs';
        errorfound(msgboxText, title);
        set(handles.button_savelistas,'Enable','on')
        return
end

%--------------------------------------------------------------------------
function fullname = savelist(hObject, eventdata, handles)

fulltext  = char(strtrim(get(handles.listbox_erpnames,'String')));
pre_fname = char(strtrim(get(handles.edit5,'String')));
if isempty(pre_fname)
    pre_fname = '';
end

%
% Save OUTPUT file
%
[filename, filepath, filterindex] = uiputfile({'*.txt';'*.dat';'*.*'},'Save erpset list as', pre_fname);

if isequal(filename,0)
        disp('User selected Cancel')
        fullname =[];
        return
else

        [px, fname, ext] = fileparts(filename);

        if strcmp(ext,'')

                if filterindex==1 || filterindex==3
                        ext   = '.txt';
                else
                        ext   = '.dat';
                end
        end

        fname = [ fname ext];
        fullname = fullfile(filepath, fname);
        disp(['For saving erpset list, user selected <a href="matlab: open(''' fullname ''')">' fullname '</a>'])
        fid_list   = fopen( fullname , 'w');

        for i=1:size(fulltext,1)-1
                fprintf(fid_list,'%s\n', fulltext(i,:));
        end

        fclose(fid_list);
end

% -------------------------------------------------------------------------
function button_savelist_Callback(hObject, eventdata, handles)
fulltext = char(strtrim(get(handles.listbox_erpnames,'String')));

if length(fulltext)>1

        fullname = get(handles.edit5, 'String');

        if ~strcmp(fullname,'')

                fid_list   = fopen( fullname , 'w');

                for i=1:size(fulltext,1)
                        fprintf(fid_list,'%s\n', fulltext(i,:));
                end

                fclose(fid_list);
                handles.listname = fullname;

                % Update handles structure
                guidata(hObject, handles);
                disp(['Saving equation list at <a href="matlab: open(''' fullname ''')">' fullname '</a>'])
        else
                button_savelistas_Callback(hObject, eventdata, handles)
                return
        end
else
        set(handles.button_savelistas,'Enable','off')
        msgboxText =  'You have not written any formula yet!';
        title = 'ERPLAB: chanoperGUI few inputs';
        errorfound(msgboxText, title);
        set(handles.button_savelistas,'Enable','on')
        return
end

% -------------------------------------------------------------------------
function button_loadlist_Callback(hObject, eventdata, handles, optionx)
if nargin<4
        optionx=0;
end
if optionx==0
        [listname, lispath] = uigetfile({  '*.txt','Text File (*.txt)'; ...
                '*.*',  'All Files (*.*)'}, ...
                'Select an edited list', ...
                'MultiSelect', 'off');

        if isequal(listname,0)
                disp('User selected Cancel')
                return
        else
                fullname = fullfile(lispath, listname);
                disp(['For erpset list user selected  <a href="matlab: open(''' fullname ''')">' fullname '</a>'])
        end
else
        fullname = handles.erpset;
        if isnumeric(fullname)
                fullname = '';
        end
end

fid_list = fopen( fullname );
formcell = textscan(fid_list, '%[^\n]','CommentStyle','#', 'whitespace', '');
lista = formcell{:};
% extra line forward
lista   = cat(1, lista, {'new erpset'});
lentext = length(lista);
fclose(fid_list);

if lentext>1
        set(handles.listbox_erpnames,'String',lista);
        set(handles.edit5,'String',fullname);
        handles.listname = fullname;
        set(handles.button_savelist, 'Enable','on')

        % Update handles structure
        guidata(hObject, handles);
else
        msgboxText =  'This list is empty!';
        title = 'ERPLAB: geterpvaluesGUI inputs';
        errorfound(msgboxText, title);
        handles.listname = [];
        set(handles.button_savelist, 'Enable','off')

        % Update handles structure
        guidata(hObject, handles);
end
set(handles.listbox_erpnames,'String',lista);

% -------------------------------------------------------------------------
function edit5_Callback(hObject, eventdata, handles)

% -------------------------------------------------------------------------
function edit5_CreateFcn(hObject, eventdata, handles)

% 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 gui_chassis_CloseRequestFcn(hObject, eventdata, handles)

if isequal(get(handles.gui_chassis, 'waitstatus'), 'waiting')
      %The GUI is still in UIWAIT, us UIRESUME
      handles.output = [];
      %Update handles structure
      guidata(hObject, handles);
      uiresume(handles.gui_chassis);
else
      % The GUI is no longer waiting, just close it
      delete(handles.gui_chassis);
end


%kgbindtexture 'Assign a Texture to a Geometry Object'
% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros gbindtexture.pane file
%
% Parameters:
% InputFile: i 'Input Geometry Object ', required: 'input geometry object'
% InputFile: i2 'Input Texture Object ', required: 'texture object to be bound'
% OutputFile: o 'Output Geometry Object', required: 'output geometry object with bound texture'
%
% Example: o = kgbindtexture({i, i2}, {'i','';'i2','';'o',''})
%
% Khoros helpfile follows below:
%
%  PROGRAM
% gbindtexture - Assign a Texture to a Geometry Object
%
%  DESCRIPTION
% .I gbindtexture
% This module "binds" a texture to an object.  The rendered object
% will then be rendered such as to have the texture "draped" over it's
% surface, in the case of 2d textures.  Texture binding is necessary
% before the renderer will do the texture mapping.  A single texture
% may be bound to multiple objects, but a given object may have only
% one texture bound to it.
%
%
%
%  EXAMPLES
%
%  "SEE ALSO"
% gcreate2dtex
%
%  RESTRICTIONS
%
%  REFERENCES
%
%  COPYRIGHT
% Copyright (C) 1996,1997 , The Regents of the University of California.  All rights reserved.
%

function varargout = kgbindtexture(varargin)
if nargin ==0
  Inputs={};arglist={'',''};
elseif nargin ==1
  Inputs=varargin{1};arglist={'',''};
elseif nargin ==2
  Inputs=varargin{1}; arglist=varargin{2};
else error('Usage: [out1,..] = kgbindtexture(Inputs,arglist).');
end
if size(arglist,2)~=2
  error('arglist must be of form {''ParameterTag1'',value1;''ParameterTag2'',value2}')
 end
narglist={'i', '__input';'i2', '__input';'o', '__output'};
maxval={0,0,0};
minval={0,0,0};
istoggle=[0,0,0];
was_set=istoggle * 0;
paramtype={'InputFile','InputFile','OutputFile'};
% identify the input arrays and assign them to the arguments as stated by the user
if ~iscell(Inputs)
Inputs = {Inputs};
end
NumReqOutputs=1; nextinput=1; nextoutput=1;
  for ii=1:size(arglist,1)
  wasmatched=0;
  for jj=1:size(narglist,1)
   if strcmp(arglist{ii,1},narglist{jj,1})  % a given argument was matched to the possible arguments
     wasmatched = 1;
     was_set(jj) = 1;
     if strcmp(narglist{jj,2}, '__input')
      if (nextinput > length(Inputs))
        error(['Input ' narglist{jj,1} ' has no corresponding input!']);
      end
      narglist{jj,2} = 'OK_in';
      nextinput = nextinput + 1;
     elseif strcmp(narglist{jj,2}, '__output')
      if (nextoutput > nargout)
        error(['Output nr. ' narglist{jj,1} ' is not present in the assignment list of outputs !']);
      end
      if (isempty(arglist{ii,2}))
        narglist{jj,2} = 'OK_out';
      else
        narglist{jj,2} = arglist{ii,2};
      end

      nextoutput = nextoutput + 1;
      if (minval{jj} == 0)
         NumReqOutputs = NumReqOutputs - 1;
      end
     elseif isstr(arglist{ii,2})
      narglist{jj,2} = arglist{ii,2};
     else
        if strcmp(paramtype{jj}, 'Integer') & (round(arglist{ii,2}) ~= arglist{ii,2})
            error(['Argument ' arglist{ii,1} ' is of integer type but non-integer number ' arglist{ii,2} ' was supplied']);
        end
        if (minval{jj} ~= 0 | maxval{jj} ~= 0)
          if (minval{jj} == 1 & maxval{jj} == 1 & arglist{ii,2} < 0)
            error(['Argument ' arglist{ii,1} ' must be bigger or equal to zero!']);
          elseif (minval{jj} == -1 & maxval{jj} == -1 & arglist{ii,2} > 0)
            error(['Argument ' arglist{ii,1} ' must be smaller or equal to zero!']);
          elseif (minval{jj} == 2 & maxval{jj} == 2 & arglist{ii,2} <= 0)
            error(['Argument ' arglist{ii,1} ' must be bigger than zero!']);
          elseif (minval{jj} == -2 & maxval{jj} == -2 & arglist{ii,2} >= 0)
            error(['Argument ' arglist{ii,1} ' must be smaller than zero!']);
          elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} < minval{jj})
            error(['Argument ' arglist{ii,1} ' must be bigger than ' num2str(minval{jj})]);
          elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} > maxval{jj})
            error(['Argument ' arglist{ii,1} ' must be smaller than ' num2str(maxval{jj})]);
          end
        end
     end
     if ~strcmp(narglist{jj,2},'OK_out') &  ~strcmp(narglist{jj,2},'OK_in')
       narglist{jj,2} = arglist{ii,2};
     end
   end
   end
   if (wasmatched == 0 & ~strcmp(arglist{ii,1},''))
        error(['Argument ' arglist{ii,1} ' is not a valid argument for this function']);
   end
end
% match the remaining inputs/outputs to the unused arguments and test for missing required inputs
 for jj=1:size(narglist,1)
     if  strcmp(paramtype{jj}, 'Toggle')
        if (narglist{jj,2} ==0)
          narglist{jj,1} = '';
        end;
        narglist{jj,2} = '';
     end;
     if  ~strcmp(narglist{jj,2},'__input') && ~strcmp(narglist{jj,2},'__output') && istoggle(jj) && ~ was_set(jj)
          narglist{jj,1} = '';
          narglist{jj,2} = '';
     end;
     if strcmp(narglist{jj,2}, '__input')
      if (minval{jj} == 0)  % meaning this input is required
        if (nextinput > size(Inputs))
           error(['Required input ' narglist{jj,1} ' has no corresponding input in the list!']);
        else
          narglist{jj,2} = 'OK_in';
          nextinput = nextinput + 1;
        end
      else  % this is an optional input
        if (nextinput <= length(Inputs))
          narglist{jj,2} = 'OK_in';
          nextinput = nextinput + 1;
        else
          narglist{jj,1} = '';
          narglist{jj,2} = '';
        end;
      end;
     else
     if strcmp(narglist{jj,2}, '__output')
      if (minval{jj} == 0) % this is a required output
        if (nextoutput > nargout & nargout > 1)
           error(['Required output ' narglist{jj,1} ' is not stated in the assignment list!']);
        else
          narglist{jj,2} = 'OK_out';
          nextoutput = nextoutput + 1;
          NumReqOutputs = NumReqOutputs-1;
        end
      else % this is an optional output
        if (nargout - nextoutput >= NumReqOutputs)
          narglist{jj,2} = 'OK_out';
          nextoutput = nextoutput + 1;
        else
          narglist{jj,1} = '';
          narglist{jj,2} = '';
        end;
      end
     end
  end
end
if nargout
   varargout = cell(1,nargout);
else
  varargout = cell(1,1);
end
global KhorosRoot
if exist('KhorosRoot') && ~isempty(KhorosRoot)
w=['"' KhorosRoot];
else
if ispc
  w='"C:\Program Files\dip\khorosBin\';
else
[s,w] = system('which cantata');
w=['"' w(1:end-8)];
end
end
[varargout{:}]=callKhoros([w 'gbindtexture"  '],Inputs,narglist);


classdef LiftCoeffModel < matlab.mixin.SetGet & matlab.mixin.Copyable
    %LiftCoeffModel Summary of this class goes here
    %   Detailed explanation goes here

    properties
        cylinderModel(1,:) CylindricalLiftModel

        liftCoeffObj(1,:) AbstractLiftCoefficientModel = AbstractLiftCoefficientModel.empty(1,0);
    end

    methods
        function obj = LiftCoeffModel()
            obj.cylinderModel = CylindricalLiftModel(1, 1);

            obj.liftCoeffObj = obj.cylinderModel;
        end

        function [ClS, liftUnitVectInertial] = getLiftCoeffAndDir(obj, ut, rVect, vVect, bodyInfo, mass, altitude, pressure, density, vVectECEF, attState)
            arguments
                obj(1,1) LiftCoeffModel
                ut(1,1) double
                rVect(3,1) double
                vVect(3,1) double
                bodyInfo(1,1) KSPTOT_BodyInfo
                mass(1,1) double
                altitude(1,1) double
                pressure(1,1) double
                density(1,1) double
                vVectECEF(3,1) double
                attState(1,1) LaunchVehicleAttitudeState
            end

            [ClS, liftUnitVectInertial] = obj.liftCoeffObj.getLiftCoeffAndDir(ut, rVect, vVect, bodyInfo, mass, altitude, pressure, density, vVectECEF, attState);
        end

        function useTf = openEditDialog(obj, lvdData)
            out = AppDesignerGUIOutput();
            lvd_EditLiftCoefficientModels_App(obj, lvdData, out);
            useTf = out.output{1};
        end
    end

    methods(Static)
        function obj = loadobj(obj)
            if(isempty(obj.cylinderModel))
                obj.cylinderModel = CylindricalLiftModel(1, 1);
            end

            if(isempty(obj.liftCoeffObj))
                obj.liftCoeffObj = obj.cylinderModel;
            end
        end
    end
end


function varargout = svmAverageGUI(varargin)
% svmAverageGUI
%   Given an svm structure, opens a GUI displaying the contents with the
%   ability to select, modify, and average across fields describing the
%   data.
%
% Usage:
%   svmAverageGUI(svm)
%
% Proper comments and ability to return the structure (even more
% important!) forthcoming.
%
% [renobowen@gmail.com 2010]
%

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

function svmAverageGUI_OpeningFcn(hObject, eventdata, handles, svm, varargin)
    if ~(exist('svm','var'))
        svm = [];
    end

    % Choose default command line output for svmAverageGUI
    handles.output      = hObject;
    handles.svm         = svm;
    handles.saveToVar   = [];

    for i = 1:2:length(varargin)
        switch (lower(varargin{i}))
            case {'savetovar'}
                handles.saveToVar = varargin{i + 1};
            otherwise
                fprintf(1, 'Unrecognized option ''%s''\n', varargin{i});
        end
    end

    handles.changed     = 0;

    % Update handles structure
    guidata(hObject, handles);

    if (~isempty(svm))
        svmAverageGUI_InitFcn(hObject, handles);
    end
end

function svmAverageGUI_InitFcn(hObject, handles)
    handles = DataList_InitFcn(hObject, handles);
    handles = RunList_InitFcn(hObject, handles);
    handles = GroupList_InitFcn(hObject, handles);
    handles = TrialList_InitFcn(hObject, handles);
    guidata(hObject, handles);
end

function varargout = svmAverageGUI_OutputFcn(hObject, eventdata, handles)

    if (isempty(handles.svm))
        fprintf(1, 'No svm structure specified - closing GUI.\n');
        close(handles.AverageGUI);
    end

end

function DataList_UpdateSelections(hObject, handles)
    runValues       = unique(handles.svm.run);
    groupValues     = unique(handles.svm.group);
    trialValues     = unique(handles.svm.trial);

    selectedRuns    = runValues(get(handles.RunList, 'Value'));
    selectedGroups  = groupValues(get(handles.GroupList, 'Value'));
    selectedTrials  = trialValues(get(handles.TrialList, 'Value'));

    mask =  ismember(handles.svm.run, selectedRuns) & ...
            ismember(handles.svm.group, selectedGroups) & ...
            ismember(handles.svm.trial, selectedTrials);

    set(handles.DataList, 'Value', find(mask));
    guidata(hObject, handles);
end

function handles = DataList_InitFcn(hObject, handles)
    strings = num2str([handles.svm.run handles.svm.group handles.svm.trial]);
    set(handles.DataList, 'String', strings);
    set(handles.DataList, 'Max', size(strings,1));
    set(handles.DataList, 'Value', 1);
    set(handles.DataList, 'ListboxTop', 1);

end

function handles = RunList_InitFcn(hObject, handles)
    strings = num2str(unique(handles.svm.run));
    set(handles.RunList, 'String', strings);
    set(handles.RunList, 'Max', size(strings,1));
    set(handles.RunList, 'Value', 1);
    set(handles.RunList, 'ListboxTop', 1);
end

function handles = GroupList_InitFcn(hObject, handles)
    strings = handles.svm.grouplabel;
    set(handles.GroupList, 'String', strings);
    set(handles.GroupList, 'Max', length(strings));
    set(handles.GroupList, 'Value', 1);
    set(handles.GroupList, 'ListboxTop', 1);
end

function handles = TrialList_InitFcn(hObject, handles)
    strings = num2str(unique(handles.svm.trial));
    set(handles.TrialList, 'String', strings);
    set(handles.TrialList, 'Max', size(strings,1));
    set(handles.TrialList, 'Value', 1);
    set(handles.TrialList, 'ListboxTop', 1);

end

function ResetDetailSelectors(hObject, handles)
    set(handles.RunList, 'Value', 1);
    set(handles.RunList, 'ListboxTop', 1);
    set(handles.GroupList, 'Value', 1);
    set(handles.GroupList, 'ListboxTop', 1);
    set(handles.TrialList, 'Value', 1);
    set(handles.TrialList, 'ListboxTop', 1);
    guidata(hObject, handles);
end

function UpdateLists(hObject, handles)
    svmAverageGUI_InitFcn(hObject, handles);
end

function handles = RepairIndices(hObject, handles)
    nLabels = length(handles.svm.grouplabel);
    markedForDeletion = zeros(1,nLabels);
    subFromInds = 0;
    for i = 1:length(handles.svm.grouplabel)
        if (sum(ismember(handles.svm.group, i)) == 0)
            markedForDeletion(i) = 1;
            subFromInds = subFromInds + 1;
        else
            inds = ismember(handles.svm.group, i);
            handles.svm.group(inds) = i - subFromInds;
        end
    end

    handles.svm.grouplabel = handles.svm.grouplabel(~markedForDeletion);
end

%% List callbacks
function DataList_Callback(hObject, eventdata, handles)
% DataList_Callback
%   Selecting within this window resets the selected run/group/trial in the
%   other lists (we're now manually editing the selection and the remaining
%   lists will no longer contain info representative of what we've
%   selected.

    ResetDetailSelectors(hObject, handles);
end

function RunList_Callback(hObject, eventdata, handles)
    DataList_UpdateSelections(hObject, handles);
end

function GroupList_Callback(hObject, eventdata, handles)
    DataList_UpdateSelections(hObject, handles);
end

function TrialList_Callback(hObject, eventdata, handles)
    DataList_UpdateSelections(hObject, handles);
end

%% Action button callbacks - used to modify data
function RelabelButton_Callback(hObject, eventdata, handles)
    % hObject    handle to AverageButton (see GCBO)
    % eventdata  reserved - to be defined in a future version of MATLAB
    % handles    structure with handles and user data (see GUIDATA)

    run         = str2num(get(handles.RunInput, 'String'));
    trial       = str2num(get(handles.TrialInput, 'String'));
    groupLabel  = get(handles.GroupInput, 'String');

    if (isempty(run) && isempty(trial) && isempty(groupLabel))
        fprintf(1, 'Empty assignment fields!\n');
        return;
    end

    mask        = false(get(handles.DataList, 'Max'),1);
    inds        = get(handles.DataList, 'Value');
    mask(inds)  = true;

    if (~isempty(run))
        handles.svm.run(mask) = run;
    end

    if (~isempty(trial))
        handles.svm.trial(mask) = trial;
    end

    if (~isempty(groupLabel))
        group = cellfind(handles.svm.grouplabel, groupLabel);
        if (isempty(group))
            group = max(handles.svm.group) + 1;
            handles.svm.grouplabel{group} = groupLabel;
        end
        handles.svm.group(mask) = group;
        handles = RepairIndices(hObject, handles);
    end

    handles.changed = 1;
    UpdateLists(hObject, handles);
end

function AverageButton_Callback(hObject, eventdata, handles)

    run         = str2num(get(handles.RunInput, 'String'));
    trial       = str2num(get(handles.TrialInput, 'String'));
    groupLabel  = get(handles.GroupInput, 'String');

    if (isempty(run) || isempty(trial) || isempty(groupLabel))
        fprintf(1, 'Empty assignment fields!\n');
        return;
    end

    group = cellfind(handles.svm.grouplabel, groupLabel);
    if (isempty(group))
        group = max(handles.svm.group) + 1;
        handles.svm.grouplabel{group} = groupLabel;
    end

    mask        = false(get(handles.DataList, 'Max'),1);
    inds        = get(handles.DataList, 'Value');
    mask(inds)  = true;

    newsvm          = handles.svm;
    newsvm.data     = newsvm.data(~mask,:);
    newsvm.run      = newsvm.run(~mask,:);
    newsvm.group    = newsvm.group(~mask,:);
    newsvm.trial    = newsvm.trial(~mask,:);

    newsvm.data     = [newsvm.data; mean(handles.svm.data(mask,:), 1)];
    newsvm.run      = [newsvm.run; run];
    newsvm.group    = [newsvm.group; group];
    newsvm.trial    = [newsvm.trial; trial];

    handles.svm     = newsvm;
    handles         = RepairIndices(hObject, handles);
    handles.changed = 1;
    UpdateLists(hObject, handles);
end

function SaveAsButton_Callback(hObject, eventdata, handles)
    if (handles.changed)
        default = {'svm'};
        if (~isempty(handles.saveToVar))
            default = handles.saveToVar;
        end
        varName = inputdlg('Assign to variable: ', 'svmAverageGUI', 1, default);
        if (isempty(varName)) return; end

        assignin('base', varName{1}, handles.svm);

        fprintf(1, 'Saved data to variable ''%s''.\n', varName{1});

        handles.changed = 0;
        guidata(hObject, handles);
    else
        fprintf(1, 'No changes to save.\n');
    end
end

function SaveButton_Callback(hObject, eventdata, handles)
    if (handles.changed)
        if (isempty(handles.saveToVar))
            handles.saveToVar = inputdlg('Assign to variable: ', 'svmAverageGUI', 1, {'svm'});
            if (isempty(handles.saveToVar)) return; end
        end
        assignin('base', handles.saveToVar{1}, handles.svm);

        fprintf(1, 'Saved data to variable ''%s''.\n', handles.saveToVar{1});

        handles.changed = 0;
        guidata(hObject, handles);
    else
        fprintf(1, 'No changes to save.\n');
    end
end

function AverageGUI_DeleteFcn(hObject, eventdata, handles)
    if (handles.changed)
        buttonChosen = questdlg('Save changes?', 'svmAverageGUI', 'Yes', 'No', 'Yes');
        if (strcmp(buttonChosen,'Yes'))
            SaveButton_Callback(hObject, eventdata, handles);
        end
    end
end

function HelpButton_Callback(hObject, eventdata, handles)
    help svmAverageGUI;
end

%% Generated by GUIDE, necessary to run
% Create functions
function DataList_CreateFcn(hObject, eventdata, handles), end
function RunList_CreateFcn(hObject, eventdata, handles), end
function GroupList_CreateFcn(hObject, eventdata, handles), end
function TrialList_CreateFcn(hObject, eventdata, handles), end
function RunInput_CreateFcn(hObject, eventdata, handles), end
function GroupInput_CreateFcn(hObject, eventdata, handles), end
function TrialInput_CreateFcn(hObject, eventdata, handles), end

% Callbacks I didn't need
function RunInput_Callback(hObject, eventdata, handles), end
function TrialInput_Callback(hObject, eventdata, handles), end
function GroupInput_Callback(hObject, eventdata, handles), end


function tic(t)
% TIMETIC/TIC Implement the TIC operation on a timetic object
%
% The tic function duplicates the behavior of the global tic command in
% matlab on a timetic object.  It sets the current time to 0 and starts the
% timer.  (Notice the different from the start function which does not set
% the time to 0.)
%
% Using tic and toc on t allow for nested timers analogous to tic and toc.
%
% Example:
%   t = timetic();
%   tic(t);
%   toc(t);
%
% See also TIC, TIMETIC/TOC, TIMETIC/START

%
% David Gleich
% Stanford University
% 27 September 2006
%

t.set(0);
t.start();


function flat = vol2flatAllROIsLevels(volume,flat)
%
% flat = vol2flatAllROIsLevels(volume,flat)
%
% Calls vol2flatROI with the currently selected ROI.  Called from
% callback in xformFlatMenu.
%
% rmk 1/15/99
%
% Modifications:
% djh, 2/2001, replaced globals with local variables
% ras, 10/2004, version for flat level view

if ~volume.selectedROI
  myErrorDlg('Must have a selected ROI in the Volume window before it can be transformed to the Inplane window.');
end

for r=1:length(volume.ROIs)
  volROI = volume.ROIs(r);
  flatROI = vol2flatROILevels(volROI,volume,flat);
  flat = addROI(flat,flatROI,1);
end


% SERVER represents a handle to a server instance.
%
% To initialize a server, use:
%
% s = Server(options);
%
% See help for Server.Server and Server.rpc for usage.
classdef Server < handle

properties
  slaveCount
  serv_sock
  slave_processes
  slave_sock
  options
  hostname
  rootpath
  savedObjects
end

methods

function server = Server(options)
% SERVER.SERVER is the constructor for a server instance.
%
% This initializes the server instance using the provided options
% (documented below).  Server() will block until all of the slaves have
% connected.  After it returns, use Server.rpc() to call remote functions.
%
%'options' is a struct containing configuration information and
% must include at least one of options.slavelist or options.slavecount.
% You can launch the slave instances of MATLAB by hand, or use the
% slaveRun.sh script.  The function returns a handle to the
% server state.  The server object is then used to perform operations on the slaves.
%
% OPTIONS:
%
% options.slavecount
%
% options.port (default=10000)
% Port on which server will listen for slave connections.  If the server gets orphaned or you
% didn't destroy the server properly with serverDestroy(), then this may complain that a port
% is in use.  Restarting the server MATLAB instance will fix the problem.
%
% options.timeout (default=5000)
% Time (in milliseconds) for timeout of server socket.  This affects how frequently you
% can Ctl-C the server while it's waiting for slaves.  The clock resets each time a slave
% connects.
%
% options.retries (default=forever)
% Number of times to retry the accept() call to wait for a client.  By default, the server
% waits forever (i.e., until the user Ctl-C's the function or the clients all connect).  For
% batch jobs, don't forget to set this to something reasonable!
%
% options.slavedir (default = `pwd`)
% Working directory on the slave.  The slaves will all 'cd' to this directory after connecting.
%
% options.startslaves
% If nonzero, serverInit will attempt to start the slaves on its own.  This is presently
% a bit unstable but will hopefully make batch jobs easier in the future.
%
% options.slavepath (default = setup_paths())
% When options.startslaves is set, specifies a single path string passed to addpath() before
% the slaves are started.  This is usually the path to the matlabserver/ directory (which includes
% the slaveRun.m file needed by the slaves.)
%
% options.slavelist
% When options.startslaves is set, contains a cell array of host names of all the slaves to start.

  import java.io.*;
  import java.net.ServerSocket;
  import java.net.Socket;

  rootpath=setup_paths();

  if (~isfield(options, 'emulate'))
    options.emulate = 0;
  end
  if (~isfield(options, 'startslaves'))
    options.startslaves = 0;
  end
  if (~isfield(options, 'matlabpool'))
    options.matlabpool = 0;
  end
  if (~isfield(options, 'timeout'))
    options.timeout = 5000; % 5 second timeout
  end
  if (~isfield(options, 'retries'))
    options.retries = 100000; % try for a really long time
  end
  if (~isfield(options, 'port'))
    options.port = 10000;
  end
  if (~isfield(options, 'slavedir'))
    options.slavedir=pwd;
  end
  if (~isfield(options, 'slavepath'))
    options.slavepath=rootpath;
  end
  if (~isfield(options, 'slavecount'))
    if (~isfield(options, 'slavelist'))
      error('Must provide options.slavelist cell array or options.slavecount.');
    elseif (options.emulate)
      error('Must provide options.slavecount when "emulate" is used.');
      options.slavecount = length(options.slavelist);
    end
  else
    if (isfield(options, 'slavelist'))
      if (options.slavecount ~= length(options.slavelist))
        error('options.slavelist doesn''t match options.slavecount.');
      end
    end
  end
  if (options.startslaves)
    if (~isfield(options, 'slavelist'))
      error('Must provide options.slavelist cell array if using options.startslaves.');
    end
  end
  slaveCount = options.slavecount;
  server.slaveCount=slaveCount;
  server.options = options;
  server.rootpath = rootpath;

  if (options.emulate)
    % do nothing.

  else % emulate == 0

  % get local hostname
  addr=java.net.InetAddress.getLocalHost();
  hostname=char(addr.getHostName());
  server.hostname=hostname;

  % Open server socket
  server.serv_sock = ServerSocket(options.port, slaveCount);
  server.serv_sock.setReuseAddress(true);
  if (options.timeout > 0)
    server.serv_sock.setSoTimeout(options.timeout);
  end

  try

    % start up slaves
    if (options.startslaves)
      RT = java.lang.Runtime.getRuntime();
      for i = 1:slaveCount
        if (strcmp(options.slavelist{i}, 'localhost') == 1)
          cmd=sprintf('matlab -nodesktop -nosplash -r addpath(''%s''),slaveRun(''%s'',%d),quit;', options.slavepath, hostname, options.port);
          server.slave_process{i}=RT.exec(cmd, '', File(options.slavedir));
        else
          cmd=sprintf('ssh %s "matlab -nodesktop -nosplash -r addpath(''%s''),slaveRun(''%s'',%d),quit;"', options.slavelist{i}, options.slavepath, hostname, options.port);
          server.slave_process{i}=RT.exec(cmd);
        end
      end
    end

    % wait for slaves to connect; NOTE: slave_sock{i} and slave_process{i}
    % may not correspond.
    for i=1:slaveCount
      for r=1:options.retries
        try
          % accept connection from slave
          server.slave_sock{i} = server.serv_sock.accept();
          break ;
        catch
          % timeout
          if (r < options.retries)
            fprintf(1,'Waiting for slave to connect... %d/%d\n',i, server.slaveCount);
          else
            display('Timed out waiting for slaves.');
            rethrow(lasterror);
          end
        end
      end
    end

    % all are connected; close listener.
    server.serv_sock.close();

    try
      % exchange info with clients
      display('Handshaking...');
      slaveinfo.workdir = options.slavedir;
      server.rpc('handshake', {slaveinfo});

      % start matlabpool sequentially...
      if (options.matlabpool ~= 0)
        for i=1:server.slaveCount
          fprintf(1, 'Starting matlabpool on slave %d...', i);
          server.sendRequest(i, 0, 'matlabpool');
          dummy=server.getReply(i);
        end
      end
    catch
      display('Handshake failed.');
      rethrow(lasterror);
    end

  catch
    delete(server);
    server=[];
    rethrow(lasterror);
  end

  end % if options.emulate == 0
end

function clearReplies(server)
  if (isfield(server, 'slave_sock'))
    for i=1:length(server.slave_sock)
      server.slave_sock{i}.setSoTimeout(200);
      try
        server.getReply(i);
      end
      server.slave_sock{i}.setSoTimeout(0);
    end
  end
end

function delete(server)
% SERVER.DELETE destroys a server instance.
%
% This closes the listening socket, all slave sockets, and terminates any
% launched slave processes.

  fprintf(1, 'Destroying server on %s:%d.\n', ...
          server.hostname, server.options.port);

  if (isfield(server, 'serv_sock'))
    server.serv_sock.close();
  end

  if (isfield(server, 'slave_sock'))
    for i=1:length(server.slave_sock)
      server.slave_sock{i}.close();
    end
  end

  if (isfield(server, 'slave_process'))
    display('Shutting down slaves...');
    for i=1:length(server.slave_process)
      server.slave_process{i}.destroy();
    end
  end

end

end % end methods

end


function [output_dir] = run_bu_experiment(bu_dir, verbose, varargin)

    if(isunix)
        executable = '"../../build/bin/FeatureExtraction"';
    else
        executable = '"../../x64/Release/FeatureExtraction.exe"';
    end

    output_dir = 'experiments/bu_out/';

    buFiles = dir([bu_dir '*.avi']);

    % Only outputing the pose (-pose)
    command = sprintf('%s -inroot "%s" -out_dir "%s" -fx 500 -fy 500 -cx 160 -cy 120 -pose -vis-track ', executable, bu_dir, output_dir);

    for i=1:numel(buFiles)
        inputFile = [buFiles(i).name];
        command = cat(2, command, sprintf(' -f "%s" ', inputFile));
    end

    if(verbose)
        command = cat(2, command, [' -tracked ' outputVideo]);
    end

    if(any(strcmp('model', varargin)))
        command = cat(2, command, [' -mloc "', varargin{find(strcmp('model', varargin))+1}, '"']);
    end

    if(isunix)
        unix(command, '-echo')
    else
        dos(command);
    end

end


function qualityMeasure = imageQuality_sseq(sr, gt)

% Making sure that only functions in the SSEQ folder can be called
addpath(genpath('../algorithms/qualityMeasures/SSEQ/'));

path = pwd;
cd(['..', filesep, 'algorithms', filesep, 'qualityMeasures', filesep, 'SSEQ']);
qualityMeasure = - SSEQ(repmat(uint8(255*sr), 1, 1, 3));
cd(path);

% Making sure that only functions in the SSEQ folder can be called
rmpath(genpath('../algorithms/qualityMeasures/SSEQ/'));


function gpuids = getGpuIds(gpuname)
    deviceCount = getGpuCount_mex();
    gpuids = int32(0:(deviceCount-1));
    for idx = 1:deviceCount
        name = getGpuName_mex(gpuids(idx));
        if ~strcmp(name, gpuname)
            gpuids(idx) = -1;
        end
    end
    gpuids = gpuids(gpuids>=0);
end


function conditionPlots(hFig)
%"conditionPlots"
%   Adjusts all plots in the figure to some standard.
%
% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.
%
% This file is part of The Computational Environment for Radiotherapy Research (CERR).
%
% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.
%
% CERR has been financially supported by the US National Institutes of Health under multiple grants.
%
% CERR is distributed under the terms of the Lesser GNU Public License.
%
%     This version of CERR is free software: you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation, either version 3 of the License, or
%     (at your option) any later version.
%
% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
% See the GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with CERR.  If not, see <http://www.gnu.org/licenses/>.

if exist('hFig')
    hFigs = hFig;
else
    rootKids = get(0, 'children');
    hFigs = rootKids(strcmpi(get(rootKids, 'type'), 'figure'));
end

for j=1:length(hFigs)

    hFig = hFigs(j);
%     pos = get(hFig, 'position');
%     pos = [pos(1) pos(2) 280 336];
%     set(hFig, 'position', pos);
%     axis fill;

    kids = get(hFig, 'children');

    axes = kids(strcmpi(get(kids, 'type'), 'axes'));

	for i=1:length(axes)
        h = axes(i);

        set(h, 'FontSize', 14, 'FontWeight', 'Bold');
%         set(get(h, 'children'), 'color', [0 0 0]);
        set(get(h, 'title'), 'FontSize', 14, 'FontWeight', 'Bold');
        set(get(h, 'xlabel'), 'FontSize', 14, 'FontWeight', 'Bold');
        set(get(h, 'ylabel'), 'FontSize', 14, 'FontWeight', 'Bold');
        hDraw = get(h, 'Children');       % Drawings
        hLines = hDraw(strcmpi(get(hDraw, 'type'), 'line'));
        set(hLines, 'LineWidth', 2, 'MarkerSize', 9);
%         set(hLines, 'LineWidth', 2);

        legend = findobj(h, 'Tag', 'legend');
        legKids = get(legend, 'children');
        text = legKids(strcmpi(get(legKids, 'type'), 'text'));
        set(text, 'fontsize', 12, 'fontweight', 'Bold');
	end

end


classdef SetPowerSrcActiveStateAction < AbstractEventAction
    %SetPowerSrcActiveStateAction Summary of this class goes here
    %   Detailed explanation goes here

    properties
        src AbstractLaunchVehicleElectricalPowerSrcSnk
        activeStateToSet(1,1) logical = false;
    end

    properties(Constant)
        emptyVarArr = AbstractOptimizationVariable.empty(0,1);
    end

    methods
        function obj = SetPowerSrcActiveStateAction(src, activeStateToSet)
            if(nargin > 0)
                obj.src = src;
                obj.activeStateToSet = activeStateToSet;
            end

            obj.id = rand();
        end

        function newStateLogEntry = executeAction(obj, stateLogEntry)
            newStateLogEntry = stateLogEntry;
            stageStates = newStateLogEntry.stageStates;

            pwrSrcStates = AbstractLaunchVehicleElectricalPowerSrcState.empty(1,0);
            for(i=1:length(stageStates)) %#ok<*NO4LP>
                pwrSrcStates = horzcat(pwrSrcStates, stageStates(i).powerSrcStates); %#ok<AGROW>
            end

            pwrSrcs = AbstractLaunchVehicleElectricalPowerSrcSnk.empty(1,0);
            for(i=1:length(pwrSrcStates))
                pwrSrcs = horzcat(pwrSrcs, pwrSrcStates(i).getEpsSrcComponent()); %#ok<AGROW>
            end

            pwrSrcInd = find(pwrSrcs == obj.src,1,'first');
            pwrSrcState = pwrSrcStates(pwrSrcInd);

            pwrSrcState.setActiveState(obj.activeStateToSet);
        end

        function initAction(obj, initialStateLogEntry)
            %nothing
        end

        function name = getName(obj)
            if(obj.activeStateToSet)
                tf = 'Active';
            else
                tf = 'Inactive';
            end

            name = sprintf('Set Power Source State (%s = %s)',obj.src.getName(),tf);
        end

        function tf = usesStage(obj, stage)
            tf = false;
        end

        function tf = usesEngine(obj, engine)
            tf = false;
        end

        function tf = usesTank(obj, tank)
            tf = false;
        end

        function tf = usesEngineToTankConn(obj, engineToTank)
            tf = false;
        end

        function tf = usesStopwatch(obj, stopwatch)
            tf = false;
        end

        function tf = usesExtremum(obj, extremum)
            tf = false;
        end

        function tf = usesTankToTankConn(obj, tankToTank)
            tf = false;
        end

        function tf = usesPwrSink(obj, powerSink)
            tf = false;
        end

        function tf = usesPwrSrc(obj, powerSrc)
            tf = [obj.src] == powerSrc;
        end

        function tf = usesPwrStorage(obj, powerStorage)
            tf = false;
        end

        function [tf, vars] = hasActiveOptimVar(obj)
            tf = false;
            vars = obj.emptyVarArr;
        end
    end

    methods(Static)
        function addActionTf = openEditActionUI(action, lv)
            [~, powerSrcs] = lv.getPowerSrcsListBoxStr();

            if(not(isempty(powerSrcs)))
%                 addActionTf = lvd_EditActionSetPwrSrcStateGUI(action, lv);

                output = AppDesignerGUIOutput({false});
                lvd_EditActionSetPwrSrcStateGUI_App(action, lv, output);
                addActionTf = output.output{1};
            else
                addActionTf = false;
                warndlg('There are no power sources on the vehicle.  Create one first.','Cannot Create Action','modal');
            end
        end
    end
end


%% numConnect
% Below is a demonstration of the features of the |numConnect| function

%%
clear; close all; clc;

%% Syntax
% |[N]=numConnect(F,V);|

%% Description
% UNDOCUMENTED
%% Examples
%
%%
%
% <<gibbVerySmall.gif>>
%
% _*GIBBON*_
% <www.gibboncode.org>
%
% _Kevin Mattheus Moerman_, <gibbon.toolbox@gmail.com>
%%
% _*GIBBON footer text*_
%
% License: <https://github.com/gibbonCode/GIBBON/blob/master/LICENSE>
%
% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for
% image segmentation, image-based modeling, meshing, and finite element
% analysis.
%
% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.


function varargout = CreateGPR(varargin)
% m-file for CreateGPR.fig
% CreateGPR, by itself, creates a new object or raises the existing
% singleton*.
%
% USAGE:
%
%    varargout = addmetabolites(varargin)
%
% INPUTS:
%    varargin:    various input arguments
%
% OUTPUTS:
%    varargout:   various output arguments
%
% EXAMPLE:
%
%    H = CreateGPR() %returns the handle to a new CreateGPR or the handle to the existing singleton*.
%
%    CreateGPR('CALLBACK',hObject,eventData,handles,...) %calls the local
%    %function named `CALLBACK` in CreateGPR.M with the given input arguments.
%
%    CreateGPR('Property','Value',...) %creates a new CreateGPR or raises the
%    %existing singleton*.  Starting from the left, property value pairs are
%    %applied to the GUI before `CreateGPR_OpeningFcn` gets called. An
%    %unrecognized property name or invalid value makes property application
%    %stop. All inputs are passed to `CreateGPR_OpeningFcn` via `varargin`.
%
% .. Author: - Stefan G. Thorleifsson 2011
%
% NOTE:
%    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 CreateGPR
% .. Last Modified by GUIDE v2.5 18-Aug-2010 13:19:08
%
% .. rBioNet is published under GNU GENERAL PUBLIC LICENSE 3.0+
% .. Thorleifsson, S. G., Thiele, I., rBioNet: A COBRA toolbox extension for
% .. reconstructing high-quality biochemical networks, Bioinformatics, Accepted.
% .. rbionet@systemsbiology.is

gui_Singleton = 1; % Begin initialization code - DO NOT EDIT
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @CreateGPR_OpeningFcn, ...
                   'gui_OutputFcn',  @CreateGPR_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 CreateGPR is made visible.
function CreateGPR_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 CreateGPR (see VARARGIN)
handles.data = varargin{1};
set(handles.uitable1,'data',handles.data)
if ~isempty(varargin{2}) % Previous gpr set in table2
    handles.data2 = {varargin{2}};
else
   handles.data2 = {};
end

set(handles.uitable2,'data',handles.data2);
% Choose default command line output for CreateGPR
handles.output = [];
handles.selection1 = [];
handles.selection2 = [];
% Update handles structure
guidata(hObject, handles);

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

% --- Outputs from this function are returned to the command line.
function varargout = CreateGPR_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;
delete(gcf)

% --- Executes on button press in group_and.
function group_and_Callback(hObject, eventdata, handles)
% hObject    handle to group_and (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
line = handles.selection2;
data2 = handles.data2;

S = size(line);

genes = {};
GPR = [];
if S(1) <= 1
    msgbox('To group genes, multiple genes must be selected.',...
        'Select genes.','help')
    return
else
    lines = line(:,1);
    genes = data2(lines,1);

    for i = 1:S(1)-1
        GPR = [ GPR genes{i} ' and '];
    end
    GPR = ['(' GPR genes{end} ')'];

    cnt = 0;
    for k = 1:S(1)

        data2(lines(k)-cnt,:) = '';
        cnt = cnt + 1;

    end
    if isempty(data2)
        data2 = {GPR};
    else

        data2(end+1,:) = {GPR};
    end
end

handles.data2 = data2;

set(handles.uitable2,'data',handles.data2);

guidata(hObject,handles)

% --- Executes on button press in group_or.
function group_or_Callback(hObject, eventdata, handles)
% hObject    handle to group_or (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
line = handles.selection2;
data2 = handles.data2;

S = size(line);

genes = {};
GPR = [];
if S(1) <= 1
    msgbox('To group genes, multiple genes must be selected.',...
        'Select genes.','help')
    return
else
    lines = line(:,1);
    genes = data2(lines,1);

    for i = 1:S(1)-1
        GPR = [ GPR genes{i} ' or '];
    end
    GPR = ['(' GPR genes{end} ')'];

    cnt = 0;
    for k = 1:S(1)

        data2(lines(k)-cnt,:) = '';
        cnt = cnt + 1;

    end
    if isempty(data2)
        data2 = {GPR};
    else

        data2(end+1,:) = {GPR};
    end
end

handles.data2 = data2;

set(handles.uitable2,'data',handles.data2);

guidata(hObject,handles)

% --- Executes on button press in group_scatter.
function group_scatter_Callback(hObject, eventdata, handles)
% hObject    handle to group_scatter (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
data2 = handles.data2;
line = handles.selection2;
S = size(line);
if ~(S(1) == 1) || S(1) == 0
    return
else
    GPR = data2(line(1),1);
    genes = GPR2Genes(GPR);
    data2(line(1),:) = '';
    data2 = [data2; genes'];
    handles.data2 = data2;
    set(handles.uitable2,'data',handles.data2);
end

guidata(hObject,handles)

% --- Executes on button press in group_finished.
function group_finished_Callback(hObject, eventdata, handles)
% hObject    handle to group_finished (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
data2 = handles.data2;
S = size(data2);
if ~(S(1) == 1)
    msgbox('When finished only one line can remain in the Genes and GPR table'...
        ,'To many lines in table.','help');
    return
else
    handles.output = data2{1,1};
end
guidata(hObject,handles)

uiresume

% --- Executes on button press in group_addgene.
function group_addgene_Callback(hObject, eventdata, handles)
% hObject    handle to group_addgene (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
line = unique(handles.selection1(:,1));
S = size(line);

genes = handles.data(line(:,1),1);

data2 = handles.data2;
if isempty(data2)
    handles.data2 = genes;
    set(handles.uitable2,'data',handles.data2);
else
    handles.data2 = [data2; genes];
    set(handles.uitable2,'data',handles.data2);
end

guidata(hObject,handles)

% --- Executes when user attempts to close figure1.
function figure1_CloseRequestFcn(hObject, eventdata, handles)
% hObject    handle to figure1 (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
uiresume

% --- Executes when selected cell(s) is changed in uitable1.
function uitable1_CellSelectionCallback(hObject, eventdata, handles)
% hObject    handle to uitable1 (see GCBO)
% eventdata  structure with the following fields (see UITABLE)
%	Indices: row and column indices of the cell(s) currently selecteds
% handles    structure with handles and user data (see GUIDATA)
handles.selection1 = eventdata.Indices;
guidata(hObject,handles)

% --- Executes when selected cell(s) is changed in uitable2.
function uitable2_CellSelectionCallback(hObject, eventdata, handles)
% hObject    handle to uitable2 (see GCBO)
% eventdata  structure with the following fields (see UITABLE)
%	Indices: row and column indices of the cell(s) currently selecteds
% handles    structure with handles and user data (see GUIDATA)
handles.selection2 = eventdata.Indices;
guidata(hObject,handles)

% --- Executes on button press in group_removegene.
function group_removegene_Callback(hObject, eventdata, handles)
% hObject    handle to group_removegene (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
line = handles.selection2;
if size(line) == [0,0]
    return
end
line = unique(line(:,1));
data2 = handles.data2;
S = size(line);
cnt = 0;
for i = 1:S(1)
    data2(line(i)-cnt,:) = '';
    cnt = cnt + 1;
end
handles.data2 = data2;
set(handles.uitable2,'data',handles.data2);
guidata(hObject,handles)


classdef dme_line3p_opf < mp.dme_line3p & mp.dme_shared_opf

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

%     properties
%     end     %% properties

%     methods
%     end     %% methods
end         %% classdef