function varargout = plotstyle(varargin)
% VL_PLOTSTYLES  Get a plot style
%   STYLES = VL_PLOTSTYLE(INDEX) returns a cell array of PLOT() options
%   for the color/line style of index INDEX. The available styles are
%   defined the ColorOrder and LineStyleOrder properties of the
%   current axes and cycled first by color and then by line style.
%
%   If there is no current axes can be found, then VL_PLOTSTYLE() uses
%   the DefaultAxesColorOrder and DefaultLineStyleOrder root
%   properties.
%
%   If INDEXES has more than one element, then VL_PLOTSTYLE(INDEXES)
%   returns a cell array of styles of the same size of INDEXES.
%
%   Example::
%     The code fragment
%
%        set(gca,'LineStyleOrder', {'-','-.'}, 'NextPlot', 'replacechildren') ;
%        plot([1 2], [1:20 ; 1:20]') ;
%
%     and
%
%       set(gca,'NextPlot', 'replacechildren') ;
%       set(gca,'LineStyleOrder', {'-','-.'}) ;
%       for i = 1:20
%         style = vl_plotstyle(i) ;
%         plot([1 2], [i i], style{:}) ;
%         hold on ;
%       end
%
%     produce visually similar results.
%
%   See also: VL_HELP().
[varargout{1:nargout}] = vl_plotstyle(varargin{:});


function results = SOFAgetVersion(flag)
%SOFAgetVersion - Get the version of the SOFA Toolbox
%   Usage: ver = SOFAgetVersion(flag)
%
%   ver = SOFAgetVersion() returns the version of the SOFA Toolbox
%
%   ver = SOFAgetVersion('Toolbox') and SOFAgetVersion('API') do the same (not case-sensitive).
%
%   ver = SOFAgetVersion('SOFA') returns the version of the SOFA supported
%   by the SOFA Toolbox.

% #Author: Piotr Majdak
% #Author: Michael Mihocic: header documentation updated (28.10.2021)
%
% SOFA Toolbox - function SOFAgetVersion
% Copyright (C) Acoustics Research Institute - Austrian Academy of Sciences;
% Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European Commission - subsequent versions of the EUPL (the "License")
% You may not use this work except in compliance with the License.
% You may obtain a copy of the License at: https://joinup.ec.europa.eu/software/page/eupl
% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing  permissions and limitations under the License.

if ~exist('flag','var')
	flag='TOOLBOX';
end

switch upper(flag)
	case {'TOOLBOX','API'}
		results = '2.1.5';
	case 'SOFA'
		results = '2.1';
end


function val=jsonopt(key,default,varargin)
%
% val=jsonopt(key,default,optstruct)
%
% setting options based on a struct. The struct can be produced
% by varargin2struct from a list of 'param','value' pairs
%
% author: Qianqian Fang, <q.fang at neu.edu>
%
% $Id: loadjson.m 371 2012-06-20 12:43:06Z fangq $
%
% input:
%      key: a string with which one look up a value from a struct
%      default: if the key does not exist, return default
%      optstruct: a struct where each sub-field is a key
%
% output:
%      val: if key exists, val=optstruct.key; otherwise val=default
%
% license:
%     BSD or GPL version 3, see LICENSE_{BSD,GPLv3}.txt files for details
%
% -- this function is part of JSONlab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%

val=default;
if(nargin<=2) return; end
opt=varargin{1};
if(isstruct(opt))
    if(isfield(opt,key))
       val=getfield(opt,key);
    elseif(isfield(opt,lower(key)))
       val=getfield(opt,lower(key));
    end
end


function monom = recovermonoms(newton_m,x);

if isempty(newton_m)
    monom = 1;
else
    error('Report this bug (call to recovermonoms with double)');
end


function [s vw] = openVolumeWindow
%
% Calls openRawVolumeWindow to set up the VOLUME data structure,
% opens and initializes the volume window.  Then calls switch2Vol.
%
%   [s vw] = openVolumeWindow
%
% djh, 2/99
% Junjie 2004.02.14 let function return s

mrGlobals

s = openRawVolumeWindow;
VOLUME{s} = switch2Vol(VOLUME{s});

selectView(VOLUME{s});

% If user requested a view output, give it to them:
if nargout > 1,	vw = VOLUME{s}; end

return;


function obj = updateTernaryColorbar(obj,colorbarIndex)

% title: ...[DONE]
% titleside: ...[DONE]
% titlefont: ...[DONE]
% thickness: ...[DONE]
% thicknessmode: ...[DONE]
% len: ...[DONE]
% lenmode: ...[DONE]
% x: ...[DONE]
% y: ...[DONE]
% autotick: ...[DONE]
% nticks: ...[DONE]
% ticks: ...[DONE]
% showticklabels: ...[DONE]
% tick0: ...[DONE]
% dtick: ...[DONE]
% ticklen: ...[DONE]
% tickwidth: ...[DONE]
% tickcolor: ...[DONE]
% tickangle: ...[NOT SUPPORTED IN MATLAB]
% tickfont: ...[DONE]
% exponentformat: ...[DONE]
% showexponent: ...[NOT SUPPORTED IN MATLAB]
% xanchor: ...[DONE]
% yanchor: ...[DONE]
% bgcolor: ...[DONE]
% outlinecolor: ...[DONE]
% outlinewidth: ...[DONE]
% borderwidth: ...[NOT SUPPORTED IN MATLAB]
% bordercolor: ...[NOT SUPPORTED IN MATLAB]
% xpad: ...[DONE]
% ypad: ...[DONE]

%-FIGURE STRUCTURE-%
figureData = get(obj.State.Figure.Handle);

%-PLOT DATA STRUCTURE- %
try
    colorbarData = get(obj.State.Colorbar(colorbarIndex).Handle);
catch
    disp('could not extract ColorBar data');
end

%-STANDARDIZE UNITS-%
colorbarunits = colorbarData.Units;
set(obj.State.Colorbar(colorbarIndex).Handle,'Units','normalized');

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

%-colorbar position-%
colorbar.xanchor = 'left';
colorbar.yanchor = 'bottom';
colorbar.x = colorbarData.Position(1)*1.025;
colorbar.y = colorbarData.Position(2);

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

%-exponent format-%
colorbar.exponentformat = obj.PlotlyDefaults.ExponentFormat;

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

% get colorbar title and labels
colorbarTitle = colorbarData.Label;

if isHG2
    colorbarTitleData = get(colorbarTitle);
    colorbarYLabel = colorbarTitle;
    colorbarYLabelData = get(colorbarTitle);
    colorbarXLabelData.String = [];
else
    colorbarTitleData = get(colorbarTitle);
    colorbarXLabel = colorbarData.XLabel;
    colorbarXLabelData = get(colorbarXLabel);
    colorbarYLabel = colorbarData.YLabel;
    colorbarYLabelData = get(colorbarYLabel);
end

%-colorbar title-%
if ~isempty(colorbarTitleData.String)
    colorbar.title = parseString(colorbarTitleData.String,colorbarTitleData.Interpreter);

elseif ~isempty(colorbarXLabelData.String)
    colorbar.title = parseString(colorbarXLabelData.String,colorbarXLabelData.Interpreter);

elseif ~isempty(colorbarYLabelData.String)
    colorbar.title = parseString(colorbarYLabelData.String,colorbarYLabelData.Interpreter);
end

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

%-STANDARDIZE UNITS-%
titleUnits = colorbarTitleData.Units;
titleFontUnits = colorbarTitleData.FontUnits;
yLabelUnits = colorbarYLabelData.Units;
yLabelFontUnits = colorbarYLabelData.FontUnits;
set(colorbarTitle,'Units','data');
set(colorbarYLabel,'Units','data');
set(colorbarYLabel,'FontUnits','points');

if ~isHG2
    xLabelUnits = colorbarXLabelData.Units;
    xLabelFontUnits = colorbarXLabelData.FontUnits;
    set(colorbarTitle,'FontUnits','points');
    set(colorbarXLabel,'Units','data');
    set(colorbarXLabel,'FontUnits','points');
end

if ~isempty(colorbarTitleData.String)
    if colorbarTitleData.Rotation == 90
        colorbar.titleside = 'right';
    else
        colorbar.titleside = 'top';
    end

    colorbar.titlefont.family = matlab2plotlyfont(colorbarTitleData.FontName);
    col = 255*colorbarTitleData.Color;
    colorbar.titlefont.color = sprintf('rgb(%f,%f,%f)', col);
    colorbar.titlefont.size = 1.20 * colorbarTitleData.FontSize;

elseif ~isempty(colorbarXLabelData.String)
    colorbar.titleside = 'right';
    colorbar.titlefont.family = matlab2plotlyfont(colorbarXLabelData.FontName);
    col = 255*colorbarXLabelData.Color;
    colorbar.titlefont.color = sprintf('rgb(%f,%f,%f)', col);
    colorbar.titlefont.size = 1.20 * colorbarXLabelData.FontSize;

elseif ~isempty(colorbarYLabelData.String)
    colorbar.titleside = 'bottom';
    colorbar.titlefont.family = matlab2plotlyfont(colorbarYLabelData.FontName);
    col = 255*colorbarYLabelData.Color;
    colorbar.titlefont.color = sprintf('rgb(%f,%f,%f)', col);
    colorbar.titlefont.size = 1.20 * colorbarYLabelData.FontSize;
end

%-REVERT UNITS-%
set(colorbarTitle,'Units',titleUnits);
set(colorbarTitle,'FontUnits',titleFontUnits);
set(colorbarYLabel,'Units',yLabelUnits);
set(colorbarYLabel,'FontUnits',yLabelFontUnits);

if ~isHG2
    set(colorbarXLabel,'Units',xLabelUnits);
    set(colorbarXLabel,'FontUnits',xLabelFontUnits);
end

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

%-some colorbar settings-%

lineWidth = colorbarData.LineWidth*obj.PlotlyDefaults.AxisLineIncreaseFactor;
tickLength = min(obj.PlotlyDefaults.MaxTickLength,...
    max(colorbarData.TickLength(1)*colorbarData.Position(3)*obj.layout.width,...
    colorbarData.TickLength(1)*colorbarData.Position(4)*obj.layout.height));

colorbar.thicknessmode = 'fraction';
colorbar.thickness = colorbarData.Position(3);
colorbar.tickwidth = lineWidth;
colorbar.ticklen = tickLength;

colorbar.lenmode = 'fraction';
colorbar.len = colorbarData.Position(4)*1.025;
colorbar.outlinewidth = lineWidth;

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

% orientation vertical check
orientVert = colorbar.len > colorbar.thickness;

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

%-coloration-%

if isHG2
    col = 255*colorbarData.Color;
else
    if orientVert
        col = 255*colorbarData.YColor;
    else
        col = 255*colorbarData.XColor;
    end
end

colorbarColor = sprintf('rgb(%f,%f,%f)', col);

colorbar.outlinecolor = colorbarColor;
colorbar.tickcolor = colorbarColor;
colorbar.tickfont.color = colorbarColor;

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

%-axis tickfont-%
colorbar.tickfont.size = colorbarData.FontSize;
colorbar.tickfont.family = matlab2plotlyfont(colorbarData.FontName);

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

%-colorbar pad-%
colorbar.xpad = obj.PlotlyDefaults.MarginPad;
colorbar.ypad = obj.PlotlyDefaults.MarginPad;

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

%-set ticklabels-%
nticks = length(colorbarData.Ticks);

if isHG2
    if isempty(colorbarData.Ticks)
        %-hide tick labels-%
        colorbar.ticks = '';
        colorbar.showticklabels = false;

    else

        %-tick direction-%
        switch colorbarData.TickDirection
            case 'in'
                colorbar.ticks = 'inside';
            case 'out'
                colorbar.ticks = 'outside';
        end

        if strcmp(colorbarData.TickLabelsMode,'auto')
            colorbar.autotick = true;
            colorbar.nticks = length(colorbarData.Ticks) + 1; %nticks = max ticks (so + 1)

        else

            %-show tick labels-%
            if isempty(colorbarData.TickLabels)
                colorbar.showticklabels = false;

            else
                colorbar.autotick = false;
                colorbar.tickvals = colorbarData.Ticks;
                colorbar.ticktext = colorbarData.TickLabels;
            end
        end
    end

else
    if orientVert
        if isempty(colorbarData.YTick)
            %-show tick labels-%
            colorbar.ticks = '';
            colorbar.showticklabels = false;
        else
            %-tick direction-%
            switch colorbarData.TickDir
                case 'in'
                    colorbar.ticks = 'inside';
                case 'out'
                    colorbar.ticks = 'outside';
            end

            if strcmp(colorbarData.YTickLabelMode,'auto')
                %-autotick-%
                colorbar.autotick = true;
                %-numticks-%
                colorbar.nticks = length(colorbarData.YTick) + 1; %nticks = max ticks (so + 1)
            else
                %-show tick labels-%
                if isempty(colorbarData.YTickLabel)
                    colorbar.showticklabels = false;
                else
                    %-autotick-%
                    colorbar.autotick = false;
                    %-tick0-%
                    colorbar.tick0 = str2double(colorbarData.YTickLabel(1,:));
                    %-dtick-%
                    colorbar.dtick = str2double(colorbarData.YTickLabel(2,:)) - str2double(colorbarData.YTickLabel(1,:));
                end
            end
        end
    else
        if isempty(colorbarData.XTick)
            %-show tick labels-%
            colorbar.ticks = '';
            colorbar.showticklabels = false;
        else
            %-tick direction-%
            switch colorbarData.TickDir
                case 'in'
                    colorbar.ticks = 'inside';
                case 'out'
                    colorbar.ticks = 'outside';
            end

            if strcmp(colorbarData.XTickLabelMode,'auto')
                %-autotick-%
                colorbar.autotick = true;
                %-numticks-%
                colorbar.nticks = length(colorbarData.XTick) + 1;
            else
                %-show tick labels-%
                if isempty(colorbarData.XTickLabel)
                    colorbar.showticklabels = false;
                else
                    %-autotick-%
                    colorbar.autotick = false;
                    %-tick0-%
                    colorbar.tick0 = str2double(colorbarData.XTickLabel(1,:));
                    %-dtick-%
                    colorbar.dtick = str2double(colorbarData.XTickLabel(2,:)) - str2double(colorbarData.XTickLabel(1,:));
                end
            end
        end
    end
end

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

%-colorbar bg-color-%
if ~isHG2

    if ~ischar(colorbarData.Color)
        col = 255*colorbarData.Color;
    else
        col = 255*figureData.Color;
    end

    obj.layout.plot_bgcolor = sprintf('rgb(%f,%f,%f)', col);
end

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

%-ASSOCIATED DATA-%
if isfield(colorbarData.UserData,'dataref')
    colorbarDataIndex = colorbarData.UserData.dataref;
else
    colorbarDataIndex = findColorbarData(obj,colorbarIndex);
end

if (nticks ~= 0)
    colorIndex = linspace(0, 1, nticks);
    colorData = linspace(0, 1, nticks-1);
    m = 1;

    for n = 1:nticks-1
        col = 1-colorData(n);
        colorscale{m} = {colorIndex(n), sprintf('rgb(%f,%f,%f)', 255*[col, col, col])};
        colorscale{m+1} = {colorIndex(n+1), sprintf('rgb(%f,%f,%f)', 255*[col, col, col])};
        m = 2*n+1;
    end
    obj.data{colorbarDataIndex}.marker.color = colorbarData.Ticks;
else
    colorscale = {{0, 'rgb(255,255,255)'}, {1, 'rgb(0,0,0)'}}
end

obj.data{colorbarDataIndex}.marker.colorscale = colorscale;
obj.data{colorbarDataIndex}.marker.colorbar = colorbar;
obj.data{colorbarDataIndex}.showscale = true;

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

%-REVERT UNITS-%
set(obj.State.Colorbar(colorbarIndex).Handle,'Units',colorbarunits);

end


% make. Make an Ot.dll

% OtMatlab: Matlab interface to the Omnitrans transport planning software

% Copyright (c) 2008, VORtech Computing
% Copyright (c) 2010, Omnitrans International

% All rights reserved.

% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are
% met:

%     * Redistributions of source code must retain the above copyright
%       notice, this list of conditions and the following disclaimer.
%     * Redistributions in binary form must reproduce the above copyright
%       notice, this list of conditions and the following disclaimer in
%       the documentation and/or other materials provided with the distribution
%     * Neither the name of VORtech Computing and Omnitrans International nor the names
%       of its contributors may be used to endorse or promote products derived
%       from this software without specific prior written permission.

% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
% POSSIBILITY OF SUCH DAMAGE.

% 2008-03-18 Created (Johan Meijdam, VORtech)

function make()
   % Omnitrans include path:
   incpath = '"C:\Program Files\Omnitrans International\OmniTRANS 5.1.5\ToolKit"';

   % Debug:
   % eval(['mex -argcheck -g -compatibleArrayDims -output Ot.dll -I' incpath ' Ot.cpp']);
   % Release:
   eval(['mex -O -compatibleArrayDims -output Ot.dll -I' incpath ' Ot.cpp']);

end


function varargout = ParseArgs(Args, varargin)

% Check input arguments
assert(nargin >= 2, ...
    'Function takes at least two arguments.');
assert(nargout == nargin-1, ...
    'Number of output arguments must be equal with the number of input arguments minus 1.');
assert(iscell(Args) && (isempty(Args) || isvector(Args)), ...
    'Args must be a cell vector.');
for i = 1:length(varargin)
    assert(iscellstr(varargin{i}) && isvector(varargin{i}), ...
        'All input arguments except the first one must be cell vectors of strings.');
end

% Convert Args to structure
if numel(Args) == 1
    if isstruct(Args{1})
        ArgStruct = Args{1};
    else
        error('If Args has only one element, that element must be a structure.');
    end
else
    ArgStruct = NameValue2Struct(Args{:});
end

% Make a cell array with all names in varargin
NumNames = sum(cellfun(@length,varargin));
AllNames = cell([1 NumNames]);
k = 0;
for i = 1:length(varargin)
    for j = 1:length(varargin{i})
        k = k + 1;
        AllNames{k} = varargin{i}{j};
    end
end
assert(k == NumNames);

% Check if Args contains only arguments with names that are not among those in varargin
ArgNames = fieldnames(ArgStruct);
for i = 1:length(ArgNames)
    if ~any(strcmp(ArgNames{i},AllNames))
        error('Unknown parameter: ''%s''',ArgNames{i});
    end
end

% Create output structures
for i = 1:nargout
    ParamStruct = struct();
    for j = 1:length(varargin{i})
        ParamName = varargin{i}{j};
        if isfield(ArgStruct,ParamName)
            ParamStruct.(ParamName) = ArgStruct.(ParamName);
        else
            ParamStruct.(ParamName) = [];
        end
    end
    varargout{i} = ParamStruct;
end

    function Struct = NameValue2Struct(varargin)
        for n = 2:2:nargin
            if iscell(varargin{n})
                % Put cell arrays in another cell array so that we don't get a
                % structure vector after the conversion
                varargin{n} = {varargin{n}};
            end
        end
        Struct = struct(varargin{:});
    end

end


function [tests,pass,perf]=test_wfdbdemo(varargin)

inputs={'verbose'};
verbose=0;
for n=1:nargin
    if(~isempty(varargin{n}))
        eval([inputs{n} '=varargin{n};']);
    end
end
%Test the examples
test_string={'wfdbdemo;close all;'};

[tests,pass,perf]=test_wrapper(test_string,[],verbose);


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

    enumeration
        FixedBounds('Fixed Bounds')
        StateComparison('State Comparison');
    end

    properties
        name char = '';
    end

    methods
        function obj = ConstraintEvalTypeEnum(name)
            obj.name = name;
        end
    end

    methods(Static)
        function [listBoxStr, enums] = getListBoxStr()
            m = enumeration('ConstraintEvalTypeEnum');
            [~,I] = sort({m.name});
            listBoxStr = {m(I).name};
            enums = m(I);
        end

        function [ind, enum] = getIndForName(name)
            m = enumeration('ConstraintEvalTypeEnum');
            [~,I] = sort({m.name});
            m = m(I);
            ind = find(ismember({m.name},name),1,'first');
            enum = m(ind);
        end

        function [enum, ind] = getEnumForListboxStr(nameStr)
            m = enumeration('ConstraintEvalTypeEnum');
            ind = find(ismember({m.name},nameStr),1,'first');
            enum = m(ind);
        end
    end
end


%--- help for dsge_solver_first_order_autoregress_1 ---
%
%  INTERNAL FUNCTION
%
%
%    Other functions named dsge_solver_first_order_autoregress_1
%
%       dsge/dsge_solver_first_order_autoregress_1
%


function topLevelBodyInfo = getTopLevelCentralBody(celBodyData)
    %getTopLevelCentralBody Summary of this function goes here
    %   Detailed explanation goes here
    try
        topLevelBodyInfo = celBodyData.emptyBodyInfo;
    catch
        topLevelBodyInfo = KSPTOT_BodyInfo.empty(1,0);
    end
    celBodyFields = fields(celBodyData);
    for(i=1:length(celBodyFields))
        bInfo = celBodyData.(celBodyFields{i});

        if(isempty(bInfo.parentBodyInfo))
            topLevelBodyInfo = bInfo;
            break;
        end
    end

    if(isempty(topLevelBodyInfo))
        topLevelBodyInfo = celBodyData.(celBodyFields{1});
    end
end


function [status,varargout] = spellcheck(text)

%SPELLCHECK checks the spelling of word(s) and returns suggestions if misspelled.
%
% [status,suggestions] = spellcheck(text);
% status = spellcheck(text);
%
%     text:         a word or string of words separated by space(s).
%     status:       returns '1' if words exist in dictionary or '0' otherwise.
%     suggestions:  an array of suggested corrections of the misspelled word
%                   or otherwise returns a message 'Correct Spelling'.
%
% Examples:
%      [status,suggestions] = spellcheck('Hellow');
%      [status,suggestions] = spellcheck('My Name is Fahad!');
%      status = spellcheck('Emirates');
%
%   Copyright 2004 Fahad Al Mahmood
%   Version: 1.0 $  $Date: 30-Jun-2004
%   Version: 1.5 $  $Date: 01-Jul-2004 (Multiple words check & status,
%                                       thanks Michael Kleder!)
%   Version: 1.6 $  $Date: 11-Jul-2004 (Fixed the 'no suggestions' result,
%                                       thanks Sander Stepanov!)

% Separating string of words into arrays of words.
k=1;
temp='';
for n=1:length(text);
    if ~isspace(text(n))
        temp = [temp text(n)];
    else
        if ~isspace(text(n-1))
            words{k} = temp;
        end
        temp='';
        k=k+1;
    end
end
words{k} = temp;

% Opening MS Word and Starting the Spelling Check

Doc = actxserver('Word.Application');
m=1;
for n=1:length(words)
    if ~isempty(words{n})
        status(m) = invoke(Doc,'CheckSpelling',words{n},[],1,1);
        if nargout==2
            invoke(Doc.Documents,'Add');
            X = invoke(Doc,'GetSpellingSuggestions',words{n});
            count = get(X,'Count');
            suggestions{m,1} = words{n};
            if count~=0
                for k=2:count+1
                    suggestion = invoke(X,'Item',k-1);
                    suggestions{m,k} = get(suggestion,'Name');
                end
            elseif count==0 & status(m)==1
                suggestions{m,2} = 'Correct Spelling';
            elseif count==0 & status(m)==0
                suggestions{m,2} = 'No Suggestions!';
            end
            varargout = {suggestions};
        end
        m=m+1;
    end
end

status = all(status);

invoke(Doc,'Quit');
delete(Doc);


% H = XLABELS(TEXT,...)
% H = XLABELS(HAX,TEXT,...)

% Last modified 2010-06-11
% Copyright (c) Jaakko Luttinen (jaakko.luttinen@tkk.fi)

function h = xlabels(text,varargin)

options = struct('Separation', []);

if isnumeric(text)
  hax = text;
  text = varargin{1};
  [options, errmsg, remopts] = argparse(options, varargin{2:end});
  error(errmsg);
else
  hax = gca;
  [options, errmsg, remopts] = argparse(options, varargin{:});
  error(errmsg);
end

h = zeros(size(hax));
for n=1:numel(hax)

  % Get axes position
  pos_ax = get(hax(n), 'Position');

  % Add a colorbar
  if iscell(text)
    h(n) = xlabel(hax(n), text{n}, remopts{:});
  else
    h(n) = xlabel(hax(n), text, remopts{:});
  end

  % Use the same units
  units = get(hax(n), 'Units');
  set(h(n), 'Units', units);

  pos = get(h(n), 'Position');
  pos(2) = -options.Separation;
  set(h(n), 'Position', pos);

end

if nargout < 1
  clear hcb;
end


function cnn_save_model(epoch_dir, net_config_input, exp_info)

if ~isempty(net_config_input)
    net_config=gen_saved_net_config(net_config_input);
    net_filename=net_config.ref.cache_filename;
    net_config.ref.cache_filename=[];
    net_config_file=fullfile(epoch_dir, net_filename);
    fprintf('save net_config to: %s\n', net_config_file);
    try
        save(net_config_file, 'net_config', '-v7.3') ;
    catch err_info
        disp(err_info.getReport);
        dbstack;
        keyboard;
    end
end

if ~isempty(exp_info)
    info_filename=exp_info.cache_filename;
    info_file=fullfile(epoch_dir, info_filename);
    fprintf('save exp_info to: %s\n', info_file);
    try
        save(info_file, 'exp_info', '-v7.3') ;
    catch err_info
        disp(err_info.getReport);
        dbstack;
        keyboard;
    end
end

end

function net_config=gen_saved_net_config(net_config_input)

assert(isa(net_config_input, 'ref_obj'));

net_config=[];
make_ref_obj(net_config);
net_config.ref=net_config_input.ref;

for group_idx=1:length(net_config.ref.group_infos)
    group_info=net_config.ref.group_infos{group_idx};

    net_info=group_info.net_info;
    if ~isempty(net_info)
        new_net_info=[];
        make_ref_obj(new_net_info);
        new_net_info.ref=net_info.ref;
        do_clean_net_info(new_net_info);
        if new_net_info.ref.net_on_gpu
            my_move_net(new_net_info, 'cpu') ;
        end
        group_info.net_info=new_net_info;
    end

    if check_group_dag_net(group_info)

        fprintf('processing dag_net for saving, group_idx:%d, group_name: %s\n', group_info.group_idx, group_info.name);

        dag_net=group_info.dag_net;
        device_org=dag_net.device;
        saved_dag_net = dag_net.saveobj() ;

        if strcmp(device_org, 'gpu')
           dag_net.move('gpu');
        end

        group_info.dag_net=saved_dag_net;
    end

    net_config.ref.group_infos{group_idx}=group_info;
end

end

function do_clean_net_info(new_net_info)

new_net_info.ref.tmp_data=[];

for i=1:numel(new_net_info.ref.layers)

    if strcmp(new_net_info.ref.layers{i}.type,'conv')
          new_net_info.ref.layers{i}.filtersMomentum = [];
          new_net_info.ref.layers{i}.biasesMomentum = [];
    end

    if strcmp(new_net_info.ref.layers{i}.type,'my_custom')
        layer_update_fn=new_net_info.ref.layers{i}.layer_update_fn;
        if ~isempty(layer_update_fn)
            update_info=[];
            update_info.group_info=input_group_info;
            new_net_info.ref.layers{i}=new_net_info.ref.layers{i}.layer_update_fn(...
                'cache_clean', new_net_info.ref.layers{i}, update_info);
        end
    end
end

end

function use_dagnn=check_group_dag_net(group_info)

    use_dagnn=isfield(group_info, 'dag_net') && ~isempty(group_info.dag_net);
    if isfield(group_info, 'use_dagnn') && group_info.use_dagnn
        assert(use_dagnn==group_info.use_dagnn);
    end

end


%% OPTI MEX Install Script

% This file enables me to quickly rebuild all solvers - it is not intended
% to be called by the user!

% My build platform:
% - Windows 7 x64
% - Visual Studio 2015
% - Intel Compiler XE (C++ & FORTRAN)
% - Intel Math Kernel Library

% YOU MUST BE IN THE BASE DIRECTORY OF THE OPTI TOOLBOX!

addpath([cd '/Solvers/Source'])
addpath([cd '/Utilities/Source'])

% %% -- Intel C++ Solvers --
% clc
% fprintf(2,'Please Specify Intel C++ as your Compiler with VS2015 Linker (Option 3, Don''t Look for Installed Compilers)...\n\n');
% mex -setup
% %% CLP
% opti_CLP_Install

%% -- VS2017 Solvers --
clc
fprintf(2,'Please Specify Visual Studio 2017 as your Compiler...\n\n');
mex -setup
%% CLP
opti_CLP_Install

%% BONMIN
opti_BONMIN_Install

%% CBC
opti_CBC_Install

%% CSDP
opti_CSDP_Install

%% DSDP
opti_DSDP_Install

%% FILTERSD
opti_FILTERSD_Install

%% GLPK
opti_GLPK_Install

%% GSL
opti_GSL_Install

%% IPOPT
opti_IPOPT_Install

%% L-BFGS-B
opti_LBFGSB_Install

%% LEVMAR
opti_LEVMAR_Install

%% LP_SOLVE
opti_LPSOLVE_Install

%% M1QN3
opti_M1QN3_Install

%% MINPACK
opti_MINPACK_Install

%% MKL TR NLS
opti_MKLTRNLS_Install

%% MUMPS
opti_MUMPS_Install

%% NL2SOL
opti_NL2SOL_Install

%% NLOPT
opti_NLOPT_Install

%% NOMAD
opti_NOMAD_Install

%% OOQP
opti_OOQP_Install

%% PSWARM
opti_PSWARM_Install

%% SCIP
opti_SCIP_Install

%% -- Utilities --
%% MKL JAC
opti_MKLJAC_Install

%% CoinUtils
opti_COINUTILS_Install

%% AMPL
opti_ASL_Install

%% RMATHLIB
opti_RMathlib_Install

%% Remove Paths
rmpath([cd '/Solvers/Source'])
rmpath([cd '/Utilities/Source'])


function path = funpath(~)
%FUNPATH Returns the path to the calling function.
% Usage:
%   path = funpath()
%   path = funpath(_) % returns the path to the parent directory
%
% See also: get_caller_name, which, dbstack

% Get the path to the calling function
path = get_caller_name('path', true);

% Return the path to the function's parent directory
if nargin > 0
    path = fileparts(path);
end
end


function varargout = par_testworker(address,func,varargin)
% Test a remote worker process by forwarding a task.
% Result = par_testworker(Address,Function,Arguments...)
%
% In:
%   Address : network address of the worker (Host:Port)
%
%   Function : handle of the function to evaluate
%
%   Arguments... : optional arguments to the function
%
% Out:
%   Result : output of the function
%
% Examples:
% 	par_testworker('192.168.0.1:23457',@sin,1000)
%
%                                Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
%                                2013-07-18

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

import java.io.*
import java.net.*
import java.lang.*

% some parameters
taskid = round(rand*100000);
disp(['assigning task id ' num2str(taskid)]);
receive_buffer_size = 64000;
receive_backlog = 10;
timeout_connect_ms = 3000;
timeout_send_ms = 5000;
timeout_recv_ms = 5000;
timeout_accept_ms = 5000;
use_hlpscope = true;
use_hlpgetresult = false;

if ischar(func)
    func = str2func(func); end;

% transfer the current scope (optional)
if use_hlpscope
    scope = hlp_resolveall;
    varargin = [{scope,func} varargin];
    func = @hlp_scope;
end

% construct message
fprintf('serializing task data...');
messagebody = hlp_serialize([{1},{func},varargin]);
disp('done.');

% --- set up TCP server to receive the reply ---

fprintf('opening TCP server to receive replies...');
while true
    try
        serv = ServerSocket(2000+round(rand*60000),receive_backlog);
        break;
    catch,end
end
serv.setReceiveBufferSize(receive_buffer_size);
serv.setSoTimeout(timeout_accept_ms);
close_server = onCleanup(@()serv.close());

% determine server's address for replies
return_port = num2str(serv.getLocalPort());
return_host = hlp_hostip;
return_address = [return_host ':' num2str(return_port)];
disp(['done; will receive on ' return_address]);

% --- send task ---

% determine target address
idx = find(address==':',1);
host = address(1:idx-1);
port = str2num(address(idx+1:end));
destination = InetSocketAddress(host,port);

% connect
fprintf('connecting to %s:%i...',host,port);
outconn = Socket();
outconn.connect(destination,timeout_connect_ms); % 3-second timeout
outconn.setTcpNoDelay(1);
outconn.setSoTimeout(timeout_send_ms);
outconn.setSoLinger(true,3);
close_outconn = onCleanup(@()outconn.close());
disp('done.');

% send message
fprintf('now sending (%.0fkb)...',length(messagebody)/1024);
out = DataOutputStream(outconn.getOutputStream());
out.writeInt(taskid);
out.writeInt(length(return_address));
out.writeBytes(return_address);
out.writeInt(length(messagebody));
out.write(messagebody);
out.flush();

% wait for handshake
fprintf('done; now waiting for checkum...');
in = DataInputStream(outconn.getInputStream());
checksum = in.readInt();
fprintf('done; checking...');
if checksum == taskid+length(return_address)+length(messagebody)
    fprintf('all clear');
else
    fprintf('ERROR: unexpected checksum');
end
% close socket
fprintf('; now closing...');
outconn.close();
disp('done.');

% --- receive reply ---

% wait for and get an incoming connection
fprintf('now waiting for reply...');
while true
    try
        conn = serv.accept();
    catch
        continue;
    end
    conn.setSoTimeout(timeout_recv_ms);
    conn.setTcpNoDelay(1);

    % receive reply
    fprintf('done; receiving data.\n');
    in = DataInputStream(conn.getInputStream());
    cr = ChunkReader(in);
    received_taskid = in.readInt();
    if received_taskid ~= taskid
        fprintf('got unexpected task id (%i instead of %i); back to waiting...\n',received_taskid,taskid);
        conn.close();
    else
        disp(['got correct task id: ' num2str(received_taskid)]);
    end
    fprintf('receiving reply...');
    replybody = typecast(cr.readFully(in.readInt()),'uint8');
    fprintf('got reply (%.0fkb).\n',length(replybody)/1024);

    fprintf('now closing...');
    conn.close();
    disp('done.');

    % construct result
    fprintf('parsing result...');
    reply = hlp_deserialize(replybody);
    disp('done.');

    % post-process result
    if isfield(reply{2},{'message','identifier','stack'})
        disp('Got an exception; traceback: ');
        rethrow(reply{2});
    else
        result = reply{2};
    end
    break;
end

if use_hlpgetresult
    varargout = result;
else
    varargout = {result};
end


%% set up path

[~,computername] = system('hostname');
computername = strtrim(computername);

switch computername,

  case 'bransonk-desktop',

    JCtrax_path = '/groups/branson/home/bransonk/tracking/code/JCtrax';
    configfilename = 'params/JLabelParams_bransonk-desktop.xml';
    rootdatadir = '/groups/branson/home/bransonk/behavioranalysis/data/larvae_vani';

  case 'bransonk-lw2',

    JCtrax_path = 'C:\Code\JCtrax';
    configfilename = 'params\JLabelParamsKristinChase.xml';
    rootdatadir = 'C:\Data\larvae_vani';

  otherwise

    warning('Unknown computer %s. Paths may not be setup correctly',computername);
    JCtrax_path = '/groups/branson/home/bransonk/tracking/code/JCtrax';
    configfilename = 'params/JLabelParams_bransonk-desktop.xml';
    rootdatadir = '/groups/branson/home/bransonk/behavioranalysis/data/larvae_vani';

end

addpath(genpath(fullfile(JCtrax_path,'pdollar_toolbox')));
addpath(fullfile(JCtrax_path,'misc'));
addpath(fullfile(JCtrax_path,'filehandling'));
jlabelpath = fileparts(which('JLabel'));
addpath(fullfile(jlabelpath,'compute_perframe_features'));

%% parameters

genotype_name = 'genotypetest';
experiment_name = '20111213-144536';

%%

expdir = fullfile(rootdatadir,genotype_name,experiment_name);

ConvertLarvaeVaniTrxToTrx(expdir);


function [ori,varargout] = loadOrientation(fname,varargin)

warning('loadOrientation is depreciated. Please use instead orientation.load');
[ori,varargout{1:nargout-1}] = orientation.load(fname,varargin{:});


addpath('/Users/gt/Dropbox/scratch_matlab/RocketSeismology')
sync_spacex_videos_usfdata
sync_youtube_video_usfdata


function out = makeLabel(type, label, value)
%makeLabel Create a ADC Label.
%   label=makeLabel() Create a Label event for ADC line
%         Possible values for type are: 'SET','INC'.
%         Label may be a counter of a flag and should be one of
%         (counters) 'SLC','SEG','REP','AVG','SET','ECO','PHS','LIN','PAR',
%         (flags)    'NAV','REV','SMS'.
%         Value: numeric value of the parameter (increment may be negative)
%                or true/false for a flag
%
%   See also  Sequence.addBlock, mr.getSupportedLabels

supported_labels=mr.getSupportedLabels();
if nargin~=3
    error('makeLabel:invalidArguments','Must supply exactly 3 parameters');
end
if ~any(ismember(supported_labels,label))
    error('makeLabel:invalidArguments','Must supply a valid label');
end
if ~any(ismember({'SET','INC'},type))
    error('makeLabel:invalidArguments','Must supply a valid type');
end
if ~isnumeric(value) && ~islogical(value)
    error('makeLabel:invalidArguments','Must supply a valid numeric or logical value');
end

switch(type)
    case 'SET'
        out.type = 'labelset';
    case 'INC'
        out.type = 'labelinc';
    otherwise
        error('unknown label type');
end
out.label=label;
out.value=value;
end


% OtSkimCubeNew Create a new skim cube.
%
% Usage:
%    hscube = OtSkimCubeNew(<path to a work directory>)
% or:
%    hscube = OtSkimCubeNew()
%    to try to use a temporary directory (%TMP%, %TEMP% or /tmp)
%
% To release a skim cube handle, call OtSkimCubeFree().

% OtMatlab: Matlab interface to the Omnitrans transport planning software

% Copyright (c) 2008, VORtech Computing
% Copyright (c) 2010, Omnitrans International

% All rights reserved.

% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are
% met:

%     * Redistributions of source code must retain the above copyright
%       notice, this list of conditions and the following disclaimer.
%     * Redistributions in binary form must reproduce the above copyright
%       notice, this list of conditions and the following disclaimer in
%       the documentation and/or other materials provided with the distribution
%     * Neither the name of VORtech Computing and Omnitrans International nor the names
%       of its contributors may be used to endorse or promote products derived
%       from this software without specific prior written permission.

% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
% POSSIBILITY OF SUCH DAMAGE.

% 2006-04-19 Created (Johan Meijdam, VORtech)

function hscube = OtSkimCubeNew(workdir)
   if nargin == 0
      workdir = getenv('TMP');
      if isempty(workdir)
         workdir = getenv('TEMP');
         if isempty(workdir)
            workdir = [filesep 'tmp'];
         end
      end
   end
   hscube = Ot('skimcube.new', workdir);
end


% The COBRAToolbox: testGetDefaultCompartmentSymbols.m
%
% Purpose:
%     - test the getDefaultCompartmentSymbols function
%
% Authors:
%     - Jacek Wachowiak

% save the current path
currentDir = pwd;

% initialize the test
fileDir = fileparts(which('getDefaultCompartmentSymbols'));
cd(fileDir);

% test variables
testCompSymbolList = {'c','m','v','x','e','t','g','r','n','p','l','y'};
testCompNameList = {'Cytoplasm','Mitochondrion','Vacuole','Peroxisome','Extracellular','Pool','Golgi','Endoplasmic_reticulum','Nucleus','Periplasm','Lysosome','Glycosome'};
% function outputs
[defaultCompartmentSymbolList, defaultCompartmentNameList] = getDefaultCompartmentSymbols();

% test
assert(isequal(defaultCompartmentSymbolList, testCompSymbolList))
assert(isequal(defaultCompartmentNameList, testCompNameList))

% change to old directory
cd(currentDir);


function dicomrt_showabout(item)
% dicomrt_showabout
%
% Display information, copyright and discalimer.
%
% Copyright (C) 2002 Emiliano Spezi (emiliano.spezi@physics.org)

if strcmp(item,'showabout_dicomrt_explore')
    what2say = {'This is dicomrt_explore.','','',...
            'Dicomrt_explore is a wrapper for a custom version of sliceomatic.',...
            'This function is part of the DICOM-RT Toolbox.',...
            'Copyright (C) 2002 Emiliano Spezi (emiliano.spezi@physics.org).',...
            'The DICOM-RT Toolbox is distributed under the General Public License (www.gnu.org/copyleft/gpl.html).'};
    helpdlg(what2say,'About dicomrt_explore')
elseif strcmp(item,'showabout_sliceomatic')
    what2say = {'The DICOM-RT Toolbox incorporates a custom version of sliceomatic v. 2.0.','','',...
            'Sliceomatic is a slice and isosurface volume exploration GUI.',...
            'Sliceomatic was written by Eric Ludlam <eludlam@mathworks.com>.',...
            'Copyright 2000, 2001, 2002 The MathWorks Inc.',...
            'Sliceomatic can be downloaded from Matlab-Central (www.mathworks.com/matlabcentral).','',...
            'Original code modified by Emiliano Spezi <emiliano.spezi@physics.org> ',...
            'to include the following capabilities:',...
            '1) axes limits control',...
            '2) support for all DICOM patient orientations',...
            '3) contour level selection',...
            '4) superposition of DICOM RTSTRUCT objects'};
    helpdlg(what2say,'About sliceomatic')
end


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

    properties
        stage LaunchVehicleStage

        stageStateToSet(1,1) logical = true;

        inheritStageState(1,1) logical = true;
        inheritStageStateFrom(1,1) InheritStateEnum = InheritStateEnum.InheritFromLastState;
        inheritStageStateFromEvent LaunchVehicleEvent = LaunchVehicleEvent.empty(1,0);
    end

    methods
        function obj = SetKinematicStateStageState(stage)
            obj.stage = stage;
        end

        function updateStateLogEntry(obj, newStateLogEntry, stateLog)
            stageState = obj.getStageState(newStateLogEntry);

            if(obj.inheritStageState)
                if(obj.inheritStageStateFrom == InheritStateEnum.InheritFromSpecifiedEvent && ...
                   not(isempty(obj.inheritStageStateFromEvent)) && ...
                   not(isempty(obj.inheritStageStateFromEvent.getEventNum())) && ...
                   obj.inheritStageStateFromEvent.getEventNum() > 0)

                    evtStateLog = stateLog.getLastStateLogForEvent(obj.inheritStageStateFromEvent);
                    if(not(isempty(evtStateLog)))
                        evtStageState = obj.getStageState(evtStateLog);
                        stageState.active = evtStageState.active;
                    end
                end
            else
                stageState.active = obj.stageStateToSet;
            end
        end

        function listboxStr = getListboxStr(obj)
            listboxStr = {};
            for(i=1:length(obj))
                listboxStr{i} = obj(i).stage.name; %#ok<AGROW>
            end
        end
    end

    methods(Access=private)
        function stageState = getStageState(obj, stateLogEntry)
            stageStates = stateLogEntry.stageStates;
            stageState = stageStates([stageStates.stage] == obj.stage);
        end
    end
end


function varargout=fig2emf(varargin)
%
% For calling details please see v_fig2emf.m
%
% This dummy routine is included for backward compatibility only
% and will be removed in a future release of voicebox. Please use
% v_fig2emf.m in future and/or update with v_voicebox_update.m
%
%      Copyright (C) Mike Brookes 2018
%      Version: $Id: fig2emf.m 10863 2018-09-21 15:39:23Z dmb $
%
if nargout
    varargout=cell(1,nargout);
    [varargout{:}]=v_fig2emf(varargin{:});
else
    v_fig2emf(varargin{:});
end


% OtQueryNew Connect to an Omnitrans query.
%
% Usage:
%    hquery = OtQueryNew()
% or:
%    hquery = OtQueryNew(<SQL statement>)
%    This form includes a call to OtQuerySetSQL()
%
% To release a query handle, call OtQueryFree().

% OtMatlab: Matlab interface to the Omnitrans transport planning software

% Copyright (c) 2008, VORtech Computing
% Copyright (c) 2010, Omnitrans International

% All rights reserved.

% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are
% met:

%     * Redistributions of source code must retain the above copyright
%       notice, this list of conditions and the following disclaimer.
%     * Redistributions in binary form must reproduce the above copyright
%       notice, this list of conditions and the following disclaimer in
%       the documentation and/or other materials provided with the distribution
%     * Neither the name of VORtech Computing and Omnitrans International nor the names
%       of its contributors may be used to endorse or promote products derived
%       from this software without specific prior written permission.

% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
% POSSIBILITY OF SUCH DAMAGE.

% 2006-02-28 Created (Johan Meijdam, VORtech)

function hquery = OtQueryNew(statement)
   if nargin == 1
      hquery = Ot('query', statement);
   else
      hquery = Ot('query');
   end
end


function display(s)
%DISPLAY - spectralobject display overloaded operator

% VERSION: 1.0 of spectralobject
% AUTHOR: Celso Reyes
% LASTUPDATE: 1/30/2007

if isequal(get(0,'FormatSpacing'),'compact')
    disp([inputname(1) ' =']);
    disp(s);
else
    disp(' ');
    disp([inputname(1) ' =']);
    disp(' ');
    disp(s);
end


function SaveFig(fname, varargin)
% OLD now use export_fig
% Usage: savefig(filename, fighdl, options)
%
% Saves a pdf, eps, png, jpeg, and/or tiff of the contents of the fighandle's (or current) figure.
% It saves an eps of the figure and the uses Ghostscript to convert to the other formats.
% The result is a cropped, clean picture. There are options for using rgb or cmyk colours,
% or grayscale. You can also choose the resolution.
%
% The advantage of savefig is that there is very little empty space around the figure in the
% resulting files, you can export to more than one format at once, and Ghostscript generates
% trouble-free files.
%
% If you find any errors, please let me know! (peder at axensten dot se)
%
% filename: File name without suffix.
%
% fighdl:  (default: gcf) Integer handle to figure.
%
% options: (default: '-r300', '-lossless', '-rgb') You can define your own
%          defaults in a global variable savefig_defaults, if you want to, i.e.
%          savefig_defaults= {'-r200','-gray'};.
% 'eps':   Output in Encapsulated Post Script (no preview yet).
% 'pdf':   Output in (Adobe) Portable Document Format.
% 'png':   Output in Portable Network Graphics.
% 'jpeg':  Output in Joint Photographic Experts Group format.
% 'tiff':  Output in Tagged Image File Format (no compression: huge files!).
% '-rgb':  Output in rgb colours.
% '-cmyk': Output in cmyk colours (not yet 'png' or 'jpeg' -- '-rgb' is used).
% '-gray': Output in grayscale (not yet 'eps' -- '-rgb' is used).
% '-fonts':  Include fonts in eps or pdf. Includes only the subset needed.
% '-lossless':  Use lossless compression, works on most formats. same as '-c0', below.
% '-c<float>':  Set compression for non-indexed bitmaps in PDFs -
%               0: lossless; 0.1: high quality; 0.5: medium; 1: high compression.
% '-r<integer>':  Set resolution.
% '-crop': Removes points and line segments outside the viewing area -- permanently.
%          Only use this on figures where many points and/or line segments are outside
%          the area zoomed in to. This option will result in smaller vector files (has no
%          effect on pixel files).
% '-dbg':  Displays gs command line(s).
%
% EXAMPLE:
% savefig('nicefig', 'pdf', 'jpeg', '-cmyk', '-c0.1', '-r250');
% Saves the current figure to nicefig.pdf and nicefig.png, both in cmyk and at 250 dpi,
%          with high quality lossy compression.
%
% REQUIREMENT: Ghostscript. Version 8.57 works, probably older versions too, but '-dEPSCrop'
%          must be supported. I think version 7.32 or newer is ok.
%
% HISTORY:
% Version 1.0, 2006-04-20.
% Version 1.1, 2006-04-27:
% - No 'epstopdf' stuff anymore! Using '-dEPSCrop' option in gs instead!
% Version 1.2, 2006-05-02:
% - Added a '-dbg' option (see options, above).
% - Now looks for a global variable 'savefig_defaults' (see options, above).
% - More detailed Ghostscript options (user will not really notice).
% - Warns when there is no device for a file-type/color-model combination.
% Version 1.3, 2006-06-06:
% - Added a check to see if there actually is a figure handle.
% - Now works in Matlab 6.5.1 (R13SP1) (maybe in 6.5 too).
% - Now compatible with Ghostscript 8.54, released 2006-06-01.
% Version 1.4, 2006-07-20:
% - Added an option '-soft' that enables anti-aliasing on pixel graphics (on by default).
% - Added an option '-hard' that don't do anti-aliasing on pixel graphics.
% Version 1.5, 2006-07-27:
% - Fixed a bug when calling with a figure handle argument.
% Version 1.6, 2006-07-28:
% - Added a crop option, see above.
% Version 1.7, 2007-03-31:
% - Fixed bug: calling print with invalid renderer value '-none'.
% - Removed GhostScript argument '-dUseCIEColor' as it sometimes discoloured things.
% Version 1.8, 2008-01-03:
% - Added MacIntel: 'MACI'.
% - Added 64bit PC (I think, can't test it myself).
% - Added option '-nointerpolate' (use it to prevent blurring of pixelated).
% - Removed '-hard' and '-soft'. Use '-nointerpolate' for '-hard', default for '-soft'.
% - Fixed the gs 8.57 warning on UseCIEColor (it's now set).
% - Added '-gray' for pdf, but gs 8.56 or newer is needed.
% - Added '-gray' and '-cmyk' for eps, but you a fairly recent gs might be needed.
% Version 1.9, 2008-07-27:
% - Added lossless compression, see option '-lossless', above. Works on most formats.
% - Added lossy compression, see options '-c<float>...', above. Works on 'pdf'.
%   Thanks to Olly Woodford for idea and implementation!
% - Removed option '-nointerpolate' -- now savefig never interpolates.
% - Fixed a few small bugs and removed some mlint comments.
% Version 2.0, 2008-11-07:
% - Added the possibility to include fonts into eps or pdf.
%
% TO DO: (Need Ghostscript support for these, so don't expect anything soon...)
% - svg output.
% - '-cmyk' for 'jpeg' and 'png'.
% - Preview in 'eps'.
% - Embedded vector fonts, not bitmap, in 'eps'.
%
% Copyright (C) Peder Axensten (peder at axensten dot se), 2006.

% KEYWORDS:     eps, pdf, jpg, jpeg, png, tiff, eps2pdf, epstopdf, ghostscript
%
% INSPIRATION:  eps2pdf (5782), eps2xxx (6858)
%
% REQUIREMENTS: Works in Matlab 6.5.1 (R13SP1) (maybe in 6.5 too).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

	op_dbg=		false;												% Default value.

	% Compression
	compr=			[' -dUseFlateCompression=true -dLZWEncodePages=true -dCompatibilityLevel=1.6' ...
					 ' -dAutoFilterColorImages=false -dAutoFilterGrayImages=false ' ...
					 ' -dColorImageFilter=%s -dGrayImageFilter=%s'];	% Compression.
	lossless=		sprintf (compr, '/FlateEncode', '/FlateEncode');
	lossy=			sprintf (compr, '/DCTEncode',   '/DCTEncode'  );
	lossy=			[lossy ' -c ".setpdfwrite << /ColorImageDict << /QFactor %g ' ...
					 '/Blend 1 /HSample [%s] /VSample [%s] >> >> setdistillerparams"'];

	% Create gs command.
	cmdEnd=			' -sDEVICE=%s -sOutputFile="%s"';					% Essential.
	epsCmd=			'';
	epsCmd=	[epsCmd ' -dSubsetFonts=true -dNOPLATFONTS'];				% Future support?
	epsCmd=	[epsCmd ' -dUseCIEColor=true -dColorConversionStrategy=/UseDeviceIndependentColor'];
	epsCmd=	[epsCmd ' -dProcessColorModel=/%s'];						% Color conversion.
	pdfCmd=	[epsCmd ' -dAntiAliasColorImages=false' cmdEnd];
	epsCmd=	[epsCmd cmdEnd];

	% Get file name.
	if((nargin < 1) || isempty(fname) || ~ischar(fname))				% Check file name.
		error('No file name specified.');
	end
	[pathstr, namestr] = fileparts(fname);
	if(isempty(pathstr)), fname= fullfile(cd, namestr);	end

	% Get handle.
	fighdl=		get(0, 'CurrentFigure'); % See gcf.						% Get figure handle.
	if((nargin >= 2) && (numel(varargin{1}) == 1) && isnumeric(varargin{1}))
		fighdl=		varargin{1};
		varargin=	{varargin{2:end}};
	end
	if(isempty(fighdl)), error('There is no figure to save!?');	end
	set(fighdl, 'Units', 'centimeters')									% Set paper stuff.
	sz=			get(fighdl, 'Position');
	sz(1:2)=	0;
	set(fighdl, 'PaperUnits', 'centimeters', 'PaperSize', sz(3:4), 'PaperPosition', sz);

	% Set up the various devices.
	% Those commented out are not yet supported by gs (nor by savefig).
	% pdf-cmyk works due to the Matlab '-cmyk' export being carried over from eps to pdf.
	device.eps.rgb=		sprintf(epsCmd, 'DeviceRGB',	'epswrite', [fname '.eps']);
	device.jpeg.rgb=	sprintf(cmdEnd,	'jpeg', 					[fname '.jpeg']);
%	device.jpeg.cmyk=	sprintf(cmdEnd,	'jpegcmyk', 				[fname '.jpeg']);
	device.jpeg.gray=	sprintf(cmdEnd,	'jpeggray',					[fname '.jpeg']);
	device.pdf.rgb=		sprintf(pdfCmd, 'DeviceRGB',	'pdfwrite', [fname '.pdf']);
	device.pdf.cmyk=	sprintf(pdfCmd, 'DeviceCMYK',	'pdfwrite', [fname '.pdf']);
	device.pdf.gray=	sprintf(pdfCmd, 'DeviceGray',	'pdfwrite', [fname '.pdf']);
	device.png.rgb=		sprintf(cmdEnd,	'png16m', 					[fname '.png']);
%	device.png.cmyk=	sprintf(cmdEnd,	'png???', 					[fname '.png']);
	device.png.gray=	sprintf(cmdEnd,	'pnggray', 					[fname '.png']);
	device.tiff.rgb=	sprintf(cmdEnd,	'tiff24nc',					[fname '.tiff']);
	device.tiff.cmyk=	sprintf(cmdEnd,	'tiff32nc', 				[fname '.tiff']);
	device.tiff.gray=	sprintf(cmdEnd,	'tiffgray', 				[fname '.tiff']);

	% Get options.
	global savefig_defaults;											% Add global defaults.
 	if( iscellstr(savefig_defaults)), varargin=	{savefig_defaults{:}, varargin{:}};
	elseif(ischar(savefig_defaults)), varargin=	{savefig_defaults, varargin{:}};
	end
	varargin=	{'-r300', '-lossless', '-rgb', varargin{:}};			% Add defaults.
	res=		'';
	types=		{};
	fonts=		'false';
	crop=		false;
	for n= 1:length(varargin)											% Read options.
		if(ischar(varargin{n}))
			switch(lower(varargin{n}))
			case {'eps','jpeg','pdf','png','tiff'},		types{end+1}=	lower(varargin{n});
			case '-rgb',				color=	'rgb';	deps= {'-depsc2'};
			case '-cmyk',				color=	'cmyk';	deps= {'-depsc2', '-cmyk'};
			case '-gray',				color=	'gray';	deps= {'-deps2'};
			case '-fonts',				fonts=			'true';
			case '-lossless',			comp=			0;
			case '-crop',				crop=			true;
			case '-dbg',				op_dbg=			true;
			otherwise
				if(regexp(varargin{n}, '^\-r[0-9]+$')), 	 res=  varargin{n};
				elseif(regexp(varargin{n}, '^\-c[0-9.]+$')), comp= str2double(varargin{n}(3:end));
				else	warning('pax:savefig:inputError', 'Unknown option in argument: ''%s''.', varargin{n});
				end
			end
		else
			warning('pax:savefig:inputError', 'Wrong type of argument: ''%s''.', class(varargin{n}));
		end
	end
	types=		unique(types);
	if(isempty(types)), error('No output format given.');	end

	if (comp == 0)														% Lossless compression
		gsCompr=		lossless;
	elseif (comp <= 0.1)												% High quality lossy
		gsCompr=		sprintf(lossy, comp, '1 1 1 1', '1 1 1 1');
	else																% Normal lossy
		gsCompr=		sprintf(lossy, comp, '2 1 1 2', '2 1 1 2');
	end

	% Generate the gs command.
	switch(computer)													% Get gs command.
		case {'MAC','MACI'},			gs= '/usr/local/bin/gs';
		case {'PCWIN','PCWIN64'},		gs= 'gswin32c.exe';
		otherwise,						gs= 'gs';
	end
	gs=		[gs		' -q -dNOPAUSE -dBATCH -dEPSCrop'];					% Essential.
	gs=		[gs     ' -dPDFSETTINGS=/prepress -dEmbedAllFonts=' fonts];	% Must be first?
	gs=		[gs		' -dUseFlateCompression=true'];						% Useful stuff.
	gs=		[gs		' -dAutoRotatePages=/None'];						% Probably good.
	gs=		[gs		' -dHaveTrueTypes'];								% Probably good.
	gs=		[gs		' ' res];											% Add resolution to cmd.

	if(crop && ismember(types, {'eps', 'pdf'}))							% Crop the figure.
		fighdl= do_crop(fighdl);
	end

	% Output eps from Matlab.
	renderer=	['-' lower(get(fighdl, 'Renderer'))];					% Use same as in figure.
	if(strcmpi(renderer, '-none')), renderer=	'-painters';	end		% We need a valid renderer.
	print(fighdl, deps{:}, '-noui', renderer, res, [fname '-temp']);	% Output the eps.

	% Convert to other formats.
	for n= 1:length(types)												% Output them.
		if(isfield(device.(types{n}), color))
			cmd=		device.(types{n}).(color);						% Colour model exists.
		else
			cmd=		device.(types{n}).rgb;							% Use alternative.
			if(~strcmp(types{n}, 'eps'))	% It works anyways for eps (VERY SHAKY!).
				warning('pax:savefig:deviceError', ...
						'No device for %s using %s. Using rgb instead.', types{n}, color);
			end
		end
		cmp=	lossless;
		if (strcmp(types{n}, 'pdf')),	cmp= gsCompr;		end			% Lossy compr only for pdf.
		if (strcmp(types{n}, 'eps')),	cmp= '';			end			% eps can't use lossless.
		cmd=	sprintf('%s %s %s -f "%s-temp.eps"', gs, cmd, cmp, fname);% Add up.
			status= system(cmd);										% Run Ghostscript.
			if (op_dbg || status), 		display (cmd),		end
	end
	delete([fname '-temp.eps']);										% Clean up.
end

function fig= do_crop(fig)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%	Remove line segments that are outside the view.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

	haxes=	findobj(fig, 'Type', 'axes', '-and', 'Tag', '');
	for n=1:length(haxes)
		xl=		get(haxes(n), 'XLim');
		yl=		get(haxes(n), 'YLim');
		lines=	findobj(haxes(n), 'Type', 'line');
		for m=1:length(lines)
			x=				get(lines(m), 'XData');
			y=				get(lines(m), 'YData');

			inx=			(xl(1) <= x) & (x <= xl(2));	% Within the x borders.
			iny=			(yl(1) <= y) & (y <= yl(2));	% Within the y borders.
			keep=			inx & iny;						% Within the box.

			if(~strcmp(get(lines(m), 'LineStyle'), 'none'))
				crossx=		((x(1:end-1) < xl(1)) & (xl(1) < x(2:end))) ...	% Crossing border x1.
						|	((x(1:end-1) < xl(2)) & (xl(2) < x(2:end))) ...	% Crossing border x2.
						|	((x(1:end-1) > xl(1)) & (xl(1) > x(2:end))) ...	% Crossing border x1.
						|	((x(1:end-1) > xl(2)) & (xl(2) > x(2:end)));	% Crossing border x2.
				crossy=		((y(1:end-1) < yl(1)) & (yl(1) < y(2:end))) ...	% Crossing border y1.
						|	((y(1:end-1) < yl(2)) & (yl(2) < y(2:end))) ...	% Crossing border y2.
						|	((y(1:end-1) > yl(1)) & (yl(1) > y(2:end))) ...	% Crossing border y1.
						|	((y(1:end-1) > yl(2)) & (yl(2) > y(2:end)));	% Crossing border y2.
				crossp=	[(	(crossx & iny(1:end-1) & iny(2:end)) ...	% Crossing a x border within y limits.
						|	(crossy & inx(1:end-1) & inx(2:end)) ...	% Crossing a y border within x limits.
						|	crossx & crossy ...							% Crossing a x and a y border (corner).
						 ),	false ...
						];
				crossp(2:end)=	crossp(2:end) | crossp(1:end-1);		% Add line segment's secont end point.

				keep=			keep | crossp;
			end
			set(lines(m), 'XData', x(keep))
			set(lines(m), 'YData', y(keep))
		end
	end
end


function nProtocols = db_import(BrainstormDbDir)
% DB_IMPORT: Import a full database from a folder on the hard-drive
%
% USAGE:  db_import(BrainstormDbDir)
%         db_import()                : Ask for the database directory

% @=============================================================================
% 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, 2010

% No directory specified
nProtocols = 0;
if (nargin < 1) || isempty(BrainstormDbDir)
    % Default directory
    if ispc
        defDir = 'C:\';
    else
        defDir = bst_get('UserDir');
    end
    % Open 'Select directory' dialog
    BrainstormDbDir = bst_uigetdir(defDir, 'Please select database directory.');
    if isempty(BrainstormDbDir) || ~ischar(BrainstormDbDir)
        return
    end
end

% Get all the subfolders
files = dir(BrainstormDbDir);
dirList = files([files.isdir] == 1);
if isempty(dirList)
    return
end
iProtocols = [];

% Loop on each subfolder
for i = 1:length(dirList)
    % Ignore folders that start with a "."
    if (dirList(i).name(1) == '.')
        continue;
    end
    % Protocol folder
    ProtocolDir = bst_fullfile(BrainstormDbDir, dirList(i).name);
    % Try to get a subject folder and a study folder
    [subjectFile, iDepthSubject] = file_find(ProtocolDir, 'brainstormsubject*.mat', 3);
    [studyFile, iDepthStudy]     = file_find(ProtocolDir, 'brainstormstudy*.mat',   3);
    % If not both files are found, it's not a brainstorm protocol
    if isempty(subjectFile) || isempty(studyFile) || (iDepthSubject ~= 3) || (iDepthSubject ~= 3)
        continue;
    end

    % Initialize protocol structure
    sProtocol = db_template('ProtocolInfo');
    [tmp__,sProtocol.Comment] = bst_fileparts(ProtocolDir, 1);
    sProtocol.SUBJECTS = bst_fileparts(bst_fileparts(subjectFile), 1);
    sProtocol.STUDIES  = bst_fileparts(bst_fileparts(studyFile), 1);
    % Load protocol
    tmp = db_edit_protocol('load', sProtocol);
    if ~isempty(tmp) && ~isequal(tmp, -1)
        iProtocols(end+1) = tmp;
    end
end

% Select the last protocol
if ~isempty(iProtocols)
    gui_brainstorm('SetCurrentProtocol', iProtocols(1));
end


classdef MimRemapBlue < MimGuiPlugin
    % MimRemapBlue. Gui Plugin for setting paint colour
    %
    %     You should not use this class within your own code. It is intended to
    %     be used by the gui of the TD MIM Toolkit.
    %
    %     MimRemapBlue 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 = 'Right upper'
        SelectedText = 'Right upper'
        ToolTip = 'Marks airway as right upper'
        Category = 'Airway label'
        Visibility = 'Dataset'
        Mode = 'Edit'

        HidePluginInDisplay = false
        PTKVersion = '1'
        ButtonWidth = 5
        ButtonHeight = 1
        Icon = 'paint.png'
        IconColour = GemMarkerPoint.DefaultColours{1}
        Location = 31
    end

    methods (Static)
        function RunGuiPlugin(gui_app)
            gui_app.ImagePanel.PaintBrushColour = 1;
        end

        function enabled = IsEnabled(gui_app)
             enabled = gui_app.IsDatasetLoaded && gui_app.ImagePanel.OverlayImage.ImageExists && ...
                isequal(gui_app.ImagePanel.SelectedControl, 'Map');
        end

        function is_selected = IsSelected(gui_app)
            is_selected = gui_app.ImagePanel.PaintBrushColour == 1;
        end
    end
end


%   AUTHORSHIP
%   Primary Developer: Stephen Meehan <swmeehan@stanford.edu>
%   Math Lead & Secondary Developer:  Connor Meehan <connor.gw.meehan@gmail.com>
%   Bioinformatics Lead:  Wayne Moore <wmoore@stanford.edu>
%   Provided by the Herzenberg Lab at Stanford University
%   License: BSD 3 clause
%
classdef ToolBar < handle
    properties
        ht=[];
        comboBoxes;
        bag=[];
        firstItems={};
        jToolbar=[];
    end
    methods
        function setEnabled(tb, yes)
            N=tb.jToolbar.getComponentCount;
            for i=0:N-1
                btn=tb.jToolbar.getComponentAtIndex(i);
                btn.setRequestFocusEnabled(false);
                if isa(btn, 'javax.swing.JPanel')
                    btn.setVisible(yes);
                else
                    btn.setEnabled(yes);
                end
            end
        end
        function this=ToolBar(ht)
            this.comboBoxes=[];
            this.bag=struct();
            this.jToolbar=ToolBarMethods.getJ(ht);
            this.ht=ht;
        end
    end

    methods(Static)

        function this=New(fig, first, removeZoom, removeRotate3D, removeEdit)
            if nargin<5
                removeEdit=true;
                if nargin<4
                    removeRotate3D=true;
                    if nargin<3
                        removeZoom=true;
                    end
                end
            end
            if first
                set(fig, 'Toolbar', 'figure');
                Gui.removeToolbarExcess(fig, removeRotate3D, removeEdit);
                if nargin>2 && removeZoom
                    Gui.removeForTooltip(fig, 'Zoom In');
                    Gui.removeForTooltip(fig, 'Zoom Out');
                    Gui.removeForTooltip(fig, 'Pan');
                end
                drawnow;
                this=ToolBar(findall(fig,'tag','FigureToolBar'));
            else
                ht_=uitoolbar(fig);
                drawnow;
                this=ToolBar(ht_);
            end
        end
    end

end


function s = n2s(n)
s = num2str(n);
return


function appendDataToHdf5(filename, datasetName, inputData, varargin)
	% Appends 3D data to existing dataset in hdf5 file, assumes x,y are the same, only appending z.
	% Biafra Ahanonu
	% started: 2014.01.07
	% inputs
		%
	% outputs
		%

	ciapkg.hdf5.appendDataToHdf5(filename, datasetName, inputData,'passArgs', varargin);
end


function save_mat(qual,outfilename)
% Saves a Seg_Quality object to a mat file.
% Inputs:
%   qual: The Seg_Quality object to be saved.
%   outfilename: The name for the mat output file.

assert(nargin==2)
assert(isa(qual,'Seg_Quality'))
assert(isa(outfilename,'char'))
assert(qual.validate())

warning('off','MATLAB:structOnObject')
qual = struct(qual);
warning('on','MATLAB:structOnObject')
save(outfilename,'qual');


function varargout = arg_guidialog(func,varargin)
% Create an input dialog that displays input fields for a Function and Parameters.
% Parameters = arg_guidialog(Function, Options...)
%
% The Parameters that are passed to the function can be used to override some of its defaults. The
% function must declare its arguments via arg_define. In addition, only a Subset of the function's
% specified arguments can be displayed.
%
% If this function is called with no arguments from within a function that uses arg_define it brings
% up a dialog for the function's defined arguments, with values assigned based on the function's
% inputs (contents of in varargin) and returns an argument struct if the dialog was confirmed with a
% click on OK, and an empty value otherwise. The calling function can exit on empty, or otherwise
% resume with entered parameters.
%
% In:
%   Function : the function for which to display arguments
%
%   Options... : optional name-value pairs; possible names are:
%                 'Parameters' : cell array of parameters to the Function to override some of its
%                                defaults.
%
%                 'Subset' : Cell array of argument names to which the dialog shall be restricted;
%                            these arguments may contain . notation to index into arg_sub and the
%                            selected branch(es) of arg_subswitch/arg_subtoggle specifiers. Empty
%                            cells show up in the dialog as empty rows.
%
%                 'Title' : title of the dialog (by default: functionname())
%
%                 'Invoke' : whether to invoke the function directly; in this case, the output
%                            arguments are those of the function (default: true, unless called in
%                            the form g = arg_guidialog; from within some function)
%
%                 'ShowGuru' : whether to show parameters marked as guru-level. (default: according
%                              to env_startup setting)
%
% Out:
%   Parameters : If Invoke was set to true, this is either the results of the function call or empty
%                (if the dialog was cancelled). If Invoke was set to false, this is either a struct
%                that is a valid input to the Function, or an empty value if cancel was clicked.
%
% Examples:
%   % bring up a configuration dialog for the given function
%   settings = arg_guidialog(@myfunction)
%
%   % bring up a config dialog with some pre-specified defaults
%   settings = arg_guidialog(@myfunction,'Parameters',{4,20,'test'})
%
%   % bring up a config dialog which displays only a subset of the function's arguments (in a particular order)
%   settings = arg_guidialog(@myfunction,'Subset',{'blah','xyz',[],'flag'})
%
%   % bring up a dialog, and invoke the function with the selected settings after the user clicks OK
%   settings = arg_guidialog(@myfunction,'Invoke',true)
%
%   % from within a function
%   args = arg_define(varargin, ...);
%   if nargin < 1
%       % optionally allow the user to enter arguments via a GUI
%       args = arg_guidialog;
%       % user clicked cancel?
%       if isempty(args), return; end
%   end
%
% See also:
%   arg_guidialog_ex, arg_guipanel, arg_define
%
%                                Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
%                                2010-10-24

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

global tracking;

if ~exist('func','var')
    % called with no arguments, from inside a function: open function dialog
    func = hlp_getcaller;
    varargin = {'Parameters',evalin('caller','varargin'),'Invoke',nargout==0};
end

if ischar(func)
    func = str2func(func); end

% parse arguments...
hlp_varargin2struct(varargin, ...
    {'params','Parameters','parameters'},{}, ...
    {'subset','Subset'},{}, ...
    {'dialogtitle','title','Title'}, [char(func) '()'], ...
    {'buttons','Buttons'},[], ...
    {'invoke','Invoke'},true, ...
    {'show_guru','ShowGuru'},tracking.gui.show_guru);
oldparams = params;

% obtain the argument specification for the function
rawspec = arg_report('rich', func, params); %#ok<*NODEF>

% extract a list of sub arguments...
if ~isempty(subset) && subset{1}==-1
    % user specified a set of items to *exclude*
    % convert subset to setdiff(all-arguments,subset)
    allnames = fieldnames(arg_tovals(rawspec));
    subset(1) = [];
    subset = allnames(~ismember(allnames,[subset 'arg_direct']));
end
[spec,subset] = obtain_items(rawspec,subset,'',show_guru);

% trim unnecessary blank margins at the beginning and end
while isempty(spec{1}) && isempty(subset{1})
    spec = spec(2:end);
    subset = subset(2:end);
end
while isempty(spec{end}) && isempty(subset{end})
    spec = spec(1:end-1);
    subset = subset(1:end-1);
end

% create an inputgui() dialog...
geometry = repmat({[0.6 0.35]},1,length(spec)+length(buttons)/2);
geomvert = ones(1,length(spec)+length(buttons)/2);
% turn the spec into a UI list...
uilist = {};
for k = 1:length(spec)

    s = spec{k};
    if isempty(s)
        uilist(end+1:end+2) = {{} {}};
    else
        if isempty(s.help)
            error(['Cannot display the argument ' subset{k} ' because it contains no description.']);
        else

            tag = subset{k};

            uilist{end+1} = {'Style','text', 'string',s.help{1}, 'fontweight','bold'};
            % depending on the type, we introduce different types of input widgets here...
            if iscell(s.range) && strcmp(s.type,'char')
                % string popup menu
                uilist{end+1} = {'Style','popupmenu', 'string',s.range,'value',find(strcmp(s.value,s.range)),'tag',tag};
            elseif strcmp(s.type,'logical')
                if iscell(s.range) % length(s.range)>1
                    % multiselect
                    uilist{end+1} = {'Style','listbox', 'string',s.range, 'value',find(ismember(s.range,s.value)),'tag',tag,'min',1,'max',100000};
                    geomvert(k) = min(3.5,length(s.range));
                else
                    % checkbox
                    uilist{end+1} = {'Style','checkbox', 'string','(set)', 'value',double(s.value),'tag',tag};
                end
            elseif strcmp(s.type,'char')
                % string edit
                uilist{end+1} = {'Style','edit', 'string', s.value,'tag',tag};
            else
                % expression edit
                if isinteger(s.value)
                    s.value = double(s.value); end
                uilist{end+1} = {'Style','edit', 'string', hlp_tostring(s.value),'tag',tag};
            end
            % append the tooltip string
            if length(s.help) > 1
                uilist{end} = [uilist{end} 'tooltipstring', regexprep(s.help{2},'\.\s+(?=[A-Z])','.\n')]; end
        end
    end

    if ~isempty(buttons) && k==buttons{1}
        % render a command button
        uilist(end+1:end+2) = {{} buttons{2}};
        buttons(1:2) = [];
    end
end

% invoke the GUI, obtaining a list of output values...
helptopic = char(func);
try
    if helptopic(1) == '@'
        fn = functions(func);
        tmp = struct2cell(fn.workspace{1});
        helptopic = class(tmp{1});
    end
catch
    disp('Cannot deduce help topic.');
end

[outs,dummy,okpressed] = inputgui('geometry',geometry, 'uilist',uilist,'helpcom',['env_doc ' helptopic], 'title',dialogtitle,'geomvert',geomvert); %#ok<ASGLU>

if ~isempty(okpressed)

    % remove blanks from the spec
    spec = spec(~cellfun('isempty',spec));
    subset = subset(~cellfun('isempty',subset));
    % turn the raw specification into a parameter struct (a non-direct one, since we will mess with
    % it)
    params = arg_tovals(rawspec);

    % for each parameter produced by the GUI...
    for k = 1:length(outs)
        s = spec{k}; % current specifier
        v = outs{k}; % current raw value
        % do type conversion according to spec
        if iscell(s.range) && strcmp(s.type,'char')
            v = s.range{v};
        elseif strcmp(s.type,'expression')
            v = eval(v);
        elseif strcmp(s.type,'logical')
            if length(s.range)>1
                v = s.range(v);
            else
                v = logical(v);
            end
        elseif strcmp(s.type,'char')
            % noting to do
        elseif ~isempty(v) && ischar(v)
            v = eval(v);
        end
        % assign the converted value to params struct...
        params = assign(params,subset{k},v);

    end

    % now send the result through the function to check for errors and obtain a values structure...
    params = arg_report('rich',func,{params});
    params = arg_tovals(params);

    % invoke the function, if so desired
    if ischar(func)
        func = str2func(func); end
    if invoke
        [varargout{1:nargout(func)}] = func(oldparams{:},params);
    else
        varargout = {params};
    end
else
    varargout = {[]};
end

% obtain a cell array of spec entries by name from the given specification
function [items,ids] = obtain_items(rawspec,requested,prefix,show_guru)
if ~exist('prefix','var')
    prefix = ''; end
items = {};
ids = {};
% determine what subset of (possibly nested) items is requested
if isempty(requested)
    % look for a special argument/property arg_dialogsel, which defines the standard dialog
    % representation for the given specification
    dialog_sel = find(cellfun(@(x)any(strcmp(x,'arg_dialogsel')),{rawspec.names}));
    if ~isempty(dialog_sel)
        requested = rawspec(dialog_sel).value; end
end
if isempty(requested)
    % empty means that all items are requested
    for k=1:length(rawspec)
        items{k} = rawspec(k);
        ids{k} = [prefix rawspec(k).names{1}];
    end
else
    % otherwise we need to obtain those items
    for k=1:length(requested)
        if ~isempty(requested{k})
            try
                [items{k},subid] = obtain(rawspec,requested{k});
            catch
                error(['The specified identifier (' prefix requested{k} ') could not be found in the function''s declared arguments.']);
            end
            ids{k} = [prefix subid];
        end
    end
end
% splice items that have children (recursively) into this list
for k = length(items):-1:1
    % special case: switch arguments are not spliced, but instead the argument that defines the
    % option popupmenu will be retained
    if ~isempty(items{k}) && ~isempty(items{k}.children) && (~iscellstr(items{k}.range) || isempty(requested))
        [subitems, subids] = obtain_items(items{k}.children,{},[ids{k} '.'],show_guru);
        if ~isempty(subitems)
            % and introduce blank rows around them
            items = [items(1:k-1) {{}} subitems {{}} items(k+1:end)];
            ids = [ids(1:k-1) {{}} subids {{}} ids(k+1:end)];
        end
    end
end

% remove items that cannot be displayed
retain = cellfun(@(x)isempty(x)||x.displayable&&(show_guru||~x.guru),items);
items = items(retain);
ids = ids(retain);

% remove double blank rows
empties = cellfun('isempty',ids);
items(empties(1:end-1) & empties(2:end)) = [];
ids(empties(1:end-1) & empties(2:end)) = [];

% obtain a spec entry by name from the given specification
function [item,id] = obtain(rawspec,identifier,prefix)
if ~exist('prefix','var')
    prefix = ''; end
% parse the . notation
dot = find(identifier=='.',1);
if ~isempty(dot)
    [head,rest] = deal(identifier(1:dot-1), identifier(dot+1:end));
else
    head = identifier;
    rest = [];
end
% search for the identifier at this level
names = {rawspec.names};
for k=1:length(names)
    if any(strcmp(names{k},head))
        % found a match!
        if isempty(rest)
            % return it
            item = rawspec(k);
            id = [prefix names{k}{1}];
        else
            % obtain the rest of the identifier
            [item,id] = obtain(rawspec(k).children,rest,[prefix names{k}{1} '.']);
        end
        return;
    end
end
error(['The given identifier (' head ') was not found among the function''s declared arguments.']);

% assign a field with dot notation in a struct
function s = assign(s,id,v)
% parse the . notation
dot = find(id=='.',1);
if ~isempty(dot)
    [head,rest] = deal(id(1:dot-1), id(dot+1:end));
    if ~isfield(s,head)
        s.(head) = struct(); end
    s.(head) = assign(s.(head),rest,v);
else
    s.(id) = v;
end


function c = abs(a)
	c = a;
end


function jHelp = bst_help(helpfile, isModal, figTitle, figSize, jHelp)
% BST_HELP: Display a help file in HTML format.
%
% USAGE:  jHelp = bst_help(helpfile, isModal=1, figTitle='Help', figSize=[510,590], jHelp=[new])
%         jHelp = bst_help(strHtml, ...)

% @=============================================================================
% 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, 2008-2012

% Initializations
import java.awt.*;
import javax.swing.*;

% ===== PARSE INPUTS =====
if (nargin < 5) || isempty(jHelp)
    jHelp = [];
end
if (nargin < 4) || isempty(figSize)
    figSize = [510,590];
end
if (nargin < 3) || isempty(figTitle)
    figTitle = 'Help';
end
if (nargin < 2) || isempty(isModal)
    isModal = 1;
end
if (helpfile(1) == '<')
    % Get HTML help string
    strHtml = helpfile;
    helpfile = [];
else
    % Figure title
    figTitle = [figTitle ': ' helpfile];
    % Get documents path
    helppath = bst_fullfile(bst_get('BrainstormDocDir'), 'help');
    % Get full filename
    helpfile = bst_fullfile(helppath, helpfile);
end

% ===== DIALOG INITIALIZATION =====
jBstFrame = bst_get('BstFrame');
% Create a new window
if isempty(jHelp)
    jFrame = java_create('javax.swing.JDialog', 'Ljava.awt.Frame;Ljava.lang.String;Z', jBstFrame, figTitle, isModal);
    jFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    jFrame.setPreferredSize(Dimension(figSize(1), figSize(2)));
    jPanelMain = jFrame.getContentPane();
% Re-use an existing window
else
    jFrame = jHelp.jFrame;
    jPanelMain = jFrame.getContentPane();
    jPanelMain.removeAll();
end

% === HELP TEXT AREA ===
% Create HTML viewer component
jTextHtml = JEditorPane();
jTextHtml.setEditable(false);
% Add an html editor kit
kit = javax.swing.text.html.HTMLEditorKit();
jTextHtml.setEditorKit(kit);
% Set content
if ~isempty(helpfile)
    jTextHtml.setPage(java.net.URL(['file:///' helpfile]));
else
    doc = kit.createDefaultDocument();
    jTextHtml.setDocument(doc);
    %jTextHtml.setContentType('text/html');
    jTextHtml.setText(strHtml);
end
% Callback when clicking on hyperlinks
java_setcb(jTextHtml, 'HyperlinkUpdateCallback', @HyperTextUpdate);
% Enclose in scroll panel
jScrollText = java_create('javax.swing.JScrollPane', 'Ljava.awt.Component;', jTextHtml);
jPanelMain.add(jScrollText, BorderLayout.CENTER);

% === FOOTER ===
% Add a "Close" button
jButtonClose = JButton('Close');
java_setcb(jButtonClose, 'ActionPerformedCallback', @CloseDialog);
jPanelMain.add(jButtonClose, BorderLayout.SOUTH);

% Display figure
jFrame.pack();
jFrame.setLocationRelativeTo(jFrame.getParent());
jFrame.setVisible(1);

% Return handle
jHelp.close  = @CloseDialog;
jHelp.jFrame = jFrame;

%% =================================================================================================
%  ====== CALLBACKS ================================================================================
%  =================================================================================================
%% ===== CLOSE DIALOG =====
    function CloseDialog(varargin)
        drawnow
        % If dialog was already closed
        if ~jFrame.isVisible()
            return
        end
        % Release mutex
        bst_mutex('release', 'Help');
        % Close dialog
        jFrame.dispose();
    end

%% ===== HYPERTEXT =====
    function HyperTextUpdate(h, ev)
        % If user clicked link
        if (ev.getEventType() == ev.getEventType().ACTIVATED)
            % Remove the 'Always on top' attribute
            jFrame.setAlwaysOnTop(0);
            % Display web page with Matlab browser
            web(char(ev.getURL()), '-browser');
        end
    end
end


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

    enumeration
        UseParallel('Compute Functions in Parallel',true)
        DoNotUseParallel('Compute Functions in Serial',false);
    end

    properties
        name char = '';
        optionVal(1,1) logical = true
    end

    methods
        function obj = PatternSearchUseParallelEnum(name, optionVal)
            obj.name = name;
            obj.optionVal = optionVal;
        end
    end

    methods(Static)
        function listBoxStr = getListBoxStr()
            m = enumeration('PatternSearchUseParallelEnum');
            [~,I] = sort({m.name});
            listBoxStr = {m(I).name};
        end

        function [ind, enum] = getIndForName(name)
            m = enumeration('PatternSearchUseParallelEnum');
            [~,I] = sort({m.name});
            m = m(I);
            ind = find(ismember({m.name},name),1,'first');
            enum = m(ind);
        end

        function [enum, ind] = getEnumForListboxStr(nameStr)
            m = enumeration('PatternSearchUseParallelEnum');
            ind = find(ismember({m.name},nameStr),1,'first');
            enum = m(ind);
        end
    end
end


function stat = test_ReadYaml()
% this function tests reading in the yaml file

stat.ok = 1;
stat.desc = '';
try
    %stat.test_ReadYaml_SimpleStructure = test_ReadYaml_SimpleStructure();
    %stat.test_ReadYaml_DateTime = test_ReadYaml_DateTime();
    fprintf('Testing read ');
    stat.test_RY_Matrices = test_RY_Matrices();
    fprintf('.');
    stat.test_RY_Whitespaces = test_RY_Whitespaces();
    fprintf('.');
    stat.test_RY_FloatingPoints = test_RY_FloatingPoints();
    fprintf('.');
    stat.test_RY_Indentation = test_RY_Indentation();
    fprintf('.');
    stat.test_RY_SequenceMapping = test_RY_SequenceMapping();
    fprintf('.');
    stat.test_RY_Simple = test_RY_Simple();
    fprintf('.');
    stat.test_RY_Time = test_RY_Time();
    fprintf('.');
    stat.test_RY_TimeVariants = test_RY_TimeVariants();
    fprintf('.');
    stat.test_RY_Import = test_RY_Import();
    fprintf('.');
    stat.test_RY_ImportDef = test_RY_ImportDef();
    fprintf('.');
    stat.test_RY_ImportNonex = test_RY_ImportNonex();
    fprintf('.');
    stat.test_RY_Inheritance = test_RY_Inheritance();
    fprintf('.');
    stat.test_RY_InheritanceMultiple = test_RY_InheritanceMultiple();
    fprintf('.');
    stat.test_RY_InheritanceLoop = test_RY_InheritanceLoop();
    fprintf('.');
    stat.test_RY_usecase_01 = test_RY_usecase_01();
    fprintf('.\n');

catch
    stat.ok = 0;
    stat.desc  = 'Program crash';
end

end

function result = PTH_PRIMITIVES()
    result = sprintf('Data%stest_primitives%s',filesep,filesep);
end

function result = PTH_IMPORT()
    result = sprintf('Data%stest_import%s',filesep,filesep);
end

function result = PTH_INHERITANCE()
    result = sprintf('Data%stest_inheritance%s',filesep,filesep);
end

function stat = test_RY_Matrices()
    stat.ok = 1;
    stat.desc = '';
    try
        ry = ReadYaml([PTH_PRIMITIVES() 'matrices.yaml']);
        tv = load([PTH_PRIMITIVES() 'matrices.mat']);
        if ~isequal(ry, tv.testval)
            stat.desc  = 'Wrong values loaded';
            stat.ok = 0;
        end;
    catch
        stat.ok = 0;
        stat.desc = 'Crash';
    end;
end

function stat = test_RY_FloatingPoints()
    stat.ok = 1;
    stat.desc = '';
    try
        ry = ReadYaml([PTH_PRIMITIVES() 'floating_points.yaml']);
        tv = load([PTH_PRIMITIVES() 'floating_points.mat']);
        if ~isequalwithequalnans(ry, tv.testval)
            stat.desc  = 'Wrong values loaded';
            stat.ok = 0;
        end;
    catch
        stat.ok = 0;
        stat.desc = 'Crash';
    end;
end

function stat = test_RY_Indentation()
    stat.ok = 1;
    stat.desc = '';
    try
        ry = ReadYaml([PTH_PRIMITIVES() 'indentation.yaml']);
        tv = load([PTH_PRIMITIVES() 'indentation.mat']);
        if ~isequal(ry, tv.testval)
            stat.desc  = 'Wrong values loaded';
            stat.ok = 0;
        end;
    catch
        stat.ok = 0;
        stat.desc = 'Crash';
    end;
end

function stat = test_RY_SequenceMapping()
    stat.ok = 1;
    stat.desc = '';
    try
        ry = ReadYaml([PTH_PRIMITIVES() 'sequence_mapping.yaml']);
        tv = load([PTH_PRIMITIVES() 'sequence_mapping.mat']);
        if ~isequal(ry, tv.testval)
            stat.desc  = 'Wrong values loaded';
            stat.ok = 0;
        end;
    catch
        stat.ok = 0;
        stat.desc = 'Crash';
    end;
end

function stat = test_RY_Simple()
    stat.ok = 1;
    stat.desc = '';
    try
        ry = ReadYaml([PTH_PRIMITIVES() 'simple.yaml']);
        tv = load([PTH_PRIMITIVES() 'simple.mat']);
        if ~isequal(ry, tv.testval)
            stat.desc  = 'Wrong values loaded';
            stat.ok = 0;
        end;
    catch
        stat.ok = 0;
        stat.desc = 'Crash';
    end;
end

function stat = test_RY_Time()
    stat.ok = 1;
    stat.desc = '';
    try
        ry = ReadYaml([PTH_PRIMITIVES() 'time.yaml']);
        tv = load([PTH_PRIMITIVES() 'time.mat']);
        if ~isequal(ry, tv.testval)
            stat.desc  = 'Wrong values loaded';
            stat.ok = 0;
        end;
    catch
        stat.ok = 0;
        stat.desc = 'Crash';
    end;
end

function stat = test_RY_TimeVariants()
    stat.ok = 1;
    stat.desc = '';
    try
        ry = ReadYaml([PTH_PRIMITIVES() 'time_variants.yaml']);
        tv = load([PTH_PRIMITIVES() 'time_variants.mat']);
        if ~isequal(ry, tv.testval)
            stat.desc  = 'Wrong values loaded';
            stat.ok = 0;
        end;
    catch
        stat.ok = 0;
        stat.desc = 'Crash';
    end;
end

function stat = test_RY_Import()
    stat.ok = 1;
    stat.desc = '';
    try
        ry = ReadYaml([PTH_IMPORT() 'import.yaml']);
        tv = load([PTH_IMPORT() 'import.mat']);
        if ~isequal(ry, tv.testval)
            stat.desc  = 'Wrong values loaded';
            stat.ok = 0;
        end;
    catch
        stat.ok = 0;
        stat.desc = 'Crash';
    end;
end

function stat = test_RY_ImportDef()
    stat.ok = 1;
    stat.desc = '';
    try
        ry = ReadYaml([PTH_IMPORT() 'import_def.yaml']);
        tv = load([PTH_IMPORT() 'import_def.mat']);
        if ~isequal(ry, tv.testval)
            stat.desc  = 'Wrong values loaded';
            stat.ok = 0;
        end;
    catch
        stat.ok = 0;
        stat.desc = 'Crash';
    end;
end

function stat = test_RY_ImportNonex()
    stat.ok = 0;
    stat.desc = 'Did not end with any exception.';
    try
        try
            ry = ReadYaml([PTH_IMPORT() 'import_nonex.yaml'],1);
        catch ex
            if strcmp(ex.identifier, 'MATLAB:MATYAML:FileNotFound')
                stat.desc = '';
                stat.ok = 1;
            else
                rethrow(ex);
            end;
        end;

    catch
        stat.ok = 0;
        stat.desc = 'Crash';
    end;
end

function stat = test_RY_Inheritance()
    stat.ok = 1;
    stat.desc = '';
    try
        ry = ReadYaml([PTH_INHERITANCE() 'inheritance.yaml']);
        tv = load([PTH_INHERITANCE() 'inheritance.mat']);
        if ~isequal(ry, tv.testval)
            stat.desc  = 'Wrong values loaded';
            stat.ok = 0;
        end;
    catch
        stat.ok = 0;
        stat.desc = 'Crash';
    end;
end

function stat = test_RY_InheritanceMultiple()
    stat.ok = 1;
    stat.desc = '';
    try
        ry = ReadYaml([PTH_INHERITANCE() 'inheritance_multiple.yaml']);
        tv = load([PTH_INHERITANCE() 'inheritance_multiple.mat']);
        if ~isequal(ry, tv.testval)
            stat.desc  = 'Wrong values loaded';
            stat.ok = 0;
        end;
    catch
        stat.ok = 0;
        stat.desc = 'Crash';
    end;
end

function stat = test_RY_InheritanceLoop()
    stat.ok = 0;
    stat.desc = 'Did not end with any exception.';
    try
        try
            ry = ReadYaml([PTH_INHERITANCE() 'inheritance_loop.yaml']);
        catch ex
            if strcmp(ex.identifier, 'MATLAB:MATYAML:inheritedtwice')
                stat.desc = '';
                stat.ok = 1;
            else
                rethrow(ex);
            end;
        end;

    catch
        stat.ok = 0;
        stat.desc = 'Crash';
    end;
end

function stat = test_RY_Whitespaces()
    stat.ok = 1;
    stat.desc = '';
    try
        ry = ReadYaml([PTH_PRIMITIVES() 'whitespaces.yaml']);
        if ~isfield(ry,'ImageFile') || ~isfield(ry,'ContoursCount')
            stat.desc  = 'Wrong values loaded';
            stat.ok = 0;
        end;
    catch
        stat.ok = 0;
        stat.desc = 'Crash';
    end;
end

function stat = test_RY_usecase_01()
    stat.ok = 1;
    stat.desc = '';
    try
        ry = ReadYaml([PTH_PRIMITIVES() 'usecase_struct_01.yaml']);
        tv = load([PTH_PRIMITIVES() 'usecase_struct_01.mat']);
        if ~isequalwithequalnans(ry, tv.testval)
            stat.desc  = 'Wrong values loaded';
            stat.ok = 0;
        end;
    catch
        stat.ok = 0;
        stat.desc = 'Crash';
    end;
end

function stat = test_ReadYaml_SimpleStructure()

stat.ok = 1;
stat.desc = '';
try
    s = ReadYaml('simple.yaml');

    ages = [s.age];

    if not(isequal([33 27], ages))  || not(all(ismember({'John Smith', 'Mary Smith'}, {s.name}) ))
        stat.desc  = ' Wrong values loaded';
        stat.ok = 0;
    end

catch
       stat.desc  = 'Program crash';
       stat.ok = 0;
end

end

function stat = test_ReadYaml_DateTime()

stat.ok = 1;
stat.desc = '';
try
    s = ReadYaml('time.yaml');

    if ~isa(s.Data.B1_S_SW{1},'DateTime')
        stat.desc  = ' Wrong data type of datetick';
        stat.ok = 0;
    end
    if isa(s.Data.B1_S_SW{2},'DateTime')
        stat.desc  = ' Wrong data type of datetick';
        stat.ok = 0;
    end
catch
       stat.desc  = 'Program crash';
       stat.ok = 0;
end
end


function newPrevPermute = addDimPrevPermute(prevPermute, dimLabel, dimNumber)
    newPrevPermute = prevPermute;

    for iDim = 1:size(prevPermute, 2)
        dimensionNumber = prevPermute{1, iDim};
        if(dimensionNumber >= dimNumber)
            newPrevPermute{1, iDim} = dimensionNumber + 1;
        end
    end
    newIndex = size(prevPermute, 2) + 1;
    newPrevPermute{1, newIndex} = dimNumber;
    newPrevPermute{2, newIndex} = dimLabel;
end


function p = new_parpool(number)

    if ~exist('number', 'var')
        number = cpu_cores();
    end

    if ~isempty(gcp('nocreate'))
        delete(gcp);
    end
    p = parpool(number);
end