function [EDF]=closedf(EDF)

% EDF=closedf(EDF)
% Opens an EDF File (European Data Format for Biosignals) into MATLAB
% About EDF
%
% EDF   struct of EDF-Header of a EDF-File

%   Version 2.0
%   15.12.1997
%   Copyright (c) 1997 by  Alois Schloegl
%   a.schloegl@ieee.org
%
% 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.
%

EDF.FILE.OPEN=0;
fclose(EDF.FILE.FID);
return;


function gdoc(varargin)

% function gdoc(functionName)
%------------------------------------------------------------------------
% View XML files using a brower embedded in a figure window or within
% MATLAB brower.
%
% Kevin Mattheus Moerman
% gibbon.toolbox@gmail.com
%
% 2016/05/13 %Updated, renamed from febView to xmlView
% 2017/08/18 %Created varargin with viewer option. Create temp file to
% allow viewing of domNode.
%------------------------------------------------------------------------
%%

switch nargin
    case 1
        topic=varargin{1};
    case 0
        topic='';
end

if isempty(topic)
   web('GIBBON_product_page.html', '-helpbrowser'); %Display main GIBBON page
else
    documentationPath=fullfile(fileparts(fileparts(mfilename('fullpath'))),'docs','html');

    helpCheckName=fullfile(documentationPath,['HELP_',topic,'.html']);
    demoCheckName=fullfile(documentationPath,['DEMO_',topic,'.html']);

    if exist(helpCheckName,'file')
        web(helpCheckName, '-helpbrowser');
    elseif exist(demoCheckName,'file')
        web(demoCheckName, '-helpbrowser');
    else
        disp('No matching HELP or DEMO files found. Searching all documentation instead');
        docsearch(topic);
    end
end

%%
% _*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/>.


%FtsZRing_Test
% FtsZ ring test class.
%
% Author: Jonathan Karr, jkarr@stanford.edu
% Affiliation: Covert Lab, Department of Bioengineering, Stanford University
% Last Updated: 1/4/2011
classdef FtsZRing_Test < edu.stanford.covert.cell.sim.CellStateTestCase
    methods
        function this = FtsZRing_Test(name)
            this = this@edu.stanford.covert.cell.sim.CellStateTestCase(name);
        end
    end
end


function errFolders = db_delete_subjects( iSubjects )
% DB_DELETE_SUBJECTS: Delete some subjects from the brainstorm database.
%
% USAGE:  errFolders = db_delete_subjects( iSubjects )
%
% INPUT:
%    - iSubjects : indices of the subejcts to delete
%
% OUTPUT:
%    - errFolders : Cell-array with full paths to folders that could not be deleted

% @=============================================================================
% This function is part of the Brainstorm software:
% https://neuroimage.usc.edu/brainstorm
%
% Copyright (c) University of Southern California & McGill University
% This software is distributed under the terms of the GNU General Public License
% as published by the Free Software Foundation. Further details on the GPLv3
% license can be found at http://www.gnu.org/copyleft/gpl.html.
%
% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE
% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY
% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY
% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.
%
% For more information type "brainstorm license" at command prompt.
% =============================================================================@
%
% Authors: Francois Tadel, 2012-2022

ProtocolInfo     = bst_get('ProtocolInfo');
ProtocolSubjects = bst_get('ProtocolSubjects');
errFolders = {};

% Remove invalid indices and default subject
iInvalid = find(iSubjects <= 0);
if ~isempty(iInvalid)
    disp('DELETE> Cannot delete default subject.');
    iSubjects(iInvalid) = [];
end

% For each subject
for i = 1:length(iSubjects)
    SubjectFile = ProtocolSubjects.Subject(iSubjects(i)).FileName;
    % === DELETE STUDIES ===
    % Find all the studies that are associated with the current brainstormsubject file
    [sStudies, iStudies] = bst_get('StudyWithSubject', SubjectFile, 'intra_subject', 'default_study');
    if ~isempty(sStudies)
        % Delete folders
        errFolders = cat(2, errFolders, db_delete_studies(iStudies));
        % Delete the studies folder for the subject
        subjDataDir = bst_fullfile(ProtocolInfo.STUDIES, bst_fileparts(bst_fileparts(sStudies(1).FileName)));
        if (file_delete(subjDataDir, 1, 1) ~= 1)
            errFolders{end+1} = subjDataDir;
            return;
        end
    end
    % === DELETE SUBJECT ===
    % Remove subject's directory
    subjAnatDir = bst_fullfile(ProtocolInfo.SUBJECTS, bst_fileparts(SubjectFile));
    if (file_delete(subjAnatDir, 1, 1) ~= 1)
        errFolders{end+1} = subjAnatDir;
        return;
    end
end
% Remove subjects from database
ProtocolSubjects.Subject(iSubjects) = [];
bst_set('ProtocolSubjects', ProtocolSubjects);
% Update tree
panel_protocols('UpdateTree');
% Save database
db_save();


function tn = tagnames(item, dflag)

% function tn = tagnames(item, dflag)
% Return the tags of all children in the job tree of an item. dflag
% indicates whether the filled (false) or defaults (true) part of the
% tree should be searched.
%
% This function is identical for all cfg_intree classes.
% It is not defined for leaf items.
%
% This code is part of a batch job configuration system for MATLAB. See
%      help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging

% Volkmar Glauche
% $Id: tagnames.m 4864 2012-08-27 13:57:31Z volkmar $

rev = '$Rev: 4864 $'; %#ok

tp = treepart(item, dflag);
citems = subsref(item, substruct('.', tp));
tn = cell(size(citems));
for k = 1:numel(citems)
    tn{k} = gettag(citems{k});
end;


classdef SetEngineActiveStateAction < AbstractEventAction
    %SetEngineActiveStateAction Summary of this class goes here
    %   Detailed explanation goes here

    properties
        engine LaunchVehicleEngine
        activeStateToSet(1,1) logical = false;
    end

    properties(Constant)
        emptyVarArr = AbstractOptimizationVariable.empty(0,1);
    end

    methods
        function obj = SetEngineActiveStateAction(engine, activeStateToSet)
            if(nargin > 0)
                obj.engine = engine;
                obj.activeStateToSet = activeStateToSet;
            end

            obj.id = rand();
        end

        function newStateLogEntry = executeAction(obj, stateLogEntry)
            newStateLogEntry = stateLogEntry;
            stage = obj.engine.stage;

            stgState = newStateLogEntry.stageStates([newStateLogEntry.stageStates.stage] == stage);

            engineState = stgState.engineStates([stgState.engineStates.engine] == obj.engine);
            engineState.active = obj.activeStateToSet;
        end

        function initAction(obj, initialStateLogEntry)
            %nothing
        end

        function name = getName(obj)
            if(obj.activeStateToSet)
                tf = 'Active';
            else
                tf = 'Inactive';
            end

            name = sprintf('Set Engine State (%s = %s)',obj.engine.name,tf);
        end

        function tf = usesStage(obj, stage)
            tf = false;
        end

        function tf = usesEngine(obj, engine)
            tf = ([obj.engine] == engine);
        end

        function tf = usesTank(obj, tank)
            tf = false;
        end

        function tf = usesEngineToTankConn(obj, engineToTank)
            tf = false;
        end

        function tf = usesStopwatch(obj, stopwatch)
            tf = false;
        end

        function tf = usesExtremum(obj, extremum)
            tf = false;
        end

        function tf = usesTankToTankConn(obj, tankToTank)
            tf = false;
        end

        function [tf, vars] = hasActiveOptimVar(obj)
            tf = false;
            vars = obj.emptyVarArr;
        end
    end

    methods(Static)
        function addActionTf = openEditActionUI(action, lv)
%             addActionTf = lvd_EditActionSetEngineStateGUI(action, lv);

            output = AppDesignerGUIOutput({false});
            lvd_EditActionSetEngineStateGUI_App(action, lv, output);
            addActionTf = output.output{1};
        end
    end
end


function spectralWidth = getSpectralWidth(MRSIStruct)
    spectralWidth = MRSIStruct.spectralWidth;
end


function genPreLitTableLatex

p = path;
if exist('C:\Users\Luis\Dropbox\MATL', 'dir')
    baseFolder = 'C:\Users\Luis\Dropbox\MATL';
elseif exist('C:\Users\lmendo\Dropbox\MATL', 'dir')
    baseFolder = 'C:\Users\lmendo\Dropbox\MATL';
else
    error('Base folder not found')
end
addpath([baseFolder '\compiler'])

preLitTableFileName = [ baseFolder '\spec\preLitTable\preLitTable.tex' ];
preLitMatFileName = [ baseFolder '\compiler\preLit.mat' ];
preLitTxtFileName = [ baseFolder '\compiler\preLit.txt' ];

% Update preLit.mat, if needed; or load file
pLTxt = dir(preLitTxtFileName);
if ~isempty(pLTxt)
    pLTxt = datenum(pLTxt.date);
else
    pLTxt = -inf;
end
pLMat = dir(preLitMatFileName);
if ~isempty(pLMat)
    pLMat = datenum(pLMat.date);
else
    pLMat = -inf;
end
if pLMat < pLTxt % regeneration of `L.mat` required
    L = genPreLit(preLitTxtFileName, preLitMatFileName); % creates `preLit` struct array
    % definitions from funDefTxtFileName file, and saves it in funDefMatFileName file
else % load `preLit` variable from funDefMatFileName directly
    load(preLitMatFileName) % loads L variable
end

fn = fieldnames(L);
for n = 1:numel(fn)
    lines = {};
    %lines{end+1} = '\begin{tabular}{|l|l||l|l||l|l|}';
    %lines{end+1} = '\begin{tabular}{|p{.03\textwidth}|p{.3\textwidth}||p{.03\textwidth}|p{.3\textwidth}||p{.03\textwidth}|p{.3\textwidth}|}';
    %lines{end+1} = '\begin{longtable}{|l|l||l|l||l|l|}';
    lines{end+1} = '\begin{longtable}{|p{.03\textwidth}|p{.29\textwidth}||p{.03\textwidth}|p{.29\textwidth}||p{.03\textwidth}|p{.29\textwidth}|}';
    %lines{end+1} = '\esptab';
    lines{end+1} = '\hline';
    lines{end+1} = sprintf('\\multicolumn{6}{|c|}{Function \\matl{%s}} \\\\ \\hline\\hline', fn{n});
    %lines{end+1} = '\matl{99} & \matl{''CollapseDelimiters''} & \matl{99} & \matl{''CollapseDelimiters''} & \matl{99} & \matl{''CollapseDelimiters''} \kill';
    keys = L.(fn{n}).key;
    vals = L.(fn{n}).val;
    for m = 1:numel(keys)
        r = mod(m,3);
        if r
            lines{end+1} = sprintf('\\matl|%s| & \\matl|%s| &', num2str(keys(m)), vals{m}); % this assumes "|" is not be used in literals
        else
            lines{end+1} = sprintf('\\matl|%s| & \\matl|%s| \\\\ \\hline', num2str(keys(m)), vals{m});
        end
    end
    if r==1
        lines{end+1} = sprintf('& & & \\\\ \\hline');
    elseif r==2
        lines{end+1} = sprintf('& \\\\ \\hline');
    end
    lines{end+1} = '\end{longtable}';
    %lines{end+1} = '\ ';

    % Write file
    [p, f, e] = fileparts(preLitTableFileName);
    fname = [p filesep f fn{n} e];
    fid = fopen(fname, 'w');
    for k = 1:numel(lines)
        fwrite(fid, lines{k});
        fwrite(fid, [13 10]); % line break, Windows style
    end
    fclose(fid);

    % Convert "\matl" contents:
    convert_matl(fname, false);
end


function [  ] = NiceSave(figname,figfolder,baseName,varargin)
%NiceSave(figname,figfolder,baseName,figtype) formats the figure for best viewing
%and saves it as a .pdf in figfolder with name recname_figname.pdf
%
%INPUTS
%   figname     string with title of figure
%   figfolder   folder to save figure to
%   baseName    name of the recording ([] for none)
%   'figtype'     'pdf','jpeg',etc
%   'includeDate' default: false. include date in filename
%
%DLevenstein Fall 2016
%TODO: add option to not overwrite old figure, but instead save as
%'figname02' etc.
%%
p = inputParser;
addParameter(p,'figtype','pdf')
addParameter(p,'includeDate',false)
parse(p,varargin{:})
figtype = p.Results.figtype;
includeDate = p.Results.includeDate;

