classdef chebpref
%CHEBPREF   Abstract class for Chebfun preferences.
%
%   CHEBPREF is an abstract class for managing preferences of the various
%   subsystems comprising Chebfun.  On its own, it provides little more than a
%   wrapper around a MATLAB struct.  Concrete preference classes inherit from
%   CHEBPREF and add to its functionality as desired.
%
% See also CHEBFUNPREF, CHEBOPPREF.

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

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %% CLASS PROPERTIES:
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    properties ( Access = protected )
        % MATLAB struct to hold a list of preferences for a given subsystem.
        prefList
    end

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %% Non-Static methods implemented by this class.
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    methods ( Access = public, Static = false )

        function out = subsref(pref, ind)
        %SUBSREF   Subscripted referencing for CHEBPREF.
        %   P.PROP, where P is a CHEBPREF object, returns the value of the
        %   CHEBPREF property PROP stored in P.  If PROP is not a CHEBPREF
        %   property, an error will be thrown.
        %
        %   CHEBPREF does not support any other subscripted referencing
        %   types, including '()' and '{}'.

            switch ( ind(1).type )
                case '.'
                    if ( isfield(pref.prefList, ind(1).subs) )
                        out = pref.prefList.(ind(1).subs);
                    end

                    if ( numel(ind) > 1 )
                        out = subsref(out, ind(2:end));
                    end
                otherwise
                    error('CHEBFUN:CHEBPREF:chebpref:badType', ...
                        'Invalid subscripted reference type.')
            end
        end

        function pref = subsasgn(pref, ind, val)
        %SUBSASGN   Subscripted assignment for CHEBPREF.
        %   P.PROP = VAL, where P is a CHEBPREF object, assigns the value
        %   VAL to the CHEBPREF property PROP stored in P.  If PROP is not a
        %   CHEBPREF property, an error will be thrown.
        %
        %   CHEBPREF does not support any other subscripted assignment types,
        %   including '()' and '{}'.

            switch ( ind(1).type )
                case '.'
                    if ( isfield(pref.prefList, ind(1).subs) )
                        pref.prefList = builtin('subsasgn', pref.prefList, ...
                            ind, val);
                    end
                otherwise
                    error('CHEBFUN:CHEBPREF:chebpref:badType', ...
                        'Invalid subscripted assignment type.')
            end
        end

    end

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %% Abstract methods
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    methods ( Abstract = true )
        % Display information about a CHEBPREF object.
        display(pref)
    end

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %% Static methods
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    methods ( Access = public, Static = true )

        function pref1 = mergePrefStructs(pref1, pref2)
        %MERGEPREFSTRUCTS   Merge preference structures.
        %   P = CHEBPREF.MERGEPREFSTRUCTS(P, Q), where P and Q are MATLAB
        %   structures, "merges" Q into P by replacing the contents of fields
        %   in P with those of identically-named fields in Q.  If Q has a field
        %   whose name does not match any of those in P, it is added to P.

            for field = fieldnames(pref2).'
                pref1.(field{1}) = pref2.(field{1});
            end
        end

    end

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %% Hidden static methods.
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    methods ( Access = public, Static = true, Hidden = true  )

        function setDefaults(makeSC, manageSCDefaults, varargin)
        %SETDEFAULTS   Set default preferences.
        %   CHEBPREF.SETDEFAULTS(MAKESC, MANAGESCDEFAULTS, ...) sets the
        %   persistently stored defaults of a subclass of CHEBPREF.  MAKESC is
        %   a handle to the subclass constructor, and MANAGESCDEFAULTS is a
        %   handle to the subclass static method responsible for managing the
        %   stored defaults.
        %
        %   Users should not call CHEBPREF.SETDEFAULTS.  Call the SETDEFAULTS
        %   method of the appropriate Chebfun subsystem whose defaults need to
        %   be altered instead.

        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        % DEVELOPER NOTES:
        %  - This is a template method to prevent subclasses from needing to
        %    duplicate the logic required to set persistently-stored defaults
        %    As the help text says, this method is not user-facing.
        %  - This method is not likely to work if the subclass does not handle
        %    things in the exact same way that the existing CHEBFUNPREF and
        %    CHEBOPPREF subclasses do.
        %  - The function referred to by the MANAGESCDEFAULTS input needs to
        %    conform to a specific prototype.  See the documentation for
        %    CHEBFUNPREF.MANAGEDEFAULTPREFS for an example.
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

            nargs = length(varargin);

            if ( nargs < 1)
                error('CHEBFUN:CHEBPREF:chebpref:notEnoughArguments', ...
                    'Not enough arguments.');
            end

            if ( nargs == 1 )
                if ( isstruct(varargin{1}) )
                    varargin{1} = makeSC(varargin{1});
                end

                if ( ischar(varargin{1}) && strcmp(varargin{1}, 'factory') )
                    manageSCDefaults('set-factory');
                elseif ( isa(varargin{1}, 'chebpref') )
                    manageSCDefaults('set', varargin{1}.prefList);
                else
                    error('CHEBFUN:CHEBPREF:chebpref:badArg', ...
                        ['When calling chebpref.setDefaults() with just ' ...
                         'one argument, that argument must be ''factory'', ' ...
                         'a subclass of CHEBPREF, or a MATLAB structure.']);
                end
            elseif ( mod(nargs, 2) == 0 )
                manageSCDefaults('set', varargin{:});
            else
                error('CHEBFUN:CHEBPREF:chebpref:unpairedArg', ...
                    'Unpaired argument in name-value pair list.');
            end
        end

    end

end


function toks = split_string(line, delim)
ntok = 0;
tmp1 = line;
while length(tmp1)>0
    [tmp2, tmp1] = strtok(tmp1, delim);
    ntok = ntok+1;
end
toks = cell(ntok, 1);
for i = 1:ntok
    [toks{i}, line] = strtok(line, delim);
end


function v = ksvdver(history)
%KSVDVER K-SVD toolbox version information.
%  KSVDVER displays the current KSVD toolbox version information.
%
%  KSVDVER('history') also displays history information about the previous
%  versions of the KSVD toolbox and their change logs.
%
%  V = KSVDVER returns the version number of the current KSVD toolbox, and
%  does not display any information.

%  Ron Rubinstein
%  Computer Science Department
%  Technion, Haifa 32000 Israel
%  ronrubin@cs
%
%  August 2009

ver = 12;

if (nargout>0)
  if (nargin>0)
    error('Invalid number of parameters.');
  end
  v = ver;

else

  if (nargin==0 || (nargin==1 && strcmpi(history,'history')))

    disp(' ');
    disp('---------------------------------');
    printf('    KSVD Toolbox version %d       ',ver);
    disp('---------------------------------');
    disp(' ');

  else
    error('Unknown parameters.');
  end

  if (nargin>0)

    %% changes only displayed since first public release %%

