function diginto(thestruct, level)

% DIGINTO  Pretty print entire structure trees.
%   DIGINTO prints the fields tree of all structures in the workspace.
%
%   DIGINTO('all') is the same as DIGINTO.
%
%   DIGINTO(STR) pretty prints the fields' tree of structure STR.

%   Copyright 2008-2009 Joan Sola @ LAAS-CNRS.

if nargin == 0 || strcmp(thestruct,'all')
    disp('Printing all structures in workspace ''base''.')
    w = evalin('base','whos');
    for i = 1:numel(w)
        if strcmp(w(i).class,'struct')
            disp(w(i).name)
            diginto(evalin('base',w(i).name))
        end
    end
    return
end

if nargin < 2
    level = 0;
end
if level == 0
    disp(inputname(1))
end

fn = fieldnames(thestruct);
for n = 1:length(fn)
    tabs = '';
    for m = 0:level
        tabs = [tabs '|   '];
    end
    disp([tabs '.' fn{n}])
    fn2 = thestruct.(fn{n});
    if isstruct(fn2)
        diginto(fn2, level+1);
    end
end

% ========== End of function - Start GPL license ==========

%   # START GPL LICENSE

%---------------------------------------------------------------------
%
%   This file is part of SLAMTB, a SLAM toolbox for Matlab.
%
%   SLAMTB 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.
%
%   SLAMTB 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 SLAMTB.  If not, see <http://www.gnu.org/licenses/>.
%
%---------------------------------------------------------------------

%   SLAMTB is Copyright:
%   Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,
%   Copyright (c) 2010-2013, Joan Sola,
%   Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,
%   SLAMTB is Copyright 2009
%   by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol
%   @ LAAS-CNRS.
%   See on top of this file for its particular copyright.

%   # END GPL LICENSE


function demo(IP)
%while(1)
    [plots,~,~]=ad9361_LTE(IP,'LTE1.4');
    close all;

    delete(plots{1});delete(plots{2});delete(plots{3});delete(plots{4});
    clear functions;
    [plots,~,~]=ad9361_LTE(IP,'LTE3');
    close all;

    delete(plots{1});delete(plots{2});delete(plots{3});delete(plots{4});
    clear functions;
    [plots,~,~]=ad9361_LTE(IP,'LTE5');
    close all;

    delete(plots{1});delete(plots{2});delete(plots{3});delete(plots{4});
    clear functions;
    [plots,~,~]=ad9361_LTE(IP,'LTE10');
    close all;

    delete(plots{1});delete(plots{2});delete(plots{3});delete(plots{4});
    clear functions;
%end


