classdef TestFastNlMeansDenoisingMulti
    %TestFastNlMeansDenoisingMulti

    properties (Constant)
        im = fullfile(mexopencv.root(),'test','lena.jpg');
    end

    methods (Static)
        function test_1
            img = cv.imread(TestFastNlMeansDenoisingMulti.im, ...
                'Grayscale',true, 'ReduceScale',2);
            imgs = repmat({img},1,5);
            out = cv.fastNlMeansDenoisingMulti(imgs, 2, 3, 'H',20);
            validateattributes(out, {class(img)}, {'size',size(img)});
        end

        function test_2
            % we use IMNOISE Image Processing Toolbox
            if ~mexopencv.require('images')
                error('mexopencv:testskip', 'toolbox');
            end

            img = cv.imread(TestFastNlMeansDenoisingMulti.im, ...
                'Grayscale',true, 'ReduceScale',2);
            imgs = cell(1,5);
            for i=1:numel(imgs)
                imgs{i} = imnoise(img, 'gaussian');
            end
            out = cv.fastNlMeansDenoisingMulti(imgs, 2, 3, 'H',20);
            validateattributes(out, {class(img)}, {'size',size(img)});
        end

        function test_3
            files = dir(fullfile(mexopencv.root(),'test','left0*.jpg'));
            imgs = cell(1, numel(files));
            for i=1:numel(files)
                imgs{i} = cv.imread(fullfile(mexopencv.root(),'test',files(i).name), ...
                    'Grayscale',true, 'ReduceScale',2);
            end
            out = cv.fastNlMeansDenoisingMulti(imgs, 6-1, 3);
            validateattributes(out, {class(imgs{1})}, {'size',size(imgs{1})});
        end

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

end


 function ob = power(ob, sup)
%function ob = power(ob, sup)
% array "power" method (A.^2)
% matrix power (mpower) would be for A^2

if isempty(ob.handle_power)
	error 'no power method for this object'
end

ob = ob.handle_power(ob, sup);
if isfield(ob, 'scale') && ob.scale ~= 1
	ob.scale = ob.scale .^ sup;
end


function checkreg = spm_cfg_checkreg
% SPM Configuration file for Check Reg
%__________________________________________________________________________
% Copyright (C) 2008-2016 Wellcome Trust Centre for Neuroimaging

% $Id: spm_cfg_checkreg.m 6952 2016-11-25 16:03:13Z guillaume $

%--------------------------------------------------------------------------
% data Images to Display
%--------------------------------------------------------------------------
data         = cfg_files;
data.tag     = 'data';
data.name    = 'Images to Display';
data.help    = {'Images to display.'};
data.filter  = 'image';
data.ufilter = '.*';
data.num     = [1 24];

%--------------------------------------------------------------------------
% checkreg Check Registration
%--------------------------------------------------------------------------
checkreg      = cfg_exbranch;
checkreg.tag  = 'checkreg';
checkreg.name = 'Check Registration';
checkreg.val  = {data};
checkreg.help = {
    'Display of orthogonal views of one or more images.'
    ''
    'Clicking in any image moves the centre of the orthogonal views. Images are shown in orientations relative to that of the first selected image. The first specified image is shown at the top-left, and the last at the bottom right.  The fastest increment is in the left-to-right direction (the same as you are reading this).'
    ''
    'If you have put your images in the correct file format, then (possibly after specifying some rigid-body rotations):'
    '    The top-left image is coronal with the top (superior) of the head displayed at the top and the left shown on the left. This is as if the subject is viewed from behind.'
    '    The bottom-left image is axial with the front (anterior) of the head at the top and the left shown on the left. This is as if the subject is viewed from above.'
    '    The top-right image is sagittal with the front (anterior) of the head at the left and the top of the head shown at the top. This is as if the subject is viewed from the left.'
    }';
checkreg.prog = @check_reg;

%==========================================================================
function check_reg(job)
spm_check_registration(char(job.data));


function [s] = readstruct(filename, defaults)
% readstruct Read a key-value file to a structure
%
% This function reads a key-value file to a structure. If possible, the
% values are converted to numbers, otherwise the value is kept as string.
%
% Input:
% - filename (string): Path to the file.
% - defaults (struct): A structure merged with read data, can be used to
%   set defaults.
%
% Output:
% - s (structure): Resulting structure.
%

fid = fopen(filename);
lines = textscan(fid, '%s', 'Delimiter', '\n');
fclose(fid);

lines = lines{1};

s = struct();

for i = 1:numel(lines)
	[key, value] = parse_line(lines{i});

	key = strrep(strrep(key, ' ', '_'), '-', '_');

	if ~isempty(key)

        tokens = strsplit(key, '.');

        s = update_struct(s, tokens, value);

	end

end;

if nargin > 1
	s = struct_merge(s, defaults);
end

end

function s = update_struct(s, keys, value)

    if numel(keys) == 1
        s.(keys{1}) = value;
    else
        if ~isfield(s, keys{1}) || ~isstruct(s.(keys{1}))
            s.(keys{1}) = struct();
        end
        s.(keys{1}) = update_struct(s.(keys{1}), keys(2:end), value);
    end

end

function [key, value] = parse_line(line)

    delimiter = find(line == '=', 1);

	if isnan(delimiter)
		key = []; value = [];
		return;
	end;

	key = line(1:delimiter-1);
	value = line(delimiter+1:end);

	[numvalue, status] = str2num(value); %#ok<ST2NM>

	if status
		value = numvalue;
	end

end


function obj = compile(obj, export_path, varargin)
    % export the symbolic expressions of the system dynamics matrices and
    % vectors and compile as MEX files.
    %
    % Parameters:
    %  export_path: the path to export the file @type char
    %  varargin: variable input parameters @type varargin
    %   StackVariable: whether to stack variables into one @type logical
    %   File: the (full) file name of exported file @type char
    %   ForceExport: force the export @type logical
    %   BuildMex: flag whether to MEX the exported file @type logical
    %   Namespace: the namespace of the function @type char

    % export the impact constraints
    i_constrs = fieldnames(obj.ImpactConstraints);
    if ~isempty(i_constrs)
        for i=1:length(i_constrs)
            constr = i_constrs{i};
            export(obj.ImpactConstraints.(constr),export_path,varargin{:});

        end

    end

    % The mass matrix will be exported by the continuoud dynamics object,
    % but call it here again will not re-export if it has been exported.
    if ~isempty(obj.Mmat)
        cellfun(@(x)export(x,export_path,varargin{:}),obj.Mmat,'UniformOutput',false);
        %         export(obj.Mmat,export_path,varargin{:});
    end

    % call superclass method
    compile@DiscreteDynamics(obj, export_path, varargin{:});
end


function DCM = spm_dcm_load(P, save_mem)
% Load a cell array of DCM filenames into a subjects x models cell array
% FORMAT DCM = spm_dcm_load(P)
%
% P        - a DCM's filename or
%          - a GCM's filename (which contains a cell array of DCM files) or
%          - a cell array of DCM filenames or
%          - a character array of DCM filenames
% save_mem - (Optional) if true, only loads priors, posteriors and F for
%            models 2-N
%
%__________________________________________________________________________
% Copyright (C) 2016 Wellcome Trust Centre for Neuroimaging

% Peter Zeidman
% $Id: spm_dcm_load.m 7479 2018-11-09 14:17:33Z peter $

if ischar(P)
    if size(P,1) > 1
        % A character array was provided
        P = cellstr(P);
    else
        % A GCM / DCM filename was provided
        x = load(P);
        if isfield(x,'GCM')
            P = x.GCM;
        elseif isfield(x,'DCM')
            P = {x.DCM};
        else
            error('Unknown DCM file type');
        end
    end
end

if nargin < 2
    save_mem = false;
end

DCM = cell(size(P));

fprintf('Loading DCMs...');
for s = 1:size(P,1)
    for m = 1:size(P,2)

        if isstruct(P{s,m})
            % DCM already a structure - leave unchanged
            dcm = P{s,m};
        else
            % Load DCM from filename
            try
                model = load(P{s,m});
                dcm   = model.DCM;
            catch
               fprintf('File: %s\n',P{s,m});
               error('Failed to load model for subject %d model %d', s, m);
            end
        end

        if save_mem && (m>1)
            % Onlt import basic structures
            DCM{s,m} = struct();
            if isfield(dcm,'a'),  DCM{s,m}.a  = dcm.a; end
            if isfield(dcm,'b'),  DCM{s,m}.b  = dcm.b; end
            if isfield(dcm,'c'),  DCM{s,m}.c  = dcm.c; end
            if isfield(dcm,'d'),  DCM{s,m}.d  = dcm.d; end
            if isfield(dcm,'F'),  DCM{s,m}.F  = dcm.F; end
            if isfield(dcm,'Ep'), DCM{s,m}.Ep = dcm.Ep; end
            if isfield(dcm,'Cp'), DCM{s,m}.Cp = dcm.Cp; end
            if isfield(dcm,'options'), DCM{s,m}.options = dcm.options; end
            if isfield(dcm,'M')
                if isfield(dcm.M,'pE'), DCM{s,m}.M.pE = dcm.M.pE; end
                if isfield(dcm.M,'pC'), DCM{s,m}.M.pC = dcm.M.pC; end
            end
        else
            % Import the whole DCM
            DCM{s,m} = dcm;
        end

    end
end
fprintf('Done\n');


%isstring_FMAT - Test if parameter is an (admissible) character string.
%
%  USAGE
%
%    test = isstring_FMAT(x,string1,string2,...)
%
%    x              item to test
%    string1...     optional list of admissible strings
%
%  SEE ALSO
%
%    See also isdmatrix, isdvector, isdscalar, isimatrix, isivector, isiscalar.
%

% Copyright (C) 2004-2010 by Michaël Zugaro
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 3 of the License, or
% (at your option) any later version.

function test = isstring_FMAT(x,varargin)

% Check number of parameters
if nargin < 1,
  error('Incorrect number of parameters (type ''help isstring_FMAT'' for details).');
end

test = true;

if ~ischar(x),
	test = false;
	return;
end

if isempty(varargin), return; end

for i = 1:length(varargin),
	if strcmp(x,varargin{i}), return; end
end

test = false;


function filePath = BF_WriteTempFile(dataVector,whatPrecision)
% BF_WriteTempFile   Write a temporary file in the system temporary directory
%
%---INPUTS:
% dataVector, a vector of data to write to file.

% ------------------------------------------------------------------------------
% Copyright (C) 2020, Ben D. Fulcher <ben.d.fulcher@gmail.com>,
% <http://www.benfulcher.com>
%
% If you use this code for your research, please cite the following two papers:
%
% (1) B.D. Fulcher and N.S. Jones, "hctsa: A Computational Framework for Automated
% Time-Series Phenotyping Using Massive Feature Extraction, Cell Systems 5: 527 (2017).
% DOI: 10.1016/j.cels.2017.10.001
%
% (2) B.D. Fulcher, M.A. Little, N.S. Jones, "Highly comparative time-series
% analysis: the empirical structure of time series and their methods",
% J. Roy. Soc. Interface 10(83) 20130048 (2013).
% DOI: 10.1098/rsif.2013.0048
%
% This function is free software: you can redistribute it and/or modify it under
% the terms of the GNU General Public License as published by the Free Software
% Foundation, either version 3 of the License, or (at your option) any later
% version.
%
% This program is distributed in the hope that it will be useful, but WITHOUT
% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
% FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
% details.
%
% You should have received a copy of the GNU General Public License along with
% this program. If not, see <http://www.gnu.org/licenses/>.
% ------------------------------------------------------------------------------

if nargin < 2
    % precision (number of significant digits) to write
    whatPrecision = 7;
end

% Filename is the tempname (which will be unique):
filePath = tempname;

% Write the file:
dlmwrite(filePath,dataVector,'precision',whatPrecision);

end


