% STD_LOADALLEEG - constructs an ALLEEG structure, given the paths and file names
%                    of all the EEG datasets that will be loaded into the ALLEEG
%                    structure. The EEG datasets may be loaded without their EEG.data
%                    (see the POP_EDITOPTIONS function), so many datasets can be
%                    loaded simultaneously. The loaded EEG datasets have dataset
%                    information and a (filename) pointer to the data.
% Usage:
%                  % Load sseveral EEG datasets into an ALLEEG structure.
%                  >> ALLEEG = std_loadalleeg(paths,datasets) ;
%                  >> ALLEEG = std_loadalleeg(STUDY) ;
% Inputs:
%   paths      - [cell array of strings] cell array with all the datasets paths.
%   datasets   - [cell array of strings] cell array with all the datasets file names.
%
% Output:
%   ALLEEG     - an EEGLAB data structure, which holds the loaded EEG sets
%                 (can also be one EEG set).
%  Example:
%          >> paths = {'/home/eeglab/data/sub1/','/home/eeglab/data/sub2/', ...
%          >>          '/home/eeglab/data/sub3/', '/home/eeglab/data/sub6/'};
%          >> datasets = { 'visattS1', 'visattS2', 'visattS3', 'visattS4'};
%          >> ALLEEG = std_loadalleeg(paths,datasets) ;
%
% See also: POP_LOADSTUDY, POP_STUDY
%
% Authors: Hilit Serby, Arnaud Delorme, SCCN, INC, UCSD, October , 2004

% Copyright (C) Hilit Serby, SCCN, INC, UCSD, October 11, 2004, hilit@sccn.ucsd.edu
%
% This file is part of EEGLAB, see https://eeglab.org
% for the documentation and details.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are met:
%
% 1. Redistributions of source code must retain the above copyright notice,
% this list of conditions and the following disclaimer.
%
% 2. 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 HOLDER 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.