function DOMnode = xml_write(filename, tree, RootName, Pref)
%XML_WRITE  Writes Matlab data structures to XML file
%
% DESCRIPTION
% xml_write( filename, tree) Converts Matlab data structure 'tree' containing
% cells, structs, numbers and strings to Document Object Model (DOM) node
% tree, then saves it to XML file 'filename' using Matlab's xmlwrite
% function. Optionally one can also use alternative version of xmlwrite
% function which directly calls JAVA functions for XML writing without
% MATLAB middleware. This function is provided as a patch to existing
% bugs in xmlwrite (in R2006b).
%
% xml_write(filename, tree, RootName, Pref) allows you to specify
% additional preferences about file format
%
% DOMnode = xml_write([], tree) same as above except that DOM node is
% not saved to the file but returned.
%
% INPUT
%   filename     file name
%   tree         Matlab structure tree to store in xml file.
%   RootName     String with XML tag name used for root (top level) node
%                Optionally it can be a string cell array storing: Name of
%                root node, document "Processing Instructions" data and
%                document "comment" string
%   Pref         Other preferences:
%     Pref.ItemName - default 'item' -  name of a special tag used to
%                     itemize cell or struct arrays
%     Pref.XmlEngine - let you choose the XML engine. Currently default is
%       'Xerces', which is using directly the apache xerces java file.
%       Other option is 'Matlab' which uses MATLAB's xmlwrite and its
%       XMLUtils java file. Both options create identical results except in
%       case of CDATA sections where xmlwrite fails.
%     Pref.CellItem - default 'true' - allow cell arrays to use 'item'
%       notation. See below.
%    Pref.RootOnly - default true - output variable 'tree' corresponds to
%       xml file root element, otherwise it correspond to the whole file.
%     Pref.StructItem - default 'true' - allow arrays of structs to use
%       'item' notation. For example "Pref.StructItem = true" gives:
%
%
%             <item> ... <\item>
%             <item> ... <\item>
%           <\b>
%         <\a>
%       while "Pref.StructItem = false" gives:
%
%            ... <\b>
%            ... <\b>
%         <\a>
%
%
% Several special xml node types can be created if special tags are used
% for field names of 'tree' nodes:
%  - node.CONTENT - stores data section of the node if other fields
%    (usually ATTRIBUTE are present. Usually data section is stored
%    directly in 'node'.
%  - node.ATTRIBUTE.name - stores node's attribute called 'name'.
%  - node.COMMENT - create comment child node from the string. For global
%    comments see "RootName" input variable.
%  - node.PROCESSING_INSTRUCTIONS - create "processing instruction" child
%    node from the string. For global "processing instructions" see
%    "RootName" input variable.
%  - node.CDATA_SECTION - stores node's CDATA section (string). Only works
%    if Pref.XmlEngine='Xerces'. For more info, see comments of F_xmlwrite.
%  - other special node types like: document fragment nodes, document type
%    nodes, entity nodes and notation nodes are not being handled by
%    'xml_write' at the moment.
%
% OUTPUT
%   DOMnode      Document Object Model (DOM) node tree in the format
%                required as input to xmlwrite. (optional)
%
% EXAMPLES:
%   MyTree=[];
%   MyTree.MyNumber = 13;
%   MyTree.MyString = 'Hello World';
%   xml_write('test.xml', MyTree);
%   type('test.xml')
%   %See also xml_tutorial.m
%
% See also
%   xml_read, xmlread, xmlwrite
%
% Written by Jarek Tuszynski, SAIC, jaroslaw.w.tuszynski_at_saic.com

%% Check Matlab Version
v = ver('MATLAB');
v = str2double(regexp(v.Version, '\d.\d','match','once'));
if (v<7)
  error('Your MATLAB version is too old. You need version 7.0 or newer.');
end

%% default preferences
DPref.TableName  = {'tr','td'}; % name of a special tags used to itemize 2D cell arrays
DPref.ItemName   = 'item'; % name of a special tag used to itemize 1D cell arrays
DPref.StructItem = true;  % allow arrays of structs to use 'item' notation
DPref.CellItem   = true;  % allow cell arrays to use 'item' notation
DPref.StructTable= 'Html';
DPref.CellTable  = 'Html';
DPref.XmlEngine  = 'Matlab';  % use matlab provided XMLUtils
%DPref.XmlEngine  = 'Xerces';  % use Xerces xml generator directly
DPref.PreserveSpace = false; % Preserve or delete spaces at the beggining and the end of stings?
RootOnly         = true;  % Input is root node only
GlobalProcInst = [];
GlobalComment  = [];
GlobalDocType  = [];

%% read user preferences
if (nargin>3)
  if (isfield(Pref, 'TableName' )),  DPref.TableName  = Pref.TableName; end
  if (isfield(Pref, 'ItemName'  )), DPref.ItemName   = Pref.ItemName;   end
  if (isfield(Pref, 'StructItem')), DPref.StructItem = Pref.StructItem; end
  if (isfield(Pref, 'CellItem'  )), DPref.CellItem   = Pref.CellItem;   end
  if (isfield(Pref, 'CellTable')),   DPref.CellTable  = Pref.CellTable; end
  if (isfield(Pref, 'StructTable')), DPref.StructTable= Pref.StructTable; end
  if (isfield(Pref, 'XmlEngine' )), DPref.XmlEngine  = Pref.XmlEngine;  end
  if (isfield(Pref, 'RootOnly'  )), RootOnly         = Pref.RootOnly;   end
  if (isfield(Pref, 'PreserveSpace')), DPref.PreserveSpace = Pref.PreserveSpace; end
end
if (nargin<3 || isempty(RootName)), RootName=inputname(2); end
if (isempty(RootName)), RootName='ROOT'; end
if (iscell(RootName)) % RootName also stores global text node data
  rName = RootName;
  RootName = char(rName{1});
  if (length(rName)>1), GlobalProcInst = char(rName{2}); end
  if (length(rName)>2), GlobalComment  = char(rName{3}); end
  if (length(rName)>3), GlobalDocType  = char(rName{4}); end
end
if(~RootOnly && isstruct(tree))  % if struct than deal with each field separatly
  fields = fieldnames(tree);
  for i=1:length(fields)
    field = fields{i};
    x = tree(1).(field);
    if (strcmp(field, 'COMMENT'))
      GlobalComment = x;
    elseif (strcmp(field, 'PROCESSING_INSTRUCTION'))
      GlobalProcInst = x;
    elseif (strcmp(field, 'DOCUMENT_TYPE'))
      GlobalDocType = x;
    else
      RootName = field;
      t = x;
    end
  end
  tree = t;
end

%% Initialize jave object that will store xml data structure
RootName = varName2str(RootName);
if (~isempty(GlobalDocType))
  %   n = strfind(GlobalDocType, ' ');
  %   if (~isempty(n))
  %     dtype = com.mathworks.xml.XMLUtils.createDocumentType(GlobalDocType);
  %   end
  %   DOMnode = com.mathworks.xml.XMLUtils.createDocument(RootName, dtype);
  warning('xml_io_tools:write:docType', ...
    'DOCUMENT_TYPE node was encountered which is not supported yet. Ignoring.');
end
DOMnode = com.mathworks.xml.XMLUtils.createDocument(RootName);

%% Use recursive function to convert matlab data structure to XML
root = DOMnode.getDocumentElement;
struct2DOMnode(DOMnode, root, tree, DPref.ItemName, DPref);

%% Remove the only child of the root node
root   = DOMnode.getDocumentElement;
Child  = root.getChildNodes; % create array of children nodes
nChild = Child.getLength;    % number of children
if (nChild==1)
  node = root.removeChild(root.getFirstChild);
  while(node.hasChildNodes)
    root.appendChild(node.removeChild(node.getFirstChild));
  end
  while(node.hasAttributes)            % copy all attributes
    root.setAttributeNode(node.removeAttributeNode(node.getAttributes.item(0)));
  end
end

%% Save exotic Global nodes
if (~isempty(GlobalComment))
  DOMnode.insertBefore(DOMnode.createComment(GlobalComment), DOMnode.getFirstChild());
end
if (~isempty(GlobalProcInst))
  n = strfind(GlobalProcInst, ' ');
  if (~isempty(n))
    proc = DOMnode.createProcessingInstruction(GlobalProcInst(1:(n(1)-1)),...
      GlobalProcInst((n(1)+1):end));
    DOMnode.insertBefore(proc, DOMnode.getFirstChild());
  end
end
% Not supported yet as the code below does not work
% if (~isempty(GlobalDocType))
%   n = strfind(GlobalDocType, ' ');
%   if (~isempty(n))
%     dtype = DOMnode.createDocumentType(GlobalDocType);
%     DOMnode.insertBefore(dtype, DOMnode.getFirstChild());
%   end
% end

%% save java DOM tree to XML file
if (~isempty(filename))
  if (strcmpi(DPref.XmlEngine, 'Xerces'))
    xmlwrite_xerces(filename, DOMnode);
  else
    xmlwrite(filename, DOMnode);
  end
end

%% =======================================================================
%  === struct2DOMnode Function ===========================================
%  =======================================================================
function [] = struct2DOMnode(xml, parent, s, TagName, Pref)
% struct2DOMnode is a recursive function that converts matlab's structs to
% DOM nodes.
% INPUTS:
%  xml - jave object that will store xml data structure
%  parent - parent DOM Element
%  s - Matlab data structure to save
%  TagName - name to be used in xml tags describing 's'
%  Pref - preferenced
% OUTPUT:
%  parent - modified 'parent'

% perform some conversions
if (ischar(s) && min(size(s))>1) % if 2D array of characters
  s=cellstr(s);                  % than convert to cell array
end
% if (strcmp(TagName, 'CONTENT'))
%   while (iscell(s) && length(s)==1), s = s{1}; end % unwrap cell arrays of length 1
% end
TagName  = varName2str(TagName);

%% == node is a 2D cell array ==
% convert to some other format prior to further processing
nDim = nnz(size(s)>1);  % is it a scalar, vector, 2D array, 3D cube, etc?
if (iscell(s) && nDim==2 && strcmpi(Pref.CellTable, 'Matlab'))
  s = var2str(s, Pref.PreserveSpace);
end
if (nDim==2 && (iscell  (s) && strcmpi(Pref.CellTable,   'Vector')) || ...
               (isstruct(s) && strcmpi(Pref.StructTable, 'Vector')))
  s = s(:);
end
if (nDim>2), s = s(:); end % can not handle this case well
nItem = numel(s);
nDim  = nnz(size(s)>1);  % is it a scalar, vector, 2D array, 3D cube, etc?

%% == node is a cell ==
if (iscell(s)) % if this is a cell or cell array
  if ((nDim==2 && strcmpi(Pref.CellTable,'Html')) || (nDim< 2 && Pref.CellItem))
    % if 2D array of cells than can use HTML-like notation or if 1D array
    % than can use item notation
    if (strcmp(TagName, 'CONTENT')) % CONTENT nodes already have <TagName> ... </TagName>
      array2DOMnode(xml, parent, s, Pref.ItemName, Pref ); % recursive call
    else
      node = xml.createElement(TagName);   % <TagName> ... </TagName>
      array2DOMnode(xml, node, s, Pref.ItemName, Pref ); % recursive call
      parent.appendChild(node);
    end
  else % use  <TagName>...<\TagName> <TagName>...<\TagName> notation
    array2DOMnode(xml, parent, s, TagName, Pref ); % recursive call
  end
%% == node is a struct ==
elseif (isstruct(s))  % if struct than deal with each field separatly
  if ((nDim==2 && strcmpi(Pref.StructTable,'Html')) || (nItem>1 && Pref.StructItem))
    % if 2D array of structs than can use HTML-like notation or
    % if 1D array of structs than can use 'items' notation
    node = xml.createElement(TagName);
    array2DOMnode(xml, node, s, Pref.ItemName, Pref ); % recursive call
    parent.appendChild(node);
  elseif (nItem>1) % use  <TagName>...<\TagName> <TagName>...<\TagName> notation
    array2DOMnode(xml, parent, s, TagName, Pref ); % recursive call
  else % otherwise save each struct separatelly
    fields = fieldnames(s);
    node = xml.createElement(TagName);
    for i=1:length(fields) % add field by field to the node
      field = fields{i};
      x = s.(field);
      switch field
        case {'COMMENT', 'CDATA_SECTION', 'PROCESSING_INSTRUCTION'}
          if iscellstr(x)  % cell array of strings -> add them one by one
            array2DOMnode(xml, node, x(:), field, Pref ); % recursive call will modify 'node'
          elseif ischar(x) % single string -> add it
            struct2DOMnode(xml, node, x, field, Pref ); % recursive call will modify 'node'
          else % not a string - Ignore
            warning('xml_io_tools:write:badSpecialNode', ...
             ['Struct field named ',field,' encountered which was not a string. Ignoring.']);
          end
        case 'ATTRIBUTE' % set attributes of the node
          if (isempty(x)), continue; end
          if (isstruct(x))
            attName = fieldnames(x);       % get names of all the attributes
            for k=1:length(attName)        % attach them to the node
              att = xml.createAttribute(varName2str(attName(k)));
              att.setValue(var2str(x.(attName{k}),Pref.PreserveSpace));
              node.setAttributeNode(att);
            end
          else
            warning('xml_io_tools:write:badAttribute', ...
              'Struct field named ATTRIBUTE encountered which was not a struct. Ignoring.');
          end
        otherwise                            % set children of the node
          struct2DOMnode(xml, node, x, field, Pref ); % recursive call will modify 'node'
      end
    end  % end for i=1:nFields
    parent.appendChild(node);
  end
%% == node is a leaf node ==
else  % if not a struct and not a cell than it is a leaf node
  switch TagName % different processing depending on desired type of the node
    case 'COMMENT'   % create comment node
      com = xml.createComment(s);
      parent.appendChild(com);
    case 'CDATA_SECTION' % create CDATA Section
      cdt = xml.createCDATASection(s);
      parent.appendChild(cdt);
    case 'PROCESSING_INSTRUCTION' % set attributes of the node
      OK = false;
      if (ischar(s))
        n = strfind(s, ' ');
        if (~isempty(n))
          proc = xml.createProcessingInstruction(s(1:(n(1)-1)),s((n(1)+1):end));
          parent.insertBefore(proc, parent.getFirstChild());
          OK = true;
        end
      end
      if (~OK)
        warning('xml_io_tools:write:badProcInst', ...
          ['Struct field named PROCESSING_INSTRUCTION need to be',...
          ' a string, for example: xml-stylesheet type="text/css" ', ...
          'href="myStyleSheet.css". Ignoring.']);
      end
    case 'CONTENT' % this is text part of already existing node
      txt  = xml.createTextNode(var2str(s, Pref.PreserveSpace)); % convert to text
      parent.appendChild(txt);
    otherwise      % I guess it is a regular text leaf node
      txt  = xml.createTextNode(var2str(s, Pref.PreserveSpace));
      node = xml.createElement(TagName);
      node.appendChild(txt);
      parent.appendChild(node);
  end
end % of struct2DOMnode function

%% =======================================================================
%  === array2DOMnode Function ============================================
%  =======================================================================
function [] = array2DOMnode(xml, parent, s, TagName, Pref)
% Deal with 1D and 2D arrays of cell or struct. Will modify 'parent'.
nDim = nnz(size(s)>1);  % is it a scalar, vector, 2D array, 3D cube, etc?
switch nDim
  case 2 % 2D array
    for r=1:size(s,1)
      subnode = xml.createElement(Pref.TableName{1});
      for c=1:size(s,2)
        v = s(r,c);
        if iscell(v), v = v{1}; end
        struct2DOMnode(xml, subnode, v, Pref.TableName{2}, Pref ); % recursive call
      end
      parent.appendChild(subnode);
    end
  case 1 %1D array
    for iItem=1:numel(s)
      v = s(iItem);
      if iscell(v), v = v{1}; end
      struct2DOMnode(xml, parent, v, TagName, Pref ); % recursive call
    end
  case 0 % scalar -> this case should never be called
    if ~isempty(s)
      if iscell(s), s = s{1}; end
      struct2DOMnode(xml, parent, s, TagName, Pref );
    end
end

%% =======================================================================
%  === var2str Function ==================================================
%  =======================================================================
function str = var2str(object, PreserveSpace)
% convert matlab variables to a string
switch (1)
  case isempty(object)
    str = '';
  case (isnumeric(object) || islogical(object))
    if ndims(object)>2, object=object(:); end  % can't handle arrays with dimention > 2
    str=mat2str(object);           % convert matrix to a string
    % mark logical scalars with [] (logical arrays already have them) so the xml_read
    % recognizes them as MATLAB objects instead of strings. Same with sparse
    % matrices
    if ((islogical(object) && isscalar(object)) || issparse(object)),
      str = ['[' str ']'];
    end
    if (isinteger(object)),
      str = ['[', class(object), '(', str ')]'];
    end
  case iscell(object)
    if ndims(object)>2, object=object(:); end  % can't handle cell arrays with dimention > 2
    [nr nc] = size(object);
    obj2 = object;
    for i=1:length(object(:))
      str = var2str(object{i}, PreserveSpace);
      if (ischar(object{i})), object{i} = ['''' object{i} '''']; else object{i}=str; end
      obj2{i} = [object{i} ','];
    end
    for r = 1:nr, obj2{r,nc} = [object{r,nc} ';']; end
    obj2 = obj2.';
    str = ['{' obj2{:} '}'];
  case isstruct(object)
    str='';
    warning('xml_io_tools:write:var2str', ...
      'Struct was encountered where string was expected. Ignoring.');
  case isa(object, 'function_handle')
    str = ['[@' char(object) ']'];
  case ischar(object)
    str = object;
  otherwise
    str = char(object);
end

%% string clean-up
str=str(:); str=str.';            % make sure this is a row vector of char's
if (~isempty(str))
  str(str<32|str==127)=' ';       % convert no-printable characters to spaces
  if (~PreserveSpace)
    str = strtrim(str);             % remove spaces from begining and the end
    str = regexprep(str,'\s+',' '); % remove multiple spaces
  end
end

%% =======================================================================
%  === var2Namestr Function ==============================================
%  =======================================================================
function str = varName2str(str)
% convert matlab variable names to a sting
str = char(str);
p   = strfind(str,'0x');
if (~isempty(p))
  for i=1:length(p)
    before = str( p(i)+(0:3) );          % string to replace
    after  = char(hex2dec(before(3:4))); % string to replace with
    str = regexprep(str,before,after, 'once', 'ignorecase');
    p=p-3; % since 4 characters were replaced with one - compensate
  end
end
str = regexprep(str,'_COLON_',':', 'once', 'ignorecase');
str = regexprep(str,'_DASH_' ,'-', 'once', 'ignorecase');


function prepareDeepPerFrameFtrsCompiled(moviefilename,trackfilename,stationary,MCRloc,tempdir,maxcores)

% function prepareDeepPerFrameFtrsCompiled(moviefilename,trackfilename,stationary,maxcores)
setup;
usedeep = true;
method = 'deep-sup';
flowname = 'DS';

if ~exist(maxcores,'var')
  totcores = features('numcores');
  if totcores>10,
    maxcores = totcores-4;
  else
    maxcores = totcores-1;
  end
end
gparams = getParams;
[readfcn,nframes,fid,headerinfo] = get_readframe_fcn(moviename);

nblocks = ceil(nframes/gparams.blocksize);
expdir = fileparts(moviefilename);
[~,expname] = fileparts(expdir);
tempname = fullfile(tempdir,expname);
partcmd = sprintf('%s %s %s %s %d deep-sup ',...
  'computeFeaturesCompiled/for_testing/run_computeFeaturesCompiled.sh',...
  MCRloc,moviefilename,trackfilename,stationary);


suite = matlab.unittest.TestSuite.fromFolder(pwd);
suite.run;


function [ text ] = tapas_BLT_initVisuals(params)
% tapas_BLT_initVisuals initializes Textures for all task relevant images
%
% Inputs:
%   params: data storage file
%
% Outputs:
%	text: image textures
%

% Set prediction cue images according to experiment mode and cue type
switch params.expMode
    case {'train_4', 'train_6'}
        if params.cuetype ==  1
            params.stimuli.cue1         = fullfile(params.path.imgfolder,'cue3_predYL_img.png');
            params.stimuli.cue1Scale    = fullfile(params.path.imgfolder,'cue3_predScale.png');
            params.stimuli.cue1SL       = fullfile(params.path.imgfolder,'cue3_predYL_selL_img.png');
            params.stimuli.cue1SR       = fullfile(params.path.imgfolder,'cue3_predYL_selR_img.png');
            params.stimuli.cue2         = fullfile(params.path.imgfolder,'cue4_predYL_img.png');
            params.stimuli.cue2Scale    = fullfile(params.path.imgfolder,'cue4_predScale.png');
            params.stimuli.cue2SL       = fullfile(params.path.imgfolder,'cue4_predYL_selL_img.png');
            params.stimuli.cue2SR       = fullfile(params.path.imgfolder,'cue4_predYL_selR_img.png');
        elseif params.cuetype ==  2
            params.stimuli.cue1         = fullfile(params.path.imgfolder,'cue3_predYR_img.png');
            params.stimuli.cue1Scale    = fullfile(params.path.imgfolder,'cue3_predScale.png');
            params.stimuli.cue1SL       = fullfile(params.path.imgfolder,'cue3_predYR_selL_img.png');
            params.stimuli.cue1SR       = fullfile(params.path.imgfolder,'cue3_predYR_selR_img.png');
            params.stimuli.cue2         = fullfile(params.path.imgfolder,'cue4_predYR_img.png');
            params.stimuli.cue2Scale    = fullfile(params.path.imgfolder,'cue4_predScale.png');
            params.stimuli.cue2SL       = fullfile(params.path.imgfolder,'cue4_predYR_selL_img.png');
            params.stimuli.cue2SR       = fullfile(params.path.imgfolder,'cue4_predYR_selR_img.png');
        elseif params.cuetype ==  3
            params.stimuli.cue1         = fullfile(params.path.imgfolder,'cue4_predYL_img.png');
            params.stimuli.cue1Scale    = fullfile(params.path.imgfolder,'cue4_predScale.png');
            params.stimuli.cue1SL       = fullfile(params.path.imgfolder,'cue4_predYL_selL_img.png');
            params.stimuli.cue1SR       = fullfile(params.path.imgfolder,'cue4_predYL_selR_img.png');
            params.stimuli.cue2         = fullfile(params.path.imgfolder,'cue3_predYL_img.png');
            params.stimuli.cue2Scale    = fullfile(params.path.imgfolder,'cue3_predScale.png');
            params.stimuli.cue2SL       = fullfile(params.path.imgfolder,'cue3_predYL_selL_img.png');
            params.stimuli.cue2SR       = fullfile(params.path.imgfolder,'cue3_predYL_selR_img.png');
        elseif params.cuetype ==  4
            params.stimuli.cue1         = fullfile(params.path.imgfolder,'cue4_predYR_img.png');
            params.stimuli.cue1Scale    = fullfile(params.path.imgfolder,'cue4_predScale.png');
            params.stimuli.cue1SL       = fullfile(params.path.imgfolder,'cue4_predYR_selL_img.png');
            params.stimuli.cue1SR       = fullfile(params.path.imgfolder,'cue4_predYR_selR_img.png');
            params.stimuli.cue2         = fullfile(params.path.imgfolder,'cue3_predYR_img.png');
            params.stimuli.cue2Scale    = fullfile(params.path.imgfolder,'cue3_predScale.png');
            params.stimuli.cue2SL       = fullfile(params.path.imgfolder,'cue3_predYR_selL_img.png');
            params.stimuli.cue2SR       = fullfile(params.path.imgfolder,'cue3_predYR_selR_img.png');
        end
    case {'task', 'debug'}
        if params.cuetype ==  1
            params.stimuli.cue1         = fullfile(params.path.imgfolder,'cue1_predYL_img.png');
            params.stimuli.cue1Scale    = fullfile(params.path.imgfolder,'cue1_predScale.png');
            params.stimuli.cue1SL       = fullfile(params.path.imgfolder,'cue1_predYL_selL_img.png');
            params.stimuli.cue1SR       = fullfile(params.path.imgfolder,'cue1_predYL_selR_img.png');
            params.stimuli.cue2         = fullfile(params.path.imgfolder,'cue2_predYL_img.png');
            params.stimuli.cue2Scale    = fullfile(params.path.imgfolder,'cue2_predScale.png');
            params.stimuli.cue2SL       = fullfile(params.path.imgfolder,'cue2_predYL_selL_img.png');
            params.stimuli.cue2SR       = fullfile(params.path.imgfolder,'cue2_predYL_selR_img.png');
        elseif params.cuetype ==  2
            params.stimuli.cue1         = fullfile(params.path.imgfolder,'cue1_predYR_img.png');
            params.stimuli.cue1Scale    = fullfile(params.path.imgfolder,'cue1_predScale.png');
            params.stimuli.cue1SL       = fullfile(params.path.imgfolder,'cue1_predYR_selL_img.png');
            params.stimuli.cue1SR       = fullfile(params.path.imgfolder,'cue1_predYR_selR_img.png');
            params.stimuli.cue2         = fullfile(params.path.imgfolder,'cue2_predYR_img.png');
            params.stimuli.cue2Scale    = fullfile(params.path.imgfolder,'cue2_predScale.png');
            params.stimuli.cue2SL       = fullfile(params.path.imgfolder,'cue2_predYR_selL_img.png');
            params.stimuli.cue2SR       = fullfile(params.path.imgfolder,'cue2_predYR_selR_img.png');
        elseif params.cuetype ==  3
            params.stimuli.cue1         = fullfile(params.path.imgfolder,'cue2_predYL_img.png');
            params.stimuli.cue1Scale    = fullfile(params.path.imgfolder,'cue2_predScale.png');
            params.stimuli.cue1SL       = fullfile(params.path.imgfolder,'cue2_predYL_selL_img.png');
            params.stimuli.cue1SR       = fullfile(params.path.imgfolder,'cue2_predYL_selR_img.png');
            params.stimuli.cue2         = fullfile(params.path.imgfolder,'cue1_predYL_img.png');
            params.stimuli.cue2Scale    = fullfile(params.path.imgfolder,'cue1_predScale.png');
            params.stimuli.cue2SL       = fullfile(params.path.imgfolder,'cue1_predYL_selL_img.png');
            params.stimuli.cue2SR       = fullfile(params.path.imgfolder,'cue1_predYL_selR_img.png');
        elseif params.cuetype ==  4
            params.stimuli.cue1         = fullfile(params.path.imgfolder,'cue2_predYR_img.png');
            params.stimuli.cue1Scale    = fullfile(params.path.imgfolder,'cue2_predScale.png');
            params.stimuli.cue1SL       = fullfile(params.path.imgfolder,'cue2_predYR_selL_img.png');
            params.stimuli.cue1SR       = fullfile(params.path.imgfolder,'cue2_predYR_selR_img.png');
            params.stimuli.cue2         = fullfile(params.path.imgfolder,'cue1_predYR_img.png');
            params.stimuli.cue2Scale    = fullfile(params.path.imgfolder,'cue1_predScale.png');
            params.stimuli.cue2SL       = fullfile(params.path.imgfolder,'cue1_predYR_selL_img.png');
            params.stimuli.cue2SR       = fullfile(params.path.imgfolder,'cue1_predYR_selR_img.png');
        end
end

% Set stimulus answer images according to cue type
if params.cuetype ==  1 || params.cuetype ==  3
    params.stimuli.stimAnswer           = fullfile(params.path.imgfolder,'stimAnsYL_img.png');
    params.stimuli.stimAnswerSL         = fullfile(params.path.imgfolder,'stimAnsYL_selL_img.png');
    params.stimuli.stimAnswerSR         = fullfile(params.path.imgfolder,'stimAnsYL_selR_img.png');
elseif params.cuetype == 2 || params.cuetype ==  4
    params.stimuli.stimAnswer           = fullfile(params.path.imgfolder,'stimAnsYR_img.png');
    params.stimuli.stimAnswerSL         = fullfile(params.path.imgfolder,'stimAnsYR_selL_img.png');
    params.stimuli.stimAnswerSR         = fullfile(params.path.imgfolder,'stimAnsYR_selR_img.png');
end

% Add extra images
params.stimuli.predtimeout      = fullfile(params.path.imgfolder,'pred_timeout_img.png');
params.stimuli.prednoresponse   = fullfile(params.path.imgfolder,'pred_noResponse.png');
params.stimuli.stimulation      = fullfile(params.path.imgfolder,'stimulation.png');
params.stimuli.iti              = fullfile(params.path.imgfolder,'iti.png');
params.stimuli.break            = fullfile(params.path.imgfolder,'break.png');
params.stimuli.ratetimeout      = fullfile(params.path.imgfolder,'rate_timeout.png');
params.stimuli.endfieldmap      = fullfile(params.path.imgfolder,'endfieldmap.png');
params.stimuli.endfinal         = fullfile(params.path.imgfolder,'endfinal.png');

for i = 1:params.nIntroTrain
    params.stimuli.introTrain{i}  = fullfile(params.path.imgfolder,['Slide',num2str(i),'.png']);
    imgIntroTrain = imread(params.stimuli.introTrain{i});
    text.IntroTrain{i} = Screen('MakeTexture', params.screen.window, imgIntroTrain);
end

for i2 = 1:params.nIntroMain
    params.stimuli.introMain{i2}  = fullfile(params.path.imgfolder,['Slide',num2str(i+i2),'.png']);
    imgIntroMain = imread(params.stimuli.introMain{i2});
    text.IntroMain{i2} = Screen('MakeTexture', params.screen.window, imgIntroMain);
end

% read images
imgcue1                         = imread(params.stimuli.cue1);
imgcue2                         = imread(params.stimuli.cue2);
imgcue1Scale                    = imread(params.stimuli.cue1Scale);
imgcue2Scale                    = imread(params.stimuli.cue2Scale);
imgcue1SL                       = imread(params.stimuli.cue1SL);
imgcue1SR                       = imread(params.stimuli.cue1SR);
imgcue2SL                       = imread(params.stimuli.cue2SL);
imgcue2SR                       = imread(params.stimuli.cue2SR);
imgpredtimeout                  = imread(params.stimuli.predtimeout);
imgprednoresponse               = imread(params.stimuli.prednoresponse);
imgstimulation                  = imread(params.stimuli.stimulation);
imgstimanswer                   = imread(params.stimuli.stimAnswer);
imgstimanswerSL                 = imread(params.stimuli.stimAnswerSL);
imgstimanswerSR                 = imread(params.stimuli.stimAnswerSR);
imgiti                          = imread(params.stimuli.iti);
imgbreak                        = imread(params.stimuli.break);
imgratetimeout                  = imread(params.stimuli.ratetimeout);
imgendfieldmap                  = imread(params.stimuli.endfieldmap);
imgendfinal                     = imread(params.stimuli.endfinal);

% Make the images into a textures that can be drawn to the screen
text.imgcue1              = Screen('MakeTexture', params.screen.window, imgcue1);
text.imgcue2              = Screen('MakeTexture', params.screen.window, imgcue2);
text.imgcue1Scale         = Screen('MakeTexture', params.screen.window, imgcue1Scale);
text.imgcue2Scale         = Screen('MakeTexture', params.screen.window, imgcue2Scale);
text.imgcue1SL            = Screen('MakeTexture', params.screen.window, imgcue1SL);
text.imgcue1SR            = Screen('MakeTexture', params.screen.window, imgcue1SR);
text.imgcue2SL            = Screen('MakeTexture', params.screen.window, imgcue2SL);
text.imgcue2SR            = Screen('MakeTexture', params.screen.window, imgcue2SR);
text.imgpredtimeout       = Screen('MakeTexture', params.screen.window, imgpredtimeout);
text.imgprednoresponse    = Screen('MakeTexture', params.screen.window, imgprednoresponse);
text.imgstimulation       = Screen('MakeTexture', params.screen.window, imgstimulation);
text.imgstimanswer        = Screen('MakeTexture', params.screen.window, imgstimanswer);
text.imgstimanswerSL      = Screen('MakeTexture', params.screen.window, imgstimanswerSL);
text.imgstimanswerSR      = Screen('MakeTexture', params.screen.window, imgstimanswerSR);
text.imgiti               = Screen('MakeTexture', params.screen.window, imgiti);
text.imgbreak             = Screen('MakeTexture', params.screen.window, imgbreak);
text.imgratetimeout       = Screen('MakeTexture', params.screen.window, imgratetimeout);
text.endfieldmap          = Screen('MakeTexture', params.screen.window, imgendfieldmap);
text.endfinal             = Screen('MakeTexture', params.screen.window, imgendfinal);
end


function repos = TestRepoList
    % TestRepoList. An example list of repositories for use with DepMatUpdate
    %
    %
    %
    %     Licence
    %     -------
    %     Part of DepMat. https://github.com/tomdoel/depmat
    %     Author: Tom Doel, 2015.  www.tomdoel.com
    %     Distributed under the MIT licence. Please see website for details.
    %

    repos = DepMatRepo.empty;
    repos(end + 1) = DepMatRepo('coremat', 'master', 'https://github.com/tomdoel/coremat.git', 'coremat_master');
    repos(end + 1) = DepMatRepo('dicomat', 'master', 'https://github.com/tomdoel/dicomat.git', 'dicomat_master');
    repos(end + 1) = DepMatRepo('matnat', 'master', 'https://github.com/tomdoel/matnat.git', 'matnat_master');
end


function printDecodeResults(decodeData, candidates, candScores, alignInfo, otherInfo, params, isOutput)
  batchSize = size(candScores, 2);
  startId = decodeData.startId;

  % output translations
  [maxScores, bestIndices] = max(candScores, [], 1); % stackSize * batchSize
  for ii = 1:batchSize
    bestId = bestIndices(ii);
    translation = candidates{ii}{bestId};
    assert(isempty(find(translation>params.tgtVocabSize, 1)));

    if isOutput
      if params.forceDecoder
        printSent(params.fid, otherInfo.forceDecodeOutputs(1:decodeData.tgtLens(ii)-1, ii), params.tgtVocab, '');
      else
        printSent(params.fid, translation(1:end-1), params.tgtVocab, ''); % remove <t_eos>
      end
      if params.charTgtGen
        printSentChar(params.charFid, translation(1:end-1), params.tgtVocab, '', otherInfo.rarePositions{ii}, otherInfo.rareWords{ii}); % remove <t_eos>
      end
    end

    % log
    printSrc(params.logId, decodeData, ii, params, startId+ii-1);
    printRef(params.logId, decodeData, ii, params, startId+ii-1);
    printSent(params.logId, translation, params.tgtVocab, ['  tgt ' num2str(startId+ii-1) ': ']);
    if params.charTgtGen
      printSentChar(params.logId, translation, params.tgtVocab, ['  tgt char' num2str(startId+ii-1) ': '], otherInfo.rarePositions{ii}, otherInfo.rareWords{ii});
    end
    % align
    if params.align
      alignment = alignInfo{ii}{bestId};
      printAlign(params.logId, translation, decodeData, alignment, params, ii, startId+ii-1, 1);
      if isOutput
        printSentAlign(params.alignId, translation, decodeData, alignment, ii, params);
      end
    end
    fprintf(params.logId, '  score %g\n', maxScores(ii));

    % debug
    printSrc(2, decodeData, ii, params, startId+ii-1);
    printRef(2, decodeData, ii, params, startId+ii-1);
    printSent(2, translation, params.tgtVocab, ['  tgt ' num2str(startId+ii-1) ': ']);
    if params.forceDecoder
      printSent(2, otherInfo.forceDecodeOutputs(1:decodeData.tgtLens(ii)-1, ii), params.tgtVocab, ['  fdc ' num2str(startId+ii-1) ': ']);
    end
    if params.charTgtGen
      printSentChar(2, translation, params.tgtVocab, ['  tgt char ' num2str(startId+ii-1) ': '], otherInfo.rarePositions{ii}, otherInfo.rareWords{ii});

      % check that no words are </c_s>
      assert(isempty(find(strcmp(otherInfo.rareWords{ii}, params.tgtCharVocab{params.tgtCharEos}), 1)));
    end

    % align
    if params.align
      printAlign(2, translation, decodeData, alignment, params, ii, startId+ii-1, 1);
    end
    fprintf(2, '  score %g\n', maxScores(ii));
  end
end

function printSentAlign(fid, translation, data, alignment, ii, params)
  srcLen = data.srcLens(ii);
  if params.isReverse
    alignment = srcLen-alignment;
  end

  tgtLen = length(translation);
  for i = 1:(tgtLen-1)
    srcPos = alignment(i+1);
    assert((1 <= srcPos) && (srcPos <= srcLen), sprintf('Assertion failed: srcPos = %d, srcLen = %d', srcPos, srcLen));
    fprintf(fid, '%d-%d ', srcPos-1, i-1); % base 0
  end
  fprintf(fid, '\n');
end

function printAlign(fid, translation, data, alignment, params, ii, sentId, printWords)
  mask = data.srcMask(ii, :);
  srcLen = data.srcLens(ii);

  if params.isReverse
    alignment = srcLen-alignment;
  end

  tgtLen = length(translation);
  if printWords
    src = data.srcInput(ii,mask);
    if params.isReverse
      src = src(end:-1:1);
    end
    fprintf(fid, 'pairs %d: ', sentId);
    for i = 1:(tgtLen-1)
      srcPos = alignment(i+1);
      assert((1 <= srcPos) && (srcPos <= srcLen), sprintf('Assertion failed: srcPos = %d, srcLen = %d', srcPos, srcLen));
      fprintf(fid, '%s-%s ', params.srcVocab{src(srcPos)}, params.tgtVocab{translation(i)});
    end
    fprintf(fid, '\n');
  end

  fprintf(fid, 'align %d: ', sentId);
  for i = 1:(tgtLen-1)
    srcPos = alignment(i+1);
    assert((1 <= srcPos) && (srcPos <= srcLen));
    fprintf(fid, '%d-%d ', srcPos-1, i-1); % base 0
  end
  fprintf(fid, '\n');

end

function printSrc(fid, data, ii, params, sentId)
  mask = data.srcMask(ii,:);
  src = data.srcInput(ii,mask);
  printSent(fid, src, params.srcVocab, ['  src ' num2str(sentId) ': ']);

  if params.isReverse
    printSent(fid, src(end:-1:1), params.srcVocab, [' rsrc ' num2str(sentId) ': ']);
  end
end

function printRef(fid, data, ii, params, sentId)
  mask = data.tgtMask(ii, :);
  ref = data.tgtOutput(ii,mask);
  printSent(fid, ref, params.tgtVocab, ['  ref ' num2str(sentId) ': ']);
end


%-----------------------------------------------------------------------
% Job saved on 18-Jul-2014 13:13:47 by cfg_util (rev $Rev$)
% spm SPM - SPM12b (5672)
% cfg_basicio BasicIO - Unknown
%-----------------------------------------------------------------------
matlabbatch{1}.spm.spatial.coreg.write.ref = '<UNDEFINED>';
matlabbatch{1}.spm.spatial.coreg.write.source = '<UNDEFINED>';
matlabbatch{1}.spm.spatial.coreg.write.roptions.interp = 7;
matlabbatch{1}.spm.spatial.coreg.write.roptions.wrap = [0 0 0];
matlabbatch{1}.spm.spatial.coreg.write.roptions.mask = 0;
matlabbatch{1}.spm.spatial.coreg.write.roptions.prefix = 'r';


function [success ips] = genInterestPoints(moviename,varargin)

[ipnames,doaskleftright] = myparse(varargin,'ipnames',{'food','mouth','perch'},...
  'doaskleftright',true);

annObj = HandleObj; % handle obj to store annotation info
hFig = playfmf('moviename',moviename,'annDataObj',annObj,'ipnames',ipnames,'doaskleftright',doaskleftright);
waitfor(hFig);
if isempty(annObj.data)
  success = false;
  ips = [];
  return;
end

fprintf(1,'Interest points generated:\n');
disp(annObj.data);

ips = struct();
for i = 1:numel(ipnames),
  ips.(ipnames{i}) = annObj.data.(ipnames{i});
end
if doaskleftright
  ips.face = annObj.data.lr;
end
success = true;


function [success] = downsampleHdf5Movie(inputFilePath, varargin)
	% Downsamples the Hdf5 movie in inputFilePath piece by piece and appends it to already created hdf5 file.
	% Biafra Ahanonu
	% started: 2013.12.19
	% base append code based on work by Dinesh Iyer (http://www.mathworks.com/matlabcentral/newsreader/author/130530)
	% note: checked between this implementation and imageJ's scale, they are nearly identical (subtracted histogram mean is 1 vs each image mean of ~1860, so assuming precision error).
	% inputs
		% inputFilePath
	% options
		% datasetName = hierarchy where data is stored in HDF5 file

	[success] = ciapkg.hdf5.downsampleHdf5Movie(inputFilePath,'passArgs', varargin);
end


% icadefs() - function to read in a set of EEGLAB system-wide (i.e. lab-wide)
%             or working directory-wide constants and preferences. Change the
%             way these are defined in the master icadefs.m file (usually
%             in dir eeglab/functions/sigprocfunc) or make a custom copy of
%             the icadefs.m file in a project directory. Then, calling functions
%             that call icadefs from an EEGLAB session in that working directory
%             will read the local copy, which may set preferences different from
%             the system-wide copy.
%
% Author: Arnaud Delorme, Scott Makeig, SCCN/INC/UCSD, La Jolla, 05-20-97

% Copyright (C) 05-20-97 Scott Makeig, SCCN/INC/UCSD, scott@sccn.ucsd.edu
%
% 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  USA

% ----------------------------------------------------------------------
% ------ EEGLAB DEFINITION - YOU MAY CHANGE THE TEXT BELOW -------------
% ----------------------------------------------------------------------

EEGOPTION_PATH = ''; % if empty, the home folder of the current user is used
                     % Note that this may create problems under Windows
                     % when unicode characters are part of the user name
                     % In this case, enter the path name manually here.

YDIR  = 1;                  % positive potential up = 1; negative up = -1
                            % for most ERP plots

HZDIR = 'up';               % ascending freqs = 'up'; descending = 'down'
                            % (e.g., timef/newtimef frequency direction)

% Checking MATLAB version
tmpvers = version;
indp = find(tmpvers == '.');
if str2num(tmpvers(indp(1)+1)) >= 1, tmpvers = [ tmpvers(1:indp(1)) '0' tmpvers(indp(1)+1:end) ]; end
indp = find(tmpvers == '.');
VERS = str2num(tmpvers(1:indp(2)-1));

% font size
tmpComputer   = computer;
tmpScreenSize = get(0, 'ScreenSize');

% Graph Definitions
DEFAULT_COLORMAP = 'jet';

if VERS < 8.04
    PLOT_LINEWIDTH   = 2;
    PLOT_LINEWIDTH_S = 1;

    % AXES FONTSIZE
    AXES_FONTSIZE   = 10;                % Axis labels and legend font size
    AXES_FONTSIZE_S = AXES_FONTSIZE - 2; % Axis labels and legend font size Small
    AXES_FONTSIZE_L = 16;                % Axis labels and legend font size Large

    % GUI FONTSIZE
    GUI_FONTSIZE    = 10;               % graphic interface font size
    GUI_FONTSIZE_S  = GUI_FONTSIZE - 2; % graphic interface font size Small
    GUI_FONTSIZE_L  = GUI_FONTSIZE + 2; % graphic interface font size Large

    % TEXT FONTSIZE
    TEXT_FONTSIZE = 10;                  % Miscellaneous font sizes
    TEXT_FONTSIZE_S = TEXT_FONTSIZE - 2; % Miscellaneous font sizes Small
    TEXT_FONTSIZE_L = TEXT_FONTSIZE + 2; % Miscellaneous font sizes Large

elseif VERS >= 8.04

    if strcmpi(tmpComputer(1:3), 'MAC')

        PLOT_LINEWIDTH   = 1;
        PLOT_LINEWIDTH_S = 0.5;

        %scale up fontsizes on higher resolution mac screens
        retinaDisplay = false;
        if tmpScreenSize(3) >= 1920 % bump fontsize only for the highest retina res settings
            retinaDisplay = true; %comment this out if you don't want fontsizes increased at high display resolutions
            %disp('Mac OSX retina display detected. If this is not desired comment out line 83 of icadefs.m');
        end

        % AXES FONTSIZE
        if retinaDisplay
          AXES_FONTSIZE   = 12;                 % Axis labels and legend font size
        else
          AXES_FONTSIZE   = 9;                 % Axis labels and legend font size
        end
        AXES_FONTSIZE_S = AXES_FONTSIZE - 2; % Axis labels and legend font size Small
        AXES_FONTSIZE_L = 12.5;              % Axis labels and legend font size Large

        % GUI FONTSIZE
        if retinaDisplay
          GUI_FONTSIZE    = 14;                % graphic interface font size
        else
          GUI_FONTSIZE    = 12;                % graphic interface font size
        end
        GUI_FONTSIZE_S  = GUI_FONTSIZE - 2; % graphic interface font size Small
        GUI_FONTSIZE_L  = GUI_FONTSIZE + 2; % graphic interface font size Large

        % TEXT FONTSIZE
        if retinaDisplay
          TEXT_FONTSIZE   = 14;                 % Miscellaneous font sizes
        else
          TEXT_FONTSIZE   = 12;                 % Miscellaneous font sizes
        end
        TEXT_FONTSIZE_S = TEXT_FONTSIZE - 2; % Miscellaneous font sizes Small
        TEXT_FONTSIZE_L = TEXT_FONTSIZE + 4; % Miscellaneous font sizes Large
    else
        PLOT_LINEWIDTH   = 1;
        PLOT_LINEWIDTH_S = 0.5;

        % AXES FONTSIZE
        AXES_FONTSIZE   = 9;                 % Axis labels and legend font size
        AXES_FONTSIZE_S = AXES_FONTSIZE - 2; % Axis labels and legend font size Small
        AXES_FONTSIZE_L = 12.5;              % Axis labels and legend font size Large

        % GUI FONTSIZE
        GUI_FONTSIZE    = 10;                % graphic interface font size
        GUI_FONTSIZE_S  = GUI_FONTSIZE - 2; % graphic interface font size Small
        GUI_FONTSIZE_L  = GUI_FONTSIZE + 2; % graphic interface font size Large

        % TEXT FONTSIZE
        TEXT_FONTSIZE   = 10;                 % Miscellaneous font sizes
        TEXT_FONTSIZE_S = TEXT_FONTSIZE - 2; % Miscellaneous font sizes Small
        TEXT_FONTSIZE_L = TEXT_FONTSIZE + 4; % Miscellaneous font sizes Large
    end
end

clear retinaDisplay tmpScreenSize tmpComputer tmpvers indp;

% the eeg_options.m file also countains additional options

% ----------------------------------------------------------------------
% ------------------------ END OF DEFINITIONS --------------------------
% ----------------------------------------------------------------------

% INSERT location of ica executable (UNIX ONLY) for binica.m below
if ~isdeployed
    eeglab_p = fileparts(which('eeglab'));
    ICABINARY = fullfile(eeglab_p, 'functions', 'resources', 'ica_linux');
    tmpComputer = computer;
    if strcmpi(tmpComputer(1:3), 'MAC')
        ICABINARY = fullfile(eeglab_p, 'functions', 'resources', 'ica_osx_intel_64');
        clear tmpComputer
    end
else
    ICABINARY = fullfile(ctfroot, 'ica_linux');
end

try
    set(0,'defaultaxesfontsize',AXES_FONTSIZE);
    set(0,'defaulttextfontsize',TEXT_FONTSIZE);
    set(0,'DefaultUicontrolFontSize',GUI_FONTSIZE);
catch
    % most likely Octave here
end

TUTORIAL_URL = 'http://sccn.ucsd.edu/wiki/EEGLAB'; % online version
DEFAULT_SRATE = 256.0175;      % default local sampling rate (rarely used)
DEFAULT_TIMLIM = [-1000 2000]; % default local epoch limits (ms)

% Set EEGLAB figure and GUI colors
% --------------------------------
lowscreendepth = 0;
if ~exist('OCTAVE_VERSION')
    if get(0, 'screendepth') <=8 % if mono or 8-bit color
	lowscreendepth = 1;
    end
end
if lowscreendepth
    %fprintf('icadefs(): Setting display parameters for mono or 8-bit color\n');
    BACKCOLOR           = [1 1 1];    % Background figure color
    BACKEEGLABCOLOR     = [1 1 1];    % EEGLAB main window background
    GUIBUTTONCOLOR      = [1 1 1];    % Buttons colors in figures
    GUIPOPBUTTONCOLOR   = [1 1 1];    % Buttons colors in GUI windows
    GUIBACKCOLOR        = [1 1 1];    % GUI background color
    GUITEXTCOLOR        = [0 0 0];      % GUI foreground color for text
    PLUGINMENUCOLOR     = [.5 0 .5];  % plugin menu color

else % if full color screen
    BACKCOLOR           = [.93 .96 1];    % EEGLAB Background figure color
    BACKEEGLABCOLOR     = [.66 .76 1];    % EEGLAB main window background
    GUIBUTTONCOLOR      = BACKEEGLABCOLOR;% Buttons colors in figures
    GUIPOPBUTTONCOLOR   = BACKCOLOR;      % Buttons colors in GUI windows
    GUIBACKCOLOR        = BACKEEGLABCOLOR;% EEGLAB GUI background color <---------
    GUITEXTCOLOR        = [0 0 0.4];      % GUI foreground color for text
    PLUGINMENUCOLOR     = [.5 0 .5];      % plugin menu color
end

% THE FOLLOWING PARAMETERS WILL BE DEPRECATED IN LATER VERSIONS
% -------------------------------------------------------------

SHRINKWARNING = 1;          % Warn user about the shrink factor in topoplot() (1/0)

MAXENVPLOTCHANS   = 264;  % maximum number of channels to plot in envproj.m
MAXPLOTDATACHANS  = 264;  % maximum number of channels to plot in dataplot.m
MAXPLOTDATAEPOCHS = 264;  % maximum number of epochs to plot in dataplot.m
MAXEEGPLOTCHANS   = 264;  % maximum number of channels to plot in eegplot.m
MAXTOPOPLOTCHANS  = 264;  % maximum number of channels to plot in topoplot.m

DEFAULT_ELOC  = 'chan.locs'; % default electrode location file for topoplot.m
DEFAULT_EPOCH = 10;       % default epoch width to plot in eegplot(s) (in sec)

SC  =  ['binica.sc'];           % Master .sc script file for binica.m
                                % MATLAB will use first such file found
                                % in its path of script directories.
                                % Copy to pwd to alter ICA defaults


path = '../traindata/transform/transform_512/02/';
dirs = dir([path '*.mat']);
dirs = struct2cell(dirs);

for i = 1:size(dirs,2)
    if(str2num(dirs{1,i}(1:end-4))>3000)
        delete([path dirs{1,i}]);
    end
end


function exportModel(model,fileName,exportGeneComplexes,supressWarnings,sortIds)
% exportModel
%   Exports a constraint-based model to an SBML file (L3V1 FBCv2)
%
%   Input:
%   model               a model structure
%   fileName            filename to export the model to. A dialog window
%                       will open if no file name is specified.
%   exportGeneComplexes true if gene complexes (all gene sets linked with
%                       AND relationship) should be recognised and exported
%                       (opt, default false)
%   supressWarnings     true if warnings should be supressed (opt, default
%                       false)
%   sortIds             logical whether metabolites, reactions and genes
%                       should be sorted alphabetically by their
%                       identifiers (opt, default false)
%
%   Usage: exportModel(model,fileName,exportGeneComplexes,supressWarnings,sortIds)
if nargin<2 || isempty(fileName)
    [fileName, pathName] = uiputfile({'*.xml;*.sbml'}, 'Select file for model export',[model.id '.xml']);
    if fileName == 0
        error('You should provide a file location')
    else
        fileName = fullfile(pathName,fileName);
    end
end
fileName=char(fileName);
if nargin<3
    exportGeneComplexes=false;
end
if nargin<4
    supressWarnings=false;
end
if nargin<5
    sortIds=false;
end
if sortIds==true
    model=sortIdentifiers(model);
end

%If no subSystems are defined, then no need to use groups package
if isfield(model,'subSystems')
    modelHasSubsystems=true;
else
    modelHasSubsystems=false;
end

%The default SBML format settings, which are used as input for appropriate
%libSBML functions to generate the blank SBML model structure before using
%exporting in with OutputSBML to xml file
sbmlLevel=3;
sbmlVersion=1;
sbmlPackages={'fbc'};
sbmlPackageVersions=2;
if modelHasSubsystems
    sbmlPackages={sbmlPackages,'groups'};
    sbmlPackageVersions=[sbmlPackageVersions,1];
end

%Check if the "unconstrained" field is still present. This shows if
%exchange metabolites have been removed
if ~isfield(model,'unconstrained')
    model.unconstrained=zeros(numel(model.mets),1);
end

%If model id and name do not exist, make sure that default
%strings are included
if ~isfield(model,'id')
    fprintf('WARNING: The model is missing the "id" field. Uses "blankID". \n');
    model.id='blankID';
end
if ~isfield(model,'name')
    fprintf('WARNING: The model is missing the "name" field. Uses "blankName". \n');
    model.name='blankName';
end

%Check the model structure
if supressWarnings==false
    checkModelStruct(model,false);
end

%Add several blank fields, if they do not exist already. This is to reduce
%the number of conditions below
if ~isfield(model,'compMiriams')
    model.compMiriams=cell(numel(model.comps),1);
end
if ~isfield(model,'inchis')
    model.inchis=cell(numel(model.mets),1);
end
if ~isfield(model,'metFormulas')
    model.metFormulas=cell(numel(model.mets),1);
end
if ~isfield(model,'metMiriams')
    model.metMiriams=cell(numel(model.mets),1);
end
if ~isfield(model,'geneMiriams') && isfield(model,'genes')
    model.geneMiriams=cell(numel(model.genes),1);
end
if ~isfield(model,'geneShortNames') && isfield(model,'genes')
    model.geneShortNames=cell(numel(model.genes),1);
end
if ~isfield(model,'subSystems')
    model.subSystems=cell(numel(model.rxns),1);
end
if ~isfield(model,'eccodes')
    model.eccodes=cell(numel(model.rxns),1);
end
if ~isfield(model,'rxnReferences')
    model.rxnReferences=cell(numel(model.rxns),1);
end
if ~isfield(model,'rxnConfidenceScores')
    model.rxnConfidenceScores=NaN(numel(model.rxns),1);
end
if ~isfield(model,'rxnNotes')
    model.rxnNotes=cell(numel(model.rxns),1);
end
if ~isfield(model,'rxnMiriams')
    model.rxnMiriams=cell(numel(model.rxns),1);
end

if sbmlLevel<3
    %Check if genes have associated compartments
    if ~isfield(model,'geneComps') && isfield(model,'genes')
        if supressWarnings==false
            EM='There are no compartments specified for genes. All genes will be assigned to the first compartment. This is because the SBML structure requires all elements to be assigned to a compartment';
            dispEM(EM,false);
        end
        model.geneComps=ones(numel(model.genes),1);
    end
end

%Convert ids to SBML-convenient format. This is to avoid the data loss when
%unsupported characters are included in ids. Here we are using part from
%convertSBMLID, originating from the COBRA Toolbox
model.rxns=regexprep(model.rxns,'([^0-9_a-zA-Z])','__${num2str($1+0)}__');
model.mets=regexprep(model.mets,'([^0-9_a-zA-Z])','__${num2str($1+0)}__');
model.comps=regexprep(model.comps,'([^0-9_a-zA-Z])','__${num2str($1+0)}__');
if isfield(model,'genes')
    problemGenes=find(~cellfun('isempty',regexp(model.genes,'([^0-9_a-zA-Z])')));
    originalGenes=model.genes(problemGenes);
    replacedGenes=regexprep(model.genes(problemGenes),'([^0-9_a-zA-Z])','__${num2str($1+0)}__');
    model.genes(problemGenes)=replacedGenes;
    for i=1:numel(problemGenes)
        model.grRules = regexprep(model.grRules, ['(^|\s|\()' originalGenes{i} '($|\s|\))'], ['$1' replacedGenes{i} '$2']);
    end
end

%Generate an empty SBML structure
modelSBML=getSBMLStructure(sbmlLevel,sbmlVersion,sbmlPackages,sbmlPackageVersions);
modelSBML.metaid=model.id;
modelSBML.id=regexprep(model.id,'([^0-9_a-zA-Z])','__${num2str($1+0)}__');
modelSBML.name=model.name;

if isfield(model,'annotation')
    if isfield(model.annotation,'note')
        modelSBML.notes=['<notes>
',regexprep(model.annotation.note,'
|
',''),'
</notes>'];
    end
else
    modelSBML.notes='<notes>
This file was generated using the exportModel function in RAVEN Toolbox 2 and OutputSBML in libSBML
</notes>';
end

modelSBML.annotation=['<annotation><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#" xmlns:bqbiol="http://biomodels.net/biology-qualifiers/" xmlns:bqmodel="http://biomodels.net/model-qualifiers/"><rdf:Description rdf:about="#meta_' model.id '">'];
if isfield(model,'annotation')
    nameString='';
    if isfield(model.annotation,'familyName')
        if ~isempty(model.annotation.familyName)
            nameString=['<vCard:Family>' model.annotation.familyName '</vCard:Family>'];
        end
    end
    if isfield(model.annotation,'givenName')
        if ~isempty(model.annotation.givenName)
            nameString=[nameString '<vCard:Given>' model.annotation.givenName '</vCard:Given>'];
        end
    end
    email='';
    if isfield(model.annotation,'email')
        if ~isempty(model.annotation.email)
            email=['<vCard:EMAIL>' model.annotation.email '</vCard:EMAIL>'];
        end
    end
    org='';
    if isfield(model.annotation,'organization')
        if ~isempty(model.annotation.organization)
            org=['<vCard:ORG rdf:parseType="Resource"><vCard:Orgname>' model.annotation.organization '</vCard:Orgname></vCard:ORG>'];
        end
    end
    if ~isempty(nameString) || ~isempty(email) || ~isempty(org)
        modelSBML.annotation=[modelSBML.annotation '<dc:creator><rdf:Bag><rdf:li rdf:parseType="Resource">'];
        if ~isempty(nameString)
            modelSBML.annotation=[modelSBML.annotation '<vCard:N rdf:parseType="Resource">' nameString '</vCard:N>'];
        end
        modelSBML.annotation=[modelSBML.annotation email org '</rdf:li></rdf:Bag></dc:creator>'];
    end
end
modelSBML.annotation=[modelSBML.annotation '<dcterms:created rdf:parseType="Resource">'...
    '<dcterms:W3CDTF>' datestr(now,'yyyy-mm-ddTHH:MM:SSZ') '</dcterms:W3CDTF>'...
    '</dcterms:created>'...
    '<dcterms:modified rdf:parseType="Resource">'...
    '<dcterms:W3CDTF>' datestr(now,'yyyy-mm-ddTHH:MM:SSZ') '</dcterms:W3CDTF>'...
    '</dcterms:modified>'];

if isfield(model,'annotation')
    if isfield(model.annotation,'taxonomy')
        modelSBML.annotation=[modelSBML.annotation '<bqbiol:is><rdf:Bag><rdf:li rdf:resource="https://identifiers.org/taxonomy/' regexprep(model.annotation.taxonomy,'taxonomy/','') '"/></rdf:Bag></bqbiol:is>'];
    end
end
modelSBML.annotation=[modelSBML.annotation '</rdf:Description></rdf:RDF></annotation>'];

%Prepare compartments
for i=1:numel(model.comps)
    %Add the default values, as these will be the same in all entries
    if i==1
        if isfield(modelSBML.compartment, 'sboTerm')
            modelSBML.compartment(i).sboTerm=290;
        end
        if isfield(modelSBML.compartment, 'spatialDimensions')
            modelSBML.compartment(i).spatialDimensions=3;
        end
        if isfield(modelSBML.compartment, 'size')
            modelSBML.compartment(i).size=1;
        end
        if isfield(modelSBML.compartment, 'constant')
            modelSBML.compartment(i).constant=1;
        end
        if isfield(modelSBML.compartment, 'isSetSize')
            modelSBML.compartment(i).isSetSize=1;
        end
        if isfield(modelSBML.compartment, 'isSetSpatialDimensions')
            modelSBML.compartment(i).isSetSpatialDimensions=1;
        end
    end
    %Copy the default values to the next entry as long as it is not the
    %last one
    if i<numel(model.comps)
        modelSBML.compartment(i+1)=modelSBML.compartment(i);
    end

    if isfield(modelSBML.compartment,'metaid')
        if regexp(model.comps{i},'^[^a-zA-Z_]')
            EM='The compartment IDs are in numeric format. For the compliance with SBML specifications, compartment IDs will be preceded with "c_" string';
            dispEM(EM,false);
            model.comps(i)=strcat('c_',model.comps(i));
        end
        modelSBML.compartment(i).metaid=model.comps{i};
    end
    %Prepare Miriam strings
    if ~isempty(model.compMiriams{i})
        [~,sbo_ind] = ismember('sbo',model.compMiriams{i}.name);
        if sbo_ind > 0
            modelSBML.compartment(i).sboTerm=str2double(regexprep(model.compMiriams{i}.value{sbo_ind},'SBO:','','ignorecase'));
            % remove the SBO term from compMiriams so the information is
            % not duplicated in the "annotation" field later on
            model.compMiriams{i}.name(sbo_ind) = [];
            model.compMiriams{i}.value(sbo_ind) = [];
        end
    end
    if ~isempty(model.compMiriams{i}) && isfield(modelSBML.compartment(i),'annotation')
        modelSBML.compartment(i).annotation=['<annotation><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#" xmlns:bqbiol="http://biomodels.net/biology-qualifiers/" xmlns:bqmodel="http://biomodels.net/model-qualifiers/"><rdf:Description rdf:about="#meta_' model.comps{i} '">'];
        modelSBML.compartment(i).annotation=[modelSBML.compartment(i).annotation '<bqbiol:is><rdf:Bag>'];
        modelSBML.compartment(i).annotation=[modelSBML.compartment(i).annotation getMiriam(model.compMiriams{i}) '</rdf:Bag></bqbiol:is></rdf:Description></rdf:RDF></annotation>'];
    end
    if isfield(modelSBML.compartment, 'name')
        modelSBML.compartment(i).name=model.compNames{i};
    end
    if isfield(modelSBML.compartment, 'id')
        modelSBML.compartment(i).id=model.comps{i};
    end

end

%Begin writing species
for i=1:numel(model.mets)
    %Add the default values, as these will be the same in all entries
    if i==1
        if isfield(modelSBML.species, 'sboTerm')
            modelSBML.species(i).sboTerm=247;
        end
        if isfield(modelSBML.species, 'initialAmount')
            modelSBML.species(i).initialAmount=1;
        end
        if isfield(modelSBML.species, 'initialConcentration')
            modelSBML.species(i).initialConcentration=0;
        end
        if isfield(modelSBML.species, 'isSetInitialAmount')
            modelSBML.species(i).isSetInitialAmount=1;
        end
        if isfield(modelSBML.species, 'isSetInitialConcentration')
            modelSBML.species(i).isSetInitialConcentration=1;
        end
    end
    %Copy the default values to the next entry as long as it is not the
    %last one
    if i<numel(model.mets)
        modelSBML.species(i+1)=modelSBML.species(i);
    end

    if isfield(modelSBML.species,'metaid')
        modelSBML.species(i).metaid=['M_' model.mets{i}];
    end
    if isfield(modelSBML.species, 'name')
        modelSBML.species(i).name=model.metNames{i};
    end
    if isfield(modelSBML.species, 'id')
        modelSBML.species(i).id=['M_' model.mets{i}];
    end
    if isfield(modelSBML.species, 'compartment')
        modelSBML.species(i).compartment=model.comps{model.metComps(i)};
    end
    if isfield(model,'unconstrained')
        if model.unconstrained(i)
            modelSBML.species(i).boundaryCondition=1;
        end
    end
    if isfield(modelSBML.species, 'fbc_charge') && isfield(model,'metCharges')
        if ~isnan(model.metCharges(i))
            modelSBML.species(i).fbc_charge=model.metCharges(i);
            modelSBML.species(i).isSetfbc_charge=1;
        else
            modelSBML.species(i).isSetfbc_charge=0;
        end
    end
    if ~isempty(model.metMiriams{i})
        [~,sbo_ind] = ismember('sbo',model.metMiriams{i}.name);
        if sbo_ind > 0
            modelSBML.species(i).sboTerm=str2double(regexprep(model.metMiriams{i}.value{sbo_ind},'SBO:','','ignorecase'));
            % remove the SBO term from metMiriams so the information is
            % not duplicated in the "annotation" field later on
            model.metMiriams{i}.name(sbo_ind) = [];
            model.metMiriams{i}.value(sbo_ind) = [];
        end
    end
    if isfield(modelSBML.species,'annotation')
        if ~isempty(model.metMiriams{i}) || ~isempty(model.metFormulas{i})
            hasInchi=false;
            if ~isempty(model.metFormulas{i})
                %Only export formula if there is no InChI. This is because
                %the metFormulas field is populated by InChIs if available
                if ~isempty(model.inchis{i})
                    hasInchi=true;
                end
                if hasInchi==false
                    modelSBML.species(i).fbc_chemicalFormula=model.metFormulas{i};
                end
            end
            if ~isempty(model.metMiriams{i}) || hasInchi==true
                modelSBML.species(i).annotation=['<annotation><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#" xmlns:bqbiol="http://biomodels.net/biology-qualifiers/" xmlns:bqmodel="http://biomodels.net/model-qualifiers/"><rdf:Description rdf:about="#meta_M_' model.mets{i} '">'];
                modelSBML.species(i).annotation=[modelSBML.species(i).annotation '<bqbiol:is><rdf:Bag>'];
                if ~isempty(model.metMiriams{i})
                    modelSBML.species(i).annotation=[modelSBML.species(i).annotation getMiriam(model.metMiriams{i})];
                end
                if hasInchi==true
                    modelSBML.species(i).annotation=[modelSBML.species(i).annotation '<rdf:li rdf:resource="https://identifiers.org/inchi/InChI=' regexprep(model.inchis{i},'^InChI=','') '"/>'];
                    modelSBML.species(i).fbc_chemicalFormula=char(regexp(model.inchis{i}, '/(\w+)/', 'tokens', 'once'));
                end
                modelSBML.species(i).annotation=[modelSBML.species(i).annotation '</rdf:Bag></bqbiol:is></rdf:Description></rdf:RDF></annotation>'];
            end
        end
    end
end

if isfield(model,'genes')
    for i=1:numel(model.genes)
        %Add the default values, as these will be the same in all entries
        if i==1
            if isfield(modelSBML.fbc_geneProduct, 'sboTerm')
                modelSBML.fbc_geneProduct(i).sboTerm=243;
            end
        end
        %Copy the default values to the next index as long as it is not the
        %last one
        if i<numel(model.genes)
            modelSBML.fbc_geneProduct(i+1)=modelSBML.fbc_geneProduct(i);
        end

        if isfield(modelSBML.fbc_geneProduct,'metaid')
            modelSBML.fbc_geneProduct(i).metaid=model.genes{i};
        end
        if ~isempty(model.geneMiriams{i})
            [~,sbo_ind] = ismember('sbo',model.geneMiriams{i}.name);
            if sbo_ind > 0
                modelSBML.fbc_geneProduct(i).sboTerm=str2double(regexprep(model.geneMiriams{i}.value{sbo_ind},'SBO:','','ignorecase'));
                % remove the SBO term from compMiriams so the information is
                % not duplicated in the "annotation" field later on
                model.geneMiriams{i}.name(sbo_ind) = [];
                model.geneMiriams{i}.value(sbo_ind) = [];
            end
        end
        if ~isempty(model.geneMiriams{i}) && isfield(modelSBML.fbc_geneProduct(i),'annotation')
            modelSBML.fbc_geneProduct(i).annotation=['<annotation><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#" xmlns:bqbiol="http://biomodels.net/biology-qualifiers/" xmlns:bqmodel="http://biomodels.net/model-qualifiers/"><rdf:Description rdf:about="#meta_' model.genes{i} '">'];
            modelSBML.fbc_geneProduct(i).annotation=[modelSBML.fbc_geneProduct(i).annotation '<bqbiol:is><rdf:Bag>'];
            modelSBML.fbc_geneProduct(i).annotation=[modelSBML.fbc_geneProduct(i).annotation getMiriam(model.geneMiriams{i}) '</rdf:Bag></bqbiol:is></rdf:Description></rdf:RDF></annotation>'];
        end
        if isfield(modelSBML.fbc_geneProduct, 'fbc_id')
            modelSBML.fbc_geneProduct(i).fbc_id=model.genes{i};
        end
        if isfield(modelSBML.fbc_geneProduct, 'fbc_label') && isfield(model,'geneShortNames')
            if isempty(model.geneShortNames{i})
                modelSBML.fbc_geneProduct(i).fbc_label=model.genes{i};
            else
                modelSBML.fbc_geneProduct(i).fbc_label=model.geneShortNames{i};
            end
        end
    end
    if exportGeneComplexes==true
        %Also add the complexes as genes. This is done by splitting grRules
        %on "or" and adding the ones which contain several genes
        geneComplexes={};
        if isfield(model,'grRules')
            %Only grRules which contain " and " can be complexes
            uniqueRules=unique(model.grRules);
            I=cellfun(@any,strfind(uniqueRules,' and '));
            uniqueRules(~I)=[];
            uniqueRules=strrep(uniqueRules,'(','');
            uniqueRules=strrep(uniqueRules,')','');
            uniqueRules=strrep(uniqueRules,' and ',':');
            for i=1:numel(uniqueRules)
                genes=regexp(uniqueRules(i),' or ','split');
                genes=genes{1}(:);
                %Check which ones are complexes
                I=cellfun(@any,strfind(genes,':'));
                geneComplexes=[geneComplexes;genes(I)];
            end
        end
        geneComplexes=unique(geneComplexes);
        if ~isempty(geneComplexes)
            %Then add them as genes. There is a possiblity that a complex
            %A&B is added as separate from B&A. This is not really an issue
            %so this is not dealt with
            for i=1:numel(geneComplexes)
                modelSBML.fbc_geneProduct(numel(model.genes)+i)=modelSBML.fbc_geneProduct(1);
                if isfield(modelSBML.fbc_geneProduct,'metaid')
                    modelSBML.fbc_geneProduct(numel(model.genes)+i).metaid=geneComplexes{i};
                end
                if isfield(modelSBML.fbc_geneProduct,'fbc_id')
                    modelSBML.fbc_geneProduct(numel(model.genes)+i).fbc_id=geneComplexes{i};
                else
                    modelSBML.fbc_geneProduct(i).fbc_label=modelSBML.fbc_geneProduct(i).fbc_id;
                end
            end
        end
    end
end

%Generate a list of unique fbc_bound names
totalValues=[model.lb; model.ub];
totalNames=cell(size(totalValues,1),1);

listUniqueValues=unique(totalValues);

for i=1:length(listUniqueValues)
    listUniqueNames{i,1}=['FB',num2str(i),'N',num2str(abs(round(listUniqueValues(i))))]; % create unique flux bound IDs.
    ind=find(ismember(totalValues,listUniqueValues(i)));
    totalNames(ind)=listUniqueNames(i,1);
end

for i=1:length(listUniqueNames)
    %Add the default values, as these will be the same in all entries
    if i==1
        if isfield(modelSBML.parameter, 'constant')
            modelSBML.parameter(i).constant=1;
        end
        if isfield(modelSBML.parameter, 'isSetValue')
            modelSBML.parameter(i).isSetValue=1;
        end
    end
    %Copy the default values to the next index as long as it is not the
    %last one
    if i<numel(listUniqueNames)
        modelSBML.parameter(i+1)=modelSBML.parameter(i);
    end
    modelSBML.parameter(i).id=listUniqueNames{i};
    modelSBML.parameter(i).value=listUniqueValues(i);
end

for i=1:numel(model.rxns)
    %Add the default values, as these will be the same in all entries
    if i==1
        if isfield(modelSBML.reaction, 'sboTerm')
            modelSBML.reaction(i).sboTerm=176;
        end
        if isfield(modelSBML.reaction, 'isSetFast')
            modelSBML.reaction(i).isSetFast=1;
        end
    end
    %Copy the default values to the next index as long as it is not the
    %last one
    if i<numel(model.rxns)
        modelSBML.reaction(i+1)=modelSBML.reaction(i);
    end

    if isfield(modelSBML.reaction,'metaid')
        modelSBML.reaction(i).metaid=['R_' model.rxns{i}];
    end

    %Export notes information
    if (~isnan(model.rxnConfidenceScores(i)) || ~isempty(model.rxnReferences{i}) || ~isempty(model.rxnNotes{i}))
        modelSBML.reaction(i).notes='<notes>';
        if ~isnan(model.rxnConfidenceScores(i))
            modelSBML.reaction(i).notes=[modelSBML.reaction(i).notes '
Confidence Level: ' num2str(model.rxnConfidenceScores(i)) '
'];
        end
        if ~isempty(model.rxnReferences{i})
            modelSBML.reaction(i).notes=[modelSBML.reaction(i).notes '
AUTHORS: ' model.rxnReferences{i} '
'];
        end
        if ~isempty(model.rxnNotes{i})
            modelSBML.reaction(i).notes=[modelSBML.reaction(i).notes '
NOTES: ' model.rxnNotes{i} '
'];
        end
        modelSBML.reaction(i).notes=[modelSBML.reaction(i).notes '</notes>'];
    end

    % Export SBO terms from rxnMiriams
    if ~isempty(model.rxnMiriams{i})
        [~,sbo_ind] = ismember('sbo',model.rxnMiriams{i}.name);
        if sbo_ind > 0
            modelSBML.reaction(i).sboTerm=str2double(regexprep(model.rxnMiriams{i}.value{sbo_ind},'SBO:','','ignorecase'));
            % remove the SBO term from rxnMiriams so the information is not
            % duplicated in the "annotation" field later on
            model.rxnMiriams{i}.name(sbo_ind) = [];
            model.rxnMiriams{i}.value(sbo_ind) = [];
        end
    end

    %Export annotation information from rxnMiriams
    if (~isempty(model.rxnMiriams{i}) && isfield(modelSBML.reaction(i),'annotation')) || ~isempty(model.eccodes{i})
        modelSBML.reaction(i).annotation=['<annotation><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#" xmlns:bqbiol="http://biomodels.net/biology-qualifiers/" xmlns:bqmodel="http://biomodels.net/model-qualifiers/"><rdf:Description rdf:about="#meta_R_' model.rxns{i} '">'];
        modelSBML.reaction(i).annotation=[modelSBML.reaction(i).annotation '<bqbiol:is><rdf:Bag>'];
        if ~isempty(model.eccodes{i})
            eccodes=regexp(model.eccodes{i},';','split');
            for j=1:numel(eccodes)
                modelSBML.reaction(i).annotation=[modelSBML.reaction(i).annotation  '<rdf:li rdf:resource="https://identifiers.org/ec-code/' regexprep(eccodes{j},'ec-code/|EC','') '"/>'];
            end
        end
        modelSBML.reaction(i).annotation=[modelSBML.reaction(i).annotation getMiriam(model.rxnMiriams{i}) '</rdf:Bag></bqbiol:is></rdf:Description></rdf:RDF></annotation>'];
    end

    if isfield(modelSBML.reaction, 'name')
        modelSBML.reaction(i).name=model.rxnNames{i};
    end
    if isfield(modelSBML.reaction, 'id')
        modelSBML.reaction(i).id=['R_' model.rxns{i}];
    end

    %Add the information about reactants and products
    involvedMets=addReactantsProducts(model,modelSBML,i);
    for j=1:numel(involvedMets.reactant)
        if j<numel(involvedMets.reactant)
            modelSBML.reaction(i).reactant(j+1)=modelSBML.reaction(i).reactant(j);
        end
        modelSBML.reaction(i).reactant(j).species=involvedMets.reactant(j).species;
        modelSBML.reaction(i).reactant(j).stoichiometry=involvedMets.reactant(j).stoichiometry;
        modelSBML.reaction(i).reactant(j).isSetStoichiometry=involvedMets.reactant(j).isSetStoichiometry;
        modelSBML.reaction(i).reactant(j).constant=involvedMets.reactant(j).constant;
    end
    if numel(involvedMets.reactant)==0
        modelSBML.reaction(i).reactant='';
    end
    for j=1:numel(involvedMets.product)
        if j<numel(involvedMets.product)
            modelSBML.reaction(i).product(j+1)=modelSBML.reaction(i).product(j);
        end
        modelSBML.reaction(i).product(j).species=involvedMets.product(j).species;
        modelSBML.reaction(i).product(j).stoichiometry=involvedMets.product(j).stoichiometry;
        modelSBML.reaction(i).product(j).isSetStoichiometry=involvedMets.product(j).isSetStoichiometry;
        modelSBML.reaction(i).product(j).constant=involvedMets.product(j).constant;
    end
    if numel(involvedMets.product)==0
        modelSBML.reaction(i).product='';
    end
    %Export reversibility information. Reactions are irreversible by
    %default
    if model.rev(i)==1
        modelSBML.reaction(i).reversible=1;
    end
    if isfield(model, 'rxnComps')
        modelSBML.reaction(i).compartment=model.comps{model.rxnComps(i)};
    end
    if isfield(model, 'grRules')
        modelSBML.reaction(i).fbc_geneProductAssociation.fbc_association.fbc_association=model.grRules{i};
    end
    modelSBML.reaction(i).fbc_lowerFluxBound=totalNames{i};
    modelSBML.reaction(i).fbc_upperFluxBound=totalNames{length(model.lb)+i};
end

%Prepare subSystems Code taken from COBRA functions getModelSubSystems,
%writeSBML, findRxnsFromSubSystem under GNU General Public License v3.0,
%license file in readme/GPL.MD. Code modified for RAVEN
if modelHasSubsystems
    modelSBML.groups_group.groups_kind = 'partonomy';
    modelSBML.groups_group.sboTerm = 633;
    tmpStruct=modelSBML.groups_group;

    rxns=strcat('R_',model.rxns);
    if ~any(cellfun(@iscell,model.subSystems))
        if ~any(~cellfun(@isempty,model.subSystems))
            subSystems = {};
        else
            subSystems = setdiff(model.subSystems,'');
        end
    else
        orderedSubs = cellfun(@(x) columnVector(x),model.subSystems,'UniformOUtput',false);
        subSystems = setdiff(vertcat(orderedSubs{:}),'');
    end
    if isempty(subSystems)
        subSystems = {};
    end
    if ~isempty(subSystems)
        %Build the groups for the group package
        groupIDs = strcat('group',cellfun(@num2str, num2cell(1:length(subSystems)),'UniformOutput',false));
        for i = 1:length(subSystems)
            cgroup = tmpStruct;
            if ~any(cellfun(@iscell,model.subSystems))
                present = ismember(model.subSystems,subSystems{i});
            else
                present = cellfun(@(x) any(ismember(x,subSystems{i})),model.subSystems);
            end
            groupMembers = rxns(present);
            for j = 1:numel(groupMembers)
                cMember = tmpStruct.groups_member;
                cMember.groups_idRef = groupMembers{j};
                if j == 1
                    cgroup.groups_member = cMember;
                else
                    cgroup.groups_member(j) = cMember;
                end
            end
            cgroup.groups_id = groupIDs{i};
            cgroup.groups_name = subSystems{i};
            if i == 1
                modelSBML.groups_group = cgroup;
            else
                modelSBML.groups_group(i) = cgroup;
            end
        end
    end
end

%Prepare fbc_objective subfield

modelSBML.fbc_objective.fbc_type='maximize';
modelSBML.fbc_objective.fbc_id='obj';

ind=find(model.c);

if isempty(ind)
    modelSBML.fbc_objective.fbc_fluxObjective.fbc_coefficient=0;
else
    for i=1:length(ind)
        %Copy the default values to the next index as long as it is not the
        %last one
        if i<numel(ind)
            modelSBML.reaction(i+1)=modelSBML.reaction(i);
        end
        values=model.c(model.c~=0);
        modelSBML.fbc_objective(i).fbc_fluxObjective.fbc_reaction=modelSBML.reaction(ind(i)).id;
        modelSBML.fbc_objective(i).fbc_fluxObjective.fbc_coefficient=values(i);
        modelSBML.fbc_objective(i).fbc_fluxObjective.isSetfbc_coefficient=1;
    end
end

modelSBML.fbc_activeObjective=modelSBML.fbc_objective.fbc_id;

fbcStr=['http://www.sbml.org/sbml/level', num2str(sbmlLevel), '/version', num2str(sbmlVersion), '/fbc/version',num2str(sbmlPackageVersions(1))];
if modelHasSubsystems
    groupStr=['http://www.sbml.org/sbml/level', num2str(sbmlLevel), '/version', num2str(sbmlVersion), '/groups/version',num2str(sbmlPackageVersions(2))];
    modelSBML.namespaces=struct('prefix',{'','fbc','groups'},...
    'uri',{['http://www.sbml.org/sbml/level', num2str(sbmlLevel), '/version', num2str(sbmlVersion), '/core'],...
    fbcStr,groupStr});
else
    modelSBML.namespaces=struct('prefix',{'','fbc'},...
    'uri',{['http://www.sbml.org/sbml/level', num2str(sbmlLevel), '/version', num2str(sbmlVersion), '/core'],...
    fbcStr});
end

if sbmlPackageVersions(1) == 2
    modelSBML.fbc_strict=1;
end

modelSBML.rule=[];
modelSBML.constraint=[];

[ravenDir,prevDir]=findRAVENroot();
fileName=checkFileExistence(fileName,1,true,false);
cd(fullfile(ravenDir,'software','libSBML'));
OutputSBML(modelSBML,fileName,1,0,[1,0]);
cd(prevDir);
end

function modelSBML=getSBMLStructure(sbmlLevel,sbmlVersion,sbmlPackages,sbmlPackageVersions)
%Returns the blank SBML model structure by using appropriate libSBML
%functions. This creates structure by considering three levels

sbmlFieldNames=getStructureFieldnames('model',sbmlLevel,sbmlVersion,sbmlPackages,sbmlPackageVersions);
sbmlDefaultValues=getDefaultValues('model',sbmlLevel,sbmlVersion,sbmlPackages,sbmlPackageVersions);

for i=1:numel(sbmlFieldNames)
    modelSBML.(sbmlFieldNames{1,i})=sbmlDefaultValues{1,i};
    sbmlSubfieldNames=getStructureFieldnames(sbmlFieldNames{1,i},sbmlLevel,sbmlVersion,sbmlPackages,sbmlPackageVersions);
    sbmlSubfieldValues=getDefaultValues(sbmlFieldNames{1,i},sbmlLevel,sbmlVersion,sbmlPackages,sbmlPackageVersions);
    if ~strcmp(sbmlFieldNames{1,i},'event') && ~strcmp(sbmlFieldNames{1,i},'functionDefinition') && ~strcmp(sbmlFieldNames{1,i},'initialAssignment')
        for j=1:numel(sbmlSubfieldNames)
            modelSBML.(sbmlFieldNames{1,i}).(sbmlSubfieldNames{1,j})=sbmlSubfieldValues{1,j};
            sbmlSubsubfieldNames=getStructureFieldnames(sbmlSubfieldNames{1,j},sbmlLevel,sbmlVersion,sbmlPackages,sbmlPackageVersions);
            sbmlSubsubfieldValues=getDefaultValues(sbmlSubfieldNames{1,j},sbmlLevel,sbmlVersion,sbmlPackages,sbmlPackageVersions);
            if ~strcmp(sbmlSubfieldNames{1,j},'modifier') && ~strcmp(sbmlSubfieldNames{1,j},'kineticLaw')
                for k=1:numel(sbmlSubsubfieldNames)
                    %'compartment' and 'species' fields are not supposed to
                    %have their standalone structures if they are subfields
                    %or subsubfields
                    if ~strcmp(sbmlSubfieldNames{1,j},'compartment') && ~strcmp(sbmlSubfieldNames{1,j},'species')
                        modelSBML.(sbmlFieldNames{1,i}).(sbmlSubfieldNames{1,j}).(sbmlSubsubfieldNames{1,k})=sbmlSubsubfieldValues{1,k};
                    end
                    %If it is fbc_association in the third level, we need
                    %to establish the fourth level, since libSBML requires
                    %it
                    if strcmp(sbmlSubsubfieldNames{1,k},'fbc_association')
                        fbc_associationFieldNames=getStructureFieldnames('fbc_association',sbmlLevel,sbmlVersion,sbmlPackages,sbmlPackageVersions);
                        fbc_associationFieldValues=getDefaultValues('fbc_association',sbmlLevel,sbmlVersion,sbmlPackages,sbmlPackageVersions);
                        for l=1:numel(fbc_associationFieldNames)
                            modelSBML.(sbmlFieldNames{1,i}).(sbmlSubfieldNames{1,j}).(sbmlSubsubfieldNames{1,k}).(fbc_associationFieldNames{1,l})=fbc_associationFieldValues{1,l};
                        end
                    end
                end
            end
        end
    end
    if ~isstruct(modelSBML.(sbmlFieldNames{1,i}))
        modelSBML.(sbmlFieldNames{1,i})=sbmlDefaultValues{1,i};
    end
end

modelSBML.unitDefinition.id='mmol_per_gDW_per_hr';

unitFieldNames=getStructureFieldnames('unit',sbmlLevel,sbmlVersion,sbmlPackages,sbmlPackageVersions);
unitDefaultValues=getDefaultValues('unit',sbmlLevel,sbmlVersion,sbmlPackages,sbmlPackageVersions);

kinds={'mole','gram','second'};
exponents=[1 -1 -1];
scales=[-3 0 0];
multipliers=[1 1 1*60*60];

for i=1:numel(unitFieldNames)
    modelSBML.unitDefinition.unit(1).(unitFieldNames{1,i})=unitDefaultValues{1,i};
    for j=1:3
        modelSBML.unitDefinition.unit(j).(unitFieldNames{1,i})=unitDefaultValues{1,i};
        if strcmp(unitFieldNames{1,i},'kind')
            modelSBML.unitDefinition.unit(j).(unitFieldNames{1,i})=kinds{j};
        elseif strcmp(unitFieldNames{1,i},'exponent')
            modelSBML.unitDefinition.unit(j).(unitFieldNames{1,i})=exponents(j);
        elseif strcmp(unitFieldNames{1,i},'scale')
            modelSBML.unitDefinition.unit(j).(unitFieldNames{1,i})=scales(j);
        elseif strcmp(unitFieldNames{1,i},'multiplier')
            modelSBML.unitDefinition.unit(j).(unitFieldNames{1,i})=multipliers(j);
        end
    end
end
end

function miriamString=getMiriam(miriamStruct)
%Returns a string with list elements for a miriam structure ('<rdf:li
%rdf:resource="https://identifiers.org/go/GO:0005739"/>' for example). This
%is just to speed up things since this is done many times during the
%exporting

miriamString='';
if isfield(miriamStruct,'name')
    for i=1:numel(miriamStruct.name)
        miriamString=[miriamString '<rdf:li rdf:resource="https://identifiers.org/' miriamStruct.name{i} '/' miriamStruct.value{i} '"/>'];
    end
end
end

function [tmp_Rxn]=addReactantsProducts(model,sbmlModel,i)
%This function provides reactants and products for particular reaction. The
%function was 'borrowed' from writeSBML in COBRA toolbox, lines 663-679

met_idx = find(model.S(:, i));
tmp_Rxn.product=[];
tmp_Rxn.reactant=[];
for j_met=1:size(met_idx,1)
    tmp_idx = met_idx(j_met,1);
    sbml_tmp_species_ref.species = sbmlModel.species(tmp_idx).id;
    met_stoich = model.S(tmp_idx, i);
    sbml_tmp_species_ref.stoichiometry = abs(met_stoich);
    sbml_tmp_species_ref.isSetStoichiometry=1;
    sbml_tmp_species_ref.constant=1;
    if (met_stoich > 0)
        tmp_Rxn.product = [ tmp_Rxn.product, sbml_tmp_species_ref ];
    else
        tmp_Rxn.reactant = [ tmp_Rxn.reactant, sbml_tmp_species_ref];
    end
end
end

function vecT = columnVector(vec)
% Code below taken from COBRA Toolbox under GNU General Public License v3.0
% license file in readme/GPL.MD.
%
% Converts a vector to a column vector
%
% USAGE:
%
%   vecT = columnVector(vec)
%
% INPUT:
%   vec:     a vector
%
% OUTPUT:
%   vecT:    a column vector

[n, m] = size(vec);

if n < m
    vecT = vec';
else
    vecT = vec;
end
end


function [dip] = ft_datatype_dip(dip, varargin)

% FT_DATATYPE_DIP descripts the FieldTrip MATLAB structure for dip data
%
% The dip structure reprents a dipole model that has been fitted to
% ERP or ERF data using a non-linear optimization approach. It is
% usually generated by the FT_DIPOLEFITTING function.
%
% FIXME more information should be added here
%
% See also FT_DATATYPE, FT_DATATYPE_SOURCE, FT_DATATYPE_VOLUME

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

if isempty(dip)
  return;
end


function s=get_name(a)
s=[get_name(a.algorithm)];
%if nargin==2
s=[s '(' get_name(a.child) ')'];
s=[s sprintf(' bags=%d m=%d',a.bags,a.m)];
%end
eval_name


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% Code to run part-based RCNNs for fine-grained detection %
%%%% Usage: put pretrained deep model paths into cnn_models %%
%%%% Also define model definition file %%%%%%%%%%%%%%%%%%%%%%%
%%%% Change all the paths to your path %%%%%%%%%%%%%%%%%%%%%%%
%%%% Written by Ning Zhang %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

init;

results = run_classification(cnn_models, model_def);


classdef TestFisheyeStereoRectify
    %TestFisheyeStereoRectify

    methods (Static)
        function test_1
            %TODO
        end

        function test_error_argnum
            try
                cv.fisheyeStereoRectify();
                throw('UnitTest:Fail');
            catch e
                assert(strcmp(e.identifier,'mexopencv:error'));
            end
        end
    end

end


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

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

%   Copyright 1984-2010 The MathWorks, Inc.
% Last Modified by GUIDE v2.5 30-Sep-2005 11:05:33

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @main_OpeningFcn, ...
                   'gui_OutputFcn',  @main_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 main is made visible.
function main_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 main (see VARARGIN)

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

% Update handles structure
guidata(hObject, handles);

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

setappdata(0  , 'hMainGui'    , gcf);
setappdata(gcf,   'thresh'    , 121);
setappdata(gcf, 'fhUpdateAxes', @updateAxes);

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

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

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

hMainGui = getappdata(0, 'hMainGui');

fileName = uigetfile('*.jpg');

setappdata(hMainGui, 'fileName', fileName);

updateAxes

function updateAxes

hMainGui = getappdata(0, 'hMainGui');
fileName = getappdata(hMainGui, 'fileName');
thresh   = getappdata(hMainGui, 'thresh');

I = imread(fileName);
I = (I > thresh);

hAxes = findobj(hMainGui, 'type', 'axes');
axes(hAxes)
imshow(I)

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

threshGui;