function [isSameModel,differences] = compareModels(modelA,modelB,printLevel)
%compares modelA with modelB, looking for differences between the
%structures
%
% INPUT
% modelA:       structure
% modelB:       structure
% printLevel:
%
% OUTPUT
% isSameModel:   true if identical models, false otherwise
% differences:   structure listing differences between models
%               *.reason: gives a text stack of why the difference occurred
%                         as well as a field
%               *.where: contains the indices and subfields of the structure
%                        where the comparison failed.
%
%
% Note: This function depends on structeq.m and celleq.m

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

differences=[];
result = 0;
i=0;
while result==0
    [result, why] = structeq(modelA,modelB);
    if result==0
        i=i+1;
        if printLevel>0
            fprintf('%s\n',why.Reason)
            fprintf('%s\n',why.Where)
        end
        differences(i).reason = why.Reason;
        differences(i).where = why.Where;
        %fieldName = strrep(why.Where,'(1)','');
        fieldName = strtok(why.Where,'(1)');
        eval(['modelB' fieldName ' = modelA' fieldName ';']);
    end
end
isSameModel = i==0;

end


function [compression_ratio] = flacwrite(varargin);
%flacWRITE Write FLAC (".FLAC") sound file. (Free Lossless Audio Codec)
%    FLACWRITE(Y,FS,NBITS,FLACFILE,ENCODING) writes data Y to a FLAC Vorbis
%    file specified by the file name FLACFILE, with a sample rate
%    of FS Hz and with NBITS number of bits. Stereo data should
%    be specified as a matrix with two columns.
%    ENCODING must be specified as an integer number from 1 to 9
%
%   1 = Fast Encoding.
%   .
%   .
%   .
%   9 = Best Encoding.
%
%   Y,FS and NBITS are mandatory fields. If FLACFILE is not defined the file
%   name will be 'Default_name.flac'. If ENCODING is not defined encoding
%   type '2' will be used by deault.
%
%   [compression_ratio] = flacwrite(Y,FS,NBITS,FLACFILE,ENCODING); returns
%   the compression ratio obtained.
%
%    See also FLACREAD, WAVREAD, WAVWRITE.
if length(varargin) < 3 | length(varargin) > 5
    error('Unsopported number of argument inputs')
end
Y = varargin{1};
FS = varargin{2};
NBITS = varargin{3};
if NBITS~=8 & NBITS~=16 & NBITS~=24 & NBITS~=32
    error('Unsopported bit depth')
end
if length(varargin) >= 4
    FLACFILE = varargin{4};
    if ischar(FLACFILE) ~= 1
        error('File name is not a string')
    end
else
    FLACFILE = 'Default_name.flac';
    disp('File name = Default_name.flac')
end

if isempty(findstr(FLACFILE,'.flac'))
    FLACFILE = strcat(FLACFILE,'.flac');
end

if length(varargin) == 5
    ENCODING = varargin{5};
else
    ENCODING = '2';
    disp('Variable bit rate, joint-stereo, 128 kb/s encoding')