function ALLEEG = std_loadalleeg(varargin)

    if nargin < 1
        help std_loadalleeg;
        return;
    end

    genpath = '';
    oldgenpath = '';
    if isstruct(varargin{1})
        datasets = {varargin{1}.datasetinfo.filename};
        try,
            paths = {varargin{1}.datasetinfo.filepath};
        catch,
            paths = cell(1,length(datasets));
            paths(:) = { '' };
        end
        genpath = varargin{1}.filepath;
        if isfield(varargin{1}.etc, 'oldfilepath')
            oldgenpath = varargin{1}.etc.oldfilepath;
        end
    else
        paths = varargin{1};
        if nargin > 1
            datasets = varargin{2};
        else
            datasets = paths;
            paths    = cell(size(datasets));
        end
    end

    set = 1;
    ALLEEG = [];

    eeglab_options;

    % read datasets
    % -------------
    comp = computer;
    warnfold = 'off';
    if length(oldgenpath) > 1 && oldgenpath(2) == ':' && ~strcmpi(comp(1:2), 'PC')
        oldgenpath = [ filesep oldgenpath(4:end) ];
        oldgenpath(find(oldgenpath == '\')) = filesep;
    end

    for dset = 1:length(paths)
        if ~isempty(paths{dset})
            if paths{dset}(2) == ':' && ~strcmpi(comp(1:2), 'PC')
                paths{dset} = [ filesep paths{dset}(4:end) ];
                paths{dset}(find(paths{dset} == '\')) = filesep;
            end
        end

        [sub2 sub1] = fileparts(char(paths{dset}));
        [sub3 sub2] = fileparts(sub2);

        % priority is given to relative path of the STUDY if STUDY has moved
        if ~isempty(oldgenpath) && oldgenpath(end) == filesep
             oldgenpath(end) = [];
        end
        if ~isequal(genpath, oldgenpath) && ~isempty(oldgenpath) %
            oldgenpath = strrep(oldgenpath, [ filesep filesep ], filesep);
            if ~isequal(genpath, oldgenpath) && ~isempty(oldgenpath)

                disp('Warning: STUDY moved since last saved, trying to load data files using relative path');
                if  ~isempty(strfind(char(paths{dset}), oldgenpath))
                    relativePath = char(paths{dset}(length(oldgenpath)+1:end));
                    relativePath = fullfile(genpath, relativePath);
                else
                    disp('Important warning: relative path cannot calculated, make sure the correct data files are loaded');
                    relativePath = char(paths{dset});
                end

                % fix issue when datasets are in a parent folder of the STUDY
                if dset == 1
                    indCommon = 1;
                    while indCommon <= length(oldgenpath) && indCommon <= length(paths{1}) && paths{1}(indCommon) == oldgenpath(indCommon)
                        indCommon = indCommon+1;
                    end
                    indCommon = indCommon-1;
                    if indCommon > 1 && indCommon < length(genpath) % do not change path if nothing in common between the two paths
                        genpath(indCommon-length(oldgenpath)+length(genpath)+1:end) = [];
                    end
                end
            else
                relativePath = char(paths{dset});
            end
        else
            relativePath = char(paths{dset});
        end

        % load files with a variety of extension using file-io
        [~,~,ext] = fileparts(datasets{dset});
        if ~isequal(lower(ext), '.set')
            disp('Importing binary file and resaving with a .set file extension as an EEGLAB dataset');
            EEG = pop_biosig(fullfile(relativePath, datasets{dset}));
            [pathTmp,fileTmp,ext] = fileparts(fullfile(relativePath, datasets{dset}));
            EEG = pop_saveset(EEG, fullfile(pathTmp, [ fileTmp '.set' ]));
        elseif exist(fullfile(relativePath, datasets{dset})) == 2
            EEG = pop_loadset('filename', datasets{dset}, 'filepath', relativePath, 'loadmode', 'info', 'check', 'off');
        elseif exist(fullfile(char(paths{dset}), datasets{dset})) == 2
            EEG = pop_loadset('filename', datasets{dset}, 'filepath', char(paths{dset}), 'loadmode', 'info', 'check', 'off');
        elseif exist( fullfile(genpath, datasets{dset})) == 2
            [tmpp tmpf ext] = fileparts(fullfile(genpath, datasets{dset}));
            EEG = pop_loadset('filename', [tmpf ext], 'filepath',tmpp, 'loadmode', 'info', 'check', 'off');
            warnfold = 'on';
        elseif exist( fullfile(genpath, sub1, datasets{dset})) == 2
            [tmpp tmpf ext] = fileparts(fullfile(genpath, sub1, datasets{dset}));
            EEG = pop_loadset('filename', [tmpf ext], 'filepath',tmpp, 'loadmode', 'info', 'check', 'off');
            warnfold = 'on';
        elseif exist( fullfile(genpath, sub2, datasets{dset}))  == 2
            [tmpp tmpf ext] = fileparts(fullfile(genpath, sub2, datasets{dset}));
            EEG = pop_loadset('filename', [tmpf ext], 'filepath',tmpp, 'loadmode', 'info', 'check', 'off');
            warnfold = 'on';
        elseif exist( fullfile(genpath, sub2, sub1, datasets{dset}))  == 2
            [tmpp tmpf ext] = fileparts(fullfile(genpath, sub2, sub1, datasets{dset}));
            EEG = pop_loadset('filename', [tmpf ext], 'filepath',tmpp, 'loadmode', 'info', 'check', 'off');
            warnfold = 'on';
        elseif exist(lower(fullfile(char(paths{dset}), datasets{dset}))) == 2
            EEG = pop_loadset('filename', lower(datasets{dset}), 'filepath',lower(char(paths{dset})), 'loadmode', 'info', 'check', 'off');
        elseif exist(fullfile(pwd, datasets{dset})) == 2
            EEG = pop_loadset('filename', lower(datasets{dset}), 'filepath',pwd, 'loadmode', 'info', 'check', 'off');
        else
            txt = [ sprintf('The dataset %s is missing\n', datasets{dset}) 10 ...
                          'Is it possible that it might have been deleted?' 10 ...
                          'If this is the case, re-create the STUDY using the remaining datasets' ];
            error(txt);
        end

        EEG = eeg_checkset(EEG);
        if ~option_storedisk
            EEG = eeg_checkset(EEG, 'loaddata');
        elseif ~ischar(EEG.data)
            EEG.data   = 'in set file';
            EEG.icaact = [];
        end

        [ALLEEG, EEG] = eeg_store(ALLEEG, EEG, 0, 'notext');
    end
    ALLEEG = eeg_checkset(ALLEEG);

    if strcmpi(warnfold, 'on') && ~strcmpi(pwd, genpath) && ~isempty(genpath)
        disp('Changing current path to STUDY path...');
        cd(genpath);
    end
    if strcmpi(warnfold, 'on')
        disp('This STUDY has a relative path set for the datasets');
        disp('so the current path MUST remain the STUDY path');
    end


function r = isreal(a)
%ISREAL       returns 1 if c is real
%
%   r = isreal(a)
%

% written  05/21/09     S.M. Rump
%

  r = isreal(a.t);


function failed_corrupt_matfiles

% MEM 8gb
% WALLTIME 10:00:00
% DEPENDENCY

files = findfiles(dccnpath('/home/common/matlab/fieldtrip/data/test'));
status = true(size(files));

for i=1:length(files)
  try
    tmp = load(files{i});
    clear tmp
    fprintf('passed reading %s\n', files{i});
  catch
    status(i) = false;
    warning('failed reading %s\n', files{i});
  end
end

if any(status==false)
  error('not all files could be read into MATLAB');
end

function files = findfiles(p)
d = dir(p);
d = d([d.bytes]<4*1e9); % skip files that are too large

files = {d(~[d.isdir]).name}';
files = files(~cellfun(@isempty, regexp(files, '\.mat$'))); % only select the mat files
files = files( cellfun(@isempty, regexp(files, '^\._')));   % exclude the OS X resource forks

for i=1:length(files)
  files{i} = fullfile(p, files{i});
end

dirs  = {d( [d.isdir]).name}';
dirs  = dirs(3:end); % the first two are . and ..

for i=1:length(dirs)
  files = cat(1, files, findfiles(fullfile(p, dirs{i})));
end


function [trackers, indices] = order_trackers(trackers, order)
% order_trackers Change the order of trackers
%
% Change the order of trackers in a cell array of tracker structures.
%
% The functions upports the following ordering options:
%
% - IdentifierAscending
% - IdentifierDescending
%
% Input:
% - trackers: Cell array of tracker structures.
% - order: A string that defines the order of trackers. See the description above for available options.
%
% Output:
% - trackers: A modified cell array of tracker structures.
% - indices: The mapping from the old to the new array.

if nargin < 2
    order = 'identifierascending';
end;

order = lower(order);

switch order
    case 'identifierascending'
        identifiers = cellfun(@(t) t.identifier, trackers, 'UniformOutput', false);
        [~, indices] = sort(identifiers);
    case 'identifierdescending'
        identifiers = cellfun(@(t) t.identifier, trackers, 'UniformOutput', false);
        [~, indices] = sort(identifiers);
        indices = fliplr(indices);
    otherwise
        return;
end;

trackers = trackers(indices);


function EEG = highPassAndICA(EEG, varargin)
% Perform a high-pass filter and ICA on data that has been Prepped
try
    params = vargin2struct(varargin);
    if isfield(EEG.etc, 'noiseDetection') && ...
            isfield(EEG.etc.noiseDetection, 'detrend') && ...
            ~isfield(params, 'detrendChannels')
        params.detrendChannels = EEG.etc.noiseDetection.detrend.detrendChannels;
    end
    [EEG, detrend]  = removeTrend(EEG, params);
    EEG.etc.highPassAndICA.detrend = detrend;

    %% Perform ICA on the data
    if isfield(EEG.etc, 'noiseDetection') && ...
            isfield(EEG.etc.noiseDetection, 'reference')
        referenceChannels = ...
            EEG.etc.noiseDetection.reference.referenceChannels;
        interpolatedChannels = ...
            EEG.etc.noiseDetection.reference.interpolatedChannels.all;
        channelsLeft = setdiff(referenceChannels, interpolatedChannels);
        pcaDim = length(channelsLeft) - 1;
        fprintf('%s: pcaDim = %d\n', EEG.setname, pcaDim);
        EEG = pop_runica(EEG, 'icatype', 'cudaica', 'extended', 1, ...
            'chanind', referenceChannels, 'pca', pcaDim);
        EEG.etc.highPassAndICA.ICA = ...
            ['extended infomax with pca Dim ' num2str(pcaDim)];
        EEG.etc.noiseDetection.reference = ...
                   cleanupReference(EEG.etc.noiseDetection.reference);
%     else
%         EEG = pop_runica(EEG, 'icatype', 'runica', 'extended', 1);
%         EEG.etc.highPassAndICA.ICA = 'runica extended infomax';
    end

catch mex
    errorMessages.highPassAndICA = ['failed highPassAndICA: ' getReport(mex)];
    errorMessages.status = 'unprocessed';
    EEG.etc.highPassAndICA.errors = errorMessages;
    fprintf(2, '%s\n', errorMessages.highPassAndICA);
end


function O = PetscOpenSocket(socketnumber)
%
%   O = PetscOpenSocket(socketnumber) - waits for a socket connection (from PETSc socket viewer)
%
%  This provides an object oriented interface to the PETSc provided Matlab routines sopen(), sread() and sclose()
%  allowing PETSc  MATLAB utilities like PetscBinaryRead.m to work cleanly with either binary
%  files or sockets
%
if nargin == 0
  S = struct('fd', sopen());
else
  S = struct('fd', sopen(socketnumber));
end
O = class(S,'PetscOpenSocket');


% ------------------------------------------------------------------------
%  Copyright (C)
%  ETHZ - Computer Vision Lab
%
%  Jordi Pont-Tuset <jponttuset@vision.ee.ethz.ch>
%  September 2015
% ------------------------------------------------------------------------
% This file is part of the BOP package presented in:
%    Pont-Tuset J, Van Gool, Luc,
%    "Boosting Object Proposals: From Pascal to COCO"
%    International Conference on Computer Vision (ICCV) 2015.
% Please consider citing the paper if you use this code.
% ------------------------------------------------------------------------
function db_root_dir = db_root_dir( database )
if strcmp(database,'Pascal') || strcmp(database,'COCO') ||  strcmp(database,'SBD') ||  strcmp(database,'ILSVRC') ||  strcmp(database,'BSDS500') || strcmp(database,'bsds_object_gt')
    db_root_dir = fullfile('/srv/glusterfs/jpont/gt_dbs/',database);
else
    error(['Unknown database: ' database]);
end

end


function imdb = vocSetup(varargin)
opts.edition = '07' ;
opts.dataDir = fullfile('data','voc07') ;
opts.archiveDir = fullfile('data','archives') ;
opts.includeDetection = false ;
opts.includeSegmentation = false ;
opts.includeTest = false ;
opts = vl_argparse(opts, varargin) ;

% Download data
if ~exist(fullfile(opts.dataDir,'Annotations')), download(opts) ; end

% Source images and classes
imdb.paths.image = esc(fullfile(opts.dataDir, 'JPEGImages', '%s.jpg')) ;
imdb.sets.id = uint8([1 2 3]) ;
imdb.sets.name = {'train', 'val', 'test'} ;
imdb.classes.id = uint8(1:20) ;
imdb.classes.name = {...
  'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', ...
  'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', ...
  'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor'} ;
imdb.classes.images = cell(1,20) ;
imdb.images.id = [] ;
imdb.images.name = {} ;
imdb.images.set = [] ;
index = containers.Map() ;
[imdb, index] = addImageSet(opts, imdb, index, 'train', 1) ;
[imdb, index] = addImageSet(opts, imdb, index, 'val', 2) ;
if opts.includeTest, [imdb, index] = addImageSet(opts, imdb, index, 'test', 3) ; end

% Source segmentations
if opts.includeSegmentation
  n = numel(imdb.images.id) ;
  imdb.paths.objectSegmentation = esc(fullfile(opts.dataDir, 'SegmentationObject', '%s.png')) ;
  imdb.paths.classSegmentation = esc(fullfile(opts.dataDir, 'SegmentationClass', '%s.png')) ;
  imdb.images.segmentation = false(1, n) ;
  [imdb, index] = addSegmentationSet(opts, imdb, index, 'train', 1) ;
  [imdb, index] = addSegmentationSet(opts, imdb, index, 'val', 2) ;
  if opts.includeTest, [imdb, index] = addSegmentationSet(opts, imdb, index, 'test', 3) ; end
end

% Compress data types
imdb.images.id = uint32(imdb.images.id) ;
imdb.images.set = uint8(imdb.images.set) ;
for i=1:20
  imdb.classes.images{i} = uint32(imdb.classes.images{i}) ;
end

% Source detections
if opts.includeDetection
  imdb.aspects.id = uint8(1:5) ;
  imdb.aspects.name = {'front', 'rear', 'left', 'right', 'misc'} ;
  imdb = addDetections(opts, imdb) ;
end

% Check images on disk and get their size
imdb = getImageSizes(imdb) ;

% -------------------------------------------------------------------------
function download(opts)
% -------------------------------------------------------------------------
switch opts.edition
  case '07',
    url='' ;
  case '08',
    url='' ;
  case '09'
    url='' ;
  case '10'
    url='http://host.robots.ox.ac.uk:8080/pascal_trainval/VOCtrainval_03-May-2010.tar' ;
  case '11'
    url='http://host.robots.ox.ac.uk:8080/pascal_trainval/VOCtrainval_25-May-2011.tar' ;
  case '12'
    url='http://host.robots.ox.ac.uk:8080/pascal_trainval/VOCtrainval_11-May-2012.tar' ;
end
trainvalData=sprintf('VOC20%strainval.tar',opts.edition) ;
testData=sprintf('VOC20%stest.tar', opts.edition) ;

if ~exist(opts.archiveDir), mkdir(opts.archiveDir) ; end
archivePath=fullfile(opts.archiveDir, trainvalData) ;
if ~exist(archivePath)
  fprintf('%s: downloading %s to %s\n', mfilename, url, archivePath) ;
  urlwrite(url, archivePath) ;
end
fprintf('%s: decompressing and rearranging %s\n', mfilename, archivePath) ;
untar(archivePath, opts.dataDir) ;
switch opts.edition
  case '11'
    % Decompresses in TrainVal/VOCdevkit, Test/VOCdevkit (sigh!)
    movefile(fullfile(opts.dataDir, 'TrainVal'), fullfile(opts.dataDir,'Test')) ;
  otherwise
    % Decomporesses directly in VOCdevkit
end

if opts.includeTest
  archivePath=fullfile(opts.archiveDir, testData) ;
  if ~exist(archivePath)
    error('Cannot download the test data automatically. Please download the file %s manually from the PASCAL test server.', archivePath)
  end
  fprintf('%s: decompressing and rearranging %s\n', mfilename, archivePath) ;
  untar(archivePath, opts.dataDir) ;
end
switch opts.edition
  case '11'
    movefile(fullfile(opts.dataDir, 'Test', 'VOCdevkit', sprintf('VOC20%s',opts.edition), '*'), opts.dataDir) ;
    rmdir(fullfile(opts.dataDir, 'Test'),'s') ;
  otherwise
    movefile(fullfile(opts.dataDir, 'VOCdevkit', sprintf('VOC20%s',opts.edition), '*'), opts.dataDir) ;
    rmdir(fullfile(opts.dataDir, 'VOCdevkit'),'s') ;
end

% -------------------------------------------------------------------------
function [imdb, index] = addImageSet(opts, imdb, index, setName, setCode)
% -------------------------------------------------------------------------
j = length(imdb.images.id) ;
for ci = 1:length(imdb.classes.name)
  className = imdb.classes.name{ci} ;
  annoPath = fullfile(opts.dataDir, 'ImageSets', 'Main', ...
    [className '_' setName '.txt']) ;
  fprintf('%s: reading %s\n', mfilename, annoPath) ;
  [names,labels] = textread(annoPath, '%s %f') ;
  for i=1:length(names)
    if ~index.isKey(names{i})
      j = j + 1 ;
      index(names{i}) = j ;
      imdb.images.id(j) = j ;
      imdb.images.set(j) = setCode ;
      imdb.images.name{j} = names{i} ;
      imdb.images.classification(j) = true ;
    else
      j = index(names{i}) ;
    end
    if labels(i) > 0, imdb.classes.images{ci}(end+1) = j ; end
  end
end

% -------------------------------------------------------------------------
function [imdb, index] = addSegmentationSet(opts, imdb, index, setName, setCode)
% -------------------------------------------------------------------------
segAnnoPath = fullfile(opts.dataDir, 'ImageSets', 'Segmentation', [setName '.txt']) ;
fprintf('%s: reading %s\n', mfilename, segAnnoPath) ;
segNames = textread(segAnnoPath, '%s') ;
j = numel(imdb.images.id) ;
for i=1:length(segNames)
  if index.isKey(segNames{i})
    k = index(segNames{i}) ;
    imdb.images.segmentation(k) = true ;
    imdb.images.set(k) = setCode ;
  else
    j = j + 1 ;
    index(segNames{i}) = j ;
    imdb.images.id(j) = j ;
    imdb.images.set(j) = setCode ;
    imdb.images.name{j} = segNames{i} ;
    imdb.images.classification(j) = false ;
    imdb.images.segmentation(j) = true ;
  end
end

% -------------------------------------------------------------------------
function imdb = getImageSizes(imdb)
% -------------------------------------------------------------------------
for j=1:numel(imdb.images.id)
  info = imfinfo(sprintf(imdb.paths.image, imdb.images.name{j})) ;
  imdb.images.size(:,j) = uint16([info.Width ; info.Height]) ;
  fprintf('%s: checked image %s [%d x %d]\n', mfilename, imdb.images.name{j}, info.Height, info.Width) ;
end

% -------------------------------------------------------------------------
function imdb = addDetections(opts, imdb)
% -------------------------------------------------------------------------
rois = {} ;
k = 0 ;
fprintf('%s: getting detections for %d images\n', mfilename, numel(imdb.images.id)) ;
for j=1:numel(imdb.images.id)
  fprintf('.') ; if mod(j,80)==0,fprintf('\n') ; end
  name = imdb.images.name{j} ;
  annoPath = fullfile(opts.dataDir, 'Annotations', [name '.xml']) ;
  if ~exist(annoPath, 'file')
    if imdb.images.classification(j) && imdb.images.set(j) ~= 3
      warning('Could not find detection annotations for image ''%s''. Skipping.', name) ;
    end
    continue ;
  end

  doc = xmlread(annoPath) ;
  x = parseXML(doc, doc.getDocumentElement()) ;

  %   figure(1) ; clf ;
  %   imagesc(imread(sprintf(imdb.paths.image,imdb.images.name{j}))) ;

  for q = 1:numel(x.object)
    xmin = sscanf(x.object(q).bndbox.xmin,'%d') ;
    ymin = sscanf(x.object(q).bndbox.ymin,'%d') ;
    xmax = sscanf(x.object(q).bndbox.xmax,'%d') - 1 ;
    ymax = sscanf(x.object(q).bndbox.ymax,'%d') - 1 ;

    k = k + 1 ;
    roi.id = k ;
    roi.image = imdb.images.id(j) ;
    roi.class = find(strcmp(x.object(q).name, imdb.classes.name)) ;
    roi.box = [xmin;ymin;xmax;ymax] ;
    roi.difficult = logical(sscanf(x.object(q).difficult,'%d')) ;
    roi.truncated = logical(sscanf(x.object(q).truncated,'%d')) ;
    if isfield(x.object(q),'occluded')
      roi.occluded = logical(sscanf(x.object(q).occluded,'%d')) ;
    else
      roi.occluded = false ;
    end
    switch x.object(q).pose
      case 'frontal', roi.aspect = 1 ;
      case 'rear', roi.aspect = 2 ;
      case {'sidefaceleft', 'left'}, roi.aspect = 3 ;
      case {'sidefaceright', 'right'}, roi.aspect = 4 ;
      case {'','unspecified'}, roi.aspect = 5 ;
      otherwise, error(sprintf('Unknown view ''%s''', x.object(q).pose)) ;
    end
    rois{k} = roi ;

    %     hold on ;
    %     label=sprintf('%s %s d:%d t:%d o:%d',...
    %       imdb.classes.name{roi.class}, ...
    %       imdb.aspects{roi.aspect}, ...
    %       roi.difficult, ...
    %       roi.truncated, ...
    %       roi.occluded) ;
    %     plotbox(roi.box,'label',label) ;
    %     drawnow ;
  end
end
fprintf('\n') ;

rois = horzcat(rois{:}) ;
imdb.objects = struct(...
    'id', uint32([rois.id]), ...
    'image', uint32([rois.image]), ...
    'class', uint8([rois.class]), ...
    'box', single([rois.box]), ...
    'difficult', [rois.difficult], ...
    'truncated', [rois.truncated], ...
    'occluded', [rois.occluded], ...
    'aspect', uint8([rois.aspect])) ;

% -------------------------------------------------------------------------
function value = parseXML(doc, x)
% -------------------------------------------------------------------------
text = {''} ;
opts = struct ;
if x.hasChildNodes
  for c = 1:x.getChildNodes().getLength()
    y = x.getChildNodes().item(c-1) ;
    switch y.getNodeType()
      case doc.TEXT_NODE
        text{end+1} = lower(char(y.getData())) ;
      case doc.ELEMENT_NODE
        param = lower(char(y.getNodeName())) ;
        if strcmp(param, 'part'), continue ; end
        value = parseXML(doc, y) ;
        if ~isfield(opts, param)
          opts.(param) = value ;
        else
          opts.(param)(end+1) = value ;
        end
    end
  end
  if numel(fieldnames(opts)) > 0
    value = opts ;
  else
    value = strtrim(horzcat(text{:})) ;
  end
end

% -------------------------------------------------------------------------
function str=esc(str)
% -------------------------------------------------------------------------
str = strrep(str, '\', '\\') ;


function [bodyPlotted] = ma_plotFrame(hFig, mAxes, maData, stateLog, time, prevBody, orbitToPlot, celBodyData, handles)
%ma_plotFrame Summary of this function goes here
%   Detailed explanation goes here
    global GLOBAL_VideoWriter GLOBAL_isRecording;
    persistent usrScMarker hCBodySurf hCBodySurfXform preCbRotateAngle hCbGrdStn hOtherScPts hOtherScOrbits hCbGrdStnText hAnnote hChildBodies hChildBodyOrbits hSunBody hLight prevFrameTime curFrameTime;

    if(~isempty(usrScMarker) && ishandle(usrScMarker))
        delete(usrScMarker);
        usrScMarker = []; %#ok<NASGU>
    end

    [orbitToPlot, stateLog] = ma_getOrbitToPlot(stateLog, time);
    stateLogRow = getStateLogRowAtTime(stateLog, time);

    if(isempty(preCbRotateAngle))
        preCbRotateAngle = 0;
    end

    if(isempty(prevFrameTime) && isempty(curFrameTime))
        prevFrameTime = clock;
        curFrameTime = prevFrameTime;
    else
        curFrameTime = clock;
    end

    bodyPlotted = stateLogRow(8);
    if(bodyPlotted ~= prevBody)
        unfreezeColors(mAxes);
        cla(mAxes,'reset');
        [hCBodySurf] = plotStateLog(stateLog, handles, false, false, false, false, orbitToPlot, [], maData, celBodyData, mAxes, hFig);
        freezeColors(mAxes);
        material(hCBodySurf,'dull');
        set(hCBodySurf,'AmbientStrength',0.1);
        hCBodySurfXform = hgtransform(mAxes);
        set(hCBodySurf,'Parent',hCBodySurfXform);

        preCbRotateAngle = 0;

        if(~isnan(prevBody))
            set(handles.cameraSrcCombo,'Value',1);
            setSrcComboUserData(handles.cameraSrcCombo, handles, false);
            set(handles.cameraTgtCombo,'Value',2);
            setTgtComboUserData(handles.cameraTgtCombo, handles, false);
        end
        setCamSrcTgtComboBoxes(handles, time);

        axisWasReset = true;
    else
        axisWasReset = false;
    end

    bodyInfo = celBodyData.getBodyInfoById(bodyPlotted);
    if(not(isempty(hCBodySurfXform)) && isvalid(hCBodySurfXform))
        M = getBodyXformMatrix(time, bodyInfo, bodyInfo.getBodyCenteredInertialFrame());
        set(hCBodySurfXform,'Matrix',M);
    end

    if(axisWasReset && ~strcmpi(get(handles.cameraTypeCombo,'UserData'),'Inertially Fixed'))
%         axisLimMult = 15;
        axisLimMult = get(handles.axesScaleFactorText,'UserData');
    else
        axisLimMult = 1;
    end

    lims = zeros(0,2);
    lims(1,:) = get(mAxes,'XLim');
    lims(2,:) = get(mAxes,'YLim');
    lims(3,:) = get(mAxes,'ZLim');
    maxMax = axisLimMult * max(max(lims));
    maxMaxArr = [-maxMax maxMax -maxMax maxMax -maxMax maxMax];
    cLim = get(mAxes,'CLim');
    maxMaxArr = [maxMaxArr, cLim];
    axis(maxMaxArr);

    bodyID = stateLogRow(1,8);
    bodyInfo = getBodyInfoByNumber(bodyID, celBodyData);

    bgColors = get(handles.backgroundColorCombo,'UserData');
    showGrid = get(handles.showGridCheckbox,'UserData');
    if(strcmpi(showGrid,'on'))
        set(mAxes,'Color',bgColors(1),'XColor',bgColors(2),'YColor',bgColors(3),'ZColor',bgColors(4));
    else
        set(mAxes,'Color',bgColors(1),'XColor',bgColors(1),'YColor',bgColors(1),'ZColor',bgColors(1));
    end
    grid(mAxes,showGrid);

	switch(get(handles.cameraTypeCombo,'UserData'))
        case 'Inertially Fixed'
            azView = get(handles.azOffsetText,'UserData');
            elView = get(handles.elOffsetText,'UserData');

            view(mAxes, [azView,elView]);
        case 'Spacecraft Fixed'
            camSrcStr = get(handles.cameraSrcCombo,'UserData');
            camTgtStr = get(handles.cameraTgtCombo,'UserData');

            [typeStrSrc, ~, idStrSrc] = parseSrcTgtStrings(camSrcStr);
            [typeStrTgt, ~, idStrTgt] = parseSrcTgtStrings(camTgtStr);

            rPosCam = getPositOfObject(maData, time, stateLogRow, typeStrSrc, idStrSrc, bodyInfo, celBodyData);
            rPosTgt = getPositOfObject(maData, time, stateLogRow, typeStrTgt, idStrTgt, bodyInfo, celBodyData);

            camViewVect = rPosTgt - rPosCam;

            [cAz,cEl,cR] = cart2sph(camViewVect(1),camViewVect(2),camViewVect(3));

            azAdd = deg2rad(get(handles.azOffsetText,'UserData'));
            elAdd = deg2rad(get(handles.elOffsetText,'UserData'));
            rngAdd = get(handles.rngOffsetText,'UserData');

            cAz = cAz + azAdd;
            cEl = cEl - elAdd;
            cR = cR + rngAdd;

            [cX,xY,cZ] = sph2cart(cAz,cEl,cR);
            camViewVect = [cX,xY,cZ];

            rPosCam = rPosTgt - camViewVect;

            campos(mAxes,rPosCam); camtarget(mAxes,rPosTgt);
            camva(mAxes,get(handles.fieldOfViewText,'UserData'));
    end

    topLevelBodyInfo = getTopLevelCentralBody(celBodyData);
    rVectSun = getAbsPositBetweenSpacecraftAndBody(time, [0,0,0]', bodyInfo, topLevelBodyInfo, celBodyData);
    if(norm(rVectSun) < 0.01)
        rVectSun = [0 0 0.01];
    end

    rVectSun = normVector(rVectSun);
    if(isempty(hLight) || ~ishghandle(hLight))
        hLight = light('Position',rVectSun,'Parent',mAxes,'style','infinite');
    else
        set(hLight,'Position',rVectSun);
    end

    hold(mAxes,'on');
    markerColor = get(handles.spacecraftMarkerColorCombo,'UserData');
    lineSpec = [get(handles.spacecraftMarkerCombo,'UserData'),markerColor];
    markerSize = get(handles.scMarkerSizeCombo,'UserData');
    usrScMarker = plot3(mAxes, stateLogRow(2),stateLogRow(3),stateLogRow(4),lineSpec,'MarkerSize',markerSize,'MarkerFaceColor',markerColor);
    hold(mAxes,'off');

%     cbSpinAngle = getBodySpinAngle(bodyInfo, time);
%     dAlpha = rad2deg(cbSpinAngle) - preCbRotateAngle;
%     rotate(hCBodySurf,[0,0,1],dAlpha,[0,0,0]);
%     set(hCBodySurf,'NormalMode','auto');
%     preCbRotateAngle = rad2deg(cbSpinAngle);

    if(~isempty(hCbGrdStn(ishghandle(hCbGrdStn))))
        delete(hCbGrdStn(ishghandle(hCbGrdStn))); hCbGrdStn = [];
    end

    if(get(handles.showGroundStationsCheckbox,'UserData')==1)
        stations = maData.spacecraft.stations;
        bdyStnFHdl = @(stnStruct) plotLocOfGrndStation(mAxes, stnStruct, bodyID, time, [0,0,0]', bodyInfo);

        [hCbGrdStn] = cellfun(bdyStnFHdl, stations,'UniformOutput',false);
        hCbGrdStn = [hCbGrdStn{:}];
    end

    delete(hOtherScPts(ishghandle(hOtherScPts)));
    delete(hOtherScOrbits(ishghandle(hOtherScOrbits)));
    if(get(handles.showOtherScCheckbox,'UserData')==1)
        otherSCs = maData.spacecraft.otherSC; %hOtherScOrbits

        otherScFHdl = @(oScStruct) plotLocOfOtherSC(mAxes, oScStruct, bodyID, time, [0,0,0]', bodyInfo, true, true);

        [hOtherScPts, hOtherScOrbits] = cellfun(otherScFHdl, otherSCs,'UniformOutput',false);
        hOtherScPts = [hOtherScPts{:}];
        hOtherScOrbits = [hOtherScOrbits{:}];
    end

    delete(hChildBodies(ishghandle(hChildBodies))); hChildBodies = [];
    showChildBodies = get(handles.showChildBodiesCheckbox,'UserData');
    showChildBodyOrbits = get(handles.showChildBodyOrbitsCheckbox,'UserData');
    if(showChildBodies == 1 || showChildBodyOrbits == 1)
        [children, ~] = getChildrenOfParentInfo(celBodyData, bodyInfo.name);
        for(i=1:length(children)) %#ok<*NO4LP>
            child = children{i};

            if(showChildBodies==1)
                [rVect, ~] = getStateAtTime(child, time, bodyInfo.gm);

                useR = child.radius;
                mColor = colorFromColorMap(child.bodycolor);

                [cX, cY, cZ] = sphere(30);
                hold(mAxes,'on')
                hChildBodies(end+1) = plot3(rVect(1), rVect(2), rVect(3),'Marker','o','MarkerEdgeColor',mColor,'MarkerFaceColor',mColor,'MarkerSize',3); %#ok<AGROW>
                hold(mAxes,'off')
                hChildBodies(end+1) = surface(rVect(1) + useR*cX, rVect(2) + useR*cY, rVect(3) + useR*cZ); %#ok<AGROW>
                colormap(mAxes, child.bodycolor)
                freezeColors(mAxes);
            end

            if(showChildBodyOrbits == 1)
                if(axisWasReset || length(hChildBodyOrbits) < length(children))
                    if(length(hChildBodyOrbits) < length(children))
                        if(i==1)
                            delete(hChildBodyOrbits(ishghandle(hChildBodyOrbits)));
                            hChildBodyOrbits = [];
                        end
                    end
                    hChildBodyOrbits(end+1) = plotBodyOrbit(child, '', bodyInfo.gm, false, mAxes, 0.5, '--'); %#ok<AGROW>
                end
            else
                delete(hChildBodyOrbits(ishghandle(hChildBodyOrbits))); hChildBodyOrbits = [];
            end
        end
    elseif(showChildBodyOrbits ~= 1)
        delete(hChildBodyOrbits(ishghandle(hChildBodyOrbits))); hChildBodyOrbits = [];
    end

    aShowUT = get(handles.annoteShowUTCheckbox,'UserData');
	aShowOrbit = get(handles.annoteShowOrbitCheckbox,'UserData');
    aShowLatLong = get(handles.annoteShowLatLongCheckbox,'UserData');
    aShowMass = get(handles.annoteShowMassCheckbox,'UserData');
    aShowFps = get(handles.showFpsCheckbox,'UserData');
    aShowEvent = get(handles.showEventNameCheckbox,'UserData');

    if(aShowUT==1 || aShowOrbit==1 || aShowLatLong==1 || aShowMass==1 || aShowFps==1 || aShowEvent==1)
        annonStr = cell(0,1);

        if(aShowUT==1)
            [year, day, hour, minute, sec] = convertSec2YearDayHrMnSec(time);
            dateStr = formDateStr(year, day, hour, minute, sec);
            annonStr{end+1} = dateStr;
        end

        if(aShowOrbit==1)
            rVect = stateLogRow(2:4);
            vVect = stateLogRow(5:7);
            gmu = bodyInfo.gm;
            [sma, ecc, inc, raan, arg, tru] = getKeplerFromState(rVect,vVect,gmu);
            oStr = sprintf('Orbit\n   Orbiting=%s\n   SMA=%g km\n   Ecc=%g\n   Inc=%g deg\n   RAAN=%g deg\n   Arg=%g deg\n   Tru=%g deg', bodyInfo.name, sma, ecc, rad2deg(inc), rad2deg(raan), rad2deg(arg), rad2deg(tru));
            annonStr{end+1} = oStr;
        end

        if(aShowEvent==1)
            eventName = maData.script{stateLogRow(13)}.name;
            annonStr{end+1} = sprintf('Event: %s', eventName);
        end

        if(aShowLatLong==1)
            rVect = stateLogRow(2:4)';
            vVect = stateLogRow(5:7)';
            [lat, long, alt] = getLatLongAltFromInertialVect(time, rVect, bodyInfo, vVect);
            ffStr = sprintf('Rotating Frame Position\n   Lat.=%g deg\n   Long.=%g deg\n   Alt.=%g km', rad2deg(lat), rad2deg(long), alt);
            annonStr{end+1} = ffStr;
        end

        if(aShowMass==1)
            totMass = sum(stateLogRow(9:12));
            dryMass = sum(stateLogRow(9));
            fuelOxMass = sum(stateLogRow(10));
            mpMass = sum(stateLogRow(11));
            xeMass = sum(stateLogRow(12));

            propNames = maData.spacecraft.propellant.names;
            if(length(propNames{1}) > 11)
                propNames{1} = propNames{1}(1:11);
            end
            if(length(propNames{2}) > 11)
                propNames{2} = propNames{2}(1:11);
            end
            if(length(propNames{3}) > 11)
                propNames{3} = propNames{3}(1:11);
            end

            massStr = sprintf('Spacecraft Masses\n   Total Mass=%g ton\n   Dry Mass=%g ton\n   %s=%g ton\n   %s=%g ton\n   %s=%g ton', totMass, dryMass, propNames{1}, fuelOxMass, ...
                              propNames{2}, mpMass, propNames{3}, xeMass);
            annonStr{end+1} = massStr;
        end

        if(aShowFps==1)
            fps = 1/etime(curFrameTime,prevFrameTime);
            if(~isfinite(fps))
                fps = 0;
            end
            annonStr{end+1} = sprintf('Frame Rate\n   FPS=%g',fps);
        end

%         annonStr =  strtrim(char(annonStr));
        annonStrN = {};
        for(i=1:length(annonStr))
            ss = strsplit(annonStr{i},char(10))';
            for(j=1:length(ss))
                ss{j} = horzcat(ss{j},'          ');
            end
            annonStrN = vertcat(annonStrN,ss); %#ok<AGROW>
        end

        if(isempty(hAnnote) || ~ishghandle(hAnnote))
            hAnnote = annotation('textbox',[0.77 0.84 0.22 0.1], 'String',annonStrN,'Tag','dataText','VerticalAlignment','top','BackgroundColor','w','FontName','FixedWidth','FontSize',8,'FitBoxToText','on','Margin',5);
        else
            set(hAnnote,'String',annonStrN);
        end
    else
        delete(hAnnote(ishghandle(hAnnote)));
        delete(findall(mAxes,'Tag','dataText'));
    end

    prevFrameTime = curFrameTime;

    if(GLOBAL_isRecording)
        GLOBAL_VideoWriter.writeVideo(getframe(hFig,get(mAxes,'Position')));
    end

%     shading(mAxes,'interp');
    drawnow;
end

function rPosCam = getPositOfObject(maData, time, stateLogRow, typeStr, idStr, bodyInfo, celBodyData)
    switch(typeStr)
        case 'sc'
            rPosCam = [stateLogRow(2),stateLogRow(3),stateLogRow(4)];
        case 'cb'
            rPosCam = [0,0,0];
        case 'osc'
            rPosCam = getRelPositionOfOtherSpacecraft(maData, idStr, stateLogRow(1), bodyInfo, celBodyData);
        case 'grd'
            rPosCam = getRelPositionOfGroundStation(maData, idStr, stateLogRow(1), bodyInfo, celBodyData);
        case 'chBd'
            bodyOther = getBodyInfoByNumber(str2double(idStr), celBodyData);
            [rVect, ~] = getStateAtTime(bodyOther, time, bodyInfo.gm);

            rPosCam = rVect;
        otherwise
            error('Unknown type string when computing position of object for mission animator camera.');
    end

    rPosCam = reshape(rPosCam,1,3);
end

function rPosCam = getRelPositionOfGroundStation(maData, grnID, time, mainScOrbitingBodyInfo, celBodyData)
    lookingFor = str2double(grnID);

    station = [];
    stations = maData.spacecraft.stations;
    for(i=1:length(stations))
        stationTemp = stations{i};
        if(abs(stationTemp.id == lookingFor) < 1E-12)
            station = stationTemp;
            break;
        end
    end

    if(isempty(station))
        error('Did not find ground station with ID %s for use in setting camera src/tgt.', oscID);
    end

    bodyInfoStn = getBodyInfoByNumber(station.parentID, celBodyData);

    lat = station.lat;
    long = station.long;
    alt = station.alt;

    rVectStn = getInertialVectFromLatLongAlt(time, lat, long, alt, bodyInfoStn, [NaN;NaN;NaN]);
    rPosCam = -getAbsPositBetweenSpacecraftAndBody(time, rVectStn, bodyInfoStn, mainScOrbitingBodyInfo, celBodyData); %might need a negative sign here
end

function rPosCam = getRelPositionOfOtherSpacecraft(maData, oscID, time, mainScOrbitingBodyInfo, celBodyData)
    lookingFor = str2double(oscID);

    otherSC = [];
    otherSCs = maData.spacecraft.otherSC;
    for(i=1:length(otherSCs))
        otherSCTemp = otherSCs{i};
        if(abs(otherSCTemp.id - lookingFor) < 1E-12)
            otherSC = otherSCTemp;
            break;
        end
    end

    if(isempty(otherSC))
        error('Did not find other spacecraft with ID %s for use in setting camera src/tgt.', oscID);
    end

    bodyInfoOSC = getBodyInfoByNumber(otherSC.parentID, celBodyData);

    epoch = otherSC.epoch;
    sma = otherSC.sma;
    ecc = otherSC.ecc;
    inc = deg2rad(otherSC.inc);
    raan =  deg2rad(otherSC.raan);
    arg = deg2rad(otherSC.arg);
    mean = deg2rad(otherSC.mean);

    inputOrbit = [sma, ecc, inc, raan, arg, mean, epoch];
    otherScInfo = getBodyInfoStructFromOrbit(inputOrbit);

    [rVectSC, ~] = getStateAtTime(otherScInfo, time, bodyInfoOSC.gm);
    rPosCam = -getAbsPositBetweenSpacecraftAndBody(time, rVectSC, bodyInfoOSC, mainScOrbitingBodyInfo, celBodyData); %might need a negative sign here
end

function [typeStr, nameStr, idStr] = parseSrcTgtStrings(str)
    pattern1 = '([\w]*): ([\w ]*)';
    pattern2 = '(id: ([0-9\.]+)\)*?';
    tokens1 = regexp(str,pattern1,'tokens');
    tokens2 = regexp(str,pattern2,'tokens');

    typeStr = strtrim(tokens1{1}{1});
    nameStr = strtrim(tokens1{1}{2});
    if(~isempty(tokens2))
        idStr = tokens2{1}{1};
    else
        idStr = '';
    end
end

function [hCbGrdStn] = plotLocOfGrndStation(hAxis, stnStruct, validBodyID, ut, posOffset, bodyInfo)
    hCbGrdStn = [];
    if(stnStruct.parentID == validBodyID)
        lat = stnStruct.lat;
        long = stnStruct.long;
        alt = stnStruct.alt;
        color = stnStruct.color;
        markerSym = stnStruct.markerSymbol;
        rVectECI = getInertialVectFromLatLongAlt(ut, lat, long, alt, bodyInfo, [NaN;NaN;NaN]);

        hold on;
        pos = rVectECI+posOffset;
        hCbGrdStn = plot3(hAxis, pos(1), pos(2), pos(3), markerSym, 'Color',color, 'MarkerFaceColor',color, 'MarkerSize', 6);
%         hCbGrdStnText = text(pos(1), pos(2), pos(3),stnStruct.name,'BackgroundColor','w');
        hold off;
    end
end


function imdb = fmd_get_database(fmdDir, varargin)
opts.seed = 0 ;
opts = vl_argparse(opts, varargin) ;

rng(opts.seed, 'twister') ;

imdb.imageDir = fullfile(fmdDir, 'image') ;
imdb.maskDir = fullfile(fmdDir, 'mask') ;

cats = dir(imdb.imageDir) ;
cats = cats([cats.isdir] & ~ismember({cats.name}, {'.','..'})) ;
imdb.classes.name = {cats.name} ;
imdb.images.id = [] ;

for c=1:numel(cats)
  ims = dir(fullfile(imdb.imageDir, imdb.classes.name{c}, '*.jpg'));
  %imdb.images.name{c} = fullfile(imdb.classes.name{c}, {ims.name}) ;
  imdb.images.name{c} = cellfun(@(S) fullfile(imdb.classes.name{c}, S), ...
    {ims.name}, 'Uniform', 0);
  imdb.images.label{c} = c * ones(1,numel(ims)) ;
  if numel(ims) ~= 100, error('ops') ; end
  sets = [1 * ones(1,40), 2 * ones(1,10), 3 * ones(1,50)] ;
  imdb.images.set{c} = sets(randperm(100)) ;
end
imdb.images.name = horzcat(imdb.images.name{:}) ;
imdb.images.label = horzcat(imdb.images.label{:}) ;
imdb.images.set = horzcat(imdb.images.set{:}) ;
imdb.images.id = 1:numel(imdb.images.name) ;

imdb.segments = imdb.images ;
imdb.segments.imageId = imdb.images.id ;
imdb.segments.mask = strrep(imdb.images.name, 'image', 'mask') ;

% make this compatible with the OS imdb
imdb.meta.classes = imdb.classes.name ;
imdb.meta.inUse = true(1,numel(imdb.meta.classes)) ;
imdb.segments.difficult = false(1, numel(imdb.segments.id)) ;


% Codes for CVPR-15 work `Face Alignment by Coarse-to-Fine Shape Searching'
% Any question please contact Shizhan Zhu: zhshzhutah2@gmail.com
% Released on July 25, 2015

function varargout = indexingData(varargin)
%varargout = indexingData(ind,varargin)
%   every element in varargin will be extracted according to ind(index),
%   and the relative output will be sent to varargout.
%   PLEASE NOTE indexing only refer to the 1st dimension!

varargout = cell(1,nargin-1);
ind = varargin{1};
for i = 2:nargin
    k = varargin{i};
    if size(k,1) == 1
        k = k';
    end
    varargout{i-1} = k(ind,:);
end

end


function varargout=myidentification(varargin)

[varargout{1:nargout}]=dsge_tools.identification(varargin{:});

end


function [OutputError,basler_vid,frame_nr_display] = PIVlab_capture_basler_synced_start(nr_of_images,ROI_basler)

hgui=getappdata(0,'hgui');
crosshair_enabled = getappdata(hgui,'crosshair_enabled');
sharpness_enabled = getappdata(hgui,'sharpness_enabled');
OutputError=0;

%% Prepare camera
delete(imaqfind); %clears all previous videoinputs
try
	hwinf = imaqhwinfo;
	%imaqreset
catch
	disp('Error: Image Acquisition Toolbox not available!')
end

info = imaqhwinfo(hwinf.InstalledAdaptors{1});

if strcmp(info.AdaptorName,'gentl')
	disp('gentl adaptor found.')
else
	disp('ERROR: gentl adaptor not found. Please got to Matlab file exchange and search for "gentl" to install it.')
end

basler_name = info.DeviceInfo.DeviceName;
disp(['Found camera: ' basler_name])
basler_supported_formats = info.DeviceInfo.SupportedFormats;
%basler_vid = videoinput(info.AdaptorName,1,basler_supported_formats{1});
basler_vid = videoinput(info.AdaptorName);

basler_settings = get(basler_vid);
basler_settings.Source.DeviceLinkThroughputLimitMode = 'off';

%% prepare axes
PIVlab_axis = findobj(hgui,'Type','Axes');
image_handle_basler=imagesc(zeros(ROI_basler(4),ROI_basler(3)),'Parent',PIVlab_axis,[0 2^8]);
setappdata(hgui,'image_handle_basler',image_handle_basler);

frame_nr_display=text(100,100,'Initializing...','Color',[1 1 0]);
colormap default %reset colormap steps
new_map=colormap('gray');
new_map(1:3,:)=[0 0.2 0;0 0.2 0;0 0.2 0];
new_map(end-2:end,:)=[1 0.7 0.7;1 0.7 0.7;1 0.7 0.7];
colormap(new_map);axis image;
set(gca,'ytick',[])
set(gca,'xtick',[])
colorbar

%% set camera parameters for free run or triggered acquisition
triggerconfig(basler_vid, 'hardware');
basler_settings.TriggerSource = 'Line3';
basler_settings.Source.ExposureMode = 'TriggerWidth';
basler_settings.Source.TriggerSource ='Line3';
basler_settings.Source.TriggerSelector='FrameStart';
basler_settings.Source.TriggerMode ='On';
basler_settings.Source.ExposureOverlapTimeMax = basler_settings.Source.SensorReadoutTime;

ROI_basler=[ROI_basler(1)-1,ROI_basler(2)-1,ROI_basler(3),ROI_basler(4)]; %unfortunaletly different definitions of ROI in pco and basler.
basler_vid.ROIPosition=ROI_basler;

%% start acqusition (waiting for trigger)
basler_frames_to_capture = nr_of_images*2;
basler_vid.FramesPerTrigger = basler_frames_to_capture;
if ~isinf(nr_of_images) %only start capturing if save box is ticked.
	flushdata(basler_vid);
	start(basler_vid);
end
preview(basler_vid,image_handle_basler);
drawnow;


function ft_compile_mex(force)

% FT_COMPILE_MEX can be used for compiling most of the FieldTrip MEX files Note that
% this function does not put the MEX files in the correct location in the private
% folders, this is managed by a Bash script. In case you are not working with Git and
% you want to recompile the mex files for your platform, you can find all mex files
% for your platform and move them to a backup directory that is not on your MATLAB
% path. Subsequently you can rtun this function to recompile it on your platform with
% your compiler settings
%
% The standards procedure for compiling mex files is detailled on
% http://www.fieldtriptoolbox.org/development/guidelines/code#compiling_mex_files
%
% Please note that this script does NOT set up your MEX environment for you, so in
% case you haven't selected the C compiler on Windows yet, you need to type 'mex
% -setup' first to choose either the LCC, Borland or Microsoft compiler. If you want
% to use MinGW, you also need to install Gnumex (http://gnumex.sourceforget.net),
% which comes with its own procedure for setting up the MEX environment.
%
% The logic in this script is to first build a list of files that actually need
% compilation for the particular platform that MATLAB is running on, and then to go
% through that list. Functions are added to the list by giving their destination
% directory and (relative to that) the name of the source file (without the .c).
% Optionally, you can specify a list of platform this file needs to be compiled on
% only, and a list of platforms where you don't compile it on. Finally, you can give
% extra arguments to the MEX command, e.g., for including other c-sources or giving
% compiler flags.
%
% See also MEX

% Copyright (C) 2010, Stefan Klanke
%
% $Id$

if nargin<1
  force=false;
end

% Possible COMPUTER types
% GLNX86
% GLNXA64
% PCWIN
% PCWIN64
% MAC
% MACI
% MACI64

[ftver, ftpath] = ft_version;

L = [];
L = add_mex_source(L,'compat/matlablt2010b/@uint64','abs');
L = add_mex_source(L,'compat/matlablt2010b/@uint64','min');
L = add_mex_source(L,'compat/matlablt2010b/@uint64','max');
L = add_mex_source(L,'compat/matlablt2010b/@uint64','plus');
L = add_mex_source(L,'compat/matlablt2010b/@uint64','minus');
L = add_mex_source(L,'compat/matlablt2010b/@uint64','times');
L = add_mex_source(L,'compat/matlablt2010b/@uint64','rdivide');

L = add_mex_source(L,'@config/private','deepcopy');
L = add_mex_source(L,'@config/private','increment');
L = add_mex_source(L,'@config/private','setzero');

L = add_mex_source(L,'realtime/online_mri','ft_omri_smooth_volume');
L = add_mex_source(L,'realtime/src/acquisition/siemens/src', 'sap2matlab', [], [], 'siemensap.c -I../include');

L = add_mex_source(L,'src','ft_getopt');
L = add_mex_source(L,'src','read_16bit');
L = add_mex_source(L,'src','read_24bit');
L = add_mex_source(L,'src','read_ctf_shm', {'GLNX86'});  % only compile on GLNX86
L = add_mex_source(L,'src','write_ctf_shm', {'GLNX86'}); % only compile on GLNX86

L = add_mex_source(L,'src','lmoutr',[],[],'geometry.c -I.');
L = add_mex_source(L,'src','ltrisect',[],[],'geometry.c -I.');
L = add_mex_source(L,'src','plinproj',[],[],'geometry.c -I.');
L = add_mex_source(L,'src','ptriproj',[],[],'geometry.c -I.');
L = add_mex_source(L,'src','routlm',[],[],'geometry.c -I.');
L = add_mex_source(L,'src','solid_angle',[],[],'geometry.c -I.');
L = add_mex_source(L,'src','rfbevent',[],{'PCWIN', 'PCWIN64'},'d3des.c -I.'); % do not compile on WIN32 and WIN64
L = add_mex_source(L,'src','meg_leadfield1');
L = add_mex_source(L,'src','splint_gh');
L = add_mex_source(L,'src','plgndr');

L = add_mex_source(L,'src','ft_spike_sub_crossx');
L = add_mex_source(L,'src','rename');
L = add_mex_source(L,'src','getpid');

L = add_mex_source(L,'src','nanmean');
L = add_mex_source(L,'src','nanstd');
L = add_mex_source(L,'src','nanvar');
L = add_mex_source(L,'src','nansum');
L = add_mex_source(L,'src','nanstd');
L = add_mex_source(L,'src','det2x2');
L = add_mex_source(L,'src','inv2x2');
L = add_mex_source(L,'src','mtimes2x2');
L = add_mex_source(L,'src','sandwich2x2');
L = add_mex_source(L,'src','combineClusters');

% this one is located elsewhere
L = add_mex_source(L,'external/fileexchange','CalcMD5',[],[],'CFLAGS=''-std=c99 -fPIC''');

% this one depends on the MATLAB version
if ft_platform_supports('libmx_c_interface')
  % use the C interface
  L = add_mex_source(L,'src','mxSerialize_c');
  L = add_mex_source(L,'src','mxDeserialize_c');
else
  % use the C++ interface
  L = add_mex_source(L,'src','mxSerialize_cpp');
  L = add_mex_source(L,'src','mxDeserialize_cpp');
end

oldDir = pwd;
try
  compile_mex_list(L, ftpath, force);
catch
  % the "catch me" syntax is broken on MATLAB74, this fixes it
  me = lasterror;
  cd(oldDir);
  rethrow(me);
end
cd(oldDir);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%
% Use as
%   list = add_mex_source(list, directory, relName, includePlatform, excludePlatform, extras)
%
% The list is a structure array of directory names, source file names, and
% extra arguments required for the compilation of MEX files. This function will
% create a new element of this structure and append it to L.
%
%   directory       = target directory of the mex-file
%   relName         = source file relative to 'directory'
%   includePlatform   = list of platforms this MEX file should only be compiled for.
%                     use an empty matrix [] to compile for all platforms
%   excludePlatform = list of platforms this MEX file should NOT be compiled for.
%   extras          = extra arguments to the MEX command, e.g. additional source files
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function L = add_mex_source(L, directory, relName, includePlatform, excludePlatform, extras)

% Check if this file only needs compilation on certain platforms (including this one)
if nargin>3 && ~isempty(includePlatform)
  ok = false;
  for k=1:numel(includePlatform)
    if strcmp(includePlatform{k}, computer)
      ok = true;
      break;
    end
  end
  if ~ok
    return
  end
end

% Check if this file cannot be compiled on certain platforms (including this one)
if nargin>4 && ~isempty(excludePlatform)
  ok = true;
  for k=1:numel(excludePlatform)
    if strcmp(excludePlatform{k}, computer)
      return;
    end
  end
end

L(end+1).dir   = directory;
L(end).relName = relName;
if nargin>5
  L(end).extras = extras;
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%
% Use as
%  compile_mex_list(L, baseDir)
%
% Compile a list of MEX files as determined by the input argument L.
% The second argument 'baseDir' is the common base directory for the
% files listed in L. The third argument is a flag that determines
% whether to force (re-)compilation even if the MEX file is up-to-date.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function compile_mex_list(L, baseDir, force)

for i=1:length(L)
  [relDir, name] = fileparts(L(i).relName);
  sfname1 = fullfile(baseDir, L(i).dir, [L(i).relName '.c']);
  sfname2 = fullfile(baseDir, L(i).dir, [L(i).relName '.cpp']);
  if exist(sfname1, 'file')
    sfname = sfname1;
    L(i).ext = 'c';
  elseif exist(sfname2, 'file')
    sfname = sfname2;
    L(i).ext = 'cpp';
  else
    sfname = '';
    L(i).ext = '';
    fprintf(1,'Error: source file for %s cannot be found.\n', L(i).relName);
    continue;
  end
  SF = dir(sfname);

  if ~force
    mfname = [baseDir filesep L(i).dir filesep name '.' mexext];
    MF = dir(mfname);
    if numel(MF)==1 && datenum(SF.date) <= datenum(MF.date)
      fprintf(1,'Skipping up-to-date MEX file %s/%s\n', L(i).dir, name);
      continue;
    end
  end
  fprintf(1,'Compiling MEX file %s/%s ...\n', L(i).dir, name);
  cd([baseDir '/' L(i).dir]);
  cmd = sprintf('mex %s.%s %s', L(i).relName, L(i).ext, L(i).extras);
  eval(cmd);
end


function [methodinfo,structs,enuminfo,ThunkLibName]=remoteApiProto
%REMOTEAPIPROTO Create structures to define interfaces found in 'extApi'.

%This function was generated by loadlibrary.m parser version 1.1.6.32
%perl options:'extApi.i -outfile=remoteApiProto.m'
ival={cell(1,0)}; % change 0 to the actual number of functions to preallocate the data.
structs=[];enuminfo=[];fcnNum=1;
fcns=struct('name',ival,'calltype',ival,'LHS',ival,'RHS',ival,'alias',ival);
ThunkLibName=[];

% extern  simxInt mtlb_simxSetJointPosition ( simxInt clientID , simxInt jointHandle , simxFloat* position , simxInt operationMode );
fcns.name{fcnNum}='mtlb_simxSetJointPosition'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'singlePtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt mtlb_simxSetJointTargetVelocity ( simxInt clientID , simxInt jointHandle , simxFloat* targetVelocity , simxInt operationMode );
fcns.name{fcnNum}='mtlb_simxSetJointTargetVelocity'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'singlePtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt mtlb_simxSetJointTargetPosition ( simxInt clientID , simxInt jointHandle , simxFloat* targetPosition , simxInt operationMode );
fcns.name{fcnNum}='mtlb_simxSetJointTargetPosition'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'singlePtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt mtlb_simxSetJointForce ( simxInt clientID , simxInt jointHandle , simxFloat* force , simxInt operationMode );
fcns.name{fcnNum}='mtlb_simxSetJointForce'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'singlePtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt mtlb_simxSetJointMaxForce ( simxInt clientID , simxInt jointHandle , simxFloat* force , simxInt operationMode );
fcns.name{fcnNum}='mtlb_simxSetJointMaxForce'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'singlePtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt mtlb_simxSetFloatSignal ( simxInt clientID , const simxChar * signalName , simxFloat* signalValue , simxInt operationMode );
fcns.name{fcnNum}='mtlb_simxSetFloatSignal'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int8Ptr', 'singlePtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt mtlb_simxSetObjectFloatParameter ( simxInt clientID , simxInt objectHandle , simxInt parameterID , simxFloat* parameterValue , simxInt operationMode );
fcns.name{fcnNum}='mtlb_simxSetObjectFloatParameter'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32', 'singlePtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt mtlb_simxSetFloatingParameter ( simxInt clientID , simxInt paramIdentifier , simxFloat* paramValue , simxInt operationMode );
fcns.name{fcnNum}='mtlb_simxSetFloatingParameter'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'singlePtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt mtlb_simxCreateDummy ( simxInt clientID , simxFloat* size , const simxUChar * colors , simxInt * objectHandle , simxInt operationMode );
fcns.name{fcnNum}='mtlb_simxCreateDummy'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'singlePtr', 'uint8Ptr', 'int32Ptr', 'int32'};fcnNum=fcnNum+1;

% extern  simxInt mtlb_simxReadProximitySensor(simxInt* clientIDandSensorHandle,simxUChar* detectionState,simxFloat* detectedPoint,simxInt* detectedObjectHandle,simxFloat* detectedSurfaceNormalVector,simxInt operationMode);
fcns.name{fcnNum}='mtlb_simxReadProximitySensor'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32Ptr', 'uint8Ptr', 'singlePtr', 'int32Ptr', 'singlePtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt mtlb_simxAuxiliaryConsoleOpen(simxInt* clientIDandMaxLinesAndModeAndPositionAndSize,const simxChar* title,simxFloat* textColor,simxFloat* backgroundColor,simxInt* consoleHandle,simxInt operationMode);
fcns.name{fcnNum}='mtlb_simxAuxiliaryConsoleOpen'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32Ptr', 'int8Ptr', 'singlePtr', 'singlePtr', 'int32Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt mtlb_simxDisplayDialog(simxInt* clientIDandDlgTypeAndOperationMode,const simxChar* titleText,const simxChar* mainText,const simxChar* initialText,const simxFloat* titleColorsAndDlgColors,simxInt* dialogHandleAndUiHandle);
fcns.name{fcnNum}='mtlb_simxDisplayDialog'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32Ptr', 'int8Ptr', 'int8Ptr','int8Ptr', 'singlePtr', 'int32Ptr'};fcnNum=fcnNum+1;
% extern  simxInt mtlb_simxQuery(simxInt* clientIDandSignalLengthAndTimeOutInMs,const simxChar* signalName,const simxUChar* signalValue,const simxChar* retSignalName,simxUChar** retSignalValue,simxInt* retSignalLength);
fcns.name{fcnNum}='mtlb_simxQuery'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32Ptr', 'int8Ptr', 'uint8Ptr', 'int8Ptr', 'uint8PtrPtr', 'int32Ptr'};fcnNum=fcnNum+1;
% extern  simxInt mtlb_simxGetObjectGroupData(simxInt* clientIDandObjectTypeAndDataTypeAndOperationMode,simxInt* handlesCountAndIntDataCountAndFloatDataCountAndStringDataCount,simxInt** handles,simxInt** intData,simxFloat** floatData,simxChar** stringData);
fcns.name{fcnNum}='mtlb_simxGetObjectGroupData'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32Ptr', 'int32Ptr', 'int32PtrPtr', 'int32PtrPtr', 'singlePtrPtr', 'int8PtrPtr'};fcnNum=fcnNum+1;
% extern  simxInt mtlb_simxCallScriptFunction_a(const simxInt* variousIntsIn,const simxChar* scriptDescriptionAndFunctionName,const simxInt* inInt,const simxFloat* inFloat,const simxChar* inString,const simxUChar* inBuffer);
fcns.name{fcnNum}='mtlb_simxCallScriptFunction_a'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32Ptr', 'int8Ptr', 'int32Ptr', 'singlePtr', 'int8Ptr', 'uint8Ptr'};fcnNum=fcnNum+1;
% extern  simxInt mtlb_simxCallScriptFunction_b(simxInt clientID,simxInt* variousIntsOut,simxInt** outInt,simxFloat** outFloat,simxChar** outString,simxUChar** outBuffer);
fcns.name{fcnNum}='mtlb_simxCallScriptFunction_b'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32Ptr', 'int32PtrPtr', 'singlePtrPtr', 'int8PtrPtr', 'uint8PtrPtr'};fcnNum=fcnNum+1;

% extern  simxInt simxGetJointPosition ( simxInt clientID , simxInt jointHandle , simxFloat * position , simxInt operationMode );
fcns.name{fcnNum}='simxGetJointPosition'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'singlePtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetJointMatrix ( simxInt clientID , simxInt jointHandle , simxFloat * matrix , simxInt operationMode );
fcns.name{fcnNum}='simxGetJointMatrix'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'singlePtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxSetSphericalJointMatrix ( simxInt clientID , simxInt jointHandle , simxFloat * matrix , simxInt operationMode );
fcns.name{fcnNum}='simxSetSphericalJointMatrix'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'singlePtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetJointForce ( simxInt clientID , simxInt jointHandle , simxFloat * force , simxInt operationMode );
fcns.name{fcnNum}='simxGetJointForce'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'singlePtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetJointMaxForce ( simxInt clientID , simxInt jointHandle , simxFloat * force , simxInt operationMode );
fcns.name{fcnNum}='simxGetJointMaxForce'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'singlePtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxReadForceSensor ( simxInt clientID , simxInt forceSensorHandle , simxUChar * state , simxFloat * forceVector , simxFloat * torqueVector , simxInt operationMode );
fcns.name{fcnNum}='simxReadForceSensor'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'uint8Ptr', 'singlePtr', 'singlePtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxBreakForceSensor ( simxInt clientID , simxInt forceSensorHandle , simxInt operationMode );
fcns.name{fcnNum}='simxBreakForceSensor'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxReadVisionSensor ( simxInt clientID , simxInt sensorHandle , simxUChar * detectionState , simxFloat ** auxValues , simxInt ** auxValuesCount , simxInt operationMode );
fcns.name{fcnNum}='simxReadVisionSensor'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'uint8Ptr', 'singlePtrPtr', 'int32PtrPtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetObjectHandle ( simxInt clientID , const simxChar * objectName , simxInt * handle , simxInt operationMode );
fcns.name{fcnNum}='simxGetObjectHandle'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int8Ptr', 'int32Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetVisionSensorImage ( simxInt clientID , simxInt sensorHandle , simxInt * resolution , simxUChar ** image , simxUChar options , simxInt operationMode );
fcns.name{fcnNum}='simxGetVisionSensorImage'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32Ptr', 'uint8PtrPtr', 'uint8', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxSetVisionSensorImage ( simxInt clientID , simxInt sensorHandle , simxUChar * image , simxInt bufferSize , simxUChar options , simxInt operationMode );
fcns.name{fcnNum}='simxSetVisionSensorImage'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'uint8Ptr', 'int32', 'uint8', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetVisionSensorDepthBuffer ( simxInt clientID , simxInt sensorHandle , simxInt * resolution , simxFloat ** buffer , simxInt operationMode );
fcns.name{fcnNum}='simxGetVisionSensorDepthBuffer'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32Ptr', 'singlePtrPtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetObjectChild ( simxInt clientID , simxInt parentObjectHandle , simxInt childIndex , simxInt * childObjectHandle , simxInt operationMode );
fcns.name{fcnNum}='simxGetObjectChild'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32', 'int32Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetObjectParent ( simxInt clientID , simxInt childObjectHandle , simxInt * parentObjectHandle , simxInt operationMode );
fcns.name{fcnNum}='simxGetObjectParent'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxLoadModel ( simxInt clientID , const simxChar * modelPathAndName , simxUChar options , simxInt * baseHandle , simxInt operationMode );
fcns.name{fcnNum}='simxLoadModel'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int8Ptr', 'uint8', 'int32Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxLoadUI ( simxInt clientID , const simxChar * uiPathAndName , simxUChar options , simxInt * count , simxInt ** uiHandles , simxInt operationMode );
fcns.name{fcnNum}='simxLoadUI'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int8Ptr', 'uint8', 'int32Ptr', 'int32PtrPtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxLoadScene ( simxInt clientID , const simxChar * scenePathAndName , simxUChar options , simxInt operationMode );
fcns.name{fcnNum}='simxLoadScene'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int8Ptr', 'uint8', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxStartSimulation ( simxInt clientID , simxInt operationMode );
fcns.name{fcnNum}='simxStartSimulation'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxPauseSimulation ( simxInt clientID , simxInt operationMode );
fcns.name{fcnNum}='simxPauseSimulation'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxStopSimulation ( simxInt clientID , simxInt operationMode );
fcns.name{fcnNum}='simxStopSimulation'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetUIHandle ( simxInt clientID , const simxChar * uiName , simxInt * handle , simxInt operationMode );
fcns.name{fcnNum}='simxGetUIHandle'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int8Ptr', 'int32Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetUISlider ( simxInt clientID , simxInt uiHandle , simxInt uiButtonID , simxInt * position , simxInt operationMode );
fcns.name{fcnNum}='simxGetUISlider'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32', 'int32Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxSetUISlider ( simxInt clientID , simxInt uiHandle , simxInt uiButtonID , simxInt position , simxInt operationMode );
fcns.name{fcnNum}='simxSetUISlider'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32', 'int32', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetUIEventButton ( simxInt clientID , simxInt uiHandle , simxInt * uiEventButtonID , simxInt * auxValues , simxInt operationMode );
fcns.name{fcnNum}='simxGetUIEventButton'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32Ptr', 'int32Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetUIButtonProperty ( simxInt clientID , simxInt uiHandle , simxInt uiButtonID , simxInt * prop , simxInt operationMode );
fcns.name{fcnNum}='simxGetUIButtonProperty'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32', 'int32Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxSetUIButtonProperty ( simxInt clientID , simxInt uiHandle , simxInt uiButtonID , simxInt prop , simxInt operationMode );
fcns.name{fcnNum}='simxSetUIButtonProperty'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32', 'int32', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxAddStatusbarMessage ( simxInt clientID , const simxChar * message , simxInt operationMode );
fcns.name{fcnNum}='simxAddStatusbarMessage'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int8Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxAuxiliaryConsoleClose ( simxInt clientID , simxInt consoleHandle , simxInt operationMode );
fcns.name{fcnNum}='simxAuxiliaryConsoleClose'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxAuxiliaryConsolePrint ( simxInt clientID , simxInt consoleHandle , const simxChar * txt , simxInt operationMode );
fcns.name{fcnNum}='simxAuxiliaryConsolePrint'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int8Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxAuxiliaryConsoleShow ( simxInt clientID , simxInt consoleHandle , simxUChar showState , simxInt operationMode );
fcns.name{fcnNum}='simxAuxiliaryConsoleShow'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'uint8', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetObjectOrientation ( simxInt clientID , simxInt objectHandle , simxInt relativeToObjectHandle , simxFloat * eulerAngles , simxInt operationMode );
fcns.name{fcnNum}='simxGetObjectOrientation'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32', 'singlePtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetObjectQuaternion ( simxInt clientID , simxInt objectHandle , simxInt relativeToObjectHandle , simxFloat * eulerAngles , simxInt operationMode );
fcns.name{fcnNum}='simxGetObjectQuaternion'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32', 'singlePtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetObjectPosition ( simxInt clientID , simxInt objectHandle , simxInt relativeToObjectHandle , simxFloat * position , simxInt operationMode );
fcns.name{fcnNum}='simxGetObjectPosition'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32', 'singlePtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxSetObjectOrientation ( simxInt clientID , simxInt objectHandle , simxInt relativeToObjectHandle , const simxFloat * eulerAngles , simxInt operationMode );
fcns.name{fcnNum}='simxSetObjectOrientation'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32', 'singlePtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxSetObjectQuaternion ( simxInt clientID , simxInt objectHandle , simxInt relativeToObjectHandle , const simxFloat * eulerAngles , simxInt operationMode );
fcns.name{fcnNum}='simxSetObjectQuaternion'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32', 'singlePtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxSetObjectPosition ( simxInt clientID , simxInt objectHandle , simxInt relativeToObjectHandle , const simxFloat * position , simxInt operationMode );
fcns.name{fcnNum}='simxSetObjectPosition'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32', 'singlePtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxSetObjectParent ( simxInt clientID , simxInt objectHandle , simxInt parentObject , simxUChar keepInPlace , simxInt operationMode );
fcns.name{fcnNum}='simxSetObjectParent'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32', 'uint8', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxSetUIButtonLabel ( simxInt clientID , simxInt uiHandle , simxInt uiButtonID , const simxChar * upStateLabel , const simxChar * downStateLabel , simxInt operationMode );
fcns.name{fcnNum}='simxSetUIButtonLabel'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32', 'int8Ptr', 'int8Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetLastErrors ( simxInt clientID , simxInt * errorCnt , simxChar ** errorStrings , simxInt operationMode );
fcns.name{fcnNum}='simxGetLastErrors'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32Ptr', 'int8PtrPtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetArrayParameter ( simxInt clientID , simxInt paramIdentifier , simxFloat * paramValues , simxInt operationMode );
fcns.name{fcnNum}='simxGetArrayParameter'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'singlePtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxSetArrayParameter ( simxInt clientID , simxInt paramIdentifier , const simxFloat * paramValues , simxInt operationMode );
fcns.name{fcnNum}='simxSetArrayParameter'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'singlePtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetBooleanParameter ( simxInt clientID , simxInt paramIdentifier , simxUChar * paramValue , simxInt operationMode );
fcns.name{fcnNum}='simxGetBooleanParameter'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'uint8Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxSetBooleanParameter ( simxInt clientID , simxInt paramIdentifier , simxUChar paramValue , simxInt operationMode );
fcns.name{fcnNum}='simxSetBooleanParameter'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'uint8', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetIntegerParameter ( simxInt clientID , simxInt paramIdentifier , simxInt * paramValue , simxInt operationMode );
fcns.name{fcnNum}='simxGetIntegerParameter'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxSetIntegerParameter ( simxInt clientID , simxInt paramIdentifier , simxInt paramValue , simxInt operationMode );
fcns.name{fcnNum}='simxSetIntegerParameter'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetFloatingParameter ( simxInt clientID , simxInt paramIdentifier , simxFloat * paramValue , simxInt operationMode );
fcns.name{fcnNum}='simxGetFloatingParameter'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'singlePtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetStringParameter ( simxInt clientID , simxInt paramIdentifier , simxChar ** paramValue , simxInt operationMode );
fcns.name{fcnNum}='simxGetStringParameter'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int8PtrPtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetCollisionHandle ( simxInt clientID , const simxChar * collisionObjectName , simxInt * handle , simxInt operationMode );
fcns.name{fcnNum}='simxGetCollisionHandle'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int8Ptr', 'int32Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetDistanceHandle ( simxInt clientID , const simxChar * distanceObjectName , simxInt * handle , simxInt operationMode );
fcns.name{fcnNum}='simxGetDistanceHandle'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int8Ptr', 'int32Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetCollectionHandle ( simxInt clientID , const simxChar * collectionName , simxInt * handle , simxInt operationMode );
fcns.name{fcnNum}='simxGetCollectionHandle'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int8Ptr', 'int32Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxReadCollision ( simxInt clientID , simxInt collisionObjectHandle , simxUChar * collisionState , simxInt operationMode );
fcns.name{fcnNum}='simxReadCollision'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'uint8Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxReadDistance ( simxInt clientID , simxInt distanceObjectHandle , simxFloat * minimumDistance , simxInt operationMode );
fcns.name{fcnNum}='simxReadDistance'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'singlePtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxRemoveObject ( simxInt clientID , simxInt objectHandle , simxInt operationMode );
fcns.name{fcnNum}='simxRemoveObject'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxRemoveModel ( simxInt clientID , simxInt objectHandle , simxInt operationMode );
fcns.name{fcnNum}='simxRemoveModel'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxRemoveUI ( simxInt clientID , simxInt uiHandle , simxInt operationMode );
fcns.name{fcnNum}='simxRemoveUI'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxCloseScene ( simxInt clientID , simxInt operationMode );
fcns.name{fcnNum}='simxCloseScene'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetObjects ( simxInt clientID , simxInt objectType , simxInt * objectCount , simxInt ** objectHandles , simxInt operationMode );
fcns.name{fcnNum}='simxGetObjects'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32Ptr', 'int32PtrPtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxEndDialog ( simxInt clientID , simxInt dialogHandle , simxInt operationMode );
fcns.name{fcnNum}='simxEndDialog'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetDialogInput ( simxInt clientID , simxInt dialogHandle , simxChar ** inputText , simxInt operationMode );
fcns.name{fcnNum}='simxGetDialogInput'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int8PtrPtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetDialogResult ( simxInt clientID , simxInt dialogHandle , simxInt * result , simxInt operationMode );
fcns.name{fcnNum}='simxGetDialogResult'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxCopyPasteObjects ( simxInt clientID , const simxInt * objectHandles , simxInt objectCount , simxInt ** newObjectHandles , simxInt * newObjectCount , simxInt operationMode );
fcns.name{fcnNum}='simxCopyPasteObjects'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32Ptr', 'int32', 'int32PtrPtr', 'int32Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetObjectSelection ( simxInt clientID , simxInt ** objectHandles , simxInt * objectCount , simxInt operationMode );
fcns.name{fcnNum}='simxGetObjectSelection'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32PtrPtr', 'int32Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxSetObjectSelection ( simxInt clientID , const simxInt * objectHandles , simxInt objectCount , simxInt operationMode );
fcns.name{fcnNum}='simxSetObjectSelection'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32Ptr', 'int32', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxClearFloatSignal ( simxInt clientID , const simxChar * signalName , simxInt operationMode );
fcns.name{fcnNum}='simxClearFloatSignal'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int8Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxClearIntegerSignal ( simxInt clientID , const simxChar * signalName , simxInt operationMode );
fcns.name{fcnNum}='simxClearIntegerSignal'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int8Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxClearStringSignal ( simxInt clientID , const simxChar * signalName , simxInt operationMode );
fcns.name{fcnNum}='simxClearStringSignal'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int8Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetFloatSignal ( simxInt clientID , const simxChar * signalName , simxFloat * signalValue , simxInt operationMode );
fcns.name{fcnNum}='simxGetFloatSignal'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int8Ptr', 'singlePtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetIntegerSignal ( simxInt clientID , const simxChar * signalName , simxInt * signalValue , simxInt operationMode );
fcns.name{fcnNum}='simxGetIntegerSignal'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int8Ptr', 'int32Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetStringSignal ( simxInt clientID , const simxChar * signalName , simxUChar ** signalValue , simxInt * signalLength , simxInt operationMode );
fcns.name{fcnNum}='simxGetStringSignal'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int8Ptr', 'uint8PtrPtr', 'int32Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetAndClearStringSignal ( simxInt clientID , const simxChar * signalName , simxUChar ** signalValue , simxInt * signalLength , simxInt operationMode );
fcns.name{fcnNum}='simxGetAndClearStringSignal'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int8Ptr', 'uint8PtrPtr', 'int32Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxReadStringStream ( simxInt clientID , const simxChar * signalName , simxUChar ** signalValue , simxInt * signalLength , simxInt operationMode );
fcns.name{fcnNum}='simxReadStringStream'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int8Ptr', 'uint8PtrPtr', 'int32Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxSetIntegerSignal ( simxInt clientID , const simxChar * signalName , simxInt signalValue , simxInt operationMode );
fcns.name{fcnNum}='simxSetIntegerSignal'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int8Ptr', 'int32', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxSetStringSignal ( simxInt clientID , const simxChar * signalName , const simxUChar * signalValue , simxInt signalLength , simxInt operationMode );
fcns.name{fcnNum}='simxSetStringSignal'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int8Ptr', 'uint8Ptr', 'int32', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxAppendStringSignal ( simxInt clientID , const simxChar * signalName , const simxUChar * signalValue , simxInt signalLength , simxInt operationMode );
fcns.name{fcnNum}='simxAppendStringSignal'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int8Ptr', 'uint8Ptr', 'int32', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxWriteStringStream ( simxInt clientID , const simxChar * signalName , const simxUChar * signalValue , simxInt signalLength , simxInt operationMode );
fcns.name{fcnNum}='simxWriteStringStream'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int8Ptr', 'uint8Ptr', 'int32', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetObjectFloatParameter ( simxInt clientID , simxInt objectHandle , simxInt parameterID , simxFloat * parameterValue , simxInt operationMode );
fcns.name{fcnNum}='simxGetObjectFloatParameter'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32', 'singlePtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetObjectIntParameter ( simxInt clientID , simxInt objectHandle , simxInt parameterID , simxInt * parameterValue , simxInt operationMode );
fcns.name{fcnNum}='simxGetObjectIntParameter'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32', 'int32Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxSetObjectIntParameter ( simxInt clientID , simxInt objectHandle , simxInt parameterID , simxInt parameterValue , simxInt operationMode );
fcns.name{fcnNum}='simxSetObjectIntParameter'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32', 'int32', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetModelProperty ( simxInt clientID , simxInt objectHandle , simxInt * prop , simxInt operationMode );
fcns.name{fcnNum}='simxGetModelProperty'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxSetModelProperty ( simxInt clientID , simxInt objectHandle , simxInt prop , simxInt operationMode );
fcns.name{fcnNum}='simxSetModelProperty'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetObjectVelocity ( simxInt clientID , simxInt objectHandle , simxFloat * linearVelocity , simxFloat * angularVelocity , simxInt operationMode );
fcns.name{fcnNum}='simxGetObjectVelocity'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'singlePtr', 'singlePtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxStart ( const simxChar * connectionAddress , simxInt connectionPort , simxUChar waitUntilConnected , simxUChar doNotReconnectOnceDisconnected , simxInt timeOutInMs , simxInt commThreadCycleInMs );
fcns.name{fcnNum}='simxStart'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int8Ptr', 'int32', 'uint8', 'uint8', 'int32', 'int32'};fcnNum=fcnNum+1;
% extern  simxVoid simxFinish ( simxInt clientID );
fcns.name{fcnNum}='simxFinish'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}=[]; fcns.RHS{fcnNum}={'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetPingTime ( simxInt clientID , simxInt * pingTime );
fcns.name{fcnNum}='simxGetPingTime'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32Ptr'};fcnNum=fcnNum+1;
% extern  simxInt simxGetLastCmdTime ( simxInt clientID );
fcns.name{fcnNum}='simxGetLastCmdTime'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxSynchronousTrigger ( simxInt clientID );
fcns.name{fcnNum}='simxSynchronousTrigger'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxSynchronous ( simxInt clientID , simxUChar enable );
fcns.name{fcnNum}='simxSynchronous'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'uint8'};fcnNum=fcnNum+1;
% extern  simxInt simxPauseCommunication ( simxInt clientID , simxUChar pause );
fcns.name{fcnNum}='simxPauseCommunication'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'uint8'};fcnNum=fcnNum+1;
% extern  simxInt simxGetInMessageInfo ( simxInt clientID , simxInt infoType , simxInt * info );
fcns.name{fcnNum}='simxGetInMessageInfo'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32Ptr'};fcnNum=fcnNum+1;
% extern  simxInt simxGetOutMessageInfo ( simxInt clientID , simxInt infoType , simxInt * info );
fcns.name{fcnNum}='simxGetOutMessageInfo'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32Ptr'};fcnNum=fcnNum+1;
% extern  simxInt simxGetConnectionId ( simxInt clientID );
fcns.name{fcnNum}='simxGetConnectionId'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32'};fcnNum=fcnNum+1;
% extern  simxUChar * simxCreateBuffer ( simxInt bufferSize );
fcns.name{fcnNum}='simxCreateBuffer'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='uint8Ptr'; fcns.RHS{fcnNum}={'int32'};fcnNum=fcnNum+1;
% extern  simxVoid simxReleaseBuffer ( simxUChar * buffer );
fcns.name{fcnNum}='simxReleaseBuffer'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}=[]; fcns.RHS{fcnNum}={'uint8Ptr'};fcnNum=fcnNum+1;
% extern  simxInt simxTransferFile ( simxInt clientID , const simxChar * filePathAndName , const simxChar * fileName_serverSide , simxInt timeOut , simxInt operationMode );
fcns.name{fcnNum}='simxTransferFile'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int8Ptr', 'int8Ptr', 'int32', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxEraseFile ( simxInt clientID , const simxChar * fileName_serverSide , simxInt operationMode );
fcns.name{fcnNum}='simxEraseFile'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int8Ptr', 'int32'};fcnNum=fcnNum+1;
methodinfo=fcns;


clear all;close all;clc
%%
M_dir = {'E:\Janelia2014\Fish1_16states_30frames';
    'E:\Janelia2014\Fish2_20140714_2_4_16states_10frames';
    'E:\Janelia2014\Fish3_20140715_1_1_16_states_10frames';
    'E:\Janelia2014\Fish4_20140721_1_8_16states_20frames';
    'E:\Janelia2014\Fish5_20140722_1_2_16states_30frames';
    'E:\Janelia2014\Fish6_20140722_1_1_3states_30,40frames';
    'E:\Janelia2014\Fish7_20140722_2_3_3states_30,50frames';
    'E:\Janelia2014\Fish8_20141222_2_2_7d_PT_3OMR_shock_lowcut';};

for i_fish = 1:6,
    datadir = M_dir{i_fish};

    %% load anatomy
    tiffname = fullfile(datadir,'ave.tif');
    info = imfinfo(tiffname,'tiff');
    nPlanes = length(info);
    s1 = info(1).Height;
    s2 = info(1).Width;
    ave_stack = zeros(s1,s2,nPlanes);
    for i=1:nPlanes,
        ave_stack(:,:,i) = imread(fullfile(datadir,'ave.tif'),i);
    end

    % x-z view
    im = squeeze(max(ave_stack,[],1));
    im=double(im);
    temp=sort(im(:),'descend');
    th1=temp(round(length(im(:))/100));
    th2=min(im(:));
    out=(im-th2)/(th1-th2);
    out(out>1)=1;
    out = flipud(out');
    anat_zx = repmat(out,[1 1 3]);

    %%
    temp = fullfile(datadir,['Fish' num2str(i_fish) '_direct_load.mat']);
    save(temp,'anat_zx','-append');

end
% %%
% for i_fish = 1:7,
%     datadir = M_dir{i_fish};
%
%     load(['CONST_F' num2str(i_fish) '.mat'],'CONST');
%     CONST2 = CONST;
%     CONST2.stim_full = CONST.photostate;
%     CONST2.CellRespAvr = CONST.CRAZ;
%
%     CONST = [];
%     names = {'ave_stack','anat_yx','anat_yz','anat_zx','CInfo','periods','shift','dshift',...
%         'CellResp','CellRespAvr','Fictive','FictiveAvr','stim_full','stimAvr',...
%         'tlists','stimrangenames'};
%     for i = 1:length(names), % use loop to save variables into fields of CONST
%         eval(['CONST.',names{i},'=', 'CONST2.', names{i},';']);
%     end
%
%     %%
%     save(['CONST_F' num2str(i_fish) '.mat'],'CONST');
%
% end


function json=get_coverage_json(obj, root_dir)
% Get JSON coverage representation
%
% json=get_coverage_json(obj, root_dir)
%
% Inputs:
%   obj                 MOcovMFile instance
%   root_dir            git root directory in which the file represented
%                       by obj resides
%
% Output:
%   json                JSON String representation of coverage, with
%                       elements:
%                       'name'          filename, relative to root_dir
%                       'source_digest' MD5 checksum of file contents
%                       'coverage'      Array with number of times each
%                                       line was executed; or null for
%                                       lines that cannot not be executed.
%
% Notes:
%   - this output can be used by the coveralls.io online coverage service
%     in combination with travis-ci

    name=mocov_get_relative_path(root_dir,obj.filename);
    source_digest=mocov_util_md5(obj.filename);
    coverage=get_coverage(obj);

    json=sprintf(['{ "name": "%s",\n',...
                    '"source_digest": "%s",\n'...
                    '"coverage": %s\n }\n'],...
                    name,source_digest,coverage);

function json_coverage=get_coverage(obj)
    executable=get_lines_executable(obj);
    executed_count=get_lines_executed_count(obj);

    n=numel(executable);

    json_parts=cell(1,2*n+1);
    json_parts{1}='[';
    for k=1:n
        line_executable=executable(k);

        if line_executable
            coverage_str=sprintf('%d',executed_count(k));
        else
            coverage_str='null';
        end

        json_parts{2*k}=coverage_str;
        if k<n
            suffix=',';
        else
            suffix=']';
        end

        json_parts{2*k+1}=suffix;
    end

    json_coverage=sprintf('%s',json_parts{:});


function download_train(data_dir)
% DOWNLOAD_TRAIN Checks, and, if required, downloads the necessary data and networks for the training.
%
%   download_train(DATA_ROOT) checks if the data and networks necessary for running the training script exist.
%   If not it downloads it in the folder structure:
%     DATA_ROOT/train/dbs/         : folder with training database mat files
%     DATA_ROOT/train/ims/         : folder with original images used for training
%     DATA_ROOT/networks/imagenet/ : CNN models pretrained for classification using imagenet data

    % Create data folder if it does not exist
    if ~exist(data_dir, 'dir')
        mkdir(data_dir);
    end

    % Create train folder if it does not exist
    train_dir = fullfile(data_dir, 'train');
    if ~exist(train_dir, 'dir')
        mkdir(train_dir);
    end

    % Download folder train/db/
    src_dir = fullfile('http://cmp.felk.cvut.cz/cnnimageretrieval/data', 'train', 'dbs');
    dst_dir = fullfile(data_dir, 'train', 'dbs');
    dl_files = {'retrieval-SfM-30k.mat',  'retrieval-SfM-30k-whiten.mat', ...
                'retrieval-SfM-120k.mat', 'retrieval-SfM-120k-whiten.mat'};
    if ~exist(dst_dir, 'dir')
        fprintf('>> Database directory does not exist. Creating: %s\n', dst_dir);
        mkdir(dst_dir);
        fprintf('>> Downloading database files from cmp.felk.cvut.cz/cnnimageretrieval\n');
    end
    for i = 1:numel(dl_files)
        src_file = fullfile(src_dir, dl_files{i});
        dst_file = fullfile(dst_dir, dl_files{i});
        if ~exist(dst_file, 'file')
            fprintf('>> DB file %s does not exist. Downloading...\n', dl_files{i});
            system(sprintf('wget %s -O %s', src_file, dst_file));
        end
    end

    % Download folder train/ims/
    src_dir = fullfile('http://cmp.felk.cvut.cz/cnnimageretrieval/data', 'train', 'ims');
    dst_dir = fullfile(data_dir, 'train', 'ims');
    dl_file = 'ims.tar.gz';
    if ~exist(dst_dir, 'dir')
        src_file = fullfile(src_dir, dl_file);
        dst_file = fullfile(dst_dir, dl_file);
        fprintf('>> Image directory does not exist. Creating: %s\n', dst_dir);
        mkdir(dst_dir);
        fprintf('>> Downloading ims.tar.gz...\n');
        system(sprintf('wget %s -O %s', src_file, dst_file));
        fprintf('>> Extracting %s...\n', dst_file);
        system(sprintf('tar -zxf %s -C %s', dst_file, dst_dir));
        fprintf('>> Extracted, deleting %s...\n', dst_file);
        system(sprintf('rm %s', dst_file));
    end
    dl_files = {'retrieval-SfM-30k-imagenames-clusterids.mat', 'retrieval-SfM-120k-imagenames-clusterids.mat'};
    for i = 1:numel(dl_files)
        src_file = fullfile(src_dir, dl_files{i});
        dst_file = fullfile(dst_dir, dl_files{i});
        if ~exist(dst_file, 'file')
            fprintf('>> Dataset image split %s does not exist. Downloading...\n', dl_files{i});
            system(sprintf('wget %s -O %s', src_file, dst_file));
        end
    end

    % Download folder networks/imagenet/
    src_dir = fullfile('http://www.vlfeat.org/matconvnet/', 'models');
    dst_dir = fullfile(data_dir, 'networks', 'imagenet');
    dl_files = {'imagenet-caffe-alex.mat', 'imagenet-vgg-verydeep-16.mat', 'imagenet-googlenet-dag.mat', ...
                'imagenet-resnet-50-dag.mat', 'imagenet-resnet-101-dag.mat', 'imagenet-resnet-152-dag.mat'};
    if ~exist(dst_dir, 'dir')
        fprintf('>> Imagenet networks directory does not exist. Creating: %s\n', dst_dir);
        mkdir(dst_dir);
        fprintf('>> Downloading imagenet networks from http://www.vlfeat.org/matconvnet\n');
    end
    for i = 1:numel(dl_files)
        src_file = fullfile(src_dir, dl_files{i});
        dst_file = fullfile(dst_dir, dl_files{i});
        if ~exist(dst_file, 'file')
            fprintf('>> Network %s does not exist. Downloading...\n', dl_files{i});
            system(sprintf('wget %s -O %s', src_file, dst_file));
        end
    end


function copy = spm_cfg_eeg_copy
% configuration file for copying
%__________________________________________________________________________
% Copyright (C) 2009-2012 Wellcome Trust Centre for Neuroimaging

% Vladimir Litvak
% $Id: spm_cfg_eeg_copy.m 5377 2013-04-02 17:07:57Z vladimir $

%--------------------------------------------------------------------------
% D
%--------------------------------------------------------------------------
D        = cfg_files;
D.tag    = 'D';
D.name   = 'File Name';
D.filter = 'mat';
D.num    = [1 1];
D.help   = {'Select the M/EEG mat file.'};

%--------------------------------------------------------------------------
% outfile
%--------------------------------------------------------------------------
outfile = cfg_entry;
outfile.tag = 'outfile';
outfile.name = 'Output filename';
outfile.strtype = 's';
outfile.num = [0 inf];
outfile.help = {'Choose filename.'};

%--------------------------------------------------------------------------
% copy
%--------------------------------------------------------------------------
copy          = cfg_exbranch;
copy.tag      = 'copy';
copy.name     = 'Copy';
copy.val      = {D, outfile};
copy.help     = {'Copying M/EEG datasets'}';
copy.prog     = @eeg_copy;
copy.vout     = @vout_eeg_copy;
copy.modality = {'EEG'};

%==========================================================================
function out = eeg_copy(job)
% construct the S struct
S           = job;
S.D         = S.D{1};
out.D       = spm_eeg_copy(S);
out.Dfname  = {fullfile(out.D)};

%==========================================================================
function dep = vout_eeg_copy(job)
% return dependencies
dep(1)            = cfg_dep;
dep(1).sname      = 'Copied M/EEG data';
dep(1).src_output = substruct('.','D');
dep(1).tgt_spec   = cfg_findspec({{'strtype','e'}});

dep(2)            = cfg_dep;
dep(2).sname      = 'Copied M/EEG datafile';
dep(2).src_output = substruct('.','Dfname');
dep(2).tgt_spec   = cfg_findspec({{'filter','mat'}});