function varargout = Gain_Finder(varargin)
%GAIN_FINDER M-file for Gain_Finder.fig
%      GAIN_FINDER, by itself, creates a new GAIN_FINDER or raises the existing
%      singleton*.
%
%      H = GAIN_FINDER returns the handle to a new GAIN_FINDER or the handle to
%      the existing singleton*.
%
%      GAIN_FINDER('Property','Value',...) creates a new GAIN_FINDER using the
%      given property value pairs. Unrecognized properties are passed via
%      varargin to Gain_Finder_OpeningFcn.  This calling syntax produces a
%      warning when there is an existing singleton*.
%
%      GAIN_FINDER('CALLBACK') and GAIN_FINDER('CALLBACK',hObject,...) call the
%      local function named CALLBACK in GAIN_FINDER.M with the given input
%      arguments.
%
%      *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 Gain_Finder

% Last Modified by GUIDE v2.5 11-Feb-2010 14:51:57

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
    'gui_Singleton',  gui_Singleton, ...
    'gui_OpeningFcn', @Gain_Finder_OpeningFcn, ...
    'gui_OutputFcn',  @Gain_Finder_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 Gain_Finder is made visible.
function Gain_Finder_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   unrecognized PropertyName/PropertyValue pairs from the
%            command line (see VARARGIN)

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

% Update handles structure
guidata(hObject, handles);

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

% --- Outputs from this function are returned to the command line.
function varargout = Gain_Finder_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;

set(handles.color_stable,'UserData',2);
set(handles.color_stable_blue,'Checked','on');

set(handles.color_boustable,'UserData',3);
set(handles.color_boustable_green,'Checked','on');