end
app_dir = which('flacwrite.m');
app_dir_base = findstr('flacwrite.m',app_dir);
encoder_dir = app_dir(1:app_dir_base-2);
%%%%% Temporary File %%%%%
[data,channels] = size(Y);
wavwrite(Y,FS,NBITS,strcat(encoder_dir,'\temp.wav'));
tmpfile = strcat(encoder_dir,'\temp.wav');
FLACFILE = strcat(pwd,'\',FLACFILE);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%% Data Encoding  using "flac.exe"  %%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
ENCODING =  num2str(ENCODING);
switch ENCODING
    case {'1'}
        [stat,info_out] = dos([encoder_dir,'\flac.exe', ' ', tmpfile, ' ', ' -0 ', ' -f ',' -o ',FLACFILE]);
    case {'2'}
        [stat,info_out] = dos([encoder_dir,'\flac.exe', ' ', tmpfile, ' ', ' -1 ', ' -f ',' -o ',FLACFILE]);
    case {'3'}
        [stat,info_out] = dos([encoder_dir,'\flac.exe', ' ', tmpfile, ' ', ' -2 ', ' -f ',' -o ',FLACFILE]);
    case {'4'}
        [stat,info_out] = dos([encoder_dir,'\flac.exe', ' ', tmpfile, ' ', ' -3 ', ' -f ',' -o ',FLACFILE]);
    case {'5'}
        [stat,info_out] = dos([encoder_dir,'\flac.exe', ' ', tmpfile, ' ', ' -4 ', ' -f ',' -o ',FLACFILE]);
    case {'6'}
        [stat,info_out] = dos([encoder_dir,'\flac.exe', ' ', tmpfile, ' ', ' -5 ', ' -f ',' -o ',FLACFILE]);
    case {'7'}
        [stat,info_out] = dos([encoder_dir,'\flac.exe', ' ', tmpfile, ' ', ' -6 ', ' -f ',' -o ',FLACFILE]);
    case {'8'}
        [stat,info_out] = dos([encoder_dir,'\flac.exe', ' ', tmpfile, ' ', ' -7 ', ' -f ',' -o ',FLACFILE]);
    case {'9'}
        [stat,info_out] = dos([encoder_dir,'\flac.exe', ' ', tmpfile, ' ', ' -8 ', ' -f ',' -o ',FLACFILE]);
    otherwise
        error('Encoding parameters not suported')
        stat = 2;
end
compression_ratio_ini = findstr(info_out,'bytes, ratio=');
compression_ratio_end = compression_ratio_ini+18;
compression_ratio = info_out(compression_ratio_ini+6:compression_ratio_end);
if stat == 1
    delete(FLACFILE);
    delete(tmpfile);
    error('Error while encoding')
end
%Delete temporary file
delete(tmpfile);


if ~isempty(strfind(fsub,'.mat'))
    dat = load(fsub);
    if isfield(dat,'X')
        X = dat.X;
    else
        X = getfield(dat,char(fieldnames(dat)));
    end
    clear dat
elseif ~isempty(strfind(fsub,'.txt'))
    X = dlmread(fsub);
else % no extension - assumed to be an SPM file
    try % Note that we are not taking care of bad samples here
        D = spm_eeg_load(fsub);
        X = permute(D(:,:,:),[2 3 1]); clear D
        X = reshape(X,[size(X,1)*size(X,2) size(X,3)]);
    catch
        if ~exist('spm_eeg_load','file')
            error('spm_eeg_load() function not found - is SPM in the path?')
        else
            error('Incorrect data format - input files must be .mat, .txt or an SPM file');
        end
    end
end


% std_renamestudyfiles() - rename files for design 1 if necessary. In design
%                          1, for backward compatibility, files could have
%                          legacy names. For consistency these files now
%                          need to be renamed. Note that the STUDY is
%                          automatically resave on disk to avoid any potential
%                          inconsistency.
%
% Usage:
%   >> STUDY = std_renamestudyfiles(STUDY, ALLEEG)
%
% Inputs:
%   STUDY      - EEGLAB STUDY set
%   ALLEEG     - vector of the EEG datasets included in the STUDY structure
%
% Output:
%      STUDY - The input STUDY with new design files.
%
% Author: Arnaud Delorme, Institute for Neural Computation UCSD, 2013-

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

function STUDY = std_renamestudyfiles(STUDY, ALLEEG)

if nargin < 2
    help std_renamestudyfiles;
    return;
end;

STUDY2 = std_makedesign(STUDY, ALLEEG, 1, STUDY.design(1), 'defaultdesign', 'forceoff', 'verbose', 'off');
allCell1 = {  STUDY.design(1).cell.filebase };
allCell2 = { STUDY2.design(1).cell.filebase };

fileExtensions = { 'daterp' 'datspec' 'datersp' 'daterpim' 'dattimef' 'datitc' 'daterpim' ...
    'icaerp' 'icaspec' 'icaersp' 'icaerpim' 'icatimef' 'icaitc' 'icaerpim' };

if ~isequal(allCell1, allCell2)

    thereIsAFileNotDesign = false;
    for index = 1:length(allCell1), if length(allCell1{index}) < 6 || all(allCell1{index}(1:6) == 'design'), thereIsAFileNotDesign = true; end; end;
    for index = 1:length(allCell1), if length(allCell1{index}) < 6 || all(allCell1{index}(1:6) == 'design'), thereIsAFileNotDesign = true; end; end;

    if thereIsAFileNotDesign
        res = questdlg2(['Old STUDY design data files have been detected.' 10 ...
            'EEGLAB wants to rename these files to improve consistency' 10 ...
            'and stability. No dataset will be renamed, only preprocessed' 10 ...
            'STUDY data files.' ], 'Rename STUDY data files', 'Cancel', ...
            'Rename', 'Rename');

        if strcmpi(res, 'rename')
            STUDY = pop_savestudy(STUDY, ALLEEG, 'savemode', 'resave');
            for iCell = 1:length(allCell1)

                % scan file extensions
                for iExt = 1:length(fileExtensions)
                    files = dir( [ allCell1{iCell} '.' fileExtensions{iExt} ]);
                    if ~isempty(files) && ~strcmpi(allCell1{iCell}, allCell2{iCell})
                        movefile( [ allCell1{iCell} '.' fileExtensions{iExt} ], ...
                            [ allCell2{iCell} '.' fileExtensions{iExt} ]);
                        disp([ 'Moving ' [ allCell1{iCell} '.' fileExtensions{iExt} ] ' to ' [ allCell2{iCell} '.' fileExtensions{iExt} ] ]);
                    end;
                end;
            end;
            STUDY = STUDY2;
            STUDY = pop_savestudy(STUDY, ALLEEG, 'savemode', 'resave');
        end;
    end;
end;


%
% In this file, we mex the C files used in this package.

clear, clc;
current_path=cd;

%% Output infor
%%
fprintf('\n ----------------------------------------------------------------------------');
fprintf('\n The program is mexing the C files. Please wait...');
fprintf('\n If you have problem with mex, you can refer to the help of Matlab.');
fprintf('\n If you cannot solve the problem, please contact with Jun Liu (j.liu@asu.edu)\n\n');

%% currently, this package uses the following C files
%%            (in the folder /SLEP/CFiles)

% files in the folder q1
cd([current_path '/SLEP/CFiles/q1']);
mex epp.c;
mex ep1R.c;
mex ep21d.c;
mex ep21R.c;
mex eplb.c;
mex eppMatrix.c;
mex eppVector.c;
mex eppVectorR.c;
mex epsgLasso.c;

% file in the folder flsa
cd([current_path '/SLEP/CFiles/flsa']);
mex flsa.c;

% file in the folder SpInvCoVa
cd([current_path '/SLEP/CFiles/SpInvCoVa']);
mex invCov.c;

% files in the folder tree
cd([current_path '/SLEP/CFiles/tree']);
mex altra.c;
mex altra_mt.c;
mex computeLambda2Max.c;
mex treeNorm.c;
mex findLambdaMax.c;
mex findLambdaMax_mt.c;

mex general_altra.c;
mex general_altra_mt.c;
mex general_treeNorm.c;
mex general_findLambdaMax.c;
mex general_findLambdaMax_mt.c;

% files in the folder order
cd([current_path '/SLEP/CFiles/order']);
mex orderTree.c;
mex orderTree_without_nonnegative.c;
mex orderTreeBinary.c;
mex orderTreeDepth1.c;
mex sequence_bottomup.c;
mex sequence_topdown.c;

%% Output infor
%%
fprintf('\n\n The C files in the folder CFiles have been successfully mexed.');
fprintf('\n\n You can now use the functions in the folder SLEP.');
fprintf('\n You are suggested to read the manual for better using the codes.');
fprintf('\n You are also suggested to run the examples in the folder Examples for these functions.');
fprintf('\n\n These codes are being developed by Jun Liu and Jieping Ye at Arizona State University.');
fprintf('\n If there is any problem, please contact with Jun Liu and Jieping Ye ({j.liu,jieping.ye}@asu.edu).');
fprintf('\n\n Thanks!');
fprintf('\n ----------------------------------------------------------------------------\n');

cd(current_path);


classdef SubcellsMesherFactory < handle

    methods (Access = public, Static)

        function obj = create(cParams)
            ndimIso = cParams.ndimIso;
            type    = cParams.type;
            switch ndimIso
                case 'Line'
                    obj = SubcellsMesher_1D(cParams);
                case 'Surface'
                    switch type
                        case 'INTERIOR'
                            obj  = SubcellsMesher_Interior(cParams);
                        case 'BOUNDARY'
                            obj = SubcellsMesher_Boundary_2D(cParams);
                    end
                case 'Volume'
                    switch type
                        case 'INTERIOR'
                            obj = SubcellsMesher_Interior(cParams);
                        case 'BOUNDARY'
                            obj = SubcellsMesher_Boundary_3D(cParams);
                    end
            end
        end

    end
end


function z = cvxprob( varargin )

global cvx___
if ~iscellstr( varargin ),
    error( 'Arguments must be strings.' );
end

%
% Clear out any old problems left at this depth. These will be here due to
% an error while constructing a CVX model, or due to the user deciding to
% start over when constructing a model
%

cvx_global
st = dbstack;
depth = length( st ) - 2;
if length(st) <= 2,
    name = '';
else
    name = st(3).name;
    if cvx___.mversion < 7,
        name = name(max(find(name==filesep))+1:end-2);
    end
end
if ~isempty( cvx___.problems ),
    ndx = find( [ cvx___.problems.depth ] >= depth );
    if ~isempty( ndx ),
        temp = cvx___.problems(ndx(1));
        if temp.depth == depth && ( ~isempty(temp.objective) || ~isempty(temp.variables) || ~isempty(temp.duals) || nnz(temp.t_variable) > 1 );
            warning( 'CVX:Empty', 'A non-empty cvx problem already exists in this scope.\n   It is being overwritten.', 1 ); %#ok
        end
        cvx_pop( temp.self, 'reset' );
    end
end

%
% Grab the latest defaults to place in the new problem
%

if ~isempty( cvx___.problems ),
    nprec  = cvx___.problems( end ).precision;
    ngprec = cvx___.problems( end ).gptol;
    nrprec = cvx___.problems( end ).rat_growth;
    nsolv  = cvx___.problems( end ).solver;
    nquiet = cvx___.problems( end ).quiet;
else
    nprec  = cvx___.precision;
    ngprec = cvx___.gptol;
    nrprec = cvx___.rat_growth;
    nsolv  = cvx___.solver;
    nquiet = cvx___.quiet;
end

%
% Construct the object
%

z = class( struct( 'index_', length( cvx___.problems ) + 1 ), 'cvxprob', cvxobj );
temp = struct( ...
    'name',          name,   ...
    'complete',      true,   ...
    'sdp',           false,  ...
    'gp',            false,  ...
    'separable',     false,  ...
    'locked',        false,  ...
    'precision',     nprec,  ...
    'solver',        nsolv,  ...
    'gptol',         ngprec, ...
    'quiet',         nquiet, ...
    'cputime',       cputime, ...
    'rat_growth',    nrprec, ...
    't_variable',    logical( sparse( length( cvx___.reserved ), 1 ) ), ...
    'n_equality',    length(cvx___.equalities), ...
    'n_linform',     length(cvx___.linforms), ...
    'n_uniform',     length(cvx___.uniforms), ...
    'variables',     [],         ...
    'duals',         [],         ...
    'dvars',         [],         ...
    'direction',     '',         ...
    'geometric',     [],         ...
    'objective',     [],         ...
    'status',        'unsolved', ...
    'result',        [],         ...
    'depth',         depth, ...
    'self',          z );
temp.t_variable( 1 ) = true;

%
% Process the argument strings
%

for k = 1 : nargin,
    mode = varargin{k};
    switch lower( mode ),
        case 'quiet',
            temp.quiet = true;
        case 'set',
            temp.complete  = false;
            temp.direction = 'find';
        case 'sdp',
            if temp.gp,
                error( 'The GP and SDP modifiers cannot be used together.' );
            end
            temp.sdp = true;
        case 'gp',
            if temp.sdp,
                error( 'The GP and SDP modifiers cannot be used together.' );
            end
            temp.gp = true;
            if cvx___.expert == 0,
                cvx___.expert = -1;
            end
        case 'separable',
            temp.separable = true;
        otherwise,
            error( 'Invalid CVX problem modifier: %s', mode );
    end
end

%
% Add the problem to the stack
%

if isempty( cvx___.problems ),
    cvx___.problems = temp;
    cvx_setpath(1);
    if cvx___.profile,
        profile resume
    end
else
    cvx___.problems( end + 1 ) = temp;
end

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


function allowaxestogrow(f)
%
% Call allowaxestogrow(f) on a figure f with multiple sub-axes.
%
% Then, whenever one of the axes is clicked, it zooms to
% the size of the window (or a preset user-defined size).
% When clicked again, the axis returns to its original position.
%
% Useful when you have a number of tiny subplots in a figure window,
% and would like to be able to visually inspect them without squinting.
%
% To set the zoomed (large) size for an axis ax:
%   setappdata(ax,'LastPosition',[LEFT BOTTOM WIDTH HEIGHT]);
% For colorbars, [0 0 0.85 1] usually works well.
%
% Version history:
%
% 0.40: Use get/setappdata instead of userdata. Use only one button-down
%       function. Add some extra links between axes for extensibility.
%       Suggestions by Jonas. 2009.05
% 0.32: Ensure invisible patch is created with correct figure parent. 2009.05
% 0.31: Try to preserve plot order better; reorder plots upon shrinking
%       so that overlay axes, etc. are better respected. Still not perfect --
%       ideally we'd preserve the original exact plot order. 2009.05
%       Preserve plot aspect ratio when creating invisible axes, following
%       suggestion by Jonas. 2009.04
%
% 0.30: Much simplified by using invisible patches to trap clicks.
%       Now requires Matlab's OpenGL renderer which may cause side effects
%       on some systems.
%       Also, allows user to set predefined size for zoomed plot.
%       Among other things, this makes colorbars finally work well. 2009.02
%
% 0.22: add workaround for reported bug when axis type is a cell array.
%       also add click support for patches.  2007.06
% 0.21: add some support for colorbars 2007.06.
% 0.20: modified to support clicks on images and lines following suggestion
%       from Jessica Louie 2007.05
% 0.11: Added code from Iram Weinstein to keep legends
%       from disappearing. 2005.08
% 0.10: Written by Matthew Caywood, <caywood@phy.ucsf.edu>, 2005.06
%
% Known bugs:
%
% Possible error if axes are plotted on top of panels.
% I don't use panels, so I'm not currently supporting them.
% Bugfixes are welcome, though. (reported by Scott Hirsch)
%
% With multiple axes in a subplot, clicks will sometimes magnify the wrong
% one, making the plot order wonky. For now, just keep clicking and it
% should fix itself.

if nargin==0, f=gcf; end

set(f,'Renderer','OpenGL');

% MSC necessary to avoid an OpenGL renderer bug where axes are flipped
% If you're having rendering problems, comment out the following line:
opengl('OpenGLBitmapZbufferBug',0)

% Cover all subplot axis children of figure f with an identically sized axis
% containing an invisible patch which triggers an event when clicked.
% Do not add to legends or colorbars.
ch = get(f,'Children');
for i = 1:length(ch)
    ax = ch(i);
    if (strcmp(get(ax,'Type'),'axes')) && ...
       ~strcmp(get(ax,'Tag'),'legend') && ...
       ~strcmp(get(ax,'Tag'),'Colorbar')

        % invisible invisax contains patch p which traps clicks,
        invisax = axes('Position',get(ax,'Position'), ...
                       'PlotBoxAspectRatioMode',get(ax,'PlotBoxAspectRatioMode'),...
                       'DataAspectRatioMode',get(ax,'DataAspectRatioMode'),...
                       'NextPlot','add');
        % invisax contains a link to ax in appdata
        setappdata(invisax,'VisibleAxes',ax);
        setappdata(invisax,'State',0); % 1 = enlarged, 0 = normal/shrunk
        axis off;

        p = patch([0 0 1 1],[0 1 1 0],[0 0 0 0],'w');
        set(p,'FaceAlpha',0);
        set(p,'EdgeAlpha',0);
        set(p,'ButtonDownFcn',@togglesubplot);

        % tag the invisible axes so that they can be manipulated as necessary
        set(p,'Tag','catchPatch')
        setappdata(ax,'catchPatchHandle',p);
        setappdata(ax,'InvisibleAxes',invisax);

        % ensure invisible patch gets put on right figure
        % MSC should not be necessary -- may work around
        % bug when creating figures quickly, at least in R14
        set(invisax,'Parent',f);
    end
end

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

function togglesubplot(src,eventdata) %#ok

% default size of enlarged axes, modify as necessary
presetaxes = [0.05 0.05 0.9 0.9];

% patch p was clicked, get invisax and ax
p = src;
invisax = get(p,'Parent');
ax = getappdata(invisax,'VisibleAxes');
state = getappdata(invisax,'State');

% get current & last position
currentpos = get(ax,'Position');
futurepos = getappdata(ax,'LastPosition');
if isempty(futurepos), futurepos = presetaxes; end

% swap current & last position
set(ax,'Position',futurepos);
set(invisax,'Position',futurepos);

setappdata(ax,'LastPosition',currentpos);

% get order of parent figure's children
f = get(ax,'Parent');
ch = get(f,'Children');

if state == 1
    % shrink
    % send invisax and ax to back
    newch = [ch(ax ~= ch & invisax ~= ch) ; invisax ; ax];
    set(f,'Children',newch);
else
    % enlarge
    % change order of parent figure's children so clicked axis
    % is drawn on top.  But keep legend uppermost, if present.

    % Find a legend for the current subplot, if it exists
    ax = findobj(ax,'type','axes');
    leg = find_legend(ax);

    % move invisax and ax to top, then move legend if present
    newch = [invisax ; ax ; ch(ax ~= ch & invisax ~= ch)];
    if ~isempty(leg)
        newch = [leg ; newch(leg ~= newch)];
    end
    set(f,'Children',newch);
end

setappdata(invisax,'State',~state); % toggle state

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

function leg = find_legend(ha)
% returns handle to legend
% from legend.m

fig = ancestor(ha,'figure');
ax = findobj(fig,'type','axes');
leg=[];
k=1;
while k<=length(ax) && isempty(leg)
    if islegend(ax(k))
        hax = handle(ax(k));
        if isequal(double(hax.axes),ha)
            leg=ax(k);
        end
    end
    k=k+1;
end

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

function tf=islegend(ax)
% from legend.m

if length(ax) ~= 1 || ~ishandle(ax)
    tf=false;
else
    tf=isa(handle(ax),'scribe.legend');
end


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

%%
clear; close all; clc;

%% Syntax
% |FUNCTION_NAME|

%% Description
% FUNCTION_NAME

%% Examples

%%
% Plot settings

%% Example:

%%
%
% <<gibbVerySmall.gif>>
%
% _*GIBBON*_
% <www.gibboncode.org>
%
% _Kevin Mattheus Moerman_, <gibbon.toolbox@gmail.com>

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


% corrmap_createclust() - creates a new cluster in the STUDY structure
%                         containing the ICs selected and stored using
%                         corrmap() function.
%
% Usage:
%          >> STUDY = corrmap_createclust(STUDY,CORRMAP)
%
% Inputs:
%  STUDY - input STUDY structure
%  ALLEEG - input ALLEEG structure
%
% Outputs:
%  STUDY - the input STUDY set structure modified with the new cluster.
%
% See also:  pop_corrmap(), corrmap()
%
% Author: F. Campos Viola, MRC-IHR, 19/10/2007

%123456789012345678901234567890123456789012345678901234567890123456789012

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

% revised by F Campos-Viola - corrmap1.01 (30/01/2009)

function STUDY = corrmap_createclust(STUDY,CORRMAP)

clusters = [];

cls = length(STUDY.cluster)+1;% number of cluster
nc  = length(STUDY.cluster); % index of last cluster

%%%%% CREATING NEW CLUSTER %%%%%

STUDY.cluster(cls).name = CORRMAP.input.clname; %cluster's name

%auxiliary variables to create matrix with indices - used to access
%correct preclustdata

% saving info int the STUDY.cluster fields
STUDY.cluster(cls).sets  = CORRMAP.corr.sets{2}(1:CORRMAP.clust.ics(2))';
STUDY.cluster(cls).comps = CORRMAP.corr.ics{2}(1:CORRMAP.clust.ics(2))';
STUDY.cluster(cls).algorithm = 'correlation (CORRMAP)';
STUDY.cluster(cls).parent = 'ParentCluster 1';
STUDY.cluster(cls).child = [];
STUDY.cluster(cls).centroid = [];
%STUDY.cluster(cls).preclust.preclustdata = STUDY.etc.preclust.preclustdata(ind,:);
STUDY.cluster(cls).preclust.preclustdata = STUDY.etc.preclust.preclustdata
STUDY.cluster(cls).preclust.preclustparams = STUDY.etc.preclust.preclustparams;
STUDY.cluster(cls).preclust.preclustcomps = STUDY.etc.preclust.preclustcomps;

%update parents clusters with cluster child indices
STUDY.cluster(1).child{cls-1} = CORRMAP.input.clname;

% clusters = [clusters 1:cls];%the new created clusters indices.

fprintf('>');
fprintf('a new cluster was created. \n'); %info for the user


function w = arrivals2waveforms(dbpath, arrivals, pretrig, posttrig, taper_seconds, nwaveforms)
% ARRIVALS2WAVEFORMS Load waveform objects corresponding to an arrivals structure
%	w = ARRIVALS2WAVEFORMS(dbpath, arrivals, pretrig, posttrig, taper_seconds, maxNumberOfWaveforms)
	w = waveform(); % Initialize output

	% Check input variables.
	if nargin<4
		disp('Incorrect number of input variables')
		return
	end

	% Create datasource
	ds = datasource('antelope', dbpath);

	% Loop over arrivals structure
	for i=1:min([nwaveforms numel(arrivals.arid)])
        scnl = scnlobject(arrivals.sta{i}, arrivals.chan{i});
		snum = epoch2datenum(arrivals.time(i) - pretrig - taper_seconds);
		enum = epoch2datenum(arrivals.time(i) + posttrig + taper_seconds);
        try
            thisw = waveform(ds, scnl, snum, enum);
        end
        if numel(thisw)==1
            w(i) = thisw;
        else
            w(i)=waveform();
        end
	end
end


function sbmlModel = convertCobraToSBML(model, sbmlLevel, sbmlVersion, compSymbolList, compNameList)
% Converts a cobra structure to an sbml structure - kept for backward Compatability
%
% USAGE:
%
%    sbmlModel = convertCobraToSBML(model, sbmlLevel, sbmlVersion, compSymbolList, compNameList)
%
% INPUT:
%    model:             COBRA model structure
%
% OPTIONAL INPUTS:
%    sbmlLevel:         SBML Level (ignored! level 3 is used)
%    sbmlVersion:       SBML Version (ignored! version 1 is used)
%    compSymbolList:    List of compartment symbols
%    compNameList:      List of copmartment names correspoding to `compSymbolList`
%
% OUTPUT:
%    sbmlModel:         SBML MATLAB structure
%
% .. Authors:
%    - Longfei Mao 24/09/15 FBCv2 support added
%    - Thomas Pfau 19/09/2016 reinstantiated for backward compatability
% NOTE:
%
%    sbmlLevel and sbmlVersion are ignored by this function and it is just
%    kept for backward compatability and might be deprecated in future
%    versions.

warning('This function is likely to be deprecated in future COBRA Toolbox version.')

TemporaryFileName = [tempname '.xml'];

if ~exist('compSymbolList','var') || ~exist('compNameList','var')
    sbmlModel = writeSBML(model,TemporaryFileName);
else
    sbmlModel = writeSBML(model,TemporaryFileName,compSymbolList,compNameList);
end

delete(TemporaryFileName)


% Init Script
% Remarks:
%   1.  sa
% TODO:
% 	1.  ds
% Release Notes
% - 1.0.000     08/11/2016  Royi Avital
%   *   First release.
%

%% General Parameters
close('all');
clear();
clc();

% set(0, 'DefaultFigureWindowStyle', 'docked');
% defaultLoosInset = get(0, 'DefaultAxesLooseInset');
% set(0, 'DefaultAxesLooseInset', [0.05, 0.05, 0.05, 0.05]);

figPosSmall     = [100, 100, 400, 300];
figPosMedium    = [100, 100, 800, 600];
figPosLarge     = [100, 100, 960, 720];
figPosDefault   = [100, 100, 560, 420];

fontSizeTitle   = 14;
fontSizeAxis    = 12;
fontSizeString  = 12;

lineWidthThin   = 1;
lineWidthNormal = 3;
lineWidthThick  = 4;

markerSizeSmall     = 4;
markerSizeNormal    = 8;
markerSizeLarge     = 10;

randomNumberStream  = RandStream('mlfg6331_64', 'NormalTransform', 'Ziggurat');
subStreamNumber     = round(sum(clock()));
% subStreamNumber     = 162;
subStreamNumber     = 2122;
set(randomNumberStream, 'Substream', subStreamNumber);
RandStream.setGlobalStream(randomNumberStream);

FALSE   = 0;
TRUE    = 1;

OFF     = 0;
ON      = 1;


function [ts,sr]=readnist(filename,sr);

% READNIST
%
%  [ts,sr]= READNIST (filename,[sr])
%
%  Reads NIST WAV/SPHERE files, such as those in N/C/TIMIT or
%  Switchboard or Mandarin-VOA TDT files.
%
%  filename can be provided with or without the .wav/.sph/.WAV/.SPH extension.
%
%  Example usage: to read '/blah/blah1/timit/dr1/fcjf0/sa1.wav' just say
%    [ts,sr] = readnist ('/blah/blah1/timit/dr1/fcjf0/sa1');
%  or
%    [ts,sr] = readnist ('/blah/blah1/timit/dr1/fcjf0/sa1.wav');
%
%  To read the ntimit file '/blah/blah1/ntimit/dr1/fcjf0/SA1.SPH'
%  just say
%    [ts,sr] = readnist ('/blah/blah1/ntimit/dr1/fcjf0/SA1');
%  or
%    [ts,sr] = readnist ('/blah/blah1/ntimit/dr1/fcjf0/SA1.SPH');
%
%  ts is a Nx1 vector of entries representing the sound sample in filename
%  sr represents the sample rate, and you DON'T have to supply it - this
%     function works it out from the file headers automatically.
%     If you do supply it, any sample rate info contained in headers is ignored.
%  The sr that is returned is
%    : the one input, or (if none is input)
%    : the sample rate in the file, or
%    : 0 (if no sample rate is supplied by the user or the file headers)
%
%  The first line of filename should have NIST_1A in its header
%    otherwise ts = [] and sr = 0
%
% Assumptions:
%  - first line of file has NIST_1A
%  - second line has an integer, usually 512 or 1024, that has the number of
%     bytes in the header
%  - the header has a line of the form "sample_rate -i D", where D is an
%     integer like 16000 that is the sampling rate in Hertz.
%  - the header has a line with "sample_byte_format" (if not, little endian
%     is assumed) and if so, that this line is either
%     "sample_byte_format -s2 01" (little endian) or
%     "sample_byte_format -s2 10" (big endian)
%
% You should be able to play the sound with the Matlab command
%   soundsc (ts,sr)
% afterwards, assuming your sound card exists and works. (If it doesnt,
% pray hard, and try again.)
%
% This file has only been tested on TIMIT, NTIMIT, CTIMIT and Switchboard (ICSI-WS97) files.
%
%	Author : D.Surendran 04/24/04 (dinojatcsdotuchicagodotedu)
%
% NOTE ON SHORTENED FILES
% Update: if you are on a unix-based system, you can also read
%   'shorten'ed files. This requires that you change the current
%   Matlab directory to one where you have write permission and
%   enough space to store an uncompressed version of the sound
%   file. The uncompressed file will be deleted afterwards, dont
%   worry!
%     The current directory should also have a copy of shorten
%   (If not, modify the command in this file that reads
%
%     cmd = ['shorten -x -d' num2str(headerlen) ' ' filename ' ' tmpfilename ';'];
%

% Acknowledgements to documentation http://ftp.cwi.nl/audio/NIST-SPHERE
% and the readtimit.m file by C.E.Ho 8/20/97 (which this file is meant to replace)

ts = [];

if nargin < 2
  sr = 0;
end
if nargin < 1
  error ('You need to have at least one input!');
end

exts = {'wav','WAV','sph','SPH'};
extsor = '';
if ~exist (filename)
  for i = 1 : length (exts)
    extsor = [extsor '.' exts{i}];
    if (i ~= length(exts))
      extsor = [extsor ' or '];
    end
    fn = [filename '.' exts{i}];
    if exist (fn)
      filename = fn;
      break;
    end
  end
end
if ~exist (filename)
  error (sprintf ('%s not found (even with %s added)',filename, extsor));
end

s=textread(filename,'%s',2);

if length(s) >= 1
  a= findstr(s{1},'NIST_1A');
  if ~(length(a)) | ~a
    error (sprintf('Not a NIST Sphere file : first line of %s doesnt contain NIST_1A',filename));
  end
else
  error (sprintf('Not a NIST Sphere file : first line of %s isnt a header',filename));
end

if length(s) >= 2
  headerlen = floor (str2num (s{2}));
  if 0 == headerlen
    error (sprintf('Second line of %s should have the header length in bytes',filename));
  end
end

fid = fopen (filename,'rt','ieee-le');             % doesnt matter which endian it is when reading ascii headers
[a,count] = fread (fid,headerlen,'uchar');         % uchar is default anyway
header = char(a');                                 % a is a vector of ascii values,
                                                   % header is an ascii string

headersplit = strread (header, '%s', length(header),'delimiter','\n');

% headersplit{i} has the i-th line of the file header

endian = 0;
useshorten = 0;
for i = 1 : length(headersplit)
  if findstr (headersplit{i},'sample_rate') & (0 == sr)
    sr = strread (headersplit{i}, 'sample_rate -i %d');
  end
  if findstr (headersplit{i},'sample_byte_format')
    endian = strread (headersplit{i}, 'sample_byte_format -s2 %d');
  end
  if findstr (headersplit{i},'sample_coding') & findstr (headersplit{i},'shorten')
    useshorten = 1;
  end
end

if (0 == sr)
  error ('What is the sample rate for this file? Cant find the sample_rate line');
end
if (0 == endian)
  warning (sprintf ('%s does not have byte format coded, assuming little endian'));
  endian = 'le';
elseif (1 == endian)
    endian = 'le';
elseif (10 == endian)
  endian = 'be';
else
  error ('error parsing line with sample_byte_format - cant work out whether this file is little or big endian');
end
fclose (fid);

if 1 == useshorten
  if ~isunix
     error ([filename 'needs to be uncompressed with Tony Robinsons' ...
	     'program - this can be done, but only when' ...
	     'this Matlab code is run on a unix-based system.' ...
	     'I cant get the ! command to behave like the' ...
	     'unix command in Matlab. Sorry! Note that' ...
	     'readnist works ok on windows for unshortened' ...
	     'NIST_1A sound files.']);
  end
  if 0 == exist ('shorten')
     error ([filename 'needs to be uncompressed with Tony Robinsons' ...
	     ' shorten program. Please installit from' ...
	     ' http://www.hornig.net/shorten/ and add its'...
	     ' directory to the Matlab path.']);
  end

  tmpfilename = ['uncompressed_' filename];

  cmd = ['./shorten -x -d' num2str(headerlen) ' ' filename ' ' tmpfilename ';'];
  unix (cmd);

  fid=fopen(tmpfilename,'r',['ieee-' endian] );
else
  fid=fopen(filename,'r',['ieee-' endian] );
end;

junk=fread(fid,headerlen,'short');
ts=fread(fid,Inf, 'short');
fclose(fid);

if (1 == useshorten) & isunix
  unix (['rm ' tmpfilename]);
else
  warning (['temporary file ' tmpfilename ' still exists!']);
end


function experiments = stack_vottir2016()

set_global_variable('bundle', 'http://data.votchallenge.net/vot2016/vot-tir2016.zip');

baseline.name = 'baseline';
baseline.converter = [];
baseline.type = 'supervised';
baseline.tags = {'camera_motion', 'dynamics_change', 'occlusion', 'size_change', 'motion_change', 'empty'};

baseline.parameters.repetitions = 15;
baseline.parameters.burnin = 10;
baseline.parameters.skip_initialize = 5;
baseline.parameters.failure_overlap = 0;

experiments = {baseline};

end


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

%% -*- texinfo -*-
%% @documentencoding UTF-8
%% @deftypemethod  @@symfun {@var{d} =} size (@var{x})
%% @deftypemethodx @@symfun {[@var{n}, @var{m}] =} size (@var{x})
%% @deftypemethodx @@symfun {@var{d} =} size (@var{x}, @var{dim})
%% Return the size of a symbolic function.
%%
%% This behaves differently than for @@sym:
%% @example
%% @group
%% syms x y
%% f(x, y) = [1 x; y 2];
%%
%% size(f)
%%   @result{} 1  1
%% @end group
%%
%% @group
%% length(f)
%%   @result{} 1
%% @end group
%% @end example
%%
%% @seealso{@@sym/size}
%% @end deftypemethod

function [n, m] = size(x, dim)

  n = [1 1];
  if (nargin == 2) && (nargout == 2)
    print_usage ();
  elseif (nargout == 2)
    m = 1;
    n = 1;
  elseif (nargin == 2)
    n = 1;
  end

end

%!test
%! syms x
%! f(x) = x;
%! d = size(f);
%! assert (isequal (d, [1 1]))
%! [n, m] = size(f);
%! assert (isequal ([n m], [1 1]))
%! assert (size(f, 1) == 1)
%! assert (size(f, 2) == 1)

%!test
%! syms x
%! f(x) = [1 x];
%! d = size(f);
%! assert (isequal (d, [1 1]))
%! [n, m] = size(f);
%! assert (isequal ([n m], [1 1]))
%! assert (size(f, 1) == 1)
%! assert (size(f, 2) == 1)


function X = imag(X)
% REAL (overloaded)

X.basis = imag(X.basis);
X.conicinfo = [0 0];
X = clean(X);


function pagechan(page_num,mode)
% PAGECHAN Change pages within environment.
%          PAGECHAN handles the transition between pages within the
%          Page Setup... environment.

% Author: Craig Borghesani
% Date: 10/16/94
% Revised:
% Copyright (c) 1999, Prentice-Hall

% obtain handle information
f2 = gcf;
f = get(f2,'userdata');
ui_data = get(f,'userdata');
ui_han = ui_data{1};
ui_han2 = get(ui_han(49),'userdata');

% variables internal to Page Setup... interface
page_setup = get(ui_han2(1),'userdata');
ptch = get(ui_han2(2),'userdata');
txt = get(ui_han2(3),'userdata');

set(txt,'string',['Page ',int2str(page_num),' Layout']);

% first, how many plots on this page
plots = page_setup(:,page_num);
plots(find(plots==0)) = [];
set(ui_han2(4),'userdata',length(plots));

color_mat = [1,0,0;0,1,0;0,0,1;1,1,0;0,1,1;0.5,0,0;0,0.5,0;0,0,0.5];
if ~mode,
 set(ui_han2(1),'value',page_num);
 set(ui_han2(2:9),'back','w','value',0);
 for k = 1:length(plots),
  set(ui_han2(plots(k)+1),'back',color_mat(plots(k),:),'value',1);
 end
end

% locations of patchs
fig_wdt = 780;
frm_wdt = 190;

%axs1_l = (frm_wdt+2+60)/fig_wdt;
axs1_l = 0.07;
axs1_b = 0.15;
%axs1_w = 0.97 - axs1_l;
axs1_w = 0.97 - (frm_wdt+2+60)/fig_wdt;
axs1_h = 0.68;

axs2_b = 0.58;
axs2_w = axs1_w/2 - 0.05;
axs2_l = axs1_l + axs2_w + 0.1;
%axs2_h = axs2_w;
axs2_h = 0.26;

%axs1_l = (frm_wdt+2+60)/fig_wdt;
%axs1_b = 0.15;
%axs1_w = 0.97 - axs1_l;
%axs1_h = 0.68;

%axs2_b = 0.58;
%axs2_w = axs1_w/2 - 0.05;
%axs2_l = axs1_l + axs2_w + 0.1;
%axs2_h = axs2_w;

set(ptch,'vis','off');
if length(plots)==1,
 xpos1 = [axs1_l, axs1_l+axs1_w, axs1_l+axs1_w, axs1_l];
 ypos1 = [axs1_b, axs1_b, axs1_b+axs1_h, axs1_b+axs1_h];
 set(ptch(1),'vis','on','facecolor',get(ui_han2(plots(1)+1),'back'),...
             'xdata',xpos1,'ydata',ypos1);

elseif length(plots)==2,
 xpos1 = [axs1_l, axs1_l+axs1_w, axs1_l+axs1_w, axs1_l];
 ypos1 = [axs2_b, axs2_b, axs2_b+axs2_h, axs2_b+axs2_h];
 ypos2 = [axs1_b, axs1_b, axs1_b+axs2_h, axs1_b+axs2_h];
 set(ptch(1),'vis','on','facecolor',get(ui_han2(plots(1)+1),'back'),...
             'xdata',xpos1,'userdata',plots(1),'ydata',ypos1);
 set(ptch(2),'vis','on','facecolor',get(ui_han2(plots(2)+1),'back'),...
             'xdata',xpos1,'userdata',plots(2),'ydata',ypos2);

elseif length(plots)==3,
 xpos1 = [axs1_l, axs1_l+axs1_w, axs1_l+axs1_w, axs1_l];
 ypos1 = [axs2_b, axs2_b, axs2_b+axs2_h, axs2_b+axs2_h];
 xpos2 = [axs1_l, axs1_l+axs2_w, axs1_l+axs2_w, axs1_l];
 ypos2 = [axs1_b, axs1_b, axs1_b+axs2_h, axs1_b+axs2_h];
 xpos3 = [axs2_l, axs2_l+axs2_w, axs2_l+axs2_w, axs2_l];
 ypos3 = [axs1_b, axs1_b, axs1_b+axs2_h, axs1_b+axs2_h];
 set(ptch(1),'vis','on','facecolor',get(ui_han2(plots(1)+1),'back'),...
             'xdata',xpos1,'userdata',plots(1),'ydata',ypos1);
 set(ptch(2),'vis','on','facecolor',get(ui_han2(plots(2)+1),'back'),...
             'xdata',xpos2,'userdata',plots(2),'ydata',ypos2);
 set(ptch(3),'vis','on','facecolor',get(ui_han2(plots(3)+1),'back'),...
             'xdata',xpos3,'userdata',plots(3),'ydata',ypos3);

elseif length(plots)==4,
 xpos1 = [axs1_l, axs1_l+axs2_w, axs1_l+axs2_w, axs1_l];
 ypos1 = [axs2_b, axs2_b, axs2_b+axs2_h, axs2_b+axs2_h];
 xpos2 = [axs2_l, axs2_l+axs2_w, axs2_l+axs2_w, axs2_l];
 ypos2 = [axs2_b, axs2_b, axs2_b+axs2_h, axs2_b+axs2_h];
 xpos3 = [axs1_l, axs1_l+axs2_w, axs1_l+axs2_w, axs1_l];
 ypos3 = [axs1_b, axs1_b, axs1_b+axs2_h, axs1_b+axs2_h];
 xpos4 = [axs2_l, axs2_l+axs2_w, axs2_l+axs2_w, axs2_l];
 ypos4 = [axs1_b, axs1_b, axs1_b+axs2_h, axs1_b+axs2_h];
 set(ptch(1),'vis','on','facecolor',get(ui_han2(plots(1)+1),'back'),...
             'xdata',xpos1,'userdata',plots(1),'ydata',ypos1);
 set(ptch(2),'vis','on','facecolor',get(ui_han2(plots(2)+1),'back'),...
             'xdata',xpos2,'userdata',plots(2),'ydata',ypos2);
 set(ptch(3),'vis','on','facecolor',get(ui_han2(plots(3)+1),'back'),...
             'xdata',xpos3,'userdata',plots(3),'ydata',ypos3);
 set(ptch(4),'vis','on','facecolor',get(ui_han2(plots(4)+1),'back'),...
             'xdata',xpos4,'userdata',plots(4),'ydata',ypos4);
end


function zmap(varargin)
    %% run ZMAP Version 7.X
    %
    % This files start up ZMAP.
    %
    % Options:
    %   -debug    : enables debugging functionality
    %   -restart  : clear all windows and variables, then restart zmap
    %   -initonly : set up zmap paths and prefs, but don't open a window
    %   -RT       : implement real-time mode
    %   -catalog alt_cat: use alt_cat as the prime catalog instead. It may be a variable name, a
    %               ZmapCatalog, or a value that canbe converted by ZmapCatalog
    %
    %
    % Options to be probably implemented
    %   -grid :
    %   -selector :
    %   -shape :
    %   -state :
    %   -bordersonly :
    %
    %
    %
    % MAJOR CHANGES to ZMAP from v 6.0:
    %  - event catalog is now a ZmapCatalog instead of a variable-sized array
    %  - dates/times are handled by MATLAB's built-in datetime and duration data types
    %  - duplicated code has been removed or consolidated
    %  - scripts have been turned into functions and classes (allowing zmap functions to be run programmatically)
    %  - GUI elements have been consolidated, updated
    %  - unreachable code (& scripts not appearing in any menus) have been removed
    %  - added ability to import catalogs from FDSN web services.
    %  - global variables have been minimized. Data sharing occurs through one class.
    %  - only result variables should appear in the base workspace.
    %  - requires minimum of matlab v 2018a,
    %
    %
    %  see README.md and the help for individual parts of ZMAP for other change details
    %

    % The matlab searchpaths are updated, existing windows closed.
    %
    %  Originally created by: Stefan Wiemer  12/94
    %  Modified by: Celso Reyes Spring 2017 - Winter 2018
    %
    % see also: ZmapCatalog, ZmapMainWindow

    global ZG
    % ZG (ZmapGlobal) provides access to all ZMAP's global variables
    % When variables are accessed directly via ZmapGlobal.Data.variablename, they
    % should not modify the original.
    % However, assigning ZmapGlobal.Data to a variable first, provides direct [read/write] access to
    % the variables.
    % This allows assignment.
    %
    %       ZmapGlobal.Data.ra = 100; % value is effectively ignored!
    %       ZG=ZmapGlobal.Data; %provide read/write access to global data.
    %       ZG.ra = 23  % changes ra globally

    % advise matlab where it can find everything zmap
    if ~exist('set_zmap_paths','file')
        p = mfilename('fullpath');
        p(end-length(mfilename) : end) = [];
        addpath(fullfile(p,'src'));
    end
    set_zmap_paths;

    startWindow      = true;
    debugMode        = false;

    possible_options = varargin(cellfun(@ischarlike,varargin));
    options          = lower(possible_options(startsWith(possible_options,'-')));

   setappdata(groot,'ZmapCoordinateSystem', CoordinateSystems.geodetic);

   % set application data

    for option = string(options)
        switch option
            case "-restart"
                msg.infodisp('Restarting ZMAP','initialization')
                restartZmap('restart');
                return

            case "-quit"
                msg.infodisp('Quitting ZMAP','initialization')
                restartZmap('quit');
                return

            case "-debug"
                msg.infodisp('debug mode enabled','initialization')
                debugMode = true;

            case "-initonly"
                msg.infodisp('Initializing Zmap without starting the default main window','initialization')
                startWindow = false;

            case "-rt"
                msg.infodisp('RealTimeMode enabled','initialization');
                setappdata(groot,'ZmapRealTimeMode', true);

            case "-cartesian"
                % must be set prior to acessing ZmapGlobal for the first time
                setappdata(groot,'ZmapCoordinateSystem', CoordinateSystems.cartesian);

                %{

            case {"-catalog"}
                vaa = varargin;
                notstrings =cellfun(@(x)~ischarlike(x),varargin);
                vaa(notstrings)={''};
                idx = find(vaa == "-catalog",1,'last'); %requres all members of vaa be strings
                c = varargin{idx+1};
                if ischarlike(c) && isvarname(c)
                    v=evalin('base',"whos('"+ c +"')");
                    if isempty(v)
                        msg.errordisp("cannot find the variable " + c, 'catalog specified');
                        return
                    end
                    alt_cat = evalin('base',"ZmapCatalog('Name', " + v.name + ")");
                    if isa(alt_cat, 'ZmapCatalog')
                        constructor_options.primeCatalog = alt_cat;
                    end
                    msg.infodisp("set primary catalog to the value from : " + v.name, 'catalog specified');
                else
                    constructor_options.primeCatalog = ZmapCatalog.from(c);
                    msg.infodisp("set primary catalog from a : " + class(c), 'catalog specified');
                end
                    %}

            otherwise
                msg.errordisp('Unknown ZMAP option: ' + option, 'Unknown ZMAP option, stopping');
                return
        end

    end

    switch getappdata(groot,'ZmapCoordinateSystem')
        case CoordinateSystems.geodetic
            setappdata(groot,'ZmapDefaultReferenceEllipsoid',referenceEllipsoid('earth','kilometer'));
        case CoordinateSystems.cartesian
            setappdata(groot,'ZmapDefaultReferenceEllipsoid',nonEllipsoid);
    end

    ZG = ZmapGlobal.Data;
    ZG.debug = debugMode;

    disp(['This is zmap.m - version ', ZmapGlobal.Data.zmap_version])
    % Set up the different computer systems
    sys = computer;

    if verLessThan('matlab',ZG.min_matlab_version)
        baseMsg = 'You are running a version of MATLAB older than %s. ZMAP %s requires MATLAB %s or newer';
        messtext = sprintf(baseMsg, ZG.min_matlab_release, ZG.zmap_version, ZG.min_matlab_version);
        msg.errordisp(messtext,  'Incompatible MATLAB Version');
        errordlg(messtext,'Warning!')
        pause(5)
        return
    end

    tested_systems = {'MAC','PCW'};
    if ~ismember( sys(1:3), tested_systems)
        msg.warndisp('ZMAP has not been tested on this computer type', 'Untested System')
        warndlg('Warning: ZMAP has not been tested on this computer type.','Untested System')
        pause(5)
    end

    assignin('base','ZG',ZmapGlobal.Data);

    % set local preference variables
    ini_zmap

    % set system dependent initial variables
    ini_zmap_sys

    % start the main zmap program
    if startWindow

        %get rid of message box that would exist if zmap was already opened without a catalog
        delete(findall(groot,'Tag','Msgbox_No Active Catalogs'));

        zw = findall(allchild(groot),'Tag','Zmap Main Window');
        s=sprintf('%d ZMAP windows exist\n', numel(zw));
        if ~isempty(zw)
            emptyzw = arrayfun(@(x)~isstruct(x.UserData) || isempty(x.UserData.catalog), zw);
            delete(zw(emptyzw));
            s = s + "... of which " + sum(emptyzw) + " were empty";
        end
        msg.dbdisp(s)
        cw = get(groot,'CurrentFigure');
        if isempty(cw)
            msg.dbdisp('No Figure currently exists');
        else
            switch cw.Tag
                case 'Zmap Main Window'
                    msg.dbdisp('ZMAP Window Exists, and is active')
                otherwise
                    % do nothing
            end
        end
        cw = figure;
        if ~isempty(ZG.primeCatalog) && questdlg('Open previous catalog?','ZMAP','Yes')=="Yes"
            ZmapMainWindow(cw, ZG.primeCatalog);
        else
            ZmapMainWindow(cw, ZmapCatalog);
        end
        if ~isappdata(groot,'ZmapShowTips') || getappdata(groot,'ZmapShowTips')
            show_a_tip();
            setappdata(groot,'ZmapShowTips',false);
        end
    end
end


function data = loadubjson(fname,varargin)
%
% data=loadubjson(fname,opt)
%    or
% data=loadubjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
%            date: 2013/08/01
%
% $Id: loadubjson.m 417 2014-01-21 22:34:49Z fangq $
%
% input:
%      fname: input file name, if fname contains "{}" or "[]", fname
%             will be interpreted as a UBJSON string
%      opt: a struct to store parsing options, opt can be replaced by
%           a list of ('param',value) pairs. The param string is equivallent
%           to a field in opt.
%
% output:
%      dat: a cell array, where {...} blocks are converted into cell arrays,
%           and [...] are converted to arrays
%
% license:
%     BSD license, see LICENSE_BSD.txt files for details
%
% -- this function is part of jsonlab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%

global pos inStr len  esc index_esc len_esc isoct arraytoken

if(regexp(fname,'[\{\}\]\[]','once'))
   string=fname;
elseif(exist(fname,'file'))
   fid = fopen(fname,'rb');
   string = fread(fid,inf,'uint8=>char')';
   fclose(fid);
else
   error('input file does not exist');
end

pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\','  ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);

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

opt=varargin2struct(varargin{:});
jsoncount=1;
while pos <= len
    switch(next_char)
        case '{'
            data{jsoncount} = parse_object(opt);
        case '['
            data{jsoncount} = parse_array(opt);
        otherwise
            error_pos('Outer level structure must be an object or an array');
    end
    jsoncount=jsoncount+1;
end % while

jsoncount=length(data);
if(jsoncount==1 && iscell(data))
    data=data{1};
end

if(~isempty(data))
      if(isstruct(data)) % data can be a struct array
          data=jstruct2array(data);
      elseif(iscell(data))
          data=jcell2array(data);
      end
end

%%
function newdata=parse_collection(id,data,obj)

if(jsoncount>0 && exist('data','var'))
    if(~iscell(data))
       newdata=cell(1);
       newdata{1}=data;
       data=newdata;
    end
end

%%
function newdata=jcell2array(data)
len=length(data);
newdata=data;
for i=1:len
      if(isstruct(data{i}))
          newdata{i}=jstruct2array(data{i});
      elseif(iscell(data{i}))
          newdata{i}=jcell2array(data{i});
      end
end

%%-------------------------------------------------------------------------
function newdata=jstruct2array(data)
fn=fieldnames(data);
newdata=data;
len=length(data);
for i=1:length(fn) % depth-first
    for j=1:len
        if(isstruct(getfield(data(j),fn{i})))
            newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i})));
        end
    end
