function figure2dot(filename, varargin)
%FIGURE2DOT    Save figure in Graphviz (.dot) file.
%  FIGURE2DOT(filename) saves the current figure as dot-file.
%
%  FIGURE2DOT(filename, 'object', HGOBJECT) constructs the graph representation
%  of the specified object (default: gcf)
%
%  You can visualize the constructed DOT file using:
%    - [GraphViz](http://www.graphviz.org) on your computer
%    - [WebGraphViz](http://www.webgraphviz.com) online
%    - [Gravizo](http://www.gravizo.com) for your markdown files
%    - and a lot of other software such as OmniGraffle
%

%   Copyright (c) 2008--2014, Nico Schlömer <nico.schloemer@gmail.com>
%   All rights reserved.
%
%   Redistribution and use in source and binary forms, with or without
%   modification, are permitted provided that the following conditions are
%   met:
%
%      * Redistributions of source code must retain the above copyright
%        notice, this list of conditions and the following disclaimer.
%      * Redistributions in binary form must reproduce the above copyright
%        notice, this list of conditions and the following disclaimer in
%        the documentation and/or other materials provided with the distribution
%
%   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
%   AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
%   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
%   ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
%   LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
%   CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
%   SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
%   INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
%   CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
%   ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
%   POSSIBILITY OF SUCH DAMAGE.
%
% =========================================================================

    ipp = m2tInputParser();
    ipp = ipp.addRequired(ipp, 'filename', @ischar);
    ipp = ipp.addParamValue(ipp, 'object', gcf, @ishghandle);
    ipp = ipp.parse(ipp, filename, varargin{:});
    args = ipp.Results;

    filehandle = fopen(args.filename, 'w');
    finally_fclose_filehandle = onCleanup(@() fclose(filehandle));

    % start printing
    fprintf(filehandle, 'digraph simple_hierarchy {\n\n');
    fprintf(filehandle, 'node[shape=box];\n\n');

    % define the root node
    node_number = 0;
    p = get(args.object, 'Parent');
    % define root element
    type = get(p, 'Type');
    fprintf(filehandle, 'N%d [label="%s"]\n\n', node_number, type);

    % start recursion
    plot_children(filehandle, p, node_number);

    % finish off
    fprintf(filehandle, '}');

    % ----------------------------------------------------------------------------
    function plot_children(fh, h, parent_node)

        children = allchild(h);

        for h = children(:)'
            if shouldSkip(h), continue, end;
            node_number = node_number + 1;

            label = {};
            label = addHGProperty(label, h, 'Type', '');
            try
                hClass = class(handle(h));
                label = addProperty(label, 'Class', hClass);
            catch
                % don't do anything
            end
            label = addProperty(label, 'Handle', sprintf('%g', double(h)));
            label = addHGProperty(label, h, 'Title', '');
            label = addHGProperty(label, h, 'Axes', []);
            label = addHGProperty(label, h, 'String', '');
            label = addHGProperty(label, h, 'Tag', '');
            label = addHGProperty(label, h, 'DisplayName', '');
            label = addHGProperty(label, h, 'Visible', 'on');
            label = addHGProperty(label, h, 'HandleVisibility', 'on');

            % print node
            fprintf(fh, 'N%d [label="%s"]\n', ...
                    node_number, m2tstrjoin(label, '\n'));

            % connect to the child
            fprintf(fh, 'N%d -> N%d;\n\n', parent_node, node_number);

            % recurse
            plot_children(fh, h, node_number);
        end
    end
end
% ==============================================================================
function bool = shouldSkip(h)
    %  returns TRUE for objects that can be skipped
    objType = get(h, 'Type');
    bool = ismember(lower(objType), guitypes());
end
% ==============================================================================
function label = addHGProperty(label, h, propName, default)
    % get a HG property and assign it to a GraphViz node label
    if ~exist('default','var') || isempty(default)
        shouldOmit = @isempty;
    elseif isa(default, 'function_handle')
        shouldOmit = default;
    else
        shouldOmit = @(v) isequal(v,default);
    end

    if isprop(h, propName)
        propValue = get(h, propName);
        if numel(propValue) == 1 && ishghandle(propValue) && isprop(propValue, 'String')
            % dereference Titles, labels, ...
            propValue = get(propValue, 'String');
        elseif ishghandle(propValue)
            % dereference other HG objects to their raw handle value (double)
            propValue = double(propValue);
        elseif iscell(propValue)
            propValue = ['{' m2tstrjoin(propValue,',') '}'];
        end

        if ~shouldOmit(propValue)
            label = addProperty(label, propName, propValue);
        end
    end
end
function label = addProperty(label, propName, propValue)
    % add a property to a GraphViz node label
    if isnumeric(propValue)
        propValue = num2str(propValue);
    elseif iscell(propValue)
        propValue = m2tstrjoin(propValue,sprintf('\n'));
    end
    label = [label, sprintf('%s: %s', propName, propValue)];
end
% ==============================================================================


% eeg_helpmenu() - Call the help file for EEGLAB menus
%
% Usage:
%   To call a menu of eeglab functions
%       >> eeg_helpmenu;
%   To open a help window with the specific called file.
%   Equivalent to calling >> pophelp( 'filename' );
%        >> eeg_helpmenu( 'filename' );
%
% Author: Arnaud Delorme CNL / Salk Institute 2001
%
% See also: eeglab()

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

function eeg_helpmenu( filename );

allmenus = { ...
'File' ''      ...
'   Import data' ''  ...
'      From ASCII/float file or Matlab array' 'pop_importdata'     ... %       Import Matlab data array
'      From continuous or seg. EGI .RAW file' 'pop_readegi'        ... %       Read continuous or seg. .EGI or .RAW datafile
'      From Multiple seg. EGI .RAW files'     'pop_readsegegi'     ... %       Read multiple seg. .EGI or .RAW datafile
'      From BCI2000 ASCII file'               'pop_loadbci'        ... %       Read .BCI datafile (Snapmaster)
'      From Snapmaster .SMA file'             'pop_snapread'       ... %       Read .SMA datafile (Snapmaster)
'      From Neuroscan .CNT file'              'pop_loadcnt'        ... %       Read .CNT datafile (Neuroscan continuous)
'      From Neuroscan .EEG file'              'pop_loadeeg'        ... %       Read .EEG datafile (Neuroscan epochs)
'      From Biosemi .BDF file'                'pop_biosig'         ... %       Read .BDF datafile
'      From .EDF file'                        'pop_biosig'         ... %       Read .EDF datafile
'      From ANT EEProbe .CNT file'            'pop_loadeep'        ... %       Read .CNT datafile (ANT EEProbe)
'      From ANT EEProbe .AVR file'            'pop_loadeep_avg'    ... %       Read .AVR datafile (ANT EEProbe)
'      From .BDF file (backup function)'      'pop_readbdf'        ... %       Read .BDF datafile
'      From Brain Vis. Rec. .VHDR file'       'pop_loadbv'         ... %       Read .VHDR datafile (Brain Vision Rec.)
'      From Brain Vis. Anal. Matlab file'     'pop_loadbva'        ... %       Read Matlab datafile (Brain Vision Analysis)
'      From CTF Folder (MEG)'                 'ctf_folder'         ... %       Import MEG datafiles from chosen CTF folder.
'      From ERPSS .RAW or .RDF file'          'pop_read_erpss'     ...
'      From INStep .ASC file'                 'pop_loadascinstep'  ... %       Read .ASC datafile (INStep)
'      From 4D .M4D pdf file'                 'pop_read4d'         ... %       Read .M4D datafile (4D pdf)
'      From other formats using FILEIO'       'pop_fileio'         ... %       Import data using FILEIO
'      From other formats using BIOSIG'       'pop_biosig'         ...
'   Import epoch info' ''      ...
'      From Matlab array or ASCII file'       'pop_importepoch'    ... %       Import Matlab array or ASCII file
'      From Neuroscan .DAT file'              'pop_loaddat'        ... %       Import .DAT info file (Neuroscan epochs)
'   Import event info' ''      ...
'      From  Matlab array or ASCII file'      'pop_importevent'    ... %       Import Matlab array or ASCII file
'      From data channel'                     'pop_chanevent'      ... %       Import events from channels
'      From Presentation .LOG file'           'pop_importpres'     ... %       Import .LOG event file (Presentation)
'      From Neuroscan .EV2 file'              'pop_importev2'      ... %       Import .EV2 even file (Neuroscan)
'   Export ' '' ...
'      Data and ICA to text file'             'pop_export'         ... %       Export Data and ICA to text file
'      Weight matrix to text file'            'pop_expica'         ... %       Export weight matrix to text file
'      Inverse weight matrix to text file'    'pop_expica'         ... %       Export inverse weight matrix to text file
'      Data to EDF/BDF/GDF file'              'pop_writeeeg'       ... %       Export Data to EDF/BDF/GDF data formats
'      Write Brain Vis. exchange format file' '            '       ...
'   Load existing dataset'                    'pop_loadset'        ... %       Load dataset
'   Save current dataset'                     'pop_saveset'        ... %       Save dataset
'   Save datasets'                            'pop_saveset'        ... %       Save dataset
'   Clear dataset(s)'                         'pop_delset'         ... %       Clear dataset(s)
'   Create Study ' '' ...
'      Using all loaded datasets'             'pop_study'          ... %       Create study using currently loaded datasets
'      Browse for datasets'                   'pop_study'          ... %       Find datasets to use in Study
'   Load existing study'                      'pop_loadstudy'      ... %       Load study
'   Save current study'                       'pop_savestudy'      ... %       Save study
'   Save current study as'                    'pop_savestudy'      ... %       Save current study as
'   Clear study'                              'pop_delset'         ... %       Clear study
'   Maximize memory'                          'pop_editoptions'    ... %       Maximize memory
'   History Scripts' '' ...
'      Save dataset history script'           'pop_saveh'          ... %       Save current dataset history
'      Save session history script'           'pop_saveh'          ... %       Save current session history
'      Run Script'                            'pop_runscript'      ... %       Run History script
'   Quit' ''      ...
'Edit' ''      ...
'   Dataset info'                             'pop_editset'        ... %       Edit dataset info
'   Event fields'                             'pop_editeventfield' ... %       Edit event fields
'   Event values'                             'pop_editeventvals'  ... %       Edit event values
'   About this dataset'                       'pop_comments'       ... %       About this dataset
'   Channel locations'                        'pop_chanedit'       ... %       Edit channels
'   Select data'                              'pop_select'         ... %       Select data
'   Select data using events'                 'pop_rmdat'          ... %       Select data using events
'   Select epochs or events'                  'pop_selectevent'    ... %       Select epochs or events
'   Copy current dataset'                     'pop_copyset'        ... %       Copy current dataset
'   Append datasets'                          'pop_mergeset'       ... %       Append another dataset
'   Delete dataset(s)'                        'pop_delset'         ... %       Delete dataset(s)
'Tools' ''      ...
'   Change sampling rate'                     'pop_resample'       ... %       Change sampling rate
'   Filter the data' '' ...
'      Basic FIR filter'                      'pop_eegfilt'        ... %       Filter the data
'      Short IIR filter'                      'pop_iirfilt'        ... %       Short IIR filter
'      ERPLAB Butterworth Digital Filter'     'pop_ERPLAB_butter1' ... %       ERPLAB Butterworth filter
'      ERPLAB Polynomial Detrending'          'pop_ERPLAB_polydetrend' ... % Polynomial detrending
'   Re-referencing'                           'pop_reref'          ... %       Average reference
'   Interpolate electrodes'                   'pop_interp'         ...
'   Reject continuous data by eye'            'pop_eegplot'        ... %       Reject continuous data
'   Extract epochs'                           'pop_epoch'          ... %       Extract epochs
'   Remove baseline'                          'pop_rmbase'         ... %       Remove baseline
'   Run ICA'                                  'pop_runica'         ... %       Run ICA
'   Remove components'                        'pop_subcomp'        ... %       Remove components
'   Automatic channel rejection'              'pop_rejchan'        ... %       Reject channels
'   Automatic epoch rejection'                'pop_autorej'        ... %       Reject epochs
'   Reject data epochs' ''  ...
'      Reject data (all methods)'             'pop_rejmenu'        ... %       Reject data (all methods)
'      Reject by inspection'                  'pop_eegplot'        ... %       Reject by inspection
'      Reject extreme values'                 'pop_eegthresh'      ... %       Reject extreme values
'      Reject by linear trend/variance'       'pop_rejtrend'       ... %       Reject by linear trend/variance
'      Reject by probability'                 'pop_jointprob'      ... %       Reject by probability
'      Reject by kurtosis'                    'pop_rejkurt'        ... %       Reject by kurtosis
'      Reject by spectra'                     'pop_rejspec'        ... %       Reject by spectra
'      Reject marked epochs'                  'pop_rejepoch'       ... %       Reject labeled epochs
'   Reject using ICA' '' ...
'      Reject components by map'              'pop_selectcomps'    ... %       Reject components by map
'      Reject data (all methods)'             'pop_rejmenu'        ... %       Reject data (all methods)
'      Reject by inspection'                  'pop_eegplot'        ... %       Reject by inspection
'      Reject extreme values'                 'pop_eegthresh'      ... %       Reject extreme values
'      Reject by linear trend/variance'       'pop_rejtrend'       ... %       Reject by linear trend/variance
'      Reject by probability'                 'pop_jointprob'      ... %       Reject by probability
'      Reject by kurtosis'                    'pop_rejkurt'        ... %       Reject by kurtosis
'      Reject by spectra'                     'pop_rejspec'        ... %       Reject by spectra
'      Reject marked epochs'                  'pop_rejepoch'       ... %       Reject labeled epochs
'   Run AMICA'  ''  ...
'      Run AMICA in parallel'                 'pop_runica'         ... %       Run AMICA in parallel (plugin)
'      Run AMICA locally'                     'pop_runica'         ... %       Run AMICA locally (plugin)
'      Load AMICA component'                  'pop_loadmodout'     ... %       Load AMICA component (plugin)
'   Run CICA'                                 ''                   ...
'   Locate dipoles using DIPFIT 2.x' '' ...
'      Head model and settings'               'pop_dipfit_settings'... %       DIPFIT Plugin settings
'      Coarse fit (grid scan)'                ''                   ... %
'      Fine fit (iterative)'                  'pop_dipfit_nonlinear'... %      Fine fit (iterative)
'      Autofit (coarse fit, fine fit & plot)' ''                   ...
'      Plot component dipoles'                ''                   ...
'   Peak detection using EEG toolbox'         ''                   ...
'   FMRIB Tools' '' ...
'      FASTR: Remove FMRI gradient artifacts' 'pop_fmrib_fastr'    ... %       Remove FMRI gradient artifacts
'      Detect QRS events'                     'pop_fmrib_qrsdetect'... %       Detect QRS events
'      Remove pulse artifacts'                'pop_fmrib_pas'      ... %       Remove pulse artifacts
'   BEM4 SCCN beta'  '' ...
'      Forward Problem Solution'              'pop_forward problem_solution' ... % Not currently working
'   Locate dipoles using LORETA' '' ...
'      Export components to LORETA'           ''                   ...
'      Import dipoles from LORETA'            ''                   ...
'      Plot dipoles on LORETA head'           ''                   ...
'Plot' ''      ...
'   Channel locations' '' ...
'      By name'                               'topoplot'           ... %       Electrodes
'      By number'                             'topoplot'           ... %       Numbers
'   Channel data (scroll)'                    'pop_eegplot'        ... %       Scroll EEG data
'   Channel spectra and maps'                 'pop_spectopo'       ... %       Channel spectra and maps
'   Channel properties'                       'pop_prop'           ... %       Component properties
'   Channel ERP image'                        'pop_erpimage'       ... %       Channel ERP image
'   Channel ERPs' ''      ...
'      With scalp maps'                       'pop_timtopo'        ... %       ERP and scalp maps
'      In scalp array'                        'pop_plottopo'       ... %       ERP in scalp array
'      In rect. array'                        'pop_plotdata'       ... %       ERP in rect. array
'   ERP maps' ''      ...
'      As 2-D scalp maps'                     'pop_topoplot'       ... %       ERP scalp maps
'      As 3-D head plots'                     'pop_headplot'       ... %       ERP head plots
'   Sum/Compare ERPs'                         'pop_comperp'        ... %       Compare ERPs
'   Component activations (scroll)'           'pop_eegplot'        ... %       Scroll component activations
'   Component spectra and maps'               'pop_spectopo'       ... %       Channel spectra and maps with components
'   Component maps' ''      ...
'      As 2-D scalp maps'                     'pop_topoplot'       ... %       Component scalp maps
'      As 3-D head plots'                     'pop_headplot'       ... %       Component head plots
'   Component properties'                     'pop_prop'           ... %       Component properties
'   Component ERP image'                      'pop_erpimage'       ... %       Component ERP image
'   Component ERPs' ''      ...
'      With component maps'                   'pop_envtopo'        ... %       Largest ERP components
'      With comp. maps (compare)'             'pop_envtopo'        ... %       Largest ERP components
'      In rectangular array'                  'pop_plotdata'       ... %       Comp. ERP time courses
'   Sum/Compare comp. ERPs'                   'pop_comperp'        ... %       Compare ERPs
'   Data statistics' ''      ...
'      Channel statistics'                    'pop_signalstat'     ...
'      Component statistics'                  'pop_signalstat'     ...
'      Event statistics'                      'pop_eventstat'      ...
'   Time-frequency transforms' ''  ...
'      Channel time-frequency'                'pop_timef'          ... %       Channel time-frequency
'      Channel cross-coherence'               'pop_crossf'         ... %       Channel cross-coherence
'      Component time-frequency'              'pop_timef'          ... %       Component time-frequency EEGLAB'));
'      Component cross-coherence'             'pop_crossf'         ... %       Component cross-coherence
'   Cluster dataset ICs'                      'pop_miclust'        ... %       Cluster ICs
'Study' ''     ...
'   Edit study info'                          'pop_study'          ...
'   Precompute channel measures'              'pop_precomp'        ...
'   Plot channel measures'                    'pop_chanplot'       ...
'   Precompute component measures'            'pop_precomp'        ...
'   Build preclustering array'                'pop_preclust'       ...
'   Cluster components'                       'pop_clust'          ...
'   Edit/plot clusters'                       'pop_clustedit'      ...
'Datasets' ''   ...
'   Current/Active Datasets (listed as selectable items)' ''       ...
'   Select multiple datasets'                  ''                  ...
'   Select the study set'                      ''                  ... %      Only selectable if study is loaded
'Help' ''    ...
'   About EEGLAB'                              'eeglab'            ...
'   About EEGLAB Help'                         'eeg_helphelp'      ...
'   EEGLAB menus'                              'eeg_helpmenu'      ...
'   EEGLAB functions'                          ''                  ...
'       Toolbox functions'                     ''                  ...
'       Signal processing functions'           'eeg_helpsigproc'   ...
'       Interactive pop_functions'             'eeg_helppop'       ...
'   EEGLAB advanced'                           ''                  ...
'       Dataset structure'                     'eeg_checkset'      ...
'       Admin functions'                       'eeg_helpadmin'     ...
'   Web tutorial'                              ''                  ...
'   Email EEGLAB'                              ''                  ...

};

text  = allmenus( 1:2:length(allmenus));
command = allmenus( 2:2:length(allmenus));

for index = 1:length(command)
	if ~isempty(command{index})
		command{index} = [ 'pophelp(''' command{index} ''');' ];
	end;
end;

textgui( text, command,'fontsize', 15, 'fontname', 'times', 'linesperpage', 18, 'title',strvcat( 'Interactive (pop_) functions', '(Click on blue text for help)'));
try
	icadefs; set(gcf, 'COLOR', BACKCOLOR);
	h = findobj('parent', gcf, 'style', 'slider');
	set(h, 'backgroundcolor', GUIBACKCOLOR);
catch, end;

if nargin > 0
	close(gcf);
    pophelp(filename);
	%command = allmenus( 2:2:length(allmenus));
	%for index = 1:length(text)
	%	if isempty(allmenus{index*2})
	%		tmpparam{index} = {  '' allmenus{(index-1)*2+1} };
	%	else
	%		tmpparam{index} = {  [ allmenus{index*2} '.m' ] allmenus{(index-1)*2+1} };
	%	end;
	%end;
 	%makehtml( tmpparam, '/home/www/eeglab/allfunctions', 'outputfile', 'tempmenu.html', 'mainonly', 'on');
    %}
end;

return;

% $$$ [textmenu nblines l] = getallmenus(findobj('tag', 1) ~= 32 )
% $$$ fontsize{ index } = fontsize{ index }+1;
% $$$ fontweight{ index } ='bold';
% $$$
% $$$ fontsize(1:length( textmenu )) = { 15 }; 6) ~= 32 fontweight{ index } ='bold'; end;
% $$$ fontweight(1:length( textmenu )) = { 'normal' }; :));
% $$$ for index = 1:length( textmenu )
% $$$ if textmenu(index
% $$$ if textmenu(index
% $$$ a = deblank(textmenu(index
% $$$ if index > length( commands )
% $$$ commands = { commands{:} [] }; 1:length(a)) = a;
% $$$ end;
% $$$ if ~isempty(commands{index})
% $$$ a = [ a ' -- ' commands{index} '()'];
% $$$ textmenu(index
% $$$ commands{index} = [ ''pophelp(''' commands{index} ''');' ]; ...
% $$$ end; click on blue text below)'  ' ...
% $$$ end; :));
% $$$
% $$$ textmenu = strvcat('Functions called through the EEGLAB menu'
% $$$ (For help message
% $$$ textmenu(1:end-1 :) commands ...
% $$$ fontsize   = { 16 15 15 fontsize{:} }; fontsize fontweight' fontweight fontname' times' linesperpage' 17 );
% $$$ fontweight = { 'bold' 'normal' 'normal' fontweight{:} };
% $$$ commands   = { '' ' ' '' commands{:} };
% $$$ textgui(textmenu(1:end-1
% $$$ fontsize'
% $$$ return;


function startup()
 fprintf('Entering startup\n');
  curdir = fileparts(mfilename('fullpath'));
    if ~(isdeployed)
    fprintf('Adding paths\n');
      addpath(genpath(fullfile(curdir, 'utils')));
      addpath(genpath(fullfile(curdir, 'functions')));
      addpath(genpath(fullfile(curdir, 'bin')));
      addpath(genpath(fullfile(curdir, 'experiments')));
      addpath(genpath(fullfile(curdir, 'imdb')));
      addpath(genpath(fullfile(curdir, 'datasets/coco2014/')));
     fprintf('Starting caffe\n');
      caffe_path = fullfile(curdir, 'external', 'caffe', 'matlab');
      if exist(caffe_path, 'dir') == 0
        error('matcaffe is missing from external/caffe/matlab; See README.md');
      end
      addpath(genpath(caffe_path));
    fprintf('Done\n');
    end
    fprintf('mask_rcnn startup done\n');
end


function s7_resave_final_check_for_errors()

stp = load('annot_full_Philippe.mat'); % train+test
phill_annot = stp.videos;
clear stp;

stp = load('annot_apt.mat'); % train+test
apt_annot = stp.videos;
clear stp;

philList = {};
for i=1:length(phill_annot)
    philList{i,1} = phill_annot(i).name; % store all the cor vid in a cellarray
end

aptList = {};

for i=1:length(apt_annot)
    aptList{i,1} = apt_annot(i).name; % store all the cor vid in a cellarray
end

images_dir = '/mnt/sun-alpha/datasets/UCF101/images';
save_path = 'saved/';

load('testnames.mat')
% load('merged_annot_remianing.mat')
load('checkpoint_improved_after_remaining.mat')
load('newAnnotats.mat')
vc = 0; tdata = cell(2,1); %v=1;
while v <= length(merged_annot)

    num_imgs = merged_annot(v).num_imgs;
    videoname = merged_annot(v).name;

    if isgood(v)
        [base_tubes,cc,ca] = verifyTubes(merged_annot(v).tubes,num_imgs,v,videoname);
        vc = vc +cc;
        if ca

            index = find(strcmp(philList,videoname));
            phil_tubes = phill_annot(index).tubes;

            index = find(strcmp(aptList,videoname));
            apt_tubes = apt_annot(index).tubes;
            base_tubes = merged_annot(v).tubes;
            if v == 1855
                base_tubes.sf = 1;
                base_tubes.ef = num_imgs;
                base_tubes.boxes = repmat(base_tubes.boxes,num_imgs,1);
                base_tubes.class = base_tubes.class;
            end
            checkboxes(base_tubes,phil_tubes,apt_tubes,num_imgs,images_dir,save_path,videoname)

            fid = fopen('temp.txt','w');

            fid = fopen('temp.txt','w');

            for t = 1 : length(base_tubes)
                fprintf(fid,'b %d %d %d\n', t, base_tubes(t).sf, base_tubes(t).ef);
            end

            for t = 1 : length(phil_tubes)
                fprintf(fid,'p %d %d %d\n', t, phil_tubes(t).sf, phil_tubes(t).ef);
            end

            for t = 1 : length(apt_tubes)
                fprintf(fid,'a %d %d %d\n', t, apt_tubes(t).sf, apt_tubes(t).ef);
            end

            fclose(fid);
            fid = fopen('temp.txt','r');

            tline = fgets(fid);
            newcell = cell(1);
            count = 1;
            newcell{count} = tline;
            while ischar(tline)
                tline = fgets(fid);
                if ischar(tline)
                    count = count + 1;
                    newcell{count} = tline;
                    disp(tline)
                end
            end
            fclose(fid);
            tdata{v} = newcell;
            class = phil_tubes(1).class;
            base_tubes = extract_bounds(newcell, base_tubes, phil_tubes, apt_tubes, num_imgs,class);
            merged_annot(v).tubes = base_tubes;
            save('newAnnotats.mat','merged_annot','v');
        end

        merged_annot(v).tubes = base_tubes;

    end
    v=v+1;
end
save('newAnnotats.mat','merged_annot','v');

% fprintf('corrected %d tubes\n',vc);
% save('../testlist','testlist');
% annot = trainannot;
% save('../trainAnnot.mat','annot');
% annot = testannot;
% save('../testAnnot.mat','annot')
% annot = combinedannot;
% save('../finalAnnots.mat','annot')

function [newtubes,cc,ca] = verifyTubes(tubes, num_imgs,v,videoname)
cc = 0;tc = 0;ca=0;
newtubes = struct();
if isfield(tubes,'ef')>0
    for t = 1 : length(tubes)
        ef = tubes(t).ef;
        sf = tubes(t).sf;
        if ef>sf
            fdiff = abs(num_imgs-ef);
            if fdiff==1 || fdiff==2
                cc = cc+1;
                tubes(t).ef = num_imgs;
                for kk = 1:fdiff
                    tubes(t).boxes = [tubes(t).boxes;tubes(t).boxes(end,:)];
                end
            end
            tc = tc +1;
            newtubes(tc).ef = tubes(t).ef;
            newtubes(tc).sf = tubes(t).sf;
            newtubes(tc).boxes = tubes(t).boxes;
            newtubes(tc).class = tubes(t).class;
        else
            fprintf('%d %s\n',v,videoname);
            ca=1;
        end
    end
else
    fprintf('tube is empty %d %s\n',v,videoname);
end

function checkboxes(base_tubes,phil_tubes,apt_tubes,num_imgs,images_dir,save_path,videoName)

for i = 1 :1: num_imgs
    % fprintf('i=%d\n', i);
    philboxes = [];
    baseboxes = [];
    aptboxes = [];
    for t = 1 : length(phil_tubes)
        if phil_tubes(t).sf<= i && phil_tubes(t).ef >=i
            offset = uint16(phil_tubes(t).sf-1);
            philboxes = [philboxes;phil_tubes(t).boxes(i-offset,:),t];
        end
    end
    if isfield(base_tubes,'sf')
        for t = 1 : length(base_tubes)
            if i >= base_tubes(t).sf && i <= base_tubes(t).ef
                offset = uint16(base_tubes(t).sf-1);
                baseboxes = [baseboxes;base_tubes(t).boxes(uint8(i-offset),:),t];
            end
        end
    end

    for t = 1 : length(apt_tubes)
        if i >= apt_tubes(t).sf && i <= apt_tubes(t).ef
            offset = uint16(apt_tubes(t).sf-1);
            aptboxes = [aptboxes;apt_tubes(t).boxes(uint8(i-offset),:),t];
        end
    end

    image_name = sprintf('%s/%s/%05d.jpg',images_dir,videoName,i);
    %     if ~isempty(philboxes) || ~isempty(baseboxes)
    plotBoxes(philboxes,baseboxes,aptboxes,image_name, videoName, save_path, i,num_imgs);
    %     pause(0.000000001);
    %     end
end

function plotBoxes(philboxes,baseboxes,aptboxes,img_file, videoName, savepath, framenr,num_imgs)

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

savefile = sprintf('%s%05d.jpg',savepath,framenr);

%img_w=500;
%img_h=500;

hold off
im = imread(img_file);
imshow(im);
%set(gca,'Units','normalized','Position',[0 0 1 1]);  %# Modify axes size
%set(gcf,'Units','pixels','Position',[200 200 img_w img_h]);  %# Modify figure size
hold on;
legends = cell(1);
count =1 ;
steps = 1:15:440;

for  b = 1 : size(philboxes,1)
    rectangle('Position', philboxes(b,1:4), 'EdgeColor','b','LineWidth',5.0 );
    text(double(philboxes(b,1)+15), double(philboxes(b,2)-15), sprintf('%d',uint8(philboxes(b,5))),'Color','blue','FontSize',14);
    count = count + 1;
end

for  b = 1 : size(baseboxes,1)
    rectangle('Position', baseboxes(b,1:4), 'EdgeColor','r','LineWidth',3.0 );
    text(double(baseboxes(b,1)), double(baseboxes(b,2)-15), sprintf('%d',uint8(baseboxes(b,5))),'Color','red','FontSize',14);
    %     text(-50,steps(count),sprintf('base %d',b),'Color','red');
    count = count + 1;
end

for  b = 1 : size(aptboxes,1)
    rectangle('Position', aptboxes(b,1:4), 'EdgeColor','g','LineWidth',1.0 );
    text(double(aptboxes(b,1))+30, double(aptboxes(b,2)-15), sprintf('%d',uint8(aptboxes(b,5))),'Color','green','FontSize',14);
    %     text(-50,steps(count),sprintf('apt %d',b),'Color','green');
    count = count + 1;
end

% title([num2str(num_imgs),' ',num2str(framenr)])
% pause(0.000001)

frm_save = getframe(gcf); %# Capture the current window
imwrite(frm_save.cdata, savefile);
% imwrite(im,savefile);
%disp('ok');

function gtVidInd = getVidInd(video,videoName)
for i=1:length(video)
    vidid = video(i).name;
    if strcmp(vidid,videoName)
        gtVidInd = i;
        break;
    end
end

function tubes = extract_bounds(newcell, base_tubes, phil_tubes, apt_tubes, num_imgs,class)
tubes = struct();
alltubes = {base_tubes,phil_tubes,apt_tubes};
for t = 1 : length(newcell)
    tline = newcell{t};
    stl = strsplit(tline,' ');

    if length(stl)<6
        [sf,ef,boxes] = gettube(alltubes,stl,num_imgs,0);
    else
        [sf,ef,boxes] = gettube(alltubes,stl,num_imgs,1);
    end
    tubes(t).sf = sf;
    tubes(t).ef = ef;
    tubes(t).class = class;
    tubes(t).boxes = boxes;
end

function [sf,ef,boxes] = gettube(alltubes,stl,num_imgs,isone)
tube  = [];
annotType = {'b','p','a'};
ind = find(strcmp(annotType,stl{1}));

annot = alltubes{ind};

tid = str2num(stl{2});

sf = max(str2num(stl{3}),annot(tid).sf);

ef = min(str2num(stl{4}),annot(tid).ef);
st = sf-annot(tid).sf+1;
et = ef-sf+st; ct = 1;
boxes = annot(tid).boxes(st:et,:);
if isone
    ind = find(strcmp(annotType,stl{5}));
    annot = alltubes{ind};
    tid = str2num(stl{6});
    sfa = str2num(stl{7});
    if (sfa-ef)>1
        for kk = 1:(sfa-ef-1)
            boxes = [boxes;boxes(end,:)];
        end
    end
    ef = str2num(stl{8});
    st = sfa-annot(tid).sf+1;
    et = ef-sfa+st; ct = 1;
    boxes = [boxes;annot(tid).boxes(st:et,:)];
end


%GETUSER Get the user field of a dataset
%
%    USERFIELD = GETUSER(A,FIELD)
%
% INPUT
%   A          Dataset
%   FIELD      Character string: name of structure field of USER field of A.
%
% OUTPUT
%   USERFIELD  Requested field
%
% If FIELD is is the empty string ('') the entire user field is returned.
%
% If the requested field does not exist USERFIELD = [];
%
% Note the the USER field of datasets was originally intended for a user
% defined description of datasets. Later its usage was extended to a field
% for storing general information on datasets. For that reason 'old'
% datasets without a structure in the user field are transformed such that
% this information is stored in a subfield USER in the user field. It can
% be retrieved by GETUSER(A).


function result = saveImageFile(arg1, arg2, arg3);
% saveImageFile(IMGDIR, fname, res);
% saveImageFile(IMGFULLFILEPATH, res);
% res=200 for spectrograms
global paths PARAMS; % we need to knwo the value of PARAMS.mode

debug.printfunctionstack('>');

result = 0;
switch nargin
	case 2,
		[IMGDIR, fname] = fileparts(arg1);
		outpath = arg1;
		res = arg2;
	case 3,
		[IMGDIR, fname] = deal(arg1, arg2);
		outpath = fullfile(arg1, sprintf('%s.png',arg2));
		res = arg3;
    otherwise,
        debug.print_debug(0, 'could not save image file - wrong number of arguments')
        return;
end

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

try
	% Save the image file
	print(gcf, '-dpng', sprintf('-r%d',res), outpath );

	% Lock the output directory if in archive mode - it means we do not want to delete these files ever
	if strcmp('PARAMS.mode','archive')
		system(sprintf('touch %s/lock',IMGDIR));
	end

	% Did our image file actually get saved?
	if exist(outpath, 'file')
		debug.print_debug(1, sprintf('%s: Saved image file %s',datestr(utnow),outpath) );
		result = 1;
	else
		debug.print_debug(1, sprintf('%s: Image file %s was not created',datestr(utnow),outpath));
	end
catch
	debug.print_debug(0, sprintf('%s: Could not save the image file %s',datestr(utnow),outpath));
end

%print_debug(sprintf('< %s',mfilename),2);
debug.printfunctionstack('<');


% open a connection to the VREP simulator
%
% Notes::
% - the VREP constructor needs to know where V-REP is installed.
% - This can come from the environment variable VREP
% - Or you can edit this file to something like
%    vrep=VREP('/Applications/V-REP_PRO_EDU_V3_1_3_rev2b_Mac');

% Copyright (C) 1993-2017, 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

%%begin

% create a connection to a running instance of V-REP
vrep = VREP();

% let's change our viewpoint, move the camera further away
%
% first we get an object to mirror the default camera
cam = vrep.camera('DefaultCamera');

% then get the camera position
p = cam.getpos

% then set the camera be twice as far away
cam.setpos(2*p)

% add the human figure Bill
bill = vrep.loadmodel('people/Walking Bill');

% get the initial pose of Bill
T = bill.getpose()

% now we can change his position
bill.setpos([0.1, 0.2, 0]);

% make him turn to his right
bill.setorient([0 0 -pi/4])

% make him lean forward a bit
bill.setorient([0 pi/8 0])

% now set him back to his initial position and orientation
bill.setpose(T);

% now we will setup some nested loops to make him shuffle around a square
orient = [0 0 0];
for j=1:4
    step = [0.05 0 0];
    bill.setorient(orient);
    % move forward
    for i=1:30
        % move relative to current pose
        bill.setpos(step, bill);
    end
    % turn at right angles
    orient(3) = orient(3) + pi/2;
end

% remove the model from the scene
bill.remove();

% now we will load a scene into VREP that contains Bill, a tree, a mirror
% and a camera
vrep.loadscene(which('scene1.ttt'), 'local');

% we will get a handle to the camera
camera = vrep.camera('Vision_sensor');

% now we start the simulator, it must be running in order for the
% camera to render

vrep.simstart();

% now we loop as the camera creeps forward (in the z-direction) and we
% display the frames
for i=1:20
    camera.setpos([0 0 0.05], camera);
    camera.grab();
    drawnow
end

% stop the simulation
vrep.simstop();

% clear the scene, remove all objects
vrep.clearscene();

% add a model of an ABB IRB140 robot
model = vrep.loadmodel('robots/non-mobile/ABB IRB 140');

% and create a VREP_arm object
arm = vrep.arm(model);

% set the pose of the robot's base
arm.setpose( transl(0.3, 0.4, 0));

% get the joint angles
q = arm.getq();

% now move the robot's joints
arm.setq(q+0.3);

% clear the scene, remove all objects
vrep.clearscene();

% close the connection to the VREP simulator
clear vrep


%function cstr = strsplit(strarr, ch)
%
% FUNCTIONALITY
% Splits string <strarr> at positions where substring <ch>
% occurs. If <ch> is not given, then ascii character 10
% (newline) is the splitting position.
% This would split for example a read-in file into its lines.
%
% INPUT
%   strarr     string to split
%   ch         optional, character or substring at which to split,
%              default is character ascii 10 = 'newline'
%
% OUTPUT
%   cstr       cell array of strings, all leading and trailing
%              spaces are deleted. Substring ch is removed from string.
%
% EXAMPLES
%   a = strsplit('aaa bbb ccc ', ' ')
%   Result: a{1}='aaa', a{2}='bbb', a{3}='ccc'
%   a = strsplit('user@server', '@')
%   Result: a{1}='user', a{3}='server'
%   a = strsplit('aabbccddeeffgg', 'dd')
%   Result: a{1}='aabbcc', a{2} = 'eeffgg'
%
% RELATED
%   strfun, depreciated stringify.m

% Copyright (C) 2002 Marc Molinari, University of Southampton
% Author: Dr Marc Molinari <m.molinari@soton.ac.uk>
% $Revision: 1.1 $ $Date: 2005/04/15 17:12:14 $ $Tag$


function view_qva(lab1,valueMap)
    % view_maxz plots the maxz LTA values calculated
    % with maxzlta.m or other similar values as a color map
    % needs valueMap, gx, gy, stri
    %
    % define size of the plot etc.
    %
%     The Z-Value Map Window
%
%
%           This window displays seismicity rate changes
%           as z-values using a color code. Negative
%           z-values indicate an increase in the seismicity
%           rate, positive values a decrease.
%           Some of the menu-bar options are
%           described below:
%
%           Threshold: You can set the maximum size that
%             a volume is allowed to have in order to be
%             displayed in the map. Therefore, areas with
%             a low seismicity rate are not displayed.
%             edit the size (in km) and click the mouse
%             outside the edit window.
%         'FixAx: You can chose the minimum and maximum
%                  values of the color-legend used.
%         'Polygon: You can select earthquakes in a
%           polygon either by entering the coordinates or
%           defining the corners with the mouse
%
%         'Circle: Select earthquakes in a circular volume:
%                Ni, the number of selected earthquakes can
%                be edited in the upper right corner of the
%                window.
%           Refresh Window: Redraws the figure, erases
%                 selected events.
%
%           zoom: Selecting Axis -> zoom on allows you to
%                 zoom into a region. Click and drag with
%                 the left mouse button. type <help zoom>
%                 for details.
%           Aspect: select one of the aspect ratio options
%           Text: You can select text items by clicking. The
%                 selected text can be rotated, moved, you
%                 can change the font size etc.
%                 Double click on text allows editing it.

    report_this_filefun();
    ZG=ZmapGlobal.Data;
    % Find out if figure already exists
    %
    qmap=findobj('Type','Figure','-and','Name','q-detect-map');

    % Set up the Seismicity Map window Enviroment
    %
    if isempty(qmap)
        qmap = figure_w_normalized_uicontrolunits( ...
            'Name','q-detect-map',...
            'NumberTitle','off', ...
            'NextPlot','new', ...
            'backingstore','on',...
            'Visible','off', ...
            'Position',position_in_current_monitor(ZG.map_len(1), ZG.map_len(2)));

        lab1 = 'day/night ratio';
        create_my_menu();

        uicontrol('Units','normal',...
            'Position',[.0 .93 .08 .06],'String','Info ',...
            'callback',@callbackfun_001);

        uicontrol('Units','normal',...
            'Position',[.92 .80 .08 .05],'String','set ni',...
            'callback',@callbackfun_006)

        set_nia = uicontrol('style','edit','value',ni,'string',num2str(ni));
        set(set_nia, 'Callback', @callbackfun_007);
        set(set_nia,'units','norm','pos',[.94 .85 .06 .05],'min',10,'max',10000);
        nilabel = uicontrol('style','text','units','norm','pos',[.90 .85 .04 .05]);
        set(nilabel,'string','ni:','background',[.7 .7 .7]);

        ZG.tresh_km = nan; re4 = valueMap;
        nilabel2 = uicontrol('style','text','units','norm','pos',[.60 .92 .25 .06]);
        set(nilabel2,'string','MinRad (in km):','background',color_fbg);
        set_ni2 = uicontrol('style','edit','value',ZG.tresh_km,'string',num2str(ZG.tresh_km),...
            'background','y');
        set(set_ni2, 'Callback', @callbackfun_008);
        set(set_ni2,'units','norm','pos',[.85 .92 .08 .06],'min',0.01,'max',10000);

        uicontrol('Units','normal',...
            'Position',[.95 .93 .05 .05],'String','Go ',...
            'callback',@callbackfun_009)

        colormap(cool)

    end   % This is the end of the figure setup

    % Now lets plot the color-map of the z-value
    %
    figure(qmap);
    delete(findobj(qmap,'Type','axes'));
    % delete(sizmap);
    reset(gca)
    cla
    set(gca,'NextPlot','replace')
    watchon;
    set(gca,'visible','off','FontSize',ZmapGlobal.Data.fontsz.s,'FontWeight','bold',...
        'FontWeight','bold','LineWidth',1.5,...
        'Box','on','SortMethod','childorder')

    rect = [0.18,  0.10, 0.7, 0.75];
    rect1 = rect;

    % find max and min of data for automatic scaling
    %
    ZG.maxc = max(valueMap(:));
    ZG.maxc = fix(ZG.maxc)+1;
    ZG.minc = min(valueMap(:));
    ZG.minc = fix(ZG.minc)-1;

    % set values gretaer ZG.tresh_km = nan
    %
    re4 = valueMap;
    re4(r > ZG.tresh_km) = nan;

    % plot image
    %
    orient landscape
    %set(gcf,'PaperPosition', [0.5 1 9.0 4.0])

    axes('position',rect)
    set(gca,'NextPlot','add')
    pco1 = pcolor(gx,gy,re4);

    axis([ min(gx) max(gx) min(gy) max(gy)])
    axis image
    set(gca,'NextPlot','add')

    shading(ZG.shading_style);

    fix_caxis.ApplyIfFrozen(gca);

    title([name ';  '   num2str(t0b) ' to ' num2str(teb) ],'FontSize',ZmapGlobal.Data.fontsz.s,...
        'Color','r','FontWeight','bold')

    xlabel('Longitude [deg]','FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.s)
    ylabel('Latitude [deg]','FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.s)

    % plot overlay
    %
    set(gca,'NextPlot','add')
    zmap_update_displays();
    globalcatalog = ZG.primeCatalog;
    ploeq = plot(globalcatalog.X,globalcatalog.Y,'k.');
    set(ploeq,'Tag','eq_plot','MarkerSize',ZG.ms6,'Marker',ty,'Color',ZG.someColor,'Visible','on')

    set(gca,'visible','on','FontSize',ZmapGlobal.Data.fontsz.s,'FontWeight','bold',...
        'FontWeight','bold','LineWidth',1.5,...
        'Box','on','TickDir','out')
    h1 = gca;
    hzma = gca;

    % Create a colorbar
    %
    h5 = colorbar('horiz');
    set(h5,'Pos',[0.35 0.05 0.4 0.02],...
        'FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.s)

    rect = [0.00,  0.0, 1 1];
    axes('position',rect)
    axis('off')
    %  Text Object Creation
    txt1 = text(...
        'Units','normalized',...
        'Position',[ 0.33 0.07 0 ],...
        'HorizontalAlignment','right',...
        'FontSize',ZmapGlobal.Data.fontsz.s,....
        'FontWeight','bold',...
        'String',lab1);

    % Make the figure visible
    %
    set(gca,'FontSize',ZmapGlobal.Data.fontsz.s,'FontWeight','bold',...
        'FontWeight','bold','LineWidth',1.5,...
        'Box','on','TickDir','out')
    figure(qmap);
    axes(h1)
    watchoff(qmap)

    %% ui functions
    function create_my_menu()
        add_menu_divider();

        add_symbol_menu('eq_plot');

        options = uimenu('Label',' Select ');
        uimenu(options,'Label','Refresh ','MenuSelectedFcn',@callbackfun_002)
        uimenu(options,'Label','Select EQ in Circle','MenuSelectedFcn',@callbackfun_003)
        uimenu(options,'Label','Select EQ in Polygon ','MenuSelectedFcn',@callbackfun_004)

        op1 = uimenu('Label',' Maps ');
        uimenu(op1,'Label','day/night value map',...
            'MenuSelectedFcn',@callbackfun_005)

        add_display_menu(1);
    end

    %% callback functions

    function callbackfun_001(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        web(['file:' hodi '/help/quarry.htm']) ;
    end

    function callbackfun_002(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        delete(findobj(qmap,'Type','axes'));
        view_qva(lab1,valueMap);
    end

    function callbackfun_003(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        h1 = gca;
        circle;
        watchoff(qmap);
        hisgra(ZG.newt2.Date.Hour,'Hour',ZG.newt2.Name);
    end

    function callbackfun_004(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        stri = 'Polygon';
        h1 = gca;
        cufi = gcf;
        selectp;
        hisgra(ZG.newt2,'Hour');
    end

    function callbackfun_005(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        lab1 ='day/night ratio';
        valueMap = old;
        view_qva(lab1,valueMap);
    end

    function callbackfun_006(mysrc,myevt)

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

    function callbackfun_007(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        %FIXME callback does nothing
    end

    function callbackfun_008(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        ZG.tresh_km=str2double(set_ni2.String);
        set_ni2.String=num2str(ZG.tresh_km);
    end

    function callbackfun_009(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        ;
        pause(1);
        re4 =valueMap;
        view_bva(lab1,valueMap);
    end
end


% conda.m
% a simple MATLAB utility to control conda
% environments on *nix systems
%
% usage
%
% MATLAB 			   Shell
% ===================================
% conda.getenv         conda env list
% conda.setenv(env)    source activate env
%
% Srinivas Gorur-Shandilya

classdef conda

properties
end

methods

end

methods (Static)

	function varargout = conda(varargin)

		varargout = {};

		if nargin == 2
			if strcmp(varargin{1},'env') && strcmp(varargin{2},'list')
				conda.getenv();
				return
			elseif strcmp(varargin{1},'activate')
				conda.setenv(varargin{2})
				return
			else
				error('Unknown argument syntax')
			end
		else
			error('Unknown argument syntax')
		end

	end

	function init()

		try
			getpref('condalab','base_path');
		catch
			str = input('Enter the path to your conda installation:  \n','s');
			str = strrep(str,[filesep 'conda'],'');
			setpref('condalab','base_path',str)
		end

		conda.addBaseCondaPath()

	end

	function addBaseCondaPath()

		try
			condalab_base_path = getpref('condalab','base_path');
		catch
			conda.init()
			condalab_base_path = getpref('condalab','base_path');
		end

		[e,o]=system('which conda');
		if e == 0
			% conda is somewhere on the path, so do nothing
			return
		end

		P = strsplit(getenv('PATH'),pathsep);
		add_to_path = true;
		for i = 1:length(P)
			if strcmp(P{i},condalab_base_path)
				add_to_path = false;
			end
		end
		if add_to_path
			setenv('PATH',[condalab_base_path pathsep getenv('PATH') ]);
		end

	end

	function varargout = getenv()
		conda.addBaseCondaPath;
		[~,envs] = system('conda env list');
		envs = strsplit(envs,'\n');

		p = strsplit(getenv('PATH'),pathsep);

		% remove the asterix because it always is on root
		for i = length(envs):-1:1
			envs{i} = strrep(envs{i},'*',' ');
			if isempty(envs{i})
				continue
			end
			if strcmp(envs{i}(1),'#')
				continue
			end

			this_env = strsplit(envs{i});
			env_names{i} = this_env{1};
			env_paths{i} = this_env{2};

			active_path = 0;
			for j = 1:length(env_paths)
				this_env_path = [env_paths{j} filesep 'bin'];
				if any(strcmp(this_env_path,p))
					active_path = j;
				end
			end

		end

		if nargout
			varargout{1} = env_names;
			varargout{2} = env_paths;
			varargout{3} = active_path;
		else
			fprintf('\n')
			for i = 1:length(env_names)
				if isempty(env_names{i})
					continue
				end
				if active_path == i
					disp(['*' env_names{i} '     ' env_paths{i}])
				else
					disp([env_names{i} '     ' env_paths{i}])
				end
			end
		end
	end % end getenv

	function setenv(env)
		conda.addBaseCondaPath;
		[~,envs] = system(['conda env list']);
		envs = strsplit(envs,'\n');

		[env_names, env_paths] = conda.getenv;

		% check that envs exists in the list
		assert(any(strcmp(env_names,env)), 'env you want to activate is not valid')

		p = getenv('PATH');
		% delete every conda env path from the path
		p = strsplit(p,pathsep);
		rm_this = false(length(p),1);
		for i = 1:length(p)
			% remove "bin" from the end
			this_path = strtrim(strrep(p{i}, [filesep 'bin'],''));
			if any(strcmp(this_path,env_paths))
				rm_this(i) = true;
			end
		end
		p(rm_this) = [];

		% add the path of the env we want to switch to
		this_env_path = [env_paths{strcmp(env_names,env)} filesep 'bin'];
		p = [this_env_path p];
		p = strjoin(p,pathsep);

		% append the base path to this, because apparently
		% conda decides to change everything every 2 months
		p = [p pathsep getpref('condalab','base_path')];

		setenv('PATH', p);

	end % setenv

	% asks the python interpreter where it is located
	function test()
		system(['python ' fileparts(which(mfilename)) filesep 'test.py']);
	end

end

end % end classdef


function T = TRaw( I )

if(nargin<1 || isempty(I)), T=single([]);   return; end

% T = single( I(:,:,4) );
T = single( I(:,:,end) );

end


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

%%
clear; close all; clc;

%% Syntax
% |febio(varargin);|

%% Description
% UNDOCUMENTED
%% Examples
%
%%
%
% <<gibbVerySmall.gif>>
%
% _*GIBBON*_
% <www.gibboncode.org>
%
% _Kevin Mattheus Moerman_, <gibbon.toolbox@gmail.com>
%%
% _*GIBBON footer text*_
%
% License: <https://github.com/gibbonCode/GIBBON/blob/master/LICENSE>
%
% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for
% image segmentation, image-based modeling, meshing, and finite element
% analysis.
%
% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.


classdef TestAreImagesInSameGroup < CoreTest
    % TestAreImagesInSameGroup. Tests for the DMAreImagesInSameGroup function.
    %
    %
    %     Licence
    %     -------
    %     Part of the TD Pulmonary Toolkit. https://github.com/tomdoel/pulmonarytoolkit
    %     Author: Tom Doel, 2012.  www.tomdoel.com
    %     Distributed under the GNU GPL v3 licence. Please see website for details.
    %

    methods
        function obj = TestAreImagesInSameGroup
            this_metadata = [];
            other_metadata = [];

            % For images to be in the same group, the following tags must either
            % be present in both metadata, or not present in both metadata. If
            % present, they must be equal. We check that the test passes in
            % these cases and fails otherwise

            [this_metadata, other_metadata] = obj.CheckMatchingOfTags(this_metadata, other_metadata, 'PatientName', 'Name1', 'Name2');
            [this_metadata, other_metadata] = obj.CheckMatchingOfTags(this_metadata, other_metadata, 'PatientID');
            [this_metadata, other_metadata] = obj.CheckMatchingOfTags(this_metadata, other_metadata, 'PatientBirthDate');

            [this_metadata, other_metadata] = obj.CheckMatchingOfTags(this_metadata, other_metadata, 'StudyInstanceUID');
            [this_metadata, other_metadata] = obj.CheckMatchingOfTags(this_metadata, other_metadata, 'SeriesInstanceUID');
            [this_metadata, other_metadata] = obj.CheckMatchingOfTags(this_metadata, other_metadata, 'StudyID');
            [this_metadata, other_metadata] = obj.CheckMatchingOfTags(this_metadata, other_metadata, 'StudyDescription');
            [this_metadata, other_metadata] = obj.CheckMatchingOfTags(this_metadata, other_metadata, 'SeriesNumber');
            [this_metadata, other_metadata] = obj.CheckMatchingOfTags(this_metadata, other_metadata, 'SeriesDescription', 'Series Description 1', 'Series Description 2');
            [this_metadata, other_metadata] = obj.CheckMatchingOfTags(this_metadata, other_metadata, 'StudyDate');
            [this_metadata, other_metadata] = obj.CheckMatchingOfTags(this_metadata, other_metadata, 'SeriesDate');

            [this_metadata, other_metadata] = obj.CheckMatchingOfTags(this_metadata, other_metadata, 'Rows', 256, 512);
            [this_metadata, other_metadata] = obj.CheckMatchingOfTags(this_metadata, other_metadata, 'Columns', 256, 512);
            [this_metadata, other_metadata] = obj.CheckMatchingOfTags(this_metadata, other_metadata, 'PixelSpacing', [1 2], [3 4]);
            [this_metadata, other_metadata] = obj.CheckMatchingOfTags(this_metadata, other_metadata, 'PatientPosition');
            [this_metadata, other_metadata] = obj.CheckMatchingOfTags(this_metadata, other_metadata, 'ImageOrientationPatient', [1;0;0;0;1;0], [0;1;0;0;0;1]);
            [this_metadata, other_metadata] = obj.CheckMatchingOfTags(this_metadata, other_metadata, 'FrameOfReferenceUID');

            [this_metadata, other_metadata] = obj.CheckMatchingOfTags(this_metadata, other_metadata, 'Modality', 'CT', 'MR');
            [this_metadata, other_metadata] = obj.CheckMatchingOfTags(this_metadata, other_metadata, 'MediaStorageSOPClassUID');
            [this_metadata, other_metadata] = obj.CheckMatchingOfTags(this_metadata, other_metadata, 'ImageType', 'ORIGINAL\PRIMARY\AXIAL', 'ORIGINAL\PRIMARY');
            [this_metadata, other_metadata] = obj.CheckMatchingOfTags(this_metadata, other_metadata, 'SOPClassUID');
            [this_metadata, other_metadata] = obj.CheckMatchingOfTags(this_metadata, other_metadata, 'ImplementationClassUID');
            [this_metadata, other_metadata] = obj.CheckMatchingOfTags(this_metadata, other_metadata, 'ImagesInAcquisition', 100, 102);
            [this_metadata, other_metadata] = obj.CheckMatchingOfTags(this_metadata, other_metadata, 'SamplesPerPixel', 1, 2);
            [this_metadata, other_metadata] = obj.CheckMatchingOfTags(this_metadata, other_metadata, 'PhotometricInterpretation');
            [this_metadata, other_metadata] = obj.CheckMatchingOfTags(this_metadata, other_metadata, 'BitsAllocated', 1, 2);
            [this_metadata, other_metadata] = obj.CheckMatchingOfTags(this_metadata, other_metadata, 'BitsStored', 1, 2);
            [this_metadata, other_metadata] = obj.CheckMatchingOfTags(this_metadata, other_metadata, 'HighBit', 1, 2);
            [this_metadata, other_metadata] = obj.CheckMatchingOfTags(this_metadata, other_metadata, 'PixelRepresentation');

            % Slice location tags: existence must match but values do not have
            % to match
            this_metadata.SliceLocation = 1;
            obj.Assert(~DMAreImagesInSameGroup(this_metadata, other_metadata), 'Should fail');
            other_metadata.SliceLocation = 2;
            obj.Assert(DMAreImagesInSameGroup(this_metadata, other_metadata), 'Should pass');

            % ImagePositionPatient tag: check consistency of image locations
            % Image positions should lie approximately on a line; there is a
            % tolerance of 10mm
            extra_metadata = other_metadata;
            this_metadata.ImagePositionPatient = [10;20;30];
            extra_metadata.ImagePositionPatient = [20;40;60];
            other_metadata.ImagePositionPatient = [30;60;110];
            obj.Assert(~DMAreImagesInSameGroup(this_metadata, other_metadata, extra_metadata), 'Should fail');
            other_metadata.ImagePositionPatient = [30;60;90];
            obj.Assert(DMAreImagesInSameGroup(this_metadata, other_metadata, extra_metadata), 'Should pass');
            extra_metadata.ImagePositionPatient = [20;-40;60];
            obj.Assert(~DMAreImagesInSameGroup(this_metadata, other_metadata, extra_metadata), 'Should fail');

            this_metadata.ImagePositionPatient = [0;30;40];
            extra_metadata.ImagePositionPatient = [0;90;120];
            other_metadata.ImagePositionPatient = [0;60;80];
            obj.Assert(DMAreImagesInSameGroup(this_metadata, other_metadata, extra_metadata), 'Should pass');
            other_metadata.ImagePositionPatient = [0;55;80];
            obj.Assert(DMAreImagesInSameGroup(this_metadata, other_metadata, extra_metadata), 'Should pass');
            this_metadata.ImagePositionPatient = [0;30;-40];
            obj.Assert(~DMAreImagesInSameGroup(this_metadata, other_metadata, extra_metadata), 'Should fail');
            this_metadata.ImagePositionPatient = [0;15;40];
            extra_metadata.ImagePositionPatient = [0;90;120];
            other_metadata.ImagePositionPatient = [0;60;80];
            obj.Assert(~DMAreImagesInSameGroup(this_metadata, other_metadata, extra_metadata), 'Should fail');
        end
    end

    methods (Access = private)
        function [this_metadata, other_metadata] = CheckMatchingOfTags(obj, this_metadata, other_metadata, tag_name, value_1, value_2)
            if nargin < 6
                value_2 = CoreSystemUtilities.GenerateUid;
            end
            if nargin < 5
                value_1 = CoreSystemUtilities.GenerateUid;
            end

            % Images should match if the tag is not present in either
            obj.Assert(DMAreImagesInSameGroup(this_metadata, other_metadata), 'Should pass');

            % Images should not match if one contains a tag
            this_metadata.(tag_name) = value_1;
            obj.Assert(~DMAreImagesInSameGroup(this_metadata, other_metadata), 'Should fail');

            % Images should not match if the tags don't match
            other_metadata.(tag_name) = value_2;
            obj.Assert(~DMAreImagesInSameGroup(this_metadata, other_metadata), 'Should fail');

            % Images should match if the tags match
            other_metadata.(tag_name) = value_1;
            obj.Assert(DMAreImagesInSameGroup(this_metadata, other_metadata), 'Should pass');
        end
    end
end


% Runs the large tests for the whole cell simulation.
%
% Author: Jonathan Karr, jkarr@stanford.edu
% Affilitation: Covert Lab, Department of Bioengineering, Stanford University
% Last updated: 8/13/2010
function runLargeTests()
%% initialize
warning('off','WholeCell:warning');
setWarnings();
setPath();
setPreferences();

%% run tests
import edu.stanford.covert.test.XMLTestRunDisplay;
import edu.stanford.covert.test.runtests;
monitor = XMLTestRunDisplay('Large Tests','Whole cell simulation large tests', 'output/runLargeTests/tests.xml');
runtests(monitor, {
    'edu.stanford.covert.cell.sim.Simulation_Large_Test'
    });


close all; clear all;
run('../vlfeat-0.9.20/toolbox/vl_setup');

addpath('transforms');
addpath('examples');

REW_worktable;
REW_racetracks;
REW_racetracks;
REW_boardingbridge;
REW_theater;
REW_riverbank;
REW_city;
REW_eyot;
REW_lawn;
REW_parterre;
REW_doorwayreliefs;
REW_building;
REW_campussquare;
REW_gym;
REW_tower;
REW_songyalake_square2;
REW_songyalake_square3;
REW_songyalake_square;
REW_palace;
REW_palace2;
REW_palace3;

APAP_railtracks;
APAP_garden;
APAP_conssite;
APAP_train;

ANAP_building;
ANAP_fense;
ANAP_intersection;
ANAP_roundabout;
ANAP_skyline;

DHW_temple;
DHW_carpark;
DHW_forest;

SPHP_bridge;
SPHP_building;
SPHP_campus;
SPHP_garden;
SPHP_park;
SPHP_street;

NISwGSP_01_PisaCathedralInterior;
NISwGSP_02_Uffizi;
NISwGSP_03_SantaMaria;
NISwGSP_03_SantaMaria_all;
NISwGSP_04_SantaMaria2;
NISwGSP_05_SienaCathedral;
NISwGSP_06_SienaCathedralLibrary;
NISwGSP_07_SienaCathedralLibrary2;
NISwGSP_08_SienaCathedralLibrary3;
NISwGSP_09_SienaCathedralLibrary4;
NISwGSP_10_SienaCathedralInterior;
NISwGSP_11_PiazzaCampo;
NISwGSP_12_PalazzoPubblico;
NISwGSP_13_PalazzoPubblico2;
NISwGSP_cise;
NISwGSP_denny;
NISwGSP_grail;
NISwGSP_Memorial_Hall;
NISwGSP_parrington;

CAVE_atrium;
CAVE_eitan_office;
CAVE_times_square;


function varargout = subsref(v,s)
%overloads subsref

switch s(1).type
  case '()'

    v.x = subsref(v.x,s(1));
    v.y = subsref(v.y,s(1));
    v.z = subsref(v.z,s(1));

    v.opt = struct;

    if numel(s)>1
      [varargout{1:nargout}] = builtin('subsref',v,s(2:end));
    else
      varargout{1} = v;
    end
  otherwise

    [varargout{1:nargout}] = builtin('subsref',v,s);

end
end


function check_dl_model( model )
% Download model file
if ~exist(model,'file')
  [~, baseModel] = fileparts(model);
  fprintf('Downloading base model file: %s ...\n', baseModel);
  mkdir_if_missing(fileparts(model)) ;
  urlwrite(...
  ['http://ftp.tugraz.at/pub/feichtenhofer/detect-track/models/' baseModel '.caffemodel'], ...
    model) ;
end

end


function [supported] = tracker_test(tracker)
% trax_test Test tracker's support for TraX protocol
%
% This function tries to run the tracker and communicate with it using the
% TraX protocol to determine if it supports it. The results are chached
% in the workspace cache directory.
%
% Input:
% - tracker: Tracker structure.
%
% Output:
% - supported (boolean): Is the protocol supported.

% Check if the result of the test is already cached
cache = fullfile(get_global_variable('directory'), 'cache', 'trax');

tracker_hash = md5hash(sprintf('%s-%s-%s', tracker.command, tracker.interpreter, strjoin(tracker.linkpath, '-')));
mkpath(cache);
cache_file = fullfile(cache, sprintf('trax_%s_%s.mat', tracker.identifier, tracker_hash));

supported = [];
if exist(cache_file, 'file')
    load(cache_file);
    if ~isempty(supported)
        return;
    end;
end;

print_text('Testing TraX protocol support for tracker %s.', tracker.identifier);

try

    data.header = false;

    data = tracker_run(tracker, @callback, data);

    supported = data.header;

catch

    supported = false;

end

if supported
    % Only cache if support is detected
    save(cache_file, 'supported');
    print_text('TraX support detected.');
else
	print_text('TraX support not detected.');
end

end

function [image, region, properties, data] = callback(state, data)

    image = [];
    region = [];
    properties = struct();

    data.header = true;
    data.state = state;

end


function varargout = mesh(varargin)
%MESH   Mesh surface of a DISKFUN.
%   MESH is not supported for DISKFUN objects, and so returns an error.
%
% See also DISKFUN/SURF.

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

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

end