function desview(filename)

% tstool/desview
% desview(filename)
%
% graphical viewer for the description of a signal stored in file filename

if nargin < 1, help(mfilename), return, end

load desview

s = signal(filename);

if isempty(s)
	warndlg(['Error opeing signal ' filename]);
end

[path,nam,ext] = fileparts(filename);
lt = list;

lt = TSTL_append(lt, [num2str(ndim(s)) '-dimensional signal ' filename]);
lt = TSTL_append(lt, ['Dlens : ' num2str(dlens(s))]);

for n=1:ndim(s)
	a = getaxis(s, n);
	if ~isempty(label(a)) & ~isempty(name(a))
		lt = TSTL_append(lt, ['X-Axis ' num2str(n)  ' : ' label(a) ' | ' name(a)  ]);
	end
end

if ~isempty(name(s))
lt = TSTL_append(lt,['Name : ' name(s)]);
end
lt = TSTL_append(lt,['Type : ' type(s)]);

if ~isempty(label(yunit(s))) & ~isempty(yname(s))
	lt = TSTL_append(lt,['Attributes of data values : ']);
	lt = TSTL_append(lt,[label(yunit(s)) ' | '  yname(s)]);
end

txt = cellstr(lt);

a = figure('Color',[0.8 0.8 0.8], ...
	'Units','normalized', ...
	'Colormap',mat0, ...
	'Visible', 'off', ...
	'Name',['Description for ' nam], ...
	'NumberTitle','off', ...
	'Resize','on', ...
	'Position',[0.46875 0.241211 0.416406 0.375], ...
	'Tag','Fig1');
b = uicontrol('Parent',a, ...
	'Units','normalized', ...
	'BackgroundColor',[1 1 1], ...
	'Position',[0.00187617 0.622396 0.996248 0.375], ...
	'Style','text', ...
	'String',txt, ...
	'HorizontalAlignment','left', ...
	'Tag','Description');
b = uicontrol('Parent',a, ...
	'Units','normalized', ...
	'BackgroundColor',[1 1 1], ...
	'Position',[0.00187617 0.322917 0.996248 0.299479], ...
	'String',cellstr(comment(s)), ...
	'Style','listbox', ...
	'Tag','Comment', ...
	'Value',1);
b = uicontrol('Parent',a, ...
	'Units','normalized', ...
	'BackgroundColor',[1 1 1], ...
	'Position',[0.00187617 0.00520833 0.996248 0.335938], ...
	'String',cellstr(history(s)), ...
	'Style','listbox', ...
	'Tag','History', ...
	'Value',1);

set(a, 'Visible', 'on');