%%

if ~exist(figfolder,'dir')
    mkdir(figfolder)
end

if includeDate
   figname = [figname,'_',date];
end
%set(gcf,'TickDir','out')

%if strcmp(figtype,'jpg')
set(gcf,'PaperOrientation','landscape');
%end
set(gcf,'PaperUnits','normalized');
set(gcf,'PaperPosition',[0 0 1 1]);
%orient portrait
saveas(gcf,[figfolder,'/',baseName,'_',figname,'.',figtype],figtype) ;

end


% VL_SIMDCTRL  Toggle VLFeat SIMD optimizations
%   VL_SIMDCTRL() returns TRUE if VLFeat SIMD optimizations are enabled
%   and FALSE otherwise.
%
%   VL_SIMDCTRL(TRUE) enables VLFeat SIMD optimizations. VL_SIMDCTRL(FALSE)
%   disables them.
%
%   See also: VL_HELP().

% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).


function add_legend_entry(plot_obj,lh,legend_string,append_name)
% Places a (curve handle, legend string) pair in a list for when
% display_legend is called.
% Inputs:
%   lh: A curve handle.
%   legend_string: The string to be displayed in the legend for the
%     curve corresponding to lh.
%   append_name: A boolean indicating whether to prepend the system
%     name (set in 'set_system') to the 'legend_string'.

if ~strcmp(legend_string,'')
    plot_obj.handles_vec = [plot_obj.handles_vec lh];
    if exist('append_name','var') && append_name
	plot_obj.legend_strings = {plot_obj.legend_strings{:},[plot_obj.sys_name ' ' legend_string]};
    else
	plot_obj.legend_strings = {plot_obj.legend_strings{:},legend_string};
    end
end

end


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

%%
clear; close all; clc;

%% Syntax
% |P=inv_parbound(Pb,Ps);|

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


function test_example_bids_video

% MEM 4gb
% WALLTIME 00:10:00