end
if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn)))
  newdata=cell(len,1);
  for j=1:len
    ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_);
    iscpx=0;
    if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn)))
        if(data(j).x0x5F_ArrayIsComplex_)
           iscpx=1;
        end
    end
    if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn)))
        if(data(j).x0x5F_ArrayIsSparse_)
            if(~isempty(strmatch('x0x5F_ArraySize_',fn)))
                dim=double(data(j).x0x5F_ArraySize_);
                if(iscpx && size(ndata,2)==4-any(dim==1))
                    ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end));
                end
                if isempty(ndata)
                    % All-zeros sparse
                    ndata=sparse(dim(1),prod(dim(2:end)));
                elseif dim(1)==1
                    % Sparse row vector
                    ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end)));
                elseif dim(2)==1
                    % Sparse column vector
                    ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end)));
                else
                    % Generic sparse array.
                    ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end)));
                end
            else
                if(iscpx && size(ndata,2)==4)
                    ndata(:,3)=complex(ndata(:,3),ndata(:,4));
                end
                ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3));
            end
        end
    elseif(~isempty(strmatch('x0x5F_ArraySize_',fn)))
        if(iscpx && size(ndata,2)==2)
             ndata=complex(ndata(:,1),ndata(:,2));
        end
        ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_);
    end
    newdata{j}=ndata;
  end
  if(len==1)
      newdata=newdata{1};
  end
