% - This function is part of ERPLAB Toolbox -

function varargout = linespecGUI(varargin)

gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
      'gui_Singleton',  gui_Singleton, ...
      'gui_OpeningFcn', @linespecGUI_OpeningFcn, ...
      'gui_OutputFcn',  @linespecGUI_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

% --------------------------------------------------------------------------------------------
function linespecGUI_OpeningFcn(hObject, eventdata, handles, varargin)
% handles.output = [];
handles.fulltext =[];
handles.output   =[];

try
      def = varargin{1};
catch
      def = [];
end
try
        nbin = varargin{2};
catch
        nbin = 1;
end
try
        lwidth = varargin{3};
catch
        lwidth = 1;
end

defs       = {'-' '-.' '--' ':'};% sorted according 1st erplab's version
defcol     = getcolorcellerps; %{'k' 'r' 'b' 'g' 'c' 'm' 'y' 'w' };

if isempty(def)
        %       defcolor = repmat({'k' 'r' 'b' 'g' 'c' 'm' 'y' },1, nbin);% sorted according 1st erplab's version
        %       defs     = {'-' '-.' '--' ':'};% sorted according 1st erplab's version
        %       d = repmat(defs',1,length(defcolor));
        %       defstyle = reshape(d',1,length(defcolor)*length(defs));

        defcolor  = repmat(defcol,1, 1*length(defs));% sorted according 1st erplab's version
        d = repmat(defs',1, 1*length(defcol));
        defstyle = reshape(d',1, numel(d));
else
        defcolor = regexp(def,'\w*','match');
        defcolor = [defcolor{:}];
        defstyle = regexp(def,'\W*','match');
        defstyle = [defstyle{:}];
        if isempty(defcolor)
                defcolor  = repmat(defcol,1, ERP.nbin*length(defs));% sorted according 1st erplab's version
                d = repmat(defs',1, ERP.nbin*length(defcol));
                defstyle = reshape(d',1, numel(d));
        end
        if isempty(defstyle)
                d = repmat(defs',1, ERP.nbin*length(defcol));
                defstyle = reshape(d',1, numel(d));
        end
end

COLORDATA  = colores(defcolor);
STYLEDATA  = estilos(defstyle);
set(handles.popupmenu_lwidth,'String', {1:20})
set(handles.popupmenu_lwidth,'Value', lwidth)

handles.defcolor  = defcolor;
handles.defstyle  = defstyle;
handles.COLORDATA = COLORDATA;
handles.STYLEDATA = STYLEDATA;
handles.nbin = nbin;

setlistbox_color(hObject, handles, COLORDATA, nbin )
setlistbox_style(hObject, handles, STYLEDATA, nbin )

for k=1:length(defcol)
      switch defcol{k}
            case 'k'
                  cwrd = 'BLACK';
            case 'r'
                  cwrd = 'RED';
            case 'b'
                  cwrd = 'BLUE';
            case 'g'
                  cwrd = 'GREEN';
            case 'c'
                  cwrd = 'CYAN';
            case 'm'
                  cwrd = 'MAGENTA';
            case 'y'
                  cwrd = 'YELLOW';
            case 'w'
                  cwrd = 'WHITE';
            otherwise
                  error('color error...')
      end
        set(handles.(['pushbutton_color' num2str(k)]),'UserData', cwrd)
        setcolorbuttons(k, cwrd, hObject, eventdata, handles);
end

% defs       = {'-' '-.' '--' ':'};
% solid   dash-dot   dashed   dotted
for k=1:length(defs)
        switch defs{k}
                case '-'
                        lwrd = 'solid';
                case '-.'
                        lwrd = 'dash-dot';
                case '--'
                        lwrd = 'dashed';
                case ':'
                        lwrd = 'dotted';
                otherwise
                        error('line error...')
        end
        set(handles.(['pushbutton_line' num2str(k)]),'String', defs{k})
        set(handles.(['pushbutton_line' num2str(k)]),'UserData', lwrd)
        %setlinebuttons(k, lwrd, hObject, eventdata, handles);
end

%
% Name & version
%
version = geterplabversion;
set(handles.gui_chassis,'Name', ['ERPLAB ' version '   -   Line specifications GUI'],'WindowStyle','modal')

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

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

% Update handles structure
guidata(hObject, handles);

% help
% helpbutton

drawnow
uiwait(handles.gui_chassis);

% --------------------------------------------------------------------------------------------
function varargout = linespecGUI_OutputFcn(hObject, eventdata, handles)
varargout{1} = handles.output;

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

% --------------------------------------------------------------------------------------------
function setcolorbuttons(ind, colorword, hObject, eventdata, handles)
try
      [img,map]    = imread(['erplab_' colorword '.jpg']);
      colormap(map)
      [row,column] = size(img);
      p = get(handles.(['pushbutton_color' num2str(ind)]),'Position');
      w = p(3); % width
      h = p(4); % hight
      steprow   = ceil(row/(5*h));
      stecolu   = ceil(column/(10*w));
      imgbutton = img(1:steprow:end,1:stecolu:end,:);
      set(handles.(['pushbutton_color' num2str(ind)]),'String','')
      set(handles.(['pushbutton_color' num2str(ind)]),'CData',imgbutton);
      set(handles.(['pushbutton_color' num2str(ind)]),'Position', [p(1) p(2) p(3)*1.25 p(4)*1.25]);
catch
      %set(handles.pushbutton_help,'String','Help');
      set(handles.(['pushbutton_color' num2str(ind)]),'String', lower(colorword(1:2)));
end

% % --------------------------------------------------------------------------------------------
% function setlinebuttons(ind, lineword, hObject, eventdata, handles)
% try
%       [img,map]    = imread(['erplab_' colorword '.jpg']);
%       colormap(map)
%       [row,column] = size(img);
%       p = get(handles.(['pushbutton_color' num2str(ind)]),'Position');
%       w = p(3); % width
%       h = p(4); % hight
%       steprow   = ceil(row/(5*h));
%       stecolu   = ceil(column/(10*w));
%       imgbutton = img(1:steprow:end,1:stecolu:end,:);
%       set(handles.(['pushbutton_color' num2str(ind)]),'String','')
%       set(handles.(['pushbutton_color' num2str(ind)]),'CData',imgbutton);
%       set(handles.(['pushbutton_color' num2str(ind)]),'Position', [p(1) p(2) p(3)*1.25 p(4)*1.25]);
% catch
%       %set(handles.pushbutton_help,'String','Help');
%       set(handles.(['pushbutton_color' num2str(ind)]),'String', lower(colorword(1:2)));
% end

% --------------------------------------------------------------------------------------------
function COLORDATA  = colores(defcolor)
% COLORDATA = struct(1);
for i=1:length(defcolor);
      %COLORDATA(i).colorname    = defcolor{i};
      COLORDATA(i).colorchar    = defcolor{i};

      switch defcolor{i}
            case 'k'
                  COLORDATA(i).colorname    = 'black';
                  COLORDATA(i).colorhtmlcode = '#000000';
            case 'r'
                  COLORDATA(i).colorname     = 'red';
                  COLORDATA(i).colorhtmlcode = '#FF0000';
            case 'b'
                  COLORDATA(i).colorname    = 'blue';
                  COLORDATA(i).colorhtmlcode = '#0000FF';
            case 'g'
                  COLORDATA(i).colorname    = 'green';
                  COLORDATA(i).colorhtmlcode = '#009000';
            case 'c'
                  COLORDATA(i).colorname    = 'cyan';
                  COLORDATA(i).colorhtmlcode = '#00FFFF';
            case 'm'
                  COLORDATA(i).colorname    = 'magenta';
                  COLORDATA(i).colorhtmlcode = '#FF00FF';
            case 'y'
                  COLORDATA(i).colorname    = 'yellow';
                  %COLORDATA(i).colorhtmlcode = '#FFFF00';     %
                  COLORDATA(i).colorhtmlcode = '#FFD700';     % or gold #FDD017
            case 'w'
                  COLORDATA(i).colorname    = 'white';
                  COLORDATA(i).colorhtmlcode = '#F1F1F1';     % winter white?
            otherwise
                  COLORDATA(i).colorname    = 'black';
                  COLORDATA(i).colorhtmlcode = '#000000';
      end
end
% --------------------------------------------------------------------------------------------
function STYLEDATA  = estilos(defstyle)
% STYLEDATA = struct(1);
for i=1:length(defstyle);
      %STYLEDATA(i).colorname    = defcolor{i};
      %STYLEDATA(i).colorchar    = defcolor{i};
      switch defstyle{i}
            case {'-',''}
                  STYLEDATA(i).line     = 'solid';
                  STYLEDATA(i).style    = '-';
            case '-.'
                  STYLEDATA(i).line     = 'dash-dot';
                  STYLEDATA(i).style    = '-.';
            case '--'
                  STYLEDATA(i).line    = 'dashed';
                  STYLEDATA(i).style    = '--';
            case ':'
                  STYLEDATA(i).line    = 'dotted';
                  STYLEDATA(i).style    = ':';
            otherwise
                  STYLEDATA(i).line     = 'dot';
                  STYLEDATA(i).style    = '-';
      end
end

% --------------------------------------------------------------------------------------------
function setlistbox_color(hObject, handles, COLORDATA, nbin )
strhtml = cell(1);
maxdig  = length(num2str(length(COLORDATA)))+1;
for i=1:length(COLORDATA)
      % strhtml{i} = sprintf('%s', colorhtmlcode{i}, upper(colorhtmlbase{i}));
      numstr = num2str(i);
      if i<=nbin
            item = ['L' repmat('0',1,maxdig-length(numstr))  numstr ':'];
      else
            item = ['empty..:'];
            %item = [item(1:maxdig+1) ':']
      end
      strhtml{i} = sprintf('%s%s', item,...
            COLORDATA(i).colorhtmlcode, upper(COLORDATA(i).colorname));
end
set( handles.listbox_color, 'String', strhtml)

%handles.COLORDATA = COLORDATA;
% Update handles structure
guidata(hObject, handles);

% --------------------------------------------------------------------------------------------
function setlistbox_style(hObject, handles, STYLEDATA, nbin )
strhtml = cell(1);
maxdig  = length(num2str(length(STYLEDATA)))+1;
for i=1:length(STYLEDATA)
      % strhtml{i} = sprintf('%s', colorhtmlcode{i}, upper(colorhtmlbase{i}));
      numstr = num2str(i);
      if i<=nbin
             item = ['L' repmat('0',1,maxdig-length(numstr))  numstr ':'];
      else
            item = 'empty..:';
            %item = [item(1:maxdig+1) ':'];
      end
      %strhtml{i} = sprintf('%s%s', item, repmat(STYLEDATA(i).line,1,16));
            strhtml{i} = sprintf('%s%s', item,...
            STYLEDATA(i).line);

end
set( handles.listbox_style, 'String', strhtml)

%handles.STYLEDATA = STYLEDATA;
% Update handles structure
guidata(hObject, handles);

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

% --------------------------------------------------------------------------------------------
function listbox_color_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
      set(hObject,'BackgroundColor','white');
end

% --------------------------------------------------------------------------------------------
function pushbutton_up_color_Callback(hObject, eventdata, handles)
COLORDATA = handles.COLORDATA;
nbin = handles.nbin;
currline = get(handles.listbox_color, 'Value'); % current line

ncolor = length(COLORDATA);
if nnz(~bitand(currline>1,currline<=ncolor))==0
      aux = COLORDATA(currline);
      COLORDATA(currline) = COLORDATA(currline-1);
      COLORDATA(currline-1) = aux;
      setlistbox_color(hObject, handles, COLORDATA, nbin )
      set(handles.listbox_color, 'Value', currline-1); % current line
end

handles.COLORDATA = COLORDATA;
% Update handles structure
guidata(hObject, handles);

% fulltext = get(handles.listbox_color, 'String');
% fulltext = regexprep(fulltext,'.*?','');
% indxline = length(fulltext);
% fulltext = char(fulltext); % string matrix
% currline = get(handles.listbox_color, 'Value'); % current line
%
% if nnz(~bitand(currline>1,currline<=indxline))==0
%
%       aux = fulltext(currline,:);
%       fulltext(currline,:) = fulltext(currline-1,:);
%       fulltext(currline-1,:) = aux;
%       %fulltext(currline,:) = [];
%       fulltext = cellstr(fulltext); % cell string
%
%       set(handles.listbox_color, 'String', fulltext);
%       %handles.lastlineclicked = {};
%
%       % Update handles structure
%       %guidata(hObject, handles);
%
%       %set(handles.edit_numeric, 'string','')
%       %set(handles.edit_string, 'string','')
%       %set(handles.edit_binindex, 'string','')
%       %set(handles.edit_bindescription, 'string','')
%       %indxline = length(fulltext);
%       currline = currline-1;
%       if currline<1
%             currline = 1;
%       end
%
%       set(handles.listbox_color, 'Value', currline);
%       %listbox_Callback(hObject, eventdata, handles)
%
%
%
%
%
%
%
%
%       handles.fulltext = fulltext;
%       %handles.listname = [];
%
%       % Update handles structure
%       guidata(hObject, handles);
% end

% --------------------------------------------------------------------------------------------
function pushbutton_down_color_Callback(hObject, eventdata, handles)
COLORDATA = handles.COLORDATA;
nbin = handles.nbin;
currline = get(handles.listbox_color, 'Value'); % current line

ncolor = length(COLORDATA);
if nnz(~bitand(currline>=1,currline<ncolor))==0
      aux = COLORDATA(currline);
      COLORDATA(currline) = COLORDATA(currline+1);
      COLORDATA(currline+1) = aux;
      setlistbox_color(hObject, handles, COLORDATA, nbin )
      set(handles.listbox_color, 'Value', currline+1); % current line
end

handles.COLORDATA = COLORDATA;
% Update handles structure
guidata(hObject, handles);

% fulltext = get(handles.listbox_color, 'String');
% indxline = length(fulltext);
% fulltext = char(fulltext); % string matrix
% currline = get(handles.listbox_color, 'Value'); % current line
%
% if nnz(~bitand(currline>=1,currline<indxline))==0
%
%       aux = fulltext(currline,:);
%       fulltext(currline,:) = fulltext(currline+1,:);
%       fulltext(currline+1,:) = aux;
%       %fulltext(currline,:) = [];
%       fulltext = cellstr(fulltext); % cell string
%
%       set(handles.listbox_color, 'String', fulltext);
%       %handles.lastlineclicked = {};
%
%       % Update handles structure
%       %guidata(hObject, handles);
%
%       %set(handles.edit_numeric, 'string','')
%       %set(handles.edit_string, 'string','')
%       %set(handles.edit_binindex, 'string','')
%       %set(handles.edit_bindescription, 'string','')
%       indxline = length(fulltext);
%       currline = currline + 1;
%       if currline>indxline
%             currline = indxline;
%       end
%
%       set(handles.listbox_color, 'Value', currline);
%       %listbox_Callback(hObject, eventdata, handles)
%
%       handles.fulltext = fulltext;
%       %handles.listname = [];
%
%       % Update handles structure
%       guidata(hObject, handles);
% end

% --------------------------------------------------------------------------------------------
function pushbutton_default_color_Callback(hObject, eventdata, handles)
nbin      = handles.nbin;
defcolor  = handles.defcolor;
COLORDATA = colores(defcolor);
setlistbox_color(hObject, handles, COLORDATA, nbin )
handles.COLORDATA = COLORDATA;
% Update handles structure
guidata(hObject, handles);

% --------------------------------------------------------------------------------------------
function pushbutton_up_style_Callback(hObject, eventdata, handles)
STYLEDATA = handles.STYLEDATA;
nbin = handles.nbin;
currline = get(handles.listbox_style, 'Value'); % current line
ncolor = length(STYLEDATA);
if nnz(~bitand(currline>1,currline<=ncolor))==0
      aux = STYLEDATA(currline);
      STYLEDATA(currline) = STYLEDATA(currline-1);
      STYLEDATA(currline-1) = aux;
      setlistbox_style(hObject, handles, STYLEDATA, nbin )
      set(handles.listbox_style, 'Value', currline-1); % current line
end

handles.STYLEDATA = STYLEDATA;
% Update handles structure
guidata(hObject, handles);

% --------------------------------------------------------------------------------------------
function pushbutton_down_style_Callback(hObject, eventdata, handles)
STYLEDATA = handles.STYLEDATA;
nbin = handles.nbin;
currline = get(handles.listbox_style, 'Value'); % current line

ncolor = length(STYLEDATA);
if nnz(~bitand(currline>=1,currline<ncolor))==0
      aux = STYLEDATA(currline);
      STYLEDATA(currline) = STYLEDATA(currline+1);
      STYLEDATA(currline+1) = aux;
      setlistbox_style(hObject, handles, STYLEDATA, nbin )
      set(handles.listbox_style, 'Value', currline+1); % current line
end
handles.STYLEDATA = STYLEDATA;
% Update handles structure
guidata(hObject, handles);
% --------------------------------------------------------------------------------------------
function pushbutton_default_style_Callback(hObject, eventdata, handles)
nbin      = handles.nbin;
defstyle  = handles.defstyle;
STYLEDATA = estilos(defstyle);
setlistbox_style(hObject, handles, STYLEDATA, nbin )
handles.STYLEDATA = STYLEDATA;
% Update handles structure
guidata(hObject, handles);
handles.STYLEDATA = STYLEDATA;
% Update handles structure
guidata(hObject, handles);

%--------------------------------------------------------------------------
function pushbutton_top_color_Callback(hObject, eventdata, handles)
COLORDATA = handles.COLORDATA;
nbin = handles.nbin;
currline = get(handles.listbox_color, 'Value'); % current line
ncolor = length(COLORDATA);
if nnz(~bitand(currline>1,currline<=ncolor))==0
      aux = COLORDATA(currline);
      COLORDATA(currline) = [];
      COLORDATA = [aux COLORDATA];
      setlistbox_color(hObject, handles, COLORDATA, nbin )
      set(handles.listbox_color, 'Value', 1); % current line
end

handles.COLORDATA = COLORDATA;
% Update handles structure
guidata(hObject, handles);

%--------------------------------------------------------------------------
function pushbutton_top_style_Callback(hObject, eventdata, handles)
STYLEDATA = handles.STYLEDATA;
nbin = handles.nbin;
currline = get(handles.listbox_style, 'Value'); % current line
ncolor = length(STYLEDATA);
if nnz(~bitand(currline>1,currline<=ncolor))==0
      aux = STYLEDATA(currline);
      STYLEDATA(currline) = [];
      STYLEDATA = [aux STYLEDATA];
      setlistbox_style(hObject, handles, STYLEDATA, nbin )
      set(handles.listbox_style, 'Value', 1); % current line
end

handles.STYLEDATA = STYLEDATA;
% Update handles structure
guidata(hObject, handles);

%--------------------------------------------------------------------------
function pushbutton_color1_Callback(hObject, eventdata, handles)
ReplaceColoratList(hObject, eventdata, handles)
% % % colorbtn = 'BLUE';
% % colorbtn = get(hObject, 'UserData');
% % % v = get(handles.listbox_color, 'Value');
% % currline = get(handles.listbox_color, 'Value'); % current line
% % s = get(handles.listbox_color, 'String');
% % w = regexp(s, '\w+$', 'match');
% % w = [w{:}];
% % ind = find(ismember(w, colorbtn), 1, 'last');
% % COLORDATA = handles.COLORDATA;
% % nbin = handles.nbin;
% % % currline = get(handles.listbox_color, 'Value'); % current line
% %
% % ncolor = length(COLORDATA);
% %
% % if nnz(~bitand(currline>=1,currline<=ncolor))==0
% %       aux = COLORDATA(currline);
% %       COLORDATA(currline) = COLORDATA(ind);
% %       COLORDATA(ind) = aux;
% %       setlistbox_color(hObject, handles, COLORDATA, nbin )
% %       %set(handles.listbox_color, 'Value', 1);
% % end
% % handles.COLORDATA = COLORDATA;
% % % Update handles structure
% % guidata(hObject, handles);
% % %     'empty..:MAGENTA'

%--------------------------------------------------------------------------
function pushbutton_color2_Callback(hObject, eventdata, handles)
ReplaceColoratList(hObject, eventdata, handles)
% % % colorbtn = '';
% % colorbtn = get(hObject, 'UserData');
% % % v = get(handles.listbox_color, 'Value');
% % currline = get(handles.listbox_color, 'Value'); % current line
% % s = get(handles.listbox_color, 'String');
% % w = regexp(s, '\w+$', 'match');
% % w = [w{:}];
% % ind = find(ismember(w, colorbtn), 1, 'last');
% % COLORDATA = handles.COLORDATA;
% % nbin = handles.nbin;
% % % currline = get(handles.listbox_color, 'Value'); % current line
% %
% % ncolor = length(COLORDATA);
% %
% % if nnz(~bitand(currline>=1,currline<=ncolor))==0
% %       aux = COLORDATA(currline);
% %       COLORDATA(currline) = COLORDATA(ind);
% %       COLORDATA(ind) = aux;
% %       setlistbox_color(hObject, handles, COLORDATA, nbin )
% %       %set(handles.listbox_color, 'Value', 1);
% % end
% % handles.COLORDATA = COLORDATA;
% % % Update handles structure
% % guidata(hObject, handles);

%--------------------------------------------------------------------------
function pushbutton_color3_Callback(hObject, eventdata, handles)
ReplaceColoratList(hObject, eventdata, handles)
% % % colorbtn = '';
% % colorbtn = get(hObject, 'UserData');
% % % v = get(handles.listbox_color, 'Value');
% % currline = get(handles.listbox_color, 'Value'); % current line
% % s = get(handles.listbox_color, 'String');
% % w = regexp(s, '\w+$', 'match');
% % w = [w{:}];
% % ind = find(ismember(w, colorbtn), 1, 'last');
% % COLORDATA = handles.COLORDATA;
% % nbin = handles.nbin;
% % % currline = get(handles.listbox_color, 'Value'); % current line
% %
% % ncolor = length(COLORDATA);
% %
% % if nnz(~bitand(currline>=1,currline<=ncolor))==0
% %       aux = COLORDATA(currline);
% %       COLORDATA(currline) = COLORDATA(ind);
% %       COLORDATA(ind) = aux;
% %       setlistbox_color(hObject, handles, COLORDATA, nbin )
% %       %set(handles.listbox_color, 'Value', 1);
% % end
% % handles.COLORDATA = COLORDATA;
% % % Update handles structure
% % guidata(hObject, handles);

%--------------------------------------------------------------------------
function pushbutton_color4_Callback(hObject, eventdata, handles)
ReplaceColoratList(hObject, eventdata, handles)
% % % colorbtn = '';
% % colorbtn = get(hObject, 'UserData');
% % % v = get(handles.listbox_color, 'Value');
% % currline = get(handles.listbox_color, 'Value'); % current line
% % s = get(handles.listbox_color, 'String');
% % w = regexp(s, '\w+$', 'match');
% % w = [w{:}];
% % ind = find(ismember(w, colorbtn), 1, 'last');
% % COLORDATA = handles.COLORDATA;
% % nbin = handles.nbin;
% % % currline = get(handles.listbox_color, 'Value'); % current line
% %
% % ncolor = length(COLORDATA);
% %
% % if nnz(~bitand(currline>=1,currline<=ncolor))==0
% %       aux = COLORDATA(currline);
% %       COLORDATA(currline) = COLORDATA(ind);
% %       COLORDATA(ind) = aux;
% %       setlistbox_color(hObject, handles, COLORDATA, nbin )
% %       %set(handles.listbox_color, 'Value', 1);
% % end
% % handles.COLORDATA = COLORDATA;
% % % Update handles structure
% % guidata(hObject, handles);

%--------------------------------------------------------------------------
function pushbutton_color5_Callback(hObject, eventdata, handles)
ReplaceColoratList(hObject, eventdata, handles)
% % % colorbtn = '';
% % colorbtn = get(hObject, 'UserData');
% % % v = get(handles.listbox_color, 'Value');
% % currline = get(handles.listbox_color, 'Value'); % current line
% % s = get(handles.listbox_color, 'String');
% % w = regexp(s, '\w+$', 'match');
% % w = [w{:}];
% % ind = find(ismember(w, colorbtn), 1, 'last');
% % COLORDATA = handles.COLORDATA;
% % nbin = handles.nbin;
% % % currline = get(handles.listbox_color, 'Value'); % current line
% %
% % ncolor = length(COLORDATA);
% %
% % if nnz(~bitand(currline>=1,currline<=ncolor))==0
% %       aux = COLORDATA(currline);
% %       COLORDATA(currline) = COLORDATA(ind);
% %       COLORDATA(ind) = aux;
% %       setlistbox_color(hObject, handles, COLORDATA, nbin )
% %       %set(handles.listbox_color, 'Value', 1);
% % end
% % handles.COLORDATA = COLORDATA;
% % % Update handles structure
% % guidata(hObject, handles);

%--------------------------------------------------------------------------
function pushbutton_color6_Callback(hObject, eventdata, handles)
ReplaceColoratList(hObject, eventdata, handles)
% % % colorbtn = '';
% % colorbtn = get(hObject, 'UserData');
% % % v = get(handles.listbox_color, 'Value');
% % currline = get(handles.listbox_color, 'Value'); % current line
% % s = get(handles.listbox_color, 'String');
% % w = regexp(s, '\w+$', 'match');
% % w = [w{:}];
% % ind = find(ismember(w, colorbtn), 1, 'last');
% % COLORDATA = handles.COLORDATA;
% % nbin = handles.nbin;
% % % currline = get(handles.listbox_color, 'Value'); % current line
% %
% % ncolor = length(COLORDATA);
% %
% % if nnz(~bitand(currline>=1,currline<=ncolor))==0
% %       aux = COLORDATA(currline);
% %       COLORDATA(currline) = COLORDATA(ind);
% %       COLORDATA(ind) = aux;
% %       setlistbox_color(hObject, handles, COLORDATA, nbin )
% %       %set(handles.listbox_color, 'Value', 1);
% % end
% % handles.COLORDATA = COLORDATA;
% % % Update handles structure
% % guidata(hObject, handles);

%--------------------------------------------------------------------------
function pushbutton_color7_Callback(hObject, eventdata, handles)
ReplaceColoratList(hObject, eventdata, handles)
% % % colorbtn = '';
% % colorbtn = get(hObject, 'UserData');
% % % v = get(handles.listbox_color, 'Value');
% % currline = get(handles.listbox_color, 'Value'); % current line
% % s = get(handles.listbox_color, 'String');
% % w = regexp(s, '\w+$', 'match');
% % w = [w{:}];
% % ind = find(ismember(w, colorbtn), 1, 'last');
% %
% % COLORDATA = handles.COLORDATA;
% % nbin = handles.nbin;
% % % currline = get(handles.listbox_color, 'Value'); % current line
% %
% % ncolor = length(COLORDATA);
% %
% % if nnz(~bitand(currline>=1,currline<=ncolor))==0
% %       aux = COLORDATA(currline);
% %       COLORDATA(currline) = COLORDATA(ind);
% %       COLORDATA(ind) = aux;
% %       setlistbox_color(hObject, handles, COLORDATA, nbin )
% %       %set(handles.listbox_color, 'Value', 1);
% % end
% % handles.COLORDATA = COLORDATA;
% % % Update handles structure
% % guidata(hObject, handles);

%--------------------------------------------------------------------------
function pushbutton_color8_Callback(hObject, eventdata, handles)
ReplaceColoratList(hObject, eventdata, handles)

%--------------------------------------------------------------------------
function ReplaceColoratList(hObject, eventdata, handles)
% colorbtn = '';
colorbtn = get(hObject, 'UserData');
% v = get(handles.listbox_color, 'Value');
currline = get(handles.listbox_color, 'Value'); % current line
s = get(handles.listbox_color, 'String');
w = regexp(s, '\w+$', 'match');
w = [w{:}];
ind = find(ismember(w, colorbtn), 1, 'last');

COLORDATA = handles.COLORDATA;
nbin = handles.nbin;
% currline = get(handles.listbox_color, 'Value'); % current line

ncolor = length(COLORDATA);

if nnz(~bitand(currline>=1,currline<=ncolor))==0
      aux = COLORDATA(currline);
      COLORDATA(currline) = COLORDATA(ind);
      COLORDATA(ind) = aux;
      setlistbox_color(hObject, handles, COLORDATA, nbin )
      %set(handles.listbox_color, 'Value', 1);
end
handles.COLORDATA = COLORDATA;
% Update handles structure
guidata(hObject, handles);

%--------------------------------------------------------------------------
function pushbutton_line1_Callback(hObject, eventdata, handles)
linebtn = get(hObject, 'UserData');
% v = get(handles.listbox_color, 'Value');
currline = get(handles.listbox_style, 'Value'); % current line
s = get(handles.listbox_style, 'String');
% w = regexp(s, '\w+$', 'match');
w = regexp(s, '\w+-*\w*$', 'match');
w = [w{:}];
ind = find(ismember(w, linebtn), 1, 'last');

STYLEDATA = handles.STYLEDATA;
nbin = handles.nbin;
% currline = get(handles.listbox_style, 'Value'); % current line

ncolor = length(STYLEDATA);

if nnz(~bitand(currline>=1,currline<=ncolor))==0
      aux = STYLEDATA(currline);
      STYLEDATA(currline) = STYLEDATA(ind);
      STYLEDATA(ind) = aux;
      setlistbox_style(hObject, handles, STYLEDATA, nbin )
      %set(handles.listbox_style, 'Value', 1); % current line
end

handles.STYLEDATA = STYLEDATA;
% Update handles structure
guidata(hObject, handles);

%--------------------------------------------------------------------------
function pushbutton_line2_Callback(hObject, eventdata, handles)
linebtn = get(hObject, 'UserData');
% v = get(handles.listbox_color, 'Value');
currline = get(handles.listbox_style, 'Value'); % current line
s = get(handles.listbox_style, 'String');
% w = regexp(s, '\w+$', 'match');
w = regexp(s, '\w+-*\w*$', 'match');
w = [w{:}];
ind = find(ismember(w, linebtn), 1, 'last');

STYLEDATA = handles.STYLEDATA;
nbin = handles.nbin;
% currline = get(handles.listbox_style, 'Value'); % current line

ncolor = length(STYLEDATA);

if nnz(~bitand(currline>=1,currline<=ncolor))==0
      aux = STYLEDATA(currline);
      STYLEDATA(currline) = STYLEDATA(ind);
      STYLEDATA(ind) = aux;
      setlistbox_style(hObject, handles, STYLEDATA, nbin )
      %set(handles.listbox_style, 'Value', 1); % current line
end

handles.STYLEDATA = STYLEDATA;
% Update handles structure
guidata(hObject, handles);

%--------------------------------------------------------------------------
function pushbutton_line3_Callback(hObject, eventdata, handles)
linebtn = get(hObject, 'UserData');
% v = get(handles.listbox_color, 'Value');
currline = get(handles.listbox_style, 'Value'); % current line
s = get(handles.listbox_style, 'String');
% w = regexp(s, '\w+$', 'match');
w = regexp(s, '\w+-*\w*$', 'match');
w = [w{:}];
ind = find(ismember(w, linebtn), 1, 'last');

STYLEDATA = handles.STYLEDATA;
nbin = handles.nbin;
% currline = get(handles.listbox_style, 'Value'); % current line

ncolor = length(STYLEDATA);

if nnz(~bitand(currline>=1,currline<=ncolor))==0
      aux = STYLEDATA(currline);
      STYLEDATA(currline) = STYLEDATA(ind);
      STYLEDATA(ind) = aux;
      setlistbox_style(hObject, handles, STYLEDATA, nbin )
      %set(handles.listbox_style, 'Value', 1); % current line
end

handles.STYLEDATA = STYLEDATA;
% Update handles structure
guidata(hObject, handles);

%--------------------------------------------------------------------------
function pushbutton_line4_Callback(hObject, eventdata, handles)
linebtn = get(hObject, 'UserData');
% v = get(handles.listbox_color, 'Value');
currline = get(handles.listbox_style, 'Value'); % current line
s = get(handles.listbox_style, 'String');
% w = regexp(s, '\w+$', 'match');
w = regexp(s, '\w+-*\w*$', 'match');
w = [w{:}];
ind = find(ismember(w, linebtn), 1, 'last');

STYLEDATA = handles.STYLEDATA;
nbin = handles.nbin;
% currline = get(handles.listbox_style, 'Value'); % current line

ncolor = length(STYLEDATA);

if nnz(~bitand(currline>=1,currline<=ncolor))==0
      aux = STYLEDATA(currline);
      STYLEDATA(currline) = STYLEDATA(ind);
      STYLEDATA(ind) = aux;
      setlistbox_style(hObject, handles, STYLEDATA, nbin )
      %set(handles.listbox_style, 'Value', 1); % current line
end

handles.STYLEDATA = STYLEDATA;
% Update handles structure
guidata(hObject, handles);

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

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

%colorlist = get( handles.listbox_color, 'String');
%colorlist = lower(regexprep(colorlist,'','','ignorecase')');
%colorlist = lower(regexprep(colorlist,'.*?','');
%'.*?','');
lwidth    = get(handles.popupmenu_lwidth,'Value');
COLORDATA = handles.COLORDATA;
STYLEDATA = handles.STYLEDATA;
output    = cellstr([char({COLORDATA.colorchar}') char({STYLEDATA(1:length(COLORDATA)).style}')])';
%[xxx indx] = ismember_bc2(colorlist, {COLORDATA.colorname});
%handles.output = {COLORDATA(indx).colorchar};
handles.output = {output lwidth};
% Update handles structure
guidata(hObject, handles);
uiresume(handles.gui_chassis);

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

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

% Hint: listbox_color 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 popupmenu_lwidth_Callback(hObject, eventdata, handles)

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

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

%--------------------------------------------------------------------------
function gui_chassis_CloseRequestFcn(hObject, eventdata, handles)
if isequal(get(handles.gui_chassis, 'waitstatus'), 'waiting')
      % The GUI is still in UIWAIT, us UIRESUME
      uiresume(handles.gui_chassis);
else
      % The GUI is no longer waiting, just close it
      delete(handles.gui_chassis);
end


function bf = const_bf(PATH)

% Path (x,y,z) by nodes
m = size(PATH,1);

bf = zeros(10*(m-1),size(PATH,2));
bf(1,:) = PATH(1,:);
bf(end-4,:) = PATH(end,:);
idx = 1;
for i=1:m-2
    bf(5*(idx)+1,:) = PATH(i+1,:);
    idx = idx+1;
    bf(5*(idx)+1,:) = PATH(i+1,:);
    idx = idx+1;
end
idx = [];
for i=1:m-2
    idx = [idx, 10*i+2:10*i+5];
end
bf(idx,:) = [];


function [output] = minus(input1, input2)

if ~iscell(input1)
  input1 = repmat({input1}, size(input2));
end
if ~iscell(input2)
  input2 = repmat({input2}, size(input1));
end
output = cellfun(@minus,input1,input2,'uniformoutput',false);


function [ output_struct ] = parsepdvinputs( varargin )
%PARSEPDVINPUTS Parse input arguments for pdv
%
%   Used in both in-memory and in-file version of PDV
%
% //////////////////////////////////////////
% /// CLASSIFICATION: UNCLASSIFIED       ///
% //////////////////////////////////////////

p = inputParser;
p.KeepUnmatched=true;
p.addParamValue('deltax', 0.25, @(x) isscalar(x)&&(x>0));
p.addParamValue('filtersize', 5, @(x) isvector(x)&&(length(x)<=2)&&all(x>0));
p.addParamValue('filtertype', 'mean', @(x)any(strcmpi(x,{'mean','median'})));
p.addParamValue('dim', 1, @(x) isequal(x,1)||isequal(x,2));
p.addParamValue('framenumber',1);
p.FunctionName = 'PDV';
p.parse(varargin{:});

output_struct=p.Results;

end

% //////////////////////////////////////////
% /// CLASSIFICATION: UNCLASSIFIED       ///
% //////////////////////////////////////////


function [ Elements, varargout ] = ply_read ( Path, Str )

%*****************************************************************************80
%
%% PLY_READ reads a PLY 3D data file.
%
%   [DATA,COMMENTS] = PLY_READ(FILENAME) reads a version 1.0 PLY file
%   FILENAME and returns a structure DATA.  The fields in this structure
%   are defined by the PLY header; each element type is a field and each
%   element property is a subfield.  If the file contains any comments,
%   they are returned in a cell string array COMMENTS.
%
%   [TRI,PTS] = PLY_READ(FILENAME,'tri') or
%   [TRI,PTS,DATA,COMMENTS] = PLY_READ(FILENAME,'tri') converts vertex
%   and face data into triangular connectivity and vertex arrays.  The
%   mesh can then be displayed using the TRISURF command.
%
%   Note: This function is slow for large mesh files (+50K faces),
%   especially when reading data with list type properties.
%
%   Example:
%   [Tri,Pts] = PLY_READ('cow.ply','tri');
%   trisurf(Tri,Pts(:,1),Pts(:,2),Pts(:,3));
%   colormap(gray); axis equal;
%
%  Discussion:
%
%    The original version of this program had a mistake that meant it
%    did not properly triangulate files whose faces were not already triangular.
%    This has been corrected (JVB, 25 February 2007).
%
%    Glenn Ramsey pointed out and corrected a problem that occurred
%    with an uninitialized value of Type2, 27 August 2012.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    27 August 2012
%
%  Author:
%
%    Pascal Getreuer 2004
%
%  Parameters:
%
%  Local Parameters:
%
%    COMMENTS, any comments from the file.
%
%    ELEMENTCOUNT, the number of each type of element in file.
%
%    ELEMENTS, the element data.
%
%    PROPERTYTYPES, the element property types.
%
%    SIZEOF, size in bytes of each type.
%

%
%  Open the input file in "read text" mode.
%
  [ fid, Msg ] = fopen ( Path, 'rt' );

  if ( fid == -1 )
    error ( Msg );
  end

  Buf = fscanf ( fid, '%s', 1 );

  if ( ~strcmp ( Buf, 'ply' ) )
    fclose ( fid );
    error('Not a PLY file.');
  end
%
%  Read the header.
%
  Position = ftell(fid);
  Format = '';
  NumComments = 0;
  Comments = {};
  NumElements = 0;
  NumProperties = 0;
  Elements = [];
  ElementCount = [];
  PropertyTypes = [];
  ElementNames = {};  % list of element names in the order they are stored in the file
  PropertyNames = [];  % structure of lists of property names

  while ( 1 )
%
%  Read a line from the file.
%
    Buf = fgetl ( fid );
    BufRem = Buf;
    Token = {};
    Count = 0;
%
%  Split the line into tokens.
%
    while ( ~isempty(BufRem) )

      [ tmp, BufRem ] = strtok(BufRem);
%
%  Count the tokens.
%
      if ( ~isempty ( tmp ) )
        Count = Count + 1;
        Token{Count} = tmp;
      end

    end
%
%  Parse the line.
%
    if ( Count )

      switch lower ( Token{1} )
%
%  Read the data format.
%
      case 'format'

        if ( 2 <= Count )

          Format = lower ( Token{2} );

          if ( Count == 3 & ~strcmp ( Token{3}, '1.0' ) )
            fclose ( fid );
            error('Only PLY format version 1.0 supported.');
          end
        end
%
%  Read a comment.
%
      case 'comment'

        NumComments = NumComments + 1;
        Comments{NumComments} = '';
        for i = 2 : Count
          Comments{NumComments} = [Comments{NumComments},Token{i},' '];
        end
%
%  Read an element name.
%
      case 'element'

        if ( 3 <= Count )

          if ( isfield(Elements,Token{2}) )
            fclose ( fid );
            error(['Duplicate element name, ''',Token{2},'''.']);
          end

          NumElements = NumElements + 1;
          NumProperties = 0;
          Elements = setfield(Elements,Token{2},[]);
          PropertyTypes = setfield(PropertyTypes,Token{2},[]);
          ElementNames{NumElements} = Token{2};
          PropertyNames = setfield(PropertyNames,Token{2},{});
          CurElement = Token{2};
          ElementCount(NumElements) = str2double(Token{3});

          if ( isnan(ElementCount(NumElements)) )
            fclose ( fid );
            error(['Bad element definition: ',Buf]);
          end

        else

          error(['Bad element definition: ',Buf]);

        end
%
%  Read an element property.
%
      case 'property'

        if ( ~isempty(CurElement) & Count >= 3 )

          NumProperties = NumProperties + 1;
          eval(['tmp=isfield(Elements.',CurElement,',Token{Count});'],...
            'fclose(fid);error([''Error reading property: '',Buf])');

          if ( tmp )
            error(['Duplicate property name, ''',CurElement,'.',Token{2},'''.']);
          end
%
%  Add property subfield to Elements.
%
          eval(['Elements.',CurElement,'.',Token{Count},'=[];'], ...
            'fclose(fid);error([''Error reading property: '',Buf])');
%
%  Add property subfield to PropertyTypes and save type.
%
          eval(['PropertyTypes.',CurElement,'.',Token{Count},'={Token{2:Count-1}};'], ...
            'fclose(fid);error([''Error reading property: '',Buf])');
%
%  Record property name order.
%
          eval(['PropertyNames.',CurElement,'{NumProperties}=Token{Count};'], ...
            'fclose(fid);error([''Error reading property: '',Buf])');

         else

           fclose ( fid );

           if ( isempty(CurElement) )
             error(['Property definition without element definition: ',Buf]);
           else
             error(['Bad property definition: ',Buf]);
           end

         end
%
%  End of header.
%
        case 'end_header'
          break;

      end
    end
  end
%
%  Set reading for specified data format.
%
  if ( isempty ( Format ) )
    warning('Data format unspecified, assuming ASCII.');
    Format = 'ascii';
  end

  switch Format

    case 'ascii'
      Format = 0;
    case 'binary_little_endian'
      Format = 1;
    case 'binary_big_endian'
      Format = 2;
    otherwise
      fclose ( fid );
      error(['Data format ''',Format,''' not supported.']);

  end
%
%  Read the rest of the file as ASCII data...
%
  if ( ~Format )
    Buf = fscanf ( fid, '%f' );
    BufOff = 1;
  else
%
%  ...or, close the file, and reopen in "read binary" mode.
%
    fclose ( fid );
%
%  Reopen the binary file as LITTLE_ENDIAN or BIG_ENDIAN.
%
    if ( Format == 1 )
      fid = fopen ( Path, 'r', 'ieee-le.l64' );
    else
      fid = fopen ( Path, 'r', 'ieee-be.l64' );
    end
%
%  Find the end of the header again.
%  Using ftell on the old handle doesn't give the correct position.
%
    BufSize = 8192;
    Buf = [ blanks(10), char(fread(fid,BufSize,'uchar')') ];
    i = [];
    tmp = -11;

    while ( isempty(i) )

      i = findstr(Buf,['end_header',13,10]);   % look for end_header + CR/LF
      i = [i,findstr(Buf,['end_header',10])];  % look for end_header + LF

      if ( isempty(i) )
        tmp = tmp + BufSize;
        Buf = [Buf(BufSize+1:BufSize+10),char(fread(fid,BufSize,'uchar')')];
      end

    end
%
%  seek to just after the line feed
%
    fseek ( fid, i + tmp + 11 + (Buf(i + 10) == 13), -1 );

  end
%
%  Read element data.
%
%  PLY and MATLAB data types (for fread)
%
  PlyTypeNames = {'char','uchar','short','ushort','int','uint','float','double', ...
    'char8','uchar8','short16','ushort16','int32','uint32','float32','double64'};

  MatlabTypeNames = {'schar','uchar','int16','uint16','int32','uint32','single','double'};

  SizeOf = [1,1,2,2,4,4,4,8];

  for i = 1 : NumElements
%
%  get current element property information
%
    eval(['CurPropertyNames=PropertyNames.',ElementNames{i},';']);
    eval(['CurPropertyTypes=PropertyTypes.',ElementNames{i},';']);
    NumProperties = size(CurPropertyNames,2);

%   fprintf('Reading %s...\n',ElementNames{i});
%
%  Read ASCII data.
%
    if ( ~Format )

      for j = 1 : NumProperties

        Token = getfield(CurPropertyTypes,CurPropertyNames{j});

        if ( strcmpi(Token{1},'list') )
          Type(j) = 1;
        else
          Type(j) = 0;
        end
%
%  Glenn Ramsey 20120827
%  Initialise Type2{} to prevent uninitialised value error.
%
        Type2{j} = '';

      end
%
%  Parse the buffer.
%
      if ( ~any(Type) )

         % no list types

        Data = reshape ( ...
          Buf(BufOff:BufOff+ElementCount(i)*NumProperties-1), ...
          NumProperties, ElementCount(i) )';

        BufOff = BufOff + ElementCount(i) * NumProperties;

      else

        ListData = cell(NumProperties,1);

        for k = 1 : NumProperties
          ListData{k} = cell(ElementCount(i),1);
        end
%
% list type
%
        for j = 1 : ElementCount(i)
          for k = 1 : NumProperties

            if ( ~Type(k) )
              Data(j,k) = Buf(BufOff);
              BufOff = BufOff + 1;
            else
              tmp = Buf(BufOff);
              ListData{k}{j} = Buf(BufOff+(1:tmp))';
              BufOff = BufOff + tmp + 1;
            end

          end
        end

      end
%
%  Read binary data.
%
    else
% translate PLY data type names to MATLAB data type names
      ListFlag = 0;  % = 1 if there is a list type
      SameFlag = 1;     % = 1 if all types are the same

      for j = 1 : NumProperties

        Token = getfield(CurPropertyTypes,CurPropertyNames{j});
%
%  Non-list type.
%
        if ( ~strcmp(Token{1},'list' ) )

          tmp = rem(strmatch(Token{1},PlyTypeNames,'exact')-1,8)+1;

          if ( ~isempty(tmp) )

            TypeSize(j) = SizeOf(tmp);
            Type{j} = MatlabTypeNames{tmp};
            TypeSize2(j) = 0;
            Type2{j} = '';

            SameFlag = SameFlag & strcmp(Type{1},Type{j});

          else

            fclose(fid);
            error(['Unknown property data type, ''',Token{1},''', in ', ...
              ElementNames{i},'.',CurPropertyNames{j},'.']);

          end

        else           % list type

          if ( length(Token) == 3 )

            ListFlag = 1;
            SameFlag = 0;
            tmp = rem(strmatch(Token{2},PlyTypeNames,'exact')-1,8)+1;
            tmp2 = rem(strmatch(Token{3},PlyTypeNames,'exact')-1,8)+1;

            if ( ~isempty(tmp) & ~isempty(tmp2) )
              TypeSize(j) = SizeOf(tmp);
              Type{j} = MatlabTypeNames{tmp};
              TypeSize2(j) = SizeOf(tmp2);
              Type2{j} = MatlabTypeNames{tmp2};
            else
              fclose(fid);
              error(['Unknown property data type, ''list ',Token{2},' ',Token{3},''', in ', ...
                ElementNames{i},'.',CurPropertyNames{j},'.']);
            end

          else

            fclose(fid);
            error(['Invalid list syntax in ',ElementNames{i},'.',CurPropertyNames{j},'.']);

          end

        end

      end

% read file

      if ( ~ListFlag )
%
%  No list types, all the same type (fast)
%
        if ( SameFlag )

          Data = fread(fid,[NumProperties,ElementCount(i)],Type{1})';
%
%  No list types, mixed type.
%
        else

          Data = zeros(ElementCount(i),NumProperties);

          for j = 1 : ElementCount(i)
            for k = 1 : NumProperties
              Data(j,k) = fread(fid,1,Type{k});
            end
          end

        end

      else

        ListData = cell(NumProperties,1);

        for k = 1 : NumProperties
          ListData{k} = cell(ElementCount(i),1);
        end

        if ( NumProperties == 1 )

          BufSize = 512;
          SkipNum = 4;
          j = 0;
%
%  List type, one property (fast if lists are usually the same length)
%
          while ( j < ElementCount(i) )

            BufSize = min(ElementCount(i)-j,BufSize);
            Position = ftell(fid);
%
%  Read in BufSize count values, assuming all counts = SkipNum
%
            [Buf,BufSize] = fread(fid,BufSize,Type{1},SkipNum*TypeSize2(1));
            Miss = find(Buf ~= SkipNum);     % find first count that is not SkipNum
            fseek(fid,Position + TypeSize(1),-1);   % seek back to after first count

            if ( isempty(Miss) )
% all counts are SkipNum
              Buf = fread(fid,[SkipNum,BufSize],[int2str(SkipNum),'*',Type2{1}],TypeSize(1))';
              fseek(fid,-TypeSize(1),0);     % undo last skip

              for k = 1:BufSize
                ListData{1}{j+k} = Buf(k,:);
              end

              j = j + BufSize;
              BufSize = floor(1.5*BufSize);

            else
%
%  Some counts are SkipNum.
%
              if ( 1 < Miss(1) )

                Buf2 = fread(fid,[SkipNum,Miss(1)-1],[int2str(SkipNum),'*',Type2{1}],TypeSize(1))';

                for k = 1:Miss(1)-1
                  ListData{1}{j+k} = Buf2(k,:);
                end

                j = j + k;

              end
%
%  Read in the list with the missed count.
%
              SkipNum = Buf(Miss(1));
              j = j + 1;
              ListData{1}{j} = fread(fid,[1,SkipNum],Type2{1});
              BufSize = ceil(0.6*BufSize);

            end
          end

        else
%
%  List type(s), multiple properties (slow)
%
          Data = zeros(ElementCount(i),NumProperties);

          for j = 1:ElementCount(i)
            for k = 1:NumProperties

              if ( isempty(Type2{k}) )
                Data(j,k) = fread(fid,1,Type{k});
              else
                tmp = fread(fid,1,Type{k});
                ListData{k}{j} = fread(fid,[1,tmp],Type2{k});
              end

            end
          end
        end
      end
    end
%
%  Put data into Elements structure
%
    for k = 1 : NumProperties

      if ( ( ~Format && ~isempty(Type(k)) ) || (Format && isempty(Type2{k})) )
        eval(['Elements.',ElementNames{i},'.',CurPropertyNames{k},'=Data(:,k);']);
      else
        eval(['Elements.',ElementNames{i},'.',CurPropertyNames{k},'=ListData{k};']);
      end

    end

  end

  clear Data
  clear ListData;

  fclose ( fid );
%
%  Output the data as a triangular mesh pair.
%
  if ( ( nargin > 1 && strcmpi(Str,'Tri') ) || nargout > 2 )
%
%  Find vertex element field
%
    Name = {'vertex','Vertex','point','Point','pts','Pts'};
    Names = [];

    for i = 1 : length(Name)

      if ( any ( strcmp ( ElementNames, Name{i} ) ) )
        Names = getfield(PropertyNames,Name{i});
        Name = Name{i};
        break;
      end

    end

    if ( any(strcmp(Names,'x')) & any(strcmp(Names,'y')) & any(strcmp(Names,'z')) )
      eval(['varargout{1}=[Elements.',Name,'.x,Elements.',Name,'.y,Elements.',Name,'.z];']);
    else
      varargout{1} = zeros(1,3);
    end
    varargout{1} = varargout{1}';

    varargout{2} = Elements;
    varargout{3} = Comments;
    Elements = [];
%
% Find face element field
%
    Name = {'face','Face','poly','Poly','tri','Tri'};
    Names = [];

    for i = 1 : length(Name)
      if ( any(strcmp(ElementNames,Name{i})) )
        Names = getfield(PropertyNames,Name{i});
        Name = Name{i};
        break;
      end
    end

    if ( ~isempty(Names) )
      % find vertex indices property subfield
      PropertyName = {'vertex_indices','vertex_indexes','vertex_index','indices','indexes'};

      for i = 1 : length(PropertyName)
        if ( any(strcmp(Names,PropertyName{i})) )
          PropertyName = PropertyName{i};
          break;
        end
      end
%
%  Convert face index list to triangular connectivity.
%
      if ( ~iscell(PropertyName) )

        eval(['FaceIndices=varargout{2}.',Name,'.',PropertyName,';']);
        N = length(FaceIndices);
        Elements = zeros(3,N*2);
        Extra = 0;

        for k = 1 : N

          Elements(1:3,k) = FaceIndices{k}(1:3)';
%
%  The original code had an error in the following loop.
%
          for j = 4 : length(FaceIndices{k})
            Extra = Extra + 1;
            Elements(1,N + Extra) = FaceIndices{k}(1);
            Elements(2,N + Extra) = FaceIndices{k}(j-1);
            Elements(3,N + Extra) = FaceIndices{k}(j);
          end

        end
%
%  Add 1 to each vertex value; PLY vertices are zero based.
%
        Elements = Elements(:,1:N+Extra) + 1;

      end
    end

  else

    varargout{1} = Comments;

  end

  return
end


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

% Copyright 2002-2003 The MathWorks, Inc.

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

% Last Modified by GUIDE v2.5 01-May-2006 23:22:44

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @configure_classify_OpeningFcn, ...
                   'gui_OutputFcn',  @configure_classify_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 configure_classify is made visible.
function configure_classify_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to configure_classify (see VARARGIN)

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

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes configure_classify wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% configure_classify(0,7500,400,500,44100,[0.01 0.001],[3 5],[0 20000])

handles.lowerfreq = varargin{1};  % Lower frequency for zooming
handles.upperfreq = varargin{2}; % Upper frequency for zooming

handles.classified_height = varargin{3} ; % the height of the image in the classified axes
handles.classified_width = varargin{4};  % the width of the image in the classified axes

handles.Fs = varargin{5}; % Frequency of audio sampling per second
handles.movingwin = varargin{6}; % Size of the moving window in seconds; the first number is the window size and the second is the step size
handles.tapers = varargin{7}; % Tapers for smoothing
handles.fpass = varargin{8}; % Range of frequency sampling

handles.fixed = varargin{9}; % Fixed scaling of the classified axes

set(handles.ZoomLowerFreq,'String',num2str(handles.lowerfreq));
set(handles.ZoomUpperFreq,'String',num2str(handles.upperfreq));
set(handles.ClassifiedWidth,'String',num2str(handles.classified_width));
set(handles.ClassifiedHeight,'String',num2str(handles.classified_height));
set(handles.Frequency,'String',num2str(handles.Fs));
set(handles.WinSize,'String',num2str(handles.movingwin(1) * 1000));
set(handles.StepSize,'String',num2str(handles.movingwin(2) * 1000));
set(handles.TW,'String',num2str(handles.tapers(1)));
set(handles.MinFreq,'String',num2str(handles.fpass(1)));
set(handles.MaxFreq,'String',num2str(handles.fpass(2)));

set(handles.FixedCheckbox,'Value',handles.fixed);

% set(handles.ZoomLowerFreq,'Enable','off');
% set(handles.ZoomUpperFreq,'Enable','off');
% set(handles.ClassifiedWidth,'Enable','off');
% set(handles.ClassifiedHeight,'Enable','off');
% set(handles.Frequency,'Enable','off');
% set(handles.WinSize,'Enable','off');
% set(handles.StepSize,'Enable','off');
% set(handles.TW,'Enable','off');
% set(handles.MinFreq,'Enable','off');
% set(handles.MaxFreq,'Enable','off');

uiwait(handles.figure1);

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

close;

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

% --- Executes during object creation, after setting all properties.
function WinSize_CreateFcn(hObject, eventdata, handles)
% hObject    handle to WinSize (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
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

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

lowerfreq = str2num(get(handles.ZoomLowerFreq,'String'));  % Lower frequency for zooming
upperfreq = str2num(get(handles.ZoomUpperFreq,'String')); % Upper frequency for zooming

classified_height = str2num(get(handles.ClassifiedHeight,'String')); % the height of the image in the classified axes
classified_width = str2num(get(handles.ClassifiedWidth,'String'));  % the width of the image in the classified axes

Fs = str2num(get(handles.Frequency,'String')); % Frequency of audio sampling per second

winsizeS = str2num(get(handles.WinSize,'String')) / 1000;
stepS = str2num(get(handles.StepSize,'String')) / 1000;
movingwin = [winsizeS stepS]; % Size of the moving window in seconds; the first number is the window size and the second is the step size

tw = str2num(get(handles.TW,'String'));

fpasslower = str2num(get(handles.MinFreq,'String')); % Range of frequency sampling
fpassupper = str2num(get(handles.MaxFreq,'String'));
fpass = [fpasslower fpassupper];

ierror = 1; % Indicates no errors encountered

if isempty(classified_height) || (classified_height < 1)
    ierror = 0;
end

if isempty(tw) || tw < 0
    ierror = 0;
end

if isempty(lowerfreq) || lowerfreq < 0
    ierror = 0;
end

if isempty(fpasslower) || fpasslower < 0
    ierror = 0;
end

if isempty(fpassupper) || fpassupper < fpasslower
    ierror = 0;
end

if isempty(upperfreq) || lowerfreq > upperfreq
    ierror = 0;
end

if isempty(winsizeS) || winsizeS < 0
    ierror = 0;
end

if isempty(stepS) || stepS < 0
    ierror = 0
end

if isempty(tw) || tw < 0
    ierror = 0
else
    tapers = [tw,floor(2*tw-1)]; % Tapers for smoothing
end

fixed = get(handles.FixedCheckbox,'Value');

if ierror == 0
    ;
else
    handles.output = {lowerfreq,upperfreq,classified_height,classified_width,Fs,movingwin,tapers,fpass,fixed};
    guidata(hObject,handles);
    uiresume(handles.figure1);
end

%uiresume;
%close;

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

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

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

% --- Executes during object creation, after setting all properties.
function StepSize_CreateFcn(hObject, eventdata, handles)
% hObject    handle to StepSize (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
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

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

% --- Executes during object creation, after setting all properties.
function TW_CreateFcn(hObject, eventdata, handles)
% hObject    handle to TW (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
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

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

% --- Executes during object creation, after setting all properties.
function MinFreq_CreateFcn(hObject, eventdata, handles)
% hObject    handle to MinFreq (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
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

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

% --- Executes during object creation, after setting all properties.
function MaxFreq_CreateFcn(hObject, eventdata, handles)
% hObject    handle to MaxFreq (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
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

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

% --- Executes during object creation, after setting all properties.
function ZoomLowerFreq_CreateFcn(hObject, eventdata, handles)
% hObject    handle to ZoomLowerFreq (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
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

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

% --- Executes during object creation, after setting all properties.
function ZoomUpperFreq_CreateFcn(hObject, eventdata, handles)
% hObject    handle to ZoomUpperFreq (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
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

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

% --- Executes during object creation, after setting all properties.
function ClassifiedWidth_CreateFcn(hObject, eventdata, handles)
% hObject    handle to ClassifiedWidth (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
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

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

% --- Executes during object creation, after setting all properties.
function ClassifiedHeight_CreateFcn(hObject, eventdata, handles)
% hObject    handle to ClassifiedHeight (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
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

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

% --- Executes during object creation, after setting all properties.
function Frequency_CreateFcn(hObject, eventdata, handles)
% hObject    handle to Frequency (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
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

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

% Hint: get(hObject,'Value') returns toggle state of FixedCheckbox

handles.fixed = get(hObject,'Value');
guidata(gcbo,handles);


function im = imNameToNum(imname)
	im = str2num(imname(5:8));
end


function varargout = getCobraSolverParams(solverType, paramNames, paramStructure)
% This function gets the specified paramStructure in `paramNames` from
% paramStructure, the global cobra paramters variable or default values set within
% this script.
%
% It will use values with the following priority
% paramStructure > solver type paramStructure > default paramStructure
%
% The specified paramStructure will be delt to the specified output arguements.
% See examples below.
%
% USAGE:
%
%    varargout = getCobraSolverParams(solverType, paramNames, paramStructure)
%
% INPUTS:
%    solverType:    Type of solver used: 'LP', 'MILP', 'QP', 'MIQP'
%    paramNames:    Cell array of strings containing parameter names OR one
%                   parameter name as string
%
% OPTIONAL INPUTS:
%    paramStructure:    Structure with fields pertaining to parameter values that
%                   should be used in place of global or default paramStructure.
%                   paramStructure can be set to 'default' to use the default
%                   values set within this script.
%
% OUTPUTS:
%    varargout:     Variables which each value corresponding to paramNames
%                   is output to.
%                   In addition, if paramStructure is passed as an input, then
%                   the final output argument is paramStructureOut, with fields
%                   removed corresponding to paramNames
%
% EXAMPLE:
%    paramStructure.saveInput = 'LPproblem.mat';
%    paramStructure.printLevel = 1;
%    [printLevel, saveInput] = getCobraSolverParams('LP', {'printLevel', 'saveInput'}, paramStructure);
%
%    %Example using default values
%    [printLevel, saveInput] = getCobraSolverParams('LP', {'printLevel','saveInput'}, 'default');
%
% .. Authors:
%       - Richard Que (12/01/2009)
%       - Ronan (16/07/2013) default MPS paramStructure are no longer global variables

if nargin < 2
    error('getCobraSolverParams: No paramStructure specified')
end

if nargin < 3
    paramStructure = [];
end
if ~isempty(paramStructure)
    paramStructureOut = paramStructure;
end
% Persistence will make names specific to one type of solver.
% Default Values
% For descriptions of the different settings please have a look at
% getCobraSolverParamsOptionsForType
valDef.minNorm = 0;

%These default tolerances are based on the default values for the Gurobi LP solver
%https://www.gurobi.com/documentation/9.0/refman/paramStructure.html
valDef.feasTol = 1e-6; % (primal) feasibility tolerance
valDef.optTol = 1e-6;  % (dual) optimality tolerance

valDef.objTol = 1e-6; % this should be used only when comparing the values of two objective functions

valDef.minNorm = [];

valDef.printLevel = 0;
valDef.verify = 0;

valDef.primalOnly = 0;

valDef.timeLimit = 1e36;
valDef.iterationLimit = 1000;

%valDef.logFile = ['Cobra' solverType 'Solver.log'];
valDef.logFile = []; %log file should be empty to avoid creating it by default
valDef.saveInput = [];
valDef.PbName = [solverType 'problem'];
valDef.debug = 0;
valDef.lifting = 0;

valDef.method = -1;

% CPLEX paramStructure
valDef.DATACHECK = 1;
valDef.DEPIND = 1;
valDef.checkNaN = 0;
valDef.warning = 0;

% tolerances
valDef.intTol = 1e-12;
valDef.relMipGapTol = 1e-12;
valDef.absMipGapTol = 1e-12;
valDef.NUMERICALEMPHASIS = 1;

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

switch solverType
    case 'LP'
        global CBT_LP_PARAMS
        parametersGlobal = CBT_LP_PARAMS;
    case 'QP'
        global CBT_QP_PARAMS
        parametersGlobal = CBT_QP_PARAMS;
    case 'MILP'
        global CBT_MILP_PARAMS
        parametersGlobal = CBT_MILP_PARAMS;
    case 'EP'
        global CBT_EP_PARAMS
        parametersGlobal = CBT_EP_PARAMS;
        valDef.feasTol = 1e-6; % (primal) feasibility tolerance
        valDef.optTol = 1e-6;  % (dual) optimality tolerance
    case 'MIQP'
        global CBT_MIQP_PARAMS
        parametersGlobal = CBT_MIQP_PARAMS;
    case 'NLP'
        global CBT_NLP_PARAMS
        parametersGlobal = CBT_NLP_PARAMS;
    otherwise
        display('Unrecognized solver type')
        return;
end

varargout = cell(1, numel(paramNames));
paramNames = columnVector(paramNames);
for i=1:length(paramNames)
    % set values to default
    if isfield(valDef,paramNames{i})
        varargout{i} = valDef.(paramNames{i});
    end
    if ~strcmp(paramStructure,'default') % skip of using default values
        % set values to global values
        if isfield(parametersGlobal,paramNames{i})
           varargout{i} = parametersGlobal.(paramNames{i});
        end
        % set values to specified values
        if isfield(paramStructure,paramNames{i})
           varargout{i} = paramStructure.(paramNames{i});
           %remove this field so paramStructureOut can be passed directly to the solver, without extra fields
           paramStructureOut = rmfield(paramStructureOut,paramNames{i});
        end
    end
end
if ~isempty(paramStructure)
    varargout{length(paramNames)+1}=paramStructureOut;
end


function toms097 ( )

%*****************************************************************************80
%
%% MAIN is the main program for TOMS097_PRB.
%
%  Discussion:
%
%    TOMS097_PRB tests the TOMS097 library.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    01 March 2014
%
%  Author:
%
%    John Burkardt
%
  timestamp ( );
  fprintf ( 1, '\n' );
  fprintf ( 1, 'TOMS097_PRB\n' );
  fprintf ( 1, '  MATLAB version\n' );
  fprintf ( 1, '  Test the TOMS097 library.\n' );

  toms097_test01 ( );
  toms097_test02 ( );
%
%  Terminate.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'TOMS097_PRB\n' );
  fprintf ( 1, '  Normal end of execution.\n' );
  fprintf ( 1, '\n' );
  timestamp ( );

  return
end