%     disp(' ');
%     disp('KSVD Toolbox version 1, 24.10.07');
%     disp('---------------------------------');
%     disp(' ');
%     disp('Initial release.');
%     disp(' ');
%     disp(' ');
%     disp(' ');
%
%     disp('KSVD Toolbox version 2, 13.12.07');
%     disp('---------------------------------');
%     disp(' ');
%     disp('Features:');
%     disp(' ');
%     disp('  1. KSVD: support for sparsity and error based coding.');
%     disp('  2. New OMPDENOISE function for generic OMP-based denoising.');
%     disp('  3. ''memusage'' parameter introduced for controlling memory usage.');
%     disp(' ');
%     disp('Bug fixes:');
%     disp(' ');
%     disp('  1. KSVD: when initializing the dictionary with a set of signals, ');
%     disp('     only selects non-zero ones.');
%     disp('  2. KSVD: only negates atoms with first element negative, instead of');
%     disp('     multiplying each atom by its sign (which nullified atoms whose');
%     disp('     first element was zero).');
%     disp('  3. KSVD: tracks training signals used to replace unused atoms, so');
%     disp('     the same one is not used twice.');
%     disp(' ');
%     disp('Internal changes:');
%     disp('  1. Eliminated the use of function cleardict in KSVD, following bugfix (3).');
%     disp(' ');
%     disp(' ');
%     disp(' ');
%
%     disp('KSVD Toolbox version 3, 16.01.08');
%     disp('---------------------------------');
%     disp(' ');
%     disp('Features:');
%     disp(' ');
%     disp('  1. Option for specifying a list of initial signals for the dictionary using');
%     disp('     the parameter initdict.')
%     disp('  2. Changed error computation from Frobenius norm to MSE.');
%     disp('  3. Added the VERBOSE parameter for controlling printed output.');
%     disp('  4. Added the muthresh parameter to KSVD.');
%     disp('  5. Added parameter maxval to OMPDENOISE and KSVDDENOISE.');
%     disp(' ');
%     disp('Internal changes:');
%     disp(' ');
%     disp('  1. Added the sparsecode method for cleaner code.');
%     disp('  2. Re-introduced the use of function cleardict.');
%     disp(' ');
%     disp('Bug fixes:');
%     disp(' ');
%     disp('  1. Function cleardict now checks correlation between atoms in absolute value.');
%     disp(' ');
%     disp(' ');
%     disp(' ');
%
%     disp('KSVD Toolbox version 4, 27.01.08');
%     disp('---------------------------------');
%     disp(' ');
%     disp('Features:');
%     disp(' ');
%     disp('  1. Added functions OMPDENOISE2 and OMPDENOISE3 for faster denoising of');
%     disp('     2-D and 3-D signals.');
%     disp('  2. Added gain and lambda parameters to OMPDENOISE and KSVDDENOISE.');
%     disp(' ');
%     disp(' ');
%     disp(' ');
%
%     disp('KSVD Toolbox version 5, 03.02.08');
%     disp('---------------------------------');
%     disp(' ');
%     disp('Features:');
%     disp(' ');
%     disp('  1. KSVD: atom update is now in random order rather than sequential.');
%     disp('  2. KSVD: improved error computation: error is now computed after the');
%     disp('     dictionary update step, eliminating the need for an additional sparse');
%     disp('     coding step at the end of the algorithm for error computation.');
%     disp('     Computed error is now RMSE for sparsity-based minimization, and average');
%     disp('     atom count for error-based minimization.');
%     disp('  3. KSVD: cleardict now replaces every atom not used by at least 4 training');
%     disp('     signals. Atoms already replaced in the dictionary update step are');
%     disp('     excluded from this criterion.');
%     disp('  4. Added the ''exact'' parameter to KSVD/KSVDDENOISE, to allow using the exact');
%     disp('     SVD solution rather than the default quicker approximation method.');
%     disp('  5. Changed behavior of VERBOSE=3 mode in KSVD, and added VERBOSE=4 mode.');
%     disp('  6. VERBOSE in OMPDENOISE/2/3 now prints a message every VERBOSE seconds,');
%     disp('     not every VERBOSE blocks.');
%     disp('  7. OMPDENOISE: faster computation of the matrix cnt (a counter matrix');
%     disp('     containing the number of blocks covering each sample in the signal.');
%     disp('  8. KSVDDENOISE: new default values for gain and lambda.');
%     disp('  9. KSVDDENOISE: reverts to function OMPDENOISE when memusage is ''low''');
%     disp(' 10. Set a limit on the number of atoms used to code each block in OMPDENOISE');
%     disp('     and KSVDDENOISE. Added the maxatoms parameter to control this limit.');
%     disp(' 11. Improved documentation.');
%     disp(' 12. Added the KSVDVER function.');
%     disp(' ');
%     disp('Internal changes:');
%     disp(' ');
%     disp('  1. Support for the new call syntax of OMP Toolbox v6.');
%     disp('  2. OMPDENOISE3 now computes the matrix cnt using much less memory. Instead');
%     disp('     of allocating three matrices the size of the input signal, it only');
%     disp('     allocates one such matrix.');
%     disp(' ');
%     disp('Bug fixes:');
%     disp(' ');
%     disp('  1. OMPDENOISE2/3 now compute the matrix cnt correctly.');
%     disp(' ');
%     disp(' ');
%     disp(' ');
%
%     disp('KSVD Toolbox version 6, 14.02.08');
%     disp('---------------------------------');
%     disp(' ');
%     disp('Features:');
%     disp(' ');
%     disp('  1. New stepsize parameter in OMPDENOISE/2/3 and KSVDDENOISE.');
%     disp('  2. ''blocksize'' parameter in OMPDENOISE/2/3 and KSVDDENOISE can now be a scalar.');
%     disp('  3. Added the Contents.m file.');
%     disp('  4. Revised VERBOSE settings in KSVDDENOISE, and slightly improved display format');
%     disp('     in KSVD.');
%     disp(' ');
%     disp('Bug fixes:');
%     disp(' ');
%     disp('  1. OMPDENOISE/2/3: fixed a bug in the computation of the matrix cnt when');
%     disp('     the signal is not square.');
%     disp(' ');
%     disp(' ');
%     disp(' ');
%
%     disp('KSVD Toolbox version 7, 18.04.08');
%     disp('---------------------------------');
%     disp(' ');
%     disp('Features:');
%     disp(' ');
%     disp('  1. OMPDENOISE now prints the estimated remaining time.');
%     disp('  2. New ''msgdelta'' parameter in KSVD and KSVDDENOISE for printing');
%     disp('     periodic status updates.');
%     disp(' ');
%     disp('Internal changes:');
%     disp(' ');
%     disp('  1. Compatible with OMP Toolbox v7.');
%     disp(' ');
%     disp(' ');
%     disp(' ');

    disp(' ');
    disp(' ');
    disp('KSVD Toolbox version 7, 18.04.08');
    disp('---------------------------------');
    disp(' ');
    disp('First public release.');
    disp(' ');
    disp(' ');
    disp(' ');

    disp('KSVD Toolbox version 8, 29.05.08');
    disp('--------------------------------');
    disp(' ');
    disp('Features:');
    disp(' ');
    disp('  1. Added ''sigma'' and ''noisemode'' parameters to OMPDENOISE and KSVDDENOISE.');
    disp('  2. Added the overcomplete DCT dictionary as an optional initial dictionary');
    disp('     in KSVDDENOISE, by setting the initdict parameter to the string ''odct''.');
    disp('  3. Improved default gain and lambda parameters in OMPDENOISE.');
    disp(' ');
    disp('Bug fixes:');
    disp(' ');
    disp('  1. KSVDDENOISE: corrected a bug which caused incorrect gain and lambda');
    disp('     parameters to be sent to OMPDENOISE in some cases.');
    disp(' ');
    disp('Internal changes:');
    disp(' ');
    disp('  1. When replacing an unused atom, the search for an example with maximal');
    disp('     error is limited to a fixed number of signals.');
    disp('  2. Improved implementation of KSVDVER.');
    disp('  3. Uses the TIMER package for time estimation.');
    disp(' ');
    disp(' ');
    disp(' ');

    disp('KSVD Toolbox version 9, 30.11.08');
    disp('--------------------------------');
    disp(' ');
    disp('Features:');
    disp(' ');
    disp('  1. OMPDENOISE and KSVDDENOISE can now return the average number of');
    disp('     non-zeros in the denoised block representations.');
    disp(' ');
    disp('Bug fixes:');
    disp(' ');
    disp('  1. Corrected an error when parameter MSGDELTA was not specified.');
    disp(' ');
    disp('Internal changes:');
    disp(' ');
    disp('  1. The COUNTCOVER function counts the number of times a pixel in a');
    disp('     multi-dimensional signal is covered by overlapping blocks.');
    disp('  2. Function CLEARDICT now computes the error norm in blocks to reduce');
    disp('     memory consumption.');
    disp(' ');
    disp(' ');
    disp(' ');

    disp('KSVD Toolbox version 10, 21.05.09');
    disp('---------------------------------');
    disp(' ');
    disp('Features:');
    disp(' ');
    disp('  1. Source code for supporting C functions now available for compilation');
    disp('     on any Matlab platform.');
    disp('  2. Added KSVDDEMO and KSVDDENOISEDEMO.');
    disp('  3. Improved performance of OMPDENOISE2, OMPDENOISE3 and KSVD.');
    disp('  4. New SHOWDICT function for displaying a dictionary of image patches.');
    disp('  5. KSVD: improved VERBOSE/MSGDELTA parameter syntax.');
    disp('  6. KSVD: messages are now displayed by default.');
    disp('  7. KSVD: only one of the parameters dictsize/initdict needs to be specified.');
    disp('  8. KSVD: eliminated the data saving option.');
    disp('  9. OMPDENOISE: messages are now displayed by default.');
    disp(' 10. KSVDDENOISE: simplified MSGDELTA parameter.');
    disp(' 11. KSVDDENOISE: default initial dictionary is now overcomplete DCT.');
    disp(' 12. KSVDDENOISE: parameter initdict can be the string ''data'' to indicate');
    disp('     initialization from training examples.');
    disp(' ');
    disp(' ');
    disp(' ');

    disp('KSVD Toolbox version 11, 03.08.09');
    disp('---------------------------------');
    disp(' ');
    disp('Features:');
    disp(' ');
    disp('  1. Added OMPDENOISE1 for fast OMP denoising of 1-D signals.');
    disp('  2. Added support for 1-D signals in KSVDDENOISE.');
    disp(' ');
    disp('Bug fixes:');
    disp('  1. Corrected a bug in OMPDENOISE/2/3 when memusage is low.');
    disp(' ');
    disp('Internal changes:');
    disp('  1. KSVD: only compute sum(data.*data) when memusage is high.');
    disp(' ');
    disp(' ');
    disp(' ');

    disp('KSVD Toolbox version 12, 24.08.09');
    disp('---------------------------------');
    disp(' ');
    disp('Features:');
    disp(' ');
    disp('  1. KSVD: significantly faster atom update computation via optimized');
    disp('     sparse-matrix code.');
    disp('  2. KSVD: reduced memory consumption by computing one column of G');
    disp('     at a time when clearing the dictionary, and using block processing');
    disp('     to compute representation error.');
    disp(' ');
    disp('Internal changes:');
    disp('  1. KSVD: when replacing an atom in cleardict, the search for an example');
    disp('     with maximal error is limited to a fixed number of signals.');
    disp('  2. KSVDDENOISEDEMO: memusage is set to ''high'' for faster performance.');
    disp(' ');
    disp(' ');

   end
end


function animatorz(action) % autogenerated function wrapper
    % turned into function by Celso G Reyes 2017

    animator(action, @slicemapz);
    ZG=ZmapGlobal.Data; % used by get_zmap_globals

    report_this_filefun(mfilename('fullpath'));

    global ps1 ps2 plin pli

    switch(action)
        case 'start'
            [ps1, ps2, plin, pli] = animator_start(@animatorz);% ButtonMotion, ButtonUp

        case 'move'
            animator_move(ps2, pli, plin)
        case 'stop'
            animator_stop(gcf);
            slicemapz('newslice');
    end
end