end

%%-------------------------------------------------------------------------
function object = parse_object(varargin)
    parse_char('{');
    object = [];
    type='';
    count=-1;
    if(next_char == '$')
        type=inStr(pos+1); % TODO
        pos=pos+2;
    end
    if(next_char == '#')
        pos=pos+1;
        count=double(parse_number());
    end
    if next_char ~= '}'
        num=0;
        while 1
            str = parseStr(varargin{:});
            if isempty(str)
                error_pos('Name of value at position %d cannot be empty');
            end
            %parse_char(':');
            val = parse_value(varargin{:});
            num=num+1;
            eval( sprintf( 'object.%s  = val;', valid_field(str) ) );
            if next_char == '}' || (count>=0 && num>=count)
                break;
            end
            %parse_char(',');
        end
    end
    if(count==-1)
        parse_char('}');
    end

%%-------------------------------------------------------------------------
function [cid,len]=elem_info(type)
id=strfind('iUIlLdD',type);
dataclass={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
if(id>0)
    cid=dataclass{id};
    len=bytelen(id);
else
    error_pos('unsupported type at position %d');
end
%%-------------------------------------------------------------------------

function [data adv]=parse_block(type,count,varargin)
global pos inStr isoct
[cid,len]=elem_info(type);
if(isoct)
    data=typecast(int8(inStr(pos:pos+len*count-1)),cid);
else
    data=typecast(uint8(inStr(pos:pos+len*count-1)),cid);
end
adv=double(len*count);

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

function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
    parse_char('[');
    object = cell(0, 1);
    dim=[];
    type='';
    count=-1;
    if(next_char == '$')
        type=inStr(pos+1);
        pos=pos+2;
    end
    if(next_char == '#')
        pos=pos+1;
        if(next_char=='[')
            dim=parse_array(varargin{:});
            count=prod(double(dim));
        else
            count=double(parse_number());
        end
    end
    if(~isempty(type))
        if(count>=0)
            [object adv]=parse_block(type,count,varargin{:});
            if(~isempty(dim))
                object=reshape(object,dim);
            end
            pos=pos+adv;
            return;
        else
            endpos=matching_bracket(inStr,pos);
            [cid,len]=elem_info(type);
            count=(endpos-pos)/len;
            [object adv]=parse_block(type,count,varargin{:});
            pos=pos+adv;
            parse_char(']');
            return;
        end
    end
    if next_char ~= ']'
         while 1
            val = parse_value(varargin{:});
            object{end+1} = val;
            if next_char == ']'
                break;
            end
            %parse_char(',');
         end
    end
    if(jsonopt('SimplifyCell',0,varargin{:})==1)
      try
        oldobj=object;
        object=cell2mat(object')';
        if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
            object=oldobj;
        elseif(size(object,1)>1 && ndims(object)==2)
            object=object';
        end
      catch
      end
    end
    if(count==-1)
        parse_char(']');
    end

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

function parse_char(c)
    global pos inStr len
    skip_whitespace;
    if pos > len || inStr(pos) ~= c
        error_pos(sprintf('Expected %c at position %%d', c));
    else
        pos = pos + 1;
        skip_whitespace;
    end

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

function c = next_char
    global pos inStr len
    skip_whitespace;
    if pos > len
        c = [];
    else
        c = inStr(pos);
    end

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

function skip_whitespace
    global pos inStr len
    while pos <= len && isspace(inStr(pos))
        pos = pos + 1;
    end

%%-------------------------------------------------------------------------
function str = parseStr(varargin)
    global pos inStr esc index_esc len_esc
 % len, ns = length(inStr), keyboard
    type=inStr(pos);
    if type ~= 'S' && type ~= 'C' && type ~= 'H'
        error_pos('String starting with S expected at position %d');
    else
        pos = pos + 1;
    end
    if(type == 'C')
        str=inStr(pos);
        pos=pos+1;
        return;
    end
    bytelen=double(parse_number());
    if(length(inStr)>=pos+bytelen-1)
        str=inStr(pos:pos+bytelen-1);
        pos=pos+bytelen;
    else
        error_pos('End of file while expecting end of inStr');
    end

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

function num = parse_number(varargin)
    global pos inStr len isoct
    id=strfind('iUIlLdD',inStr(pos));
    if(isempty(id))
        error_pos('expecting a number at position %d');
    end
    type={'int8','uint8','int16','int32','int64','single','double'};
    bytelen=[1,1,2,4,8,4,8];
    if(isoct)
        num=typecast(int8(inStr(pos+1:pos+bytelen(id))),type{id});
    else
        num=typecast(uint8(inStr(pos+1:pos+bytelen(id))),type{id});
    end
    pos = pos + bytelen(id)+1;

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

function val = parse_value(varargin)
    global pos inStr len
    true = 1; false = 0;

    switch(inStr(pos))
        case {'S','C','H'}
            val = parseStr(varargin{:});
            return;
        case '['
            val = parse_array(varargin{:});
            return;
        case '{'
            val = parse_object(varargin{:});
            if isstruct(val)
                if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact')))
                    val=jstruct2array(val);
                end
            elseif isempty(val)
                val = struct;
            end
            return;
        case {'i','U','I','l','L','d','D'}
            val = parse_number(varargin{:});
            return;
        case 'T'
            val = true;
            pos = pos + 1;
            return;
        case 'F'
            val = false;
            pos = pos + 1;
            return;
        case {'Z','N'}
            val = [];
            pos = pos + 1;
            return;
    end
    error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------

function error_pos(msg)
    global pos inStr len
    poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
    if poShow(3) == poShow(2)
        poShow(3:4) = poShow(2)+[0 -1];  % display nothing after
    end
    msg = [sprintf(msg, pos) ': ' ...
    inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
    error( ['JSONparser:invalidFormat: ' msg] );

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

function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
    pos=regexp(str,'^[^A-Za-z]','once');
    if(~isempty(pos))
        if(~isoct)
            str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
        else
            str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
        end
    end
    if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return;  end
    if(~isoct)
        str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
    else
        pos=regexp(str,'[^0-9A-Za-z_]');
        if(isempty(pos)) return; end
        str0=str;
        pos0=[0 pos(:)' length(str)];
        str='';
        for i=1:length(pos)
            str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
        end
        if(pos(end)~=length(str))
            str=[str str0(pos0(end-1)+1:pos0(end))];
        end
    end
    %str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';

%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
    if(str(pos)=='"')
        if(~(pos>1 && str(pos-1)=='\'))
            endpos=pos;
            return;
        end
    end
    pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos e1l e1r maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
    c=tokens(pos);
    if(c==']')
        level=level-1;
        if(isempty(e1r)) e1r=bpos(pos); end
        if(level==0)
            endpos=bpos(pos);
            return
        end
    end
    if(c=='[')
        if(isempty(e1l)) e1l=bpos(pos); end
        level=level+1;
        maxlevel=max(maxlevel,level);
    end
    if(c=='"')
        pos=matching_quote(tokens,pos+1);
    end
    pos=pos+1;
end
if(endpos==0)
    error('unmatched "]"');
end


vidObj = VideoReader('f9-29_ne_twr.mov');
save vidfile.mat vidObj
%%
% Specify that reading should start at 0.5 seconds from the
% beginning.
%vidObj.CurrentTime = 0.5;

% Create an axes
currAxes = axes;
figure
fnum = 1;
while hasFrame(vidObj)
    vidFrame = readFrame(vidObj);
    %image(vidFrame, 'Parent', currAxes);
    fnum
    imagesc(vidFrame)
    %stop
    %currAxes.Visible = 'off';
    pause(2.0/vidObj.FrameRate);
    fnum=fnum+1;
end


function setup_ilsvrcanimalpart()
%% download images
if(~exist('../data/detanimalpart','dir'))
    system('rm -r ../data/detanimalpart');
    system('git clone https://github.com/zqs1022/detanimalpart.git');
    system('mv detanimalpart ../data/');
end

%% settings
conf.data.imgdir='../data/detanimalpart/';
conf.data.readCode='./data_input/data_input_DET-2015-subset-ILSVRC2013train/';
conf.data.minArea=50^2;

conf.output.dir='./mat/';

Name_batch={'n01443537','n01503061','n01639765','n01662784','n01674464','n01882714','n01982650','n02084071','n02118333','n02121808','n02129165','n02129604','n02131653','n02324045','n02342885','n02355227','n02374451','n02391049','n02395003','n02398521','n02402425','n02411705','n02419796','n02437136','n02444819','n02454379','n02484322','n02503517','n02509815','n02510455'};
for i=1:numel(Name_batch)
    mkdir([conf.output.dir,Name_batch{i}]);
    save([conf.output.dir,Name_batch{i},'/conf.mat'],'conf');
end

addpath(genpath('./tool'));
addpath(conf.data.readCode);


function all_bbox_proposals = extract_selective_search_boxes_from_dataset(image_db, ss_boxes_dst_file)
%
% This file is part of the code that implements the following paper:
% Title      : "LocNet: Improving Localization Accuracy for Object Detection"
% Authors    : Spyros Gidaris, Nikos Komodakis
% Institution: Universite Paris Est, Ecole des Ponts ParisTech
% ArXiv link : http://arxiv.org/abs/1511.07763
% code       : https://github.com/gidariss/LocNet
%
% AUTORIGHTS
% --------------------------------------------------------
% Copyright (c) 2016 Spyros Gidaris
%
% Title     : "LocNet: Improving Localization Accuracy for Object Detection"
% ArXiv link: http://arxiv.org/abs/1511.07763
% Licensed under The MIT License [see LICENSE for details]
% ---------------------------------------------------------

try
    ld = load(ss_boxes_dst_file);
    all_bbox_proposals = ld.all_bbox_proposals;
catch
    chunk_size = 1000;
    num_imgs   = numel(image_db.image_paths);
    num_chunks = ceil(num_imgs/chunk_size);

    ss_boxes_dst_file_in_progress1 = regexprep(ss_boxes_dst_file, '.mat', '_in_progress.mat');
    ss_boxes_dst_file_in_progress2 = regexprep(ss_boxes_dst_file, '.mat', '_in_progress_prev.mat');

    try
        try
            ld = load(ss_boxes_dst_file_in_progress1);
            all_bbox_proposals = ld.all_bbox_proposals;
            first_chunk = ld.chunk + 1;
        catch
            ld = load(ss_boxes_dst_file_in_progress2);
            all_bbox_proposals = ld.all_bbox_proposals;
            first_chunk = ld.chunk + 1;
        end
    catch exception
        fprintf('Exception message %s\n', getReport(exception));
        all_bbox_proposals = cell(num_imgs,1);
        first_chunk = 1;
    end

    total_num_elems = 0;
    total_time = 0;
    count = 0;
    for chunk = first_chunk:num_chunks
        start_idx = (chunk-1) * chunk_size + 1;
        stop_idx  = min(chunk * chunk_size, num_imgs);
        th = tic;
        all_bbox_proposals(start_idx:stop_idx) = extract_selective_search_prposlas(image_db.image_paths(start_idx:stop_idx));
        for i = start_idx:stop_idx
            count = count + 1;
            total_num_elems = total_num_elems + numel(all_bbox_proposals{i});
        end
        elapsed_time = toc(th);
        total_time = total_time + elapsed_time;
        est_rem_time = (total_time / count) * (num_imgs - stop_idx);
        est_num_bytes = (total_num_elems / count) * num_imgs * 4 / (1024*1024*1024);
        fprintf('Extract Selective Search boxes %s %d/%d: ET %.2fmin | ETA %.2fmin | EST. NUM BYTES %.2f giga\n', ...
            image_db.image_set_name, stop_idx, num_imgs, ...
            total_time/60, est_rem_time/60, est_num_bytes);

        if (exist(ss_boxes_dst_file_in_progress1,'file')>0)
            copyfile(ss_boxes_dst_file_in_progress1,ss_boxes_dst_file_in_progress2);
        end

        save(ss_boxes_dst_file_in_progress1, 'all_bbox_proposals', 'chunk', '-v7.3');
    end

    save(ss_boxes_dst_file, 'all_bbox_proposals', '-v7.3');
end
end

function all_box_proposals = extract_selective_search_prposlas(image_paths)
fast_mode = true;
num_imgs = length(image_paths);
all_box_proposals = cell(num_imgs,1);
parfor (i = 1:num_imgs)
%     th = tic;
    img = imread(image_paths{i});
    all_box_proposals{i} = selective_search_boxes(img, fast_mode);
    all_box_proposals{i} = single(all_box_proposals{i}(:,[2 1 4 3]));
%     fprintf(' image %d/%d: elapsed time %.2f\n', i, num_imgs, toc(th))
end
end


function eddy = mod_new_eddy(STATS, amplitude, lat, lon, thresh, sa, cyc, geospeed, extrema_num, detect)
%NEW_EDDY Initializes new eddy objects, run with no arguments to create an
%empty matrix
    if nargin
        eddy = struct('Stats', STATS, ...
            'Lat', lat, ...
            'Lon', lon, ...
            'Amplitude', amplitude, ...
            'ThreshFound', thresh, ...
            'SurfaceArea', sa, ...
            'Date', NaN, ...
            'Cyc', cyc, ...
            'MeanGeoSpeed', geospeed, ...
            'NumberOfExtrema', extrema_num, ...
            'DetectedBy', detect);
    else
        eddy = struct('Stats', {}, ...
            'Lat', {}, ...
            'Lon', {}, ...
            'Amplitude', {}, ...
            'ThreshFound', {}, ...
            'SurfaceArea', {}, ...
            'Date', {}, ...
            'Cyc', {}, ...
            'MeanGeoSpeed', {}, ...
            'NumberOfExtrema', {}, ...
            'DetectedBy', {});
    end
end


function [pred_boxes, scores] = fast_rcnn_im_detect(conf, caffe_net, im, boxes, max_rois_num_in_gpu)
% [pred_boxes, scores] = fast_rcnn_im_detect(conf, caffe_net, im, boxes, max_rois_num_in_gpu)
% --------------------------------------------------------
% Fast R-CNN
% Reimplementation based on Python Fast R-CNN (https://github.com/rbgirshick/fast-rcnn)
% Copyright (c) 2015, Shaoqing Ren
% Licensed under The MIT License [see LICENSE for details]
% --------------------------------------------------------

    [im_blob, rois_blob, ~] = get_blobs(conf, im, boxes);

    % When mapping from image ROIs to feature map ROIs, there's some aliasing
    % (some distinct image ROIs get mapped to the same feature ROI).
    % Here, we identify duplicate feature ROIs, so we only compute features
    % on the unique subset.
    [~, index, inv_index] = unique(rois_blob, 'rows');
    rois_blob = rois_blob(index, :);
    boxes = boxes(index, :);

    % permute data into caffe c++ memory, thus [num, channels, height, width]
    im_blob = im_blob(:, :, [3, 2, 1], :); % from rgb to brg
    im_blob = permute(im_blob, [2, 1, 3, 4]);
    im_blob = single(im_blob);
    rois_blob = rois_blob - 1; % to c's index (start from 0)
    rois_blob = permute(rois_blob, [3, 4, 2, 1]);
    rois_blob = single(rois_blob);

    total_rois = size(rois_blob, 4);
    total_scores = cell(ceil(total_rois / max_rois_num_in_gpu), 1);
    total_box_deltas = cell(ceil(total_rois / max_rois_num_in_gpu), 1);
    for i = 1:ceil(total_rois / max_rois_num_in_gpu)

        sub_ind_start = 1 + (i-1) * max_rois_num_in_gpu;
        sub_ind_end = min(total_rois, i * max_rois_num_in_gpu);
        sub_rois_blob = rois_blob(:, :, :, sub_ind_start:sub_ind_end);

        net_inputs = {im_blob, sub_rois_blob};

        % Reshape net's input blobs
        caffe_net.reshape_as_input(net_inputs);
        output_blobs = caffe_net.forward(net_inputs);

        if conf.test_binary
            % simulate binary logistic regression
            scores = caffe_net.blobs('cls_score').get_data();
            scores = squeeze(scores)';
            % Return scores as fg - bg
            scores = bsxfun(@minus, scores, scores(:, 1));
        else
            % use softmax estimated probabilities
            scores = output_blobs{2};
            scores = squeeze(scores)';
        end

        % Apply bounding-box regression deltas
        box_deltas = output_blobs{1};
        box_deltas = squeeze(box_deltas)';

        total_scores{i} = scores;
        total_box_deltas{i} = box_deltas;
    end

    scores = cell2mat(total_scores);
    box_deltas = cell2mat(total_box_deltas);

    pred_boxes = fast_rcnn_bbox_transform_inv(boxes, box_deltas);
    pred_boxes = clip_boxes(pred_boxes, size(im, 2), size(im, 1));

    % Map scores and predictions back to the original set of boxes
    scores = scores(inv_index, :);
    pred_boxes = pred_boxes(inv_index, :);

    % remove scores and boxes for back-ground
    pred_boxes = pred_boxes(:, 5:end);
    scores = scores(:, 2:end);
end

function [data_blob, rois_blob, im_scale_factors] = get_blobs(conf, im, rois)
    [data_blob, im_scale_factors] = get_image_blob(conf, im);
    rois_blob = get_rois_blob(conf, rois, im_scale_factors);
end

function [blob, im_scales] = get_image_blob(conf, im)
    [ims, im_scales] = arrayfun(@(x) prep_im_for_blob(im, conf.image_means, x, conf.test_max_size), conf.test_scales, 'UniformOutput', false);
    im_scales = cell2mat(im_scales);
    blob = im_list_to_blob(ims);
end

function [rois_blob] = get_rois_blob(conf, im_rois, im_scale_factors)
    [feat_rois, levels] = map_im_rois_to_feat_rois(conf, im_rois, im_scale_factors);
    rois_blob = single([levels, feat_rois]);
end

function [feat_rois, levels] = map_im_rois_to_feat_rois(conf, im_rois, scales)
    im_rois = single(im_rois);

    if length(scales) > 1
        widths = im_rois(:, 3) - im_rois(:, 1) + 1;
        heights = im_rois(:, 4) - im_rois(:, 2) + 1;

        areas = widths .* heights;
        scaled_areas = bsxfun(@times, areas(:), scales(:)'.^2);
        [~, levels] = min(abs(scaled_areas - 224.^2), [], 2);
    else
        levels = ones(size(im_rois, 1), 1);
    end

    feat_rois = round(bsxfun(@times, im_rois-1, scales(levels))) + 1;
end

function boxes = clip_boxes(boxes, im_width, im_height)
    % x1 >= 1 & <= im_width
    boxes(:, 1:4:end) = max(min(boxes(:, 1:4:end), im_width), 1);
    % y1 >= 1 & <= im_height
    boxes(:, 2:4:end) = max(min(boxes(:, 2:4:end), im_height), 1);
    % x2 >= 1 & <= im_width
    boxes(:, 3:4:end) = max(min(boxes(:, 3:4:end), im_width), 1);
    % y2 >= 1 & <= im_height
    boxes(:, 4:4:end) = max(min(boxes(:, 4:4:end), im_height), 1);
end


classdef Blender < handle
    %BLENDER  Class for all image blenders
    %
    % See also: cv.Stitcher
    %

    properties (SetAccess = private)
        % Object ID
        id
    end

    methods
        function this = Blender(blenderType, varargin)
            %BLENDER  Constructor
            %
            %     obj = cv.Blender(blenderType)
            %     obj = cv.Blender(blenderType, 'OptionName',optionValue, ...)
            %
            % ## Input
            % * __blenderType__ image blender type. One of:
            %   * __NoBlender__ Simple blender which puts one image over
            %     another.
            %   * __FeatherBlender__ Simple blender which mixes images at its
            %     borders.
            %   * __MultiBandBlender__ Blender which uses multi-band blending
            %     algorithm (see [BA83]).
            %
            % ## Options
            % The following are options for the various algorithms:
            %
            % ### `FeatherBlender`
            % * __Sharpness__ default 0.02
            %
            % ### `MultiBandBlender`
            % * __TryGPU__ default false
            % * __NumBands__ default 5
            % * __WeightType__ One of:
            %   * __single__ (default)
            %   * __int16__
            %
            % ## References
            % [BA83]:
            % > Peter J Burt and Edward H Adelson.
            % > "A multiresolution spline with application to image mosaics".
            % > ACM Transactions on Graphics (TOG), 2(4):217-236, 1983.
            %
            % See also: cv.Blender.blend
            %
            this.id = Blender_(0, 'new', blenderType, varargin{:});
        end

        function delete(this)
            %DELETE  Destructor
            %
            %     obj.delete()
            %
            % See also: cv.Blender
            %
            if isempty(this.id), return; end
            Blender_(this.id, 'delete');
        end

        function typename = typeid(this)
            %TYPEID  Name of the C++ type (RTTI)
            %
            %     typename = obj.typeid()
            %
            % ## Output
            % * __typename__ Name of C++ type
            %
            typename = Blender_(this.id, 'typeid');
        end
    end

    %% Blender
    methods
        function prepare(this, varargin)
            %PREPARE  Prepares the blender for blending
            %
            %     obj.prepare(corners, sizes)
            %     obj.prepare(dst_roi)
            %
            % ## Input
            % * __corners__ Source images top-left corners. Cell-array of 2D
            %   points `{[x,y],...}`.
            % * __sizes__ Source image sizes. Cell-array of sizes
            %   `{[w,h],...}`.
            % * **dst_roi** Destination ROI rectangle `[x,y,w,h]`, same as
            %   obtained by calling `cv.Blender.resultRoi(corners,sizes)`.
            %
            % See also: cv.Blender.feed
            %
            Blender_(this.id, 'prepare', varargin{:});
        end

        function feed(this, img, mask, tl)
            %FEED  Processes the image
            %
            %     obj.feed(img, mask, tl)
            %
            % ## Input
            % * __img__ Source image, 3-channel of type `int16`.
            % * __mask__ Source image mask, 1-channel of type `uint8`.
            % * __tl__ Source image top-left corners `[x,y]`.
            %
            % See also: cv.Blender.blend
            %
            Blender_(this.id, 'feed', img, mask, tl);
        end

        function [dst, dst_mask] = blend(this, varargin)
            %BLEND  Blends and returns the final pano
            %
            %     [dst, dst_mask] = obj.blend()
            %     [dst, dst_mask] = obj.blend('OptionName',optionValue, ...)
            %
            % ## Output
            % * __dst__ Final pano, of type `int16`.
            % * **dst_mask** Final pano mask, of type `uint8`.
            %
            % ## Options
            % * __Dst__
            % * __Mask__
            %
            % See also: cv.Blender.feed
            %
            [dst, dst_mask] = Blender_(this.id, 'blend', varargin{:});
        end
    end

    %% FeatherBlender
    methods
        function [weight_maps, dst_roi] = createWeightMaps(this, masks, corners)
            %CREATEWEIGHTMAPS  Creates weight maps for fixed set of source images by their masks and top-left corners
            %
            %     [weight_maps, dst_roi] = obj.createWeightMaps(masks, corners)
            %
            % ## Input
            % * __masks__ Cell-array of image masks.
            % * __corners__ Cell-array of top-left corners `{[x,y],...}`.
            %
            % ## Output
            % * **weight_maps** Cell-array of weight maps.
            % * **dst_roi** ROI rectangle `[x,y,w,h]`.
            %
            % Final image can be obtained by simple weighting of the source
            % images.
            %
            [weight_maps, dst_roi] = Blender_(this.id, 'createWeightMaps', masks, corners);
        end
    end

    %% Auxiliary methods
    methods (Static)
        function pyr = createLaplacePyr(img, num_levels, varargin)
            %CREATELAPLACEPYR  Create Laplace pyramid
            %
            %     pyr = cv.Blender.createLaplacePyr(img, num_levels)
            %     pyr = cv.Blender.createLaplacePyr(..., 'OptionName',optionValue, ...)
            %
            % ## Input
            % * __img__ Input image.
            % * **num_levels** Number of pyramid levels.
            %
            % ## Output
            % * __pyr__ Laplace pyramid, cell-array of matrices.
            %
            % ## Options
            % * __UseGPU__ (requires CUDA). default false
            %
            % See also: cv.Blender.restoreImageFromLaplacePyr, cv.buildPyramid
            %
            pyr = Blender_(0, 'createLaplacePyr', img, num_levels, varargin{:});
        end

        function img = restoreImageFromLaplacePyr(pyr, varargin)
            %RESTOREIMAGEFROMLAPLACEPYR  Restore source image from Laplace pyramid
            %
            %     img = cv.Blender.restoreImageFromLaplacePyr(pyr)
            %     img = cv.Blender.restoreImageFromLaplacePyr(pyr, 'OptionName',optionValue, ...)
            %
            % ## Input
            % * __pyr__ Laplace pyramid, cell-array of matrices.
            %
            % ## Output
            % * __img__ Output image.
            %
            % ## Options
            % * __UseGPU__ (requires CUDA). default false
            %
            % See also: cv.Blender.createLaplacePyr, cv.buildPyramid
            %
            img = Blender_(0, 'restoreImageFromLaplacePyr', pyr, varargin{:});
        end

        function [roi,success] = overlapRoi(tl1, tl2, sz1, sz2)
            %OVERLAPROI  Overlap ROI
            %
            %     [roi,success] = cv.Blender.overlapRoi(tl1, tl2, sz1, sz2)
            %
            % ## Input
            % * __tl1__ First top-left corner `[x1,y1]`.
            % * __tl2__ Second top-left corner `[x2,y2]`.
            % * __sz1__ First size `[w1,h1]`.
            % * __sz2__ Second size `[w2,h2]`.
            %
            % ## Output
            % * __roi__ Output rectangle `[x,y,w,h]`.
            % * __success__ Success flag.
            %
            % See also: cv.Blender.resultRoi
            %
            [roi,success] = Blender_(0, 'overlapRoi', tl1, tl2, sz1, sz2);
        end

        function roi = resultRoi(corners, sizes)
            %RESULTROI  Result ROI
            %
            %     roi = cv.Blender.resultRoi(corners, sizes)
            %
            % ## Input
            % * __corners__ Cell-array of top-left corners `{[x,y],...}`.
            % * __sizes__ Cell-array of corresponding sizes `{[w,h],...}`.
            %
            % ## Output
            % * __roi__ Output rectangle `[x,y,w,h]`.
            %
            % See also: cv.Blender.resultRoiIntersection
            %
            roi = Blender_(0, 'resultRoi', corners, sizes);
        end

        function roi = resultRoiIntersection(corners, sizes)
            %RESULTROIINTERSECTION  Result ROI intersection
            %
            %     roi = cv.Blender.resultRoiIntersection(corners, sizes)
            %
            % ## Input
            % * __corners__ Cell-array of top-left corners `{[x,y],...}`.
            % * __sizes__ Cell-array of corresponding sizes `{[w,h],...}`.
            %
            % ## Output
            % * __roi__ Output rectangle `[x,y,w,h]`.
            %
            % See also: cv.Blender.resultRoi
            %
            roi = Blender_(0, 'resultRoiIntersection', corners, sizes);
        end

        function tl = resultTl(corners)
            %RESULTTL  Result top-left corner
            %
            %     tl = cv.Blender.resultTl(corners)
            %
            % ## Input
            % * __corners__ Cell-array of top-left corners `{[x,y],...}`.
            %
            % ## Output
            % * __tl__ top-left corner `[x,y]`
            %
            % See also: cv.Blender.resultRoi
            %
            tl = Blender_(0, 'resultTl', corners);
        end
    end

end