function obj = updateColorbar(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 get colorbar data');
    end

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

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

    %-variable initialization-%
    if isHG2
        outlineColor = [0 0 0];
    else
        if colorbarData.Position(4) > colorbarData.Position(3)
            outlineColor = 255*colorbarData.YColor;
        else
            outlineColor = 255*colorbarData.XColor;
        end
    end

    outlineColor = sprintf('rgb(%f,%f,%f)', outlineColor);
    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 placement-%
    colorbar.x = colorbarData.Position(1);
    colorbar.y = colorbarData.Position(2);
    colorbar.len = colorbarData.Position(4);
    colorbar.thickness = colorbarData.Position(3);

    colorbar.xpad = obj.PlotlyDefaults.MarginPad;
    colorbar.ypad = obj.PlotlyDefaults.MarginPad;
    colorbar.xanchor = 'left';
    colorbar.yanchor = 'bottom';

    colorbar.outlinewidth = lineWidth;
    colorbar.outlinecolor = outlineColor;
    colorbar.exponentformat = obj.PlotlyDefaults.ExponentFormat;
    colorbar.thicknessmode = 'fraction';
    colorbar.lenmode = 'fraction';

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

    %-tick setings-%
    colorbar.tickcolor = outlineColor;
    colorbar.tickfont.color = outlineColor;
    colorbar.tickfont.size = colorbarData.FontSize;
    colorbar.tickfont.family = matlab2plotlyfont(colorbarData.FontName);
    colorbar.ticklen = tickLength;
    colorbar.tickwidth = lineWidth;

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

    %-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

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

    %-STANDARDIZE UNITS FOR TITLE-%
    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

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

    %-colorbar title settings-%
    isTitle = true;

    if ~isempty(colorbarTitleData.String)
        titleString = colorbarTitleData.String;
        titleInterpreter = colorbarTitleData.Interpreter;

        if colorbarTitleData.Rotation == 90
            titleSide = 'right';
        else
            titleSide = 'top';
        end

        titleFontSize = 1.20 * colorbarTitleData.FontSize;
        titleFontColor = sprintf('rgb(%f,%f,%f)', 255*colorbarTitleData.Color);
        titleFontFamily = matlab2plotlyfont(colorbarTitleData.FontName);

    elseif ~isempty(colorbarXLabelData.String)
        titleString = colorbarXLabelData.String;
        titleInterpreter = colorbarXLabelData.Interpreter;

        titleSide = 'right';
        titleFontSize = 1.20 * colorbarXLabelData.FontSize;
        titleFontColor = sprintf('rgb(%f,%f,%f)', 255*colorbarXLabelData.Color);
        titleFontFamily = matlab2plotlyfont(colorbarXLabelData.FontName);

    elseif ~isempty(colorbarYLabelData.String)
        titleString = colorbarYLabelData.String;
        titleInterpreter = colorbarYLabelData.Interpreter;

        titleSide = 'bottom';
        titleFontSize = 1.20 * colorbarYLabelData.FontSize;
        titleFontColor = sprintf('rgb(%f,%f,%f)', 255*colorbarYLabelData.Color);
        titleFontFamily = matlab2plotlyfont(colorbarYLabelData.FontName);

    else
        isTitle = false;
    end

    if isTitle
        colorbar.title = parseString(titleString, titleInterpreter);
        colorbar.titleside = titleSide;
        colorbar.titlefont.size = titleFontSize;
        colorbar.titlefont.color = titleFontColor;
        colorbar.titlefont.family = titleFontFamily;
    end

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

    %-REVERT UNITS FOR TITLE-%
    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

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

    %-tick labels-%
    tickValues = colorbarData.Ticks;
    tickLabels = colorbarData.TickLabels;
    showTickLabels = true;

    if isHG2
        if isempty(tickValues)
            showTickLabels = false;
            colorbar.ticks = '';

        elseif isempty(tickLabels)
            colorbar.tickvals = tickValues;

        else
            colorbar.tickvals = tickValues;
            colorbar.ticktext = tickLabels;
        end

        if showTickLabels
            colorbar.showticklabels = showTickLabels;

            switch colorbarData.AxisLocation
                case 'in'
                    colorbar.ticklabelposition = 'inside';
                case 'out'
                    colorbar.ticklabelposition = 'outside';
            end

            switch colorbarData.TickDirection
                case 'in'
                    colorbar.ticks = 'inside';
                case 'out'
                    colorbar.ticks = 'outside';
            end

        end

    else
        colorbar = setTicksNotHG2(colorbar, colorbarData);
    end

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

    %-colorbar bg-color-%
    if ~isHG2
        if ~ischar(colorbarData.Color)
            bgColor = 255*colorbarData.Color;
        else
            bgColor = 255*figureData.Color;
        end

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

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

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

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

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

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

    %-------------------------------------------------------------------------%
end

function colorbar = setTicksNotHG2(colorbar, colorbarData)
    verticalOrientation = colorbar.len > colorbar.thickness;

    if verticalOrientation
        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


% MATLAB xUnit Test Framework
% Version 3.0.1 (R2010a) 16-Jun-2010
%
% Running Unit Tests
%   runtests                  - Run unit tests
%
% Writing Unit Tests
%   assertElementsAlmostEqual - Assert floating-point array elements almost equal
%   assertEqual               - Assert that inputs are equal
%   assertFilesEqual          - Assert that two files have the same content
%   assertExceptionThrown     - Assert that specified exception is thrown
%   assertFalse               - Assert that input condition is false
%   assertTrue                - Assert that input condition is true
%   assertVectorsAlmostEqual  - Assert floating-point vectors almost equal in norm sense
%   initTestSuite             - Utility script used for subfunction-based tests
%
% Framework Classes
%   CommandWindowTestRunDisplay - Print test suite results to command window
%   VerboseCommandWindowTestRunDisplay - Print verbose test suite results to command window
%   FunctionHandleTestCase    - Test case based on a function handle
%   TestCase                  - Class defining interface for test cases
%   TestCaseInDir             - Test case requiring temporary directory change
%   TestCaseWithAddPath       - Test case requiring temporary path modification
%   TestComponent             - Abstract base class for TestCase and TestSuite
%   TestComponentInDir        - Test component requiring temporary directory change
%   TestLogger                - Collect data (silently) from running test suite
%   TestRunMonitor            - Abstract base class for monitoring test suite
%   TestSuite                 - Collection of TestComponent objects
%   TestSuiteInDir            - Test suite requiring temporary directory change

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


classdef DesignVarMonitor_LevelSet_3D < DesignVarMonitor_LevelSet

    properties (Access = protected)
        unfittedType = 'BOUNDARY'
        meshIncludeBoxContour = true
    end

end


benchmarkDir = 'data/MOT16/train/';
allMets = evaluateTracking('c5-train.txt', 'results/', benchmarkDir);


function create_cache(cache_name)
  % CREATE_CACHE Save the workspace of the caller function using the provided
  % cache_name, possibly overwriting it.
  %
  % create_cache(cache_name)
  %
  % Inputs:
  %   cache_name  path to .mat cache file
  %
  % See also: find_cache

  if isunix
    % get a list of current variables in this scope, this is the input "state"
    variables = evalin('caller','who');
    variable_names = sprintf('^%s$|',variables{:});
    save_cmd = sprintf('save(''%s'',''-regexp'',''%s'');',cache_name,variable_names);
    evalin('caller',save_cmd);
  end
end


function ft_compile_forward(force)
% FT_COMPILE_FORWARD  This script/function is used for compiling the various MEX files used in FieldTrip 'forward'
%
% Please note that this script does NOT set up your MEX environment for you, so in case
% you haven't selected the C compiler on Windows yet, you need to type 'mex -setup' first
% to choose either the Borland or Microsoft compiler. If you want to use MinGW, you also
% need to install Gnumex (http://gnumex.sourceforget.net), which comes with its own
% procedure for setting up the MEX environment.

% The logic in this script is to first build a list of files that actually need compilation for the
% particular platform that Matlab is running on, and then to go through that list.
% Functions are added to the list by giving their destination directory and (relative to that) the
% name of the source file (without the .c). Optionally, you can specify a list of platform this
% file needs to be compiled on only, and a list of platforms where you don't compile it on.
% Finally, you can give extra arguments to the MEX command, e.g., for including other c-sources or
% giving compiler flags.
% (C) 2010 S. Klanke

if nargin<1
   force=false;
end

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

L = [];
L = add_mex_source(L,'private','plgndr');
L = add_mex_source(L,'private','meg_leadfield1');
L = add_mex_source(L,'private','lmoutr',[],[],'geometry.c -I.');
L = add_mex_source(L,'private','solid_angle',[],[],'geometry.c -I.');
L = add_mex_source(L,'private','ptriproj',[],[],'geometry.c -I.');

oldDir = pwd;
[baseDir, myName] = fileparts(mfilename('fullpath'));
try
  compile_mex_list(L, baseDir, force);
catch me
  cd(oldDir);
  rethrow(me);
end
cd(oldDir);


%PLAYREC Multichannel non-blocking audio recording and playback
%
% Run:
%     playrec('help')
%
% Tho get the actual help.
%
% PLAYREC is a MEX file which means it has to be compiled in order to work.
% Please see INSTALL-Matlab or INSTALL-Octave for details.
%
% Originally created by Robert Humphrey (see license_playrec.txt) and
% currently hosted at https://github.com/PlayrecForMatlab/playrec
% For further details visit the webpage or run playrec('about') and
% playrec('overview')
%
% This is however a sightly modified version doing an on-the-fly
% sample rate conversion if the target sample rate is not supported by
% the device.
%


function [ ret ] = setPin12Off( t_Kuka )
%% About:
% This function is used to set off the Pin 12 on the KUKA iiwa 7 R 800.

%% Syntax:
% [ ret ] = setPin12Off( t_Kuka )

%% Arreguments:
% t_Kuka: is the TCP/IP connection

%% Return value:
% ret: a boolean variable
% true: if the message is treated successfully
% false: if an error has happened

% Copy right, Mohammad SAFEEA, 3rd of May 2017

theCommand='pin12off';
fprintf(t_Kuka, theCommand);
message=fgets(t_Kuka);
ret=checkAcknowledgment(message);
end


function InsertHeader(varargin)
% InsertHeader - Adds a template to the top of current file in editor for documentation.
%
% Syntax: InsertHeader(varargin)
% varargin - optional input of full file name
%   Example 1:  InsertHeader adds header to top of currently selected file in
%   editor
%   Example 2: InsertHeader('InsertHeader') added the current header information to this
%   file. NOTE:  THIS CANNOT BE UNDONE!  THE FIRST TIME YOU USE THIS, PLEASE
%   HAVE A BACK UP COPY OF THE FILE IN CASE IT MAKES A MISTAKE.
%   Custom defined headers can be created in the subfunction defined at
%   the end of the file.  I wish to express thanks to the authors of tedit.m and
%   newfcn.m which helped me to create this routine.
%  See also:  tedit, newfcn
%
% Subfunctions: EditorCurrentFile, parseForSubFcns, insertHeaderTemplateFile

% AUTHOR    : Dan Kominsky
% Copyright 2011  Prime Photonics, LC.
%%

if nargin==1
	CurrentFile=varargin{1};
else
	% Call subfunction to determine the current file:
	[CurrentFile]=EditorCurrentFile;
end
% Ask to make sure I am going to add the header to the correct file
resp=questdlg(['Add Header to file: ' CurrentFile '?'],'Header Query');
if ~strcmpi(resp,'Yes'),return;end;

if verLessThan('matlab','7.12.0') % Matlab interface changed with 7.12.0
  old_style = true;
% Define the handle for the java commands:
edhandle=com.mathworks.mlservices.MLEditorServices;
% Save the current document so changes aren't lost
edhandle.saveDocument(CurrentFile);
[PATH,FILENAME]=fileparts(CurrentFile);

% Load the existing file
rawText=char(edhandle.builtinGetDocumentText(CurrentFile));

else
  old_style = false;
  % Define the handle for the java commands:
  editorObject = matlab.desktop.editor.getActive;
  % Save the current document so changes aren't lost
  editorObject.save;
  % Load the text:
  rawText=editorObject.Text;

  [PATH,FILENAME]=fileparts(CurrentFile);

end

% For some reason the previous command replaces (at least on windows) each
% carraige return with a carraige return/line feed combo.  The next line removes
% the double spacing.   It may not be necessary on other platforms!
% In some cases it might use just the char(10), so convert that to char(13);
currentText=regexprep(rawText,[char(13) char(10)],char(13));
currentText=regexprep(currentText,char(10),char(13));

% Check to find the true end of the first line.  If it is a continuation, keep
% going until the function definition is ended.
ellipsisTest=true;
firstLine='';
remainder=currentText;
while ellipsisTest
	[tmpfirstLine,remainder]=strtok(remainder,char(13));
	firstLine=[firstLine,char(13),tmpfirstLine];
	if sum(firstLine(end-4:end)==46)>=3
		ellipsisTest=true;
	else
		ellipsisTest=false;
	end
	pause(0.01)
end

funcLabel=any(regexp(firstLine,'function'));
syntaxStr={};
inputs={};
outputs={};
count=1;
if funcLabel
	syntaxStr=regexprep(firstLine,'function','');
	hasEquals=any(regexp(syntaxStr,'='));
	if hasEquals
	[beforeEq,afterEq]=strtok(strtrim(syntaxStr),'=');
	else
		beforeEq='';afterEq=strtrim(syntaxStr);
	end
	tmpoutputs=regexp(beforeEq,'(\w+)','tokens');
	for n=1:numel(tmpoutputs)
		outputs{n}=char(tmpoutputs{n});
	end
	tmpinputs=regexp(afterEq,'(\w+)','tokens');
	funcname=char(tmpinputs{1});
	for n=2:numel(tmpinputs)
		inputs{n-1}=char(tmpinputs{n});
	end
end

  subFcnName=parseForSubFcns(CurrentFile);

% insertHeaderTemplateFile contains the text to be added into the file
tmpl=insertHeaderTemplateFile(FILENAME,inputs,outputs,syntaxStr,subFcnName);

% Convert to a string
parseIn = sprintf('%s\n',tmpl{:});

% Concatenate the firstline (function definition), header, and body:
concatenatedText=strcat(firstLine,parseIn,remainder);
% Strip any extra leading carraige returns:
while (double(concatenatedText(1)))==13 || (double(concatenatedText(1)))==10
	concatenatedText(1)=[];
end

  if old_style
% Close the file:
edhandle.closeDocument(CurrentFile);
% Open and OVERWRITE the file
fid=fopen(CurrentFile,'wt');
fprintf(fid,'%s\n',concatenatedText);
fclose(fid);
% Reopen the file to the begining.
edhandle.openDocumentToLine(CurrentFile,1);
  else
    editorObject.save;
    fid=fopen(CurrentFile,'wt');
    fprintf(fid,'%s\n',concatenatedText);
    fclose(fid);
    editorObject.reload;
  end
end

% ------------------------
function [CurFile, varargout] = EditorCurrentFile

  if verLessThan('matlab','7.12.0') % Matlab interface changed with 7.12.0
% Define the handle for the set of java commands:
desktopHandle=com.mathworks.mlservices.MatlabDesktopServices.getDesktop;
% Determine the last selected document in the editor:
lastDocument=desktopHandle.getLastDocumentSelectedInGroup('Editor');
% Strip off the '*' which indicates that it has been modified.
CurFile=strtok(char(desktopHandle.getTitle(lastDocument)),'*');

if nargout>1
	varargout{1}=lastDocument;
end
  else
    editorObject = matlab.desktop.editor.getActive;
    CurFile = editorObject.Filename;
  end

end

function [functions varargout]=parseForSubFcns(myFunc)
  if exist(myFunc,'file')
    % We have a full path to the file
    str= mlintmex('-calls',myFunc);
  else
    % File is on the path, and we must find it:
    str= mlintmex('-calls',which(myFunc));
  end
  [a,b,c,d,e] = regexp(str,'([NS])\d* (\d+) (\d+) (\w+)\n');
  if isempty(e)
    functions = [];varargout{1}=[];
    return
  end
  if nargout < 1
    sprintf('Sub/Nest\t\tLine#\t\tCol#\t\tName')
    for iFcn = 1:numel(e)
      S=sprintf('%8s\t\t%6s\t\t%6s\t\t%s',e{iFcn}{1:4});
      disp(S)
    end
  else
    functions = [];
    for iFcn = 1:numel(e)
      S=sprintf('%s, ',e{iFcn}{4});
      functions = [functions S];
      cellList{iFcn} = e{iFcn}{4};
    end
    functions(end-1:end) = [];
    if nargout>1
      varargout{1} = cellList;
    end
  end
end

function tmpl=insertHeaderTemplateFile(FILENAME,varargin)
% insertHeaderTemplateFile Contains the header which is automatically inserted
%   tmpl = insertHeaderTemplateFile(FILENAME)
%
%   Example
%   insertHeaderTemplateFile('currentFile.m') returns the cell array of strings
%   which is inserted into file headers.
%
%   See also

% AUTHOR    : Dan Kominsky
  % Copyright 2006 Prime Photonics, LC.
%%
applyComment=@(x)['% ' x ' - Description'];
commaPad=@(x)[x{:}, ', '];

if nargin>1
	inputLines=cellfun(applyComment,varargin{1}','UniformOutput',false);
else
	inputLines='';
end
if nargin>2
	outputLines=cellfun(applyComment,varargin{2}','UniformOutput',false);
else
	outputLines='';
end
if nargin>3
  synt_str_raw = strtrim(varargin{3});
  synt_str_eols = regexprep(synt_str_raw,'\n','\n%');
  synt_str_adj = regexprep(synt_str_eols,'\r','\r%');
	syntaxStr=['% Syntax: ' synt_str_adj];
else
	syntaxStr='';
end
if nargin>4
    subFcns = ['% Subfunctions: ' varargin{4}];
else
	subFcns='% Subfunctions: none';
end
topLines={ ...
	''
  ['% ' FILENAME  ' - One line description of what the function or script performs (H1 line)']
	'% Optional file header info (to give more details about the function than in the H1 line)'};
midLines=[syntaxStr; inputLines;outputLines];
bottomLines={	'%   Example'
	'%  Line 1 of example '
	'%'};
authorLines={...
	'%   See also: '
	''
	'% AUTHOR    : Jebediah Obediah'
	['% Copyright ' datestr(now,'yyyy') '  XYZ Corp.']
	'%%'};

tmpl=[topLines;midLines;bottomLines;subFcns;authorLines];
end


classdef PTKContext
    % PTKContext. An enumeration used to specify a region of interest
    %
    %     Contexts are used in relation to PTKImageTemplate to request a template
    %     image for a particular region of interest.
    %
    %
    %     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.
    %

    enumeration
        OriginalImage,  % The full image
        LungROI,        % A region containing the lung and airways
        LeftLungROI,    % A region containing the left lung
        RightLungROI,   % A region containing the right lung

        Lungs,          % Left and right lung masks after removal of airways

        LeftLung,       % Left lung mask
        RightLung,      % Right lung mask

        RightUpperLobe,
        RightMiddleLobe,
        RightLowerLobe,
        LeftUpperLobe,
        LeftLowerLobe,

        % Right lung segments
        R_AP,
        R_P,
        R_AN,
        R_L,
        R_M,
        R_S,
        R_MB,
        R_AB,
        R_LB,
        R_PB,

        % Left lung segments
        L_APP,
        L_APP2,
        L_AN,
        L_SL,
        L_IL,
        L_S,
        L_AMB,
        L_LB,
        L_PB

    end

end


function h = imcredit(s)
%IMCREDIT Display image credit string
%   H = IMCREDIT(S) displays the string S at the bottom right of the image
%   displayed in the current axes.  S is wrapped to 30 characters and
%   displayed in a light gray small font.  H is the handle of the text
%   object created by IMCREDIT.
%
%   This function assumes the typical display created using imshow: a
%   single axes containing a single image, with no axes ticks or tick
%   labels.  The credit string is placed just below the bottom edge of the
%   axes box.
%
%   Note: IMCREDIT requires LINEWRAP, which is available on the MATLAB
%   Central File Exchange.
%
%   Example
%       imshow(rand(256,256))
%       imcredit('Image courtesy of Joe and Frank Hardy, MIT, 1993')
%
%   Possible enhancements:
%   * Adjust credit string position if axes tick labels are visible
%   * Adjust text color based on figure background color
%   * Additional syntaxes, including linewrap and text property options
%
%   See also LINEWRAP.

% Steven L. Eddins
% $Revision: 1.2 $  $Date: 2006/02/07 02:39:05 $

ax_handle = gca;
x = getRight(ax_handle);
y = getBottom(ax_handle);
text_handle = text(x, y, linewrap(s, 30), ...
   'VerticalAlignment', 'top', ...
   'HorizontalAlignment', 'right', ...
   'FontSize', 7, ...
   'Color', [.5 .5 .5]);

if nargout > 0
   h = text_handle;
end

%==========================================================================
function right = getRight(ax_handle)
% right = getRight(ax_handle) returns the x-coordinate, in axes data space,
% of the right edge of the axes box.

x_limits = get(ax_handle, 'XLim');
if strcmp(get(ax_handle, 'XDir'), 'normal')
   right = x_limits(2);
else
   right = x_limits(1);
end
%--------------------------------------------------------------------------

%==========================================================================
function bottom = getBottom(ax_handle)
% bottom = getBottom(ax_handle) returns the y-coordinate, in axes data
% space, of the bottom edge of the axes box.
y_limits = get(ax_handle, 'YLim');
if strcmp(get(ax_handle, 'YDir'), 'normal')
   bottom = y_limits(1);
else
   bottom = y_limits(2);
end
%--------------------------------------------------------------------------


function tt() % autogenerated function wrapper
 % turned into function by Celso G Reyes 2017

ZG=ZmapGlobal.Data; % used by get_zmap_globals
report_this_filefun(mfilename('fullpath'));

catSave =...
    [ 'zmap_message_center.set_info(''Save Data'',''  '');think;',...
    '[file1,path1] = uigetfile(fullfile(ZmapGlobal.Data.data_dir, ''*.mat''), ''Earthquake Datafile'');end;',...
    'if length(file1) > 1 , sapa2 = [''save '' path1 file1 '' a faults main mainfault coastline  ''],',...
    'eval(sapa2) ,end, done'];

end


function matRad_compileOmpMCInterface(dest,omcFolder)
% Compiles the ompMC interface (integrated as submodule)
%
% call
%   matRad_compileOmpMCInterface()
%   matRad_compileOmpMCInterface(dest)
%   matRad_compileOmpMCInterface(dest,sourceFolder)
%
% input:
%   dest:           (optional) destination for mex file. Default: location
%                   of this file
%   sourceFolder:   (optional) path to ompMC . Default assumes its checked
%                   out in the submodules folder of matRad
%
% References
%
%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Copyright 2020 the matRad development team.
%
% This file is part of the matRad project. It is subject to the license
% terms in the LICENSE file found in the top-level directory of this
% distribution and at https://github.com/e0404/matRad/LICENSES.txt. No part
% of the matRad project, including this file, may be copied, modified,
% propagated, or distributed except according to the terms contained in the
% LICENSE file.
%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

matRad_cfg = MatRad_Config.instance();

env = matRad_getEnvironment();

if nargin < 1
    dest = fileparts(mfilename('fullpath'));
end

if nargin < 2
    omcFolder = [matRad_cfg.matRadRoot filesep 'submodules' filesep 'ompMC'];
end

sourceFolder = [omcFolder filesep 'src'];
interfaceFolder = [omcFolder filesep 'ucodes' filesep 'omc_matrad'];

mainFile = [interfaceFolder filesep 'omc_matrad.c'];

addFiles = {'ompmc.c','omc_utilities.c','omc_random.c'};
addFiles = cellfun(@(f) fullfile(sourceFolder,f),addFiles,'UniformOutput',false);

addFiles = strjoin(addFiles,' ');

if exist ('OCTAVE_VERSION','builtin')
    ccName = evalc('mkoctfile -p CC');
else
    myCCompiler = mex.getCompilerConfigurations('C','Selected');
    ccName = myCCompiler.ShortName;
end

%These settings have only been tested for MSVC and g++. You may need to adapt for other compilers
if ~isempty(strfind(ccName,'MSVC')) %Not use contains(...) because of octave
    flags{1,1} = 'COMPFLAGS';
    flags{1,2} = '/openmp';
    flags{2,1} = 'OPTIMFLAGS';
    flags{2,2} = '/O2';
else
    flags{1,1} = 'CFLAGS';
    flags{1,2} = '-std=gnu99 -fopenmp -O3';
    flags{2,1} = 'LDFLAGS';
    flags{2,2} = '-fopenmp';

end

includestring =  ['-I' sourceFolder];

flagstring = '';

%For Octave, the flags will be set in the environment, while they
%will be parsed as string arguments in MATLAB
for flag = 1:size(flags,1)
    if strcmp(env,'OCTAVE')
        preFlagContent = evalc(['mkoctfile -p ' flags{flag,1}]);
        if ~isempty(preFlagContent)
            preFlagContent = preFlagContent(1:end-1); %Strip newline
        end
        newContent = [preFlagContent ' ' flags{flag,2}];
        setenv(flags{flag,1},newContent);
        matRad_cfg.dispDebug('Set compiler flag %s to %s\n',flags{flag,1},newContent);
    else
        flagstring = [flagstring flags{flag,1} '="$' flags{flag,1} ' ' flags{flag,2} '" '];
    end
end

mexCall = ['mex -largeArrayDims ' flagstring ' ' includestring ' ' mainFile ' ' addFiles];
matRad_cfg.dispDebug('Compiler call: %s\n',mexCall);

currDir = pwd;
cd(dest);
eval(mexCall);
cd(currDir);
end


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Copyright 2014 National Renewable Energy Laboratory and National
% Technology & Engineering Solutions of Sandia, LLC (NTESS).
% Under the terms of Contract DE-NA0003525 with NTESS,
% the U.S. Government retains certain rights in this software.
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% 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.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function blkStruct = slblocks

Browser.Library='PTOSim_Lib';
Browser.Name='PTO-Sim';
Browser.Choice=1; % Option to generate the required repository info in memory.

blkStruct.Browser=Browser;


function [result_for_kitti_eval] = generateDataForKITTIEvaluationFromFile(result_for_kitti_eval, fno, dnos, detections)

    sz = size(result_for_kitti_eval,1);

    for i = 1:length(dnos)

        result_for_kitti_eval(sz+i, 1)   = fno;
        result_for_kitti_eval(sz+i, 2)   = dnos(i);
        result_for_kitti_eval(sz+i, 3:6) = detections{fno}(i, 1:4);
        result_for_kitti_eval(sz+i, 7)   = 0.9;

    end

end


%% HILBERT_BATCH_LOCAL uses the BATCH command to run the HILBERT code locally.
%
%  Discussion:
%
%    The HILBERT code is a function, so first we must write a script
%    called HILBERT_SCRIPT that runs the function.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    22 May 2012
%
%  Author:
%
%    John Burkardt
%
  clear

  workers = 3;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'HILBERT_BATCH_LOCAL\n' );
  fprintf ( 1, '  Run HILBERT_SCRIPT locally.\n' );
%
%  The BATCH command sends the script for execution.
%
  my_job = batch ( 'hilbert_script', ...
    'Configuration', 'local', ...
    'CaptureDiary', true, ...
    'FileDependencies', { 'hilbert_fun' }, ...
    'matlabpool', workers );
%
%  WAIT pauses the MATLAB session til the job completes.
%
  wait ( my_job );
%
%  DIARY displays any messages printed during execution.
%
  diary ( my_job );
%
%  The LOAD command makes the script's workspace available.
%  The script created the array "a", so let's ask for its size
%  just to show that it really was created.
%
  load ( my_job );

  size ( a )
%
%  DESTROY cleans up data about the job we no longer need.
%
  destroy ( my_job );

  fprintf ( 1, '\n' );
  fprintf ( 1, 'HILBERT_BATCH_LOCAL\n' );
  fprintf ( 1, '  Normal end of execution.\n' );


function assert(condition,message)

if ~condition
  if nargin < 2
    error('Assertion failed');
  end
  error(message)
end


function print_error_red(msg, tab_before)
% show error in red

    if nargin < 1
        disp('usage: print_error_red(msg)');
        return;
    end

    if nargin < 2
        tab_before = 1;
    end

    if ~iscell(msg)
        disp('error message must be a cell array of strings.');
        return;
    end

    % make sure we have a column vector
    if size(msg, 1) > size(msg, 2)
        msg = msg';
    end

    %% create a fake error output
    if tab_before == 1
        for i = 1 : numel(msg)
            fprintf(2, '\t %s \n', msg{1, i});
        end
    else
        for i = 1 : numel(msg)
            fprintf(2, ' %s \n', msg{1, i});
        end
    end

end
%% EOF


function gui_edit_channelflag( DataFile )
% GUI_EDIT_CHANNELFLAG: Edit the ChannelFlag array of a MEG/EEG recordings file, with the associated Channel file.
%
% USAGE: gui_edit_channelflag( DataFile )

% @=============================================================================
% 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-2018

global GlobalData;
ChannelFile = [];

%% ===== LOAD CHANNEL/DATA FILE =====
% Progress bar
bst_progress('start', 'Channel editor', 'Initialization...');
% Get the DataFile in the Brainstorm database
[sStudy, iStudy] = bst_get('DataFile', DataFile);
% Try to find file in stat files
if isempty(sStudy)
    [sStudy, iStudy] = bst_get('StatFile', DataFile);
end
% If DataFile in database
if ~isempty(sStudy)
    % Get channel file
    Channel = bst_get('ChannelForStudy', iStudy);
    if ~isempty(Channel)
        ChannelFile = Channel.FileName;
    end
% DataFile not in database: try absolute reference
elseif file_exist(DataFile)
    % Try to find a channel file in the DataFile directory
    dirFiles = dir(bst_fullfile(bst_fileparts(DataFile), 'channel*.mat'));
    if ~isempty(dirFiles)
        ChannelFile = bst_fullfile(bst_fileparts(DataFile), dirFiles(1).name);
    end
end
% No ChannelFile
if isempty(ChannelFile)
    bst_error('Channel file not found.', 'Edit ChannelFlag');
    return
end

% ===== START CHANNEL EDITOR =====
% Check if a "Channel Editor" panel already exists
panel = bst_get('Panel', 'ChannelEditor');
% If panel exists
if ~isempty(panel)
    % Close it
    gui_hide(panel);
end
% Create new panel
newpanel = panel_channel_editor('CreatePanel', ChannelFile, DataFile);
if isempty(newpanel)
    bst_progress('stop');
    return
end
% Show panel
bstContainer = gui_show(newpanel, 'JavaWindow', ['Edit ChannelFlag: ', DataFile], 0, 0, 1);
if isempty(bstContainer)
    return;
end

% Get current layout
[jBstArea, FigArea, nScreens, jFigArea, jInsets] = gui_layout('GetScreenBrainstormAreas');
% Place this figure on the screen to take all the possible figure space
jFrame = bstContainer.handle{1};
jFrame.setLocation(jFigArea.getX(), jFigArea.getY() - jInsets.bottom);
jFrame.setSize(jFigArea.getWidth(), jFigArea.getHeight());

% Set selected sensors
if ~isempty(GlobalData.DataViewer.SelectedRows)
    panel_channel_editor('SetChannelSelection', GlobalData.DataViewer.SelectedRows, 0);
end
bst_progress('stop');


function [data] = tapas_linear_prepare_data(data, model, inference)
%%
%
% aponteeduardo@gmail.com
% copyright (C) 2016
%

data = data;

end


function new_name = fname_concat(name, str)

    split = regexp(name, '.mat', 'split');
    new_name = strcat(split{1}, str, '.mat');
end


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

%%
clear; close all; clc;

%% Syntax
% |[C]=grayColor(varargin);|

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


% std_editset() - modify a STUDY set structure.
%
% Usage:
%             >> [STUDY, ALLEEG] = std_editset(STUDY, ALLEEG, key1, val1, ...);
% Inputs:
%   STUDY      - EEGLAB STUDY set
%   ALLEEG     - vector of the EEG datasets included in the STUDY structure
%
% Optional inputs:
%   'commands' - {cell_array} change STUDY (see command description and
%                 example below.
%   'name'     - [string] specify a (mnemonic) name for the STUDY structure.
%                {default: ''}
%   'task'     - [string] attach a description of the experimental task(s)
%                performed by the STUDY subjects {default: ''}.
%   'filename' - [string] filename for the STUDY set.
%   'filepath' - [string] file path (directory/folder) in which the STUDY file
%                will be saved.
%   'addchannellabels' - ['on'|'off'] add channel labels ('1', '2', '3', ...)
%                to all datasets of a STUDY to ensure that all STUDY functions
%                will work {default: 'off'}
%   'notes'    - [string] notes about the experiment, the datasets, the STUDY,
%                or anything else to store with the STUDY itself {default: ''}.
%   'updatedat' - ['on'|'off'] update 'subject' 'session' 'condition' and/or
%                'group' fields of STUDY dataset(s).
%   'savedat'   - ['on'|'off'] re-save datasets
%   'inbrain'   - ['on'|'off'] select components for clustering from all STUDY
%                 datasets with equivalent dipoles located inside the brain volume.
%                 Dipoles are selected based on their residual variance and their
%                 location {default: 'off'}
%
% Each of the 'commands' (above) is a cell array composed of any of the following:
%   'index'     - [integer] modify dataset index.
%   'remove'    - [integer] remove dataset index.
%   'subject'   - [string] subject code.
%   'condition' - [string] dataset condition.
%   'session '  - [integer] dataset session number.
%   'group'     - [string] dataset group.
%   'load'      - [filename] load dataset from specified filename
%   'dipselect' - [float<1] select components for clustering from all STUDY
%                 datasets with dipole model residual var. below this value.
%   'inbrain'   - ['on'|'off'] same as above. This option may also be
%                 placed in the command list (preceeding the 'dipselect'
%                 option).
%
% Outputs:
%   STUDY      - a new STUDY set containing some or all of the datasets in ALLEEG,
%                plus additional information from the optional inputs above.
%   ALLEEG     - a vector of EEG datasets included in the STUDY structure
%
%  See also:  pop_createstudy(), std_loadalleeg(), pop_clust(), pop_preclust(),
%             eeg_preclust(), eeg_createdata()
%
% Authors: Arnaud Delorme, Hilit Serby, SCCN/INC/UCSD, October , 2004-

% Copyright (C) Arnaud Delorme & Scott Makeig, SCCN/INC/UCSD, October 11, 2004, smakeig@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

function [STUDY, ALLEEG] = std_editset(STUDY, ALLEEG, varargin)

if (nargin < 3)
    help std_editset;
    return;
end;

% decode input parameters
% -----------------------
g = finputcheck(varargin, { 'updatedat' 'string'  { 'on' 'off' }  'off';
                            'name'      'string'  { }             '';
                            'task'      'string'  { }             '';
                            'notes'     'string'  { }             '';
                            'filename'  'string'  { }             '';
                            'filepath'  'string'  { }             '';
                            'resave'    'string'  { 'on' 'off' 'info' }  'off';
                            'savedat'   'string'  { 'on' 'off' }  'off';
                            'addchannellabels' 'string'  { 'on' 'off' }  'off';
                            'rmclust'   'string'  { 'on' 'off' }  'on';
                            'inbrain'   'string'  { 'on' 'off' }  'off';
                            'commands'  'cell'    {}              {} }, 'std_editset');
if isstr(g), error(g); end;

if ~isempty(g.name),  STUDY.name  = g.name; end
if ~isempty(g.task),  STUDY.task  = g.task; end
if ~isempty(g.notes), STUDY.notes = g.notes; end

% make one cell array with commands
% ---------------------------------
allcoms = {};
if ~isempty(g.commands)
    if iscell(g.commands{1})
        for k = 1:length(g.commands)
            % put index field first
            indindex   = strmatch('index', lower(g.commands{k}(1:2:end)));
            if ~isempty(indindex)
                 tmpcom = { 'index' g.commands{k}{2*(indindex-1)+1+1} g.commands{k}{:} };
            else tmpcom = g.commands{k};
            end;
            allcoms = { allcoms{:} tmpcom{:} };
        end;
    else
        allcoms = g.commands;
    end;
end;
g.commands = allcoms;

% add 'dipselect' command if 'inbrain' option is selected
% ---------------------------------
dipselectExists = false;
for k = 1:2:length(g.commands)
    if strcmp(g.commands{k},'dipselect')
       dipselectExists = true;
    end;
end;
if strcmp(g.inbrain,'on') && ~dipselectExists
    g.commands{length(g.commands)+1} = 'dipselect';
    g.commands{length(g.commands)+1} = 0.15;
end;

% copy values
% -----------
if ~isfield(STUDY, 'datasetinfo')
    for realindex = 1:length(ALLEEG)
        if ~isempty(ALLEEG(realindex).data)
            [tmppath tmpfile tmpext] = fileparts(  fullfile(ALLEEG(realindex).filepath, ALLEEG(realindex).filename) );
            STUDY.datasetinfo(realindex).filepath  = tmppath;
            STUDY.datasetinfo(realindex).filename  = [ tmpfile tmpext ];
            STUDY.datasetinfo(realindex).subject   = ALLEEG(realindex).subject;
            STUDY.datasetinfo(realindex).session   = ALLEEG(realindex).session;
            STUDY.datasetinfo(realindex).condition = ALLEEG(realindex).condition;
            STUDY.datasetinfo(realindex).group     = ALLEEG(realindex).group;
        end;
    end;
end;

% execute commands
% ----------------
currentind = 1;
rmlist = [];
for k = 1:2:length(g.commands)

    switch g.commands{k}
        case 'index'
            currentind = g.commands{k+1};
        case 'subject'
            STUDY.datasetinfo(currentind).subject = g.commands{k+1};
        case 'comps'
            STUDY.datasetinfo(currentind).comps = g.commands{k+1};
        case 'condition'
            STUDY.datasetinfo(currentind).condition = g.commands{k+1};
        case 'group'
            STUDY.datasetinfo(currentind).group   = g.commands{k+1};
        case 'session'
            STUDY.datasetinfo(currentind).session = g.commands{k+1};
        case 'session'
            STUDY.datasetinfo(currentind).session = g.commands{k+1};
        case 'remove'
            ALLEEG(end+2)            = ALLEEG(end);
            ALLEEG(g.commands{k+1})  = ALLEEG(end-1); % empty dataset
            ALLEEG(end-1:end)        = [];
            STUDY.datasetinfo(end+2)           = STUDY.datasetinfo(end);
            STUDY.datasetinfo(g.commands{k+1}) = STUDY.datasetinfo(end-1);
            STUDY.datasetinfo(end-1:end)       = [];
            if isfield(STUDY.datasetinfo, 'index')
                STUDY.datasetinfo = rmfield(STUDY.datasetinfo, 'index');
            end;
            STUDY.datasetinfo(1).index = [];
            STUDY.changrp = [];
        case 'return', return;
        case 'inbrain'
            g.inbrain = g.commands{k+1};
        case 'dipselect'
            STUDY = std_checkset(STUDY, ALLEEG);
            rv = g.commands{k+1};
            clusters = std_findsameica(ALLEEG);

            for cc = 1:length(clusters)

                idat = 0;
                for tmpi = 1:length(clusters{cc})
                    if isfield(ALLEEG(clusters{cc}(tmpi)).dipfit, 'model')
                        idat = clusters{cc}(tmpi);
                    end;
                end;

                indleft = [];
                if rv ~= 1
                    if idat ~= 0
                        if strcmp(g.inbrain,'on')
                            fprintf('Selecting dipoles with less than %%%2.1f residual variance and removing dipoles outside brain volume in dataset ''%s''\n', ...
                                100*rv, ALLEEG(idat).setname);
                            indleft = eeg_dipselect(ALLEEG(idat), rv*100,'inbrain');
                        else
                           fprintf('Selecting dipoles with less than %%%2.1f residual variance in dataset ''%s''\n', ...
                                100*rv, ALLEEG(idat).setname);
                            indleft = eeg_dipselect(ALLEEG(idat), rv*100,'rv');
                        end;
                    else
                        fprintf('No dipole information found in ''%s'' dataset, using all components\n', ALLEEG.setname)
                    end
                end;
                for tmpi = 1:length(clusters{cc})
                    STUDY.datasetinfo(clusters{cc}(tmpi)).comps = indleft;
                end;
            end;
            STUDY.cluster = [];
            STUDY = std_checkset(STUDY, ALLEEG); % recreate parent dataset

        case 'load'
            TMPEEG = std_loadalleeg( { g.commands{k+1} } );
            ALLEEG = eeg_store(ALLEEG, eeg_checkset(TMPEEG), currentind);
            ALLEEG(currentind).saved = 'yes';

            % update datasetinfo structure
            % ----------------------------
            [tmppath tmpfile tmpext] = fileparts( fullfile(ALLEEG(currentind).filepath, ...
                                                           ALLEEG(currentind).filename) );
            STUDY.datasetinfo(currentind).filepath  = tmppath;
            STUDY.datasetinfo(currentind).filename  = [ tmpfile tmpext ];
            STUDY.datasetinfo(currentind).subject   = ALLEEG(currentind).subject;
            STUDY.datasetinfo(currentind).session   = ALLEEG(currentind).session;
            STUDY.datasetinfo(currentind).condition = ALLEEG(currentind).condition;
            STUDY.datasetinfo(currentind).group     = ALLEEG(currentind).group;
            STUDY.datasetinfo(currentind).index     = currentind;
        otherwise, error(sprintf('Unknown command %s', g.commands{k}));
    end
end

% add channel labels automatically
% -------------------------------
if strcmpi(g.addchannellabels, 'on')
    disp('Generating channel labels for all datasets...');
    for currentind = 1:length(ALLEEG)
        for ind = 1:ALLEEG(currentind).nbchan
            ALLEEG(currentind).chanlocs(ind).labels = int2str(ind);
        end;
    end;
    ALLEEG(currentind).saved = 'no';
    g.savedat = 'on';
end;

% update ALLEEG structure?
% ------------------------
if strcmpi(g.updatedat, 'on')
    for currentind = 1:length(ALLEEG)
        if ~strcmpi(ALLEEG(currentind).subject,   STUDY.datasetinfo(currentind).subject)
            ALLEEG(currentind).subject          = STUDY.datasetinfo(currentind).subject;
            ALLEEG(currentind).saved            = 'no';
        end;
        if ~strcmpi(ALLEEG(currentind).condition, STUDY.datasetinfo(currentind).condition)
            ALLEEG(currentind).condition        = STUDY.datasetinfo(currentind).condition;
            ALLEEG(currentind).saved            = 'no';
        end;
        if ~isequal(ALLEEG(currentind).session, STUDY.datasetinfo(currentind).session)
            ALLEEG(currentind).session          = STUDY.datasetinfo(currentind).session;
            ALLEEG(currentind).saved            = 'no';
        end;
        if ~strcmpi(char(ALLEEG(currentind).group), char(STUDY.datasetinfo(currentind).group))
            ALLEEG(currentind).group            = STUDY.datasetinfo(currentind).group;
            ALLEEG(currentind).saved            = 'no';
        end;
    end;
end;

% remove empty datasets (cannot be done above because some empty datasets
% might not have been removed)
% ---------------------
[ ALLEEG STUDY.datasetinfo ] = removeempty(ALLEEG, STUDY.datasetinfo);

% save datasets if necessary
% --------------------------
if strcmpi(g.savedat, 'on')
    for index = 1:length(ALLEEG)
        if isempty(ALLEEG(index).filename)
            fprintf('Cannot resave ALLEEG(%d) because the dataset has no filename\n', index);
        else
            TMP = pop_saveset(ALLEEG(index), 'savemode', 'resave');
            ALLEEG = eeg_store(ALLEEG, TMP, index);
            ALLEEG(index).saved = 'yes';
        end;
    end;
end;

% remove cluster information if necessary
% ---------------------------------------
if strcmpi(g.rmclust, 'on')
    STUDY.cluster = [];
end;

% save study if necessary
% -----------------------
STUDY.changrp = [];
[STUDY ALLEEG] = std_checkset(STUDY, ALLEEG);
if ~isempty(g.filename),
    [STUDY.filepath STUDY.filename ext] = fileparts(fullfile( g.filepath, g.filename ));
    STUDY.filename = [ STUDY.filename ext ];
    g.resave = 'on';
end
if strcmpi(g.resave, 'on')
    STUDY = pop_savestudy(STUDY, ALLEEG, 'savemode', 'resave');
end;

% ---------------------
% remove empty elements
% ---------------------
function [ALLEEG, datasetinfo] = removeempty(ALLEEG, datasetinfo);

    rmindex = [];
    for index = 1:length(datasetinfo)
        if isempty(datasetinfo(index).subject) & isempty(ALLEEG(index).nbchan)
            rmindex = [ rmindex index ];
        end;
    end;
    datasetinfo(rmindex) = [];
    ALLEEG(rmindex)      = [];
    for index = 1:length(datasetinfo)
        datasetinfo(index).index = index;
    end;

    % remove empty ALLEEG structures
    % ------------------------------
    while length(ALLEEG) > length(datasetinfo)
       ALLEEG(end) = [];
    end;


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

    enumeration
        X('X_0', 1)
        Z('Z_0', 3);
    end

    properties
        name char = '';
        adjustInd(1,1) double = 0;
    end

    methods
        function obj = HaloCoordAdjustEnum(name, adjustInd)
            obj.name = name;
            obj.adjustInd = adjustInd;
        end
    end

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

        function [ind, enum] = getIndForName(name)
            m = enumeration('HaloCoordAdjustEnum');
            [~,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('HaloCoordAdjustEnum');
            ind = find(ismember({m.name},nameStr),1,'first');
            enum = m(ind);
        end
    end
end


function foundScans=selectInitParameters(foundScans)
% foundScans=selectInitParameters(foundScans)
% this function generates a gui to set parameters needed to preprocess fMRI
% data. The gui alows the user to change and set all the parameters needed
% to perform a preprocessing of a complete fMRI session.
%
%
%
%   I needs a foundScans(n) strcuture with n the number off scans in
%   the complete session including scout, inplanes, anaotmy or even shimming
%   founScans should contain:
%
%
%   foundScans(1).DirName='1';
%   foundScans(1).Files=0;
%   foundScans(1).Slices=0;
%   foundScans(1).Volumes=0;
%   foundScans(1).Sequence='';
%   foundScans(1).Action='';
%   foundScans(1).Filenames='';
%   foundScans(1).SkipVols='';
%   foundScans(1).Cycles='';
%   foundScans(1).Filename4d='';
%
%   a good preprocesssing scrip guesses most of these parameters before
%   calling   selectInitParameters to ajust them and add the missing
%   parameters..
%
%
%
%
% Mostly written by Mark Schira (mark@ski.org)

OptionsPerColumn=60;
if isunix
    fontSize = 10;
else
    fontSize = 9;
end
global HandlesOfGUI;
global lastedit;

ActionList={'Nothing','Inplanes','Functional','RefFunc','Anatomical','DTI','Reference'};
nDirs = size(foundScans,2);
disp(nDirs);

ncols=ceil(nDirs/OptionsPerColumn);
nOptionsPerColumn=ceil(nDirs/ncols);
disp(nOptionsPerColumn);

headerStr='Parameters';

%scale factors for x and y axis coordinates
xs = 1.8;
ys = 1.4;
colwidth=64;
colPos=[2 10 35 50 70 82 94 106 118];
%default sizes
butWidth=10;
botMargin = 0.2;
%height = nOptions+2+botMargin*2+.5;
height = nOptionsPerColumn+3.5+botMargin*2+.7;

% width = max(size(optionStr,2),length(headerStr))+2;
width = max(ncols*colwidth,length(headerStr))+2;
width = max(width,2*butWidth+2);

%open the figure
h_mainFig = figure('MenuBar','none',...
    'Units','char',...
    'Resize','off',...
    'NumberTitle','off',...
    'Position',[20, 10, width*xs,height*ys]);
bkColor = get(h_mainFig,'Color');

%___________________________________________________________
%Display title inside a frame
x = 1;
% y = nOptions+1+botMargin;
y = nOptionsPerColumn+2.5+botMargin;
uicontrol('Style','frame',...
    'Units','char',...
    'String',headerStr,...
    'Position',[x*xs,(y+.2)*ys,(width-2)*xs,ys*1.3],...
    'HorizontalAlignment','center',...
    'FontSize',fontSize);
uicontrol('Style','text',...
    'Units','char',...
    'String',headerStr,...
    'Position',[(x+.25)*xs,(y+.3)*ys,(width-2.5)*xs,ys*.9],...
    'HorizontalAlignment','center',...
    'FontSize',fontSize+2);

y=y-1.1;
putuptext('Dir',[colPos(1),(y+.3)*ys,colPos(2)-colPos(1)-1,ys*.9],fontSize);
putuptext('Protocol',[colPos(2),(y+.3)*ys,colPos(3)-colPos(2)-1,ys*.9],fontSize);
putuptext('NoFiles',[colPos(3),(y+.3)*ys,colPos(4)-colPos(3)-4,ys*.9],fontSize);
putuptext('Action',[colPos(4),(y+.3)*ys,colPos(5)-colPos(4)-1,ys*.9],fontSize);
putuptext('Volume',[colPos(5),(y+.3)*ys,colPos(6)-colPos(5)-1,ys*.9],fontSize);
putuptext('Slices',[colPos(6),(y+.3)*ys,colPos(7)-colPos(6)-1,ys*.9],fontSize);
putuptext('Skip',[colPos(7),(y+.3)*ys,colPos(8)-colPos(7)-1,ys*.9],fontSize);
putuptext('Cycles',[colPos(8),(y+.3)*ys,colPos(9)-colPos(8)-1,ys*.9],fontSize);
%putuptext('Condition # ',[colPos(9),(y+.3)*ys,colPos(10)-colPos(9)-1,ys*.9],fontSize);

y=y-0.1;

for ii=1:length(foundScans)
    y=y-1;
    %report the findings
    putuptext(int2str(ii),[colPos(1),(y+.3)*ys,colPos(2)-colPos(1)-1,ys*.9],fontSize);
    putuptext(foundScans(ii).Sequence,[colPos(2),(y+.3)*ys,colPos(3)-colPos(2)-1,ys*.9],fontSize);
    putuptext(int2str(foundScans(ii).Files),[colPos(3),(y+.3)*ys,colPos(4)-colPos(3)-1,ys*.9],fontSize);
    %the aktionMenue
    pos=[colPos(4),(y+.3)*ys,colPos(5)-colPos(4)-4,ys*.9];
    h_action(ii) = uicontrol('Units','char','HorizontalAlignment','left',...
        'Style','popupmenu','String',ActionList,'Position',pos,'BackgroundColor',[0.85 0.85 0.85]);
    if isempty(foundScans(ii).Action)
        ActionVal=1;
    else
        ActionVal=find(strcmp(foundScans(ii).Action,ActionList));
    end
    set(h_action(ii),'Value',ActionVal);

    %the parameters of the scans

    h_Volumes(ii)=uicontrol('Units','char','HorizontalAlignment','center',...
        'Style','edit','String',num2str(foundScans(ii).Volumes,4),...
        'Position',[colPos(5),(y+.3)*ys,colPos(6)-colPos(5)-1,ys*.9],'BackgroundColor',[0.85 0.85 0.85]);
    callBackStr=['global lastedit;lastedit=',char(39),'Vol_',int2str(ii),char(39),';'];
    set(h_Volumes(ii),'Callback',callBackStr);

    h_Slices(ii)=uicontrol('Units','char','HorizontalAlignment','center',...
        'Style','edit','String',int2str(foundScans(ii).Slices),...
        'Position',[colPos(6),(y+.3)*ys,colPos(7)-colPos(6)-1,ys*.9],'BackgroundColor',[0.85 0.85 0.85]);
    callBackStr=['global lastedit;lastedit=',char(39),'Sli_',int2str(ii),char(39),';'];
    set(h_Slices(ii),'Callback',callBackStr);

    h_SkipVols(ii)=uicontrol('Units','char','HorizontalAlignment','center',...
        'Style','edit','String',int2str(foundScans(ii).SkipVols),...
        'Position',[colPos(7),(y+.3)*ys,colPos(8)-colPos(7)-1,ys*.9],'BackgroundColor',[0.85 0.85 0.85]);
    callBackStr=['global lastedit;lastedit=',char(39),'Ski_',int2str(ii),char(39),';'];
    set(h_SkipVols(ii),'Callback',callBackStr);

    h_Cycles(ii)=uicontrol('Units','char','HorizontalAlignment','center',...
        'Style','edit','String',int2str(foundScans(ii).SkipVols),...
        'Position',[colPos(8),(y+.3)*ys,colPos(9)-colPos(8)-1,ys*.9],'BackgroundColor',[0.85 0.85 0.85]);
    callBackStr=['global lastedit;lastedit=',char(39),'Cyc_',int2str(ii),char(39),';'];
    set(h_Cycles(ii),'Callback',callBackStr);
end

HandlesOfGUI.h_Volumes=h_Volumes;
HandlesOfGUI.h_Slices=h_Slices;
HandlesOfGUI.h_SkipVols=h_SkipVols;
HandlesOfGUI.h_Cycles=h_Cycles;

y=y-1.4;
uicontrol('Style','pushbutton',...
    'String','Cancel',...
    'Units','char',...
    'Position',[colPos(4)-4,(y+.3)*ys,colPos(5)-colPos(4)-4,ys*.9],...
    'CallBack','uiresume',...
    'FontSize',fontSize,...
    'UserData','Cancel');

x = width-butWidth-1;
uicontrol('Style','pushbutton',...
    'String','OK',...
    'Units','char',...
    'Position',[colPos(2),(y+.3)*ys,colPos(3)-colPos(2)-4,ys*.9],...
    'CallBack','uiresume',...
    'FontSize',fontSize,...
    'UserData','OK');
global MY_GLOBAL
CopyDownString=['global lastedit; global h_Volumes; selectInitParamChange(lastedit);'];

sabutton=uicontrol('Style','pushbutton',...
    'String','Fill last Value',...
    'Units','char',...
    'Position',[colPos(6)-5,(y+.3)*ys,colPos(8)-colPos(6)-2,ys*.9],...
    'FontSize',fontSize-4,...
    'Callback',CopyDownString,...
    'UserData','OK');

%let the user select some radio buttons and
%wait for a 'uiresume' callback from OK/Cancel
uiwait

%determine which button was hit.
response = get(gco,'UserData');

%gather the status of the radio buttons if 'OK' was
%selected.  Otherwise return empty matrix.
if strcmp(response,'OK')
    for thisScan=1:length(foundScans)
        foundScans(thisScan).Action=ActionList(get(h_action(thisScan),'Value'));
        foundScans(thisScan).Volumes=getNumberFromString(get(h_Volumes(thisScan),'String'));
        foundScans(thisScan).Slices=getNumberFromString(get(h_Slices(thisScan),'String'));
        foundScans(thisScan).SkipVols=getNumberFromString(get(h_SkipVols(thisScan),'String'));
        foundScans(thisScan).Cycles=getNumberFromString(get(h_Cycles(thisScan),'String'));
    end

else
    foundScans = [];
end

close(h_mainFig);

return;
end

function putuptext(TEXT,pos,fontSize)
uicontrol('Style','text',...
    'Units','char',...
    'String',TEXT ,...
    'Position',pos,...
    'HorizontalAlignment','center',...
    'FontSize',9);
end


 function tf = streq(a,b,n)
%function tf = streq(a, b [,n])
%	return 1 if two strings are equal (optionally only up to 1st n chars)
if nargin == 2
	tf = strcmp(a,b);
elseif nargin == 3
	tf = strncmp(a,b,n);
else
	help(mfilename), error(mfilename)
end


% getFolder
%
% Similar to uigetdir except that it will remember the location of the
% last opened folder.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Use plotAverageWaveforms
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   Kian Torab
%   ktorab@blackrockmicro.com
%   Blackrock Microsystems
%   Salt Lake City, UT
%
%   Version 1.0.0.0
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function dataFolder = getFolder

settingFileFullPath = getSettingFileFullPath('getFolder');

%% Opens the getFolder.ini file to see what the last accessed folder was
if exist(settingFileFullPath, 'file') == 2
    settingsFID = fopen(settingFileFullPath, 'r');
    defaultOpenLocation = fscanf(settingsFID, '%200c');
    fclose(settingsFID);
else
    defaultOpenLocation = [];
end

%% Gets a folder by opening the last accessed folder as the last location
dataFolder = uigetdir(defaultOpenLocation);

%% Saves the last opened folder in the getFolder.ini file for later use
if ischar(dataFolder)
    settingsFID = fopen(settingFileFullPath, 'w');
    fprintf(settingsFID, '%s', dataFolder);
    fclose(settingsFID);
end


function skeletonLabeler( objTypes, vidNm, annNm )
% Video bound box (vbb) Labeler.
%
% USAGE
%  vbbLabeler( [objTypes], [vidNm], [annNm] )
%
% INPUTS
%  objTypes - [{'object'}] list of object types to annotate
%  imgDir   - [] initial video to load
%  resDir   - [] initial annotation to load
%

    % defaults
    if(nargin<1 || isempty(objTypes)), objTypes={'object'}; end
    if(nargin<2 || isempty(vidNm)), vidNm=''; end
    if(nargin<3 || isempty(annNm)), annNm=''; end

    % handles to gui objects / other globals
    [hFig, pSet, pCp, pMp] = deal([]);
    [curInd,curSeg, setApi,dispApi] = deal([]);

    makeLayout();
    setApi = setMakeApi(); % set the parameters
    dispApi  = dispMakeApi(); % display & update
    setApi.closeVid();
    set(hFig,'Visible','on');
    drawnow;

    % optionally load default data
    if(~isempty(vidNm)), setApi.openVid(vidNm); end
    if(~isempty(annNm)), setApi.openAnn(annNm); end

    function makeLayout()
        % hFig: main figure
        set(0,'Units','pixels'); ss=get(0,'ScreenSize');
        if( ss(3)<800 || ss(4)<600 ), error('screen too small'); end
        pos = [(ss(3)-580-400)/2 (ss(4)-650-200)/2 580+400 680+200];
        hFig = figure( 'Name','Labeler', 'NumberTitle','off', ...
          'Toolbar','auto', 'MenuBar','none', 'Resize','on', ...
          'Color','k', 'Visible','off', 'DeleteFcn',@exitLb, 'Position',pos, ...
          'keyPressFcn',@keyPress );

        % pSet: top panel containing setting
        pSet.h=uipanel('Units','pixels', 'BackgroundColor',[.1 .1 .1],'BorderType','none','Position', [8 645+200 580 30], 'Parent',hFig);
        pSet.hOpen   = uicontrol(pSet.h,'BackgroundColor',[.7 .7 .7],'FontSize', 10, 'Position', [5  3 90 20],'String','Open');
        pSet.nImgLbl = uicontrol(pSet.h,'Style','text','FontSize',8,'BackgroundColor',[.1 .1 .1],'ForegroundColor','w','Position',[185 0 50 20],'HorizontalAlignment','Left', 'String', '/');
        pSet.IndLbl  = uicontrol(pSet.h,'Style','edit','FontSize',8,'BackgroundColor',[.1 .1 .1],'ForegroundColor','w','Position',[135 3 50 20],'HorizontalAlignment','Right');
        pSet.hImageName = uicontrol(pSet.h,'Style','text','FontSize',8,'BackgroundColor',[.1 .1 .1],'ForegroundColor','w','Position',[240 0 90 20],'HorizontalAlignment','Left');

        % pCp: control pannel
        pCp.h=uipanel('Units','pixels', 'BackgroundColor',[.1 .1 .1],'BorderType','none','Position', [8 613+200 580 30],'Parent',hFig);
        pCp.hBtPrvImg    = uicontrol(pCp.h,'BackgroundColor',[.7 .7 .7],'FontSize', 10, 'Position', [5  3 90 25],'String','PreviousImage');
        pCp.hBtShowImg   = uicontrol(pCp.h,'BackgroundColor',[.7 .7 .7],'FontSize', 10, 'Position', [100  3 90 25],'String','ShowImage');
        pCp.hBtShowMask  = uicontrol(pCp.h,'BackgroundColor',[.7 .7 .7],'FontSize', 10, 'Position', [195 3 80 25],'String','ShowMask');
        pCp.hBtShowSkel  = uicontrol(pCp.h,'BackgroundColor',[.7 .7 .7],'FontSize', 10, 'Position', [280 3 90 25],'String','ShowSkeleton');
        pCp.hBtNextImg   = uicontrol(pCp.h,'BackgroundColor',[.7 .7 .7],'FontSize', 10, 'Position', [375 3 80 25],'String','NextImage');
        pCp.hBtAnnSave   = uicontrol(pCp.h,'BackgroundColor',[.7 .7 .7],'FontSize', 10, 'Position', [460 3 95 25],'String','AnnotationSave');

        % pMp main panel
        pMp.h=uipanel('Units','pixels', 'BackgroundColor',[.1 .1 .1],'BorderType','none','Position', [8 8 580+400 604+200],'Parent',hFig);
        pMp.hAx=axes('Units','pixels', 'Position', [5 40 560+400 560+200], 'Parent',pMp.h, 'Color', [1 1 1]);
        pMp.hBtPrvObj  = uicontrol(pMp.h,'BackgroundColor',[.7 .7 .7],'FontSize', 10, 'Position', [5  3 90 25],'String','PreviousObject');
        pMp.hBtOriMask = uicontrol(pMp.h,'BackgroundColor',[.7 .7 .7],'FontSize', 10, 'Position',[100  3 90 25],'String','OriginalMask');
        pMp.hBtExdDisc = uicontrol(pMp.h,'BackgroundColor',[.7 .7 .7],'FontSize', 10, 'Position',[195 3 80 25],'String','ExtendDisc');
        pMp.hBtExdPoly = uicontrol(pMp.h,'BackgroundColor',[.7 .7 .7],'FontSize', 10, 'Position',[280 3 80 25],'String','ExtendPoly');
        pMp.hBtAnn     = uicontrol(pMp.h,'BackgroundColor',[.7 .7 .7],'FontSize', 10, 'Position',[365 3 80 25],'String','Annotation');
        pMp.hBtNxtObj  = uicontrol(pMp.h,'BackgroundColor',[.7 .7 .7],'FontSize', 10, 'Position',[450 3 80 25],'String','NextObject');

        function exitLb( h, e ) %#ok<INUSD>
        	setApi.closeVid();
        end

        function keyPress( h, evnt ) %#ok<INUSL>
            char=int8(evnt.Character); if(isempty(char)), char=0; end;
            if( char==28 ), dispApi.setPlay(-inf); end
            if( char==29 ), dispApi.setPlay(+inf); end
            if( char==31 ), dispApi.setPlay(0); end
        end
    end

    function api = setMakeApi()
        % variables
        [imgPath, segPath, imgLst] = deal([]);
        [imgROI, seg, segIdx, skeGt,skeInst, extIdx] = deal([]);
        [segMask, extMask, skelFlag, annFlag] = deal([]);
        [h, w] = deal([]);

        imgPath     = [VOC2011Path '\VOCdevkit\VOC2011\JPEGImages';
        segPath     = [VOC2011Path '\VOCdevkit\VOC2011\SegmentationObject';
        imgLstPath  = [VOC2011Path '\VOCdevkit\VOC2011\ImageSets\Segmentation\train.txt';
        f=fopen(imgLstPath); imgLst=textscan(f,'%s %*s'); imgLst=imgLst{1}; fclose(f);
        set(pSet.nImgLbl, 'String', ['\' num2str(length(imgLst))]);

        % callbacks
        set(pSet.hOpen, 'callback', @(h,e) imgOpen());
        set(pCp.hBtNextImg, 'callback', @(h,e) nextImg());
        set(pCp.hBtPrvImg, 'callback', @(h,e) previousImg());
        set(pCp.hBtShowImg, 'callback', @(h,e) showImg());
        set(pCp.hBtShowMask, 'callback', @(h,e) showMask());
        set(pCp.hBtShowSkel, 'callback', @(h,e) showSkel());
        set(pCp.hBtAnnSave, 'callback', @(h,e) annSave());

        set(pMp.hBtPrvObj, 'callback', @(h,e) previousObj());
        set(pMp.hBtNxtObj, 'callback', @(h,e) nextObj());
        set(pMp.hBtOriMask, 'callback', @(h,e) oriMask());
        set(pMp.hBtExdDisc, 'callback', @(h,e) exdMaskDisc());
        set(pMp.hBtExdPoly, 'callback', @(h,e) exdMaskPoly());
        set(pMp.hBtAnn, 'callback', @(h,e) annotation());

        % create api
        api=struct('imgSet',@imgSet, ...
          'imgOpen',@imgOpen, 'closeVid', @closeVid);

        function imgShow()
            curSeg = 0;
            set(pSet.IndLbl, 'String', num2str(curInd));
            set(pSet.hImageName, 'String', [imgLst{curInd} '.jpg']);
            set(pCp.hBtShowSkel, 'Enable','off');
            set(pCp.hBtAnnSave, 'Enable','off');

            cla(pMp.hAx); set(pMp.hAx,'XTick',[],'YTick',[]);
            set( hFig, 'CurrentAxes', pMp.hAx );
            imgROI = imread([imgPath '\' imgLst{curInd} '.jpg']);
            [h,w,~] =size(imgROI);
            set( pMp.hAx, 'Position', [5 40 980 804]);
            img = uint8(50*ones(804,980,3));
            img(420-floor(h/2):419-floor(h/2)+h,485-floor(w/2):484-floor(w/2)+w,1) = imgROI(:,:,1);
            img(420-floor(h/2):419-floor(h/2)+h,485-floor(w/2):484-floor(w/2)+w,2) = imgROI(:,:,2);
            img(420-floor(h/2):419-floor(h/2)+h,485-floor(w/2):484-floor(w/2)+w,3) = imgROI(:,:,3);
            image(img); axis off;
            seg = imread([segPath '\' imgLst{curInd} '.png']);
            segIdx = unique(seg);
            skeGt = false(h,w);
            extMask = cell(50,1);
            skeInst = cell(length(segIdx)-2,1);
            skelFlag= false(length(segIdx)-2,1);
            segMask = false(804,980);
        end

        function segShow(segmask)
            tmp = uint8(50*ones(804,980,3));
            tmp(420-floor(h/2):419-floor(h/2)+h,485-floor(w/2):484-floor(w/2)+w,1) = imgROI(:,:,1);
            tmp(420-floor(h/2):419-floor(h/2)+h,485-floor(w/2):484-floor(w/2)+w,2) = imgROI(:,:,2);
            tmp(420-floor(h/2):419-floor(h/2)+h,485-floor(w/2):484-floor(w/2)+w,3) = imgROI(:,:,3);
            tmp(:,:,1) = tmp(:,:,1).*uint8(~segmask);
            tmp(:,:,2) = tmp(:,:,2).*uint8(~segmask);
            tmp(:,:,3) = tmp(:,:,3).*uint8(~segmask);
            image(tmp);
            axis off;
        end

        function imgOpen()
            num = get(pSet.IndLbl, 'String');
            if(isempty(num))
                curInd = 1;
            else
                curInd = uint16(str2num(num));
            end
            imgShow();
        end

        function nextImg()
            if(curInd < 1112)
                curInd = curInd+1;
            end
            imgShow();
        end

        function previousImg()
            if(curInd>1)
                curInd = curInd-1;
            end
            imgShow();
        end

        function showImg()
            imgROI = imread([imgPath '\' imgLst{curInd} '.jpg']);
            [h,w,~] =size(imgROI);
            set( pMp.hAx, 'Position', [5 40 980 804]);
            img = uint8(50*ones(804,980,3));
            img(420-floor(h/2):419-floor(h/2)+h,485-floor(w/2):484-floor(w/2)+w,1) = imgROI(:,:,1);
            img(420-floor(h/2):419-floor(h/2)+h,485-floor(w/2):484-floor(w/2)+w,2) = imgROI(:,:,2);
            img(420-floor(h/2):419-floor(h/2)+h,485-floor(w/2):484-floor(w/2)+w,3) = imgROI(:,:,3);
            image(img); axis off;
        end

        function showMask()
            segMaskROI = seg == segIdx(length(segIdx));
            segMask(420-floor(h/2):419-floor(h/2)+h,485-floor(w/2):484-floor(w/2)+w) = segMaskROI;
            segShow(segMask);
        end

        function showSkel()
            for i= 1:length(segIdx)-2
                skeGt = skeGt|skeInst{i};
            end

            tmp = uint8(50*ones(804,980,3));
            tmp(420-floor(h/2):419-floor(h/2)+h,485-floor(w/2):484-floor(w/2)+w,1) = imgROI(:,:,1);
            tmp(420-floor(h/2):419-floor(h/2)+h,485-floor(w/2):484-floor(w/2)+w,2) = imgROI(:,:,2);
            tmp(420-floor(h/2):419-floor(h/2)+h,485-floor(w/2):484-floor(w/2)+w,3) = imgROI(:,:,3);
            tmpMask = false(804,980);
            tmpMask(420-floor(h/2):419-floor(h/2)+h,485-floor(w/2):484-floor(w/2)+w)= seg>0;
            tmpGt = false(804,980);
            tmpGt(420-floor(h/2):419-floor(h/2)+h,485-floor(w/2):484-floor(w/2)+w) = skeGt;
            tmpMask = uint8(~tmpMask);
            tmpMask(tmpGt) = 255;

            tmp(:,:,1) = tmp(:,:,1).*tmpMask;
            tmp(:,:,2) = tmp(:,:,2).*tmpMask;
            tmp(:,:,3) = tmp(:,:,3).*tmpMask;
            image(tmp);axis off;

            set(pCp.hBtAnnSave, 'Enable','on');
        end

        function annSave()
            sym = skeGt;
            save(['skeGt/' imgLst{curInd} '.mat'], 'sym');
            msgbox('save sucessed.');
        end

        function previousObj()
            if(curSeg>1)
                curSeg = curSeg-1;
            else
               curSeg = 1;
            end
            annFlag = true;
            segMaskROI = seg == segIdx(curSeg+1);
            segMask(420-floor(h/2):419-floor(h/2)+h,485-floor(w/2):484-floor(w/2)+w) = segMaskROI;
            segShow(segMask);
            extIdx = 1;
        end

        function nextObj()
            if(curSeg<length(segIdx)-2)
                curSeg = curSeg+1;
            end
            annFlag = true;
            segMaskROI = seg == segIdx(curSeg+1);
            segMask(420-floor(h/2):419-floor(h/2)+h,485-floor(w/2):484-floor(w/2)+w) = segMaskROI;
            segShow(segMask);
            extIdx = 1;
        end

        function oriMask()
            extIdx = 1;
            annFlag = true;
            segShow(segMask);
        end

        function exdMaskDisc()
            if curSeg >0
                [x,y] = ginput(2);
                if(length(x)<2)
                    return;
                end

                tmpMask = false(size(segMask));
                % extend by disc
                dot1 = [x(1) y(1)];
                dot2 = [x(2) y(2)];
                tmpMask = extendDisc(tmpMask, dot1, dot2);

                tmpMask = imfill(tmpMask, 'holes');

                if extIdx==1
                    extMask{extIdx} = tmpMask;
                else
                    extMask{extIdx} = extMask{extIdx-1}|tmpMask;
                end
                tmpMask = segMask|extMask{extIdx};
                segShow(tmpMask);
                if (extIdx<51)
                    extIdx = extIdx+1;
                end
            end
        end

        function exdMaskPoly()
            if curSeg >0
                [x,y] = ginput(4);
                if(length(x)<2)
                    return;
                end
                tmpMask = false(size(segMask));
                % extend by polygon
                x = [x(1) x(2) x(3) x(4)];
                y = [y(1) y(2) y(3) y(4)];
                tmpMask = extendPolygon(tmpMask, x, y);
                tmpMask = imfill(tmpMask, 'holes');
                if extIdx==1
                    extMask{extIdx} = tmpMask;
                else
                    extMask{extIdx} = extMask{extIdx-1}|tmpMask;
                end
                tmpMask = segMask|extMask{extIdx};
                segShow(tmpMask);
                if (extIdx<51)
                    extIdx = extIdx+1;
                end
            end
        end

        function annotation()
            if curSeg >0
                if(extIdx>1)
                    tmpMask = extMask{extIdx-1};
                    tmpMask = segMask|tmpMask;
                else
                    tmpMask = segMask;
                end

                try

                    epsilon = 0.8;
                    skel = skel_pruning_bpr(tmpMask, epsilon, 9);
                    skel = skel>0;

                    tmp = uint8(50*ones(804,980,3));
                    tmp(420-floor(h/2):419-floor(h/2)+h,485-floor(w/2):484-floor(w/2)+w,1) = imgROI(:,:,1);
                    tmp(420-floor(h/2):419-floor(h/2)+h,485-floor(w/2):484-floor(w/2)+w,2) = imgROI(:,:,2);
                    tmp(420-floor(h/2):419-floor(h/2)+h,485-floor(w/2):484-floor(w/2)+w,3) = imgROI(:,:,3);

                    if annFlag
                        tmpMask = uint8(~tmpMask);
                    else
                        skel = skel & segMask;
                        tmpMask = uint8(~segMask);
                    end

                    tmpMask(skel) = 255;

                    tmp(:,:,1) = tmp(:,:,1).*tmpMask;
                    tmp(:,:,2) = tmp(:,:,2).*tmpMask;
                    tmp(:,:,3) = tmp(:,:,3).*tmpMask;
                    image(tmp);axis off;
                    annFlag = ~annFlag;

                    skelFlag(curSeg) = true;
                    skeInst{curSeg} = skel(420-floor(h/2):419-floor(h/2)+h,485-floor(w/2):484-floor(w/2)+w);

                    if all(skelFlag==true)
                        set(pCp.hBtShowSkel, 'Enable','on');
                    end
                end
            end
        end

        function mask = extendDisc(extMask, dot1, dot2)
            dot1 = double(dot1);
            dot2 = double(dot2);
            mask = extMask;
            x0 = (dot1(1)+dot2(1))/2;
            y0 = (dot1(2)+dot2(2))/2;
            R0 = sqrt((dot1(1)-dot2(1))^2+(dot1(2)-dot2(2))^2)/2;
            dy = dot2(2)-dot1(2);
            dx = dot2(1)-dot1(1);
            theta0 = atan((dot2(2)-dot1(2))/(dot2(1)-dot1(1)));
            if dot2(2)-dot1(2)>=0 && dot2(1)-dot1(1)<0
                theta0 = atan((dot2(2)-dot1(2))/(dot2(1)-dot1(1)))-pi;
            elseif dot2(2)-dot1(2)>=0 && dot2(1)-dot1(1)>0
                theta0 = atan((dot2(2)-dot1(2))/(dot2(1)-dot1(1)));
            elseif dot2(2)-dot1(2)<0 && dot2(1)-dot1(1)<0
                theta0 = atan((dot2(2)-dot1(2))/(dot2(1)-dot1(1)))-pi;
            elseif dot2(2)-dot1(2)<0 && dot2(1)-dot1(1)>0
                theta0 = atan((dot2(2)-dot1(2))/(dot2(1)-dot1(1)));
            elseif dot2(2)-dot1(2)<0 && dot2(1)-dot1(1)==0
                theta0 = -pi/2;
            elseif dot2(2)-dot1(2)>0 && dot2(1)-dot1(1)==0
                theta0 = pi/2;
            end

            Theta=linspace(theta0,theta0+pi,1000);
            x = x0+ cos(Theta)*R0;
            y = y0 + sin(Theta)*R0;
            for ii=1:1000
                mask(round(y(ii)),round(x(ii)))=true;
            end
            x = linspace(dot1(1),dot2(1),500);
            y = linspace(dot1(2),dot2(2),500);
            for ii=1:500
                mask(round(y(ii)),round(x(ii)))=true;
            end

        end

        function mask = extendPolygon(extMask, x, y)
            mask = extMask;
            a = [linspace(x(1),x(2),500) linspace(x(2),x(3),500) linspace(x(3),x(4),500) linspace(x(4),x(1),500)];
            b = [linspace(y(1),y(2),500) linspace(y(2),y(3),500) linspace(y(3),y(4),500) linspace(y(4),y(1),500)];
            for ii=1:2000
                mask(round(b(ii)),round(a(ii)))=true;
            end
        end

        function closeVid()
%             dispApi.init([]);
        end
    end

    function api = dispMakeApi()
        api=struct( 'showImage',@showImage, 'imgSet',@imgSet, ...
          'imgOpen',@imgOpen);

    end

end


function centerfigureonscreen(hFig)

screenSize = get(groot, 'ScreenSize');
hFig.Position = [screenSize(3)/2-hFig.Position(3)/2 ...
                 screenSize(4)/2-hFig.Position(4)/2 ...
                 hFig.Position(3) ...
                 hFig.Position(4)];

end


function interp1_table1_import

libname = 'interp1_table1.a';

type11r = ['double[K1] r_ck, double[K1] i_ck, int32 K1, ' ...
	'double[J1*L1+1] r_h1, int32 J1, int32 L1, ' ...
	'double[M] p_tm, int32 M, double[M] &r_fm, double[M] &i_fm'];

myimport(libname, 'interp1_table1_real_per', 'void', type11r);

function myimport(libname, name, type_return, type_call)
import(libname, name, name, type_return, type_call);