function showmovi()
    %  this is the file showmovi.m. It displays a movie with the variable
    %  name 'm'.
    %   Stefan Wiemer 11/94
    % turned into function by Celso G Reyes 2017

    ZG=ZmapGlobal.Data; % used by get_zmap_globals

    report_this_filefun();

    % This is the info window text
    %
    ttlStrmov='The Movie Window                                ';
    hlpStr1mov= ...
        ['                                                '
        ' This window displays a movie, a series of      '
        ' equivally spaced time cuts. Dispalyed are      '
        ' z-values of the selected function (e.g AS(t))  '
        ' in map view. The colorbar scaling is the same  '
        ' for eah frame, the maximum and minimum are the '
        ' overll maximum for all frames.                 '
        ' Menu options:                                  '
        '                                                '
        ' Circle: select the ni closest earthquakes to a '
        '       point selected with the mouse.           '
        ' Play:  Plays the movie. First the movie is     '
        '       loaded into the memory, then it is played'
        '       n-times (depending on the setting of the '
        '       <# of run> input box)                    '
        ' Speed: This is the number of frames per second '
        '       displayed. Your computer may not be able '
        '       to display the movie in high speed.       '
        ' Forward one frame (>) : Displays the next frame'
        ' Backward one frame: Displays the previous frame'
        ' Colormap: Seelect one of the colormaps in the  '
        '       pulldownmenu.                            '
        '                                                '];

    % find out if figure exists
    mov=findobj('Type','Figure','-and','Name','Movie Window');

    % Set up the Movie window Enviroment
    %
    %if isempty(mov)
    mov =   figure_w_normalized_uicontrolunits( ...
        'Name','Movie Window',...
        'NumberTitle','off', ...
        'NextPlot','new', ...
        'Visible','on', ...
        'Position',fs_m);

    %end % if exist

    figure(mov);
    set(gca,'NextPlot','add')
    mov = gcf;
    whitebg(color_fbg);
    h = gcf;
    speed = 0.5;
    clf reset
    drawnow;
    set(gcf,'resize','off');
    set(gca,'pos',rect1)

    axis off;
    cur_color = 'jet';
    colormap(jet);
    m0 = uicontrol('style','text','unit','norm','pos',[.06 .5 .8 .1]);
    set(m0,'string','Please Wait .... loading Data');
    set(m0,'background',color_fbg);
    drawnow;

    delete(m0);
    [a1,b1] = size(m);

    m1 = 'Loading movie to the Graphics Server ... please wait';

    movie(m(:,1),1,30);

    rect = [0.15 0.90 0.50 0.05 ];
    axes('position',rect)
    pco2 = pcolor([ZG.minc:0.1:ZG.maxc ; ZG.minc:0.1:ZG.maxc]);
    set(gca,'visible','on')
    h4 = gca;
    set(h4,'YTick',[-10 10])
    set(h4,'XTick',[-1000 1000])
    set(h4,'FontWeight','bold')
    shading flat

    rect = [0.15 0.90 0.50 0.05 ];
    pco5 = axes('position',rect);
    h5 = gca;
    axis([ ZG.minc ZG.maxc 0 1  ])
    set(h5,'YTick',[-10 10])
    set(h5,'FontWeight','bold')

    %rect = rect1;
    rect = [0.05 0.20 0.82 0.73 ];

    pco6 = axes('position',rect1);
    axis([min(gx) max(gx) min(gy)  max(gy) ])
    set(gca,'NextPlot','add')
    h6 = gca;
    hmo = gca;
    set(h6,'FontWeight','bold')

    movie(m(:,1),1,30);

    cs = uicontrol('style','popupmenu','string','HSV|Hot|Cool|Pink|Bone|Gary|Jet');
    set(cs,'unit','norm','pos',[.763 .05 .202 .05],...
        'callback',@callbackfun_001);
    h2 = uicontrol('style','text','unit','norm','string','Colormap');
    set(h2,'pos',[.763 .1 .2 .05],'background',color_fbg);

    frame_slide = uicontrol('style','slider','max',b1,'min',1,'uni','norm');
    set(frame_slide,'value',1,'pos',[.750 .25 .04 .5], 'callback',@callbackfun_002);
    frame = uicontrol('style','edit','value',10,'string',num2str(i), 'Callback', @callbackfun_003);
    flabel = uicontrol('style','text','units','norm','pos',[.55 .13 .2 .05]);
    set(flabel,'string','Speed','background',color_fbg);
    set(frame,'units','norm','pos',[.60 .07 .1 .05],'min',0.1,'max',30);

    uicontrol('style','text','units','norm','pos',[.80 .90 .20 .05],...
        'String','Forward 1 ','background',color_fbg);
    uicontrol('style','text','units','norm','pos',[.80 .80 .20 .05],...
        'String','Backward 1 ','background',color_fbg);

    next = uicontrol('style','pushbutton','unit','norm','pos',[0.75 .90 .04 .05]);
    set(next,'string','>','ForeGroundColor','k');
    set(next, 'callback',@callbackfun_004);
    bac = uicontrol('style','pushbutton','unit','norm','pos',[0.75 .80 .04 .05]);
    set(bac,'string','<');
    set(bac, 'callback',@callbackfun_005);
    time = uicontrol('style','edit','value',3,'string',num2str(3), 'Callback', @callbackfun_006);
    set(time,'units','norm','pos',[.23 .07 .1 .05],'min',1,'max',1000);
    tlabel = uicontrol('style','text','units','norm','pos',[.18 .13 .2 .05]);
    set(tlabel,'string','# of runs','background',color_fbg);
    start = uicontrol('style','pushbutton','unit','norm','pos',[.06 .05 .15 .1]);
    set(start,'interruptible','yes','string','Play');
    set(start, 'callback',@callbackfun_007);
    mc = 'close(gcf)';

    circ = uicontrol('units','norm','pos',[.40 .10 .10 .1],'style','pushbutton');
    set(circ,'string','Circle', 'callback',@callbackfun_008);

    set_ni = uicontrol('style','edit','value',100,'string',num2str(100));

    set(set_ni, 'Callback', @callbackfun_009);

    set(set_ni,'units','norm','pos',[.40 .02 .15 .05],'min',10,'max',10000);
    nilabel = uicontrol('style','text','units','norm','pos',[.36 .02 .04 .05]);
    set(nilabel,'string','ni:','background',color_fbg);

    uicontrol('Units','normal',...
        'Position',[.0 .95 .08 .06],'String','Close ',...
        'callback',@callbackfun_010)

    uicontrol('Units','normal',...
        'Position',[.0 .85 .08 .06],'String','Info ',...
        'callback',@callbackfun_011)

    uicontrol('Units','normal',...
        'Position',[.0 .75 .08 .06],'String','Refresh ',...
        'callback',@callbackfun_012);

    %si = signatur('ZMAP','',[0.01 0.02]);
    %set(si,'Color','k')

    axes(h6);
    watchoff(mess)
    watchoff(mov)

    function callbackfun_001(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        v = get(cs,'value');
        cur_color=lower(v);
        colormap(cur_color);
        movie(m(:,i),1,1);
    end

    function callbackfun_002(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        i=(get(frame_slide,'Value'));
        movie(m(:,i),1,1);
    end

    function callbackfun_003(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        speed=str2double(frame.String);
    end

    function callbackfun_004(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        i=i+1;
        if i > b1
            i=b1;
        end
        movie(m(:,i),1,1);
        frame_slide.Value=i;
    end

    function callbackfun_005(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        i=i-1;
        if i < 1
            i=1;
        end
        movie(m(:,i),1,1);
        frame_slide.Value=i;
    end

    function callbackfun_006(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        set(time,'Value',str2double(get(time,'string')));
    end

    function callbackfun_007(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        disp(m1);
        movie(m,fix(get(time,'value')*15/size(m,2)),speed);
    end

    function callbackfun_008(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        circmo;
    end

    function callbackfun_009(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        ni=str2double(set_ni.String);
        set_ni.String=num2str(ni);
    end

    function callbackfun_010(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        clear m;
        close(mov);

    end

    function callbackfun_011(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        zmaphelp(ttlStrmov,hlpStr1mov);
    end

    function callbackfun_012(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        close;
        showmovi;
    end

end


function removeCDReactions(fileName,rxnRemoveList,printLevel)
%removes a list of reactions from a cell designer map, also removes
%correspinding species and species aliases if necessary
%
% INPUT
%   xmlStruct:      Structure obtained from the "xml2struct" function.
%                   To be kept for the conversion back to an XML file
%                   of the structure.
%
%   map:            Matlab structure of the map containing all the
%                   relevant fields usable for checking and correction.
%
%   rxnRemoveList:  Cell array of reaction abbreviation to be removed
%
%   printLevel:     {0,(1)}
%
% OUTPUT
%   xmlStructOut:   Structure for the conversion back to an XML file
%                   of the structure.
%
%   mapOut:         Matlab structure of the smaller map containing all the
%                   relevant fields usable for checking and correction.
%
% rxnNotInMap: boolean vector the length of rxnRemoveList
%                        indicating reactions that could not be found in the map
%
% Ronan Fleming 2020

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

if 0
    xmlStruct = xml2struct(fileName);

    nMapReactions = length(xmlStruct.sbml.model.listOfReactions.reaction);

    mapRxns = cell(nMapReactions,1);
    for i=1:nMapReactions
        mapRxns{i}= xmlStruct.sbml.model.listOfReactions.reaction{i}.annotation.celldesigner_colon_extension.celldesigner_colon_name.Text;
    end

else
    %use the map structure to be able to delete isolated species and
    %species aliases
    [xmlStruct, map] = transformXML2Map(fileName);
    mapRxns = map.rxnName;
end

[mapRxnsToRemove,LOCB]=ismember(mapRxns,rxnRemoveList);

rxnNotInMap=~ismember((1:length(rxnRemoveList))',LOCB);
if any(rxnNotInMap)
    if printLevel>0
        ind = find(rxnNotInMap);
        for i=1:length(ind)
            fprintf('%s%s\n',rxnRemoveList{ind(i)}, ' not present in the map')
        end
    end
end

[s,~]= size(map.sID);
[m,~]=size(map.sAlias);

%use the map mapping matrices to determine which species and species
%aliases to remove
% map.sID	s x r	logical	Logical matrix with rows = speciesID and columns = reactionsID
mapSpeciesToRemove = getCorrespondingRows(map.sID, true(s,1), mapRxnsToRemove, 'exclusive');

% map.sAlias	m x r	logical	Logical matrix with rows = speciesAlias and columns = reactionsID
mapMolsToRemove = getCorrespondingRows(map.sAlias, true(m,1), mapRxnsToRemove, 'exclusive');

%remove reactions
xmlStruct.sbml.model.listOfReactions.reaction = xmlStruct.sbml.model.listOfReactions.reaction(~mapRxnsToRemove);

%remove species
xmlStruct.sbml.model.listOfSpecies.species = xmlStruct.sbml.model.listOfSpecies.species(~mapSpeciesToRemove);

%remove species alias
xmlStruct.sbml.model.annotation.celldesigner_colon_extension.celldesigner_colon_listOfSpeciesAliases.celldesigner_colon_speciesAlias =...
    xmlStruct.sbml.model.annotation.celldesigner_colon_extension.celldesigner_colon_listOfSpeciesAliases.celldesigner_colon_speciesAlias(~mapMolsToRemove);

%write out the reduced xml file
struct2xml(xmlStruct, [fileName(1:end-4) '_subset.xml']);


function [cellmap] = createObjMap(inputImages,varargin)
	% Creates a cellmap from a ZxXxY input matrix of input images.
	% Biafra Ahanonu
	% started: 2013.10.12
	% inputs
		%
	% outputs
		%

	[cellmap] = ciapkg.image.createObjMap(inputImages,'passArgs', varargin);
end


function R = get(DS, props)
%GET gets the properties of the dataset
%
% $ Syntax $
%   - R = get(DS, propname)
%   - R = get(DS, propname cell array)
%
% $ Description $
%   - R = get(DS, propname) gets a property value with its name specified
%     by propname
%
%   - R = get(DS, propname cell array) gets a set of properties with the
%     names given in a cell array. Consequently, the property values are
%     returns through a cell array of the same size.
%
% $ Remarks $
%   - The
% $ History $
%   - Created by Dahua Lin on Jul 23rd, 2006
%

%% Skeleton

if ischar(props)
    S = struct(DS);
    R = getprop(S, props);

elseif iscell(props)
    S = struct(DS);
    R = cell(size(props));
    n = numel(R);
    for i = 1 : n
        if ~ischar(props{i})
            error('dsdml:invalidarg', ...
                'The property name should be a char string');
        end
        R{i} = getprop(S, props{i});
    end

else
    error('dsdml:invalidarg', ...
        'The props should be a property name or a cell of property names');
end

%% Property getting function

function R = getprop(S, propname)

if isfield(S, propname)
    R = S.(propname);
elseif ~isempty(S.attribs) && isfield(S.attribs, propname)
    R = S.attribs.(propname);
else
    switch(propname)
        case 'numsamples'
            R = getnumsamples(S);
        case 'numgroups'
            R = getnumgroups(S);
        case 'numunits'
            R = length(S.units);

        case 'samples'
            R = getsamples(S);
        case 'groups'
            R = getgroups(S);
        case 'class_ids'
            R = getclass_ids(S);
        case 'filenames'
            R = getfilenames(S);
        case 'nums'
            R = getnums(S);

        case 'numspergrp'
            R = getnumspergrp(S);
        case 'grpnums'
            R = getgrpnums(S);
        case 'grpclass_ids'
            R = getgrpclass_ids(S);

        otherwise
            error('dsdml:invalidarg', ...
                'Invalid property name of the dataset: %s', propname);
    end
end

%% Specific property getting functions

function R = getnumsamples(S)

switch S.unittype
    case 'Sample'
        R = length(S.units);
    case 'SampleGroup'
        R = 0;
        ng = length(S.units);
        for i = 1 : ng
            R = R + length(S.units(i).samples);
        end
    otherwise
        invalid_utype(S);
end

function R = getnumgroups(S)

switch S.unittype
    case {'Sample', 'SampleGroup'}
        R = length(S.units);
    otherwise
        invalid_utype(S);
end

function R = getsamples(S)

switch S.unittype
    case 'Sample'
        R = S.units;
    case 'SampleGroup'
        R = vertcat(S.units.samples);
    otherwise
        invalid_utype(S);
end

function R = getgroups(S)

switch S.unittype
    case 'Sample'
        n = length(S.units);
        U = S.units;
        R = struct(...
            'class_id', cell(n, 1), ...
            'samples', cell(n, 1), ...
            'attribs', cell(n, 1));
        for i = 1 : n
            R(i).class_id = U(i).class_id;
            R(i).samples = U(i);
        end
    case 'SampleGroup'
        R = S.units;
    otherwise
        invalid_utype(S);
end

function R = getclass_ids(S)

switch(S.unittype)
    case 'Sample'
        n = length(S.units);
        R = zeros(n, 1);
        for i = 1 : n
            R(i) = S.units(i).class_id;
        end
    case 'SampleGroup'
        n = getnumsamples(S);
        R = zeros(n, 1);
        c = 0;
        ng = length(S.units);
        for i = 1 : ng
            ns = length(S.units(i).samples);
            R(c+1:c+ns) = S.units(i).class_id;
            c = c + ns;
        end
    otherwise
        invalid_utype(S);
end

function R = getfilenames(S)

switch(S.unittype)
    case 'Sample'
        n = length(S.units);
        R = cell(n, 1);
        for i = 1 : n
            R{i} = S.units(i).filename;
        end
    case 'SampleGroup'
        n = getnumsamples(S);
        R = cell(n, 1);
        c = 0;
        ng = length(S.units);
        for i = 1 : ng
            ns = length(S.units(i).samples);
            [R{c+1:c+ns}] = deal(S.units(i).samples.filename);
            c = c + ns;
        end
    otherwise
        invalid_utype(S);
end

function R = getnums(S)

R = countnums(getclass_ids(S));

function R = getnumspergrp(S)

switch (S.unittype)
    case 'Sample'
        n = length(S.units);
        R = ones(n, 1);

    case 'SampleGroup'
        n = length(S.units);
        R = zeros(n, 1);
        for i = 1 : n
            R(i) = length(S.units(i).samples);
        end

    otherwise
        invalid_utype(S);
end

function R = getgrpnums(S)

R = countnums(getgrpclass_ids(S));

function R = getgrpclass_ids(S)

switch (S.unittype)
    case {'Sample', 'SampleGroup'}
        n = length(S.units);
        R = zeros(n, 1);
        for i = 1 : n
            R(i) = S.units(i).class_id;
        end

    otherwise
        invalid_utype(S);
end

%% Auxiliary functions

function invalid_utype(S)

error('dsdml:invalidunittype', ...
            'Invalid unit type: %s', S.unittype);

function nums = countnums(A)

A = A(:);
difs = diff(A);
n = length(A);
nums = [0; find(difs ~= 0); n];
nums = diff(nums);


function fh = copyfig(fh)
%COPYFIG Create a copy of a figure, without changing the figure
%
% Examples:
%   fh_new = copyfig(fh_old)
%
% This function will create a copy of a figure, but not change the figure,
% as copyobj sometimes does, e.g. by changing legends.
%
% IN:
%    fh_old - The handle of the figure to be copied. Default: gcf.
%
% OUT:
%    fh_new - The handle of the created figure.

% Copyright (C) Oliver Woodford 2012, Yair Altman 2015

% 26/02/15: If temp dir is not writable, use the dest folder for temp
%           destination files (Javier Paredes)
% 15/04/15: Suppress warnings during copyobj (Dun Kirk comment on FEX page 2013-10-02)
% 09/09/18: Fix issue #252: Workaround for cases where copyobj() fails for any reason

    % Set the default
    if nargin == 0
        fh = gcf;
    end
    % Is there a legend?
    useCopyobj = isempty(findall(fh, 'Type', 'axes', 'Tag', 'legend'));
    if useCopyobj
        % Safe to copy using copyobj
        oldWarn = warning('off'); %Suppress warnings during copyobj (Dun Kirk comment on FEX page 2013-10-02)
        try
            fh = copyobj(fh, 0);
        catch
            % Fix issue #252: Workaround for cases where copyobj() fails for any reason
            useCopyobj = false;  % if copyobj() croaks, use file save/load below
        end
        warning(oldWarn);
    end
    if ~useCopyobj
        % copyobj will change the figure, so save and then load it instead
        tmp_nam = [tempname '.fig'];
        try
            % Ensure that the temp dir is writable (Javier Paredes 26/2/15)
            fid = fopen(tmp_nam,'w');
            fwrite(fid,1);
            fclose(fid);
            delete(tmp_nam);  % cleanup
        catch
            % Temp dir is not writable, so use the current folder
            [dummy,fname,fext] = fileparts(tmp_nam); %#ok<ASGLU>
            fpath = pwd;
            tmp_nam = fullfile(fpath,[fname fext]);
        end
        hgsave(fh, tmp_nam);
        fh = hgload(tmp_nam);
        delete(tmp_nam);
    end
end


function output = yalmip_default_output;
output.Primal    = [];
output.Dual      = [];
output.Slack     = [];
output.problem = 0;
output.infostr = yalmiperror(0);
output.solverinput  = [];
output.solveroutput = [];
output.solvertime   = 0;


function x = rhs( y )
x = y.rhs_;

% Copyright 2005-2014 CVX Research, Inc.
% See the file LICENSE.txt for full copyright information.
% The command 'cvx_where' will show where this file is located.


function view=xformFlatLevelMenu(view)
%
% view = xformFlatLevelMenu(view)
%
% Set up the callbacks for the xformView menu in the Flat Level view
%
% djh, 1/9/98
% rmk, 1/10/99 added xformParMap
% rmk, 1/15/99 added xformAllROIs
% ras, 10/04 created xformFlatLevelMenu

mrGlobals;

xformMenu = uimenu('Label','Xform','separator','on');

% Xform ROI callback:
%   gray=checkSelectedGray;
%   view=vol2flatCurROILevels(gray,view);
%   view=refreshScreen(view,0);
callBackstr=['gray=checkSelectedGray; ',...
        view.name,'=vol2flatCurROILevels(gray,',view.name,'); ',...
        view.name,'=refreshScreen(',view.name,',0);'];
uimenu(xformMenu,'Label','ROI (selected)','Separator','off',...
    'CallBack',callBackstr);

% Xform AllROIs callback:
%   gray=checkSelectedGray;
%   view=vol2flatAllROIsLevels(gray,view);
%   view=refreshScreen(view,0);
callBackstr=['gray=checkSelectedGray; ',...
        view.name,'=vol2flatAllROIsLevels(gray,',view.name,'); ',...
        view.name,'=refreshScreen(',view.name,',0);'];
uimenu(xformMenu,'Label','ROIs (all)','Separator','on',...
    'CallBack',callBackstr);

% Xform CorAnal all scans callback:
%   gray=checkSelectedGray;
%   view=vol2flatCorAnalLevels(gray,view,0);
%   view=refreshScreen(view,1);
callBackstr=['gray=checkSelectedGray; ',...
        view.name,'=vol2flatCorAnalLevels(gray,',view.name,',0); ',...
        view.name,'=refreshScreen(',view.name,',1);'];
uimenu(xformMenu,'Label','CorAnal (all scans)','Separator','on',...
    'CallBack',callBackstr);

% Xform CorAnal current scan callback:
%   gray=checkSelectedGray;
%   view=vol2flatCorAnalLevels(gray,view,getCurScan(view));
%   view=refreshScreen(view,1);
callBackstr=['gray=checkSelectedGray; ',...
        view.name,'=vol2flatCorAnalLevels(gray,',view.name,',getCurScan(',view.name,')); ',...
        view.name,'=refreshScreen(',view.name,',1);'];
uimenu(xformMenu,'Label','CorAnal (current scan)','Separator','on',...
    'CallBack',callBackstr);

% Xform CorAnal select scans callback:
%   gray=checkSelectedGray;
%   view=vol2flatCorAnalLevels(gray,view);
%   view=refreshScreen(view,1);
callBackstr=['gray=checkSelectedGray; ',...
        view.name,'=vol2flatCorAnalLevels(gray,',view.name,'); ',...
        view.name,'=refreshScreen(',view.name,',1);'];
uimenu(xformMenu,'Label','CorAnal (select scans)','Separator','on',...
    'CallBack',callBackstr);

% Xform ParMap all scans callback:
%   gray=checkSelectedGray;
%   view=vol2flatParMapLevels(gray,view,0);
%   view=setDisplayMode(view,'map');
%   view=refreshScreen(view,1);
callBackstr=['gray=checkSelectedGray; ',...
        view.name,'=vol2flatParMapLevels(gray,',view.name,',0); ',...
        view.name,'=setDisplayMode(',view.name,',''map''); ',...
        view.name,'=refreshScreen(',view.name,',1);'];
uimenu(xformMenu,'Label','Parameter Map (all scans)','Separator','on',...
    'CallBack',callBackstr);

% Xform ParMap current scan callback:
%   gray=checkSelectedGray;
%   view=vol2flatParMapLevels(gray,view,getCurScan(view));
%   view=setDisplayMode(view,'map');
%   view=refreshScreen(view,1);
callBackstr=['gray=checkSelectedGray; ',...
        view.name,'=vol2flatParMapLevels(gray,',view.name,',getCurScan(',view.name,')); ',...
        view.name,'=setDisplayMode(',view.name,',''map''); ',...
        view.name,'=refreshScreen(',view.name,',1);'];
uimenu(xformMenu,'Label','Parameter Map (current scan)','Separator','on',...
    'CallBack',callBackstr);

% Xform ParMap select scans callback:
%   gray=checkSelectedGray;
%   view=vol2flatParMapLevels(gray,view);
%   view=setDisplayMode(view,'map');
%   view=refreshScreen(view,1);
callBackstr=['gray=checkSelectedGray; ',...
        view.name,'=vol2flatParMapLevels(gray,',view.name,'); ',...
        view.name,'=setDisplayMode(',view.name,',''map''); ',...
        view.name,'=refreshScreen(',view.name,',1);'];
uimenu(xformMenu,'Label','Parameter Map (select scans)','Separator','on',...
    'CallBack',callBackstr);

% Xform tSeries all scans callback:
%   gray=checkSelectedGray;
%   view=vol2flatTSeriesLevels(gray,view,0);
%   view=setDisplayMode(view,'map');
%   view=refreshScreen(view,1);
callBackstr=['gray=checkSelectedGray; ',...
        view.name,'=vol2flatTSeriesLevels(gray,',view.name,',0); ',...
        view.name,'=setDisplayMode(',view.name,',''map''); ',...
        view.name,'=refreshScreen(',view.name,',1);'];
uimenu(xformMenu,'Label','tSeries (all scans)','Separator','on',...
    'CallBack',callBackstr);

% Xform tSeries current scan callback:
%   gray=checkSelectedGray;
%   view=vol2flatTSeriesLevels(gray,view,getCurScan(view));
%   view=setDisplayMode(view,'map');
%   view=refreshScreen(view,1);
callBackstr=['gray=checkSelectedGray; ',...
        view.name,'=vol2flatTSeriesLevels(gray,',view.name,',getCurScan(',view.name,')); ',...
        view.name,'=setDisplayMode(',view.name,',''map''); ',...
        view.name,'=refreshScreen(',view.name,',1);'];
uimenu(xformMenu,'Label','tSeries (current scan)','Separator','on',...
    'CallBack',callBackstr);

% Xform tSeries select scans callback:
%   gray=checkSelectedGray;
%   view=vol2flatTSeriesLevels(gray,view);
%   view=setDisplayMode(view,'map');
%   view=refreshScreen(view,1);
callBackstr=['gray=checkSelectedGray; ',...
        view.name,'=vol2flatTSeriesLevels(gray,',view.name,'); ',...
        view.name,'=setDisplayMode(',view.name,',''map''); ',...
        view.name,'=refreshScreen(',view.name,',1);'];
uimenu(xformMenu,'Label','tSeries (select scans)','Separator','on',...
    'CallBack',callBackstr);

return


%FEATSETC Set classifier

% Copyright: R.P.W. Duin, r.p.w.duin@37steps.com
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands

function [out1,out2] = featsetc(a,objclassf,fsetindex,fsetcombc,fsetclassf,fsetlab)

error('featsetc has been replaced by bagc')


function v = cvxtuple( varargin )

if nargin == 1,
    v = varargin{1};
    switch class( v ),
        case 'struct',
            if numel( v ) ~= 1,
                error( 'struct arrays not permitted in cvx tuple objects.' );
            end
        case 'cell',
            v = reshape( v, 1, numel( v ) );
        otherwise,
            return
    end
else
    v = varargin;
end

v = class( struct( 'value_', { v } ), 'cvxtuple', cvxobj );

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


function sample()
% Create an output file with sys command
!touch test_file.txt
fid = fopen('test_file.txt', 'w');
for i=1:20
    fprintf(fid, '%d unterminated\n, i);
end
fclose(fid);
end

function unusedFunc(passedInput)
persistent global_value;
global_value = global_value + 1;
%% Title of cell
printed_var = subFunc(global_value)
unused_var = printed_var;
    function out = subFunc(scaleFactor)
        fprintf('Scale %.4f\n', scaleFactor);
        out = passedInput * scaleFactor;
    end
end


function version = om_getgccversion
% checks for gcc compiler version (works if superior to gcc3)
% Copyright (C) 2010-2017, OpenMEEG developers

tmpdir = pwd;
cd /tmp
[junk,tname] = fileparts(tempname);
txtfile  = [tname '.txt'];
dos(['gcc -v >& ' txtfile]);
efid = fopen(txtfile);

tmp = ''; cnt = 1;
vec = [];
while ~isnumeric(tmp)
    tmp = fgetl(efid);
    vec{cnt} = tmp;
    cnt = cnt+1;
end
fclose(efid);
delete(txtfile);
cd(tmpdir);
tmp = deblank(vec{cnt-2});
num = findstr('gcc version ',tmp);
version = str2num(tmp(num+11:num+12));
if isempty(version) && findstr('clang',vec{2}) > 0
    version = 5;
end


function obsNames = prtUtilGenerateDefaultObservationNames(indices2)
% obsNames = prtUtilGenerateDefaultObservationNames(indices2)

% Previously static in prtDataSetBase
%     function obsNames = generateDefaultObservationNames(indices2)
%         obsNames = prtUtilCellPrintf('Observation %d',num2cell(indices2));
%         obsNames = obsNames(:);
%     end
obsNames = prtUtilCellPrintf('Observation %d',num2cell(indices2));
obsNames = obsNames(:);


function v = setLayerInputs(obj, layer, inputs)
%SETLAYERINPUTS  Set or change the inputs to a layer
%   Example: NET.SETLAYERINPUTS('layerName', {'input1', 'input2', ...})

v = [] ;
l = obj.getLayerIndex(layer) ;
for input = inputs
  v(end+1) = obj.addVar(char(input)) ;
end
obj.layers(l).inputs = inputs ;
obj.rebuild() ;


% Ryan Steindl based on Robotics Toolbox for MATLAB (v6 and v9)
%
% Copyright (C) 1993-2011, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB 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 Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB.  If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function r = subsasgn(r, s, v)

	if s(1).type  ~= '.'
		error('only .field supported')
	end
	switch s(1).subs,
	case 'links'
		r.links = v;
	case 'lineopt',
		r.lineopt = v;
	case 'shadowopt',
		r.shadowopt = v;
	case 'offset',
		L = r.links;
		for i=1:r.n,
			L(i).offset = v(i);
		end
	case 'qlim',
		if numrows(v) ~= r.n,
			error('insufficient rows in joint limit matrix');
		end
		L = r.links;
		for i=1:r.n,
			L(i).qlim = v(i,:);
		end
	case 'q',
		r.q = v;
	case 'handle',
		r.handle = v;
	case 'plotopt',
		r.plotopt = v;
	case 'gravity',
		r.gravity = v;
	case 'tool',
		if ~ishomog(v)
			error('base must be a homogeneous transform');
		end
		r.tool = v;
	case 'base',
		if ~ishomog(v)
			error('base must be a homogeneous transform');
		end
		r.base = v;
	case 'name',
		r.name = v;
	case 'manufacturer',
		r.manufacturer = v;
	case 'comment',
		r.comment = v;
	otherwise, error('Unknown method in subsasgn')
	end


% print_n_updates - example hook function for each update
% Copyright (C) 2011 KyungHyun Cho, Tapani Raiko, Alexander Ilin
%
% This program is free software; you can redistribute it and/or
% modify it under the terms of the GNU General Public License
% as published by the Free Software Foundation; either version 2
% of the License, or (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
%

function err = print_n_updates (R, args)

if R.verbose == 1
    fprintf(2, '# updates: %d\n', R.iteration.n_updates);
end

err = 0;


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

    properties

    end

    methods
        vect = getVectorAtTime(obj, time, vehElemSet, inFrame)

        name = getName(obj)

        setName(obj, name)

        listboxStr = getListboxStr(obj)

        useTf = openEditDialog(obj)

        tf = isVehDependent(obj)

        origin = getOriginPointInViewFrame(obj, time, vehElemSet, viewFrame)

        tf = usesGroundObj(obj, groundObj)

        tf = usesGeometricPoint(obj, point)

        tf = usesGeometricVector(obj, vector)

        tf = usesGeometricCoordSys(obj, coordSys)

        tf = usesGeometricRefFrame(obj, refFrame)

        tf = usesGeometricAngle(~, ~)

        tf = usesGeometricPlane(~, ~)

        tf = isInUse(obj, lvdData)
    end

    methods(Sealed)
        function tf = eq(a,b)
            tf = eq@handle(a,b);
        end

        function tf = ne(a,b)
            tf = ne@handle(a,b);
        end
    end
end


function s=mergestruct(s1,s2)
%
% s=mergestruct(s1,s2)
%
% merge two struct objects into one
%
% authors:Qianqian Fang (q.fang <at> neu.edu)
% date: 2012/12/22
%
% input:
%      s1,s2: a struct object, s1 and s2 can not be arrays
%
% output:
%      s: the merged struct object. fields in s1 and s2 will be combined in s.
%
% 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)
%

if(~isstruct(s1) || ~isstruct(s2))
    error('input parameters contain non-struct');
end
if(length(s1)>1 || length(s2)>1)
    error('can not merge struct arrays');
end
fn=fieldnames(s2);
s=s1;
for i=1:length(fn)
    s=setfield(s,fn{i},getfield(s2,fn{i}));
end


addpath /n/fs/vision/www/pvt/

latexFname = '/Users/xj/Documents/museumIJCV/museumCSG/ijcv.tex';
oriPath = '/Users/xj/Documents/museumIJCV/museumCSG/all';
newPath = '/Users/xj/Documents/museumIJCV/museumCSG/';

% this script parse a latex file and copy all figures into a new location
% this is usually used to get a clean version for submitting latex files
% to places like IJCV or ECCV that requires the latex file for final
% submission

str = file2string(latexFname);

pos = strfind(str,'\includegraphics[');

newline = sprintf('\n');

images = {};

for i=1:length(pos)
    ps = strfind(str(pos(i):end),'{');  ps = ps(1);
    pe = strfind(str(pos(i):end),'}');  pe = pe(1);

    nlp = strfind(str(1:pos(i)),newline);
    if isempty(nlp)
        nlp = 0;
    else
        nlp = nlp(end);
    end

    cmp = strfind(str(1:pos(i)),'%');
    if isempty(cmp)
        cmp = 0;
    else
        cmp = cmp(end);
    end

    if nlp>=cmp
        images{end+1} = str(pos(i)+ps:pos(i)+pe-2);
    end
end

for i=1:length(images)
    newF = fullfile(newPath,images{i});
    if ~exist(fileparts(newF),'dir')
        mkdir(fileparts(newF));
    end
    copyfile(fullfile(oriPath,images{i}),newF);
end


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

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

% Last Modified by GUIDE v2.5 20-Mar-2004 17:42:25

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @plot_function_OpeningFcn, ...
                   'gui_OutputFcn',  @plot_function_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before plot_function is made visible.
function plot_function_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to plot_function (see VARARGIN)

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

% Update handles structure
guidata(hObject, handles);

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

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

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

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

% Hints: get(hObject,'String') returns contents of a as text
%        str2double(get(hObject,'String')) returns contents of a as a double

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

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

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

% Hints: get(hObject,'String') returns contents of b as text
%        str2double(get(hObject,'String')) returns contents of b as a double

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

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

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

% Hints: get(hObject,'String') returns contents of c as text
%        str2double(get(hObject,'String')) returns contents of c as a double

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

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

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

% Hints: get(hObject,'String') returns contents of xmin as text
%        str2double(get(hObject,'String')) returns contents of xmin as a double

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

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

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

% Hints: get(hObject,'String') returns contents of xmax as text
%        str2double(get(hObject,'String')) returns contents of xmax as a double

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

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

% --- Executes on selection change in popupmenu1.
function popupmenu1_Callback(hObject, eventdata, handles)
% hObject    handle to popupmenu1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

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

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

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

% --- Executes on selection change in popupmenu2.
function popupmenu2_Callback(hObject, eventdata, handles)
% hObject    handle to popupmenu2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

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

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

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

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

% Hints: get(hObject,'String') returns contents of edit7 as text
%        str2double(get(hObject,'String')) returns contents of edit7 as a double

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

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


function [trl, event] = ft_trialfun_trial(cfg)

% FT_TRIALFUN_TRIAL creates a trial definition that corresponds to the
% events that are returned by FT_READ_EVENT with type='trial'
%
% You can use this function as follows
%   cfg           = [];
%   cfg.dataset   = string, containing filename or directory
%   cfg.trialfun  = 'ft_trialfun_trial';
%   cfg           = definetrial(cfg);
%   data          = preprocessing(cfg);
%
% See also FT_DEFINETRIAL, FT_PREPROCESSING

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

if isfield(cfg, 'event')
  % for BCI applications events should be specified in the cfg
  % to prevent reading the same events many times
  event = cfg.event;
else
  event = ft_read_event(cfg.dataset);
end

sel = find(strcmp({event.type}, 'trial'));
trl = zeros(length(sel),3);

smp = [event.sample];

for i=1:length(sel)
  % determine the begin, end and offset for each trial and add it to the Nx3 matrix
  begsample = event(sel(i)).sample;
  endsample = begsample + event(sel(i)).duration - 1;
  offset    = event(sel(i)).offset;

  tmpsel    = find(smp==smp(sel(i))-offset);
  tmpval    = zeros(1,0);
  for k=1:length(tmpsel)
    if ~isempty(event(tmpsel(k)).value)
      % this assumes per trial that the triggers occur in a standardised
      % order, otherwise the entries per column will have different
      % meanings
      tmpval = [tmpval event(tmpsel(k)).value];
    end
  end

  trl(i,1:(length(tmpval)+3))  = [begsample endsample offset tmpval];
end


function asc = read_eyelink_asc(filename)

% READ_EYELINK_ASC reads the header information, input triggers, messages
% and all data points from an Eyelink *.asc file. The output events are
% represented as matlab tables (after Aug 2022)
%
% Use as
%   asc = read_eyelink_asc(filename)

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

% read the whole file at once
fid = fopen_or_error(filename, 'rt');
aline = fread(fid, inf, 'char=>char');          % returns a single long string
fclose(fid);

aline(aline==uint8(sprintf('\r'))) = [];        % remove cariage return
aline = tokenize(aline, uint8(newline));        % split on newline

sel = startsWith(aline, '0') | ...
      startsWith(aline, '1') | ...
      startsWith(aline, '2') | ...
      startsWith(aline, '3') | ...
      startsWith(aline, '4') | ...
      startsWith(aline, '5') | ...
      startsWith(aline, '6') | ...
      startsWith(aline, '7') | ...
      startsWith(aline, '8') | ...
      startsWith(aline, '9');

datline = aline(sel);
aline   = aline(~sel);

% according to the eyelink documentation, the sample lines have different
% flavours, depending on how the data was collected (monocular or
% binocular), and possibly the conversion settings from edf2asc
% Monocular,                              <time> <xp>  <yp>  <ps>
% Monocular, with velocity                <time> <xp>  <yp>  <ps>  <xv>  <yv>
% Monocular, with resolution              <time> <xp>  <yp>  <ps>  <xr>  <yr>
% Monocular, with velocity and resolution <time> <xp>  <yp>  <ps>  <xv>  <yv>  <xr>  <yr>
% Binocular,                              <time> <xpl> <ypl> <psl> <xpr> <ypr> <psr>
% Binocular, with velocity                <time> <xpl> <ypl> <psl> <xpr> <ypr> <psr> <xvl> <yvl> <xvr> <yvr>
% Binocular, with resolution              <time> <xpl> <ypl> <psl> <xpr> <ypr> <psr> <xr> <yr>
% Binocular, with velocity and resolution <time> <xpl> <ypl> <psl> <xpr> <ypr> <psr> <xvl> <yvl> <xvr> <yvr><xr> <yr>
%
% Then, there may be additional columns, if recorded with cornea reflection
% mode:
%
% MONOCULAR Corneal Reflection (CR) Samples
% "..." if no warning for sample
% first character is "I" if sample was interpolated
% second character is "C" if CR missing
% third character is "R" if CR recovery in progress
%
% BINOCULAR Corneal Reflection (CR) Samples?
% "....." if no warning for sample
% first character is "I" if sample was interpolated
% second character is "C" if LEFT CR missing
% third character is "R" if LEFT CR recovery in progress
% fourth character is "C" if RIGHT CR missing
% fifth character is "R" if RIGHT CR recovery in progress
%
% Then, there may be additional columns, if data collection was done in
% remote mode:
%
% Data files recorded using the Remote Mode have extra columns to encode the
% target distance, position, and eye/target status information. The first three
% columns are:
% <target x>: X position of the target in camera coordinate (a value from 0 to 10000).
% Returns "MISSING_DATA" (-32768) if target is missing.
% <target y>: Y position of the target in camera coordinate (a value from 0 to 10000).
% Returns "MISSING_DATA" (-32768) if target is missing.
% <target distance>: Distance between the target and camera (in millimeters).
% Returns "MISSING_DATA" (-32768) if target is missing.
% The next thirteen fields represent warning messages for that sample relating to
% the target and eye image processing."............." if no warning for target and eye image
% first character is "M" if target is missing
% second character is "A" if extreme target angle occurs
% third character is "N" if target is near eye so that the target window and eye window overlap
% fourth character is "C" if target is too close
% fifth character is "F" if target is too far
% sixth character is "T" if target is near top edge of the camera image
% seventh character is "B" if target is near bottom edge of the camera image
% eighth character is "L" if target is near left edge of the camera image
% ninth character is "R" if target is near right edge of the camera image
% tenth character is "T" if eye is near top edge of the camera image
% eleventh character is "B" if eye is near bottom edge of the camera image
% twelfth character is "L" if eye is near left edge of the camera image
% thirteenth character is "R" if eye is near right edge of the camera image
% For a binocular recording, there will be seventeen target/eye status columns,
% with the last eight columns reporting the warning messages for the left and
% right eyes separately.

% So, anecdotally, parsing the file is a bit tedious, and not very robust.
% Reading and converting per line is super slow, so here I chose to pipe
% the datalines through a checker that removes all '...' '.....'
% '.............' and '.................' (or containing warning) stuff
% so that we end up with more or less well behaved data.

% check if the formatting for all datlines is similar
seltab = char(datline)==sprintf('\t');
ntab   = sum(seltab,2);

% check whether all lines have the same number of columns
assert(all(ntab==ntab(1)));

% identify the chunks of consecutive '...' and comments
str = char(datline)';
str(end+1, :) = sprintf('\t');
siz = size(str);
str = uint8(str(:)');

boolval = str==46 | (str>=65&str<=90); % dots or capital letters
begsmp  = find(boolval==1 & [0 boolval(1:end-1)]==0);
endsmp  = find(boolval==1 & [boolval(2:end) 1]==0);
sel     = ~ismember(endsmp-begsmp+1, [3 5 13 17]);
boolval(begsmp(sel)) = false;
str(boolval) = 32;

str = reshape(char(str), siz); % now all the warnings etc should have been removed
datline = cellstr(str(1:end-1,:)');

% check again if the formatting for all datlines is similar
nline  = numel(datline);
seltab = char(datline)==sprintf('\t');
ntab   = sum(seltab,2);

% check whether all lines have the same number of columns
assert(all(ntab==ntab(1)));

fmt = repmat('%s ', [1 ntab(1)+1]);
fmt = fmt(1:end-1);

% convert datline in a long string again
datline = char(datline)';
datline(end+1, :) = sprintf('\t');
datline = datline(:)';

C   = textscan(datline, fmt, nline, 'Delimiter', sprintf('\t'));
dat = zeros(nline, numel(C)) + nan;
for i=1:numel(C)
  notok = strcmp(C{i}, '.')|strcmp(C{i}, '  ')|strcmp(C{i}, '     ')|cellfun('isempty', C{i})|startsWith(C{i}, '. ');
  ok    = ~notok;
  tmp = reshape([char(C{i}(ok))';repmat(' ',1,sum(ok))],[],1)';

  % convert to floats, much faster than str2double
  if sum(ok)
    tmp = textscan(tmp, '%f');
    dat(ok, i) = tmp{1};
  end
end
asc.dat = dat';

% remove any all-nan rows
asc.dat(sum(~isfinite(asc.dat),2)==size(asc.dat,2), :) = [];

selsfix    = startsWith(aline, 'SFIX');
selefix    = startsWith(aline, 'EFIX');
selssacc   = startsWith(aline, 'SSACC');
selesacc   = startsWith(aline, 'ESACC');
selsblink  = startsWith(aline, 'SBLINK');
seleblink  = startsWith(aline, 'EBLINK');
selmsg     = startsWith(aline, 'MSG');
selhdr     = startsWith(aline, '**');
selinput   = startsWith(aline, 'INPUT');

asc.sfix   = tocell(aline(selsfix)); % convert cell-vector of lines into a cell array
asc.efix   = tocell(aline(selefix));
asc.ssacc  = tocell(aline(selssacc));
asc.esacc  = tocell(aline(selesacc));
asc.sblink = tocell(aline(selsblink));
asc.eblink = tocell(aline(seleblink));
asc.msg    = tocell(aline(selmsg), 1);
asc.header = char(aline(selhdr));
asc.input  = tocell(aline(selinput));

% convert the cell-arrays into tables
if ~isempty(asc.sfix),   asc.sfix   = totable(asc.sfix(:, 2:end),   {'eye' 'stime'}); end
if ~isempty(asc.sblink), asc.sblink = totable(asc.sblink(:, 2:end), {'eye' 'stime'}); end
if ~isempty(asc.ssacc),  asc.ssacc  = totable(asc.ssacc(:, 2:end),  {'eye' 'stime'}); end
if ~isempty(asc.input),  asc.input  = totable(asc.input(:, 2:end),  {'timestamp', 'value'}, [1 2]); end

% these lines may have been formatted in different ways
if ~isempty(asc.efix)
  try
    asc.efix = totable(asc.efix(:,2:end), {'eye', 'stime', 'etime', 'dur', 'axp', 'ayp', 'aps'});
  catch
    asc.efix = totable(asc.efix(:,2:end), {'eye', 'stime', 'etime', 'dur', 'axp', 'ayp', 'aps', 'xr', 'yr'});
  end
end
if ~isempty(asc.eblink)
  asc.eblink = totable(asc.eblink(:,2:end), {'eye', 'stime', 'etime', 'dur'});
end
if ~isempty(asc.esacc)
  try
    asc.esacc = totable(asc.esacc(:,2:end), {'eye', 'stime', 'etime', 'dur', 'sxp', 'syp', 'exp', 'eyp', 'ampl', 'pv'});
  catch
    asc.esacc = totable(asc.esacc(:,2:end), {'eye', 'stime', 'etime', 'dur', 'sxp', 'syp', 'exp', 'eyp', 'ampl', 'pv', 'xr', 'yr'});
  end
end

function lineout = convertline(linein, msgflag)

% split the line by horizontal tabs, and the first output element
% thereof by spaces.

%tmp     = strrep(linein, sprintf('\t'), ' ');
lineout = strsplit(linein, '\t');
lineout = [strsplit(lineout{1}, ' ') lineout(2:end)];
if msgflag
  tmp = strsplit(lineout{2}, ' ');
  lineout = [lineout(1) tmp(1) {sprintf('%s ', tmp{2:end})}];
end

function tableout = totable(cellin, fnames, convert)

if nargin<3
  convert = 2:numel(fnames);
end

% convert into table, and do a str2double conversion for the numeric data,
% assuming only the first variable to be kept as a string

tableout = cell2table(cellin, 'VariableNames', fnames);
for k = convert
  tableout.(fnames{k}) = str2double(tableout.(fnames{k}));
end

function cellout = tocell(textin, msgflag)

if nargin<2
  msgflag = false;
end

cellout = {};
for k = 1:numel(textin)
  tline   = convertline(textin{k}, msgflag);
  if k==1
    cellout = cell(numel(textin), numel(tline));
  end
  cellout(k,:) = tline;
end


function D = addparts(D, mode)
% This function looks at the parts of the object and adds them inside the
% object struct. This useful when perfoming queries.
%
% D = addparts(D)
%
% The objects will have this new fields:
% D(i).annotation.object(j).parts.object(n).name
% D(i).annotation.object(j).parts.object(n).polygon
% D(i).annotation.object(j).parts.object(n).crop
% D(i).annotation.object(j).parts.object(n).occluded
%
% This function also allows inserting the object as a part of itself. This
% might be useful in some cases...
%
% D = addparts(D, 'addobjectasparts')

if nargin<2
    mode = '';
end

for i = 1:length(D)
    D(i).annotation = dealparts(D(i).annotation);

    if isfield(D(i).annotation, 'object')
        for j = 1:length(D(i).annotation.object)
            Nparts=0;
            % check that the field object is not inside already
            if ~isfield(D(i).annotation.object(j), 'parts') || ~isfield(D(i).annotation.object(j).parts, 'object')
                % chech that there are parts
                if isfield(D(i).annotation.object(j), 'parts') && isfield(D(i).annotation.object(j).parts, 'hasparts')
                    parts = D(i).annotation.object(j).parts.hasparts;
                    Nparts = length(parts);

                    % insert parts
                    for n = 1:Nparts
                        D(i).annotation.object(j).parts.object(n) = D(i).annotation.object(parts(n));
                    end
                end

                % if option 'addobjectasparts' then add object as part
                if strcmp(mode, 'addobjectasparts')
                    D(i).annotation.object(j).parts.object(Nparts+1).name = D(i).annotation.object(j).name;
                    D(i).annotation.object(j).parts.object(Nparts+1).occluded = D(i).annotation.object(j).occluded;
                    D(i).annotation.object(j).parts.object(Nparts+1).polygon = D(i).annotation.object(j).polygon;
                    D(i).annotation.object(j).parts.object(Nparts+1).crop = D(i).annotation.object(j).crop;
                end
            end
        end
    end
end

function annotation = dealparts(annotation)

if isfield(annotation, 'object') && isfield(annotation.object(1), 'parts')
    Nobjects = length(annotation.object);

    ids = [annotation.object.id];

    for n = 1:Nobjects
        parts = annotation.object(n).parts;
        if isfield(parts, 'ispartof')
            if isnumeric(annotation.object(n).parts.ispartof)
                [foo, ispartof] = ismember(annotation.object(n).parts.ispartof, ids);
            else
                [foo, ispartof] = ismember(str2num(annotation.object(n).parts.ispartof), ids);
            end
            annotation.object(n).parts.ispartof = ispartof;
        end

        if isfield(parts, 'hasparts')
            if isnumeric(annotation.object(n).parts.hasparts)
                [foo, hasparts] = ismember(annotation.object(n).parts.hasparts, ids);
            else
                [foo, hasparts] = ismember(str2num(annotation.object(n).parts.hasparts), ids);
            end
            hasparts = setdiff(hasparts, 0);
            annotation.object(n).parts.hasparts = hasparts;
        end
    end

end


function y = htmlcolors(x)

% HTMLCOLORS looks up the RGB value for a named color (string), or the name for a given RGB value
%
% Use as
%   rgb = htmlcolors(name)
% or
%   name = htmlcolors(rgb)
% or
%   list = htmlcolors
%
% See https://www.rapidtables.com/web/color/html-color-codes.html
% and https://www.color-hex.com/color-palettes/
%
% See also FT_COLORMAP, COLORMAP, COLORMAPEDITOR, BREWERMAP, MATPLOTLIB, CMOCEAN

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

mapping = {
  'lightsalmon',           [255,160,122]
  'salmon',                [250,128,114]
  'darksalmon',            [233,150,122]
  'lightcoral',            [240,128,128]
  'indianred',             [205,92,92]
  'crimson',               [220,20,60]
  'firebrick',             [178,34,34]
  'red',                   [255,0,0]
  'darkred',               [139,0,0]
  'coral',                 [255,127,80]
  'tomato',                [255,99,71]
  'orangered',             [255,69,0]
  'gold',                  [255,215,0]
  'orange',                [255,165,0]
  'darkorange',            [255,140,0]
  'lightyellow',           [255,255,224]
  'lemonchiffon',          [255,250,205]
  'lightgoldenrodyellow',  [250,250,210]
  'papayawhip',            [255,239,213]
  'moccasin',              [255,228,181]
  'peachpuff',             [255,218,185]
  'palegoldenrod',         [238,232,170]
  'khaki',                 [240,230,140]
  'darkkhaki',             [189,183,107]
  'yellow',                [255,255,0]
  'lawngreen',             [124,252,0]
  'chartreuse',            [127,255,0]
  'limegreen',             [50,205,50]
  'lime',                  [0,255,0]
  'forestgreen',           [34,139,34]
  'green',                 [0,128,0]
  'darkgreen',             [0,100,0]
  'greenyellow',           [173,255,47]
  'yellowgreen',           [154,205,50]
  'springgreen',           [0,255,127]
  'mediumspringgreen',     [0,250,154]
  'lightgreen',            [144,238,144]
  'palegreen',             [152,251,152]
  'darkseagreen',          [143,188,143]
  'mediumseagreen',        [60,179,113]
  'seagreen',              [46,139,87]
  'olive',                 [128,128,0]
  'darkolivegreen',        [85,107,47]
  'olivedrab',             [107,142,35]
  'lightcyan',             [224,255,255]
  'cyan',                  [0,255,255]
  'aqua',                  [0,255,255]
  'aquamarine',            [127,255,212]
  'mediumaquamarine',      [102,205,170]
  'paleturquoise',         [175,238,238]
  'turquoise',             [64,224,208]
  'mediumturquoise',       [72,209,204]
  'darkturquoise',         [0,206,209]
  'lightseagreen',         [32,178,170]
  'cadetblue',             [95,158,160]
  'darkcyan',              [0,139,139]
  'teal',                  [0,128,128]
  'powderblue',            [176,224,230]
  'lightblue',             [173,216,230]
  'lightskyblue',          [135,206,250]
  'skyblue',               [135,206,235]
  'deepskyblue',           [0,191,255]
  'lightsteelblue',        [176,196,222]
  'dodgerblue',            [30,144,255]
  'cornflowerblue',        [100,149,237]
  'steelblue',             [70,130,180]
  'royalblue',             [65,105,225]
  'blue',                  [0,0,255]
  'mediumblue',            [0,0,205]
  'darkblue',              [0,0,139]
  'navy',                  [0,0,128]
  'midnightblue',          [25,25,112]
  'mediumslateblue',       [123,104,238]
  'slateblue',             [106,90,205]
  'darkslateblue',         [72,61,139]
  'lavender',              [230,230,250]
  'thistle',               [216,191,216]
  'plum',                  [221,160,221]
  'violet',                [238,130,238]
  'orchid',                [218,112,214]
  'fuchsia',               [255,0,255]
  'magenta',               [255,0,255]
  'mediumorchid',          [186,85,211]
  'mediumpurple',          [147,112,219]
  'blueviolet',            [138,43,226]
  'darkviolet',            [148,0,211]
  'darkorchid',            [153,50,204]
  'darkmagenta',           [139,0,139]
  'purple',                [128,0,128]
  'indigo',                [75,0,130]
  'pink',                  [255,192,203]
  'lightpink',             [255,182,193]
  'hotpink',               [255,105,180]
  'deeppink',              [255,20,147]
  'palevioletred',         [219,112,147]
  'mediumvioletred',       [199,21,133]
  'white',                 [255,255,255]
  'snow',                  [255,250,250]
  'honeydew',              [240,255,240]
  'mintcream',             [245,255,250]
  'azure',                 [240,255,255]
  'aliceblue',             [240,248,255]
  'ghostwhite',            [248,248,255]
  'whitesmoke',            [245,245,245]
  'seashell',              [255,245,238]
  'beige',                 [245,245,220]
  'oldlace',               [253,245,230]
  'floralwhite',           [255,250,240]
  'ivory',                 [255,255,240]
  'antiquewhite',          [250,235,215]
  'linen',                 [250,240,230]
  'lavenderblush',         [255,240,245]
  'lightgray',             [211,211,211]
  'silver',                [192,192,192]
  'darkgray',              [169,169,169]
  'gray',                  [128,128,128]
  'dimgray',               [105,105,105]
  'lightslategray',        [119,136,153]
  'slategray',             [112,128,144]
  'darkslategray',         [47,79,79]
  'black',                 [0,0,0]
  'cornsilk',              [255,248,220]
  'blanchedalmond',        [255,235,205]
  'bisque',                [255,228,196]
  'navajowhite',           [255,222,173]
  'wheat',                 [245,222,179]
  'burlywood',             [222,184,135]
  'tan',                   [210,180,140]
  'rosybrown',             [188,143,143]
  'sandybrown',            [244,164,96]
  'goldenrod',             [218,165,32]
  'peru',                  [205,133,63]
  'chocolate',             [210,105,30]
  'saddlebrown',           [139,69,19]
  'sienna',                [160,82,45]
  'brown',                 [165,42,42]
  'maroon',                [128,0,0]
  };

if nargin==0
  % return the list with names
  y = mapping(:,1);
elseif ischar(x)
  % look up the corresponding RGB values
  sel = strcmp(mapping(:,1), x);
  y = mapping{sel, 2};
  y = y/255;
elseif isnumeric(x)
  x = x*255;
  % look up the corresponding name
  rgb = vertcat(mapping{:,2});
  rgb(:,1) = rgb(:,1) - x(1);
  rgb(:,2) = rgb(:,2) - x(2);
  rgb(:,3) = rgb(:,3) - x(3);
  [dum, sel] = min(sum(rgb.^2, 2));
  y = mapping{sel,1};
end


function idmap = read_txt(infilename)
% Reads ids from a text file and constructs an Id_Map object.
% Inputs:
%   infilename: The name for the text file to read.
% Outputs:
%   idmap: An Id_Map object created from the information in the text
%     file.

assert(nargin==1)
assert(isa(infilename,'char'))

fid = fopen(infilename);
lines = textscan(fid,'%s%s');
fclose(fid);

idmap = Id_Map();
idmap.leftids = lines{1};
idmap.rightids = lines{2};

assert(idmap.validate())

end


function warning_flexible(varargin)
% Function allowing to have better control over the warnings
% that might not be necessary at some point
% _______________________________________________________________________
% Copyright (C) 2012 Wellcome Trust Centre for Neuroimaging

% Vladimir Litvak
% $Id: warning_flexible.m 5467 2013-05-05 20:03:50Z vladimir $

warning off backtrace
warning(varargin{:});
warning on backtrace


classdef ADXL345busDataBaseClass < TimeSeriesDataBaseClass

    %% Abstract public 'read-only' properties
    properties (Abstract, SetAccess = private)
        FileNameAppendage;
    end

    %% Public 'read-only' properties
    properties (SetAccess = private)
        ADXL345A = struct('X', [], 'Y', [], 'Z', []);
        ADXL345B = struct('X', [], 'Y', [], 'Z', []);
        ADXL345C = struct('X', [], 'Y', [], 'Z', []);
        ADXL345D = struct('X', [], 'Y', [], 'Z', []);
    end

    %% Abstract protected properties
    properties (Access = protected)
        AccelerometerUnits;
    end

    %% Protected methods
    methods (Access = protected)
        function obj = Import(obj, fileNamePrefix)
            data = obj.ImportCSVnumeric(fileNamePrefix);
            obj.ADXL345A.X = data(:,2);
            obj.ADXL345A.Y = data(:,3);
            obj.ADXL345A.Z = data(:,4);
            obj.ADXL345B.X = data(:,5);
            obj.ADXL345B.Y = data(:,6);
            obj.ADXL345B.Z = data(:,7);
            obj.ADXL345C.X = data(:,8);
            obj.ADXL345C.Y = data(:,9);
            obj.ADXL345C.Z = data(:,10);
            obj.ADXL345D.X = data(:,11);
            obj.ADXL345D.Y = data(:,12);
            obj.ADXL345D.Z = data(:,13);
            obj.SampleRate = obj.SampleRate;    % call set method to create time vector
        end
    end

    %% Public methods
    methods (Access = public)
        function fig = Plot(obj)
            if(obj.NumPackets == 0)
                error('No data to plot.');
            else
                if(isempty(obj.Time))
                    time = 1:obj.NumPackets;
                else
                    time = obj.Time;
                end
                fig = figure('Name', obj.CreateFigName());
                ax(1) = subplot(4,1,1);
                hold on;
                plot(time, obj.ADXL345A.X, 'r');
                plot(time, obj.ADXL345A.Y, 'g');
                plot(time, obj.ADXL345A.Z, 'b');
                legend('X', 'Y', 'Z');
                xlabel(obj.TimeAxis);
                ylabel(strcat('Acceleration (', obj.AccelerometerUnits, ')'));
                title('ADXL345 A');
                hold off;
                ax(2) = subplot(4,1,2);
                hold on;
                plot(time, obj.ADXL345B.X, 'r');
                plot(time, obj.ADXL345B.Y, 'g');
                plot(time, obj.ADXL345B.Z, 'b');
                legend('X', 'Y', 'Z');
                xlabel(obj.TimeAxis);
                ylabel(strcat('Acceleration (', obj.AccelerometerUnits, ')'));
                title('ADXL345 B');
                hold off;
                ax(3) = subplot(4,1,3);
                hold on;
                plot(time, obj.ADXL345C.X, 'r');
                plot(time, obj.ADXL345C.Y, 'g');
                plot(time, obj.ADXL345C.Z, 'b');
                legend('X', 'Y', 'Z');
                xlabel(obj.TimeAxis);
                ylabel(strcat('Acceleration (', obj.AccelerometerUnits, ')'));
                title('ADXL345 C');
                hold off;
                ax(4) = subplot(4,1,4);
                hold on;
                plot(time, obj.ADXL345D.X, 'r');
                plot(time, obj.ADXL345D.Y, 'g');
                plot(time, obj.ADXL345D.Z, 'b');
                legend('X', 'Y', 'Z');
                xlabel(obj.TimeAxis);
                ylabel(strcat('Acceleration (', obj.AccelerometerUnits, ')'));
                title('ADXL345 D');
                hold off;
                linkaxes(ax,'x');
            end
        end
    end
end


function ok = StartSIFT(interactive,nosplash)
% This function initializes the Source Information Flow Toolbox (SIFT)
% Author: Tim Mullen, 2011, SCCN/INC/UCSD

ok = false;

if nargin<1
    interactive = false;
end
if nargin<2
    nosplash = false;
end

fprintf('Initializing SIFT...\n');

% temporary hack to remove measure projection toolbox from path
% (MPT interferes with SIFT)
% if exist('measure_projection')
%     hlp_removeMeasureProjection;
% end

if ispc, SLASH = '\'; else SLASH = '/'; end
if ~isdeployed
    siftroot = fileparts(which('StartSIFT'));
else
    try
        siftroot = utl_whichfile('StartSIFT');
    catch
        siftroot = [ctfroot filesep 'dependency' filesep 'SIFT-private'];
        if ~exist(siftroot,'dir'),siftroot = pwd;end
    end
end
disp(siftroot)
ArfitURL    = 'http://www.gps.caltech.edu/~tapio/arfit/arfit.zip';
ARfitTargetPath  = [siftroot SLASH 'external' SLASH 'arfit'];

% add subfolders to path (if not already present)
if ~exist('vis_TimeFreqGrid.m','file') && ~isdeployed
    disp('SIFT: Adding subfolders.')
    addpath(genpath(siftroot));
end

% call up the splash screen
if interactive && ~nosplash
    gui_splashscreen;
end

% optionally download arfit (if not already present)
if ~exist(ARfitTargetPath,'file') && interactive
    res = input('SIFT: Would you like to download and install the ARFIT toolbox as a SIFT plugin (recommended)? ''y''/''n'': ','s');
    if strcmpi(res,'y')

        fprintf('SIFT: Downloading and installing ARFIT from %s ...\n',ArfitURL);

        try
            outdir = unzip(ArfitURL,ARfitTargetPath);
        catch e
            switch e.identifier
                case 'MATLAB:unzip:urlwriteError'
                    fprintf('%s Aborting download.\n',e.message);
                case 'MATLAB:unzip:invalidZipFile'
                    fprintf('Unable to unpack file %s Aborting installation.\n', e.message);
                    res=rmdir(ARfitTargetPath,'s'); % clean up
            end

            return;
        end
        if ~isdeployed
            addpath(genpath(ARfitTargetPath));
            fprintf('SIFT: ARFIT installed to %s%c\n',fileparts(outdir{1}),SLASH);
        end
    end
end

ok = true;

fprintf('Start SIFTing!\n');


function res = sensors(this, type, newsens)
% Sets and gets sensor fields for EEG and MEG
% returns empty matrix if no sensors are defined.
% FORMAT res = sensors(this, type, newsens)
%   type - 'EEG' or 'MEG'
% _______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging

% Vladimir Litvak
% $Id: sensors.m 4790 2012-07-17 16:00:20Z vladimir $

if nargin<2
    error('Sensor type (EEG or MEG) must be specified');
end

switch lower(type)
    case 'eeg'
        if nargin < 3
            if isfield(this.sensors, 'eeg')
                res = this.sensors.eeg;
            else
                res = [];
            end
        else
            this.sensors(1).eeg = ft_datatype_sens(newsens);
            res = this;
        end
    case 'meg'
        if nargin < 3
            if isfield(this.sensors, 'meg')
                res = this.sensors.meg;
            else
                res = [];
            end
        else
            this.sensors(1).meg = ft_datatype_sens(newsens);
            res = this;
        end
    otherwise
        error('Unsupported sensor type');
end


function z_callBack_virtualTeachPendant_J2_minus()
%% Soft realtime joints control Joint X button callback
% Copyright: Mohammad SAFEEA, 27th-July-2018
global virtual_smartPad_w_joints_command;
disp('Moving J2 in negative direction');
virtual_smartPad_w_joints_command(2)=-1;
end


function [bioQualifiers,standardQualifiers] = getBioQualifiers()
% Get a list of possible bioqualifiers
%
% USAGE:
%    annotationQualifiers = getBioQualifiers()
%
% OUTPUT:
%    bioQualifiers:    A cell array of bioqualifier strings in descending order.
%    standardQualifiers:        A n x 2 cell array with the first column representing the standard identifiers and the second column representing the alternative name.

bioQualifiers = {'version','taxon','relation',...
                 'propertyBearer','property',...
                 'parthood','part','origin','occursIn',...
                 'isVersionOf','isRelatedTo','isPropertyOf',...
                 'isPartOf','isInstanceOf','isHomologTo','isEncodedBy',...
                 'isDescribedBy','isDerivedFrom','is','instance','identity',...
                 'hypernym','homolog','hasVersion',...
                 'hasTaxon','hasProperty','hasPart','hasInstance',...
                 'encodes','encoder','encodement',...
                 'description','container','class'};

standardQualifiers = {'is', 'identity';...
                      'isDerivedFrom', 'origin';...
                      'isDescribedBy', 'description';...
                      'isInstanceOf', 'class';...
                      'hasInstance', 'instance';...
                      'encodes', 'encodement';...
                      'hasPart', 'part';...
                      'hasProperty', 'property';...
                      'hasVersion', 'version';...
                      'isEncodedBy', 'encoder';...
                      'isHomologTo', 'homolog';...
                      'isPartOf', 'parthood';...
                      'isPropertyOf', 'propertyBearer';...
                      'isVersionOf', 'hypernym';...
                      'occursIn', 'container';...
                      'hasTaxon', 'taxon'};