function item = cfg_intree(varargin)

% This is currently only a "marker" class that should be inherited by all
% within-tree classes. It does not add fields and does not have methods.
%
% This code is part of a batch job configuration system for MATLAB. See
%      help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging

% Volkmar Glauche
% $Id: cfg_intree.m 1716 2008-05-23 08:18:45Z volkmar $

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

item = class(struct('unused',[]), mfilename);


function varargout = HELP3(varargin)
% HELP3 M-file for HELP3.fig
%      HELP3, by itself, creates a new HELP3 or raises the existing
%      singleton*.
%
%      H = HELP3 returns the handle to a new HELP3 or the handle to
%      the existing singleton*.
%
%      HELP3('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in HELP3.M with the given input arguments.
%
%      HELP3('Property','Value',...) creates a new HELP3 or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before HELP3_OpeningFunction gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to HELP3_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help HELP3

% Last Modified by GUIDE v2.5 06-Feb-2008 23:04:44

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @HELP3_OpeningFcn, ...
                   'gui_OutputFcn',  @HELP3_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before HELP3 is made visible.
function HELP3_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to HELP3 (see VARARGIN)

% Choose default command line output for HELP3
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes HELP3 wait for user response (see UIRESUME)
% uiwait(handles.figure1);

% --- Outputs from this function are returned to the command line.
function varargout = HELP3_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;


function bool = mymkdir_dist(dirName)
%from santosh
[tmp,h] = unix('hostname');
if 0 %strfind(h,'onega')
  fprintf(1,'onega lock skip\n');
  bool = true;
  return;
end
[smesg, smess, smessid] = mkdir(dirName);
bool = ~strcmp(smessid,'MATLAB:MKDIR:DirectoryExists');


PitchTraking()


function str = showmydoc(item, indent)

% function str = showmydoc(item, indent)
% Display help text for a cfg_choice and all of its options, without
% recursive calls to child nodes.
%
% This code is part of a batch job configuration system for MATLAB. See
%      help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging

% Volkmar Glauche
% $Id: showmydoc.m 2085 2008-09-12 10:26:59Z volkmar $

rev = '$Rev: 2085 $'; %#ok
str1 = showdoc(item.cfg_item, indent);
citems = subsref(item, substruct('.','val'));
str2{1} = sprintf('This branch contains %d items:', numel(citems));
% Display short listing of branch items first
str3 = cell(1,numel(citems));
for k = 1:numel(citems)
    str3{k} = sprintf('* %s', subsref(citems{k}, substruct('.','name')));
end;
str = [str1(:); {''}; str2(:); str3(:)];


% BV_CLOSE  Closes a TCP connection to BrainVision Recorder
%     BV_CLOSE(H)
%     In:
%     h : handle to an existing BrainVision connection

% Author: Hal Greenwald, The MITRE Corporation, 29-NOV-2011

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

function bv_close(h)
if ~h.initialized
    return;
end
disp('Cleaning up connection to BrainVision Recorder');
pnet(h.handle, 'close');
if evalin('base', ['exist(' 'sprintf(''%s'', h.name)' ')'])
    evalin('base',['clear ' sprintf('%s',h.name) ';']);
end


function [success] = modelAddOutsideDependencies(dependencyName,varargin)
	% Used to request certain outside dependencies from users.
	% Biafra Ahanonu
	% started: 2017.11.16 [16:50:28]
	% inputs
		%
	% outputs
		%

	% changelog
		% 2019.10.15 [12:29:30] - Added flag to prevent recursive loop between resetMiji and modelAddOutsideDependencies.
		% 2021.02.01 [??15:19:40] - Update `_external_programs` to call ciapkg.getDirExternalPrograms() to standardize call across all functions.
		% 2021.06.20 [00:20:12] - Updated to add support for ImageJ call instead of Fiji.
		% 2021.08.08 [19:30:20] - Updated to handle CIAtah v4.0 switch to all functions inside ciapkg package.
		% 2021.12.26 [09:10:55] - No longer use Fiji-based Miji.
	% TODO
		%

	import ciapkg.api.* % import CIAtah functions in ciapkg package API.

	%========================
	options.exampleOption = '';
	options.defaultExternalProgramDir = ciapkg.getDirExternalPrograms();
	options.recursionExit = 0;
	% get options
	options = getOptions(options,varargin);
	% display(options)
	% unpack options into current workspace
	% fn=fieldnames(options);
	% for i=1:length(fn)
	% 	eval([fn{i} '=options.' fn{i} ';']);
	% end
	%========================

	try
		success = 0;
		switch dependencyName
			case 'miji'
				if exist('MIJ','class')==8
					disp('Miji loaded!')
					return;
				else
					manageMiji('startStop','setupImageJ');
					if exist('MIJ','class')==8
						disp('Miji loaded!')
						return;
					end
                end

                % No longer use Fiji-based Miji.
                return;

				if exist('Miji.m','file')==2
					display(['Miji located in: ' which('Miji.m')]);
					% Miji is loaded, continue
				elseif ~isempty(java.lang.System.getProperty('plugins.dir'))&options.recursionExit==0
					disp('Miji JAR files already loaded, skipping. If Miji issue, use "resetMiji".')
				else
					% pathToMiji = inputdlg('Enter path to Miji.m in Fiji (e.g. \Fiji.app\scripts):',...
					%              'Miji path', [1 100]);
					% pathToMiji = pathToMiji{1};
					% display('Dialog box: Enter path to Miji.m in Fiji (likely in "scripts" folder, e.g. \Fiji.app\scripts)')
					fijiList = getFileList(options.defaultExternalProgramDir,'(Fiji.app|fiji-.*-20151222(?!.zip|.dmg))');
					if ~isempty(fijiList)
						if ismac
							checkMijiPath = [fijiList{1} filesep 'scripts'];
						elseif isunix
							checkMijiPath = [fijiList{1} filesep 'Fiji.app' filesep 'scripts'];
						elseif ispc
							checkMijiPath = [fijiList{1} filesep 'Fiji.app' filesep 'scripts'];
						else
							checkMijiPath = [fijiList{1} filesep 'Fiji.app' filesep 'scripts'];
						end
						% checkMijiPath = [options.defaultExternalProgramDir filesep 'Fiji.app' filesep 'scripts'];
						if exist(checkMijiPath,'dir')==7
							fprintf('AUTOMATICALLY adding Miji path: %s\n',checkMijiPath);
							pathToMiji = checkMijiPath;
						end
					end
					if exist('pathToMiji','var')==0
						if exist(options.defaultExternalProgramDir,'dir')==7
							loadPathHere = options.defaultExternalProgramDir;
							loadStr = ['Enter path to Miji.m in Fiji (likely in "scripts" folder, e.g. ' filesep ciapkg.pkgName options.defaultExternalProgramDir '\Fiji.app\scripts)'];
						else
							loadPathHere = '\.';
							loadStr = ['Enter path to Miji.m in Fiji (likely in "scripts" folder, e.g. \Fiji.app\scripts)'];
						end
						disp(['Dialog box: ' loadStr])
						pathToMiji = uigetdir(loadPathHere,loadStr);
					end
					if ischar(pathToMiji)
						privateLoadBatchFxnsPath = 'private\settings\privateLoadBatchFxns.m';
						if exist(privateLoadBatchFxnsPath,'file')~=0
							fid = fopen(privateLoadBatchFxnsPath,'at')
							fprintf(fid, '\npathtoMiji = ''%s'';\n', pathToMiji);
							fclose(fid);
						end
						addpath(pathToMiji);
					end

					if options.recursionExit==1
						return;
					end

					% % If MIJ class not loaded, load Miji.m.
					% if exist('MIJ')~=8
					% 	% Load Miji so paths added to javaclasspath('-dynamic')
					% 	currP=pwd;Miji;cd(currP);
					% 	MIJ.exit;
					% end

					% % First attempt to open Miji
					% try
					% 	MIJ.start;
					% catch err
					% 	disp(repmat('@',1,7))
					% 	disp(getReport(err,'extended','hyperlinks','on'));
					% 	disp(repmat('@',1,7))

					% 	disp('Reset Java class path and Miji then try again');
					% 	resetMiji

					% 	% Try again after resetting Miji.
					% 	try
					% 		MIJ.start;
					% 	catch err
					% 		disp(repmat('@',1,7))
					% 		disp('Apparently Miji hates your computer, sorry!')
					% 		disp(getReport(err,'extended','hyperlinks','on'));
					% 		disp(repmat('@',1,7))
					% 	end
					% end

					% Get Miji properly loaded in the path
					resetMiji;

					% % Load Miji so paths added to javaclasspath('-dynamic')
					% currP=pwd;Miji;cd(currP);
					% MIJ.exit;
				end
			otherwise
				display('Incorrect option input.')
				% do nothing
		end
	catch err
		display(repmat('@',1,7))
		disp(getReport(err,'extended','hyperlinks','on'));
		display(repmat('@',1,7))
	end
end


function obj = display(obj)
	% Biafra Ahanonu
	% Started: 2021.03.25 [22:11:25] (branched from ciatah.m)

	% Overload display method so can run object by just typing 'obj' in command window.
	obj.runPipeline;
	% display('hello');
end


function File = getFullPath(File, Style)
% getFullPath - Get absolute canonical path of a file or folder
% Absolute path names are safer than relative paths, when e.g. a GUI or TIMER
% callback changes the current directory. Only canonical paths without "." and
% ".." can be recognized uniquely.
% Long path names (>259 characters) require a magic initial key "\\?\" to be
% handled by Windows API functions, e.g. for Matlab's FOPEN, DIR and EXIST.
%
% FullName = getFullPath(Name, Style)
% INPUT:
%   Name:  String or cell string, absolute or relative name of a file or
%          folder. The path need not exist. Unicode strings, UNC paths and long
%          names are supported.
%   Style: Style of the output as string, optional, default: 'auto'.
%          'auto': Add '\\?\' or '\\?\UNC\' for long names on demand.
%          'lean': Magic string is not added.
%          'fat':  Magic string is added for short names also.
%          The Style is ignored when not running under Windows.
%
% OUTPUT:
%   FullName: Absolute canonical path name as string or cell string.
%          For empty strings the current directory is replied.
%          '\\?\' or '\\?\UNC' is added on demand.
%
% NOTE: The M- and the MEX-version create the same results, the faster MEX
%   function works under Windows only.
%   Some functions of the Windows-API still do not support long file names.
%   E.g. the Recycler and the Windows Explorer fail even with the magic '\\?\'
%   prefix. Some functions of Matlab accept 260 characters (value of MAX_PATH),
%   some at 259 already. Don't blame me.
%   The 'fat' style is useful e.g. when Matlab's DIR command is called for a
%   folder with les than 260 characters, but together with the file name this
%   limit is exceeded. Then "dir(getFullPath([folder, '\*.*], 'fat'))" helps.
%
% EXAMPLES:
%   cd(tempdir);                    % Assumed as 'C:\Temp' here
%   getFullPath('File.Ext')         % 'C:\Temp\File.Ext'
%   getFullPath('..\File.Ext')      % 'C:\File.Ext'
%   getFullPath('..\..\File.Ext')   % 'C:\File.Ext'
%   getFullPath('.\File.Ext')       % 'C:\Temp\File.Ext'
%   getFullPath('*.txt')            % 'C:\Temp\*.txt'
%   getFullPath('..')               % 'C:\'
%   getFullPath('..\..\..')         % 'C:\'
%   getFullPath('Folder\')          % 'C:\Temp\Folder\'
%   getFullPath('D:\A\..\B')        % 'D:\B'
%   getFullPath('\\Server\Folder\Sub\..\File.ext')
%                                   % '\\Server\Folder\File.ext'
%   getFullPath({'..', 'new'})      % {'C:\', 'C:\Temp\new'}
%   getFullPath('.', 'fat')         % '\\?\C:\Temp\File.Ext'
%
% COMPILE:
%   Automatic: InstallMex getFullPath.c uTest_getFullPath
%   Manual:    mex -O getFullPath.c
%   Download:  http://www.n-simon.de/mex
% Run the unit-test uTest_getFullPath after compiling.
%
% Tested: Matlab 6.5, 7.7, 7.8, 7.13, WinXP/32, Win7/64
%         Compiler: LCC2.4/3.8, BCC5.5, OWC1.8, MSVC2008/2010
% Assumed Compatibility: higher Matlab versions
% Author: Jan Simon, Heidelberg, (C) 2009-2013 matlab.THISYEAR(a)nMINUSsimon.de
%
% See also: CD, FULLFILE, FILEPARTS.

% $JRev: R-G V:032 Sum:7Xd/JS0+yfax Date:15-Jan-2013 01:06:12 $
% $License: BSD (use/copy/change/redistribute on own risk, mention the author) $
% $UnitTest: uTest_getFullPath $
% $File: Tools\GLFile\getFullPath.m $
% History:
% 001: 20-Apr-2010 22:28, Successor of Rel2AbsPath.
% 010: 27-Jul-2008 21:59, Consider leading separator in M-version also.
% 011: 24-Jan-2011 12:11, Cell strings, '~File' under linux.
%      Check of input types in the M-version.
% 015: 31-Mar-2011 10:48, BUGFIX: Accept [] as input as in the Mex version.
%      Thanks to Jiro Doke, who found this bug by running the test function for
%      the M-version.
% 020: 18-Oct-2011 00:57, BUGFIX: Linux version created bad results.
%      Thanks to Daniel.
% 024: 10-Dec-2011 14:00, Care for long names under Windows in M-version.
%      Improved the unittest function for Linux. Thanks to Paul Sexton.
% 025: 09-Aug-2012 14:00, In MEX: Paths starting with "\\" can be non-UNC.
%      The former version treated "\\?\C:\<longpath>\file" as UNC path and
%      replied "\\?\UNC\?\C:\<longpath>\file".
% 032: 12-Jan-2013 21:16, 'auto', 'lean' and 'fat' style.

% Initialize: ==================================================================
% Do the work: =================================================================

% #############################################
% ### USE THE MUCH FASTER MEX ON WINDOWS!!! ###
% #############################################

% Difference between M- and Mex-version:
% - Mex does not work under MacOS/Unix.
% - Mex calls Windows API function getFullPath.
% - Mex is much faster.

% Magix prefix for long Windows names:
if nargin < 2
    Style = 'auto';
end

% Handle cell strings: NOTE: It is faster to create a function
% @cell\getFullPath.m under Linux, but under Windows this would shadow the
% fast C-Mex.
if isa(File, 'cell')
    for iC = 1:numel(File)
        File{iC} = getFullPath(File{iC}, Style);
    end
    return;
end

% Check this once only:
isWIN    = strncmpi(computer, 'PC', 2);
MAX_PATH = 260;

% Warn once per session (disable this under Linux/MacOS):
persistent hasDataRead
if isempty(hasDataRead)
    % Test this once only - there is no relation to the existence of
    % DATAREAD!
    %if isWIN
    %   Show a warning, if the slower Matlab version is used - commented,
    %   because this is not a problem and it might be even useful when the
    %   MEX-folder is not inlcuded in the path yet.
    %   warning('JSimon:getFullPath:NoMex', ...
    %      ['getFullPath: Using slow Matlab-version instead of fast Mex.',
    %      ...
    %       char(10), 'Compile: InstallMex getFullPath.c']);
    %end

    % DATAREAD is deprecated in 2011b, but still available. In Matlab 6.5,
    % REGEXP does not know the 'split' command, therefore DATAREAD is
    % preferred:
    hasDataRead = ~isempty(which('dataread'));
end

if isempty(File)  % Accept empty matrix as input:
    if ischar(File) || isnumeric(File)
        File = cd;
        return;
    else
        error(['JSimon:', mfilename, ':BadTypeInput1'], ...
            ['*** ', mfilename, ': Input must be a string or cell string']);
    end
end

if ischar(File) == 0  % Non-empty inputs must be strings
    error(['JSimon:', mfilename, ':BadTypeInput1'], ...
        ['*** ', mfilename, ': Input must be a string or cell string']);
end

if isWIN  % Windows: --------------------------------------------------------
    FSep = '\';
    File = strrep(File, '/', FSep);

    % Remove the magic key on demand, it is appended finally again:
    if strncmp(File, '\\?\', 4)
        if strncmpi(File, '\\?\UNC\', 8)
            File = ['\', File(7:length(File))];  % Two leading backslashes!
        else
            File = File(5:length(File));
        end
    end

    isUNC   = strncmp(File, '\\', 2);
    FileLen = length(File);
    if isUNC == 0                        % File is not a UNC path
        % Leading file separator means relative to current drive or base
        % folder:
        ThePath = cd;
        if File(1) == FSep
            if strncmp(ThePath, '\\', 2)   % Current directory is a UNC path
                sepInd  = strfind(ThePath, '\');
                ThePath = ThePath(1:sepInd(4));
            else
                ThePath = ThePath(1:3);     % Drive letter only
            end
        end

        if FileLen < 2 || File(2) ~= ':'  % Does not start with drive letter
            if ThePath(length(ThePath)) ~= FSep
                if File(1) ~= FSep
                    File = [ThePath, FSep, File];
                else                        % File starts with separator:
                    File = [ThePath, File];
                end
            else                           % Current path ends with separator:
                if File(1) ~= FSep
                    File = [ThePath, File];
                else                        % File starts with separator:
                    ThePath(length(ThePath)) = [];
                    File = [ThePath, File];
                end
            end

        elseif FileLen == 2 && File(2) == ':'   % "C:" current directory on C!
            % "C:" is the current directory on the C-disk, even if the
            % current directory is on another disk! This was ignored in
            % Matlab 6.5, but modern versions considers this strange
            % behaviour.
            if strncmpi(ThePath, File, 2)
                File = ThePath;
            else
                try
                    File = cd(cd(File));
                catch    % No MException to support Matlab6.5...
                    if exist(File, 'dir')  % No idea what could cause an error then!
                        rethrow(lasterror);
                    else  % Reply "K:\" for not existing disk:
                        File = [File, FSep];
                    end
                end
            end
        end
    end

else         % Linux, MacOS: ---------------------------------------------------
    FSep = '/';
    File = strrep(File, '\', FSep);

    if strcmp(File, '~') || strncmp(File, '~/', 2)  % Home directory:
        HomeDir = getenv('HOME');
        if ~isempty(HomeDir)
            File(1) = [];
            File    = [HomeDir, File];
        end

    elseif strncmpi(File, FSep, 1) == 0
        % Append relative path to current folder:
        ThePath = cd;
        if ThePath(length(ThePath)) == FSep
            File = [ThePath, File];
        else
            File = [ThePath, FSep, File];
        end
    end
end

% Care for "\." and "\.." - no efficient algorithm, but the fast Mex is
% recommended at all!
if ~isempty(strfind(File, [FSep, '.']))
    if isWIN
        if strncmp(File, '\\', 2)  % UNC path
            index = strfind(File, '\');
            if length(index) < 4    % UNC path without separator after the folder:
                return;
            end
            Drive            = File(1:index(4));
            File(1:index(4)) = [];
        else
            Drive     = File(1:3);
            File(1:3) = [];
        end
    else  % Unix, MacOS:
        isUNC   = false;
        Drive   = FSep;
        File(1) = [];
    end

    hasTrailFSep = (File(length(File)) == FSep);
    if hasTrailFSep
        File(length(File)) = [];
    end

    if hasDataRead
        if isWIN  % Need "\\" as separator:
            C = dataread('string', File, '%s', 'delimiter', '\\');  %#ok<REMFF1>
        else
            C = dataread('string', File, '%s', 'delimiter', FSep);  %#ok<REMFF1>
        end
    else  % Use the slower REGEXP, when DATAREAD is not available anymore:
        C = regexp(File, FSep, 'split');
    end

    % Remove '\.\' directly without side effects:
    C(strcmp(C, '.')) = [];

    % Remove '\..' with the parent recursively:
    R = 1:length(C);
    for dd = reshape(find(strcmp(C, '..')), 1, [])
        index    = find(R == dd);
        R(index) = [];
        if index > 1
            R(index - 1) = [];
        end
    end

    if isempty(R)
        File = Drive;
        if isUNC && ~hasTrailFSep
            File(length(File)) = [];
        end

    elseif isWIN
        % If you have CStr2String, use the faster:
        %   File = CStr2String(C(R), FSep, hasTrailFSep);
        File = sprintf('%s\\', C{R});
        if hasTrailFSep
            File = [Drive, File];
        else
            File = [Drive, File(1:length(File) - 1)];
        end

    else  % Unix:
        File = [Drive, sprintf('%s/', C{R})];
        if ~hasTrailFSep
            File(length(File)) = [];
        end
    end
end

% "Very" long names under Windows:
if isWIN
    if ~ischar(Style)
        error(['JSimon:', mfilename, ':BadTypeInput2'], ...
            ['*** ', mfilename, ': Input must be a string or cell string']);
    end

    if (strncmpi(Style, 'a', 1) && length(File) >= MAX_PATH) || ...
            strncmpi(Style, 'f', 1)
        % Do not use [isUNC] here, because this concerns the input, which
        % can '.\File', while the current directory is an UNC path.
        if strncmp(File, '\\', 2)  % UNC path
            File = ['\\?\UNC', File(2:end)];
        else
            File = ['\\?\', File];
        end
    end
end

% return;
end


function blkStruct = slblocks
%SLBLOCKS Define the Simulink library block representation.
%
%    Define the Simulink library block representation for the Testing

%    CP 10-11-05
%    Copyright 2005-2006, Fraunhofer FOKUS
%    $Revision: 1.0.0.0 $  $Date: 2005/11/10 20:11:50 $
%    $Revision: 1.0.0.0 $  $Date: 2006/07/10 20:11:50 $

blkStruct.Name    = 'MIL Test Blockset';
% The function that is called when
% the user double-clicks on this icon.
blkStruct.OpenFcn = 'MIL_Test';
blkStruct.MaskInitialization = '';

% Define the library list for the Simulink Library browser.
% Return the name of the library model and the name for it
Browser(1).Library = 'MIL_Test';
Browser(1).Name    = 'MIL Test Blockset';
%Browser(1).IsFlat  = 1;% Is this library "flat" (i.e. no subsystems)?

blkStruct.Browser = Browser;

% End of slblocks.m


classdef SettingsHomogenizedVarComputer < AbstractSettings

    properties (Access = public)
        type
        designVariable
        dim
    end

    methods (Access = public, Static)

        function obj = create(cParams)
            factory = SettingsHomogenizedVarComputerFactory();
            obj     = factory.create(cParams);
        end

    end

end


classdef prtUiControl < hgsetget

    properties

        handle
    end

    properties (Dependent)
        backgroundColor
        beingDeleted
        busyAction
        buttonDownFcn
        callback
        cData
        children
        createFcn
        deleteFcn
        enable
        extent
        fontAngle
        fontName
        fontSize
        fontUnits
        fontWeight
        foregroundColor
        handleVisibility
        hitTest
        horizontalAlignment
        interruptible
        keyPressFcn
        listboxTop
        max
        min
        parent
        position
        selected
        selectionHighlight
        sliderStep
        string
        style
        tag
        tooltipString
        type
        uiContextMenu
        units
        userData
        value
        visible
    end
    methods
        function self = prtUiControl(varargin)
            self.handle = uicontrol(varargin{:});
        end

        function set.backgroundColor(self, val)
            set(self.handle,'backgroundColor',val);
        end
        function val = get.backgroundColor(self)
            val = get(self.handle,'backgroundColor');
        end
        function set.beingDeleted(self, val)
            set(self.handle,'beingDeleted',val);
        end
        function val = get.beingDeleted(self)
            val = get(self.handle,'beingDeleted');
        end
        function set.busyAction(self, val)
            set(self.handle,'busyAction',val);
        end
        function val = get.busyAction(self)
            val = get(self.handle,'busyAction');
        end
        function set.buttonDownFcn(self, val)
            set(self.handle,'buttonDownFcn',val);
        end
        function val = get.buttonDownFcn(self)
            val = get(self.handle,'buttonDownFcn');
        end
        function set.callback(self, val)
            set(self.handle,'callback',val);
        end
        function val = get.callback(self)
            val = get(self.handle,'callback');
        end
        function set.cData(self, val)
            set(self.handle,'cData',val);
        end
        function val = get.cData(self)
            val = get(self.handle,'cData');
        end
        function set.children(self, val)
            set(self.handle,'children',val);
        end
        function val = get.children(self)
            val = get(self.handle,'children');
        end
        function set.createFcn(self, val)
            set(self.handle,'createFcn',val);
        end
        function val = get.createFcn(self)
            val = get(self.handle,'createFcn');
        end
        function set.deleteFcn(self, val)
            set(self.handle,'deleteFcn',val);
        end
        function val = get.deleteFcn(self)
            val = get(self.handle,'deleteFcn');
        end
        function set.enable(self, val)
            set(self.handle,'enable',val);
        end
        function val = get.enable(self)
            val = get(self.handle,'enable');
        end
        function set.extent(self, val)
            set(self.handle,'extent',val);
        end
        function val = get.extent(self)
            val = get(self.handle,'extent');
        end
        function set.fontAngle(self, val)
            set(self.handle,'fontAngle',val);
        end
        function val = get.fontAngle(self)
            val = get(self.handle,'fontAngle');
        end
        function set.fontName(self, val)
            set(self.handle,'fontName',val);
        end
        function val = get.fontName(self)
            val = get(self.handle,'fontName');
        end
        function set.fontSize(self, val)
            set(self.handle,'fontSize',val);
        end
        function val = get.fontSize(self)
            val = get(self.handle,'fontSize');
        end
        function set.fontUnits(self, val)
            set(self.handle,'fontUnits',val);
        end
        function val = get.fontUnits(self)
            val = get(self.handle,'fontUnits');
        end
        function set.fontWeight(self, val)
            set(self.handle,'fontWeight',val);
        end
        function val = get.fontWeight(self)
            val = get(self.handle,'fontWeight');
        end
        function set.foregroundColor(self, val)
            set(self.handle,'foregroundColor',val);
        end
        function val = get.foregroundColor(self)
            val = get(self.handle,'foregroundColor');
        end
        function set.handleVisibility(self, val)
            set(self.handle,'handleVisibility',val);
        end
        function val = get.handleVisibility(self)
            val = get(self.handle,'handleVisibility');
        end
        function set.hitTest(self, val)
            set(self.handle,'hitTest',val);
        end
        function val = get.hitTest(self)
            val = get(self.handle,'hitTest');
        end
        function set.horizontalAlignment(self, val)
            set(self.handle,'horizontalAlignment',val);
        end
        function val = get.horizontalAlignment(self)
            val = get(self.handle,'horizontalAlignment');
        end
        function set.interruptible(self, val)
            set(self.handle,'interruptible',val);
        end
        function val = get.interruptible(self)
            val = get(self.handle,'interruptible');
        end
        function set.keyPressFcn(self, val)
            set(self.handle,'keyPressFcn',val);
        end
        function val = get.keyPressFcn(self)
            val = get(self.handle,'keyPressFcn');
        end
        function set.listboxTop(self, val)
            set(self.handle,'listboxTop',val);
        end
        function val = get.listboxTop(self)
            val = get(self.handle,'listboxTop');
        end
        function set.max(self, val)
            set(self.handle,'max',val);
        end
        function val = get.max(self)
            val = get(self.handle,'max');
        end
        function set.min(self, val)
            set(self.handle,'min',val);
        end
        function val = get.min(self)
            val = get(self.handle,'min');
        end
        function set.parent(self, val)
            set(self.handle,'parent',val);
        end
        function val = get.parent(self)
            val = get(self.handle,'parent');
        end
        function set.position(self, val)
            set(self.handle,'position',val);
        end
        function val = get.position(self)
            val = get(self.handle,'position');
        end
        function set.selected(self, val)
            set(self.handle,'selected',val);
        end
        function val = get.selected(self)
            val = get(self.handle,'selected');
        end
        function set.selectionHighlight(self, val)
            set(self.handle,'selectionHighlight',val);
        end
        function val = get.selectionHighlight(self)
            val = get(self.handle,'selectionHighlight');
        end
        function set.sliderStep(self, val)
            set(self.handle,'sliderStep',val);
        end
        function val = get.sliderStep(self)
            val = get(self.handle,'sliderStep');
        end
        function set.string(self, val)
            set(self.handle,'string',val);
        end
        function val = get.string(self)
            val = get(self.handle,'string');
        end
        function set.style(self, val)
            set(self.handle,'style',val);
        end
        function val = get.style(self)
            val = get(self.handle,'style');
        end
        function set.tag(self, val)
            set(self.handle,'tag',val);
        end
        function val = get.tag(self)
            val = get(self.handle,'tag');
        end
        function set.tooltipString(self, val)
            set(self.handle,'tooltipString',val);
        end
        function val = get.tooltipString(self)
            val = get(self.handle,'tooltipString');
        end
        function set.type(self, val)
            set(self.handle,'type',val);
        end
        function val = get.type(self)
            val = get(self.handle,'type');
        end
        function set.uiContextMenu(self, val)
            set(self.handle,'uiContextMenu',val);
        end
        function val = get.uiContextMenu(self)
            val = get(self.handle,'uiContextMenu');
        end
        function set.units(self, val)
            set(self.handle,'units',val);
        end
        function val = get.units(self)
            val = get(self.handle,'units');
        end
        function set.userData(self, val)
            set(self.handle,'userData',val);
        end
        function val = get.userData(self)
            val = get(self.handle,'userData');
        end
        function set.value(self, val)
            set(self.handle,'value',val);
        end
        function val = get.value(self)
            val = get(self.handle,'value');
        end
        function set.visible(self, val)
            set(self.handle,'visible',val);
        end
        function val = get.visible(self)
            val = get(self.handle,'visible');
        end
    end
end


classdef MimImportNewManualSegmentation < MimGuiPlugin
    % MimImportNewManualSegmentation. Gui Plugin
    %
    %     You should not use this class within your own code. It is intended to
    %     be used by the gui of the TD MIM Toolkit.
    %
    %     MimImportNewManualSegmentation 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 = 'Import new segmentation'
        SelectedText = 'Import new segmentation'
        ToolTip = 'Imports a new segmentation from an external file'
        Category = 'Segment region'
        Visibility = 'Dataset'
        Mode = 'Segment'

        Icon = 'add_patch.png'
        Location = 26

        HidePluginInDisplay = false
        PTKVersion = '1'
        ButtonWidth = 6
        ButtonHeight = 2
    end

    methods (Static)
        function RunGuiPlugin(gui_app)
            gui_app.ImportManualSegmentation();
        end

        function enabled = IsEnabled(gui_app)
            enabled = gui_app.IsDatasetLoaded;
        end

    end
end


function obj = as_channeltag(obj)
   switch(class(obj))
      case 'ChannelTag' %good. do nothing.
      case 'scnlobject'
         obj = get(obj, 'channeltag');
      otherwise
         obj = ChannelTag(obj); %attempt natural conversion
         % should be able to handle 'N.S.L.C'
   end
end


function [params] = backwardCompatible(params, fieldNames, defaultValue)
  for ii=1:length(fieldNames)
    field = fieldNames{ii};
    if ~isfield(params, field)
      params.(field) = defaultValue;
    end
  end
end


function [] = emailme(x)
%% Send email message when simulation finish to my Gmail account
% Based on:
% http://obasic.net/how-to-send-e-mail-from-matlab
%
% Coded by: Manuel Diaz

%% Set Parameters of my Gmail Account
setpref('Internet', 'E_mail', 'manuel.ade@gmail.com');
setpref('Internet', 'SMTP_Username', 'manuel.ade@gmail.com');
setpref('Internet', 'SMTP_Password', 'xxxxxx');
setpref('Internet', 'SMTP_Server', 'smtp.gmail.com');
props = java.lang.System.getProperties;
props.setProperty('mail.smtp.auth','true');
props.setProperty('mail.smtp.socketFactory.class', 'javax.net.ssl.SSLSocketFactory');
props.setProperty('mail.smtp.socketFactory.port', '465');

if x == 'yes'; % Send message
sendmail('manuel.ade@gmail.com', 'Mail from XXX', ...
    ['Hello Mr. Diaz! This is a mesage from XXX!' 10 ...
     'Your simulation has completed succesfully']);
end


function test_suite = test_a_bit
initTestSuite

function test_now

function test_later


function varargout = BrowserCurationGUI(varargin)
% BROWSERCURATIONGUI MATLAB code for BrowserCurationGUI.fig
%      BROWSERCURATIONGUI, by itself, creates a new BROWSERCURATIONGUI or raises the existing
%      singleton*.
%
%      H = BROWSERCURATIONGUI returns the handle to a new BROWSERCURATIONGUI or the handle to
%      the existing singleton*.
%
%      BROWSERCURATIONGUI('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in BROWSERCURATIONGUI.M with the given input arguments.
%
%      BROWSERCURATIONGUI('Property','Value',...) creates a new BROWSERCURATIONGUI or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before BrowserCurationGUI_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to BrowserCurationGUI_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help BrowserCurationGUI

% Last Modified by GUIDE v2.5 20-Jul-2011 14:25:09

% Begin initialization code - DO NOT EDIT
gui_Singleton = 0;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @BrowserCurationGUI_OpeningFcn, ...
                   'gui_OutputFcn',  @BrowserCurationGUI_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end

% BrowserCurationGUI(browserObj,curationCfg)
% browserObj: handle to OlyDat.Browser object
% curationCfg: struct array providing curation fields. curationCfg
% configures the ith column in the curation table. Note that the 1st column
% is reserved for the "excluded" column. curationCfg fields:
%   * Name: curation field name
%   * TableName: name for column header in table
%   * TableColWidth: width in pixels for col. 0 indicates auto-size.
function BrowserCurationGUI_OpeningFcn(hObject, eventdata, handles, varargin)

handles.output = hObject;
handles.browser = varargin{1};
handles.curationCfg = varargin{2};
handles.selectedCell = [];

% table metadata
handles.tableMetadataExcludedColIdx = 1;
handles.tableMetadataCurationField2Col = struct();
handles.tableMetadataCol2Field = {''}; % first col is empty for excluded col

NcurationCfg = numel(handles.curationCfg);
for cfgIdx = 1:NcurationCfg
    name = handles.curationCfg(cfgIdx).Name;
    handles.tableMetadataCurationField2Col.(name) = cfgIdx+1;
    handles.tableMetadataCol2Field{cfgIdx+1,1} = name;
end

% configure table based on tableMetadata
Ncol = NcurationCfg+1;
tfColEditable = false(1,Ncol);
tfColEditable(handles.tableMetadataExcludedColIdx) = true; % excluded col is editable; rest are not
colFmt = cell(1,Ncol);
colFmt{1} = 'logical'; % unused, see below
colNames = [{'Excluded'} {handles.curationCfg.TableName}];
colWidths = [{60} {handles.curationCfg.TableColWidth}];
for colIdx = 1:Ncol
    if colWidths{colIdx}==0
        colWidths{colIdx} = 'auto';
    end
end

% (*) AL 1/5/2012: including ColumnFormat in the set leads to a SEGV on
% maci64. This is consistent/reproduceable. However simply leaving out the
% ColumnFormat set seems to work fine. The ColumnFormat property will not
% have the right size (eg will not have Ncol number of elements), but
% in this situation MATLAB appears to just use auto-formatting for all
% columns and for now that is working fine.
set(handles.tblCuration,'ColumnEditable',tfColEditable,... % 'ColumnFormat',colFmt,... (*) see above
                        'ColumnName',colNames,...
                        'ColumnWidth',colWidths,...
                        'Data',cell(1,Ncol));

% context menu
uh = uicontextmenu;
uimenu(uh,'label','Enter Curation Info','Callback',@ctxtMnuEnterCurationInfo);
uimenu(uh,'label','Clear Curation Info','Callback',@ctxtMnuClearCurationInfo);
uimenu(uh,'label','Sort Ascending','Callback',@ctxtMnuSortAscending,'Separator','on');
uimenu(uh,'label','Sort Descending','Callback',@ctxtMnuSortDescending);
uimenu(uh,'label','Bring Excluded/Marked to Top','Callback',@ctxtMnuBringExcludedMarkedToTop);
set(handles.tblCuration,'UIContextMenu',uh);

% handles.tableMetadataCurationField2Col = struct('experiment_id',2,'experiment_name',3,'manual_pf',4,
% 'notes_curation',5,'flag_redo',6,'flag_review',7,'manual_curation_date',8,'manual_curator',9);
% handles.tableMetadataCol2Field = {'';'experiment_id';'experiment_name';'manual_pf';'notes_curation';
%     'flag_redo';'flag_review';'manual_curation_date';'manual_curator'};

guidata(hObject,handles);

% This gui is custom-resizeable
set(handles.uipanel1,'Units','Normalized');

% Explicitly call resizefcn b/c the orig layout is not precisely consistent
% with what is done in resize.
uipanel1_ResizeFcn(handles.uipanel1,[],handles);

centerfig(hObject);

function uipanel1_ResizeFcn(hObject,~,handles)
TBLCURATION_Y_TOP_SPACER = 8.0;
TBLCURATION_Y_BOTTOM_SPACER = 10.0;
TBLCURATION_X_SPACER = 8.0;
TBL_CURATION_BETWEEN_BUTTONS_X_SPACER = 3.0;
TBL_CURATION_AFTER_BUTTONS_X_SPACER = 11.0;

% get panel width/height in pixels
origUnits = get(hObject,'Units');
set(hObject,'Units','pixels');
pnlPos = get(hObject,'Position');
set(hObject,'Units',origUnits);
pnlWidth = pnlPos(3);
pnlHeight = pnlPos(4);

% get top posn of unexclude all button
pbUnexcludeAllPos = get(handles.pbUnexcludeAll,'Position');
pbTopPosInPixels = pbUnexcludeAllPos(2)+pbUnexcludeAllPos(4);

% set tbl position
tblPos(1) = TBLCURATION_X_SPACER;
tblPos(2) = pbTopPosInPixels + TBLCURATION_Y_BOTTOM_SPACER;
tblPos(3) = pnlWidth-2.0*TBLCURATION_X_SPACER;
tblPos(4) = pnlHeight-tblPos(2)-TBLCURATION_Y_TOP_SPACER;
set(handles.tblCuration,'Position',tblPos);

% set posn of UnexcludeAll, MarkAllCurated buttons
pbMarkAllUncuratedPos = get(handles.pbMarkAllUncuratedAsPass,'Position');
pbUnexcludeAllXPos = pnlWidth - pbUnexcludeAllPos(3) - pbMarkAllUncuratedPos(3) ...
    - TBL_CURATION_BETWEEN_BUTTONS_X_SPACER - TBL_CURATION_AFTER_BUTTONS_X_SPACER;
pbUnexcludeAllPos(1) = pbUnexcludeAllXPos;
pbMarkAllUncuratedXPos = pnlWidth - pbMarkAllUncuratedPos(3) - TBL_CURATION_AFTER_BUTTONS_X_SPACER;
pbMarkAllUncuratedPos(1) = pbMarkAllUncuratedXPos;
set(handles.pbUnexcludeAll,'Position',pbUnexcludeAllPos);
set(handles.pbMarkAllUncuratedAsPass,'Position',pbMarkAllUncuratedPos);

function figure1_ResizeFcn(~,~,~)
%none

function varargout = BrowserCurationGUI_OutputFcn(hObject, eventdata, handles)
varargout{1} = handles.output;

% A note on exp selection. When rows of the CurationGUI are selected, the
% corresponding experiments are selected in the Browser. However, when
% experiments are selected in the Browser, the corresponding rows of the
% curationGUI are NOT selected. The primary reason for this is that the
% native ML tables do not permit programmatically setting their selection.

function tblCuration_CellSelectionCallback(hObject,eventdata,handles)
if ~isempty(eventdata.Indices)
    handles.selectedCell = eventdata.Indices;
    guidata(hObject,handles);
    zlclSelectExperimentsInBrowserBasedOnSelectedCellCache(handles);
else
    handles.selectedCell = [];
    guidata(hObject,handles);
end

function tblCuration_CellEditCallback(hObject, eventdata, handles) %#ok<*INUSL,*DEFNU>
% If there are multiple selections in the table, the upper-left-most will be used
rowIdx = eventdata.Indices(1,1);
colIdx = eventdata.Indices(1,2);
data = get(hObject,'Data');

switch colIdx
    case handles.tableMetadataExcludedColIdx
        % 'excluded' column

        % Make sure this experiment (row) is selected. This may be
        % unnecessary, ie if tblCuration_CellSelectionCallback is always
        % called first.
        expID = data{rowIdx,handles.tableMetadataCurationField2Col.experiment_id};
        handles.browser.selectExperiment(expID);

        tf = eventdata.NewData;
        handles.browser.setRemoveExp(tf,false);

        parentFigure = ancestor(hObject,'figure');
        uistack(parentFigure,'top');
    otherwise
        assert(false,'This no longer ever occurs');
end

% This is unused
% function s = zlclRow2CurationInfoStruct(row,handles)
% flds = handles.tableMetadataCol2Field;
% Nflds = numel(flds);
% assert(numel(row)==Nflds);
% s = struct();
% for c = 1:Nflds
%     if ~isempty(flds{c}) % excluded col will have an empty field
%         val = row{c};
%         if ischar(val)
%             % convert empty option ' ' to ''
%             val = strtrim(val);
%         end
%         s.(flds{c}) = val;
%     end
% end

%%% ACTIONS/HELPERS
function zlclSelectExperimentsInBrowserBasedOnSelectedCellCache(handles)
rowIdxs = handles.selectedCell(:,1);
data = get(handles.tblCuration,'Data');
eids = data(rowIdxs,handles.tableMetadataCurationField2Col.experiment_id);
handles.browser.selectExperiment(cell2mat(eids));

function zlclDisplaySelectCellMsgBox(msg)
msgbox(msg,'No cell selected');

function zlclActionEnterCurationMarks(handles)
if isempty(handles.selectedCell)
    zlclDisplaySelectCellMsgBox('Please select a cell to specify a row.');
else
    % select experiments in the Browser and open CurationInfoEntry.
    zlclSelectExperimentsInBrowserBasedOnSelectedCellCache(handles);
    handles.browser.curationOpenCurationInfoEntry();
end

function zlclActionClearCurationMarks(handles)
if isempty(handles.selectedCell)
    zlclDisplaySelectCellMsgBox('Please select a cell to specify a row.');
else
    zlclSelectExperimentsInBrowserBasedOnSelectedCellCache(handles);
    handles.browser.curationClearCurationInfoForCurrentExp();
end

function zlclSortByData(tableH,sortData,dir)
data = get(tableH,'Data');
assert(size(data,1)==numel(sortData(:)));

[~,idx] = sort(sortData(:));
switch dir
    case 'ascend'
        %none
    case 'descend'
        idx = idx(end:-1:1);
end

data = data(idx,:);
set(tableH,'Data',data);

function zlclSortHelper(handles,direction)
if isempty(handles.selectedCell)
    zlclDisplaySelectCellMsgBox('Select a cell to specify a column for sorting.');
else
    data = get(handles.tblCuration,'Data');
    colIdx = handles.selectedCell(1,2); % use column of first selected cell
    colData = data(:,colIdx);
    if isnumeric(colData{1}) || islogical(colData{1})
        colData = cell2mat(colData);
    end
    zlclSortByData(handles.tblCuration,colData,direction);

    % After setting the table data to a new value, MATLAB de-selects any
    % selected cells. Ideally, would like to have the original cell (in
    % terms of coordinates) selected, so that the user may eg 'sort
    % ascending', then immediately 'sort descending' if they got the wrong
    % direction. Unfortunately, this is not possible with the ML uitable
    % without dropping into Java; this is a potentialy maintenance
    % dependency so for now we don't do it. To sort one way and then the
    % other, the user will have to re-select a cell in the appropriate
    % column.
end

% At the moment, this checks for marking by checking the manual_curator
% field (hardcoded).
function zlclBringExcludedMarkedToTop(handles)
data = get(handles.tblCuration,'Data');
Nrows = size(data,1);

excludedColIdx = handles.tableMetadataExcludedColIdx;
if isfield(handles.tableMetadataCurationField2Col,'manual_curator')
  % todo: this should not be hardcoded against manual_curator
  manualCuratorColIdx = handles.tableMetadataCurationField2Col.manual_curator;
  tfManualCuration = true;
else
  tfManualCuration = false;
end

indicator = false(Nrows,1);
for c = 1:Nrows
    row = data(c,:);

    tfExcluded = row{excludedColIdx};
    if tfExcluded
        indicator(c) = true;
        continue;
    end

    if tfManualCuration && ~isempty(row{manualCuratorColIdx})
        indicator(c) = true;
    end
end
zlclSortByData(handles.tblCuration,indicator,'descend');

%%% BUTTONS
function pbEnterCurationMarks_Callback(hObject,eventdata,handles)
zlclActionEnterCurationMarks(handles);

function pbClearMarks_Callback(hObject,eventdata,handles)
zlclActionClearCurationMarks(handles);

function pbUnexcludeAll_Callback(hObject, eventdata, handles)
handles.browser.unexcludeAllExps();

function pbMarkAllUncuratedAsPass_Callback(hObject, eventdata, handles)
handles.browser.curationMarkAllUncuratedAsPass();

%%% CONTEXT MENU
function ctxtMnuEnterCurationInfo(src,~)
zlclActionEnterCurationMarks(guidata(src));

function ctxtMnuClearCurationInfo(src,~)
zlclActionClearCurationMarks(guidata(src));

function ctxtMnuSortAscending(src,~)
zlclSortHelper(guidata(src),'ascend');

function ctxtMnuSortDescending(src,~)
zlclSortHelper(guidata(src),'descend');

function ctxtMnuBringExcludedMarkedToTop(src,~)
zlclBringExcludedMarkedToTop(guidata(src));

%%% REGULAR MENU
function mnuFileLoad_Callback(hObject, eventdata, handles)
handles.browser.curationLoadCurationFile();

function mnuFileAppend_Callback(hObject, eventdata, handles)
handles.browser.curationAppendCurationDataToFile();

function mnuFileWriteNew_Callback(hObject, eventdata, handles)
handles.browser.curationWriteCurationDataToNewFile();

function mnuSortAscending_Callback(hObject,eventdata,handles)
zlclSortHelper(handles,'ascend');

function mnuSortDescending_Callback(hObject,eventdata,handles)
zlclSortHelper(handles,'descend');

function mnuBringExcludedMarkedToTop_Callback(hObject,eventdata,handles)
zlclBringExcludedMarkedToTop(handles);


function str = showdetail(item)

% function str = showdetail(item)
% Display details for a cfg_choice and all of its options.
%
% This code is part of a batch job configuration system for MATLAB. See
%      help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging

% Volkmar Glauche
% $Id: showdetail.m 4867 2012-08-30 13:04:51Z volkmar $

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

str = showdetail(item.cfg_item);
str{end+1} = 'Class  : cfg_mchoice';
str{end+1} = ['Set one or more of the options listed as a struct with a ' ...
              'fields:'];
% Display detailed help for each cfg_choice value item
tags = tagnames(item, true);
for k = 1:numel(tags)
    str{end+1} = sprintf('.%s', tags{k});
end;


function varargout = TabPanel(varargin)
% TABPANEL M-file for TabPanel.fig
%      TABPANEL, by itself, creates a new TABPANEL or raises the existing
%      singleton*.
%
%      H = TABPANEL returns the handle to a new TABPANEL or the handle to
%      the existing singleton*.
%
%      TABPANEL('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in TABPANEL.M with the given input arguments.
%
%      TABPANEL('Property','Value',...) creates a new TABPANEL or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before TabPanel_OpeningFunction gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to TabPanel_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help TabPanel

% Last Modified by GUIDE v2.5 20-Apr-2004 10:07:56

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @TabPanel_OpeningFcn, ...
                   'gui_OutputFcn',  @TabPanel_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin & isstr(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before TabPanel is made visible.
function TabPanel_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to TabPanel (see VARARGIN)

% Choose default command line output for TabPanel
handles.output = hObject;

% uicontrols handles list for tabA and tabB respectively
handles.tabA = [ handles.txNullA, handles.pbNullA, handles.axDisplay ];
handles.tabB = [ handles.txNullB, handles.pbNullB, handles.pbTest, ...
                 handles.chTest,  handles.lbTest, handles.rbTest ];

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes TabPanel wait for user response (see UIRESUME)
% uiwait(handles.TabPanel);

% --- Outputs from this function are returned to the command line.
function varargout = TabPanel_OutputFcn(hObject, eventdata, handles)
% Get default command line output from handles structure
varargout{1} = handles.output;

% --- If Enable == 'on', executes on mouse press in 5 pixel border.
% --- Otherwise, executes on mouse press in 5 pixel border or over tabA.
function tabA_ButtonDownFcn(hObject, eventdata, handles)
%
set(handles.tabA, 'Visible', 'on');
set(handles.tabB, 'Visible', 'off');

% --- If Enable == 'on', executes on mouse press in 5 pixel border.
% --- Otherwise, executes on mouse press in 5 pixel border or over tabB.
function tabB_ButtonDownFcn(hObject, eventdata, handles)
%

set(handles.tabA, 'Visible', 'off');
set(handles.tabB, 'Visible', 'on');

% --- Executes on selection change in lbTest.
function lbTest_Callback(hObject, eventdata, handles)

% --- Executes on button press in chTest.
function chTest_Callback(hObject, eventdata, handles)

% --- Executes on button press in pbTest.
function pbTest_Callback(hObject, eventdata, handles)

oStr = get( handles.lbTest, 'String');
nStr = 'Thanx. I needed it!';
lbStr = strvcat(oStr, nStr);
set( handles.lbTest, 'String', lbStr);

% --- Executes on button press in rbTest.
function rbTest_Callback(hObject, eventdata, handles)

% --- Executes on button press in pbNullB.
function pbNullB_Callback(hObject, eventdata, handles)


function scrollWheel(fig,stats)
% function scrollWheel(fig,stats)
%
% Callback function for the mouse scrollWheel.
%
% APA, 2/29/2016

global stateS

if ~stateS.planLoaded
    return;
end

if stats.VerticalScrollCount > 0
    sliceCallBack('ChangeSlc','prevslice')
else
    sliceCallBack('ChangeSlc','nextslice')
end


classdef FileReader < handle

    properties (Access = protected)
        filePath
        fid
    end

    methods (Access = protected)

        function openFile(obj)
            obj.fid = fopen(obj.filePath);
        end

        function closeFile(obj)
            fclose(obj.fid);
        end

    end

    methods (Abstract, Access = public)
        read(obj)
        getDataBase(obj)
    end

end


function hostname = hlp_hostname()
% Find the hostname in a platform-independent fashion.

% 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

import java.net.InetAddress;
hostname = char(InetAddress.getLocalHost());
hostname = hostname(1:find(hostname=='/',1)-1);


function hRD = plugin_rd_rxtx
% Reference design definition

%   Copyright 2014-2015 The MathWorks, Inc.

% Call the common reference design definition function
hRD = AnalogDevices.adrv9009.common.plugin_rd('ZCU102', 'Rx & Tx');
AnalogDevices.adrv9009.zcu102.add_io(hRD, 'Rx & Tx');


function File = GetFullPath(File, Style)
% GetFullPath - Get absolute canonical path of a file or folder
% Absolute path names are safer than relative paths, when e.g. a GUI or TIMER
% callback changes the current directory. Only canonical paths without "." and
% ".." can be recognized uniquely.
% Long path names (>259 characters) require a magic initial key "\\?\" to be
% handled by Windows API functions, e.g. for Matlab's FOPEN, DIR and EXIST.
%
% FullName = GetFullPath(Name, Style)
% INPUT:
%   Name:  String or cell string, absolute or relative name of a file or
%          folder. The path need not exist. Unicode strings, UNC paths and long
%          names are supported.
%   Style: Style of the output as string, optional, default: 'auto'.
%          'auto': Add '\\?\' or '\\?\UNC\' for long names on demand.
%          'lean': Magic string is not added.
%          'fat':  Magic string is added for short names also.
%          The Style is ignored when not running under Windows.
%
% OUTPUT:
%   FullName: Absolute canonical path name as string or cell string.
%          For empty strings the current directory is replied.
%          '\\?\' or '\\?\UNC' is added on demand.
%
% NOTE: The M- and the MEX-version create the same results, the faster MEX
%   function works under Windows only.
%   Some functions of the Windows-API still do not support long file names.
%   E.g. the Recycler and the Windows Explorer fail even with the magic '\\?\'
%   prefix. Some functions of Matlab accept 260 characters (value of MAX_PATH),
%   some at 259 already. Don't blame me.
%   The 'fat' style is useful e.g. when Matlab's DIR command is called for a
%   folder with les than 260 characters, but together with the file name this
%   limit is exceeded. Then "dir(GetFullPath([folder, '\*.*], 'fat'))" helps.
%
% EXAMPLES:
%   cd(tempdir);                    % Assumed as 'C:\Temp' here
%   GetFullPath('File.Ext')         % 'C:\Temp\File.Ext'
%   GetFullPath('..\File.Ext')      % 'C:\File.Ext'
%   GetFullPath('..\..\File.Ext')   % 'C:\File.Ext'
%   GetFullPath('.\File.Ext')       % 'C:\Temp\File.Ext'
%   GetFullPath('*.txt')            % 'C:\Temp\*.txt'
%   GetFullPath('..')               % 'C:\'
%   GetFullPath('..\..\..')         % 'C:\'
%   GetFullPath('Folder\')          % 'C:\Temp\Folder\'
%   GetFullPath('D:\A\..\B')        % 'D:\B'
%   GetFullPath('\\Server\Folder\Sub\..\File.ext')
%                                   % '\\Server\Folder\File.ext'
%   GetFullPath({'..', 'new'})      % {'C:\', 'C:\Temp\new'}
%   GetFullPath('.', 'fat')         % '\\?\C:\Temp\File.Ext'
%
% COMPILE:
%   Automatic: InstallMex GetFullPath.c uTest_GetFullPath
%   Manual:    mex -O GetFullPath.c
%   Download:  http://www.n-simon.de/mex
% Run the unit-test uTest_GetFullPath after compiling.
%
% Tested: Matlab 2009a, 2015b(32/64), 2016b, 2018b, Win7/10
%         Compiler: LCC2.4/3.8, BCC5.5, OWC1.8, MSVC2008/2010
% Assumed Compatibility: higher Matlab versions
% Author: Jan Simon, Heidelberg, (C) 2009-2019 matlab.2010(a)n(MINUS)simon.de
%
% See also: CD, FULLFILE, FILEPARTS.

% $JRev: R-M V:038 Sum:C/6JMzUYsYsc Date:19-May-2019 17:25:55 $
% $License: BSD (use/copy/change/redistribute on own risk, mention the author) $
% $UnitTest: uTest_GetFullPath $
% $File: Tools\GLFile\GetFullPath.m $
% History:
% 001: 20-Apr-2010 22:28, Successor of Rel2AbsPath.
% 010: 27-Jul-2008 21:59, Consider leading separator in M-version also.
% 011: 24-Jan-2011 12:11, Cell strings, '~File' under linux.
%      Check of input types in the M-version.
% 015: 31-Mar-2011 10:48, BUGFIX: Accept [] as input as in the Mex version.
%      Thanks to Jiro Doke, who found this bug by running the test function for
%      the M-version.
% 020: 18-Oct-2011 00:57, BUGFIX: Linux version created bad results.
%      Thanks to Daniel.
% 024: 10-Dec-2011 14:00, Care for long names under Windows in M-version.
%      Improved the unittest function for Linux. Thanks to Paul Sexton.
% 025: 09-Aug-2012 14:00, In MEX: Paths starting with "\\" can be non-UNC.
%      The former version treated "\\?\C:\<longpath>\file" as UNC path and
%      replied "\\?\UNC\?\C:\<longpath>\file".
% 032: 12-Jan-2013 21:16, 'auto', 'lean' and 'fat' style.
% 038: 19-May-2019 17:25, BUGFIX, Thanks HHang Li, "File(7:..." -> "File(8:..."

% Initialize: ==================================================================
% Do the work: =================================================================

% #############################################
% ### USE THE MUCH FASTER MEX ON WINDOWS!!! ###
% #############################################

% Difference between M- and Mex-version:
% - Mex does not work under MacOS/Unix.
% - Mex calls Windows API function GetFullPath.
% - Mex is much faster.

% Magic prefix for long Windows names:
if nargin < 2
   Style = 'auto';
end

% Handle cell strings:
% NOTE: It is faster to create a function @cell\GetFullPath.m under Linux, but
% under Windows this would shadow the fast C-Mex.
if isa(File, 'cell')
   for iC = 1:numel(File)
      File{iC} = GetFullPath(File{iC}, Style);
   end
   return;
end

% Check this once only:
isWIN    = strncmpi(computer, 'PC', 2);
MAX_PATH = 260;

% Warn once per session (disable this under Linux/MacOS):
persistent hasDataRead
if isempty(hasDataRead)
   % Test this once only - there is no relation to the existence of DATAREAD!
   %if isWIN
   %   Show a warning, if the slower Matlab version is used - commented, because
   %   this is not a problem and it might be even useful when the MEX-folder is
   %   not inlcuded in the path yet.
   %   warning('JSimon:GetFullPath:NoMex', ...
   %      ['GetFullPath: Using slow Matlab-version instead of fast Mex.', ...
   %       char(10), 'Compile: InstallMex GetFullPath.c']);
   %end

   % DATAREAD is deprecated in 2011b, but still available. In Matlab 6.5, REGEXP
   % does not know the 'split' command, therefore DATAREAD is preferred:
   hasDataRead = ~isempty(which('dataread'));
end

if isempty(File)  % Accept empty matrix as input:
   if ischar(File) || isnumeric(File)
      File = cd;
      return;
   else
      error(['JSimon:', mfilename, ':BadTypeInput1'], ...
         '*** %s: Input must be a string or cell string', mfilename);
   end
end

if ischar(File) == 0  % Non-empty inputs must be strings
   error(['JSimon:', mfilename, ':BadTypeInput1'], ...
      '*** %s: Input must be a string or cell string', mfilename);
end

if isWIN  % Windows: --------------------------------------------------------
   FSep = '\';
   File = strrep(File, '/', FSep);

   % Remove the magic key on demand, it is appended finally again:
   if strncmp(File, '\\?\', 4)
      if strncmpi(File, '\\?\UNC\', 8)
         % [BUGFIX] 19-May-2019, Thanks HHang Li, "File(7:..." -> "File(8:..."
         File = ['\', File(8:length(File))];  % Two leading backslashes!
      else
         File = File(5:length(File));
      end
   end

   isUNC   = strncmp(File, '\\', 2);
   FileLen = length(File);
   if isUNC == 0                        % File is not a UNC path
      % Leading file separator means relative to current drive or base folder:
      ThePath = cd;
      if File(1) == FSep
         if strncmp(ThePath, '\\', 2)   % Current directory is a UNC path
            sepInd  = strfind(ThePath, '\');
            ThePath = ThePath(1:sepInd(4));
         else
            ThePath = ThePath(1:3);     % Drive letter only
         end
      end

      if FileLen < 2 || File(2) ~= ':'  % Does not start with drive letter
         if ThePath(length(ThePath)) ~= FSep
            if File(1) ~= FSep
               File = [ThePath, FSep, File];
            else                        % File starts with separator:
               File = [ThePath, File];
            end
         else                           % Current path ends with separator:
            if File(1) ~= FSep
               File = [ThePath, File];
            else                        % File starts with separator:
               ThePath(length(ThePath)) = [];
               File = [ThePath, File];
            end
         end

      elseif FileLen == 2 && File(2) == ':'   % "C:" current directory on C!
         % "C:" is the current directory on the C-disk, even if the current
         % directory is on another disk! This was ignored in Matlab 6.5, but
         % modern versions considers this strange behaviour.
         if strncmpi(ThePath, File, 2)
            File = ThePath;
         else
            try
               backCD = cd;
               File   = cd(cd(File));
               cd(backCD);
            catch ME
               if exist(File, 'dir')  % No idea what could cause an error then!
                  rethrow(ME);
               else  % Reply "K:\" for not existing disk:
                  File = [File, FSep];
               end
            end
         end
      end
   end

else         % Linux, MacOS: ---------------------------------------------------
   FSep = '/';
   File = strrep(File, '\', FSep);

   if strcmp(File, '~') || strncmp(File, '~/', 2)  % Home directory:
      HomeDir = getenv('HOME');
      if ~isempty(HomeDir)
         File(1) = [];
         File    = [HomeDir, File];
      end

   elseif strncmpi(File, FSep, 1) == 0
      % Append relative path to current folder:
      ThePath = cd;
      if ThePath(length(ThePath)) == FSep
         File = [ThePath, File];
      else
         File = [ThePath, FSep, File];
      end
   end
end

% Care for "\." and "\.." - no efficient algorithm, but the fast Mex is
% recommended at all!
if ~isempty(strfind(File, [FSep, '.']))
   if isWIN
      if strncmp(File, '\\', 2)  % UNC path
         index = strfind(File, '\');
         if length(index) < 4    % UNC path without separator after the folder:
            return;
         end
         Drive            = File(1:index(4));
         File(1:index(4)) = [];
      else
         Drive     = File(1:3);
         File(1:3) = [];
      end
   else  % Unix, MacOS:
      isUNC   = false;
      Drive   = FSep;
      File(1) = [];
   end

   hasTrailFSep = (File(length(File)) == FSep);
   if hasTrailFSep
      File(length(File)) = [];
   end

   if hasDataRead
      if isWIN  % Need "\\" as separator:
         C = dataread('string', File, '%s', 'delimiter', '\\');  %#ok<REMFF1>
      else
         C = dataread('string', File, '%s', 'delimiter', FSep);  %#ok<REMFF1>
      end
   else  % Use the slower REGEXP, when DATAREAD is not available anymore:
      C = regexp(File, FSep, 'split');
   end

   % Remove '\.\' directly without side effects:
   C(strcmp(C, '.')) = [];

   % Remove '\..' with the parent recursively:
   R = 1:length(C);
   for dd = reshape(find(strcmp(C, '..')), 1, [])
      index    = find(R == dd);
      R(index) = [];
      if index > 1
         R(index - 1) = [];
      end
   end

   if isempty(R)
      File = Drive;
      if isUNC && ~hasTrailFSep
         File(length(File)) = [];
      end

   elseif isWIN
      % If you have CStr2String, use the faster:
      %   File = CStr2String(C(R), FSep, hasTrailFSep);
      File = sprintf('%s\\', C{R});
      if hasTrailFSep
         File = [Drive, File];
      else
         File = [Drive, File(1:length(File) - 1)];
      end

   else  % Unix:
      File = [Drive, sprintf('%s/', C{R})];
      if ~hasTrailFSep
         File(length(File)) = [];
      end
   end
end

% "Very" long names under Windows:
if isWIN
   if ~ischar(Style)
      error(['JSimon:', mfilename, ':BadTypeInput2'], ...
         '*** %s: Input must be a string or cell string', mfilename);
   end

   if (strncmpi(Style, 'a', 1) && length(File) >= MAX_PATH) || ...
         strncmpi(Style, 'f', 1)
      % Do not use [isUNC] here, because this concerns the input, which can
      % '.\File', while the current directory is an UNC path.
      if strncmp(File, '\\', 2)  % UNC path
         File = ['\\?\UNC', File(2:end)];
      else
         File = ['\\?\', File];
      end
   end
end

% return;


function DICOM_fixMatlabBug
% When a DICOM I/O bug comes up, run this code once to fix.
%
% Details: Matlab's own DICOM toolbox is obviously written for Siemens
% scanner images. When running on GE images, it occassionally comes up with
% bugs. However, because the matlab source code is hidden in a private
% directory, we have to copy the file in VISTASOFT folder into that private
% directory, in order to overwrite the Matlab's problematic source code.
%
% Hence, this fixbug code may need to be expanded in the future if more
% bugs come up.
%
% Junjie Liu 2004/01/23
% 2004.04.08 Bob Dougherty: added check for pc- otherwise, this throws an
% error on linux due to file permissions.
% 2006.05.05 RFD: now politely backs up the original file. Is this patch
% still needed?
% 2006.05.22 RFD: disabled this fix- it's probably not needed and actually
% causes problems on newer matlabs.

matlabDir = fileparts(which('dicomread'));
if isempty(matlabDir);
    disp('Matlab version needs to be >6.5 to get DICOM toolbox');
    disp('In Linux please run matlab651 manually');
    error('dicomread function not found in Matlab. Your Matlab version is too old!');
end
% if(ispc)
%     matlabDir = fullfile(matlabDir,'private');
%
%     fixedDir = fileparts(which('DICOM_fixMatlabBug'));
%
%     disp('Overwritting your Matlab DICOM toolbox to fix possible bugs...');
%
%     fixedFile = fullfile(fixedDir,'dicom_read_attr.m');
%     matlabFile = fullfile(matlabDir,'dicom_read_attr.m');
%     [success message] = copyfile(matlabFile, fullfile(matlabDir,'dicom_read_attr_ORIGINAL.m'));
%     if(~success) warning(message); return; end;
%     [success message] = copyfile(fixedFile,matlabFile);
%     if ~success, warning(message); return; end;
%     disp('Overwritting Successful!');
% else
%     disp('Please ensure that your installation of matlab has been patched.');
% end
return;


function shortcuts = GetShortcuts(category, labels)
%GETSHORTCUTS Returns details of existing toolbar shortcuts.
%
% SHORTCUTS = GETSHORTCUTS(CATEGORY) returns the labels, callback, icon
% path and whether or not the shortcut is editable, for each existing
% toolbar shortcut in the category; those in the 'Toolbar Shortcuts' by
% default.
%
% SHORTCUTS = GETSHORTCUTS(CATEGORY, LABELS) works as
% above, but only returns shortcuts with labels matching LABELS.
%
% Examples:
%
% shortcuts = GetShortcuts();
%
% See also: GetShortcutNames, AddShortcut

% $Author: rcotton $	$Date: 2010/08/23 14:35:09 $	$Revision: 1.1 $
% Copyright: Health and Safety Laboratory 2010

shortcutUtils = GetShortcutUtils();

SetDefaultValue(1, 'category', DefaultToolbarCategoryName());

filter = nargin >= 2 && ~isempty(labels);

shortcutArray = ...
   shortcutUtils.getShortcutsByCategory(category).toArray();

shortcuts = struct('label', {}, 'callback', {}, ...
   'icon', {}, 'category', {}, 'editable', {});

for i = 1:shortcutArray.length
   label = char(shortcutArray(i).getLabel());
   if ~filter || strcontains(label, labels)
      shortcuts(end + 1).label = label;           %#ok<AGROW>
      shortcuts(end).callback = ...
         char(shortcutArray(i).getCallback());
      shortcuts(end).icon = ...
         char(shortcutArray(i).getIconPath());
      shortcuts(end).category = category;
      shortcuts(end).editable = ...
         shortcutArray(i).isEditable;
   end
end

end