%
%% Converting an example video dataset for sharing in BIDS
%
% The [BIDS standard](https://bids.neuroimaging.io) does currently not specify how to represent video recordings. This example - and the support that is implemented in the **[data2bids](https://github.com/fieldtrip/fieldtrip/blob/release/data2bids.m)** function - should be considered as a preliminary proposal to help researchers with their existing data. This example may also serve to start a discussion on whether and how this data type should be added to the [BIDS specification](http://bids-specification.readthedocs.io/).
%
% In many experiments video data can be recorded along with other measurements. This is often used to off-line screen the subjects behavior and to annotate the video, i.e. note the time segments with specific (desired or undesired) behavior. Neither the video recording  (which can be considered as raw data), nor the annotations (which can be considered as derived data) are currently formally part of BIDS, although it is not so difficult to come up with a way that these can be represented in a BIDS-like fashion.
%
%% # Example
%
% The example data is available from our [FTP server](ftp://ftp.fieldtriptoolbox.org/pub/fieldtrip/example/bids_video/).
%
% The example includes the original video recording under the “original” directory. It also has a copy of the script to do the conversion under “code”. The reorganized data is under the “bids” directory. According to [the documentation](https://bids-specification.readthedocs.io/en/stable/02-common-principles.html#source-vs-raw-vs-derived-data) the original data can be added to the BIDS dataset under the “sourcedata” directory and code can be added to the “code” directory. This way no information is lost and the conversion/reorganization is fully reproducible.
%
% In general: if your original data is in a different format than the BIDS representation (e.g., DICOM instead of NIFTI), you probably want to keep a copy of the original data, e.g., on a data acquisition collection on the Donders Repository. If it is in the same format like here - since we are not converting the video file, you could simply delete the original files after conversion. In either case - your own analyses and the shared data would be based on the BIDS representation.
%
cfg = [];

cfg.InstitutionName             = 'Radboud University';
cfg.InstitutionalDepartmentName = 'Donders Institute for Brain, Cognition and Behaviour';
cfg.InstitutionAddress          = 'Kapittelweg 29, 6525 EN, Nijmegen, The Netherlands';

% this is required for dataset_description.json
cfg.dataset_description.Name                = 'Video example';
cfg.dataset_description.BIDSVersion         = 'unofficial extension';

% this is optional for dataset_description.json
cfg.dataset_description.License             = 'n/a';
cfg.dataset_description.Authors             = 'n/a';
cfg.dataset_description.Acknowledgements    = 'n/a';
cfg.dataset_description.Funding             = 'n/a';
cfg.dataset_description.ReferencesAndLinks  = 'n/a';
cfg.dataset_description.DatasetDOI          = 'n/a';

% provide some metadata about the task that was performed
cfg.TaskDescription = 'The subject was walking, stopping, turning, etcetera, while wearing a mobile EEG system on his head and a mobile NIRS system in his pocket';

cfg.method    = 'copy'; % video should simply be copied, not converted
cfg.dataset   = dccnpath('/home/common/matlab/fieldtrip/data/ftp/example/bids_video/original/Video_20190411_210224.mp4');
cfg.bidsroot  = fullfile(tempdir, 'bids');
cfg.datatype  = 'video';
cfg.sub       = '01';
cfg.task      = 'walking';

% construct an empty table that has the required columns 'onset' and 'duration' (in seconds)
% this uses the optional 'trial_type' column to indicate what happened
onset      = nan;
duration   = nan;
trial_type = {''};
cfg.events = table(onset, duration, trial_type);

% add the actual  events with onset, duration and trial_type
cfg.events(1,:) = {12, 2, 'standing up'};
cfg.events(2,:) = {15, 11, 'walking'};
cfg.events(3,:) = {26, 3, 'right turn'};
cfg.events(4,:) = {29, 10, 'walking'};

data2bids(cfg);
%
% This example also shows how to add annotations of the video to the `_events.tsv` file. If you do not have annotations (yet), you would leave the `cfg.events` field empty.
%
% In case you would have multiple subsequent videos in a single session, you would use `cfg.run=1, 2, ...` to specify the successive recordings.


function m = read_genesis_image(fname)
% m = read_ge(fname)

%
% read_genesis_image.m
%
% Original Author: Bruce Fischl
% CVS Revision Info:
%    $Author: nicks $
%    $Date: 2011/03/02 00:04:12 $
%    $Revision: 1.3 $
%
% Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH"
%
% Terms and conditions for use, reproduction, distribution and contribution
% are found in the 'FreeSurfer Software License Agreement' contained
% in the file 'LICENSE' found in the FreeSurfer distribution, and here:
%
% https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense
%
% Reporting: freesurfer@nmr.mgh.harvard.edu
%

fid = fopen(fname, 'r', 'b');
if fid < 0
	disp(sprintf('read_genesis_image: error opening file %s', fname));
	return;
end

fseek(fid, 4, 'bof');
image_offset = fread(fid, 1, 'int');
rows = fread(fid, 1, 'int');
cols = fread(fid, 1, 'int');

fseek(fid, image_offset, 'bof');
m = fread(fid, [rows cols], 'short');

fclose(fid);

% eof


classdef LvdSensorSet < matlab.mixin.SetGet
    %LvdSensorSet Summary of this class goes here
    %   Detailed explanation goes here

    properties
        sensors(1,:) AbstractSensor

        lvdData LvdData
    end

    methods
        function obj = LvdSensorSet(lvdData)
            obj.lvdData = lvdData;
        end

        function addSensor(obj, sensor)
            obj.sensors(end+1) = sensor;
        end

        function removeSensor(obj, sensor)
            obj.sensors([obj.sensors] == sensor) = [];
        end

        function [listBoxStr, sensors] = getListboxStr(obj)
            listBoxStr = {};

            for(i=1:length(obj.sensors))
                listBoxStr{end+1} = obj.sensors(i).getListboxStr(); %#ok<AGROW>
            end

            sensors = obj.sensors;
        end

        function indPoints = getSensorsForInds(obj, inds)
            indPoints = obj.sensors(inds);
        end

        function inds = getIndsForSensors(obj, indSensors)
            inds = [];
            for(i=1:length(indSensors))
                for(j=1:length(obj.sensors))
                    if(indSensors(i) == obj.sensors(j))
                        inds(end+1) = j; %#ok<AGROW>
                        break;
                    end
                end
            end
        end

        function indSensor = getSensorAtInd(obj, ind)
            if(ind > 0 && ind <= length(obj.sensors))
                indSensor = obj.sensors(ind);
            else
                indSensor = AbstractSensor.empty(1,0);
            end
        end

        function tf = usesGroundObj(obj, groundObj)
            tf = false;
            for(i=1:length(obj.sensors))
                tf = tf || obj.sensors(i).usesGroundObj(groundObj);
            end
        end

        function tf = usesGeometricPoint(obj, point)
            tf = false;
            for(i=1:length(obj.sensors))
                tf = tf || obj.sensors(i).usesGeometricPoint(point);
            end
        end

        function tf = usesGeometricVector(obj, vector)
            tf = false;
            for(i=1:length(obj.sensors))
                tf = tf || obj.sensors(i).usesGeometricVector(vector);
            end
        end

        function tf = usesGeometricCoordSys(obj, coordSys)
            tf = false;
            for(i=1:length(obj.sensors))
                tf = tf || obj.sensors(i).usesGeometricCoordSys(coordSys);
            end
        end

        function tf = usesGeometricRefFrame(obj, refFrame)
            tf = false;
            for(i=1:length(obj.sensors))
                tf = tf || obj.sensors(i).usesGeometricRefFrame(refFrame);
            end
        end

        function tf = usesGeometricAngle(obj, angle)
            tf = false;
            for(i=1:length(obj.sensors))
                tf = tf || obj.sensors(i).usesGeometricAngle(angle);
            end
        end

        function tf = usesGeometricPlane(obj, plane)
            tf = false;
            for(i=1:length(obj.sensors))
                tf = tf || obj.sensors(i).usesGeometricPlane(plane);
            end
        end
    end
end


function [y,varname]=xml2struct(filename_or_xml_string)

%XML2STRUCT reads non-MbML compliant xmlfile into matlab structure
%
% Syntax: [y,varname]=xml2struct(filename_or_xml_string)
%
% Description:
%   1. Convert any non-MbML xml into MbML compliant string
%   2. Stores consecutive structures in the a dimensional strucure
%
% If the non-MbML compliant XML has a consistent internal reference structure
% (those that were derived from explicit data models often do)
% this conversion will produce the best results, by building
%
% Note: if your XML string is MbML compliant use XML2MAT instead
%
% See also: XML2STRUCT
%
% Jonas Almeida, almeidaj@musc.edu, 19 May 2003, MAT4NAT Tbox

[y,varname]=xml2cell(filename_or_xml_string);
y=consolidateall(y);


function file_delete ( file_name )

%*****************************************************************************80
%
%% FILE_DELETE deletes a named file if it exists.
%
%  Discussion:
%
%    You might want to call this routine to get rid of any old copy
%    of a file, before trying to open a new copy with the OPEN argument:
%      status = 'new'.
%
%    It's not always safe to open a file with " STATUS = 'UNKNOWN' ".
%    For instance, on the SGI, the most recent version of the FORTRAN
%    compiler seems to go crazy when I open an unformatted direct
%    access file this way.  It creates an enormous file (of somewhat
%    random size).  The problem goes away if I delete any old copy
%    using this routine, and then open a fresh copy with
%    " STATUS = 'NEW' ".  It's a scary world.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    19 November 2004
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string FILE_NAME, the name of the file.
%

%
%  Does the file exist?
%
  if ( ~file_exist ( file_name ) )
    return
  end

  fprintf ( 1, '\n' );
  fprintf ( 1, 'FILE_DELETE:\n' );
  fprintf ( 1, '  Deleting old version of "%s".\n', file_name );

  delete ( file_name );

  return
end


function obj = loadobj(s)
% LOADOBJ  Initialize a DagNN object from a structure.
%   OBJ = LOADOBJ(S) initializes a DagNN objet from the structure
%   S. It is the opposite of S = OBJ.SAVEOBJ().
%   If S is a string, initializes the DagNN object with data
%   from a mat-file S. Otherwise, if S is an instance of `dagnn.DagNN`,
%   returns S.

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

if ischar(s) s = load(s); end
if isstruct(s)
  assert(isfield(s, 'layers'), 'Invalid model.');
  if ~isstruct(s.layers)
    warning('The model appears to be `simplenn` model. Using `fromSimpleNN` instead.');
    obj = dagnn.DagNN.fromSimpleNN(s);
    return;
  end
  obj = dagnn.DagNN() ;
  for l = 1:numel(s.layers)
    constr = str2func(s.layers(l).type) ;
    block = constr() ;
    block.load(struct(s.layers(l).block)) ;
    obj.addLayer(...
      s.layers(l).name, ...
      block, ...
      s.layers(l).inputs, ...
      s.layers(l).outputs, ...
      s.layers(l).params,...
      'skipRebuild', true) ;
  end
  obj.rebuild();
  if isfield(s, 'params')
    for f = setdiff(fieldnames(s.params)','name')
      f = char(f) ;
      for i = 1:numel(s.params)
        p = obj.getParamIndex(s.params(i).name) ;
        obj.params(p).(f) = s.params(i).(f) ;
      end
    end
  end
  if isfield(s, 'vars')
    for f = setdiff(fieldnames(s.vars)','name')
      f = char(f) ;
      for i = 1:numel(s.vars)
        p = obj.getVarIndex(s.vars(i).name) ;
        obj.vars(p).(f) = s.vars(i).(f) ;
      end
    end
  end
  for f = setdiff(fieldnames(s)', {'vars','params','layers'})
    f = char(f) ;
    obj.(f) = s.(f) ;
  end
elseif isa(s, 'dagnn.DagNN')
  obj = s ;
else
  error('Unknown data type %s for `loadobj`.', class(s));
end


function out = false( in )
%FALSE for initialization of nested cell arrays
%
% (c) Thomas Kuestner
% ---------------------------------------------------------------------

out = cellfun(@(x) false(x), in.data{2,1}, 'UniformOutput', false);
out = reconFlatCellMatrix(out, in.data{1,1});
out = TRAFO(out,in.meta);

end


function varargout = setupSolarized(varargin) %#ok<STOUT>
%===============================================================================
% FUNCTION:
%   setupSolarized.m
%
% PURPOSE:
%   Loads the Solarized color scheme, either light or dark as specified by the
%   user. More information about the Solarzied project can be found online:
%
%       http://ethanschoonover.com/solarized
%
% RESULTS OF SCRIPT:
%   o The script loads the color pallet as defined by the solarized project
%   o Optional string inputs are 'light', ''dark', or 'default' (see examples
%   below for proper usage. The default option will restore the Matlab default
%   color scheme.
%
% EXAMPLE:
%   o setupSolarized('light');
%   o setupSolarized('dark');
%   o setupSolarized('default');
%===============================================================================

%===============================================================================
% REVISION HISTORY:
%   o Add colors setup to return to default
%       - Wang Yudong / 2015-01-05
%   o Utilities Toolbox:
%       - B. Hager / 2013-05-31 <- Original and debugged.
%
% COPYRIGHT:
%   This work and derivatives of this work are copyrighted by Honda
%   Aircraft Company. Any use without permission is strictly
%   prohibited.
%===============================================================================
%% Initial Setup
if (nargin==1)
    slrzd = varargin{1};
elseif (nargin==0)
    slrzd = 'default';
end

% Setup the color pallet           % SOLARIZED HEX     16/8 TERMCOL  XTERM/HEX   L*A*B      RGB         HSB
% divide by 256 for Matlab         % --------- ------- ---- -------  ----------- ---------- ----------- -----------
sol.base03  = [  0  43  54] / 256; % base03    #002b36  8/4 brblack  234 #1c1c1c 15 -12 -12   0  43  54 193 100  21
sol.base02  = [  7  54  66] / 256; % base02    #073642  0/4 black    235 #262626 20 -12 -12   7  54  66 192  90  26
sol.base01  = [ 88 110 117] / 256; % base01    #586e75 10/7 brgreen  240 #585858 45 -07 -07  88 110 117 194  25  46
sol.base00  = [101 123 131] / 256; % base00    #657b83 11/7 bryellow 241 #626262 50 -07 -07 101 123 131 195  23  51
sol.base0   = [131 148 150] / 256; % base0     #839496 12/6 brblue   244 #808080 60 -06 -03 131 148 150 186  13  59
sol.base1   = [147 161 161] / 256; % base1     #93a1a1 14/4 brcyan   245 #8a8a8a 65 -05 -02 147 161 161 180   9  63
sol.base2   = [238 232 213] / 256; % base2     #eee8d5  7/7 white    254 #e4e4e4 92 -00  10 238 232 213  44  11  93
sol.base3   = [253 246 227] / 256; % base3     #fdf6e3 15/7 brwhite  230 #ffffd7 97  00  10 253 246 227  44  10  99
sol.yellow  = [181 137   0] / 256; % yellow    #b58900  3/3 yellow   136 #af8700 60  10  65 181 137   0  45 100  71
sol.orange  = [203  75  22] / 256; % orange    #cb4b16  9/3 brred    166 #d75f00 50  50  55 203  75  22  18  89  80
sol.red     = [220  50  47] / 256; % red       #dc322f  1/1 red      160 #d70000 50  65  45 220  50  47   1  79  86
sol.magenta = [211  54 130] / 256; % magenta   #d33682  5/5 magenta  125 #af005f 50  65 -05 211  54 130 331  74  83
sol.violet  = [108 113 196] / 256; % violet    #6c71c4 13/5 brmagenta 61 #5f5faf 50  15 -45 108 113 196 237  45  77
sol.blue    = [ 38 139 210] / 256; % blue      #268bd2  4/4 blue      33 #0087ff 55 -10 -45  38 139 210 205  82  82
sol.cyan    = [ 42 161 152] / 256; % cyan      #2aa198  6/6 cyan      37 #00afaf 60 -35 -05  42 161 152 175  74  63
sol.green   = [133 153   0] / 256; % green     #859900  2/2 green     64 #5f8700 60 -20  65 133 153   0  68 100  60
mat.black   = [  0   0   0] / 256;
mat.white   = [255 255 255] / 256;
mat.blue    = [  0   0 255] / 256;
mat.green   = [ 34 139  34] / 256;
mat.violet  = [160  32 240] / 256;
mat.red178  = [178   0   0] / 256;
mat.red230  = [230   0   0] / 256;
mat.golden  = [178 140   0] / 256;
mat.orange  = [255 148   0] / 256;
mat.chamois = [238 225 180] / 256;
mat.iceblue = [202 232 232] / 256;
mat.persian = [  0 163 163] / 256;
mat.yellow  = [252 252 220] / 256;

%% Setup Color Scheme for Light/Dark Options
if strcmp(slrzd,'light')
    sycb = 0;           % Set 'Use system colors' checkbox to False
    txc  = sol.base00;  % Set 'Text' color
    bgc  = sol.base3;   % Set 'Background' color
    kwd  = sol.blue;    % Set 'Keywords' color
    cmt  = sol.cyan;    % Set 'Comments' color - spec calls for base1, not sure about that...
    str  = sol.magenta; % Set 'Strings' color
    ustr = sol.orange;  % Set 'Unterminated strings' color
    scmd = sol.yellow;  % Set 'System commands' color
    errs = sol.red;     % Set 'Errors' color
    hyp  = sol.blue;    % Set 'Hyperlinks' color
    warn = sol.orange;  % Set 'Warnings' color
    afhb = 0;           % Set 'Autofix highlight' checkbox to False
    afh  = sol.base2;   % Set 'Autofix highlight' color
%     ahib = 0;           % Set 'Automatically highlight' checkbox to False
%     ahi  = sol.violet;  % Set 'Automatically highlight' color
    vwss = sol.green;   % Set 'Variables with shared scope' color
    hsb  = 0;           % Set 'Highlight sections' checkbox to False
    hsbc = mat.yellow;  % Set 'Highlight sections' color to default yellow
    hclb = 1;           % Set 'Highlight current line' checkbox to True
    hcl  = sol.base2;   % Set 'Highlight current line' color
    slnb = 1;           % Set 'Show line numbers' checkbox to True
    rtlb = 1;           % Set 'Show line' checkbox in Right-hand text limit to True
elseif strcmp(slrzd,'dark')
    sycb = 0;           % Set 'Use system colors' checkbox to False
    txc  = sol.base0;   % Set 'Text' color
    bgc  = sol.base03;  % Set 'Background' color
    kwd  = sol.blue;    % Set 'Keywords' color
    cmt  = sol.cyan;    % Set 'Comments' color - spec calls for base1, not sure about that...
    str  = sol.magenta; % Set 'Strings' color
    ustr = sol.orange;  % Set 'Unterminated strings' color
    scmd = sol.yellow;  % Set 'System commands' color
    errs = sol.red;     % Set 'Errors' color
    hyp  = sol.blue;    % Set 'Hyperlinks' color
    warn = sol.orange;  % Set 'Warnings' color
    afhb = 0;           % Set 'Autofix highlight' checkbox to False
    afh  = sol.base00;  % Set 'Autofix highlight' color
%     ahib = 0;           % Set 'Automatically highlight' checkbox to False
%     ahi  = sol.violet;  % Set 'Automatically highlight' color
    vwss = sol.green;   % Set 'Variables with shared scope' color
    hsb  = 0;           % Set 'Highlight sections' checkbox to False
    hsbc = sol.base02;  % Set 'Highlight sections' color to default yellow
    hclb = 1;           % Set 'Highlight current line' checkbox to True
    hcl  = sol.base02;  % Set 'Highlight current line' color
    slnb = 1;           % Set 'Show line numbers' checkbox to True
    rtlb = 1;           % Set 'Show line' checkbox in Right-hand text limit to True
elseif strcmp(slrzd,'default')
    sycb = 1;           % Set 'Use system colors' checkbox to True
    txc  = mat.black;   % Set 'Text' color
    bgc  = mat.white;   % Set 'Background' color
    kwd  = mat.blue;    % Set 'Keywords' color
    cmt  = mat.green;   % Set 'Comments' color - spec calls for base1, not sure about that...
    str  = mat.violet;  % Set 'Strings' color
    ustr = mat.red178;  % Set 'Unterminated strings' color
    scmd = mat.golden;  % Set 'System commands' color
    errs = mat.red230;  % Set 'Errors' color
    hyp  = mat.blue;    % Set 'Hyperlinks' color
    warn = mat.orange;  % Set 'Warnings' color
    afhb = 1;           % Set 'Autofix highlight' checkbox to True
    afh  = mat.chamois; % Set 'Autofix highlight' color
%     ahib = true;        % Set 'Automatically highlight' checkbox to True
%     ahi  = mat.iceblue; % Set 'Automatically highlight' color
    vwss = mat.persian; % Set 'Variables with shared scope' color
    hsb  = 1;           % Set 'Highlight sections' checkbox to True
    hsbc = mat.yellow;  % Set 'Highlight sections' color to default yellow
    hclb = 0;           % Set 'Highlight current line' checkbox to False
    hcl  = sol.base2;   % Set 'Highlight current line' color
    slnb = 1;           % Set 'Show line numbers' checkbox to True
    rtlb = 1;           % Set 'Show line' checkbox in Right-hand text limit to True
end

%% Desktop tool colors
com.mathworks.services.Prefs.setBooleanPref('ColorsUseSystem',sycb); clear('sycb')

com.mathworks.services.Prefs.setColorPref('ColorsText',java.awt.Color(txc(1), txc(2), txc(3)));
com.mathworks.services.ColorPrefs.notifyColorListeners('ColorsText'); clear('txc')

com.mathworks.services.Prefs.setColorPref('ColorsBackground',java.awt.Color(bgc(1), bgc(2), bgc(3)));
com.mathworks.services.ColorPrefs.notifyColorListeners('ColorsBackground'); clear('bgc')

%% Setup MATLAB syntax highlighting colors
com.mathworks.services.Prefs.setColorPref('Colors_M_Keywords',java.awt.Color(kwd(1), kwd(2), kwd(3)));
com.mathworks.services.ColorPrefs.notifyColorListeners('Colors_M_Keywords'); clear('kwd')

com.mathworks.services.Prefs.setColorPref('Colors_M_Comments',java.awt.Color(cmt(1), cmt(2), cmt(3)));
com.mathworks.services.ColorPrefs.notifyColorListeners('Colors_M_Comments'); clear('cmt')

com.mathworks.services.Prefs.setColorPref('Colors_M_Strings',java.awt.Color(str(1), str(2), str(3)));
com.mathworks.services.ColorPrefs.notifyColorListeners('Colors_M_Strings'); clear('str')

com.mathworks.services.Prefs.setColorPref('Colors_M_UnterminatedStrings',java.awt.Color(ustr(1), ustr(2), ustr(3)));
com.mathworks.services.ColorPrefs.notifyColorListeners('Colors_M_UnterminatedStrings'); clear('ustr')

com.mathworks.services.Prefs.setColorPref('Colors_M_SystemCommands',java.awt.Color(scmd(1), scmd(2), scmd(3)));
com.mathworks.services.ColorPrefs.notifyColorListeners('Colors_M_SystemCommands'); clear('scmd')

com.mathworks.services.Prefs.setColorPref('Colors_M_Errors',java.awt.Color(errs(1), errs(2), errs(3)));
com.mathworks.services.ColorPrefs.notifyColorListeners('Colors_M_Errors');clear('errs')

%% Other colors
com.mathworks.services.Prefs.setColorPref('Colors_HTML_HTMLLinks',java.awt.Color(hyp(1), hyp(2), hyp(3)));
com.mathworks.services.ColorPrefs.notifyColorListeners('Colors_HTML_HTMLLinks'); clear('hyp')

%% Code analyzer colors
com.mathworks.services.Prefs.setColorPref('Colors_M_Warnings',java.awt.Color(warn(1), warn(2), warn(3)));
com.mathworks.services.ColorPrefs.notifyColorListeners('Colors_M_Warnings'); clear('warn')

com.mathworks.services.Prefs.setBooleanPref('ColorsUseMLintAutoFixBackground',afhb);
com.mathworks.services.Prefs.setColorPref('ColorsMLintAutoFixBackground',java.awt.Color(afh(1), afh(2), afh(3)));
com.mathworks.services.ColorPrefs.notifyColorListeners('ColorsMLintAutoFixBackground'); clear('afhb','afh')

%% Variable and function colors
% com.mathworks.services.Prefs.setBooleanPref('Editor.VariableHighlighting.Automatic',ahib);
% com.mathworks.services.Prefs.setColorPref('Editor.VariableHighlighting.Color',java.awt.Color(ahi(1), ahi(2), ahi(3)));
% com.mathworks.services.ColorPrefs.notifyColorListeners('Editor.VariableHighlighting.Color'); clear('ahib','ahi')

% *** need to add checkbox option for variables with shared scope here
com.mathworks.services.Prefs.setColorPref('Editor.NonlocalVariableHighlighting.TextColor',java.awt.Color(vwss(1), vwss(2), vwss(3)));
com.mathworks.services.ColorPrefs.notifyColorListeners('Editor.NonlocalVariableHighlighting.TextColor');clear('vwss')

%% Section display options
com.mathworks.services.Prefs.setBooleanPref('EditorCodepadHighVisible',hsb);
com.mathworks.services.Prefs.setColorPref('Editorhighlight-lines', java.awt.Color(hsbc(1), hsbc(2), hsbc(3)));
clear('hsb','hsbc');

%% Editor/Debugger General display options
com.mathworks.services.Prefs.setBooleanPref('Editorhighlight-caret-row-boolean',hclb);
com.mathworks.services.Prefs.setColorPref('Editorhighlight-caret-row-boolean-color',java.awt.Color(hcl(1), hcl(2), hcl(3)));
com.mathworks.services.ColorPrefs.notifyColorListeners('Editorhighlight-caret-row-boolean-color'); clear('hclb','hcl')

com.mathworks.services.Prefs.setBooleanPref('EditorShowLineNumbers',slnb); clear('slnb')

com.mathworks.services.Prefs.setBooleanPref('EditorRightTextLineVisible',rtlb);
%EditorRightTextLineLimit=I80
%EditorRightTextLimitLineWidth=I1
clear('rtlb')

%% Cleanup
clear('sol')
clear('mat')


% Check if an input file is in BNT format
%
% Checks format of the input file. Returns TRUE if the file is in BNT
% format or FALSE otherwise. If file doesn't exist returns FALSE.
%
function result = isBntFormat(filename)
    result = false;
    if exist(filename, 'file') == 0
        return;
    end

    fid = data.safefopen(filename, 'r');
    str = fgets(fid);

    result = ischar(str) && ~isempty(strfind(lower(str), 'name')) && ~isempty(strfind(lower(str), 'version'));
end


function tf = isTestCaseSubclass(name)
%isTestCaseSubclass True for name of a TestCase subclass
%   tf = isTestCaseSubclass(name) returns true if the string name is the name of
%   a TestCase subclass on the MATLAB path.

%   Steven L. Eddins
%   Copyright 2008-2009 The MathWorks, Inc.

tf = false;

class_meta = meta.class.fromName(name);
if isempty(class_meta)
    % Not the name of a class
    return;
end

if strcmp(class_meta.Name, 'TestCase')
    tf = true;
else
    tf = isMetaTestCaseSubclass(class_meta);
end

function tf = isMetaTestCaseSubclass(class_meta)

tf = false;

if strcmp(class_meta.Name, 'TestCase')
    tf = true;
else
    % Invoke function recursively on parent classes.
    super_classes = class_meta.SuperClasses;
    for k = 1:numel(super_classes)
        if isMetaTestCaseSubclass(super_classes{k})
            tf = true;
            break;
        end
    end
end


function r = rank(varargin)
% rank = 1

r = 1;


% DATASETSTOOLBOXES Loads in toolboxes for DATASETS.

importLatest('ndlutil');


function handles = vis_plotModelValidation(whitestats,PCstats,stabilitystats,varargin)
% Visualize the results of model validation as computed by
% pop_est_validateMVAR()
%
% Inputs:
%
%       whitestats:     Cell array of structs each containing results of
%                       tests for whiteness of residuals for a single
%                       dataset/condition
%                       (as output by est_checkMVARWhiteness())
%                       If not available, pass in an empty matrix to skip
%                       plotting this result.
%       PCstats:        Cell array of structs each containing results of
%                       tests for consistency of the model for a single
%                       dataset/condition
%                       (as output by est_checkMVARConsistency())
%                       If not available, pass in an empty matrix to skip
%                       plotting this result.
%       stabilitystats: Cell array of structs each containing results of
%                       tests for stability of the model for a single
%                       dataset/condition
%                       (as output by est_checkMVARStability())
%                       If not available, pass in an empty matrix to skip
%                       plotting this result.
%
%
% Optional:
%
%       whitenessCriteria:   Cell array of whiteness criteria
%       checkWhiteness:      (boolean) plot whiteness results
%       checkConsistency:    (boolean) plot consistency results
%       checkStability:      (boolean) plot stability results
%       windowTimes:        Times (sec) of windows for x-axis labeling.
%                           This MUST be the same length as number of
%                           time windows (e.g.) whitestats{1}.winStartIdx
%       conditions:         Cell array of condition labels
%                           e.g. conditions = {ALLEEG.condition}
%
% Outputs:
%
%       Figures will be rendered showing model validation results for each
%       dataset. The handles to the figures are returned.
%
% See Also: pop_est_validateMVAR(),est_checkMVARWhiteness(),
%           est_checkMVARStability(), est_checkMVARConsistency()
%
% References:
%
% [1] Mullen T (2010) The Source Information Flow Toolbox (SIFT):
%   Theoretical Handbook and User Manual. Chapter 6.
%   Available at: http://www.sccn.ucsd.edu/wiki/Sift
%
% Author: Tim Mullen, 2010, SCCN/INC, UCSD.
% Email:  tim@sccn.ucsd.edu

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

% if ~isempty(varargin) && isstruct(varargin{1})
%     varargin = [hlp_struct2varargin(varargin{1}) varargin];
% end

whitenessCriteria = {};

% find the names of all whiteness tests stored in whitestats
if ~isempty(whitestats{1})
    fn = fieldnames(whitestats{1});
    for i=1:length(fn)
        if isfield(whitestats{1}.(fn{i}),'fullname')
            whitenessCriteria = [whitenessCriteria fn{i}];
        end
    end
end

num_conds = max([length(whitestats),length(PCstats),length(stabilitystats)]);

g = finputcheck(varargin, ...
    {'whitenessCriteria'   'cell'  whitenessCriteria   whitenessCriteria; ...
    'checkWhiteness',     'boolean'   []          true; ...
    'checkConsistency'    'boolean'   []          true; ...
    'checkStability'      'boolean'   []          true; ...
    'windowTimes'         'real'      []          [];   ...
    'conditions'          'cell'      {}          {}; ...
    },'mode','ignore','quiet');

if isempty(whitestats{1}),         g.checkWhiteness    = false;    end
if isempty(PCstats{1}),            g.checkConsistency  = false;    end
if isempty(stabilitystats{1}),     g.checkStability    = false;    end
if isempty(g.conditions),          g.conditions        = cell(1,num_conds); end

numrows = sum([g.checkWhiteness g.checkConsistency g.checkStability]);
numcols = 1;

for cond = 1:num_conds

    if isempty(g.conditions{cond})
        g.conditions{cond} = sprintf('Condition %d',cond);
    end

    % plot results
    handles(cond) = figure('Name',sprintf('%s - Model Validation Results',g.conditions{cond}));
    curplot=1;

    if g.checkWhiteness
        % Plot results of residual whiteness checks
        if ~iscell(whitestats), whitestats = {whitestats}; end

        ax=subplot(numrows,numcols,curplot);
        for i = 1:length(g.whitenessCriteria)
            wcstr = lower(hlp_variableize(g.whitenessCriteria{i}));
            wc = whitestats{cond}.(wcstr);
            pvals(i,:) = wc.pval;
            if size(pvals,2)>1
                lgnd{i} = sprintf('%s (%d/%d white)',wc.fullname, sum(wc.w),length(wc.w));
            else
                lgnd{i} = sprintf('%s (%swhite)',wc.fullname, fastif(wc.w,'','not '));
            end
        end

        if size(pvals,2)>1
            % more than one window -- make lineplot
            if ~isempty(g.windowTimes)
                abscissa = g.windowTimes;
            else
                abscissa = 1:length(whitestats{cond}.winStartIdx);
            end
            plot(ax,abscissa,pvals','Marker','.');
            xlabel(ax,fastif(isempty(g.windowTimes),'Window number','Time (sec)'));

            legend(ax,lgnd);
            set(ax, ...
                'Xlim',[abscissa(1)-abs(diff(abscissa(1:2))) abscissa(end)+abs(diff(abscissa(1:2)))], ...
                'Ylim',[max(0,min(pvals(:))-0.5), min(1,max(pvals(:))+0.5)]);
            axcpystr = 'legend(''''show'''');';
        else
            % single window -- create bar plots
            h = bar(ax,pvals);
            ch = get(h,'Children');

            set(ax,'xticklabel',lgnd);
            colors = [[1 0 0];[0 0 1];[0 1 0];[0 0 0];[1 0 1];[0 1 1]];
            colors = colors(1:length(pvals),:);
            set(ch,'FaceVertexCData',colors);
            %             set(gca,'xlim',[0 length(length(g.whitenessCriteria))+1],'Ylim',[max(0,min(pvals(:))-0.5), min(1,max(pvals(:))+0.5)]);
            axcpystr = '';
        end

        hl=hline(whitestats{cond}.alpha,'b','1-p_{port}',[1.01 -0.01],ax);
        set(hl,'linestyle','--','linewidth',2);
        ylabel({'Whiteness Significance'});

        curplot=curplot+1;

        if ismember_bc('acf',lower(g.whitenessCriteria))
            hl=hline(1-whitestats{cond}.alpha,'r','1-P_{acf}',[1.01 -0.01],ax);
            set(hl,'linestyle','--','linewidth',2);
        end

        axcopy(ax,axcpystr);
    end

    if g.checkConsistency
        % Plot results of consistency checks

        if ~iscell(PCstats), PCstats = {PCstats}; end

        ax=subplot(numrows,numcols,curplot);
        if length(PCstats{cond}.PC)>1
            % more than one window -- make lineplot
            meanpc = mean(PCstats{cond}.PC);
            stdpc  = std(PCstats{cond}.PC);
            if ~isempty(g.windowTimes)
                abscissa = g.windowTimes;
            else
                abscissa = 1:1:length(PCstats{cond}.winStartIdx);
            end
            plot(ax,abscissa,PCstats{cond}.PC,'Marker','.');
            xlabel(ax,fastif(isempty(g.windowTimes),'Window number','Time (sec)'));
            set(ax,...
            'Xlim',[abscissa(1)-abs(diff(abscissa(1:2))) abscissa(end)+abs(diff(abscissa(1:2)))], ...
            'Ylim',[min(PCstats{cond}.PC)-50 min(max(PCstats{cond}.PC)+50,100)]);
            % make legend
            text(0.98,0.9,sprintf('Mean PC: %0.2f+/-%0.3g%%',meanpc,stdpc), ...
                    'units','normalized','horizontalalignment','right', ...
                    'edgecolor','k','backgroundcolor','w','parent',ax);
            % make a small histogram on right side of plot
            %             axpos = get(ax,'Position');
            %             axhist = axesRelative(ax, 'Position',[1.01 0 0.1 1], 'Units','Normalized');   %axes('Position',[axpos(1)+axpos(3)+0.01 axpos(2) 0.05 axpos(4)]);
            %             hist(axhist,PCstats{cond}.PC,10);
            %             vline(mean(PCstats{cond}.PC),':r');
            %             set(axhist,'View',[90 90]);
            %             set(axhist,'xdir','rev');
        else
            % single window -- make barplot
            bar(ax,PCstats{cond}.PC);
            % make legend
            text(0.98,0.9,sprintf('(%0.2f%% Consistent)',PCstats{cond}.PC), ...
                'units','normalized','horizontalalignment','right', ...
                'edgecolor','k','backgroundcolor','w','parent',ax);
%             legend(sprintf('(%0.2f%% Consistent)',PCstats{cond}.PC));
            set(ax,'Ylim',[min(0,PCstats{cond}.PC)-1 max(PCstats{cond}.PC,100)+1]);
            set(ax,'xtick',[]);
        end

        ylabel('Percent Consistency');
        axcopy(ax);
        curplot = curplot+1;
    end

    if g.checkStability
        % Plot results of stability checks

        if ~iscell(stabilitystats), stabilitystats = {stabilitystats}; end

        % plot stability results
        ax=subplot(numrows,numcols,curplot);
        if length(stabilitystats{cond}.stability)>1
            % more than one window -- make lineplot
            %boxplot(real(lambda)');
            maxlambda = max(real(stabilitystats{cond}.lambda),[],2);
            if ~isempty(g.windowTimes)
                abscissa = g.windowTimes;
            else
                abscissa = 1:length(stabilitystats{cond}.winStartIdx);
            end
            plot(ax,abscissa,maxlambda,'Marker','.');
            xlabel(ax,fastif(isempty(g.windowTimes),'Window number','Time (sec)'));

            set(ax,'Xlim',[abscissa(1)-abs(diff(abscissa(1:2))) abscissa(end)+abs(diff(abscissa(1:2)))], ...
                   'Ylim',[1.2*min(maxlambda(:)) max(0.01,1.3*max(maxlambda(:)))]);
        else
            % single window -- make barplot
            maxlambda = max(real(stabilitystats{cond}.lambda(:)));
            bar(ax,maxlambda);
            set(ax,'xtick',[]);
        end

        %     set(gca,'ylim',[max(0,0.7*min(abs(lambda(:)))) max(1.3,1.3*max(abs(lambda(:))))]);
        %     axis auto
        hl=hline(0,[],[],[],ax);
        set(hl,'linestyle','--','linewidth',2);
        ylabel(ax,{'Stability Index','(should be < 0)'});
        numstable = sum(stabilitystats{cond}.stability);
        % make legend
        text(0.98,0.9,sprintf('(%d/%d stable)',numstable,length(stabilitystats{cond}.stability)), ...
                'units','normalized','horizontalalignment','right', ...
                'edgecolor','k','backgroundcolor','w','parent',ax);
%         legend(ax,sprintf('(%d/%d stable)',numstable,length(stabilitystats{cond}.stability)));

        axcopy(ax);
    end
end

try
    icadefs; set(handles, 'color', BACKCOLOR);
catch
end;


function [] = system_name1(block)

% Callback processing function for mask parameter
% - number of <Requirement name> used in the System
set_param(block, 'LinkStatus', 'none');
load_system('Simulink'); % Load Simulink library (background)
load_system('MIL_Test');

No = str2double(get_param(block,'No')); % Get # of VF-s
OldNo = length(find_system(block, 'regexp', 'on','LookUnderMasks','all','Name','<Requirement name>'));

for i = 1:max(No,OldNo)
    if OldNo > No && i > No && i <= OldNo % Remove
        % Remove lines
        set_param([block '/Bus Creator'], 'Inputs', num2str(No));
        SigAtTLines = get_param([block '/<Requirement name>' num2str(i)],'LineHandles');
        delete_line(SigAtTLines.Inport(1));
        delete_line(SigAtTLines.Outport(1));
        delete_line([block '/Arbitration'],['In' num2str(i) '/' num2str(1)],['Collect Verdicts/' num2str(i)]);
        % Remove blocks
        delete_block([block '/<Requirement name>' num2str(i)]);

        % remove lines from Bus Selector
        SigFrBS = get_param([block '/Bus Selector'], 'LineHandles');
        delete_line(SigFrBS.Outport(i));

        % remove Outport of Arbitration
        delete_block([block '/Arbitration/In' num2str(i)]);

        % Remove Inport of Bus Creator4

    elseif No > OldNo && i > OldNo && i <= No % Add
        % Add blocks
        add_block('MIL_Test/Validation Function/Test Evaluation Architecture/<system name>/<Requirement name>',[block '/<Requirement name>' num2str(i)]);
        set_param([block '/<Requirement name>' num2str(i)], 'LinkStatus', 'none');
        if i == 2
             pos = get_param([block '/<Requirement name>'], 'Position');
        else pos = get_param([block '/<Requirement name>' num2str(i-1)], 'Position');
        end
        pos1 = pos(1);
        pos3 = pos(3);
        pos2 = pos(2)+80;
        pos4 = pos(4)+80;
        set_param([block '/<Requirement name>' num2str(i)], 'Position',[pos1 pos2 pos3 pos4]);
        set_param([block '/Bus Creator'], 'Inputs', num2str(i));

        % Add Inports of Bus Creator4
        set_param([block '/Bus Creator4'], 'Inputs', num2str(i));

        % Add Outports of Bus Selector
        % OutSignal of Bus Seletor
        %Signal1 = 'signal1.signal1.signal1';
        %for j = 2 : i
        SignalP = strcat(',','signal',num2str(i),'.signal1.signal1');
        %Signal1 = strcat(Signal1,SignalP);
        Signal1 = get_param([block '/Bus Selector'], 'OutputSignals');
        Signal1 = strcat(Signal1,SignalP);
        %end
        set_param([block '/Bus Selector'], 'OutputSignals',Signal1)

        % Add lines
        add_line(block,['<Requirement name>' num2str(i) '/1'],['Bus Creator/' num2str(i)],'autorouting','on');
        add_line(block,['Signal Conversion/1'],['<Requirement name>' num2str(i) '/1'],'autorouting','on');

        % Add lines between Bus Selector and Bus Creator4
        add_line(block,['Bus Selector/' num2str(i)],['Bus Creator4/' num2str(i)],'autorouting','on');

        % Add Input to Arbitration
        add_block('Simulink/Ports & Subsystems/In1',[block '/Arbitration/In' num2str(i)]);
        if i == 2
             posi = get_param([block '/Arbitration/In1'], 'Position');
        else posi = get_param([block '/Arbitration/In' num2str(i-1)], 'Position');
        end
        pos1 = posi(1);
        pos3 = posi(3);
        pos2 = posi(2)+40;
        pos4 = posi(4)+40;
        set_param([block '/Arbitration/In' num2str(i)], 'Position',[pos1 pos2 pos3 pos4]);

        % fix position of Memory
        fix_pos([block '/Arbitration/Collect Verdicts'],[block '/Arbitration/Memory'],0,10);

        % Add Line from Bus Selector to Arbitration
        add_line(block,['Bus Selector/' num2str(i)],['Arbitration/' num2str(i)],'autorouting','on');

        % Set Inputports of 'Collect Verdicts'
        set_param([block '/Arbitration/Collect Verdicts'], 'Inputs', num2str(i+1));

        % Put the Memory Outsignal always in the last Inport of Collect
        % Verdicts
        delete_line([block '/Arbitration'],['Memory/' num2str(1)],['Collect Verdicts/' num2str(i)]);
        add_line([block '/Arbitration'],['Memory/' num2str(1)],['Collect Verdicts/' num2str(i+1)],'autorouting','on');

        % Add line from 'in' to 'Collect Verdicts', which happens in the
        % undersystem Arbitration
        add_line([block '/Arbitration'],['In' num2str(i) '/' num2str(1)],['Collect Verdicts/' num2str(i)],'autorouting','on');
    end
end

% Remove Outport of Bus Selector & Input of Bus Creator4

    if OldNo > No  % Remove
        set_param([block '/Bus Creator4'], 'Inputs', num2str(No));
        delete_line([block '/Arbitration'],['Memory/' num2str(1)],['Collect Verdicts/' num2str(OldNo+1)]);
        set_param([block '/Arbitration/Collect Verdicts'], 'Inputs', num2str(No+1));
        add_line([block '/Arbitration'],['Memory/' num2str(1)],['Collect Verdicts/' num2str(No+1)],'autorouting','on');
        if No == 1
            S1 = 'signal1.signal1.signal1';
        else
            S1 = 'signal1.signal1.signal1';
            for j = 2:No
              S1 = strcat(S1,',','signal',num2str(j),'.signal1.signal1');
           end
        end
        set_param([block '/Bus Selector'], 'OutputSignals',S1);

    end


function ROIid = getROIdbId(view)
% function ROIid = getROIdbId(view)
% User should select a ROI from a list (a list of all
% ROIs available in the DB).
% Or maybe we must show ROIs for the current session only?..

OKflag = openDbConnection(view);
if(~OKflag)
  ROIid = 0;
  return;
end;

[IdList,NameList,SessionIdList] = ...
  mysql('SELECT rois.id,rois.ROIname,rois.sessionid FROM rois');
[KnownSessionsId,KnownSessionsName] = ...
  mysql('SELECT sessions.id, sessions.sessionCode FROM sessions,rois WHERE sessions.id=rois.sessionid');
mysql('close');

for(Q=1:length(IdList))
  if(SessionIdList(Q)~=0)
    NameList{Q} = ['Session [' KnownSessionsName{max(find(KnownSessionsId==SessionIdList(Q)))} ']: ' NameList{Q}];
  else
    NameList{Q} = ['Unknown session: ' NameList{Q}];
  end
end

[ROIid,OK] = selector(IdList,NameList,'Choose a ROI');

if(OK==0)
  ROIid = 0;
end


function [paramsOut] = postProcessGUI(hObject, callbackdata, inputData) %#ok<INUSL>
title ='Post process parameters';
defaultStruct = inputData.userData.postProcess;
mainFigure = findobj('Type', 'Figure', '-and', 'Name', inputData.name);
userdata = get(mainFigure, 'UserData');
if isempty(userdata) || ~isfield(userdata, 'postProcess')
    paramsOut = struct();
else
    paramsOut = userdata.postProcess;
end
[defaultStruct, errors] = checkStructureDefaults(paramsOut, defaultStruct);

if ~isempty(errors)
    warning('postProcessGUI:bad parameters', getMessageString(errors)); %#ok<CTPCT>
end
if defaultStruct.cleanupReference.value
    cleanUpCheckValue = 1;
else
    cleanUpCheckValue = 0;
end
if defaultStruct.keepFiltered.value
    filteredCheckValue = 1;
else
    filteredCheckValue = 0;
end
if defaultStruct.removeInterpolatedChannels.value
    removeCheckValue = 1;
else
    removeCheckValue = 0;
end
closeOpenWindows(title);
geometry = {[1, 1], [1, 1], [1, 1]};
geomvert = [];
uilist = {{'style', 'text', 'string', 'Clean up reporting fields', 'TooltipString', ''}...
    {'style', 'checkbox', 'tag', 'cleanupReference', 'Value', cleanUpCheckValue}...
    {'style', 'text', 'string', 'Keep filtered', 'TooltipString', ''}...
    {'style', 'checkbox', 'tag', 'keepFiltered', 'Value', filteredCheckValue}...
    {'style', 'text',  'string', 'Remove bad interpolated channels'}...
    {'style', 'checkbox', 'tag', 'removeInterpolatedChannels', 'Value', removeCheckValue}};
[~, ~, ~, paramsOut] = inputgui('geometry', geometry, ...
    'geomvert', geomvert, 'uilist', uilist, 'title', title, ...
    'helpcom', 'pophelp(''pop_prepPipeline'')');
if (isempty(paramsOut))  % Cancelled out
    return;
end
mainFigure = findobj('Type', 'Figure', '-and', 'Name', inputData.name);
userdata = get(mainFigure, 'UserData');
if paramsOut.cleanupReference
    userdata.postProcess.cleanupReference = true;
else
    userdata.postProcess.cleanupReference = false;
end
if paramsOut.keepFiltered
    userdata.postProcess.keepFiltered = true;
else
    userdata.postProcess.keepFiltered = false;
end
if paramsOut.removeInterpolatedChannels
    userdata.postProcess.removeInterpolatedChannels = true;
else
    userdata.postProcess.removeInterpolatedChannels = false;
end
set(mainFigure, 'UserData', userdata);
end


function res = format(varargin)
%FINISH       Called when exiting Matlab: set rounding mode to nearest
%

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

  setround(0)


% WriteSegy : writes data to disk using SEGY REV 1 standard.
%
% EX
% WriteSegy('datacube.segy',data,'dt',.004,'Inline3D',Inline,'Crossline3D',Crossline,'cdpX',X,'cdpY',Y);
%
% to use a specific SEG revision use :
% WriteSegy('test.segy',seisdata,'revision',0); % SEG-Y Revision 0
% WriteSegy('test.segy',seisdata,'revision',1); % SEG-Y Revision 1
%
% to use a specific Data Sampling Format use :
% WriteSegy('test.segy',seisdata,'dsf',1); % IBM FLAOTING POINT
%
% Forice Revision 1 and IEEE Floating point :
% WriteSegy('test.segy',seisdata,'dsf',5,'revision',1);
%
% See also : WriteSegyStructure, WriteSu, WriteSuStructure
%

%
% (C) 2001-2007, Thomas Mejer Hansen, tmh@gfy.ku.dk/thomas.mejer.hansen@gmail.com
%
%    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 WriteSegy(filename,data,varargin);

    [ns,ntraces]=size(data);

    for i=1:2:length(varargin)
        var=varargin{i};
        val=varargin{i+1};
        eval([var,'=[',num2str(val),'];']);
    end

    if exist('dt')~=1
        dt=0.004;
        SegymatVerbose([mfilename,' - No dt set. Using dt=',num2str(dt)],0)
    end

    %%%%%%%%%%
    % SET UP SegyHeader structure.
    if exist('TextualFileHeader'), SegyHeader.TextualFileHeader=TextualFileHeader; end
    if exist('Job')==1, SegyHeader.Job=Job; end;
    if exist('Line')==1, SegyHeader.Line=Line; end
    if exist('Reel')==1, SegyHeader.Reel=Reel; end
    if exist('DataTracePerEnsemble')==1, SegyHeader.DataTracePerEnsemble=DataTracePerEnsemble; end
    if exist('AuxiliaryTracePerEnsemble')==1, SegyHeader.AuxiliaryTracePerEnsemble=AuxiliaryTracePerEnsemble; end
    if exist('dt')==1, SegyHeader.dt=dt.*1e+6; end
    if exist('dtOrig')==1, SegyHeader.dtOrig=dtOrig; end
    if exist('ns')==1, SegyHeader.ns=ns; end
    if exist('nsOrig')==1, SegyHeader.nsOrig=nsOrig; end
    if exist('EnsembleFold')==1, SegyHeader.EnsembleFold=EnsembleFold;  end
    if exist('TraceSorting')==1, SegyHeader.TraceSorting=TraceSorting; end
    if exist('VerticalSumCode')==1, SegyHeader.VerticalSumCode=VerticalSumCode; end

    %%%%%%%%%%
    %% CHOOSE WHICH SEGY REVISION AND DATATYPE TO USE
    %% DEFAULT IS REVISION 1, 4-byte IEEE

    % IF A SPECFIC REVISION HAS BEEN CHOSEN, USE THAT
    if exist('revision')==1,
        if revision==1,
            SegyHeader.SegyFormatRevisionNumber=256;
        else
            SegyHeader.SegyFormatRevisionNumber=0;
        end
        SegymatVerbose([mfilename,' :  Using user specified SEG Y revision : ',num2str(revision)],1)
    end

    % IF A SPECFIC DATA SAMPLING FORMAT HAS BEEN SELECTED USE THAT
    if exist('dsf')==1,
        SegyHeader.DataSampleFormat=dsf;
        SegymatVerbose([mfilename,' :  Using user specified Data Sample Format : ',num2str(revision)],1)
    end

    % OPEN SEGY FILE HANDLE
    segyid = fopen(filename,'w','b');   % ALL DISK FILES ARE IN BIG
                                        % ENDIAN FORMAT, ACCORDING TO SEG
                                        % Y rev 1

    % Write SEGY HEADER
    SegyHeader=PutSegyHeader(segyid,SegyHeader);

    for i=1:ntraces;
        if (i/100)==round(i/100),
            SegymatVerbose(['writing trace ',num2str(i),' of ',num2str(ntraces)],0);
        end
        % Basic TraceHeader information

        % INITALIZE SEGY TRACE HEADER
        if exist('SegyTraceHeader')==0;
            SegyTraceHeader=InitSegyTraceHeader(ns,dt*1e+6);
        end

        if exist('TraceNumber')==0
            SegyTraceHeader.TraceNumber=i;
            SegyTraceHeader.TraceSequenceFile=i;
        end

        % Update TraceHeader information if available
        if exist('cdpX')==1,SegyTraceHeader.cdpX = cdpX(i);end
        if exist('offset')==1,SegyTraceHeader.offset = offset(i);end
        if exist('cdpY')==1,SegyTraceHeader.cdpY = cdpY(i);end
        if exist('Inline3D')==1,SegyTraceHeader.Inline3D = Inline3D(i);end
        if exist('Crossline3D')==1,SegyTraceHeader.Crossline3D=Crossline3D(i);end

        if exist('YearDataRecorded')==1,SegyTraceHeader.YearDataRecorded=YearDataRecorded(i);end
        if exist('DayOfYear')==1,SegyTraceHeader.DayOfYear=DayOfYear(i);end
        if exist('HourOfDay')==1,SegyTraceHeader.HourOfDay=HourOfDay(i);end
        if exist('MinuteOfOur')==1,SegyTraceHeader.MinuteOfOur=MinuteOfOur(i);end
        if exist('SecondOfMinute')==1,SegyTraceHeader.SecondOfMinute=SecondOfMinute(i);end
        if exist('TimeBaseCode')==1,SegyTraceHeader.TimeBaseCode=TimeBaseCode(i);end

        % Write the Trace
        PutSegyTrace(segyid,data(:,i),SegyTraceHeader,SegyHeader);
    end

    % CLOSE SEGY FILE HANDLE

    fclose(segyid);


function q = reshape(q,varargin)
% overloads reshape

q.a = reshape(q.a,varargin{:});
q.b = reshape(q.b,varargin{:});
q.c =  reshape(q.c,varargin{:});
q.d = reshape(q.d,varargin{:});
q.i = reshape(q.i,varargin{:});


% Compile libraries and download network

[home_dir, name, ext] = fileparts(mfilename('fullpath'));

warning('ON', 'STRCF:install')

% mtimesx
if exist('external_libs/mtimesx', 'dir') == 7
    cd external_libs/mtimesx
    mtimesx_build;
    cd(home_dir)
else
    error('STRCF:install', 'Mtimesx not found.')
end

% PDollar toolbox
if exist('external_libs/pdollar_toolbox/external', 'dir') == 7
    cd external_libs/pdollar_toolbox/external
    toolboxCompile;
    cd(home_dir)
else
    warning('STRCF:install', 'PDollars toolbox not found. Clone this submodule if you want to use HOG features. Skipping for now.')
end

% matconvnet
if exist('external_libs/matconvnet/matlab', 'dir') == 7
    cd external_libs/matconvnet/matlab
    try
        disp('Trying to compile MatConvNet with GPU support')
        vl_compilenn('enableGpu', true)
    catch err
        warning('STRCF:install', 'Could not compile MatConvNet with GPU support. Compiling for only CPU instead.\nVisit http://www.vlfeat.org/matconvnet/install/ for instructions of how to compile MatConvNet.\nNote: remember to move the mex-files after re-compiling.');
        vl_compilenn;
    end
    status = movefile('mex/vl_*.mex*');
    cd(home_dir)

    % donwload network
    cd feature_extraction
    mkdir networks
    cd networks
    if ~(exist('imagenet-vgg-m-2048.mat', 'file') == 2)
        disp('Downloading the network "imagenet-vgg-m-2048.mat" from "http://www.vlfeat.org/matconvnet/models/imagenet-vgg-m-2048.mat"...')
        urlwrite('http://www.vlfeat.org/matconvnet/models/imagenet-vgg-m-2048.mat', 'imagenet-vgg-m-2048.mat')
        disp('Done!')
    end
    cd(home_dir)
else
    warning('STRCF:install', 'Matconvnet not found. Clone this submodule if you want to use CNN features. Skipping for now.')
end


function [selection,value] = listdlgARH(varargin)
%LISTDLG  List selection dialog box.
%   [SELECTION,OK] = LISTDLG('ListString',S) creates a modal dialog box
%   which allows you to select a string or multiple strings from a list.
%   SELECTION is a vector of indices of the selected strings (length 1 in
%   the single selection mode).  This will be [] when OK is 0.  OK is 1 if
%   you push the OK button, or 0 if you push the Cancel button or close the
%   figure.
%
%   Double-clicking on an item or pressing <CR> when multiple items are
%   selected has the same effect as clicking the OK button.  Pressing <CR>
%   is the same as clicking the OK button. Pressing <ESC> is the same as
%   clicking the Cancel button.
%
%   Inputs are in parameter,value pairs:
%
%   Parameter       Description
%   'ListString'    cell array of strings for the list box.
%   'SelectionMode' string; can be 'single' or 'multiple'; defaults to
%                   'multiple'.
%   'ListSize'      [width height] of listbox in pixels; defaults
%                   to [160 300].
%   'InitialValue'  vector of indices of which items of the list box
%                   are initially selected; defaults to the first item.
%   'Name'          String for the figure's title; defaults to ''.
%   'PromptString'  string matrix or cell array of strings which appears
%                   as text above the list box; defaults to {}.
%   'OKString'      string for the OK button; defaults to 'OK'.
%   'CancelString'  string for the Cancel button; defaults to 'Cancel'.
%
%   A 'Select all' button is provided in the multiple selection case.
%
%   Example:
%     d = dir;
%     str = {d.name};
%     [s,v] = listdlg('PromptString','Select a file:',...
%                     'SelectionMode','single',...
%                     'ListString',str)
 %
%  See also DIALOG, ERRORDLG, HELPDLG, INPUTDLG,
%    MSGBOX, QUESTDLG, WARNDLG.

%   Copyright 1984-2014 The MathWorks, Inc.

%   'uh'            uicontrol button height, in pixels; default = 22.
%   'fus'           frame/uicontrol spacing, in pixels; default = 8.
%   'ffs'           frame/figure spacing, in pixels; default = 8.

% simple test:
%
% d = dir; [s,v] = listdlg('PromptString','Select a file:','ListString',{d.name});
%

% Generate a warning in -nodisplay and -noFigureWindows mode.
% warnfiguredialog('listdlgARH');

narginchk(1,inf)

figname = '';
smode = 2;   % (multiple)
promptstring = {};
liststring = [];
listsize = [160 300];
initialvalue = [];
okstring = getString(message('MATLAB:uistring:popupdialogs:OK'));
cancelstring = getString(message('MATLAB:uistring:popupdialogs:Cancel'));
fus = 8;
ffs = 8;
uh = 22;

if mod(length(varargin),2) ~= 0
    % input args have not com in pairs, woe is me
    error(message('MATLAB:listdlg:InvalidArgument'))
end
for i=1:2:length(varargin)
    switch lower(varargin{i})
     case 'name'
      figname = varargin{i+1};
     case 'promptstring'
      promptstring = varargin{i+1};
     case 'selectionmode'
      switch lower(varargin{i+1})
       case 'single'
        smode = 1;
       case 'multiple'
        smode = 2;
      end
     case 'listsize'
      listsize = varargin{i+1};
     case 'liststring'
      liststring = varargin{i+1};
     case 'initialvalue'
      initialvalue = varargin{i+1};
     case 'uh'
      uh = varargin{i+1};
     case 'fus'
      fus = varargin{i+1};
     case 'ffs'
      ffs = varargin{i+1};
     case 'okstring'
      okstring = varargin{i+1};
     case 'cancelstring'
      cancelstring = varargin{i+1};
     otherwise
      error(message('MATLAB:listdlg:UnknownParameter', varargin{ i }))
    end
end

if ischar(promptstring)
    promptstring = cellstr(promptstring);
end

if isempty(initialvalue) && smode==1
    initialvalue = 1;
end

if isempty(liststring)
    error(message('MATLAB:listdlg:NeedParameter'))
end

ex = get(0,'DefaultUicontrolFontSize')*1.7;  % height extent per line of uicontrol text (approx)

fp = get(0,'DefaultFigurePosition');
w = 2*(fus+ffs)+listsize(1);
h = 2*ffs+6*fus+ex*length(promptstring)+listsize(2)+uh+(smode==2)*(fus+uh);
fp = [fp(1) fp(2)+fp(4)-h w h];  % keep upper left corner fixed

fig_props = { ...
    'windowstyle'            'modal' ...
    'name'                   figname ...
    'color'                  get(0,'DefaultUicontrolBackgroundColor') ...
    'resize'                 'off' ...
    'numbertitle'            'off' ...
    'menubar'                'none' ...
    'visible'                'off' ...
    'createfcn'              ''    ...
    'position'               fp   ...
    'closerequestfcn'        'delete(gcbf)' ...
            };

liststring=cellstr(liststring);

fig = figure(fig_props{:});

if ~isempty(promptstring)
    prompt_text = uicontrol('Style','text','String',promptstring,...
        'HorizontalAlignment','left',...
        'Position',[ffs+fus fp(4)-(ffs+fus+ex*length(promptstring)) ...
        listsize(1) ex*length(promptstring)]); %#ok
end

btn_wid = (fp(3)-2*(ffs+fus)-fus)/2;

listbox = uicontrol('Style','listbox',...
                    'Position',[ffs+fus ffs+uh+4*fus+(smode==2)*(fus+uh) listsize],...
                    'String',liststring,...
                    'BackgroundColor','w',...
                    'Max',smode,...
                    'Tag','listbox',...
                    'Value',initialvalue, ...
                    'Callback', {@doListboxClick});

ok_btn = uicontrol('Style','pushbutton',...
                   'String',okstring,...
                   'Position',[ffs+fus ffs+fus btn_wid uh],...
                   'Tag','ok_btn',...
                   'Callback',{@doOK,listbox});

cancel_btn = uicontrol('Style','pushbutton',...
                       'String',cancelstring,...
                       'Position',[ffs+2*fus+btn_wid ffs+fus btn_wid uh],...
                       'Tag','cancel_btn',...
                       'Callback',{@doCancel,listbox});

if smode == 2
    selectall_btn = uicontrol('Style','pushbutton',...
                              'String',getString(message('MATLAB:uistring:popupdialogs:SelectAll')),...
                              'Position',[ffs+fus 4*fus+ffs+uh listsize(1) uh],...
                              'Tag','selectall_btn',...
                              'Callback',{@doSelectAll, listbox});

    if length(initialvalue) == length(liststring)
        set(selectall_btn,'Enable','off')
    end
    set(listbox,'Callback',{@doListboxClick, selectall_btn})
end

set([fig, ok_btn, cancel_btn, listbox], 'KeyPressFcn', {@doKeypress, listbox});

set(fig,'Position',getnicedialoglocationARH(fp, get(fig,'Units')));
% Make ok_btn the default button.
setdefaultbuttonARH(fig, ok_btn);

% make sure we are on screen
movegui(fig)
set(fig, 'Visible','on'); drawnow;

try
    % Give default focus to the listbox *after* the figure is made visible
    uicontrol(listbox);
    c = matlab.ui.internal.dialog.DialogUtils.disableAllWindowsSafely(true);
    uiwait(fig);
    delete(c);
catch
    if ishghandle(fig)
        delete(fig)
    end
end

if isappdata(0,'ListDialogAppData__')
    ad = getappdata(0,'ListDialogAppData__');
    selection = ad.selection;
    value = ad.value;
    rmappdata(0,'ListDialogAppData__')
else
    % figure was deleted
    selection = [];
    value = 0;
end
drawnow; % Update the view to remove the closed figure (g1031998)

%% figure, OK and Cancel KeyPressFcn
function doKeypress(src, evd, listbox) %#ok
switch evd.Key
 case 'escape'
  doCancel([],[],listbox);
end

%% OK callback
function doOK(ok_btn, evd, listbox) %#ok
if (~isappdata(0, 'ListDialogAppData__'))
    ad.value = 1;
    ad.selection = get(listbox,'Value');
    setappdata(0,'ListDialogAppData__',ad);
    delete(gcbf);
end

%% Cancel callback
function doCancel(cancel_btn, evd, listbox) %#ok
ad.value = 0;
ad.selection = [];
setappdata(0,'ListDialogAppData__',ad)
delete(gcbf);

%% SelectAll callback
function doSelectAll(selectall_btn, evd, listbox) %#ok
set(selectall_btn,'Enable','off')
set(listbox,'Value',1:length(get(listbox,'String')));

%% Listbox callback
function doListboxClick(listbox, evd, selectall_btn) %#ok
% if this is a doubleclick, doOK
if strcmp(get(gcbf,'SelectionType'),'open')
    doOK([],[],listbox);
elseif nargin == 3
    if length(get(listbox,'String'))==length(get(listbox,'Value'))
        set(selectall_btn,'Enable','off')
    else
        set(selectall_btn,'Enable','on')
    end
end


function disp(x)
%DISP         Display function for pop-up windows in debugger
%
%Displays x without header
%

% written  04/26/13     S.M. Rump
%

  display(x,[],1);


function [selection,value] = listdlg(varargin)
%LISTDLG  List selection dialog box.
%   [SELECTION,OK] = LISTDLG('ListString',S) creates a modal dialog box
%   which allows you to select a string or multiple strings from a list.
%   SELECTION is a vector of indices of the selected strings (length 1 in
%   the single selection mode).  This will be [] when OK is 0.  OK is 1 if
%   you push the OK button, or 0 if you push the Cancel button or close the
%   figure.
%
%   Double-clicking on an item or pressing <CR> when multiple items are
%   selected has the same effect as clicking the OK button.  Pressing <CR>
%   is the same as clicking the OK button. Pressing <ESC> is the same as
%   clicking the Cancel button.
%
%   Inputs are in parameter,value pairs:
%
%   Parameter       Description
%   'ListString'    cell array of strings for the list box.
%   'SelectionMode' string; can be 'single' or 'multiple'; defaults to
%                   'multiple'.
%   'ListSize'      minimum [width height] of listbox in pixels; defaults
%                   to [160 300]. The maximum [width height] is fixed to
%                   [800 600].
%   'InitialValue'  vector of indices of which items of the list box
%                   are initially selected; defaults to the first item.
%   'Name'          String for the figure's title; defaults to ''.
%   'PromptString'  string matrix or cell array of strings which appears
%                   as text above the list box; defaults to {}.
%   'OKString'      string for the OK button; defaults to 'OK'.
%   'CancelString'  string for the Cancel button; defaults to 'Cancel'.
%
%   A 'Select all' button is provided in the multiple selection case.
%
%   Example:
%     d = dir;
%     str = {d.name};
%     [s,v] = listdlg('PromptString','Select a file:',...
%                     'SelectionMode','single',...
%                     'ListString',str)
 %
%  See also DIALOG, ERRORDLG, HELPDLG, INPUTDLG,
%    MSGBOX, QUESTDLG, WARNDLG.

%   Copyright 1984-2005 The MathWorks, Inc.
%   $Revision: 6641 $  $Date: 2005/10/28 15:54:55 $

%   'uh'            uicontrol button height, in pixels; default = 22.
%   'fus'           frame/uicontrol spacing, in pixels; default = 8.
%   'ffs'           frame/figure spacing, in pixels; default = 8.

% simple test:
%
% d = dir; [s,v] = listdlg('PromptString','Select a file:','ListString',{d.name});
%

figname = '';
smode = 2;   % (multiple)
promptstring = {};
liststring = [];
listsize = [160 300];
initialvalue = [];
okstring = 'OK';
cancelstring = 'Cancel';
fus = 8;
ffs = 8;
uh = 22;

if mod(length(varargin),2) ~= 0
    % input args have not com in pairs, woe is me
    cfg_message('MATLAB:listdlg:InvalidArgument', 'Arguments to LISTDLG must come param/value in pairs.')
end
for i=1:2:length(varargin)
    switch lower(varargin{i})
     case 'name'
      figname = varargin{i+1};
     case 'promptstring'
      promptstring = varargin{i+1};
     case 'selectionmode'
      switch lower(varargin{i+1})
       case 'single'
        smode = 1;
       case 'multiple'
        smode = 2;
      end
     case 'listsize'
      listsize = varargin{i+1};
     case 'liststring'
      liststring = varargin{i+1};
     case 'initialvalue'
      initialvalue = varargin{i+1};
     case 'uh'
      uh = varargin{i+1};
     case 'fus'
      fus = varargin{i+1};
     case 'ffs'
      ffs = varargin{i+1};
     case 'okstring'
      okstring = varargin{i+1};
     case 'cancelstring'
      cancelstring = varargin{i+1};
     otherwise
      cfg_message('MATLAB:listdlg:UnknownParameter', ['Unknown parameter name passed to LISTDLG.  Name was ' varargin{i}])
    end
end

if ischar(promptstring)
    promptstring = cellstr(promptstring);
end

if isempty(initialvalue)
    initialvalue = 1;
end

if isempty(liststring)
    cfg_message('MATLAB:listdlg:NeedParameter', 'ListString parameter is required.')
end

liststring=cellstr(liststring);
lfont = cfg_get_defaults('cfg_ui.lfont');
bfont = cfg_get_defaults('cfg_ui.bfont');
tmpObj = uicontrol('style','listbox',...
    'max',100,...
    'Visible','off',...
    lfont{:});
lext = cfg_maxextent(tmpObj, liststring);
ex = get(tmpObj,'Extent');
ex = ex(4);
delete(tmpObj);
listsize = min([800 600],max(listsize, [max(lext)+16, ex*numel(liststring)]));

fp = get(0,'defaultfigureposition');
w = 2*(fus+ffs)+listsize(1);
h = 2*ffs+6*fus+ex*length(promptstring)+listsize(2)+uh+(smode==2)*(fus+uh);
fp = [fp(1) fp(2)+fp(4)-h w h];  % keep upper left corner fixed

fig_props = { ...
    'name'                   figname ...
    'color'                  get(0,'defaultUicontrolBackgroundColor') ...
    'resize'                 'off' ...
    'numbertitle'            'off' ...
    'menubar'                'none' ...
    'windowstyle'            'modal' ...
    'visible'                'off' ...
    'createfcn'              ''    ...
    'position'               fp   ...
    'closerequestfcn'        'delete(gcbf)' ...
            };

fig = figure(fig_props{:});

if ~isempty(promptstring)
    prompt_text = uicontrol('style','text','string',promptstring,...
        'horizontalalignment','left',...
        'position',[ffs+fus fp(4)-(ffs+fus+ex*length(promptstring)) ...
        listsize(1) ex*length(promptstring)]); %#ok
end

btn_wid = (fp(3)-2*(ffs+fus)-fus)/2;

listbox = uicontrol('style','listbox',...
                    'position',[ffs+fus ffs+uh+4*fus+(smode==2)*(fus+uh) listsize],...
                    'string',liststring,...
                    'backgroundcolor','w',...
                    'max',smode,...
                    'tag','listbox',...
                    'value',initialvalue, ...
                    'callback', {@doListboxClick}, ...
                    lfont{:});

ok_btn = uicontrol('style','pushbutton',...
                   'string',okstring,...
                   'position',[ffs+fus ffs+fus btn_wid uh],...
                   'callback',{@doOK,listbox},...
                   bfont{:});

cancel_btn = uicontrol('style','pushbutton',...
                       'string',cancelstring,...
                       'position',[ffs+2*fus+btn_wid ffs+fus btn_wid uh],...
                       'callback',{@doCancel,listbox},...
                       bfont{:});

if smode == 2
    selectall_btn = uicontrol('style','pushbutton',...
                              'string','Select all',...
                              'position',[ffs+fus 4*fus+ffs+uh listsize(1) uh],...
                              'tag','selectall_btn',...
                              'callback',{@doSelectAll, listbox});

    if length(initialvalue) == length(liststring)
        set(selectall_btn,'enable','off')
    end
    set(listbox,'callback',{@doListboxClick, selectall_btn})
end

set([fig, ok_btn, cancel_btn, listbox], 'keypressfcn', {@doKeypress, listbox});

set(fig,'position',getnicedialoglocation(fp, get(fig,'Units')));
% Make ok_btn the default button.
setdefaultbutton(fig, ok_btn);

% make sure we are on screen
movegui(fig)
set(fig, 'visible','on'); drawnow;

try
    % Give default focus to the listbox *after* the figure is made visible
    uicontrol(listbox);
    uiwait(fig);
catch
    if ishandle(fig)
        delete(fig)
    end
end

if isappdata(0,'ListDialogAppData__')
    ad = getappdata(0,'ListDialogAppData__');
    selection = ad.selection;
    value = ad.value;
    rmappdata(0,'ListDialogAppData__')
else
    % figure was deleted
    selection = [];
    value = 0;
end

%% figure, OK and Cancel KeyPressFcn
function doKeypress(src, evd, listbox) %#ok
switch evd.Key
 case 'escape'
  doCancel([],[],listbox);
end

%% OK callback
function doOK(ok_btn, evd, listbox) %#ok
if (~isappdata(0, 'ListDialogAppData__'))
    ad.value = 1;
    ad.selection = get(listbox,'value');
    setappdata(0,'ListDialogAppData__',ad);
    delete(gcbf);
end

%% Cancel callback
function doCancel(cancel_btn, evd, listbox) %#ok
ad.value = 0;
ad.selection = [];
setappdata(0,'ListDialogAppData__',ad)
delete(gcbf);

%% SelectAll callback
function doSelectAll(selectall_btn, evd, listbox) %#ok
set(selectall_btn,'enable','off')
set(listbox,'value',1:length(get(listbox,'string')));

%% Listbox callback
function doListboxClick(listbox, evd, selectall_btn) %#ok
% if this is a doubleclick, doOK
if strcmp(get(gcbf,'SelectionType'),'open')
    doOK([],[],listbox);
elseif nargin == 3
    if length(get(listbox,'string'))==length(get(listbox,'value'))
        set(selectall_btn,'enable','off')
    else
        set(selectall_btn,'enable','on')
    end
end


function S = edl_readprops(filename, nodetag)
%EDL_READPROPS Reads properties from a property table XML file
%
% $ Syntax $
%   - S = edl_readprops(filename, nodetag)
%
% $ Arguments $
%   - filename:     the filename of the XML file describing the properties
%   - nodetag:      the tag name of each child node of the document node
%   - S:            the struct array of read document
%                   - 'tag':  the document node tag
%                   - 'attribs': the document node attributes
%                   - the struct array using nodetag as fieldname
%
% $ Description $
%   - S = edl_readprops(filename, nodetag) reads a table of properties from
%     a property table XML file.
%
% $ History $
%   - Created by Dahua Lin, on Aug 10th, 2006
%   - Modified by Dahua Lin, on Aug 13rd, 2006
%       - adds support of document header attribute
%       - changes the structure of the result
%       - adds the selection of node tag
%

%% Read file

if nargin < 2
    raise_lackinput('edl_readprops', 2);
end

xdoc = xmlread(filename);
docelem = xdoc.getDocumentElement;

%% Read header

S.tag = char(docelem.getTagName);
S.attribs = xml_getattribs(docelem);

%% Read properties

propElemList = docelem.getElementsByTagName(nodetag);
n = propElemList.getLength;

if n > 0
    % pre-allocation
    % (this can remarkably accelerates the construction of large struct array)
    attrMap = propElemList.item(0).getAttributes;
    firstattr = attrMap.item(0);
    firstname = char(firstattr.getName);
    entries = struct(firstname, cell(n, 1));

    for i = 1 : n

        curentry = propElemList.item(i-1);
        attrMap = curentry.getAttributes;
        na = attrMap.getLength;

        for j = 1 : na
            attr = attrMap.item(j-1);
            attrname = char(attr.getName);
            attrval = char(attr.getValue);
            entries(i).(attrname) = attrval;
        end

    end
else
    entries = [];
end

S.(nodetag) = entries;


classdef MimZeroIsTransparent < MimGuiPlugin
    % MimZeroIsTransparent. Gui Plugin for switching transparency of zero
    %
    %     You should not use this class within your own code. It is intended to
    %     be used by the gui of the TD MIM Toolkit.
    %
    %     MimZeroIsTransparent is a Gui Plugin for the MIM Toolkit.
    %
    %
    %     Licence
    %     -------
    %     Part of the TD MIM Toolkit. https://github.com/tomdoel
    %     Author: Tom Doel, Copyright Tom Doel 2014.  www.tomdoel.com
    %     Distributed under the MIT licence. Please see website for details.
    %

    properties
        ButtonText = 'Show zero transparent'
        SelectedText = 'Show zero as black'
        ToolTip = 'Changes whether zero values in the overlay are shown as black or transparent'
        Category = 'Segmentation display'
        Visibility = 'Dataset'
        Mode = 'Segment'

        HidePluginInDisplay = false
        PTKVersion = '1'
        ButtonWidth = 6
        ButtonHeight = 1
        Icon = 'show_black.png'
        Location = 24
    end

    methods (Static)
        function RunGuiPlugin(gui_app)
            gui_app.ImagePanel.BlackIsTransparent = ~gui_app.ImagePanel.BlackIsTransparent;
        end

        function enabled = IsEnabled(gui_app)
            enabled = gui_app.IsDatasetLoaded && gui_app.ImagePanel.OverlayImage.ImageExists && ~strcmp(gui_app.ImagePanel.Mode, MimModes.View3DMode) && gui_app.ImagePanel.ShowOverlay;
        end

        function is_selected = IsSelected(gui_app)
            is_selected = gui_app.ImagePanel.BlackIsTransparent;
        end
    end
end


% eeg_options() - eeglab option script
%
% Note: DO NOT EDIT, instead use pop_editoptions() or the menu
%       /File/Maximize memory in EEGLAB gui

% STUDY and file options (set these checkboxes if you intend to work with studies)
option_storedisk = 0 ; % If set, keep at most one dataset in memory. This allows processing hundreds of datasets within studies.
option_savetwofiles = 1 ; % If set, save not one but two files for each dataset (header and data). This allows faster data loading in studies.
option_saveversion6 = 1 ; % If set, write Matlab files in Matlab v6.5 (max compatibility). If not, write files in Matlab v7.3 (larger than 2Gb).
% Memory options
option_single = 0 ; % If set, use single precision under Matlab 7.x. This saves RAM but can lead to rare numerical imprecisions.
option_memmapdata = 0 ; % If set, use memory mapped array under Matlab 7.x. This may slow down some computation (beta).
option_eegobject = 0 ; % If set, use the EEGLAB EEG object instead of the standard EEG structure (beta).
% ICA options
option_computeica = 0 ; % If set, precompute ICA activations. This requires more RAM but allows faster plotting of component activations.
option_scaleicarms = 1 ; % If set, scale ICA component activities to RMS (Root Mean Square) in microvolt (recommended).
% Folder options
option_rememberfolder = 1 ; % If set, when browsing to open a new dataset assume the folder/directory of previous dataset.

% Toolbox options
option_donotusetoolboxes = 0 ; % If set, do not use Matlab additional toolboxes functions even if they are present (need to restart EEGLAB).
% EEGLAB connectivity and support
option_checkversion = 1 ; % If set, check for new version of EEGLAB at startup.
option_chat = 0 ; % If set, enable EEGLAB chat - currently UCSD only - restart EEGLAB after changing that option.


function imname = imNumToName(im, ext)
	imname = arrayfun(@(x) sprintf('img_%04d',x), im, 'UniformOutput', false);
	if(exist('ext', 'var'))
		imname = strcat(imname, '.', ext);
	end
	if(length(im) == 1)
		imname = imname{1};
	end
end


function  readframe = klb_get_readframe_fcn(filename,varargin)

[dim,numThreads] = myparse(varargin,'dim',3,'numThreads',[]);
readframe = @(f) klbreadframe(f);

  function im = klbreadframe(f)
    im = readKLBslice(filename,f,dim,numThreads);
  end
end


function datatype = fmf_get_datatype( data_format )

if strcmp(data_format,'MONO8'),
  datatype = 'uint8';
else,
  if strcmp(data_format,'YUV422'),
    datatype = 'uint16';
  else,
    error( 'Only MONO8 supported for now' );
  end
end


function [template] = tapas_load_template(fname)
%% Loads a file that work as a template for filling.
%
% Input
%   fname       -- File name.
%
% Output
%   string      -- An array containing the string.
%

% aponteeduardo@gmail.com
% copyright (C) 2017
%

fid = fopen(fname);
try
    template = {};
    while feof(fid) == 0
       template{end + 1} = fgets(fid);
    end
catch err
    % Make sure that the file is closed properly.
    try
        fclose(fid);
    end
    rethrow(err);
end
fclose(fid);
template = [template{:}];

end


plotset.pfrequ.binArray   = binArray;
plotset.pfrequ.plotallbin = plotallbin;
plotset.pfrequ.chanArray  = chanArray;
plotset.pfrequ.plotallch  = plotallch;
plotset.pfrequ.chanArray_MGFP = chanArray_MGFP;
plotset.pfrequ.blcorr     = blcorr;
plotset.pfrequ.xscale     = xxscale;
plotset.pfrequ.yscale     = yyscale;
plotset.pfrequ.linewidth  = linewidth;
plotset.pfrequ.isiy       = isiy;
plotset.pfrequ.fschan     = fschan;
plotset.pfrequ.fslege     = fslege;
plotset.pfrequ.fsaxtick   = fsaxtick;
%plotset.pfrequ.meap       = meap;
plotset.pfrequ.pstyle     = pstyle;
plotset.pfrequ.errorstd   = errorstd;
plotset.pfrequ.stdalpha   = stdalpha;
plotset.pfrequ.pbox       = pbox;
plotset.pfrequ.counterwin = counterwin;
plotset.pfrequ.holdch     = holdch;
plotset.pfrequ.yauto      = yauto;
plotset.pfrequ.yautoticks = yautoticks;
plotset.pfrequ.xautoticks = xautoticks;
plotset.pfrequ.binleg     = binleg;
plotset.pfrequ.chanleg    = chanleg;
plotset.pfrequ.isMGFP     = isMGFP;
plotset.pfrequ.ismaxim    = ismaxim;
%plotset.pfrequ.istopo     = istopo;
plotset.pfrequ.axsize     = axsize;
plotset.pfrequ.minorticks = minorticks;
plotset.pfrequ.linespec   = linespeci;
plotset.pfrequ.legepos    = legepos;
plotset.pfrequ.posgui     = posgui;
if ~isfield(plotset.pfrequ, 'posminigui')
        plotset.pfrequ.posminigui = [];
end
plotset.pfrequ.posfig     = posfig;

% adjusting
plotset.pfrequ.binArray   = plotset.pfrequ.binArray(plotset.pfrequ.binArray<=ERP.nbin);
plotset.pfrequ.chanArray  = plotset.pfrequ.chanArray(plotset.pfrequ.chanArray<=ERP.nchan);
plotset.pfrequ.chanArray_MGFP = plotset.pfrequ.chanArray_MGFP(plotset.pfrequ.chanArray_MGFP<=ERP.nchan);

plotset.pfrequ.ibckground  = ibckground;

% if plotset.pfrequ.xscale(1) < ERP.xmin*1000
%       plotset.pfrequ.xscale(1) = ceil(ERP.xmin*1000);
% end
% if plotset.pfrequ.xscale(2) > ERP.xmax*1000
%       plotset.pfrequ.xscale(2) = floor(ERP.xmax*1000);
% end


function hdr = empty_hdr
% Create an empty NIFTI-1 header
% FORMAT hdr = empty_hdr
% _______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging

%
% $Id$

org = niftistruc;
for i=1:length(org),
    hdr.(org(i).label) = org(i).def;
end;