set(handles.color_unstable,'UserData',1);
set(handles.color_unstable_red,'Checked','on');
% --- Executes on selection change in tab_result.
function tab_result_Callback(hObject, eventdata, handles)
% hObject    handle to tab_result (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

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

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

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

function input_gedit_Callback(hObject, eventdata, handles)
% hObject    handle to input_gedit (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 input_gedit as text
%        str2double(get(hObject,'String')) returns contents of input_gedit as a double

% --- Executes during object creation, after setting all properties.
function input_gedit_CreateFcn(hObject, eventdata, handles)
% hObject    handle to input_gedit (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 start_gedit_Callback(hObject, eventdata, handles)
% hObject    handle to start_gedit (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 start_gedit as text
%        str2double(get(hObject,'String')) returns contents of start_gedit as a double

% --- Executes during object creation, after setting all properties.
function start_gedit_CreateFcn(hObject, eventdata, handles)
% hObject    handle to start_gedit (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 to_gedit_Callback(hObject, eventdata, handles)
% hObject    handle to to_gedit (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 to_gedit as text
%        str2double(get(hObject,'String')) returns contents of to_gedit as a double

% --- Executes during object creation, after setting all properties.
function to_gedit_CreateFcn(hObject, eventdata, handles)
% hObject    handle to to_gedit (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 intv_gedit_Callback(hObject, eventdata, handles)
% hObject    handle to intv_gedit (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 intv_gedit as text
%        str2double(get(hObject,'String')) returns contents of intv_gedit as a double

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

%============specify color for stable system================
switch get(handles.color_stable,'UserData')
    case 1
        stacol='red';
    case 2
        stacol='blue';
    case 3
        stacol='green';
    case 4
        stacol='yellow';
    case 5
        stacol='gray';
end
%===========================================================

%=========specify color for boundary stable system==========
switch get(handles.color_boustable,'UserData')
    case 1
        boustacol='red';
    case 2
        boustacol='blue';
    case 3
        boustacol='green';
    case 4
        boustacol='yellow';
    case 5
        boustacol='gray';
end
%===========================================================

%===========specify color for unstable system===============
switch get(handles.color_unstable,'UserData')
    case 1
        unstacol='red';
    case 2
        unstacol='blue';
    case 3
        unstacol='green';
    case 4
        unstacol='yellow';
    case 5
        unstacol='gray';
end
%===========================================================

set(handles.tab_result,'String','');

pstr=get(handles.input_gedit,'String');

if isempty(get(handles.input_gedit,'String'))
    errordlg('Equation not found','Equation Error');
    return
elseif isempty(findstr(pstr,'k'))
    errordlg('Variable of gain(k) is''nt exist','Equation Error');
    return
elseif isempty(get(handles.start_gedit,'String'))
    errordlg('Start gain value not found','Input Error');
    return

elseif isempty(get(handles.to_gedit,'String'))
    errordlg('End gain value not found','Input Error');
    return

elseif isempty(get(handles.intv_gedit,'String'))
    errordlg('Interval not found','Input Error');
    return

end

hwait=waitbar(0,'please wait...','CreateCancelBtn','cancel_exe');
setappdata(hwait,'abort',false);
syms k;
psym=sym(pstr);

start=str2double(get(handles.start_gedit,'String'));
interval=str2double(get(handles.intv_gedit,'String'));
to=str2double(get(handles.to_gedit,'String'));

res='';
b=1;

for i=start:interval:to
    if getappdata(hwait,'abort')
        waitbar(to,hwait,'caceling... 100%');
        delete(hwait);
        return;
    end
    pol=subs(psym,k,i);
    rot=fixz(double(solve(poly2strs(pol,'s'))),7);
    [num rep]=repeatv(rot);
    len=length(num);
    rhp=0;
    njw=0;
    nrjw=0;
    cen=0;
    for j=1:len
        if real(num(j))>0
            rhp=rhp+rep(j);
        elseif real(num(j))==0 && imag(num(j))~=0
            njw=njw+rep(j);
            if rep(j)>=2
                nrjw=nrjw+rep(j);
            end
        elseif num(j)==0
            cen=cen+rep(j);
        end
    end
    nrjw=nrjw/2;
    if rhp~=0 || nrjw>=2 || cen~=0
        res{b}=['',unstacol)...
            sprintf('k=%g',i) '      '...
            'system is unstable' ''];
        b=b+1;
    elseif rhp==0 && nrjw==0 && cen==0 && njw~=0
        res{b}=['',boustacol)...
            sprintf('k=%g',i) '      '...
            'system is boundary stable' ''];
        b=b+1;
    else
        res{b}=['',stacol)...
            sprintf('k=%g',i) '      '...
            'system is stable' ''];
        b=b+1;
    end

    if i>0
        waitbar(i/to,hwait,sprintf('please wait... %d%%',round((i/to)*100)));
    end
end
res{b}=' ';
set(handles.tab_result,'Enable','inactive');
set(handles.tab_result,'String',res);
set(handles.tab_result,'Value',b);
delete(hwait);

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

% --------------------------------------------------------------------
function color_default_Callback(hObject, eventdata, handles)
% hObject    handle to color_default (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.color_stable_red,'Checked','off');
set(handles.color_stable_blue,'Checked','off');
set(handles.color_stable_green,'Checked','off');
set(handles.color_stable_yellow,'Checked','off');
set(handles.color_stable_gray,'Checked','off');

set(handles.color_boustable_red,'Checked','off');
set(handles.color_boustable_blue,'Checked','off');
set(handles.color_boustable_green,'Checked','off');
set(handles.color_boustable_yellow,'Checked','off');
set(handles.color_boustable_gray,'Checked','off');

set(handles.color_unstable_red,'Checked','off');
set(handles.color_unstable_blue,'Checked','off');
set(handles.color_unstable_green,'Checked','off');
set(handles.color_unstable_yellow,'Checked','off');
set(handles.color_unstable_gray,'Checked','off');

set(handles.color_stable,'UserData',2);
set(handles.color_stable_blue,'Checked','on');

set(handles.color_boustable,'UserData',3);
set(handles.color_boustable_green,'Checked','on');

set(handles.color_unstable,'UserData',1);
set(handles.color_unstable_red,'Checked','on');
% --------------------------------------------------------------------
function color_stable_Callback(hObject, eventdata, handles)
% hObject    handle to color_stable (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

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

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

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

% --------------------------------------------------------------------
function color_stable_red_Callback(hObject, eventdata, handles)
% hObject    handle to color_stable_red (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.color_stable_red,'Checked','off');
set(handles.color_stable_blue,'Checked','off');
set(handles.color_stable_green,'Checked','off');
set(handles.color_stable_yellow,'Checked','off');
set(handles.color_stable_gray,'Checked','off');

set(handles.color_stable,'UserData',1);
set(handles.color_stable_red,'Checked','on');

% --------------------------------------------------------------------
function color_stable_blue_Callback(hObject, eventdata, handles)
% hObject    handle to color_stable_blue (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.color_stable_red,'Checked','off');
set(handles.color_stable_blue,'Checked','off');
set(handles.color_stable_green,'Checked','off');
set(handles.color_stable_yellow,'Checked','off');
set(handles.color_stable_gray,'Checked','off');

set(handles.color_stable,'UserData',2);
set(handles.color_stable_blue,'Checked','on');

% --------------------------------------------------------------------
function color_stable_green_Callback(hObject, eventdata, handles)
% hObject    handle to color_stable_green (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.color_stable_red,'Checked','off');
set(handles.color_stable_blue,'Checked','off');
set(handles.color_stable_green,'Checked','off');
set(handles.color_stable_yellow,'Checked','off');
set(handles.color_stable_gray,'Checked','off');

set(handles.color_stable,'UserData',3);
set(handles.color_stable_green,'Checked','on');

% --------------------------------------------------------------------
function color_stable_yellow_Callback(hObject, eventdata, handles)
% hObject    handle to color_stable_yellow (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.color_stable_red,'Checked','off');
set(handles.color_stable_blue,'Checked','off');
set(handles.color_stable_green,'Checked','off');
set(handles.color_stable_yellow,'Checked','off');
set(handles.color_stable_gray,'Checked','off');

set(handles.color_stable,'UserData',4);
set(handles.color_stable_yellow,'Checked','on');

% --------------------------------------------------------------------
function color_stable_gray_Callback(hObject, eventdata, handles)
% hObject    handle to color_stable_gray (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.color_stable_red,'Checked','off');
set(handles.color_stable_blue,'Checked','off');
set(handles.color_stable_green,'Checked','off');
set(handles.color_stable_yellow,'Checked','off');
set(handles.color_stable_gray,'Checked','off');

set(handles.color_stable,'UserData',5);
set(handles.color_stable_gray,'Checked','on');

% --------------------------------------------------------------------
function color_boustable_red_Callback(hObject, eventdata, handles)
% hObject    handle to color_boustable_red (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.color_boustable_red,'Checked','off');
set(handles.color_boustable_blue,'Checked','off');
set(handles.color_boustable_green,'Checked','off');
set(handles.color_boustable_yellow,'Checked','off');
set(handles.color_boustable_gray,'Checked','off');

set(handles.color_boustable,'UserData',1);
set(handles.color_boustable_red,'Checked','on');

% --------------------------------------------------------------------
function color_boustable_blue_Callback(hObject, eventdata, handles)
% hObject    handle to color_boustable_blue (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.color_boustable_red,'Checked','off');
set(handles.color_boustable_blue,'Checked','off');
set(handles.color_boustable_green,'Checked','off');
set(handles.color_boustable_yellow,'Checked','off');
set(handles.color_boustable_gray,'Checked','off');

set(handles.color_boustable,'UserData',2);
set(handles.color_boustable_blue,'Checked','on');

% --------------------------------------------------------------------
function color_boustable_green_Callback(hObject, eventdata, handles)
% hObject    handle to color_boustable_green (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.color_boustable_red,'Checked','off');
set(handles.color_boustable_blue,'Checked','off');
set(handles.color_boustable_green,'Checked','off');
set(handles.color_boustable_yellow,'Checked','off');
set(handles.color_boustable_gray,'Checked','off');

set(handles.color_boustable,'UserData',3);
set(handles.color_boustable_green,'Checked','on');

% --------------------------------------------------------------------
function color_boustable_yellow_Callback(hObject, eventdata, handles)
% hObject    handle to color_boustable_yellow (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.color_boustable_red,'Checked','off');
set(handles.color_boustable_blue,'Checked','off');
set(handles.color_boustable_green,'Checked','off');
set(handles.color_boustable_yellow,'Checked','off');
set(handles.color_boustable_gray,'Checked','off');

set(handles.color_boustable,'UserData',4);
set(handles.color_boustable_yellow,'Checked','on');

% --------------------------------------------------------------------
function color_boustable_gray_Callback(hObject, eventdata, handles)
% hObject    handle to color_boustable_gray (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.color_boustable_red,'Checked','off');
set(handles.color_boustable_blue,'Checked','off');
set(handles.color_boustable_green,'Checked','off');
set(handles.color_boustable_yellow,'Checked','off');
set(handles.color_boustable_gray,'Checked','off');

set(handles.color_boustable,'UserData',5);
set(handles.color_boustable_gray,'Checked','on');

% --------------------------------------------------------------------
function color_unstable_red_Callback(hObject, eventdata, handles)
% hObject    handle to color_unstable_red (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.color_unstable_red,'Checked','off');
set(handles.color_unstable_blue,'Checked','off');
set(handles.color_unstable_green,'Checked','off');
set(handles.color_unstable_yellow,'Checked','off');
set(handles.color_unstable_gray,'Checked','off');

set(handles.color_unstable,'UserData',1);
set(handles.color_unstable_red,'Checked','on');

% --------------------------------------------------------------------
function color_unstable_blue_Callback(hObject, eventdata, handles)
% hObject    handle to color_unstable_blue (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.color_unstable_red,'Checked','off');
set(handles.color_unstable_blue,'Checked','off');
set(handles.color_unstable_green,'Checked','off');
set(handles.color_unstable_yellow,'Checked','off');
set(handles.color_unstable_gray,'Checked','off');

set(handles.color_unstable,'UserData',2);
set(handles.color_unstable_blue,'Checked','on');

% --------------------------------------------------------------------
function color_unstable_green_Callback(hObject, eventdata, handles)
% hObject    handle to color_unstable_green (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.color_unstable_red,'Checked','off');
set(handles.color_unstable_blue,'Checked','off');
set(handles.color_unstable_green,'Checked','off');
set(handles.color_unstable_yellow,'Checked','off');
set(handles.color_unstable_gray,'Checked','off');

set(handles.color_unstable,'UserData',3);
set(handles.color_unstable_green,'Checked','on');

% --------------------------------------------------------------------
function color_unstable_yellow_Callback(hObject, eventdata, handles)
% hObject    handle to color_unstable_yellow (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.color_unstable_red,'Checked','off');
set(handles.color_unstable_blue,'Checked','off');
set(handles.color_unstable_green,'Checked','off');
set(handles.color_unstable_yellow,'Checked','off');
set(handles.color_unstable_gray,'Checked','off');

set(handles.color_unstable,'UserData',4);
set(handles.color_unstable_yellow,'Checked','on');

% --------------------------------------------------------------------
function color_unstable_gray_Callback(hObject, eventdata, handles)
% hObject    handle to color_unstable_gray (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.color_unstable_red,'Checked','off');
set(handles.color_unstable_blue,'Checked','off');
set(handles.color_unstable_green,'Checked','off');
set(handles.color_unstable_yellow,'Checked','off');
set(handles.color_unstable_gray,'Checked','off');

set(handles.color_unstable,'UserData',5);
set(handles.color_unstable_gray,'Checked','on');

% --------------------------------------------------------------------
function help_help_Callback(hObject, eventdata, handles)
% hObject    handle to help_help (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
hlpl1=sprintf('you can input Equation only poly(Coefficient of Equation(s)=0)');
hlpl2=sprintf('\n with variable ''k''(Gain)');
hlpl3=sprintf('\n---for example : [1 3 3 2 k]--- or [1 3*k 2 1 2*k 1]---');
hlpl4=sprintf('\ncaution : variable of Gain is lowercase(k) & not uppercase(K)');
hlpl5=sprintf('\nif input(poly equation) haven''t variable of Gain(k) then');
hlpl6=sprintf('\ngui give error message');
hlpl7=sprintf('\ndecrease interval==increase precision==long time process');
hlpt=strvcat(hlpl1,hlpl2,hlpl3,hlpl4,hlpl5,hlpl6,hlpl7);
helpdlg(hlpt,'Help:Input');

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

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

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

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

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

% --------------------------------------------------------------------
function help_demo_ex1_step1_Callback(hObject, eventdata, handles)
% hObject    handle to help_demo_ex1_step1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.input_gedit,'String','[1 3 3 2 k]');
set(handles.start_gedit,'String','-10');
set(handles.to_gedit,'String','10');
set(handles.intv_gedit,'String','1');

% --------------------------------------------------------------------
function help_demo_ex1_step2_Callback(hObject, eventdata, handles)
% hObject    handle to help_demo_ex1_step2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.input_gedit,'String','[1 3 3 2 k]');
set(handles.start_gedit,'String','0');
set(handles.to_gedit,'String','2');
set(handles.intv_gedit,'String','0.01');

% --------------------------------------------------------------------
function help_demo_ex2_step1_Callback(hObject, eventdata, handles)
% hObject    handle to help_demo_ex2_step1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.input_gedit,'String','[1 3*k 6 4 1]');
set(handles.start_gedit,'String','-10');
set(handles.to_gedit,'String','10');
set(handles.intv_gedit,'String','1');

% --------------------------------------------------------------------
function help_demo_ex2_step2_Callback(hObject, eventdata, handles)
% hObject    handle to help_demo_ex2_step2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.input_gedit,'String','[1 3*k 6 4 1]');
set(handles.start_gedit,'String','0');
set(handles.to_gedit,'String','8');
set(handles.intv_gedit,'String','0.1');

% --------------------------------------------------------------------
function help_demo_ex3_step1_Callback(hObject, eventdata, handles)
% hObject    handle to help_demo_ex3_step1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.input_gedit,'String','[1 0 5 0 k]');
set(handles.start_gedit,'String','-10');
set(handles.to_gedit,'String','10');
set(handles.intv_gedit,'String','1');

% --------------------------------------------------------------------
function help_demo_ex3_step2_Callback(hObject, eventdata, handles)
% hObject    handle to help_demo_ex3_step2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.input_gedit,'String','[1 0 5 0 k]');
set(handles.start_gedit,'String','0');
set(handles.to_gedit,'String','7');
set(handles.intv_gedit,'String','0.1');

% --------------------------------------------------------------------
function help_demo_ex4_step1_Callback(hObject, eventdata, handles)
% hObject    handle to help_demo_ex4_step1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.input_gedit,'String','[1 0 6 0 9 0 k]');
set(handles.start_gedit,'String','-10');
set(handles.to_gedit,'String','10');
set(handles.intv_gedit,'String','1');