function [objfiles, timestamp_out] = cs_make (f)
%CS_MAKE compiles CSparse for use in MATLAB.
%   Usage:
%       cs_make
%       [objfiles, timestamp] = cs_make (f)
%
%   With no input arguments, or with f=0, only those files needing to be
%   compiled are compiled (like the Unix/Linux/GNU "make" command, but not
%   requiring "make").  If f is a nonzero number, all files are compiled.
%   If f is a string, only that mexFunction is compiled.  For example,
%   cs_make ('cs_add') just compiles the cs_add mexFunction.  This option is
%   useful when developing a single new mexFunction.  This function can only be
%   used if the current directory is CSparse/MATLAB/CSparse.  Returns a list of
%   the object files in CSparse, and the latest modification time of any source
%   codes.
%
%   To add a new function and its MATLAB mexFunction to CSparse:
%
%       (1) Create a source code file CSparse/Source/cs_mynewfunc.c.
%       (2) Create a help file, CSparse/MATLAB/CSparse/cs_mynewfunc.m.
%           This is very useful, but not strictly required.
%       (3) Add the prototype of cs_mynewfunc to CSparse/Include/cs.h.
%       (4) Create its MATLAB mexFunction, CSparse/MATLAB/cs_mynewfunc_mex.c.
%       (5) Edit cs_make.m, and add 'cs_mynewfunc' to the 'cs' and 'csm' lists.
%       (6) Type 'cs_make' in the CSparse/MATLAB/CSparse directory.
%           If all goes well, your new function is ready for use in MATLAB.
%
%       (7) Optionally add 'cs_mynewfunc' to CSparse/Source/Makefile
%           and CSparse/MATLAB/CSparse/Makefile, if you want to use the
%           Unix/Linux/GNU make command instead of cs_make.m.  See where
%           'cs_add' and 'cs_add_mex' appear in those files, and add
%           'cs_mynewfunc' accordingly.
%       (8) Optionally add 'cs_mynewfunc' to Tcov/Makefile, and add additional
%           test code to cs_test.c, and add MATLAB test code to MATLAB/Test/*.
%
%   Example:
%       cs_make                  % compile everything
%       cs_make ('cs_chol') ;    % just compile cs_chol mexFunction
%
%   See also MEX.

%   Copyright 2006-2007, Timothy A. Davis.
%   http://www.cise.ufl.edu/research/sparse

fprintf ('Compiling CSparse\n') ;

% CSparse source files, in ../../Source, such as ../../Source/cs_add.c.
% Note that not all CSparse source files have their own mexFunction.
cs = { 'cs_add', 'cs_amd', 'cs_chol', 'cs_cholsol', 'cs_counts', ...
    'cs_cumsum', 'cs_dfs', 'cs_dmperm', 'cs_droptol', 'cs_dropzeros', ...
    'cs_dupl', 'cs_entry', 'cs_etree', 'cs_fkeep', 'cs_gaxpy', 'cs_happly', ...
    'cs_house', 'cs_ipvec', 'cs_load', 'cs_lsolve', 'cs_ltsolve', 'cs_lu', ...
    'cs_lusol', 'cs_malloc', 'cs_maxtrans', 'cs_multiply', 'cs_norm', ...
    'cs_permute', 'cs_pinv', 'cs_post', 'cs_print', 'cs_pvec', 'cs_qr', ...
    'cs_qrsol', 'cs_scatter', 'cs_scc', 'cs_schol', 'cs_sqr', 'cs_symperm', ...
    'cs_tdfs', 'cs_transpose', 'cs_compress', 'cs_updown', 'cs_usolve', ...
    'cs_utsolve', 'cs_util', 'cs_reach', 'cs_spsolve', 'cs_ereach', ...
    'cs_leaf', 'cs_randperm' } ;
    % add cs_mynewfunc to the above list

details = 1 ;
kk = 0 ;
csm = { } ;
if (nargin == 0)
    force = 0 ;
elseif (ischar (f))
    fprintf ('cs_make: compiling ../../Source files and %s_mex.c\n', f) ;
    force = 0 ;
    csm = {f} ;
else
    force = f ;
    details = details | (force > 1) ;                                       %#ok
    if (force & details)                                                    %#ok
        fprintf ('cs_make: re-compiling everything\n') ;
    end
end
if (force)
    fprintf ('Compiling CSparse\n') ;
end

if (isempty (csm))
    % mexFunctions, of the form cs_add_mex.c, etc, in this directory
    csm = { 'cs_add', 'cs_amd', 'cs_chol', 'cs_cholsol', 'cs_counts', ...
        'cs_dmperm', 'cs_droptol', 'cs_etree', 'cs_gaxpy', 'cs_lsolve', ...
        'cs_ltsolve', 'cs_lu', 'cs_lusol', 'cs_multiply', 'cs_permute', ...
        'cs_print', 'cs_qr', 'cs_qrsol', 'cs_scc', 'cs_symperm', 'cs_thumb', ...
        'cs_transpose', 'cs_sparse', 'cs_updown', 'cs_usolve', ...
        'cs_utsolve', 'cs_randperm', 'cs_sqr' } ;
        % add cs_mynewfunc to the above list
end

try
    % ispc does not appear in MATLAB 5.3
    pc = ispc ;
catch
    % if ispc fails, assume we are on a Windows PC if it's not unix
    pc = ~isunix ;
end

if (pc)
    obj = '.obj' ;
else
    obj = '.o' ;
end

srcdir = '../../Source/' ;
hfile = '../../Include/cs.h' ;

% compile each CSparse source file
[anysrc timestamp kk] = compile_source ('', 'cs_mex', obj, hfile, force, ...
    kk, details) ;
CS = ['cs_mex' obj] ;
if (nargout > 0)
    objfiles = ['..' filesep 'CSparse' filesep 'cs_mex' obj] ;
end
for i = 1:length (cs)
    [s t kk] = compile_source (srcdir, cs {i}, obj, hfile, force, kk, details) ;
    timestamp = max (timestamp, t) ;
    anysrc = anysrc | s ;                                                   %#ok
    CS = [CS ' ' cs{i} obj] ;                                               %#ok
    if (nargout > 0)
        objfiles = [objfiles ' ..' filesep 'CSparse' filesep cs{i} obj] ;   %#ok
    end
end

% compile each CSparse mexFunction
obj = ['.' mexext] ;
for i = 1:length (csm)
    [s t] = cs_must_compile ('', csm{i}, '_mex', obj, hfile, force) ;
    timestamp = max (timestamp, t) ;
    if (anysrc | s)                                                         %#ok
        cmd = sprintf ('mex -O -I../../Include %s_mex.c %s -output %s', ...
            csm{i}, CS, csm{i}) ;
        kk = do_cmd (cmd, kk, details) ;
    end
end

fprintf ('\n') ;
if (nargout > 1)
    timestamp_out = timestamp ;
end

if (force)
    fprintf ('CSparse successfully compiled.\n') ;
end

%-------------------------------------------------------------------------------
function [s,t,kk] = compile_source (srcdir, f, obj, hfile, force, kk, details)
% compile a source code file in ../../Source, leaving object file in
% this directory.
[s t] = cs_must_compile (srcdir, f, '', obj, hfile, force) ;
if (s)
    cmd = sprintf ('mex -O -c -I../../Include %s%s.c', srcdir, f) ;
    kk = do_cmd (cmd, kk, details) ;
end

%-------------------------------------------------------------------------------
function kk = do_cmd (s, kk, details)
%DO_CMD: evaluate a command, and either print it or print a "."
s = strrep (s, '/', filesep) ;
if (details)
    fprintf ('%s\n', s) ;
else
    if (mod (kk, 60) == 0)
        fprintf ('\n') ;
    end
    kk = kk + 1 ;
    fprintf ('.') ;
end
eval (s) ;


function option_num = p18_option_num ( )

%*****************************************************************************80
%
%% P18_OPTION_NUM returns the number of options for problem 18.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    03 September 2008
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, integer OPTION_NUM, the number of options.
%
  option_num = 1;

  return
end


classdef TestDescriptorMatcher
    %TestDescriptorMatcher

    properties (Constant)
        fields = {'queryIdx', 'trainIdx', 'imgIdx', 'distance'};
    end

    methods (Static)
        function test_1
            X = randn(20,3);
            Y = randn(5,3);
            matchers = { ...
                cv.DescriptorMatcher('BruteForce'), ...
                cv.DescriptorMatcher('BruteForce-L1'), ...
                cv.DescriptorMatcher('BruteForce-SL2'), ...
                cv.DescriptorMatcher('FlannBased'), ...
                cv.DescriptorMatcher('BFMatcher', ...
                    'NormType','L2', 'CrossCheck',false), ...
                cv.DescriptorMatcher('FlannBasedMatcher', ...
                    'Index',  {'KDTree', 'Trees',4}, ...
                    'Search', {'Checks',32, 'EPS',0, 'Sorted',true})
            };
            for i = 1:numel(matchers)
                typename = matchers{i}.typeid();
                matchers{i}.add(X);
                matchers{i}.train();

                m = matchers{i}.match(Y);
                validateattributes(m, {'struct'}, {'vector'});
                assert(all(ismember(TestDescriptorMatcher.fields, ...
                    fieldnames(m))));

                k = 3;
                m = matchers{i}.knnMatch(Y, k);
                validateattributes(m, {'cell'}, {'vector', 'numel',size(Y,1)});
                cellfun(@(mm) validateattributes(mm, {'struct'}, ...
                    {'vector', 'numel',k}), m);
                cellfun(@(mm) assert(all(ismember(...
                    TestDescriptorMatcher.fields, fieldnames(mm)))), m);

                maxDist = 2.0;
                m = matchers{i}.radiusMatch(Y, maxDist);
                validateattributes(m, {'cell'}, {'vector', 'numel',size(Y,1)});
                cellfun(@(mm) validateattributes(mm, ...
                    {'struct'}, {'vector'}), m);
                cellfun(@(mm) assert(all(ismember(...
                    TestDescriptorMatcher.fields, fieldnames(mm)))), m);
                assert(all(cellfun(@(mm) all([mm.distance] <= maxDist), m)));
            end
        end

        function test_2
            X = randi([0,255], [20,3], 'uint8');
            Y = randi([0,255], [5,3], 'uint8');
            matchers = { ...
                cv.DescriptorMatcher('BruteForce-Hamming'), ...
                cv.DescriptorMatcher('BruteForce-HammingLUT'), ...
                ... cv.DescriptorMatcher('BruteForce-Hamming(2)')  %TODO
            };
            for i = 1:numel(matchers)
                typename = matchers{i}.typeid();
                matchers{i}.add(X);
                matchers{i}.train();

                m = matchers{i}.match(Y);
                validateattributes(m, {'struct'}, {'vector'});
                assert(all(ismember(TestDescriptorMatcher.fields, ...
                    fieldnames(m))));

                k = 3;
                m = matchers{i}.knnMatch(Y, k);
                validateattributes(m, {'cell'}, ...
                    {'vector', 'numel',size(Y,1)});
                cellfun(@(mm) validateattributes(mm, {'struct'}, ...
                    {'vector', 'numel',k}), m);
                cellfun(@(mm) assert(all(ismember(...
                    TestDescriptorMatcher.fields, fieldnames(mm)))), m);

                maxDist = 10.0;
                m = matchers{i}.radiusMatch(Y, maxDist);
                validateattributes(m, {'cell'}, ...
                    {'vector', 'numel',size(Y,1)});
                cellfun(@(mm) validateattributes(mm, ...
                    {'struct'}, {'vector'}), m);
                cellfun(@(mm) assert(all(ismember(...
                    TestDescriptorMatcher.fields, fieldnames(mm)))), m);
                assert(all(cellfun(@(mm) all([mm.distance] <= maxDist), m)));
            end
        end

        function test_3
            X = randn(20,3);
            Y = randn(5,3);
            matcher = cv.DescriptorMatcher('BruteForce');
            assert(matcher.isMaskSupported());
            mask = rand(size(Y,1), size(X,1)) > 0.5;
            m = matcher.match(Y, X, 'Mask',mask);
            validateattributes(m, {'struct'}, {'vector'});
            m = matcher.knnMatch(Y, X, 3, 'Mask',mask);
            validateattributes(m, {'cell'}, {'vector', 'numel',size(Y,1)});
            m = matcher.radiusMatch(Y, X, 2.0, 'Mask',mask);
            validateattributes(m, {'cell'}, {'vector', 'numel',size(Y,1)});
        end

        function test_4
            files = dir(fullfile(mexopencv.root(),'test','shape0*.png'));
            if isempty(files)
                error('mexopencv:testskip', 'missing data');
            end
            query = [];

            % compute descriptors for all training images
            obj = cv.ORB();
            matcher = cv.DescriptorMatcher('BruteForce-Hamming');
            idxQuery = 1;
            idxTrain = setdiff(1:numel(files), idxQuery);
            for i=1:numel(files)
                img = cv.imread(fullfile(mexopencv.root(),'test',files(i).name), 'Flags',0);
                [~,desc] = obj.detectAndCompute(img);
                assert(~isempty(desc));
                if i == idxQuery
                    query = desc;
                else
                    matcher.add(desc);
                end
            end

            D = matcher.getTrainDescriptors();
            validateattributes(D, {'cell'}, ...
                {'vector', 'numel',numel(idxTrain)});
            cellfun(@(desc) validateattributes(desc, ...
                {obj.descriptorType()}, ...
                {'size',[NaN obj.descriptorSize()]}), D);

            % find matches between query and train set
            matcher.train();
            m = matcher.match(query);

            % naive approach to find nearest image
            [~,ord] = sort([m.distance]);         % retain best 100 (min dist)
            m = m(ord(1:min(100,end)));
            ii = idxTrain(mode([m.imgIdx]) + 1);  % most frequest image index
            query = files(idxQuery).name;
            closest = files(ii).name;
        end
    end

end


%kcxvisualHSV 'create visually a HSV constant image '
% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros cxvisualHSV.pane file
%
% Parameters:
% Integer: width 'Width', default: 100: 'width of the image'
% Integer: height 'Height', default: 100: 'height of the image'
% Integer: hue 'Initial Hue value', default: 0: 'initial hue'
% Integer: saturation 'Initial Saturation value', default: 100: 'initial saturation'
% Integer: value 'Initial Value value', default: 100: 'initial value'
% OutputFile: o 'Output', required: 'Resulting output data object'
%
% Example: o = kcxvisualHSV( {'width',100;'height',100;'hue',0;'saturation',100;'value',100;'o',''})
%
% Khoros helpfile follows below:
%
%  PROGRAM
% cxvisualHSV - create visually a HSV constant image
%
%  DESCRIPTION
% Allows the user to visually create an 3-band RGB image with Hue, Saturation and Value values specified via the user interface (values are shown in RGB too). Shows an area with the selected color while interacting.
%
%
%
%  EXAMPLES
%
%  "SEE ALSO"
% cxvisualRGB
%
%  RESTRICTIONS
%
%  REFERENCES
% All references for the toolbox COLOR are on the file $COLOR/Readme.html
%
%  COPYRIGHT
% Copyright (C) 1997 Rafael Santos. Khoros (C) Khoral Research, Inc.
%

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

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


% %function [xml, rxml] = LoadXml_old(FileBase)
% %loads the xml file using xmltools_olds (have to have it in the path)
% % rxml returns it's original layout - very messy structure but contains all
% % the xml file contents.
% % xml - is the ouput structure which is backwards compatible to LoadPar
% % output, so you can use it instead ..also loads some usefull stuff -
% % Anatomoical groups with Skips , Spike electrode groups
% % more can be added later (e.g. parameters of the process scripts)
% % this script is written for xml version 1.1 .. older version doesn't work.
% % additions are welcome
% %
% % By default, fbasename is the name of the directory where the data are, so
% % the exact xml file path should not be put in argument
% % By calling
% % xml = LoadXml(xmlfile,'raw')
% % the xml file specified in argument will be loaded
% % (added by A Peyrache)
%

function [xml, rxml] = LoadXml_old(fbasename,varargin)
% xml = struct;
warning(['this function is now deprecated from /buzcode and a '...
        ' backwards compatible version of LoadParameters.m will run now..\n'])
xml = LoadParameters(fbasename);
rxml =  xml;

%if isempty(varargin)
%    [fbasename mergedir rootdir] = extractfbasename(fbasename);
%elseif strcmpi(varargin,'raw')
%    fprintf('Loading directly xml file')
%else
%    error('Unrecognized option')
%end
% %if xml was in the filebase by chance
% xmli = strfind(fbasename,'.xml');
% if ~isempty(xmli)
%     fbasename = fbasename(1:xmli-1);
% end
% rxml = xmltools_old([fbasename '.xml']);
%
% rxml = rxml.child(2);
%
% % from this level all children are the different parameters fields
%
% xml.FileName = fbasename;
%
% for i=1:length(rxml.child)
%
%     switch rxml.child(i).tag
%
%         case 'generalInfo'
%             xml.Date = rxml.child(i).child(1).value; % date of xml file creation?
%
%         case 'acquisitionSystem'
%             xml.nBits = str2num(rxml.child(i).child(1).value); % number of bits of the file
%             xml.nChannels = str2num(rxml.child(i).child(2).value);
%             xml.SampleRate = str2num(rxml.child(i).child(3).value);
%             xml.SampleTime = 1e6/xml.SampleRate; %to make backwards compatible
%             xml.VoltageRange = str2num(rxml.child(i).child(4).value);
%             xml.Amplification = str2num(rxml.child(i).child(5).value);
%             xml.Offset =  str2num(rxml.child(i).child(6).value);
%
%         case 'fieldPotentials'
%             xml.lfpSampleRate = str2num(rxml.child(i).child.value);
%
%         case 'anatomicalDescription'
%             tmp = rxml.child(i).child.child;
%             for grpI =1:length(tmp)
%                 for chI=1:length(tmp(grpI).child)
%                     xml.AnatGrps(grpI).Channels(chI) = str2num(tmp(grpI).child(chI).value);
%                     xml.AnatGrps(grpI).Skip(chI) = str2num(tmp(grpI).child(chI).attribs.value);
%                 end
%             end
%
%         case 'spikeDetection'
%             if ~isempty(rxml.child(i).child)
%                 tmp =rxml.child(i).child.child;
%                 for grpI =1:length(tmp)
%                     for chI=1:length(tmp(grpI).child(1).child)
%                         xml.SpkGrps(grpI).Channels(chI) = str2num(tmp(grpI).child(1).child(chI).value);
%                     end
%                     if length(tmp(grpI).child)>1
%                         xml.SpkGrps(grpI).nSamples = str2num(tmp(grpI).child(2).value);
%                         xml.SpkGrps(grpI).PeakSample = str2num(tmp(grpI).child(3).value);
%                         xml.SpkGrps(grpI).nFeatures = str2num(tmp(grpI).child(4).value);
%                     end
%                     %backwards compatibility
%                     xml.nElecGps = length(tmp);
%                     xml.ElecGp{grpI} = xml.SpkGrps(grpI).Channels;
%                 end
%             else
%                 xml.nElecGps = 0;
%             end
%
%
%         case 'programs'
%             tmp = rxml.child(i).child;
%             for i=1:length(tmp)
%                 if strcmp(tmp(i).child(1).value,'process_mhipass')
%                     for j=1:length(tmp(i).child(2).child )
%                         if strcmp(tmp(i).child(2).child(j).child(1).value,'frequency')
%                             xml.HiPassFreq = str2num(tmp(i).child(2).child(j).child(2).value);
%                             break
%                         end
%                     end
%                 end
%             end
%     end
%
%
% end
%
%
% % general recursive parsing will have to wait.


% Copyright (C) 2013-2016 Nathanael Perraudin, Johan Paratte, David I Shuman.
% This file is part of GSPbox version {VERSION}
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.

% If you use this toolbox please kindly cite
%     N. Perraudin, J. Paratte, D. Shuman, V. Kalofolias, P. Vandergheynst,
%     and D. K. Hammond. GSPBOX: A toolbox for signal processing on graphs.
%     ArXiv e-prints, Aug. 2014.
% http://arxiv.org/abs/1408.5781


% Author: Guosheng Lin (guosheng.lin@gmail.com)

% This is an example of resume training with lower learning rate.

function demo_refinenet_train_reduce_learning_rate()

rng('shuffle');

addpath('./my_utils');
dir_matConvNet='../libs/matconvnet/matlab';
run(fullfile(dir_matConvNet, 'vl_setupnn.m'));

run_config=[];
ds_config=[];

run_config.use_gpu=true;
% run_config.use_gpu=false;
run_config.gpu_idx=1;

% use a random model name:
% model_name=['model_' datestr(now, 'YYYYmmDDHHMMSS')];

% or specify a model_name for training, if the cached snapshot files existed, it will resume training
% model_name='model_20161219094311_example';

% update the model name when reducing learning rate for training, e.g.,
model_name='model_20161219094311_example_epoch70_low_learn_rate';

ds_name='voc2012_trainval';
gen_ds_info_fn=@my_gen_ds_info_voc;

% control the size of input images
run_config.input_img_short_edge_min=450;
run_config.input_img_short_edge_max=1100;

run_config.input_img_scale=1;

ds_config.use_dummy_gt=false;
run_config.use_dummy_gt=ds_config.use_dummy_gt;
ds_config.use_custom_data=false;

ds_config.ds_name=ds_name;
ds_config.gen_ds_info_fn=gen_ds_info_fn;
ds_config.ds_info_cache_dir=fullfile('../datasets', ds_name);

run_config.root_cache_dir=fullfile('../cache_data', ds_name, model_name);
mkdir_notexist(run_config.root_cache_dir);

run_config.model_name=model_name;

diary_dir=run_config.root_cache_dir;
mkdir_notexist(diary_dir);
diary(fullfile(diary_dir, 'output.txt'));
diary on

run_dir_name=fileparts(mfilename('fullpath'));
[~, run_dir_name]=fileparts(run_dir_name);
run_config.run_dir_name=run_dir_name;
run_config.run_file_name=mfilename();

fprintf('\n\n\n=====================================================================\n');
disp('gen ds_info');

disp('ds_config:');
disp(ds_config);

ds_info=gen_dataset_info(ds_config);

my_diary_flush();

fprintf('\n\n\n=====================================================================\n');
disp('run network');

run_config.run_evaonly=false;

% settings for training:

% run_config.trained_model_path=[];
% run_config.learning_rate=5e-4;

% init from a cached model
% e.g., can be used for resuming network training with a lower learning rate by
% initilizing from a cached model.
% the following is an example for loading a cached model and using a lower learning
% to continue the training

run_config.trained_model_path='../cache_data/voc2012_trainval/model_20161219094311_example/model_cache/epoch_70';
run_config.learning_rate=5e-5;

run_config.epoch_num=600;

% turn on this option to cache all data into memory, if it's possible
% run_config.cache_data_mem=true;
run_config.cache_data_mem=false;

% random crop training:
run_config.crop_box_size=400;

% for cityscape, using a larger crop:
% run_config.crop_box_size=600;

% evaluate step: do evaluation every 5 epochs, can be set to 10:
run_config.eva_run_step=5;
run_config.snapshot_step=1;

% choose ImageNet pre-trained resnet:
run_config.init_resnet_layer_num=50;
% run_config.init_resnet_layer_num=101;
% run_config.init_resnet_layer_num=152;

% generate network
run_config.gen_network_fn=@gen_network_main;

run_config.gen_net_opts_fn=@gen_net_opts_model_type1;

% uncomment the following for debug:
% select a subset for both training and evaluation.
% ds_info.train_idxes=ds_info.train_idxes(1:10);
% ds_info.test_idxes=ds_info.train_idxes;
% run_config.snapshot_step=10;

train_opts=run_config.gen_net_opts_fn(run_config, ds_info.class_info);

disp('train_opts:');
disp(train_opts);

disp('train_opts.eva_param:');
disp(train_opts.eva_param);

my_diary_flush();

imdb=my_gen_imdb(train_opts, ds_info);

data_norm_info=[];
data_norm_info.image_mean=128;

imdb.ref.data_norm_info=data_norm_info;

if run_config.use_gpu
	gpu_num=gpuDeviceCount;
	if gpu_num>=1
		gpuDevice(run_config.gpu_idx);
    else
        error('no gpu found!');
	end
end

[net_config, net_exp_info]=prepare_running_model(train_opts);

% net_config can be changed here before running the network

my_net_tool(train_opts, imdb, net_config, net_exp_info);

fprintf('\n\n--------------------------------------------------\n\n');
disp('results are saved in:');
disp(run_config.root_cache_dir);

my_diary_flush();
diary off

end


function ind = wsddnVOChash_lookup(hash,s)
% From the PASCAL VOC 2011 devkit

hsize=numel(hash.key);
h=mod(str2double(s([4 6:end])),hsize)+1;
ind=hash.val{h}(strmatch(s,hash.key{h},'exact'));


function E = read_buffer_offline_events(eventfile, hdr)
% function E = read_buffer_offline_events(eventfile, header)
%
% This function reads FCDC buffer-type events from a binary file.

% (C) 2010 S. Klanke

type = {
  'char'
  'uint8'
  'uint16'
  'uint32'
  'uint64'
  'int8'
  'int16'
  'int32'
  'int64'
  'single'
  'double'
};

wordsize = {
  1 % 'char'
  1 % 'uint8'
  2 % 'uint16'
  4 % 'uint32'
  8 % 'uint64'
  1 % 'int8'
  2 % 'int16'
  4 % 'int32'
  8 % 'int64'
  4 % 'single'
  8 % 'double'
};

F = fopen_or_error(eventfile,'rb',hdr.orig.endianness);
numEvt = 0;

fseek(F, 0, 'eof');
fileSize = ftell(F);
fseek(F, 0, 'bof');

maxEvt = floor(fileSize / 32);
if maxEvt == 0
   E = [];
   return;
end

E = repmat(struct('type', 0, 'sample', 0, 'duration', 0, 'offset', 0, 'value', 0), [maxEvt,1]);

num=0;

while ~feof(F)
  try
    type_type   = fread(F, 1, 'uint32');
    type_numel  = fread(F, 1, 'uint32');
    value_type  = fread(F, 1, 'uint32');
    value_numel = fread(F, 1, 'uint32');
    sample      = fread(F, 1, 'int32');
    offset      = fread(F, 1, 'int32');
    duration    = fread(F, 1, 'int32');
    bufsize     = fread(F, 1, 'uint32');
    buf         = fread(F, bufsize, 'uint8=>uint8');
  catch
    break;
  end

  type_size  = wordsize{type_type+1}*type_numel;
  value_size = wordsize{value_type+1}*value_numel;

  if type_size + value_size > bufsize
     ft_warning('Invalid event definition - skipping remaining contents');
     break;
  end

  num=num+1;
  E(num).sample = sample + 1; % offset are 1-based in Matlab
  E(num).offset = offset;
  E(num).duration = duration;
  if type_type==0
    E(num).type = char(buf(1:type_size))';
  else
    E(num).type = typecast(buf(1:type_size), type{type_type+1});
  end
  if value_type==0
    E(num).value = char(buf((type_size+1):(type_size+value_size)))';
  else
    E(num).value = typecast(buf((type_size+1):(type_size+value_size)), type{value_type+1});
  end
end

E = E(1:num);


function varargout = uminus(varargin)
%UMINUS   Unary minus for a SPHEREFUN.

% Copyright 2017 by The University of Oxford and The Chebfun Developers.
% See http://www.chebfun.org/ for Chebfun information.

[varargout{1:nargout}] = uminus@separableApprox(varargin{:});

end


function  [plx] = get_all_from_plx(fileName)

plx = [];
if (nargin == 0 | isempty(fileName))
   [fname, pathname] = uigetfile('*.plx', 'Select a .plx file');
   if isequal(fname,0)
     error 'No file was selected'
     return
   end
   fileName = fullfile(pathname, fname);
end

[plx.tscounts, plx.wfcounts, plx.evcounts, plx.slowcounts] = plx_info(fileName,1);
[OpenedFilePath, plx.Version, plx.Freq, plx.Comment, plx.Trodalness, plx.NPW, plx.PreThresh, plx.SpikePeakV, plx.SpikeADResBits, plx.SlowPeakV, plx.SlowADResBits, plx.Duration, plx.DateTime] = plx_information(fileName);
[dirstr, name, ext] = fileparts(OpenedFilePath);
plx.FileName = [name ext];

% try valid and invalid channels and units
% max unit is 26
% max spike channel number is 128
for iunit = -1:30
    for ich = -1:130
        [plx.ts.n{iunit+2,ich+2}, plx.ts.ts{iunit+2,ich+2}] = plx_ts(fileName, ich , iunit );
        [plx.wf.n{iunit+2,ich+2}, plx.wf.npw{iunit+2,ich+2}, plx.wf.ts{iunit+2,ich+2}, plx.wf.wf{iunit+2,ich+2}] = plx_waves(fileName, ich , iunit );
        [plx.wf_v.n{iunit+2,ich+2}, plx.wf_v.npw{iunit+2,ich+2}, plx.wf_v.ts{iunit+2,ich+2}, plx.wf_v.wf{iunit+2,ich+2}] = plx_waves_v(fileName, ich , iunit );
     end
end

[nspk,plx.spk_filters] = plx_chan_filters(fileName);
[nspk,plx.spk_gains] = plx_chan_gains(fileName);
[nspk,plx.spk_threshs] = plx_chan_thresholds(fileName);
[nspk,plx.spk_names] = plx_chan_names(fileName);

% try valid and invalid channels
% ona 128-channel system, there could be 128*3 a/d channels
for ich = -1:400
	[plx.ad_gi.freq{ich+2}, plx.ad_gi.nad{ich+2}, plx.ad_gi.ts{ich+2}, plx.ad_gi.frag{ich+2}] = plx_ad_gap_info(fileName, ich);
	[plx.ad.freq{ich+2}, plx.ad.nad{ich+2}, plx.ad.ts{ich+2}, plx.ad.frag{ich+2}, plx.ad.val{ich+2}] = plx_ad(fileName, ich);
	[plx.ad_v.freq{ich+2}, plx.ad_v.nad{ich+2}, plx.ad_v.ts{ich+2}, plx.ad_v.frag{ich+2}, plx.ad_v.val{ich+2}] = plx_ad_v(fileName, ich);
	[plx.ad_span.freq{ich+2}, plx.ad_span.nad{ich+2}, plx.ad_span.val{ich+2}] = plx_ad_span(fileName, ich, 10,20);
	[plx.ad_span_v.freq{ich+2}, plx.ad_span_v.nad{ich+2} plx.ad_span_v.val{ich+2}] = plx_ad_span_v(fileName, ich, 10,20);
    % try invalid start/end combinations
	[plx.ad_span_inv1.freq{ich+2}, plx.ad_span_inv1.nad{ich+2} plx.ad_span_inv1.val{ich+2}] = plx_ad_span_v(fileName, ich, 10,-5);
    [plx.ad_span_inv2.freq{ich+2}, plx.ad_span_inv2.nad{ich+2} plx.ad_span_inv2.val{ich+2}] = plx_ad_span_v(fileName, ich, 10,9);
    [plx.ad_span_inv3.freq{ich+2}, plx.ad_span_inv3.nad{ich+2} plx.ad_span_inv3.val{ich+2}] = plx_ad_span_v(fileName, ich, -2,3);
end

[nad,plx.adfreqs] = plx_adchan_freqs(fileName);
[nad,plx.adgains] = plx_adchan_gains(fileName);
[nad,plx.adnames] = plx_adchan_names(fileName);

% the events
[u,plx.evnames] = plx_event_names(fileName);
[u,plx.evchans] = plx_event_chanmap(fileName);
for iev = -1:310
	[plx.nevs{iev+2}, plx.tsevs{iev+2}, plx.svdummy{iev+2}] = plx_event_ts(fileName, iev);
	if ( iev > 0 && iev <= length(plx.evchans) && plx.evcounts(iev) > 0 )
	    evch = plx.evchans(iev);
	    if ( evch == 257 )
			[plx.strobed.n, plx.strobed.ts, plx.strobed.v] = plx_event_ts(fileName, evch);
            [plx.nCoords, plx.nDim, plx.nVTMode, plx.c] = plx_vt_interpret(plx.strobed.ts, plx.strobed.v);
        end
    end
end

plx_close(fileName);

% try to get a/d channel after closing
for ich = -1:400
	[plx.ad2.freq{ich+2}, plx.ad2.nad{ich+2}, plx.ad2.ts{ich+2}, plx.ad2.frag{ich+2}, plx.ad2.val{ich+2}] = plx_ad(fileName, ich);
end
plx_close('');


function [data, mmap] = loadjson(fname,varargin)
%
% data=loadjson(fname,opt)
%    or
% [data, mmap]=loadjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string and return a
% matlab data structure with optional memory-map (mmap) table
%
% authors:Qianqian Fang (q.fang <at> neu.edu)
% created on 2011/09/09, including previous works from
%
%         Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713
%            created on 2009/11/02
%         François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393
%            created on  2009/03/22
%         Joel Feenstra:
%         http://www.mathworks.com/matlabcentral/fileexchange/20565
%            created on 2008/07/03
%
% input:
%      fname: input file name; if fname contains "{}" or "[]", fname
%             will be interpreted as a JSON string
%      opt: (optional) a struct to store parsing options, opt can be replaced by
%           a list of ('param',value) pairs - the param string is equivallent
%           to a field in opt. opt can have the following
%           fields (first in [.|.] is the default)
%
%           SimplifyCell [1|0]: if set to 1, loadjson will call cell2mat
%                         for each element of the JSON data, and group
%                         arrays based on the cell2mat rules.
%           FastArrayParser [1|0 or integer]: if set to 1, use a
%                         speed-optimized array parser when loading an
%                         array object. The fast array parser may
%                         collapse block arrays into a single large
%                         array similar to rules defined in cell2mat; 0 to
%                         use a legacy parser; if set to a larger-than-1
%                         value, this option will specify the minimum
%                         dimension to enable the fast array parser. For
%                         example, if the input is a 3D array, setting
%                         FastArrayParser to 1 will return a 3D array;
%                         setting to 2 will return a cell array of 2D
%                         arrays; setting to 3 will return to a 2D cell
%                         array of 1D vectors; setting to 4 will return a
%                         3D cell array.
%           UseMap [0|1]: if set to 1, loadjson uses a containers.Map to
%                         store map objects; otherwise use a struct object
%           ShowProgress [0|1]: if set to 1, loadjson displays a progress bar.
%           ParseStringArray [0|1]: if set to 0, loadjson converts "string arrays"
%                         (introduced in MATLAB R2016b) to char arrays; if set to 1,
%                         loadjson skips this conversion.
%           FormatVersion [3|float]: set the JSONLab format version; since
%                         v2.0, JSONLab uses JData specification Draft 1
%                         for output format, it is incompatible with all
%                         previous releases; if old output is desired,
%                         please set FormatVersion to 1.9 or earlier.
%           Encoding ['']: json file encoding. Support all encodings of
%                         fopen() function
%           ObjectID [0|interger or list]: if set to a positive number,
%                         it returns the specified JSON object by index
%                         in a multi-JSON document; if set to a vector,
%                         it returns a list of specified objects.
%           JDataDecode [1|0]: if set to 1, call jdatadecode to decode
%                         JData structures defined in the JData
%                         Specification.
%           BuiltinJSON [0|1]: if set to 1, this function attempts to call
%                         jsondecode, if presents (MATLAB R2016b or Octave
%                         6) first. If jsondecode does not exist or failed,
%                         this function falls back to the jsonlab parser
%           MmapOnly [0|1]: if set to 1, this function only returns mmap
%           MMapInclude 'str1' or  {'str1','str2',..}: if provided, the
%                         returned mmap will be filtered by only keeping
%                         entries containing any one of the string patterns
%                         provided in a cell
%           MMapExclude 'str1' or  {'str1','str2',..}: if provided, the
%                         returned mmap will be filtered by removing
%                         entries containing any one of the string patterns
%                         provided in a cell
%
% output:
%      dat: a cell array, where {...} blocks are converted into cell arrays,
%           and [...] are converted to arrays
%      mmap: (optional) a cell array as memory-mapping table in the form of
%             {{jsonpath1,[start,length,<whitespace_pre>]},
%              {jsonpath2,[start,length,<whitespace_pre>]}, ...}
%           where jsonpath_i is a string in the JSONPath [1,2] format, and
%           "start" is an integer referring to the offset from the begining
%           of the stream, and "length" is the JSON object string length.
%           An optional 3rd integer "whitespace_pre" may appear to record
%           the preceding whitespace length in case expansion of the data
%           record is needed when using the mmap.
%
%           The format of the mmap table retruned from this function
%           follows the JSON-Mmap Specification Draft 1 [3] defined by the
%           NeuroJSON project, see https://neurojson.org/jsonmmap/draft1/
%
%           Memory-mapping table (mmap) is useful when fast reading/writing
%           specific data records inside a large JSON file without needing
%           to load/parse/overwrite the entire file.
%
%           The JSONPath keys used in mmap is largely compatible to the
%           upstream specification defined in [1], with a slight extension
%           to handle contatenated JSON files.
%
%           In the mmap jsonpath key, a '$' denotes the root object, a '.'
%           denotes a child of the preceding element; '.key' points to the
%           value segment of the child named "key" of the preceding
%           object; '[i]' denotes the (i+1)th member of the preceding
%           element, which must be an array. For example, a key
%
%           $.obj1.obj2[0].obj3
%
%           defines the memory-map of the "value" section in the below
%           hierarchy:
%             {
%                "obj1":{
%            	     "obj2":[
%                       {"obj3":value},
%                       ...
%                    ],
%                    ...
%                 }
%             }
%           Please note that "value" can be any valid JSON value, including
%           an array, an object, a string or numerical value.
%
%           To handle concatenated JSON objects (including ndjson,
%           http://ndjson.org/), such as
%
%             {"root1": {"obj1": ...}}
%             ["root2", value1, value2, {"obj2": ...}]
%             {"root3": ...}
%
%           we use '$' or '$0' for the first root-object, and '$1' refers
%           to the 2nd root object (["root2",...]) and '$2' referrs to the
%           3rd root object, and so on. Please note that this syntax is an
%           extension from the JSONPath documentation [1,2]
%
%           [1] https://goessner.net/articles/JsonPath/
%           [2] http://jsonpath.herokuapp.com/
%           [3] https://neurojson.org/jsonmmap/draft1/
%
% examples:
%      dat=loadjson('{"obj":{"string":"value","array":[1,2,3]}}')
%      dat=loadjson(['examples' filesep 'example1.json'])
%      [dat, mmap]=loadjson(['examples' filesep 'example1.json'],'SimplifyCell',0)
%
% license:
%     BSD or GPL version 3, see LICENSE_{BSD,GPLv3}.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%

    opt=varargin2struct(varargin{:});

    if(regexp(fname,'^\s*(?:\[.*\])|(?:\{.*\})\s*$','once'))
       string=fname;
    elseif(exist(fname,'file'))
       try
           encoding = jsonopt('Encoding','',opt);
           if(isempty(encoding))
               string = fileread(fname);
           else
               fid = fopen(fname,'r','n',encoding);
               string = fread(fid,'*char')';
               fclose(fid);
           end
       catch
           try
               string = urlread(fname);
           catch
               string = urlread(['file://',fullfile(pwd,fname)]);
           end
       end
    elseif(regexpi(fname,'^\s*(http|https|ftp|file)://'))
       string = urlread(fname);
    else
       error_pos('input file does not exist');
    end

    if(jsonopt('BuiltinJSON',0,opt) && exist('jsondecode','builtin'))
        try
            newstring=regexprep(string,'[\r\n]','');
            newdata=jsondecode(newstring);
            newdata=jdatadecode(newdata,'Base64',1,'Recursive',1,varargin{:});
            data=newdata;
            return;
        catch
            warning('built-in jsondecode function failed to parse the file, fallback to loadjson');
        end
    end

    pos = 1; inputlen = length(string); inputstr = string;
    arraytokenidx=find(inputstr=='[' | inputstr==']');
    arraytoken=inputstr(arraytokenidx);

    % String delimiters and escape chars identified to improve speed:
    esc = find(inputstr=='"' | inputstr=='\' ); % comparable to: regexp(inputstr, '["\\]');
    index_esc = 1;

    opt.arraytoken_=arraytoken;
    opt.arraytokenidx_=arraytokenidx;
    opt.simplifycell=jsonopt('SimplifyCell',1,opt);
    opt.simplifycellarray=jsonopt('SimplifyCellArray',opt.simplifycell,opt);
    opt.formatversion=jsonopt('FormatVersion',3,opt);
    opt.fastarrayparser=jsonopt('FastArrayParser',1,opt);
    opt.parsestringarray=jsonopt('ParseStringArray',0,opt);
    opt.usemap=jsonopt('UseMap',0,opt);
    opt.arraydepth_=1;
    opt.mmaponly=jsonopt('MmapOnly',0,opt);

    if(jsonopt('ShowProgress',0,opt)==1)
        opt.progressbar_=waitbar(0,'loading ...');
    end

    objid=jsonopt('ObjectID',0,opt);
    maxobjid=max(objid);
    if(maxobjid==0)
        maxobjid=inf;
    end
    opt.jsonpath_='$';
    if(nargout>1 || opt.mmaponly)
        mmap={};
    end
    jsoncount=1;
    while pos <= inputlen
        [cc,pos,w1]=next_char(inputstr, pos);
        switch(cc)
            case '{'
                if(nargout>1 || opt.mmaponly)
                    mmap{end+1}={opt.jsonpath_,[pos, 0, w1]};
                    [data{jsoncount},pos,index_esc,newmmap] = parse_object(inputstr, pos, esc, index_esc,opt);
                    mmap{end}{2}(2)=pos-mmap{end}{2}(1);
                    mmap=[mmap(:);newmmap(:)];
                else
                    [data{jsoncount},pos,index_esc] = parse_object(inputstr, pos, esc, index_esc,opt);
                end
            case '['
                if(nargout>1 || opt.mmaponly)
                    mmap{end+1}={opt.jsonpath_,[pos,0,w1]};
                    [data{jsoncount},pos,index_esc,newmmap] = parse_array(inputstr, pos, esc, index_esc,opt);
                    mmap{end}{2}(2)=pos-mmap{end}{2}(1);
                    mmap=[mmap(:);newmmap(:)];
                else
                    [data{jsoncount},pos,index_esc] = parse_array(inputstr, pos, esc, index_esc,opt);
                end
            otherwise
                pos=error_pos('Outer level structure must be an object or an array',inputstr,pos);
        end
	    if(jsoncount>=maxobjid)
	        break;
	    end
        opt.jsonpath_=sprintf('$%d',jsoncount);
        jsoncount=jsoncount+1;
    end % while

    if(length(objid)>1 || min(objid)>1)
        data=data(objid(objid<=length(data)));
    end

    jsoncount=length(data);
    if(jsoncount==1 && iscell(data))
        data=data{1};
    end
    if(nargout>1 || opt.mmaponly)
        mmap=mmap';
        mmap=filterjsonmmap(mmap, jsonopt('MMapExclude',{},opt), 0);
        mmap=filterjsonmmap(mmap, jsonopt('MMapInclude',{},opt), 1);
        mmap=cellfun(@(x) {x{1},x{2}(1:(2+int8(length(x{2})>=3 && (x{2}(3)>0))))}, mmap, 'UniformOutput', false);
    end
    if(jsonopt('JDataDecode',1,varargin{:})==1)
        try
            data=jdatadecode(data,'Base64',1,'Recursive',1,varargin{:});
        catch ME
            warning(['Failed to decode embedded JData annotations, '...
                'return raw JSON data\n\njdatadecode error: %s\n%s\nCall stack:\n%s\n'], ...
                ME.identifier, ME.message, savejson('',ME.stack));
        end
    end
    if(opt.mmaponly)
        data=mmap;
    end
    if(isfield(opt,'progressbar_'))
        close(opt.progressbar_);
    end
end

%%-------------------------------------------------------------------------
%% helper functions
%%-------------------------------------------------------------------------

function [object, pos,index_esc, mmap] = parse_array(inputstr, pos, esc, index_esc, varargin) % JSON array is written in row-major order
    if(nargout>3)
        mmap={};
        origpath=varargin{1}.jsonpath_;
    end
    pos=parse_char(inputstr, pos, '[');
    object = cell(0, 1);
    arraydepth=varargin{1}.arraydepth_;
    pbar=-1;
    if(isfield(varargin{1},'progressbar_'))
        pbar=varargin{1}.progressbar_;
    end
    format=varargin{1}.formatversion;
    [cc,pos]=next_char(inputstr,pos);
    endpos=[];

    if cc ~= ']'
        try
            if((varargin{1}.fastarrayparser)>=1 && arraydepth>=varargin{1}.fastarrayparser)
                [endpos, maxlevel]=fast_match_bracket(varargin{1}.arraytoken_,varargin{1}.arraytokenidx_,pos);
                if(~isempty(endpos))
                    arraystr=['[' inputstr(pos:endpos)];
                    arraystr=sscanf_prep(arraystr);
                    if(isempty(find(arraystr=='"', 1)))
                        % handle 1D array first
                        if(maxlevel==1)
                            astr=arraystr(2:end-1);
                            astr(astr==' ')='';
                            [obj, count, errmsg, nextidx]=sscanf(astr,'%f,',[1,inf]);
                            if(nextidx>=length(astr)-1)
                                    object=obj;
                                    pos=endpos;
                                    pos=parse_char(inputstr, pos, ']');
                                    return;
                            end
                        end

                        % for N-D packed array in a nested array construct,
                        if(maxlevel>=2 && ~isempty(regexp(arraystr(2:end),'^\s*\[','once')))
                            [dims,isndarray]=nestbracket2dim(arraystr);
                            rowstart=find(arraystr(2:end)=='[',1)+1;
                            if(rowstart && isndarray)
                                [obj, nextidx]=parsendarray(arraystr,dims);
                                if(nextidx>=length(arraystr)-1)
                                    object=obj;
                                    if(format>1.9)
                                        object=permute(object,ndims(object):-1:1);
                                    end
                                    pos=endpos;
                                    pos=parse_char(inputstr, pos, ']');
                                    if(pbar>0)
                                        waitbar(pos/length(inputstr),pbar,'loading ...');
                                    end
                                    return;
                                end
                            end
                        end
                    end
                end
            end
            if(isempty(regexp(arraystr,':','once')) && isempty(regexp(arraystr,'\(','once')))
                arraystr=regexprep(arraystr,'\[','{');
                arraystr=regexprep(arraystr,'\]','}');
                if(varargin{1}.parsestringarray==0)
                    arraystr=regexprep(arraystr,'\"','''');
                end
                object=eval(arraystr);
                if(iscell(object))
                    object=cellfun(@unescapejsonstring,object,'UniformOutput',false);
                end
                pos=endpos;
            end
        catch
        end
        if(isempty(endpos) || pos~=endpos)
            w2=0;
            while 1
                varargin{1}.arraydepth_=arraydepth+1;
                if(nargout>3)
                    varargin{1}.jsonpath_=[origpath sprintf('[%d]',length(object))];
                    mmap{end+1}={varargin{1}.jsonpath_, [pos, 0, w2]};
                    [val, pos, index_esc, newmmap] = parse_value(inputstr, pos, esc, index_esc,varargin{:});
                    mmap{end}{2}(2)=pos-mmap{end}{2}(1);
                    mmap=[mmap(:);newmmap(:)];
                else
                    [val, pos,index_esc] = parse_value(inputstr, pos, esc, index_esc,varargin{:});
                end
                object{end+1} = val;
                [cc,pos]=next_char(inputstr,pos);
                if cc == ']'
                    break;
                end
                [pos, w1, w2]=parse_char(inputstr, pos, ',');
            end
        end
    end

    if(varargin{1}.simplifycell)
      if(iscell(object) && ~isempty(object) && (all(cellfun(@isnumeric, object)) || all(cellfun(@isstruct, object))))
          if(all(cellfun(@(e) isequal(size(object{1}), size(e)), object(2:end))))
              try
                  oldobj=object;
                  if(iscell(object) && length(object)>1 && ndims(object{1})>=2)
                      catdim=size(object{1});
                      catdim=ndims(object{1})-(catdim(end)==1)+1;
                      object=cat(catdim,object{:});
                      object=permute(object,ndims(object):-1:1);
                  else
                      object=cell2mat(object.').';
                  end
                  if(iscell(oldobj) && isstruct(object) && numel(object)>1 && varargin{1}.simplifycellarray==0)
                      object=oldobj;
                  end
              catch
              end
          end
      end
      if(~iscell(object) && size(object,1)>1 && ndims(object)==2)
            object=object.';
      end
    end
    pos=parse_char(inputstr, pos, ']');

    if(pbar>0)
        waitbar(pos/length(inputstr),pbar,'loading ...');
    end
end
%%-------------------------------------------------------------------------

function [pos, w1, w2]=parse_char(inputstr, pos, c)
    w1=pos;
    w2=0;
    pos=skip_whitespace(pos, inputstr);
    w1=pos-w1;
    if pos > length(inputstr) || inputstr(pos) ~= c
        pos=error_pos(sprintf('Expected %c at position %%d', c),inputstr,pos);
    else
        pos = pos + 1;
        w2=pos;
        pos=skip_whitespace(pos, inputstr);
        w2=pos-w2;
    end
end
%%-------------------------------------------------------------------------

function [c, pos, w1] = next_char(inputstr, pos)
    w1=pos;
    pos=skip_whitespace(pos, inputstr);
    w1=pos-w1;
    if pos > length(inputstr)
        c = [];
    else
        c = inputstr(pos);
    end
end

%%-------------------------------------------------------------------------
function [str, pos,index_esc, mmap] = parseStr(inputstr, pos, esc, index_esc, varargin)
    if(nargout>3)
        mmap={};
    end
    if inputstr(pos) ~= '"'
        pos=error_pos('String starting with " expected at position %d',inputstr,pos);
    else
        pos = pos + 1;
    end
    str = '';
    while pos <= length(inputstr)
        while index_esc <= length(esc) && esc(index_esc) < pos
            index_esc = index_esc + 1;
        end
        if index_esc > length(esc)
            str = [str inputstr(pos:end)];
            pos = length(inputstr) + 1;
            break;
        else
            str = [str inputstr(pos:esc(index_esc)-1)];
            pos = esc(index_esc);
        end
        nstr = length(str);
        switch inputstr(pos)
            case '"'
                pos = pos + 1;
                if(~isempty(str))
                    if(strcmp(str,'_Inf_'))
                        str=Inf;
                    elseif(strcmp(str,'-_Inf_'))
                        str=-Inf;
                    elseif(strcmp(str,'_NaN_'))
                        str=NaN;
                    end
                end
                return;
            case '\'
                if pos+1 > length(inputstr)
                    pos=error_pos('End of file reached right after escape character',inputstr,pos);
                end
                pos = pos + 1;
                switch inputstr(pos)
                    case {'"' '\' '/'}
                        str(nstr+1) = inputstr(pos);
                        pos = pos + 1;
                    case {'b' 'f' 'n' 'r' 't'}
                        str(nstr+1) = sprintf(['\' inputstr(pos)]);
                        pos = pos + 1;
                    case 'u'
                        if pos+4 > length(inputstr)
                            pos=error_pos('End of file reached in escaped unicode character',inputstr,pos);
                        end
                        str(nstr+(1:6)) = inputstr(pos-1:pos+4);
                        pos = pos + 5;
                end
            otherwise % should never happen
                str(nstr+1) = inputstr(pos);
                keyboard;
                pos = pos + 1;
        end
    end
    str=unescapejsonstring(str);
    pos=error_pos('End of file while expecting end of inputstr',inputstr,pos);
end
%%-------------------------------------------------------------------------

function [num, pos] = parse_number(inputstr, pos, varargin)
    currstr=inputstr(pos:min(pos+30,end));
    [num, one, err, delta] = sscanf(currstr, '%f', 1);
    if ~isempty(err)
        pos=error_pos('Error reading number at position %d',inputstr,pos);
    end
    pos = pos + delta-1;
end
%%-------------------------------------------------------------------------

function varargout = parse_value(inputstr, pos, esc, index_esc, varargin)
    len=length(inputstr);
    if(isfield(varargin{1},'progressbar_'))
        waitbar(pos/len,varargin{1}.progressbar_,'loading ...');
    end
    varargout{3}=index_esc;
    if(nargout>3)
            varargout{4}={};
    end
    switch(inputstr(pos))
        case '"'
            [varargout{1:nargout}] = parseStr(inputstr, pos, esc, index_esc,varargin{:});
            return;
        case '['
            [varargout{1:nargout}] = parse_array(inputstr, pos, esc, index_esc, varargin{:});
            return;
        case '{'
            [varargout{1:nargout}] = parse_object(inputstr, pos, esc, index_esc, varargin{:});
            return;
        case {'-','0','1','2','3','4','5','6','7','8','9'}
            [varargout{1:2}] = parse_number(inputstr, pos, varargin{:});
            return;
        case 't'
            if pos+3 <= len && strcmpi(inputstr(pos:pos+3), 'true')
                varargout{1} = true;
                varargout{2} = pos + 4;
                return;
            end
        case 'f'
            if pos+4 <= len && strcmpi(inputstr(pos:pos+4), 'false')
                varargout{1} = false;
                varargout{2} = pos + 5;
                return;
            end
        case 'n'
            if pos+3 <= len && strcmpi(inputstr(pos:pos+3), 'null')
                varargout{1} = [];
                varargout{2} = pos + 4;
                return;
            end
    end
    varargout{2}=error_pos('Value expected at position %d',inputstr,pos);
end

%%-------------------------------------------------------------------------
function [object, pos, index_esc, mmap] = parse_object(inputstr, pos, esc, index_esc, varargin)
    if(nargout>3)
        mmap={};
        origpath=varargin{1}.jsonpath_;
    end
    pos=parse_char(inputstr, pos, '{');
    usemap=varargin{1}.usemap;
    if(usemap)
	object = containers.Map();
    else
	object = [];
    end
    [cc,pos]=next_char(inputstr,pos);
    if cc ~= '}'
        while 1
            [str, pos, index_esc] = parseStr(inputstr, pos, esc, index_esc, varargin{:});
            if isempty(str) && ~usemap
                str='x0x0_'; % empty name is valid in JSON, decodevarname('x0x0_') restores '\0'
            end
            [pos, w1, w2]=parse_char(inputstr, pos, ':');
            if(nargout>3)
                varargin{1}.jsonpath_=[origpath,'.',str];
                mmap{end+1}={varargin{1}.jsonpath_,[pos,0,w2]};
                [val, pos,index_esc, newmmap] = parse_value(inputstr, pos, esc, index_esc, varargin{:});
                mmap{end}{2}(2)=pos-mmap{end}{2}(1);
                mmap=[mmap(:);newmmap(:)];
            else
                [val, pos,index_esc] = parse_value(inputstr, pos, esc, index_esc, varargin{:});
            end
            if(usemap)
		object(str)=val;
	    else
		object.(encodevarname(str,varargin{:}))=val;
	    end
            [cc,pos]=next_char(inputstr,pos);
            if cc == '}'
                break;
            end
            pos=parse_char(inputstr, pos, ',');
        end
    end
    pos=parse_char(inputstr, pos, '}');
end

%%-------------------------------------------------------------------------

function pos=error_pos(msg, inputstr, pos)
    poShow = max(min([pos-15 pos-1 pos pos+20],length(inputstr)),1);
    if poShow(3) == poShow(2)
        poShow(3:4) = poShow(2)+[0 -1];  % display nothing after
    end
    msg = [sprintf(msg, pos) ': ' ...
    inputstr(poShow(1):poShow(2)) '<error>' inputstr(poShow(3):poShow(4)) ];
    error( ['JSONLAB:JSON:InvalidFormat: ' msg] );
end

%%-------------------------------------------------------------------------

function newpos=skip_whitespace(pos, inputstr)
    newpos=pos;
    while newpos <= length(inputstr) && isspace(inputstr(newpos))
        newpos = newpos + 1;
    end
end

%%-------------------------------------------------------------------------
function newstr=unescapejsonstring(str)
    newstr=str;
    if(iscell(str))
        try
            newstr=cell2mat(cellfun(@(x) cell2mat(x),str(:),'un',0));
        catch
        end
    end
    if(~ischar(str))
        return;
    end
    escapechars={'\\','\"','\/','\a','\b','\f','\n','\r','\t','\v'};
    for i=1:length(escapechars)
        newstr=regexprep(newstr,regexprep(escapechars{i},'\\','\\\\'), escapechars{i});
    end
    newstr=regexprep(newstr,'\\u([0-9A-Fa-f]{4})', '${char(base2dec($1,16))}');
end

%%-------------------------------------------------------------------------
function arraystr=sscanf_prep(str)
    arraystr=str;
    if(regexp(str,'"','once'))
        arraystr=regexprep(arraystr,'"_NaN_"','NaN');
        arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf');
    end
    arraystr(arraystr==sprintf('\n'))=' ';
    arraystr(arraystr==sprintf('\r'))=' ';
end

%%-------------------------------------------------------------------------
function [obj, nextidx]=parsendarray(arraystr, dims)
    astr=arraystr;
    astr(astr=='[')=' ';
    astr(astr==']')=' ';
    astr(astr==',')=' ';
    [obj, count, errmsg, nextidx]=sscanf(astr,'%f',inf);
    if(nextidx>=length(astr)-1)
            obj=reshape(obj,dims);
            nextidx=length(arraystr)+1;
    end
end


function [c, r, t, cpulse] = tapas_physio_read_physlogfiles_GE(log_files, ...
verbose)
% reads out physiological time series and timing vector depending on the
% MR scanner vendor and the modality of peripheral cardiac monitoring (ECG
% or pulse oximetry)
%
%   [cpulse, rpulse, t, c] = tapas_physio_read_physlogfiles_GE(logfiles, ...
%                               verbose)
%
%   NOTE: if one
%
% IN    log_files
%       .log_cardiac        contains ECG or pulse oximeter time course
%                           for GE: ECGData...
%       .log_respiration    contains breathing belt amplitude time course
%                           for GE: RespData...
%       .sampling_interval  1 entry: sampling interval (seconds)
%                           for both log files
%                           2 entries: 1st entry sampling interval (seconds)
%                           for cardiac logfile, 2nd entry for respiratory
%                           logfile
%       verbose
%       .level              debugging plots are created if level >=3
%       .fig_handles        appended by handle to output figure
%
% OUT
%   cpulse              time events of R-wave peak in cardiac time series (seconds)
%                       for GE: usually empty
%   r                   respiratory time series
%   t                   vector of time points (in seconds)
%                       NOTE: This assumes the default sampling rate of 40
%                       Hz
%   c                   cardiac time series (ECG or pulse oximetry)
%
% EXAMPLE
%   [ons_secs.cpulse, ons_secs.rpulse, ons_secs.t, ons_secs.c] =
%       tapas_physio_read_physlogfiles_GE(logfiles);
%
%   See also tapas_physio_main_create_regressors

% Author: Lars Kasper
% Created: 2013-02-16
% Copyright (C) 2013 Institute for Biomedical Engineering, ETH/Uni Zurich.
%
% This file is part of the PhysIO toolbox, which is released under the terms of the GNU General Public
% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL
% (either version 3 or, at your option, any later version). For further details, see the file
% COPYING or <http://www.gnu.org/licenses/>.

%% read out values
DEBUG = verbose.level >= 3;

hasRespirationFile = ~isempty(log_files.respiration);
hasCardiacFile = ~isempty(log_files.cardiac);

if hasRespirationFile
    r = load(log_files.respiration, 'ascii');
else
    r = [];
end

if hasCardiacFile
    c = load(log_files.cardiac, 'ascii');
else
    c = [];
end

%% interpolate to greater precision, if 2 different sampling rates are given

dt = log_files.sampling_interval;

hasDifferentSamplingRates = numel(dt) > 1;

if hasDifferentSamplingRates && hasCardiacFile && hasRespirationFile
    dtCardiac = dt(1);
    dtRespiration = dt(2);
    isHigherSamplingCardiac = dtCardiac < dtRespiration;

    nSamplesRespiration = size(r,1);
    nSamplesCardiac = size(c,1);

    tCardiac = -log_files.relative_start_acquisition + ...
        ((0:(nSamplesCardiac-1))*dtCardiac)';

    tRespiration = -log_files.relative_start_acquisition + ...
        ((0:(nSamplesRespiration-1))*dtRespiration)';

    if isHigherSamplingCardiac
        t = tCardiac;
        rInterp = interp1(tRespiration, r, t);

        if DEBUG
            fh = plot_interpolation(tRespiration, r, t, rInterp, ...
                {'respiratory', 'cardiac'});
            verbose.fig_handles(end+1) = fh;
        end
        r = rInterp;

    else
        t = tRespiration;
        cInterp = interp1(tCardiac, c, t);

        if DEBUG
            fh = plot_interpolation(tCardiac, c, t, cInterp, ...
                {'cardiac', 'respiratory'});
            verbose.fig_handles(end+1) = fh;
        end
        c = cInterp;

    end

else
    nSamples = size(c,1);
    t = -log_files.relative_start_acquisition + ((0:(nSamples-1))*dt)';
end

cpulse = [];
end

% local function to plot interpolation result
function fh = plot_interpolation(tOrig, yOrig, tInterp, yInterp, ...
    stringOrigInterp)
fh = tapas_physio_get_default_fig_params;
stringTitle = sprintf('Read-In: Interpolation of %s signal', stringOrigInterp{1});
set(fh, 'Name', stringTitle);
plot(tOrig, yOrig, 'go--');  hold all;
plot(tInterp, yInterp,'r.');
legend({
    sprintf('after interpolation to %s timing', ...
    stringOrigInterp{1}), ...
    sprintf('original %s time series', stringOrigInterp{2}) });
title(stringTitle);
xlabel('time (seconds');
end


%GETOBJSIZE Get object size
%
%    OBJSIZE = GETOBJSIZE(A,N)
%    [OBJSIZE1,OBJSIZE2,OBJSIZE3] = GETOBJSIZE(A)
%
% Note that the object size can be a scalar, or, in case of feature images,
% an image size vector.


function M = Qdec2num(Qdec)
% M = Qdec2num(Qdec)
%
% Attempts to convert the two dimensional cell string array Qdec to numeric
% matrix M.
%
% Input
% Qdec: Two dimensional cell string array of Qdec data (eg. read with
% fReadQdec).
%
% Output
% M: Numeric matrix (without the name of the variables).
%
% $Revision: 1.2 $  $Date: 2015/01/06 17:14:53 $
% Original Author: Jorge Luis Bernal Rusiel
% CVS Revision Info:
%    $Author: mreuter $
%    $Date: 2015/01/06 17:14:53 $
%    $Revision: 1.2 $
%
Qdec = Qdec(2:end,:);
M = str2double(Qdec);


function [errorCode, ima] = pco_sdk_example_single_EDITED(exposure_time,triggermode)
% set variables grab and display a single images
%
%   [errorCode] = pco_sdk_example_single(exposure_time,triggermode)
%
% * Input parameters :
%    exposure_time           camera exposure time (default=10ms)
%    triggermode             camera trigger mode (default=AUTO)
%
% * Output parameters :
%    errorCode               ErrorCode returned from pco.camera SDK-functions
%
%grab images from a recording pco camera
%using script function pco_camera_stack
%display the grabbed images
%
%function workflow
%open camera
%set variables
%start camera
%grab image
%show image
%stop camera
%close camera
%

glvar=struct('do_libunload',0,'do_close',0,'camera_open',0,'out_ptr',[]);

if(~exist('exposure_time','var'))
 exposure_time = 10;
end

if(~exist('triggermode','var'))
 triggermode = 0;
end

%reduce_display_size=1: display only top-left corner 800x600Pixel
reduce_display_size=0;

pco_camera_load_defines();
subfunc=pco_camera_subfunction();
subfunc.fh_lasterr(0);

[errorCode,glvar]=pco_camera_open_close(glvar);
pco_errdisp('pco_camera_setup',errorCode);
disp(['camera_open should be 1 is ',int2str(glvar.camera_open)]);
if(errorCode~=PCO_NOERROR)
 commandwindow;
 return;
end

out_ptr=glvar.out_ptr;

try

subfunc.fh_stop_camera(out_ptr);

cam_desc=libstruct('PCO_Description');
set(cam_desc,'wSize',cam_desc.structsize);
[errorCode,~,cam_desc] = calllib('PCO_CAM_SDK', 'PCO_GetCameraDescription', out_ptr,cam_desc);
pco_errdisp('PCO_GetCameraDescription',errorCode);

if(bitand(cam_desc.dwGeneralCapsDESC1,GENERALCAPS1_NO_TIMESTAMP)==0)
 subfunc.fh_enable_timestamp(out_ptr,TIMESTAMP_MODE_OFF); %TIMESTAMP_MODE_BINARYANDASCII
end

%enable MetaData if available
%if(bitand(cam_desc.dwGeneralCapsDESC1,GENERALCAPS1_METADATA))
% subfunc.fh_set_metadata_mode(out_ptr,1);
%end

subfunc.fh_set_exposure_times(out_ptr,exposure_time,2,0,2)
subfunc.fh_set_triggermode(out_ptr,triggermode);

%if PCO_ArmCamera does fail no images can be grabbed

errorCode = calllib('PCO_CAM_SDK', 'PCO_ArmCamera', out_ptr);
if(errorCode~=PCO_NOERROR)
 pco_errdisp('PCO_ArmCamera',errorCode);
 ME = MException('PCO_ERROR:ArmCamera','Cannot continue script with not armed camera');
 subfunc.fh_lasterr(errorCode);
 throw(ME);
end

%adjust transfer parameter if necessary
subfunc.fh_set_transferparameter(out_ptr);
subfunc.fh_get_triggermode(out_ptr);
subfunc.fh_show_frametime(out_ptr);

disp('get single image');
%subfunc.fh_start_camera(out_ptr);
[errorCode,ima,metadata,glvar]=pco_camera_stack(1,glvar);
if(errorCode==PCO_NOERROR)

% m=max(max(imar(10:end-10,10:end-10)));
% imshow(ima',[0,m+100]);
figure
imagesc(ima)
%draw_image(imar,[0 m+100]);
% disp(['found max ',int2str(m)]);
 %disp('Press "Enter" to proceed')
 %pause();
 %close()
end

subfunc.fh_stop_camera(out_ptr);

if(~isempty(metadata))
 [metadatasize,~]=size(metadata);
 [errorCode_m,metastruct]=subfunc.fh_get_struct_metadata(metadata,metadatasize);
 if(errorCode_m)
  pco_errdisp('get_struct_metadata',errorCode_m);
 else
  txt=subfunc.fh_print_meta_timestamp(metastruct);
  disp(['Timestamp of meta (',num2str(1,'%04d'),'):  ',txt]);
  subfunc.fh_print_meta_struct(metastruct);
 end
end

catch ME
 errorCode=subfunc.fh_lasterr();
 txt=blanks(101);
 txt=calllib('PCO_CAM_SDK','PCO_GetErrorTextSDK',pco_uint32err(errorCode),txt,100);

 clearvars -except ME glvar;

 if(glvar.camera_open==1)
  glvar.do_close=1;
  glvar.do_libunload=1;
  pco_camera_open_close(glvar);
 end

 if strfind(ME.identifier,'PCO_ERROR:')
  msg=[ME.identifier,' ',ME.message];
  disp(txt);
  warning('off','backtrace')
  warning(msg)
  for k=1:length(ME.stack)
    disp(['from file ',ME.stack(k).file,' at line ',num2str(ME.stack(k).line)]);
  end

  clearvars;
  commandwindow;
  return;
 else
  clearvars -except ME;
  rethrow(ME)
 end
end

clearvars -except glvar ima errorCode;

if(glvar.camera_open==1)
 glvar.do_close=1;
 glvar.do_libunload=1;
 pco_camera_open_close(glvar);
end

clearvars glvar;
commandwindow;
end


%Speed comparison between isStopWord functions implemented with:
    %1)cellArray
    %2)containers.map

n = 1000;

text = fileread('C:\Users\FLOW\Documents\Internships_Research\faridani-MatlabNLP-2e75adc\isStopWord\test.txt');
text = sanitizeComment(text);   %remove all but letters
text = lower(text);
text = regexp(text,' ','split'); %text now in cell array
%text = text(1:n);   %determine size of test text based on given n

testMap = containers.Map;
for i = 1:size(text,2)
    word = porterStemmer(cell2mat(text(i)));
    if isKey(testMap,word)
    else
        testMap(word) = word;
    end
end

testCellArray = keys(testMap);

tic;

mapOut = isStopWordMap('aura',testMap);

mapTime = toc;

tic;

caOut = isStopWord('aura',testCellArray);

caTime = toc;

fprintf('map implementation of isStopWord returns %d in %f\n',mapOut,mapTime)
fprintf('cell array implementation of isStopWord returns %d in %f\n',caOut,caTime)


function v = drosInsituPositives(ids, drosinsitu, drosexp),

% DROSINSITUPOSITIVES Filter genes by looking for positive in-situ annotations.
% FORMAT
% DESC Filter a set of genes by retaining ones with positive in-situ
% annotations, keeping the order of the original list.
% ARG ids : Genes to look, expressed as indices in drosexp
% ARG drosinsitu : drosinsitu data set returned by drosLoadData
% ARG drosexp : drosexp data set returned by drosLoadData
% RETURN v : the filtered indices
%
% SEEALSO : drosLoadData
%
% COPYRIGHT : Antti Honkela, 2009

% SHEFFIELDML

isgenes = drosinsitu.genes(find(sum(drosinsitu.data, 2)));
I = drosFindGeneinds(drosexp, isgenes, 0);

[C, IA, IB] = intersect(ids, I);

v = ids(sort(IA));


function Model = buildTmodel(Model)
% Initiates the template model (Tmodel). It adds model
% designations before some of the cell arrays add creates indenty arrays
% that indicate which reactions and metabolties are contained in which
% models. This function should be used after `verifyModel`.
%
% USAGE:
%
%    Tmodel = buildTmodel(Model)
%
% INPUTS:
%    Model:     Cobra model.
%
% OUTPUTS:
%    Model:     Template model which to which another model can be
%               compared. Known as `Tmodel` in other scripts
%
% Please cite:
% `Sauls, J. T., & Buescher, J. M. (2014). Assimilating genome-scale
% metabolic reconstructions with modelBorgifier. Bioinformatics
% (Oxford, England), 30(7), 1036?8`. http://doi.org/10.1093/bioinformatics/btt747
%
% ..
%    Edit the above text to modify the response to help addMetInfo
%    Last Modified by GUIDE v2.5 06-Dec-2013 14:19:28
%    This file is published under Creative Commons BY-NC-SA.
%
%    Correspondance:
%    johntsauls@gmail.com
%
%    Developed at:
%    BRAIN Aktiengesellschaft
%    Microbial Production Technologies Unit
%    Quantitative Biology and Sequencing Platform
%    Darmstaeter Str. 34-36
%    64673 Zwingenberg, Germany
%    www.brain-biotech.de

modelName = Model.description ; % Declare variables.
nameFields = {'rxnID' 'metID' 'subSystems' 'rxnReferences' ...
              'rxnECNumbers' 'grRules'} ;

%% Put the model name in for appropriate fields.
for iF = 1:length(nameFields)
    % Determine which entries are non empty.
    haveData = find(~cellfun(@isempty, Model.(nameFields{iF}))) ;
    Model.(nameFields{iF})(haveData) = ...
        strcat(modelName, ':', Model.(nameFields{iF})(haveData)) ;
end

%% Create indentity structure.
Model.Models.(modelName).rxns = true(length(Model.rxns), 1) ;
Model.Models.(modelName).mets = true(length(Model.mets), 1) ;

%% Add genes.
Model.Models.(modelName).genes = Model.genes ;

%% Move bound info into structures.
lb = Model.lb ;
ub = Model.ub ;
c = Model.c ;

Model.lb = ([]);
Model.ub = ([]);
Model.c = ([]);

Model.lb.(modelName) = lb ;
Model.ub.(modelName) = ub ;
Model.c.(modelName) = c ;

%% Make S sparse.
Model.S = sparse(Model.S) ;

%% Remove extra fields that could get in the way.
unwantedFields = {'description' 'genes' 'rxnGeneMat' 'rules'} ;
for iField = 1:length(unwantedFields)
    try
        Model = rmfield(Model, unwantedFields{iField}) ;
        %fprintf(['Removed ' unwantedFields{iField} ' from in Tmodel\n'])
    catch
        %fprintf([unwantedFields{iField} ' not in Tmodel\n'])
    end
end


function obj = fromSimpleNN(net, varargin)
% FROMSIMPLENN  Initialize a DagNN object from a SimpleNN network
%   FROMSIMPLENN(NET) initializes the DagNN object from the
%   specified CNN using the SimpleNN format.
%
%   SimpleNN objects are linear chains of computational layers. These
%   layers exchange information through variables and parameters that
%   are not explicitly named. Hence, FROMSIMPLENN() uses a number of
%   rules to assign such names automatically:
%
%   * From the input to the output of the CNN, variables are called
%     `x0` (input of the first layer), `x1`, `x2`, .... In this
%     manner `xi` is the output of the i-th layer.
%
%   * Any loss layer requires two inputs, the second being a label.
%     These are called `label` (for the first such layers), and then
%     `label2`, `label3`,... for any other similar layer.
%
%   Additionally, given the option `CanonicalNames` the function can
%   change the names of some variables to make them more convenient to
%   use. With this option turned on:
%
%   * The network input is called `input` instead of `x0`.
%
%   * The output of each SoftMax layer is called `prob` (or `prob2`,
%     ...).
%
%   * The output of each Loss layer is called `objective` (or `
%     objective2`, ...).
%
%   * The input of each SoftMax or Loss layer of type *softmax log
%     loss* is called `prediction` (or `prediction2`, ...). If a Loss
%     layer immediately follows a SoftMax layer, then the rule above
%     takes precendence and the input name is not changed.
%
%   FROMSIMPLENN(___, 'OPT', VAL, ...) accepts the following options:
%
%   `CanonicalNames`:: false
%      If `true` use the rules above to assign more meaningful
%      names to some of the variables.

% Copyright (C) 2015 Karel Lenc and Andrea Vedaldi.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).

opts.canonicalNames = false ;
opts = vl_argparse(opts, varargin) ;

import dagnn.*

obj = DagNN() ;
net = vl_simplenn_move(net, 'cpu') ;
net = vl_simplenn_tidy(net) ;

% copy meta-information as is
obj.meta = net.meta ;

for l = 1:numel(net.layers)
  inputs = {sprintf('x%d',l-1)} ;
  outputs = {sprintf('x%d',l)} ;

  params = struct(...
        'name', {}, ...
        'value', {}, ...
        'learningRate', [], ...
        'weightDecay', []) ;
  if isfield(net.layers{l}, 'name')
    name = net.layers{l}.name ;
  else
    name = sprintf('layer%d',l) ;
  end

  switch net.layers{l}.type
    case {'conv', 'convt'}
      sz = size(net.layers{l}.weights{1}) ;
      hasBias = ~isempty(net.layers{l}.weights{2}) ;
      params(1).name = sprintf('%sf',name) ;
      params(1).value = net.layers{l}.weights{1} ;
      if hasBias
        params(2).name = sprintf('%sb',name) ;
        params(2).value = net.layers{l}.weights{2} ;
      end
      if isfield(net.layers{l},'learningRate')
        params(1).learningRate = net.layers{l}.learningRate(1) ;
        if hasBias
          params(2).learningRate = net.layers{l}.learningRate(2) ;
        end
      end
      if isfield(net.layers{l},'weightDecay')
        params(1).weightDecay = net.layers{l}.weightDecay(1) ;
        if hasBias
          params(2).weightDecay = net.layers{l}.weightDecay(2) ;
        end
      end
      switch net.layers{l}.type
        case 'conv'
          block = Conv() ;
          block.size = sz ;
          block.pad = net.layers{l}.pad ;
          block.stride = net.layers{l}.stride ;
          block.dilate = net.layers{l}.dilate ;
        case 'convt'
          block = ConvTranspose() ;
          block.size = sz ;
          block.upsample = net.layers{l}.upsample ;
          block.crop = net.layers{l}.crop ;
          block.numGroups = net.layers{l}.numGroups ;
      end
      block.hasBias = hasBias ;
      block.opts = net.layers{l}.opts ;

    case 'pool'
      block = Pooling() ;
      block.method = net.layers{l}.method ;
      block.poolSize = net.layers{l}.pool ;
      block.pad = net.layers{l}.pad ;
      block.stride = net.layers{l}.stride ;
      block.opts = net.layers{l}.opts ;

    case {'normalize', 'lrn'}
      block = LRN() ;
      block.param = net.layers{l}.param ;

    case {'dropout'}
      block = DropOut() ;
      block.rate = net.layers{l}.rate ;

    case {'relu'}
      block = ReLU() ;
      block.leak = net.layers{l}.leak ;

    case {'sigmoid'}
      block = Sigmoid() ;

    case {'softmax'}
      block = SoftMax() ;

    case {'softmaxloss'}
      block = Loss('loss', 'softmaxlog') ;
      % The loss has two inputs
      inputs{2} = getNewVarName(obj, 'label') ;

    case {'bnorm'}
      block = BatchNorm() ;
      params(1).name = sprintf('%sm',name) ;
      params(1).value = net.layers{l}.weights{1} ;
      params(2).name = sprintf('%sb',name) ;
      params(2).value = net.layers{l}.weights{2} ;
      params(3).name = sprintf('%sx',name) ;
      params(3).value = net.layers{l}.weights{3} ;
      if isfield(net.layers{l},'learningRate')
        params(1).learningRate = net.layers{l}.learningRate(1) ;
        params(2).learningRate = net.layers{l}.learningRate(2) ;
        params(3).learningRate = net.layers{l}.learningRate(3) ;
      end
      if isfield(net.layers{l},'weightDecay')
        params(1).weightDecay = net.layers{l}.weightDecay(1) ;
        params(2).weightDecay = net.layers{l}.weightDecay(2) ;
        params(3).weightDecay = 0 ;
      end

    otherwise
      error([net.layers{l}.type ' is unsupported']) ;
  end

  obj.addLayer(...
    name, ...
    block, ...
    inputs, ...
    outputs, ...
    {params.name}) ;

  for p = 1:numel(params)
    pindex = obj.getParamIndex(params(p).name) ;
    if ~isempty(params(p).value)
      obj.params(pindex).value = params(p).value ;
    end
    if ~isempty(params(p).learningRate)
      obj.params(pindex).learningRate = params(p).learningRate ;
    end
    if ~isempty(params(p).weightDecay)
      obj.params(pindex).weightDecay = params(p).weightDecay ;
    end
  end
end

% --------------------------------------------------------------------
% Rename variables to canonical names
% --------------------------------------------------------------------

if opts.canonicalNames
  for l = 1:numel(obj.layers)
    if l == 1
      obj.renameVar(obj.layers(l).inputs{1}, 'input') ;
    end
    if isa(obj.layers(l).block, 'dagnn.SoftMax')
      obj.renameVar(obj.layers(l).outputs{1}, getNewVarName(obj, 'prob')) ;
      obj.renameVar(obj.layers(l).inputs{1}, getNewVarName(obj, 'prediction')) ;
    end
    if isa(obj.layers(l).block, 'dagnn.Loss')
      obj.renameVar(obj.layers(l).outputs{1}, 'objective') ;
      if isempty(regexp(obj.layers(l).inputs{1}, '^prob.*'))
        obj.renameVar(obj.layers(l).inputs{1}, ...
                      getNewVarName(obj, 'prediction')) ;
      end
    end
  end
end

if isfield(obj.meta, 'inputs')
  obj.meta.inputs(1).name = obj.layers(1).inputs{1} ;
end

% --------------------------------------------------------------------
function name = getNewVarName(obj, prefix)
% --------------------------------------------------------------------
t = 0 ;
name = prefix ;
while any(strcmp(name, {obj.vars.name}))
  t = t + 1 ;
  name = sprintf('%s%d', prefix, t) ;
end


function value = file_line_width ( file_name )

%*****************************************************************************80
%
%% FILE_LINE_WIDTH reports the length of the longest line in a file.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    22 February 2010
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string FILE_NAME, the name of the input file.
%
%    Output, integer VALUE, the length of the longest line.
%
  value = -1;

  input = fopen ( file_name );

  if ( input < 0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'FILE_LINE_WIDTH - Error!\n' );
    fprintf ( 1, '  Could not open the file "%s".\n', file_name );
    error ( 'FILE_LINE_WIDTH - Error!' );
    return;
  end

  value = 0;
  line_width = 0;

  while ( 1 )

    [ c, count ] = fread ( input, 1 );

    if ( count < 1 )
      break;
    end

    if ( c == 10 || c == 13 )
      line_width = 0;
    else
      line_width = line_width + 1;
      value = max ( value, line_width );
    end

  end

  fclose ( input );

  return
end


function [EEG g] = pre_selectComps(varargin)
%
% Remove some components from icaact matrix and dipfit structure.
%
% Inputs:
%
%   EEG:        EEG data structure
%
% Optional:     <'Name',Value> pairs
%
%     VerbosityLevel:   Verbosity level. 0 = no output, 1 = text, 2 = graphical
%                       Possible values: 0,1,2
%                       Default value  : 0
%                       Input Data Type: real number (double)
%
%     ComponentsToKeep: Select components to analyze
%                       This should be a cell array of strings containing the IDs of components you wish to keep
%                       Input Data Type: boolean
% Outputs:
%
%   EEG:        processed EEG structure
%   g:          argument specification structure
%
% See Also: pre_prepData()
%
% References:
%
% [1] Mullen T (2010) The Source Information Flow Toolbox (SIFT):
%   Theoretical Handbook and User Manual. Section 6.5.1
%   Available at: http://www.sccn.ucsd.edu/wiki/Sift
%
% Author: Tim Mullen 2010, SCCN/INC, UCSD.
% Email:  tim@sccn.ucsd.edu

% This function is part of the Source Information Flow Toolbox (SIFT)
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

% extract the allowable component names
CAT = arg_extract(varargin,'CAT',1);
MyComponentNames = CAT.curComponentNames;

% setup the argument structure
g = arg_define([0 1],varargin, ...
    arg_norep('CAT',mandatory), ...
    arg({'verb','VerbosityLevel'},0,{int32(0) int32(1) int32(2)},'Verbosity level. 0 = no output, 1 = text, 2 = graphical'), ...
    arg({'ComponentsToKeep'},MyComponentNames,MyComponentNames,'Select components to analyze. This should be a cell array of strings containing the IDs of channels or components you wish to keep','type','logical') ...
    );

nbcomps = size(g.EEG.CAT.srcdata,1);
ComponentIndicesToKeep = find(ismember_bc(MyComponentNames,g.ComponentsToKeep));

if g.verb, fprintf('Selecting components...\n'); end

% select a subset of components from g.EEG
rmcomps = setdiff_bc(1:nbcomps,ComponentIndicesToKeep);

g.EEG.CAT.srcdata(rmcomps,:)     = [];
g.EEG.CAT.srcdata = reshape(g.EEG.CAT.srcdata, size(g.EEG.CAT.srcdata,1), g.EEG.CAT.pnts, g.EEG.CAT.trials);

g.EEG.CAT.curComps            = ComponentIndicesToKeep;
g.EEG.CAT.curComponentNames   = g.ComponentsToKeep;

EEG = g.EEG;


function [view,hdr] = BV_voi2roi(view,voiFile,unTalFlag,talPath);
% BV_voi2roi: converts a brain voyager .voi file into
% an ROI in a mrLoadRet volume.
%
% Usage: [view,hdr] = BV_voi2roi(view,[voiFile,unTalFlag,talPath]);
%
% Args:
%       voiFile: path of Brain Voyager .voi file. If not passed in,
%       provides a dialog to select it.
%
%       unTalFlag: flag (set to 0 or 1) which causes the VOI/ROIs to be
%       converted from Talairach coords (saved that way in BV) to unTalled
%       coords (in mrLoadRet). Defaults to 1, do untal. NOTE: even if
%       manually set to 0, if the BV .voi file specifies the file type as
%       'TAL', it will automatically set unTalFlag to 1.
%
%       talPath: for when unTalFlag==1, the location of a .mat file,
%       created using computeTalairach.m, which contains the transform
%       information for going between tal and untal space. If unspecified,
%       checks the vANATOMYPATH directory, and, failing that, prompts the
%       user.
%
% Dependencies: BV_tal2untal
%
% ras 03/03
mrGlobals;

% right now I'm just making this work with volume views --
% bow out if it's another type of view
if ~isequal(view.viewType,'Volume') & ~isequal(view.viewType,'Gray')
    fprintf('Sorry, but this only works with Volume/Gray views right now.\n');
    return
end

if ~exist('unTalFlag','var')    unTalFlag = 1;      end

% prompt for BV .voi file if it's not passed in
if ~exist('voiFile','var') | isempty(voiFile)
    msg = ['Choose a Brain Voyager .voi file...'];
    startDir = fullfile(RAID,'3Danat','BV_vmr');
    if ~exist(startDir)
        startDir = pwd;
    end
    voiFile = getPathStrDialog(startDir,msg,'*.voi');
end

if ~exist(voiFile,'file')
    error(['File ' voiFile ' is not a valid file.']);
end

% prompt for a BV .tal file containing talairach information
if unTalFlag==1 & ~exist('talPath','var')

    % make an educated guess as to where the talPath might be
    guess = fullfile(fileparts(vANATOMYPATH),'vAnatomy_talairach.mat');

    if exist(guess,'file')
        talPath = guess;
    else
        disp('Choose a .mat file containing the talairach points for this volume');
        disp('(See ''help computeTalairach'' if you are unsure of what this is.)');
        msg = ['Choose a .mat file from coputeTalairach...'];
        talPath = getPathStrDialog(pwd,msg,'*.mat');
    end
 end

% Get the volume size - for flipping one of the dimensions to preserve L/R
volAnatSize=size(view.anat);

% open the voi file
[fid message] = fopen(voiFile,'r');
if fid==-1
    error(message);
end

%%%%% read the header
blank = fgetl(fid);
ignoretxt = fscanf(fid,'%s',1);
hdr.FileVersion = fscanf(fid,'%i',1);
blank = fgetl(fid);
blank = fgetl(fid);
ignoretxt = fscanf(fid,'%s',1);
hdr.CoordsType = fscanf(fid,'%s',1);
if isequal(hdr.CoordsType,'TAL')
    unTalFlag = 1;
end
blank = fgetl(fid);
blank = fgetl(fid);
blank = fgetl(fid);
ignoretxt = fscanf(fid,'%s',1);
hdr.numVOIs = fscanf(fid,'%i',1);
blank = fgetl(fid);
blank = fgetl(fid);

%%%%% loop through ROIs, reading them in
for voi = 1:hdr.numVOIs

    % read VOI/ROI name, num voxels in brainvoyager coords
    ignoretxt = fscanf(fid,'%s',1);
    hdr.VOInames{voi} = fscanf(fid,'%s',1);
    blank = fgetl(fid);
    blank = fgetl(fid);
    ignoretxt = fscanf(fid,'%s',1);
    hdr.numBVVoxels(voi) = fscanf(fid,'%i',1);
    blank = fgetl(fid);

    % init ROI substruct
    ROIs(voi).color = 'b'; % default color is blue
    ROIs(voi).coords = [];
    ROIs(voi).name = hdr.VOInames{voi};
    ROIs(voi).viewType = view.viewType;

    % read coordinates of VOI
    voiCoords = [];
    for vxl = 1:hdr.numBVVoxels(voi)
        voiCoords(vxl,1) = fscanf(fid,'%i',1);
        voiCoords(vxl,2) = fscanf(fid,'%i',1);
        voiCoords(vxl,3) = fscanf(fid,'%i',1);
    end
    blank = fgetl(fid);
    blank = fgetl(fid);

	if unTalFlag
        voiCoords = BV_tal2unTal(voiCoords,talPath);
    end

    ROIs(voi).coords = round(voiCoords');

    fprintf('%s \n',ROIs(voi).name);
end

%%%%% read linked VTC files at the end; put info in hdr
blank = fgetl(fid);
ignoretxt = fscanf(fid,'%s',1);
hdr.numLinkedVTCs = fscanf(fid,'%i',1);
blank = fgetl(fid);
for vtc = 1:hdr.numLinkedVTCs
    hdr.VTCs{vtc} = fgetl(fid);
end

% close the file
fclose(fid);

% append ROIs to current view
view.ROIs = [view.ROIs ROIs];

% let the user know it worked
fprintf('Converted %i ROIs from the BV file %s.\n',length(ROIs),voiFile);

% refresh ROIs
r = view.selectedROI;
if r > 0
    view = selectROI(view,r);
else
	view = selectROI(view,1);
end

return


function proposals= calcRigorForIm( input, rigorconfig )
%RIGOR Summary of this function goes here
%   Detailed explanation goes here

%RIGOR doesnt suppoert .mat as an input yet
if ismac
    error('rigor not supported on macOS');
end
im = input;
	[masks]=rigor_obj_segments(im,'force_recompute',true);

	if(isfield((rigorconfig.opts),'numProposals'))
		numProposals=rigorconfig.opts.numProposals;
	        if(size(masks,3)>=numProposals)
        	        masks=masks(:,:,1:numProposals);
        	else
                	fprintf('Only %d proposals were generated for image: %s\n',size(masks,3),imname);
        	end
	end
	boxes=zeros(size(masks,3),4);
	for j=1:size(masks,3)
		boxes(j,:)=mask2box(masks(:,:,j));
	end
	proposals.boxes= boxes;
	proposals.regions=masks;
end


function [seq, ground_truth] = load_video_info(video_path, video_name)

ground_truth = dlmread([video_path '/groundtruth_rect.txt']);
% ground_truth = dlmread([video_path, '/', video_name, '_gt', '.txt']);

seq.len = size(ground_truth, 1);
seq.init_rect = ground_truth(1,:);

img_path = [video_path '/img/'];

if exist([img_path num2str(1, '%04i.png')], 'file'),
    img_files = num2str((1:seq.len)', [img_path '%04i.png']);
elseif exist([img_path num2str(1, '%04i.jpg')], 'file'),
    img_files = num2str((1:seq.len)', [img_path '%04i.jpg']);
elseif exist([img_path num2str(1, '%04i.bmp')], 'file'),
    img_files = num2str((1:seq.len)', [img_path '%04i.bmp']);
else
    error('No image files to load.')
end

seq.s_frames = cellstr(img_files);

end


function tf = strlexle(a, b)
%STRLEXLE Lexicographic less than or equal to.
%
%   STRLEXLE(A, B) returns 1 if A is lexicographically less than or equal to B,
%   and 0 otherwise.
%
%   This is a MATLAB version of the Perl `le' operator.
%
%   See also LE.

%   Author:      Peter J. Acklam
%   Time-stamp:  2003-10-13 11:15:58 +0200
%   E-mail:      pjacklam@online.no
%   URL:         http://home.online.no/~pjacklam

   tf = strlexcmp(a, b) <= 0;


function gp_save(file,data,header)
%GP_SAVE saves x,y as a text file in a Gnuplot compatible format
%
%   Usage: gp_save(file,data,[header])
%
%   Input parameters:
%       file    - filename of the data file
%       data    - data matrix
%       header  - header comment added before the data
%
%   See also: gp_save_matrix

%*****************************************************************************
% The MIT License (MIT)                                                      *
%                                                                            *
% Copyright (c) 2010-2019 SFS Toolbox Developers                             *
%                                                                            *
% Permission is hereby granted,  free of charge,  to any person  obtaining a *
% copy of this software and associated documentation files (the "Software"), *
% to deal in the Software without  restriction, including without limitation *
% the rights  to use, copy, modify, merge,  publish, distribute, sublicense, *
% and/or  sell copies of  the Software,  and to permit  persons to whom  the *
% Software is furnished to do so, subject to the following conditions:       *
%                                                                            *
% The above copyright notice and this permission notice shall be included in *
% all copies or substantial portions of the Software.                        *
%                                                                            *
% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
% IMPLIED, INCLUDING BUT  NOT LIMITED TO THE  WARRANTIES OF MERCHANTABILITY, *
% FITNESS  FOR A PARTICULAR  PURPOSE AND  NONINFRINGEMENT. IN NO EVENT SHALL *
% THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
% LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT, TORT  OR OTHERWISE, ARISING *
% FROM,  OUT OF  OR IN  CONNECTION  WITH THE  SOFTWARE OR  THE USE  OR OTHER *
% DEALINGS IN THE SOFTWARE.                                                  *
%                                                                            *
% The SFS Toolbox  allows to simulate and  investigate sound field synthesis *
% methods like wave field synthesis or higher order ambisonics.              *
%                                                                            *
% https://sfs.readthedocs.io                            sfstoolbox@gmail.com *
%*****************************************************************************

%% ===== Checking of input  parameters ==================================
nargmin = 2;
nargmax = 3;
narginchk(nargmin,nargmax);
if nargin==nargmax-1
    header = '';
end
isargchar(file);
isargmatrix(data);
isargchar(header);

%% ===== Main ============================================================
% Write header to the file
fid = fopen(file,'w');
fprintf(fid,'# Data file generated by gp_save.m\n');
fprintf(fid,['# ',header,'\n']);
fclose(fid);
% Append the data to the file using tabulator as a delimiter between the data
if isoctave
    dlmwrite(file,data,'\t','-append');
else
    dlmwrite(file,data,'delimiter','\t','-append');
end