% --------------------------------------------------------------------
function help_demo_ex4_step2_Callback(hObject, eventdata, handles)
% hObject    handle to help_demo_ex4_step2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.input_gedit,'String','[1 0 6 0 9 0 k]');
set(handles.start_gedit,'String','0');
set(handles.to_gedit,'String','4');
set(handles.intv_gedit,'String','0.1');

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

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

% --------------------------------------------------------------------
function cgmenuin_copy_Callback(hObject, eventdata, handles)
% hObject    handle to cgmenuin_copy (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
clipboard('copy',get(handles.input_gedit,'String'));

% --------------------------------------------------------------------
function cgmenuin_paste_Callback(hObject, eventdata, handles)
% hObject    handle to cgmenuin_paste (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.input_gedit,'String',clipboard('paste'));


function [ ret ] =setPin1Off( t_Kuka )
%% About:
% This function is used to set off the Pin 1 of the KUKA iiwa 7 R 800.

%% Syntax:
% [ ret ] = setPin1Off( t_Kuka )

%% Arreguments:
% t_Kuka: is the TCP/IP connection

%% Return value:
% ret: a boolean variable
% true: if the message is treated successfully
% false: if an error has happened

% Copy right, Mohammad SAFEEA, 3rd of May 2017

theCommand='pin1off';
fprintf(t_Kuka, theCommand);
message=fgets(t_Kuka);
ret=checkAcknowledgment(message);
end


function closeAllFigures(fig_handle)
% Close all the dockable figures
% goGPS main windows are not dockable and will remain open ^_^
%
% SINTAX:
%   closeAllFigures(<fig_handles>);
%   closeAllFigures()
%
% EXAMPLE:
%   dockAllFigures();
%
% INPUT:
%   fig_handles = listo of handlers to the figure to close        <optional argument>
%
% DEFAULT VALUES:
%   fig_handle all the figures
%

%--- * --. --- --. .--. ... * ---------------------------------------------
%               ___ ___ ___
%     __ _ ___ / __| _ | __|
%    / _` / _ \ (_ |  _|__ \
%    \__, \___/\___|_| |___/
%    |___/                    v 1.0RC1
%
%--------------------------------------------------------------------------
%  Copyright (C) 2021 Geomatics Research & Development srl (GReD)
%  Written by:       Andrea Gatti
%  Contributors:     Andrea Gatti ...
%  A list of all the historical goGPS contributors is in CREDITS.nfo
%--------------------------------------------------------------------------
%
%   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/>.
%
%--------------------------------------------------------------------------
% 01100111 01101111 01000111 01010000 01010011
%--------------------------------------------------------------------------
    if (nargin == 1)
        set(fig_handle,'WindowStyle','docked');
    else
        all_fh = findall(0,'Type','figure');
        for fid = 1:length(all_fh)
            if numel(all_fh(fid).DockControls) ~= 3
                delete(all_fh(fid));
            end
        end
    end
end


function closeInplaneWindow()
%
% closeInplaneWindow()
%
% clears INPLANE while closing the corresponding window.
%
% djh, 1/26/98
mrGlobals

% Get the current figure
currentFigure = get(0,'CurrentFigure');

% Find and clear the corresponding INPLANE structure
try
    for s = 1:length(INPLANE)
        if checkfields(INPLANE{s}, 'ui', 'figNum')
            if INPLANE{s}.ui.figNum==currentFigure
                % let's try saving the prefs as we go,
                % so we pick up where we left off... (ras 01/06)
                if ispref('VISTA', 'savePrefs')
                    flag = getpref('VISTA', 'savePrefs');
                    if flag==1
                        savePrefs(INPLANE{s});
                    end
                end

                % if this was the selected inplane, well, it ain't no more.
                if selectedINPLANE == s
                    selectedINPLANE = [];
                end

                % finally, clear the global variable
                INPLANE{s} = [];
            end
        end
    end
end

% Delete the window
delete(currentFigure);

% If there are no open Inplane windows left, re-initialize it as empty
if isempty(cellfind(INPLANE)), INPLANE = {}; end

% Check if there are no more open views: if not, clean the workspace
if isempty(cellfind(INPLANE)) & isempty(cellfind(VOLUME)) & ...
   isempty(cellfind(FLAT))
    mrvCleanWorkspace;
end

return


function [ wav_files ] = find_wav( path )
%FIND_WAV, find all wav file recursively
wav_files = [];
if(isdir(path) == 0)

    return;
end
path_files = dir(path);
fileNum = length(path_files);
for k= 3:fileNum
    file = [path,'\', path_files(k).name];
    if (path_files(k).isdir == 1)
        ret = find_wav(file);
        if(isempty(ret) ~= 1)
            if(isempty(wav_files))
                wav_files = char(ret);
            else
                wav_files = char(wav_files, ret);
            end
        end
    elseif strfind(path_files(k).name, '.wav')
        if(isempty(wav_files))
            wav_files = char(file);
        else
            wav_files = char(wav_files, file);
        end
    end
end
end


function [rasterSegments, planC, isError] = getRasterSegments(structureID, planC, varargin)
%"getRasterSegments"
%   Data Access Function -- Returns rasterSegments for specified
%   structure from given planC.  varargin allows for a particular
%   slice to be specified, in which case only rasterSegs from that
%   slice are returned.
%
%   If structureID is a string, segs are returned from the structure
%   whose name (case insensitive) matches structureID. If numeric,
%   a direct index is used.
%
% JRA 10/27/03
%
%Usage:
%   [rasterSegments, planC, isError] = getRasterSegments(structureID, planC, varargin)

if ~exist('planC')
    global planC
end

%Warnings only display if isError is not a argout.
if nargout ~= 3
    showWarnings = 1;
else
    showWarnings = 0;
end
rasterSegments = [];
errorMsg = '';
isError = 0;

try
    indexS = planC{end};
    allStructureNames = {planC{indexS.structures}.structureName};
catch
    isError = errorEncounter(['Invalid planC.'], showWarnings);
    return;
end

%Check for matching structureID strings.
if ischar(structureID)
    requestedName = structureID;
    structureID = find(strcmpi(structureID, allStructureNames));
    if isempty(structureID)
        isError = errorEncounter(['No structure matching name ''' requestedName ''' exists.'], showWarnings);
        return;
    end
%Check that numeric ID is in range, and only one value is asked for.
elseif isnumeric(structureID)
    numStructures = length(planC{indexS.structures});
    if structureID > numStructures | structureID <= 0 | length(structureID) > 1
        isError = errorEncounter(['Numeric structureID is out of range.'], showWarnings);
        return;
    end
%Not a number, not a string.  Invalid ID.
else
    isError = errorEncounter(['Invalid structureID.'], showWarnings);
    return;
end

%Try and access rasterSegments given the current index.
if isfield(planC{indexS.structures}, 'rasterSegments')
    rasterSegments = planC{indexS.structures}(structureID).rasterSegments;

    if isempty(rasterSegments)
        try
            warning(['No rasterSegments exist for structure ' allStructureNames{structureID} ', generating.']); %Do not set iserror.
            if isfield(planC{indexS.structures}(structureID), 'associatedScan') & ~isempty(planC{indexS.structures}(structureID).associatedScan)
                scanSet = planC{indexS.structures}(structureID).associatedScan;
            else
                scanSet = 1;
            end

            planC = getRasterSegs(planC, structureID);
            rasterSegments = planC{indexS.structures}(structureID).rasterSegments;
        catch
            isError = errorEncounter(['No rasterSegments exist for structure ' allStructureNames{structureID} ', could not be generated.'], showWarnings);
        end
    end

    if nargin == 3
        sliceNum = varargin{1};
        rasterSegments = rasterSegments(find(rasterSegments(:,6) == sliceNum),:);
    end
else
    isError = errorEncounter(['rasterSegments field is nonexistant. Archive appears corrupt.'], showWarnings);
end

function isError = errorEncounter(errorString, showWarnings)
    isError = 1;
    if showWarnings
        warning(errorString);
    end


%kksync 'synchronize an objects database and any caches'
% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros ksync.pane file
%
% Parameters:
% String: tb 'Toolbox', default: ' ': 'toolbox name'
% String: oname 'Object ', default: ' ': 'name of object in toolbox'
%
% Example: kksync( {'tb',' ';'oname',' '})
%
% Khoros helpfile follows below:
%
%  PROGRAM
% ksync - synchronize object database and any caches
%
%  DESCRIPTION
% .I ksync
% is used to synchronize an object with any cache held by kcms.
% There are two common situations where "ksync" would be used:
%
%  "o"
% When an object's database has been manually edited,
% using "kdbmedit",
% or some other utility.
%
%  "o"
% When a cache mechanism has been changed.
%
% For example, if kcms is changed to store a new field in the cache,
% then all caches must be updated.
% The example below shows how all objects in all toolboxes can
% be synchronized.
%
% In the future "ksync" will be updated to include options for
% synchronizing all objects within a given toolbox,
% and synchronizing all objects in all toolboxes.
%
%
%
%  EXAMPLES
% The following bourne shell script can be used to invoke ksync on
% all objects in all toolboxes
%
%
%     #!/bin/sh
%     for toolbox in `kecho -echo toolboxes`; do
%             for object in `kecho -tb $toolbox -echo objects`; do
%                     ksync -tb $toolbox -oname $object
%             done
%     done
%
%
%  "SEE ALSO"
%
%  RESTRICTIONS
%
%  REFERENCES
%
%  COPYRIGHT
% Copyright (C) 1993 - 1997, Khoral Research, Inc. ("KRI")  All rights reserved.
%

function varargout = kksync(varargin)
Inputs={};
if nargin ==0
  arglist={'',''};
elseif nargin ==1
  arglist=varargin{1};
else error('Usage: [out1,..] = kksync(arglist).');
end
if size(arglist,2)~=2
  error('arglist must be of form {''ParameterTag1'',value1;''ParameterTag2'',value2}')
 end
narglist={'tb', ' ';'oname', ' '};
maxval={0,0};
minval={0,0};
istoggle=[0,0];
was_set=istoggle * 0;
paramtype={'String','String'};
% identify the input arrays and assign them to the arguments as stated by the user
if ~iscell(Inputs)
Inputs = {Inputs};
end
NumReqOutputs=0; 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(0);
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
callKhoros([w 'ksync"  '],Inputs,narglist);


classdef GeneralFormattingDirective < MBeautifier.Directive

    properties (SetAccess = immutable)
        Name = 'Format'
    end

    methods (Access = protected)
        function [success, toBeGarbadeCollected] = tryToupdateFromValue(obj, value)
            success = true;
            toBeGarbadeCollected = false;
            if strcmpi(value, 'on')
                obj.Values = {};
                toBeGarbadeCollected = true;
            elseif strcmpi(value, 'off')
                obj.Values = {'off'};
            else
                toBeGarbadeCollected = ~numel(obj.Values);
                success = false;
            end
        end
    end
end


function ostr = mlstripcommentsstr(istr)
%MLSTRIPCOMMENTSSTR Strip comments from a string with MATLAB code.
%
%   OSTR = MLSTRIPCOMMENTSSTR(ISTR) takes the input string ISTR, assuming it
%   contains MATLAB code, strips all MATLAB comments, and returns the result as
%   the output string OSTR.  The input string must be a row vector or a cell
%   array of row vectors.  Any input string may be a multi-line string, that is
%   a string containing newline characters, for example a string containing the
%   entire contents of an m-file.
%
%   Example:  Read all MATLAB code from an m-file opened for reading on file
%   identifier "fid" and strip all comments:
%
%       str = fread(fid);               % data as numerical column vector
%       str = char(str)';               % data as character row vector
%       str = mlstripcommentsstr(str);  % strip all MATLAB comments
%
%   See also MLSTRIPCOMMENTSFILE, MLSTRIPCOMMENTSFID.

%   Author:      Peter J. Acklam
%   Time-stamp:  2004-03-18 08:23:19 +0100
%   E-mail:      pjacklam@online.no
%   URL:         http://home.online.no/~pjacklam

   % Regex for removing a comment on a line possibly containing MATLAB code.
   %
   % Use a persistent variable so that the variable is set up only once.
   %
   % Find the part of the line which is not a comment and then replace the
   % whole line with the part that was not a comment.
   %
   % A comment is started by a percent sign, but not all percent signs start a
   % comment.  A percent sign might be embedded in a string, in which case the
   % percent sign obviously does not start a comment.  So we must look for
   % percent signs which are not embedded in strings.  To do this we must find
   % all strings.  Strings are delimited by single quotes, but not all single
   % quotes start strings.  A single quote might also be a tranpose operator.
   % So we must look for single quotes which are not tranpose operators.
   %
   % The MATLAB grammar (syntax and semantics) is not available to the public,
   % but from my knowledge, a single quote is a transpose operator if and only
   % if one of the following criteria is satisfied
   %
   %   1) it follows a right closing delimiter
   %   2) it follows right after a variable name or function name
   %   3) it follows right after a period (as part of the ".'" operator)
   %   4) it follows right after another tranpose operator
   %
   % This can be immediately after a right closing bracket ("]"), right closing
   % parenthesis (")"), right closing brace ("}"), an English letter ("a" to
   % "z" and "A" to "Z", a digit ("0" to "9"), an underline ("_"), a period
   % ("."), or another single quote ("'").

   persistent mainregex

   if isempty(mainregex)

      mainregex = [ ...
         ' (                   ' ... % Grouping parenthesis (content goes to $1).
         '   ( ^ | \n )        ' ... % Beginning of string or beginning of line.
         '   (                 ' ... % Non-capturing grouping parenthesis.
         '                     ' ...
         '' ... % Match anything that is neither a comment nor a string...
         '       (             ' ... % Non-capturing grouping parenthesis.
         '           [\]\)}\w.]' ... % Either a character followed by
         '           ''+       ' ... %    one or more transpose operators
         '         |           ' ... % or else
         '           [^''%]    ' ... %   any character except single quote (which
         '                     ' ... %   starts a string) or a percent sign (which
         '                     ' ... %   starts a comment).
         '       )+            ' ... % Match one or more times.
         '                     ' ...
         '' ...  % ...or...
         '     |               ' ...
         '                     ' ...
         '' ...  % ...match a string.
         '       ''            ' ... % Opening single quote that starts the string.
         '         [^''\n]*    ' ... % Zero or more chars that are neither single
         '                     ' ... %   quotes (special) nor newlines (illegal).
         '         (           ' ... % Non-capturing grouping parenthesis.
         '           ''''      ' ... % An embedded (literal) single quote character.
         '           [^''\n]*  ' ... % Again, zero or more chars that are neither
         '                     ' ... %   single quotes nor newlines.
         '         )*          ' ... % Match zero or more times.
         '       ''            ' ... % Closing single quote that ends the string.
         '                     ' ...
         '   )*                ' ... % Match zero or more times.
         ' )                   ' ...
         ' [^\n]*              ' ... % What remains must be a comment.
                  ];

      % Remove all the blanks from the regex.
      mainregex = mainregex(~isspace(mainregex));

   end

   % Initialize output.
   ostr = istr;

   % If input is a character array, put it into a cell array.  We'll later make
   % sure output is a character array if input is a character array.
   if ischar(ostr)
      ostr = {ostr};
   end

   % Iterate over each element in the cell array.
   for i = 1 : numel(ostr)

      % Get the ith input string.
      str = ostr{i};

      % All character arrays must be row vectors.
      if (ndims(str) > 2) | (any(size(str) > 0) & (size(str, 1) ~= 1))
         error('All character arrays must be row vectors.');
      end

      % Note:  With MATLAB 6.5.1 it seems that the '^' and '$' anchors in the
      % regexes '(^|\n)' and '($|\n)' are not working (bug?), so use a
      % workaround:  prepend and append a newline and remove them later.

      use_workaround = 1;

      if use_workaround
         lf   = sprintf('\n');     % LF = Line feed character
         str = [lf, str, lf];      % prepend and append an LF
      end

      % Remove comment lines.
      str = regexprep(str, '(^|\n)[^\S\n]*%[^\n]*', '$1', 'tokenize');

      % Remove a comment on a line possibly containing MATLAB code.
      str = regexprep(str, mainregex, '$1', 'tokenize');

      % Remove trailing whitespace from each line.
      str = regexprep(str, '[^\S\n]+($|\n)', '$1', 'tokenize');

      % Compress multiple blank lines.
      %str = regexprep(str, '\n\n\n+', sprintf('\n\n'));

      if use_workaround
         str = str(2:end-1);       % remove leading and trailing LF
      end

      % Insert ith string into output cell array.
      ostr{i} = str;

   end

   % If the input was a character array, make sure output is so too.
   if ischar(istr)
      ostr = ostr{1};
   end


function answer = strstart (str1, str2)
    case_sensitive = true;
    answer = strstarti (str1, str2, case_sensitive);
end

%!test
%! myassert(strstart('haha', 'haha/private'));
%! myassert(~strstart('Haha', 'haha/private'));
%! myassert(~strstart('hahablah', 'haha/private2'));
%! myassert(~strstart('packed:rcond:complexNotSupported', ...
%!     'packed:chol:complexNotSupported'));
%! out = strstart('haha', {'haha/private', 'blah/private', ''});
%! myassert(out, [true, false, false])


function optionsFile = getEEGOptionsFile()
% This function will get the location of the EEGLAB options file.
%
% Output parameters:
%  optionsFile               The path to the file storing the
%                            EEGLAB options. An empty string will be
%                            returned if there is no options file found.

% Copyright (C) 2015  Kay Robbins with contributions from Nima
% Bigdely-Shamlo, Christian Kothe, Tim Mullen, Jeremy Cockfield,
% and Cassidy Matousek
%
% 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 2 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, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  US
optionsFile = '';
eeglab_options;
if ~isempty(EEGOPTION_PATH)
    homefolder = EEGOPTION_PATH;
elseif ispc
    if ~exist('evalc') %#ok<EXIST>
        eval('evalc = @(x)(eval(x));');
    end
    homefolder = deblank(evalc('!echo %USERPROFILE%'));
else
    homefolder = '~';
end
location = fullfile(homefolder, 'eeg_options.m');
if exist(location, 'file')
    optionsFile = location;
end
end % getEEGOptionsFile


function checkDir(path2outputs)

if ~exist(path2outputs, 'dir')
    mkdir(path2outputs);
end


function varargout = panel_raw_shortcuts(varargin)
% PANEL_RAW_SHORTCUTS: Edit keyboard shortcuts for the RAW Viewer.

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

eval(macro_method);
end

%% ===== CREATE PANEL =====
function [bstPanelNew, panelName] = CreatePanel() %#ok<DEFNU>
    % Java initializations
    import java.awt.*;
    import javax.swing.*;
    panelName = 'EditShortcuts';
    % Get current shortcuts
    RawViewerOptions = bst_get('RawViewerOptions');

    % Create main panel
    jPanelNew = gui_component('Panel');
    jPanelNew.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
    % PANEL: left panel (list of available categories)
    jPanelShort = gui_river([8,8], [0,10,15,10], 'Keyboard shortcuts');
    % Font size for the options
    TEXT_DIM = java_scaled('dimension', 50, 20);
    % Create 9 text boxes
    jText = javaArray('javax.swing.JTextField', 9);
    jRadioSimple = javaArray('javax.swing.JRadioButton', 9);
    jRadioExt = javaArray('javax.swing.JRadioButton', 9);
    jRadioPage = javaArray('javax.swing.JRadioButton', 9);
    jTextMin = javaArray('javax.swing.JTextField', 9);
    jTextMax = javaArray('javax.swing.JTextField', 9);
    jLabelSep = javaArray('javax.swing.JLabel', 9);
    jLabelUnits = javaArray('javax.swing.JLabel', 9);
    for i = 1:9
        % Event name
        gui_component('label', jPanelShort, 'br', sprintf('Shortcut %d: ', i));
        jText(i) = gui_component('text', jPanelShort, 'tab hfill', RawViewerOptions.Shortcuts{i,2}, {java_scaled('dimension', 120,22)});
        % Event type
        jRadioSimple(i) = gui_component('radio', jPanelShort, 'tab hfill', 'Simple', [], [], @UpdatePanel);
        jRadioPage(i) = gui_component('radio', jPanelShort, 'tab hfill', 'Full page', [], [], @UpdatePanel);
        jRadioExt(i) = gui_component('radio', jPanelShort, 'tab hfill', 'Extended', [], [], @UpdatePanel);
        jButtonGroup = ButtonGroup();
        jButtonGroup.add(jRadioSimple(i));
        jButtonGroup.add(jRadioPage(i));
        jButtonGroup.add(jRadioExt(i));
        switch (RawViewerOptions.Shortcuts{i,3})
            case 'simple',    jRadioSimple(i).setSelected(1);
            case 'page',      jRadioPage(i).setSelected(1);
            case 'extended',  jRadioExt(i).setSelected(1);
        end
        % Default epoch time
        if (length(RawViewerOptions.Shortcuts{i,4}) < 2)
            RawViewerOptions.Shortcuts{i,4} = [-0.1, 0.1];
        end
        % Epoch time
        jTextMin(i) = gui_component('texttime', jPanelShort, [], ' ', TEXT_DIM,[],[]);
        jLabelSep(i) = gui_component('label',    jPanelShort, [], '-');
        jTextMax(i) = gui_component('texttime', jPanelShort, [], ' ', TEXT_DIM,[],[]);
        jLabelUnits(i) = gui_component('label', jPanelShort, [], 'ms');
        gui_validate_text(jTextMin(i), [], jTextMax(i), {-100000, 100000, 100}, 'ms', 0, RawViewerOptions.Shortcuts{i,4}(1), []);
        gui_validate_text(jTextMax(i), jTextMin(i), [], {-100000, 100000, 100}, 'ms', 0, RawViewerOptions.Shortcuts{i,4}(2), []);
    end
    jPanelNew.add(jPanelShort, BorderLayout.CENTER);
    % Update selected options
    UpdatePanel();

    % PANEL: Selections buttons
    jPanelValidation = gui_river([10 0], [10 10 0 10]);
        % Cancel
        gui_component('button', jPanelValidation, 'br right', 'Cancel', [], [], @ButtonCancel_Callback);
        % Save
        gui_component('button', jPanelValidation, '', 'Save', [], [], @ButtonSave_Callback);
    jPanelNew.add(jPanelValidation, BorderLayout.SOUTH);

    % Create the BstPanel object that is returned by the function
    % => constructor BstPanel(jHandle, panelName, sControls)
    bstPanelNew = BstPanel(panelName, ...
                           jPanelNew, ...
                           struct('jText',        jText, ...
                                  'jRadioSimple', jRadioSimple, ...
                                  'jRadioPage',   jRadioPage, ...
                                  'jRadioExt',    jRadioExt, ...
                                  'jTextMin',     jTextMin, ...
                                  'jTextMax',     jTextMax));

%% =================================================================================
%  === CONTROLS CALLBACKS  =========================================================
%  =================================================================================
    %% ===== UPDATE PANEL =====
    function UpdatePanel(varargin)
        for k = 1:9
            isExt = jRadioExt(k).isSelected();
            jTextMin(k).setEnabled(isExt);
            jTextMax(k).setEnabled(isExt);
            jLabelSep(k).setEnabled(isExt);
            jLabelUnits(k).setEnabled(isExt);
        end
    end

    %% ===== VALIDATION BUTTONS =====
    function ButtonCancel_Callback(varargin)
        % Close panel without saving
        gui_hide(panelName);
    end
    function ButtonSave_Callback(varargin)
        % Save changes
        isOk = SaveShortcuts();
        if ~isOk
            return;
        end
        % Close panel
        gui_hide(panelName);
    end
end

%% =================================================================================
%  === INTERFACE CALLBACKS =========================================================
%  =================================================================================
%% ===== SAVE SHORTCUTS =====
function isOk = SaveShortcuts()
    isOk = 0;
    % Get current shortcuts
    RawViewerOptions = bst_get('RawViewerOptions');
    % Get panel controls handles
    ctrl = bst_get('PanelControls', 'EditShortcuts');
    % Get all the shortcuts
    for i = 1:9
        RawViewerOptions.Shortcuts{i,2} = strtrim(char(ctrl.jText(i).getText()));
        if ctrl.jRadioSimple(i).isSelected()
            RawViewerOptions.Shortcuts{i,3} = 'simple';
        elseif ctrl.jRadioPage(i).isSelected()
            RawViewerOptions.Shortcuts{i,3} = 'page';
        elseif ctrl.jRadioExt(i).isSelected()
            RawViewerOptions.Shortcuts{i,3} = 'extended';
            RawViewerOptions.Shortcuts{i,4} = [str2double(ctrl.jTextMin(i).getText()), str2double(ctrl.jTextMax(i).getText())] ./ 1000;
        end
    end
    % Reject shortcuts with same name and different types (simple/extended)
    evtNames = unique(lower(RawViewerOptions.Shortcuts(:,2)));
    if (length(evtNames) < 9)
        for i = 1:length(evtNames)
            iShortcut = find(strcmpi(RawViewerOptions.Shortcuts(:,2), evtNames{i}));
            if (length(iShortcut) > 1) && any(~strcmpi(RawViewerOptions.Shortcuts(iShortcut,3), RawViewerOptions.Shortcuts(iShortcut(1),3)))
                bst_error(['Event "' evtNames{i} '" cannot be linked to multiple shortcuts of different types.'], 'Save shortcuts', 0);
                return;
            end
        end
    end
    % Save shortcuts
    bst_set('RawViewerOptions', RawViewerOptions);
    % Return success
    isOk = 1;
end


% This is the timer function to update the figure.
% Save as timerCallbackFcn.m
function timerCallbackFcn(hTimer, eventData, hfig, I, map)
    figure(hfig);

    % i is the frame index
    persistent i;
    if isempty(i), i=1; end

    % display the i-th frame in the GIF
    imshow(I(:,:,i),map);

    % increment frame index i
    i=i+1;
    numframes=size(I,4);
    if (i>numframes), i=1; end
end


function F = tag(F,text)
% TAG
%
% Sets the tag on a constraint.

F = flatten(F);
if nargin == 1
    F = F.clauses{1}.handle;
else
for i = 1:length(F.clauses)
    if ~isequal(F.clauses{i}.handle,'placeholder')
        F.clauses{i}.handle = text;
    end
end
end


% Copy this template configuration file to your VOT workspace.
% Enter the full path to the ECO repository root folder.

CFWCR_repo_path = 'your CFWCR path'

tracker_label = 'CFWCR';
tracker_command = generate_matlab_command('CFWCR_VOT()', {[CFWCR_repo_path, 'vot2017_trax']});
tracker_interpreter = 'matlab';
tracker_trax = true;


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

%!test
%! % just check whether it runs:
%! mydatejd_inv(1);


function status = cbarSave(cbar, pth);
% Save a colorbar to a MATLAB file.
%
% status = cbarSave(cbar, [pth=dialog]);
%
% Returns a 1 if the save was successful and a 0 otherwise.
%
% ras, 02/24/07.
status = 0;

if notDefined('cbar'), error('Need a colorbar.'); end

if notDefined('pth') % dialog
	pth = mrvSelectFile('w', 'mat', [], 'Save a colorbar...');
end

save(pth, '-struct', 'cbar');

if exist(pth, 'file')
	status = 1;
end

return


addpath(genpath(pwd))
x = input('Would you like to save the path for the next session of MATLAB? (y/(n))','s');
if (isempty(x))
    x = 'n';
end

if x=='y' || x=='Y'
    savepath
    disp('Path saved.')
else
    disp('Path added, but not saved.  It will only be used for this session of MATLAB.')
end


function [grRules_new,genes,rxnGeneMat] = translateGrRules(grRules,targetFormat,origFormat,noMatch)
%translateGrRules  Translate grRules to other other gene ID types.
%
% translateGrRules converts grRules to a chosen target gene ID type(s).
% The original and target gene type(s) must be one of the following:
%
%       'ENSG'     Ensembl gene ID
%       'ENST'     Ensembl transcript ID
%       'ENSP'     Ensembl protein ID
%       'UniProt'  UniProt protein ID
%       'Symbol'   HUGO gene abbreviation
%       'Entrez'   Entrez (NCBI) gene ID
%
% The function will try to determine the original gene ID format, but this
% can be manually specified with the "origFormat" input. Furthermore, the
% user can supply a custom conversion key in the "targetFormat" input that
% uses gene IDs other than the above built-in ID types (see details below).
%
% NOTE: All trailing ".#" after Entrez or Ensembl ID (e.g., ENSG0000123.1)
%       will be REMOVED. The grRules may therefore change; e.g.:
%           '123.1 or 123.2 or 4365.1' --> '123 or 4365'
%
% NOTE: The function also "cleans" the grRules, meaning duplicate genes,
%       extra parentheses, etc. will be removed from each grRule. See
%       "cleanModelGeneRules.m" for more details.
%
%
% USAGE:
%
%   [grRules_new,genes,rxnGeneMat] = translateGrRules(grRules,targetFormat,origFormat,noMatch);
%
%
% INPUTS:
%
%   grRules     A cell vector of gene-reaction rules (e.g., model.grRules).
%
%   targetFormat    The desired output format of the grRules. This can be
%                   one or multiple gene ID types, and must be selected
%                   from the following: 'ENSG', 'ENSP', 'ENST', 'UniProt',
%                   'Symbol', 'Entrez'.
%                   DEFAULT: 'Symbol'.
%
%               *** NOTE: As a special case, instead of entering a target
%                   format or list of formats, this input can be replaced
%                   with a custom conversion key. This conversion key must
%                   be an Nx2 cell array, where the first column contains
%                   gene IDs corresponding to the current grRules, and the
%                   second column contains new gene IDs to which the rules
%                   will be translated.
%
%   origFormat  (Optional) A string specifying the original gene ID type
%               (e.g., 'UniProt'). If not provided, the function will try
%               to automatically determine the type of IDs present.
%
%   noMatch     What to do in case a gene in the original grRules does not
%               have a corresponding match in the new gene IDs to which the
%               grRules are to be translated. Choose from the following:
%
%               'delete'    (DEFAULT) Delete (exclude) the gene from the
%                           new rule.
%
%               'original'  keep the original gene ID. Note, this will
%                           result in mixed gene ID types in grRules and
%                           the corresponding list of genes, which may
%                           cause problems in other applications.
%
%
% OUTPUTS:
%
%   grRules_new  grRules with the gene IDs converted to the target format.
%                If targetFormat is more than one ID type, then grRules
%                will be returned as a structure, with a different field
%                for each gene ID type.
%
%   genes        A list of all genes found in the converted grRules.
%                If targetFormat is more than one ID type, then genes will
%                be returned as a structure, with a different field for
%                each gene ID type.
%
%   rxnGeneMat   A matrix associating reactions to genes, build from the
%                converted grRules and genes list. If targetFormat is more
%                than one ID type, then rxnGeneMat will be returned as a
%                structure, with a different field for each gene ID type.
%

% handle input arguments
if nargin < 4
    noMatch = 'delete';
elseif ~ismember(lower(noMatch),{'original','delete'})
    error('Valid inputs for noMatch are "original" or "delete".');
end

if nargin < 3
    gene_type_orig = {};
else
    gene_type_orig = origFormat;
end

custom_key = false;
if nargin < 2 || isempty(targetFormat)
    targetFormat = 'Symbol';
elseif ischar(targetFormat)
    % convert target format from string to cell
    targetFormat = {targetFormat};
elseif (size(targetFormat,2) == 2) && (size(targetFormat,1) > 10)  % check that it has some arbitrarly long length above 10
    % use custom conversion key
    custom_key = true;
    conv_key = targetFormat;
    targetFormat = {'NewFormat'};
    conv_key_head = {'OldFormat','NewFormat'};
    gene_type_orig = 'OldFormat';
else
    % ensure it is a column vector
    targetFormat = targetFormat(:);
end

% allow for non-exact matches to "Symbol" option
targetFormat(ismember(lower(targetFormat),{'name','names','symbol','symbols'})) = {'Symbol'};
if ismember(lower(gene_type_orig), {'name','names','symbol','symbols'})
    gene_type_orig = 'Symbol';
end

% get original list of genes from the grRules
genes_orig = getGenesFromGrRules(grRules);
if ismember('and',genes_orig) || ismember('or',genes_orig)
    error('Problem reading grRules. Verify that all "and" and "or" elements are lowercase and surrounded by spaces.');
end

% preprocess gene list and gene-reaction rules, if necessary
if any(ismember({'GPI','GAPDH'},genes_orig))  % need a more robust method to check if it's gene symbols
    % check if the list is gene symbols, if so, do not modify
    rules_orig = grRules;
    if ~custom_key && isempty(gene_type_orig)
        gene_type_orig = 'Symbol';
    end
else
    % remove ".#" from gene IDs (e.g. ENSG00000198888.2 -> ENSG00000198888, or 2597.1 -> 2597)
    genes_orig = regexprep(genes_orig,'\.\d+$','');
    rules_orig = regexprep(grRules,'\.\d+','');
end

% determine the original gene ID type, if not gene symbols
if isempty(gene_type_orig)
    if startsWith(genes_orig{1},{'ENSG','ENST','ENSP'})
        % ensembl ID type
        gene_type_orig = genes_orig{1}(1:4);
    elseif all(ismember(cellfun(@length,genes_orig),[6,10])) && all(cellfun(@(x) ~isempty(regexp(x,'^[A-Z]\d\w\w\w\d','once')),genes_orig))
        % Uniprot IDs are 6 or 10 characters, with format [A-Z][0-9][A-Z,0-9][A-Z,0-9][A-Z,0-9][0-9]...
        gene_type_orig = 'UniProt';
    elseif ~any(isnan(str2double(genes_orig)))
        % Entrez IDs are only digits
        gene_type_orig = 'Entrez';
    else
        error('Unable to recognize the type of gene IDs in the model.');
    end
end

% remove duplicate genes (if any)
genes_orig = unique(genes_orig,'stable');

if ~custom_key
    % import ID conversion key from the model "genes.tsv" annotation file

    % get the path
    [ST, I] = dbstack('-completenames');
    path = fileparts(ST(I).file);
    tmpfile = fullfile(path,'..','..','model','genes.tsv');

    % import as structure, convert to table, and extract header
    tmp = struct2table(importTsvFile(tmpfile));
    conv_key = table2array(tmp);
    conv_key_head = tmp.Properties.VariableNames;
    clear tmp

    % change header names to match contents of GENE_TYPES
    [hasMatch,ind] = ismember(conv_key_head,{'genes','geneENSTID',...
        'geneENSPID','geneUniProtID','geneSymbols','geneEntrezID'});
    type_abbrevs = {'ENSG';'ENST';'ENSP';'UniProt';'Symbol';'Entrez'};
    conv_key_head = type_abbrevs(ind(hasMatch));
end

% begin by "cleaning" the original grRules
rules_orig = cleanGrRules(rules_orig);

% convert rules to all other gene ID types
for i = 1:length(targetFormat)

    % extract portion of conversion key required; resulting variable will
    % be two columns of IDs, where column 1 is the original gene ID type,
    % and column 2 is the new gene ID type.
    [~,ind] = ismember([{gene_type_orig}, targetFormat(i)], conv_key_head);
    conv_key_sub = conv_key(:,ind);

    % remove rows with empty key entries or unneeded genes
    conv_key_sub(any(cellfun(@isempty,conv_key_sub),2),:) = [];
    conv_key_sub(~ismember(conv_key_sub(:,1),genes_orig),:) = [];

    % expand entries with multiple IDs (separated by semicolons) into
    % multiple rows with one ID per entry
    nested_key = cellfun(@(x) strip(strsplit(x, ';'))', conv_key_sub, 'UniformOutput', false);
    dup_col2 = arrayfun(@(i) repmat(nested_key(i,2), numel(nested_key{i,1}), 1), [1:size(nested_key,1)]', 'UniformOutput', false);
    semi_nested_key = [vertcat(nested_key{:,1}), vertcat(dup_col2{:})];
    dup_col1 = arrayfun(@(i) repmat(semi_nested_key(i,1), numel(semi_nested_key{i,2}), 1), [1:size(semi_nested_key,1)]', 'UniformOutput', false);
    conv_key_sub = [vertcat(dup_col1{:}), vertcat(semi_nested_key{:,2})];

    % only keep unique rows of conversion key
    [~,tmp] = ismember(conv_key_sub,unique(conv_key_sub));
    [~,ind] = unique(tmp,'rows');
    conv_key_sub = conv_key_sub(ind,:);

    if strcmpi(noMatch,'orig')
        % Identify genes that do not exist in the conversion key. For these
        % genes, add additional rows to the conversion key such that if an
        % original gene ID has no corresponding new gene ID, the original
        % gene ID will be used instead.
        unmatched = genes_orig(~ismember(genes_orig,conv_key_sub(:,1)));
        conv_key_sub = [conv_key_sub;repmat(unmatched,1,2)];
    end

    % define inline function to convert between gene IDs
    convertGene = @(g) strjoin(conv_key_sub(ismember(conv_key_sub(:,1),g),2), ' | ');

    % convert "and" to "&" and "or" to "|" (easier to work with)
    rules_new = rules_orig;
    rules_new = regexprep(rules_new, ' or ', ' | ');
    rules_new = regexprep(rules_new, ' and ', ' & ');

    % check if the target format is the original format
    if strcmp(targetFormat{i},gene_type_orig)
        % if current model rules are already in the target format, do not
        % convert gene IDs
    else
        % convert gene IDs
        % This next line identifies gene IDs as collections of characters that
        % are not spaces, parentheses, or the symbols & or |. It then replaces
        % those gene IDs with the new gene ID type, which calls the convertGene
        % inline function to retrieve.
        rules_new = regexprep(rules_new, '[^&|\(\) ]+', '(${convertGene($0)})');
    end

    % clean up rules (removes extra parentheses, repeated genes, etc.)
    rules_new = cleanGrRules(rules_new);

    % generate new rxnGeneMat and gene list based on converted grRules
    [genes.(targetFormat{i}),rxnGeneMat.(targetFormat{i})] = getGenesFromGrRules(rules_new);

    % restore "&" as "and" and "|" as "or"
    rules_new = regexprep(rules_new, ' \| ', ' or ');
    rules_new = regexprep(rules_new, ' & ', ' and ');

    % add new rules to model structure
    grRules_new.(targetFormat{i}) = rules_new;

end

% if only one target format is specified, structures are not necessary
if length(targetFormat) == 1
    grRules_new = grRules_new.(targetFormat{1});
    if ~isempty(genes)
        genes = genes.(targetFormat{1});
        rxnGeneMat = rxnGeneMat.(targetFormat{1});
    end
end


function lineArray = read_mixed_csv(fileName,delimiter)
  fid = fopen(fileName,'r');   %# Open the file
  lineArray = cell(100,1);     %# Preallocate a cell array (ideally slightly
                               %#   larger than is needed)
  lineIndex = 1;               %# Index of cell to place the next line in
  nextLine = fgetl(fid);       %# Read the first line from the file
  while ~isequal(nextLine,-1)         %# Loop while not at the end of the file
    lineArray{lineIndex} = nextLine;  %# Add the line to the cell array
    lineIndex = lineIndex+1;          %# Increment the line index
    nextLine = fgetl(fid);            %# Read the next line from the file
  end
  fclose(fid);                 %# Close the file
  lineArray = lineArray(1:lineIndex-1);  %# Remove empty cells, if needed
  for iLine = 1:lineIndex-1              %# Loop over lines
    lineData = textscan(lineArray{iLine},'%s',...  %# Read strings
                        'Delimiter',delimiter);
    lineData = lineData{1};              %# Remove cell encapsulation
    if strcmp(lineArray{iLine}(end),delimiter)  %# Account for when the line
      lineData{end+1} = '';                     %#   ends with a delimiter
    end
    lineArray(iLine,1:numel(lineData)) = lineData;  %# Overwrite line data
  end
end


classdef dbPitts < dbBase

    methods

        function db= dbPitts(fullSize, whichSet)
            % fullSize is: true or false
            % whichSet is one of: train, val, test

            assert( ismember(whichSet, {'train', 'val', 'test'}) );

            if fullSize
                sizeSuffix= '250k';
            else
                sizeSuffix= '30k';
            end

            db.name= sprintf('pitts%s_%s', sizeSuffix, whichSet);

            paths= localPaths();
            dbRoot= paths.dsetRootPitts;
            db.dbPath= [dbRoot, 'images/'];
            db.qPath= [dbRoot, 'queries/'];

            db.dbLoad();
        end

    end

end


function [solvers,keep,allsolvers] = getavailablesolvers(findallsolvers,options);

solvers = definesolvers;allsolvers = solvers;
keep = ones(length(solvers),1);

if ~findallsolvers
    for i = 1:length(solvers)
        isavailable = 1;
        j = 1;

        while (j <= length(solvers(i).checkfor)) && isavailable
            s = exist(solvers(i).checkfor{j},'file');
            s = (s~=0) & (s~=7);
            isavailable = isavailable & s;
            j = j + 1;
        end
        if ~isavailable
            keep(i)=0;
        end
    end
end

if nargout == 1 || nargout==3
    solvers = solvers(find(keep));
end


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

%%
clear; close all; clc;

%% Syntax
% |D=import_FBG(loadName);|

%% 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 cd2EditedFile()
% cd2EditedFile: goes to the the file opened in editor
%
% references at:
% <<http://blogs.mathworks.com/community/2011/05/16/matlab-editor-api-examples/>>

% Copyright 2012, Clemens Ager
%%
a = fileparts(matlab.desktop.editor.getActiveFilename);
cd(a);


function disp( x, prefix ) %#ok
if nargin < 2, prefix = ''; end
disp( [ prefix, 'cvx base object' ] );

% Copyright 2010 Michael C. Grant and Stephen P. Boyd.
% See the file COPYING.txt for full copyright information.
% The command 'cvx_where' will show where this file is located.


function filename = utl_whichfile(identifier)
% Find the .m file which defines the given function identifier.
% Filename = utl_whichfile(Identifier)
%
% This is a special-purpose alternative to the builtin 'which', for use in deployed situations.
%
% In these cases, 'which' returns the filename of only an encrypted version of the defining
% function, so it cannot be used to access the m code. This function assumes that the source code
% for each function ships with the release, and returns the file name for a given identifier.
%
% In:
%   Identifier : identifier of some function
%
% Out:
%   Filename : .m file that contains the code which implements the
%              identified function
%
% Notes:
%   This function does not have all the facilities of which(), and assumes that there is one unique
%   source file for every looked up identifier.
%
%   If the global cell string tracking.paths.toolboxes exists, its contents will be used as root
%   directories; otherwise, env_translatepath('functions:/') will be used.
%
% See also:
%   which
%
%                                Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
%                                2010-04-04

persistent filenames; % table of m file names, indexed by identifier

try
    % look up the record for this file name
    filename = filenames.(identifier);
catch %#ok<CTCH>
    if isempty(filenames)
        % file table is empty (first-time run): build it recursively from root directories
        global tracking; %#ok<TLEV>
        if isfield(tracking,'paths') && isfield(tracking.paths,'toolboxes')
            root_dirs = tracking.paths.toolboxes;
        else
            root_dirs = {env_translatepath('functions:/')};
        end
        for d=1:length(root_dirs)
            populate_records(root_dirs{d}); end
    else
        error('No file was found that corresponds to the identifier %s. Make sure it is in the searched directories.',hlp_tostring(identifier));
    end
    try
        filename = filenames.(identifier);
    catch %#ok<CTCH>
        error('No file was found that corresponds to the identifier %s. Make sure it is in the searched directories.',hlp_tostring(identifier));
    end
end

    % recursively populate file table from an initial directory.
    function populate_records(path)
        if path(end) == filesep
            path(end) = []; end
        for info = dir(path)'
            if info.isdir
                % found a directory: recurse
                if ~any(strcmp(info.name,{'.','..'}))
                    populate_records([path filesep info.name]); end
            else
                % found a file? add it to the table if an .m file
                if length(info.name) > 2 && strcmp(info.name(end-1:end),'.m')
                    try
                        filenames.(info.name(1:end-2)) = [path filesep info.name];
                    catch
                        disp_once('utl_whichfile: found .m file that is not a function name: %s (ignoring)',[path filesep info.name]);
                    end
                end
            end
        end
    end

end


classdef MimShowMarkers < MimGuiPlugin
    % MimShowMarkers. Gui Plugin for entering marker edit mode
    %
    %     You should not use this class within your own code. It is intended to
    %     be used by the gui of the TD MIM Toolkit.
    %
    %     MimEnterMarkerMode is a Gui Plugin for showing or hiding markers
    %
    %
    %     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
        ButtonText = 'Show Markers'
        SelectedText = 'Hide Markers'
        ToolTip = 'Enters marker edit mode'
        Category = 'Marker display'
        Visibility = 'Dataset'
        Mode = 'Markers'

        HidePluginInDisplay = false
        PTKVersion = '1'
        ButtonWidth = 6
        ButtonHeight = 1
        Location = 1
        Icon = 'markers.png'
    end

    methods (Static)
        function RunGuiPlugin(gui_app)
            gui_app.ImagePanel.ShowMarkers = ~gui_app.ImagePanel.ShowMarkers;
        end

        function enabled = IsEnabled(gui_app)
            enabled = gui_app.IsDatasetLoaded;
        end

        function is_selected = IsSelected(gui_app)
            is_selected = gui_app.ImagePanel.ShowMarkers;
        end
    end
end


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

    properties
        src AbstractLaunchVehicleElectricalPowerSrcSnk

        srcStateToSet(1,1) logical = true;

        inheritSrcState(1,1) logical = true;
        inheritSrcStateFrom(1,1) InheritStateEnum = InheritStateEnum.InheritFromLastState;
        inheritSrcStateFromEvent LaunchVehicleEvent = LaunchVehicleEvent.empty(1,0);
    end

    methods
        function obj = SetKinematicStateEPSrcState(src)
            obj.src = src;
        end

        function updateStateLogEntry(obj, newStateLogEntry, stateLog)
            srcState = obj.getSrcState(newStateLogEntry);

            if(obj.inheritSrcState)
                if(obj.inheritSrcStateFrom == InheritStateEnum.InheritFromSpecifiedEvent && ...
                   not(isempty(obj.inheritSrcStateFromEvent)) && ...
                   not(isempty(obj.inheritSrcStateFromEvent.getEventNum())) && ...
                   obj.inheritSrcStateFromEvent.getEventNum() > 0)

                    evtStateLog = stateLog.getLastStateLogForEvent(obj.inheritSrcStateFromEvent);
                    if(not(isempty(evtStateLog)))
                        evtSrcState = obj.getSrcState(evtStateLog);
                        srcState.setActiveState(evtSrcState.getActiveState());
                    end
                end
            else
                srcState.setActiveState(obj.srcStateToSet);
            end
        end

        function listboxStr = getListboxStr(obj)
            listboxStr = {};
            for(i=1:length(obj))
                listboxStr{i} = obj(i).src.getName(); %#ok<AGROW>
            end
        end
    end

    methods(Access=private)
        function srcState = getSrcState(obj, stateLogEntry)
            srcStates = stateLogEntry.getAllPwrSrcsStates();
            srcState = srcStates(getEpsSrcComponent(srcStates) == obj.src);
        end
    end
end


function timeSliderStateChanged(src,evt, lvdData, handles, app)
    s = dbstack;
    matches = strfind({s.name},'timeSliderStateChanged');
    matches = cell2mat(matches(2:end));
    tf = any(matches == 1);

    if(not(tf))
        try
            time = evt.Value;
        catch
            time = src.Value;
        end
        hAx = handles.dispAxes;

        markerTrajData = lvdData.viewSettings.selViewProfile.markerTrajData;
        markerBodyData = lvdData.viewSettings.selViewProfile.markerBodyData;
        markerBodyAxesData = lvdData.viewSettings.selViewProfile.markerTrajAxesData;
        markerGrdObjData = lvdData.viewSettings.selViewProfile.markerGrdObjData;
        centralBodyData = lvdData.viewSettings.selViewProfile.centralBodyData;
        pointData = lvdData.viewSettings.selViewProfile.pointData;
        vectorData = lvdData.viewSettings.selViewProfile.vectorData;
        refFrameData = lvdData.viewSettings.selViewProfile.refFrameData;
        angleData = lvdData.viewSettings.selViewProfile.angleData;
        planeData = lvdData.viewSettings.selViewProfile.planeData;
        sensorData = lvdData.viewSettings.selViewProfile.sensorData;
        sensorTgtData = lvdData.viewSettings.selViewProfile.sensorTgtData;

        notify(app, 'GenericStatusLabelUpdate', GenericStatusLabelUpdate('Drawing Scene...'));

%         notify(app, 'GenericStatusLabelUpdate', GenericStatusLabelUpdate('Drawing Vehicle Trajectory...'));
        markerTrajData.plotBodyMarkerAtTime(time, hAx);

%         notify(app, 'GenericStatusLabelUpdate', GenericStatusLabelUpdate('Drawing Celestial Bodies...'));
        for(i=1:length(markerBodyData)) %#ok<*NO4LP>
            markerBodyData(i).plotBodyMarkerAtTime(time, hAx);
        end

%         notify(app, 'GenericStatusLabelUpdate', GenericStatusLabelUpdate('Drawing Vehicle Body Axes...'));
        markerBodyAxesData.plotBodyAxesAtTime(time, hAx);

%         notify(app, 'GenericStatusLabelUpdate', GenericStatusLabelUpdate('Drawing Ground Objects...'));
        for(i=1:length(markerGrdObjData))
            markerGrdObjData(i).plotBodyMarkerAtTime(time, hAx);
        end

%         notify(app, 'GenericStatusLabelUpdate', GenericStatusLabelUpdate('Drawing Geometric Reference Frames...'));
        for(i=1:length(refFrameData))
            refFrameData(i).plotRefFrameAtTime(time, hAx);
        end

%         notify(app, 'GenericStatusLabelUpdate', GenericStatusLabelUpdate('Drawing Geometric Vectors...'));
        for(i=1:length(vectorData))
            vectorData(i).plotVectorAtTime(time, hAx);
        end

%         notify(app, 'GenericStatusLabelUpdate', GenericStatusLabelUpdate('Drawing Geometric Angles...'));
        for(i=1:length(angleData))
            angleData(i).plotAngleAtTime(time, hAx);
        end

%         notify(app, 'GenericStatusLabelUpdate', GenericStatusLabelUpdate('Drawing Geometric Planes...'));
        for(i=1:length(planeData))
            planeData(i).plotPlaneAtTime(time, hAx);
        end

%         notify(app, 'GenericStatusLabelUpdate', GenericStatusLabelUpdate('Drawing Geometric Points...'));
        for(i=1:length(pointData))
            pointData(i).plotPointAtTime(time, hAx);
        end

%         notify(app, 'GenericStatusLabelUpdate', GenericStatusLabelUpdate('Drawing Sensors...'));
        sensorTgtResults = SensorTargetResults.empty(1,0);
        for(i=1:length(sensorData))
            subResults = sensorData(i).plotSensorAtTime(time, hAx);
            sensorTgtResults = horzcat(sensorTgtResults, subResults(:)'); %#ok<AGROW>
        end

        if(numel(sensorTgtResults) > 0)
%             notify(app, 'GenericStatusLabelUpdate', GenericStatusLabelUpdate('Drawing Sensor Targets...'));

            mergedResults = SensorTargetResults.mergeResults(sensorTgtResults);
            for(i=1:length(sensorTgtData))
                sensorTgtData(i).plotTargetResults(mergedResults, hAx);
            end
        end

        centralBodyData.setCentralBodyRotation(time);

%         notify(app, 'GenericStatusLabelUpdate', GenericStatusLabelUpdate('Creating Light Source...'));
        lvdData.viewSettings.selViewProfile.updateLightPosition(time);

        [year, day, hour, minute, sec] = convertSec2YearDayHrMnSec(time);
        epochStr = formDateStr(year, day, hour, minute, sec);

        [~, timeEvtsListboxStrs] = lvdData.script.getAllEvtsThatOccurAtTime(time);
        for(i=1:length(timeEvtsListboxStrs))
            timeEvtsListboxStrs(i) = sprintf('Event: %s',timeEvtsListboxStrs(i));
        end
        evtsStr = strjoin(timeEvtsListboxStrs,'\n');

        if(not(isempty(timeEvtsListboxStrs)))
            dashes = repmat('-',1,max(strlength(timeEvtsListboxStrs)));
        else
            dashes = '';
        end

        tooltipStr = sprintf('UT = %0.3f sec\n%s\n%s', time, dashes, evtsStr);

        handles.timeSliderValueLabel.String = epochStr;
        handles.timeSliderValueLabel.TooltipString = tooltipStr;

        setappdata(app.DispAxesTimeSlider,'lastTime',time);
        drawnow limitrate;
    end
end


tracker_label = 'Demo_py';

% Note: be carefull for double backslashes on Windows
tracker_command = generate_python_command('python_static_rgbd', ...
    {'<path-to-toolkit-dir>\\tracker\\examples\\python', ...  % tracker source and vot.py are here
    '<path-to-trax-dir>\\support\\python'});

tracker_interpreter = 'python';

tracker_linkpath = {'<path-to-trax-build-dir>\bin', ...
    '<path-to-trax-build-dir>\lib'};


%UMINUS Mapping overload