function A = catstruct(varargin)
%
% taken from MATLAB File Exchange
% https://de.mathworks.com/matlabcentral/fileexchange/7842-catstruct
%
% Copyright (c) 2015, Jos van der Geest
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are met:
%
% * Redistributions of source code must retain the above copyright notice, this
%   list of conditions and the following disclaimer.
%
% * Redistributions in binary form must reproduce the above copyright notice,
%   this list of conditions and the following disclaimer in the documentation
%   and/or other materials provided with the distribution
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
% DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
% FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
% DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
% SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
% CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
% OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
% OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
%
% CATSTRUCT   Concatenate or merge structures with different fieldnames
%   X = CATSTRUCT(S1,S2,S3,...) merges the structures S1, S2, S3 ...
%   into one new structure X. X contains all fields present in the various
%   structures. An example:
%
%     A.name = 'Me' ;
%     B.income = 99999 ;
%     X = catstruct(A,B)
%     % -> X.name = 'Me' ;
%     %    X.income = 99999 ;
%
%   If a fieldname is not unique among structures (i.e., a fieldname is
%   present in more than one structure), only the value from the last
%   structure with this field is used. In this case, the fields are
%   alphabetically sorted. A warning is issued as well. An axample:
%
%     S1.name = 'Me' ;
%     S2.age  = 20 ; S3.age  = 30 ; S4.age  = 40 ;
%     S5.honest = false ;
%     Y = catstruct(S1,S2,S3,S4,S5) % use value from S4
%
%   The inputs can be array of structures. All structures should have the
%   same size. An example:
%
%     C(1).bb = 1 ; C(2).bb = 2 ;
%     D(1).aa = 3 ; D(2).aa = 4 ;
%     CD = catstruct(C,D) % CD is a 1x2 structure array with fields bb and aa
%
%   The last input can be the string 'sorted'. In this case,
%   CATSTRUCT(S1,S2, ..., 'sorted') will sort the fieldnames alphabetically.
%   To sort the fieldnames of a structure A, you could use
%   CATSTRUCT(A,'sorted') but I recommend ORDERFIELDS for doing that.
%
%   When there is nothing to concatenate, the result will be an empty
%   struct (0x0 struct array with no fields).
%
%   NOTE: To concatenate similar arrays of structs, you can use simple
%   concatenation:
%     A = dir('*.mat') ; B = dir('*.m') ; C = [A ; B] ;

%   NOTE: This function relies on unique. Matlab changed the behavior of
%   its set functions since 2013a, so this might cause some backward
%   compatibility issues when dulpicated fieldnames are found.
%
%   See also CAT, STRUCT, FIELDNAMES, STRUCT2CELL, ORDERFIELDS

% version 4.1 (feb 2015), tested in R2014a
% (c) Jos van der Geest
% email: jos@jasen.nl

% History
% Created in 2005
% Revisions
%   2.0 (sep 2007) removed bug when dealing with fields containing cell
%                  arrays (Thanks to Rene Willemink)
%   2.1 (sep 2008) added warning and error identifiers
%   2.2 (oct 2008) fixed error when dealing with empty structs (thanks to
%                  Lars Barring)
%   3.0 (mar 2013) fixed problem when the inputs were array of structures
%                  (thanks to Tor Inge Birkenes).
%                  Rephrased the help section as well.
%   4.0 (dec 2013) fixed problem with unique due to version differences in
%                  ML. Unique(...,'last') is no longer the deafult.
%                  (thanks to Isabel P)
%   4.1 (feb 2015) fixed warning with narginchk

narginchk(1,Inf) ;
N = nargin ;

if ~isstruct(varargin{end}),
    if isequal(varargin{end},'sorted'),
        narginchk(2,Inf) ;
        sorted = 1 ;
        N = N-1 ;
    else
        error('catstruct:InvalidArgument','Last argument should be a structure, or the string "sorted".') ;
    end
else
    sorted = 0 ;
end

sz0 = [] ; % used to check that all inputs have the same size

% used to check for a few trivial cases
NonEmptyInputs = false(N,1) ;
NonEmptyInputsN = 0 ;

% used to collect the fieldnames and the inputs
FN = cell(N,1) ;
VAL = cell(N,1) ;

% parse the inputs
for ii=1:N,
    X = varargin{ii} ;
    if ~isstruct(X),
        error('catstruct:InvalidArgument',['Argument #' num2str(ii) ' is not a structure.']) ;
    end

    if ~isempty(X),
        % empty structs are ignored
        if ii > 1 && ~isempty(sz0)
            if ~isequal(size(X), sz0)
                error('catstruct:UnequalSizes','All structures should have the same size.') ;
            end
        else
            sz0 = size(X) ;
        end
        NonEmptyInputsN = NonEmptyInputsN + 1 ;
        NonEmptyInputs(ii) = true ;
        FN{ii} = fieldnames(X) ;
        VAL{ii} = struct2cell(X) ;
    end
end

if NonEmptyInputsN == 0
    % all structures were empty
    A = struct([]) ;
elseif NonEmptyInputsN == 1,
    % there was only one non-empty structure
    A = varargin{NonEmptyInputs} ;
    if sorted,
        A = orderfields(A) ;
    end
else
    % there is actually something to concatenate
    FN = cat(1,FN{:}) ;
    VAL = cat(1,VAL{:}) ;
    FN = squeeze(FN) ;
    VAL = squeeze(VAL) ;

    [UFN,ind] = unique(FN, 'last') ;
    % If this line errors, due to your matlab version not having UNIQUE
    % accept the 'last' input, use the following line instead
    % [UFN,ind] = unique(FN) ; % earlier ML versions, like 6.5

    if numel(UFN) ~= numel(FN),
        warning('catstruct:DuplicatesFound','Fieldnames are not unique between structures.') ;
        sorted = 1 ;
    end

    if sorted,
        VAL = VAL(ind,:) ;
        FN = FN(ind,:) ;
    end

    A = cell2struct(VAL, FN);
    A = reshape(A, sz0) ; % reshape into original format
end


%TestSuiteTest Unit tests for TestSuite class

classdef TestSuiteTest < TestCaseInDir

   methods
      function self = TestSuiteTest(name)
         self = self@TestCaseInDir(name, ...
             fullfile(fileparts(which(mfilename)), 'helper_classes'));
      end

      function testClassNameIn(self)
         % Syntax check: TestSuite('classname')
         suite = TestSuite('TwoPassingTests');
         assertTrue(numel(suite.TestComponents) == 2, ...
            'TestSuite finds two test methods given class name');
      end

      function testCurrentDirectory(self)
         % See that the no-input syntax executes without error.
         % Not sure how to test this more effectively.
         suite = TestSuite();
      end

      function testNoTestMethods(self)
         % TestCase class containing no test methods
         suite = TestSuite('NoTestMethods');
         assertTrue(numel(suite.TestComponents) == 0, ...
            'No test cases when class contains no test methods');
      end

      function test_fromTestCaseClassName(self)
          suite = TestSuite.fromTestCaseClassName('TwoPassingTests');
          assertTrue(numel(suite.TestComponents) == 2);
          assertTrue(ismember(suite.TestComponents{1}.Name, ...
              {'testMethod1', 'testMethod2'}));
          assertTrue(ismember(suite.TestComponents{2}.Name, ...
              {'testMethod1', 'testMethod2'}));
      end

      function test_fromTestCaseClassName_badclass(self)
          assertExceptionThrown(@() TestSuite.fromTestCaseClassName('atan2'), ...
              'xunit:fromTestCaseClassName');
      end

      function test_fromName_TestCaseSubclass(self)
          suite = TestSuite.fromName('TwoPassingTests');
          assertTrue(numel(suite.TestComponents) == 2);
          assertEqual(suite.Name, 'TwoPassingTests');
      end

      function test_fromName_notTestCaseSubclass(self)
          suite = TestSuite.fromName('TestRunMonitor');
          assertTrue(isempty(suite.TestComponents));
          assertEqual(suite.Name, 'TestRunMonitor');
      end

      function test_fromName_simpleTest(self)
          suite = TestSuite.fromName('testSimple');
          assertEqual(numel(suite.TestComponents), 1);
          assertEqual(suite.Name, 'testSimple');
          assertEqual(suite.Location, which('testSimple'));
      end

      function test_fromName_subfunctions(self)
          suite = TestSuite.fromName('testFunctionHandlesA');
          assertEqual(numel(suite.TestComponents), 2);
          assertEqual(suite.Name, 'testFunctionHandlesA');
          assertEqual(suite.Location, which('testFunctionHandlesA'));
      end

      function test_fromName_bogus_name(self)
          suite = TestSuite.fromName('atan2');
          assertTrue(isempty(suite.TestComponents));
          assertEqual(suite.Name, 'atan2');
      end

      function test_fromName_with_filter_string(self)
          suite = TestSuite.fromName('testFunctionHandlesA:testA');
          assertEqual(numel(suite.TestComponents), 1);
          assertEqual(suite.TestComponents{1}.Name, 'testA');
          assertEqual(suite.Name, 'testFunctionHandlesA');
      end

      function test_fromName_with_nonmatching_filter_string(self)
          suite = TestSuite.fromName('testFunctionHandlesA:foobar');
          assertTrue(isempty(suite.TestComponents));
      end

      function test_fromName_with_dirname(self)
         xunit_test_dir = which('TestSuiteTest');
         xunit_test_dir = fileparts(xunit_test_dir);
         cwd_test_dir = fullfile(xunit_test_dir, 'cwd_test');
         suite = TestSuite.fromName(cwd_test_dir);

         assertEqual(suite.Name, 'cwd_test');
         assertEqual(suite.Location, cwd_test_dir);
         assertEqual(numel(suite.TestComponents), 3);
      end

      function test_fromPwd(self)
          % Verify that the fromPwd method returns a nonempty TestSuite object
          % from the helper_classes directory, with the correct number of
          % test components.
          suite = TestSuite.fromPwd();
          assertTrue(isa(suite, 'TestSuite'));
          assertTrue(numel(suite.TestComponents) == 16);
      end

   end

end


function out = cfg_run_file_fplist(job)

% function out = cfg_run_file_fplist(job)
%
% Select files non-interactively using cfg_getfile('FPList',...) or
% cfg_getfile('FPListRec',...).
%
% 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_run_file_fplist.m 6918 2016-11-02 14:33:11Z guillaume $

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

[out.files, out.dirs] = cfg_getfile(job.rec, job.dir{1}, job.filter);
if numel(out.files) < 2, plural = ''; else plural = 's'; end
if strcmpi(job.rec,'FPListRec'), rec = ' (and subdirectories)'; else rec = ''; end
fprintf('Found %d file%s matching filter ''%s'' in %s%s.\n',...
    numel(out.files),plural,job.filter,job.dir{1},rec);


% This file is part of the Matlab Toolbox for Dimensionality Reduction v0.7.2b.
% The toolbox can be obtained from http://homepage.tudelft.nl/19j49
% You are free to use, change, or redistribute this code in any way you
% want for non-commercial purposes. However, it is appreciated if you
% maintain the name of the original author.
%
% (C) Laurens van der Maaten, 2010
% University California, San Diego / Delft University of Technology

if strcmpi(get(handles.k,'Visible'),'on')
    if get(handles.listbox1,'Value')~=25
        if get(handles.ka,'Value')
            set(handles.k,'Enable','off');
        else
            set(handles.k,'Enable','on');
        end
    end
end


function types = guitypes()
% GUITYPES returns a cell array of MATLAB/Octave GUI object types
%
% Syntax
%   types = guitypes()
%
% These types are ignored by matlab2tikz and figure2dot.
%
% See also: matlab2tikz, figure2dot

types = {'uitoolbar', 'uimenu', 'uicontextmenu', 'uitoggletool',...
         'uitogglesplittool', 'uipushtool', 'hgjavacomponent',...
         'matlab.graphics.shape.internal.Button', ...
         'matlab.ui.controls.ToolbarPushButton', ...
         'matlab.ui.controls.ToolbarStateButton', ...
         'matlab.ui.controls.ToolbarDropdown', ...
         'matlab.ui.controls.AxesToolbar', ...
         };
end


function [expdirlistfile,expdirs,expdirsCreated,expdirs_linux] = setUpDirUsingCluster(rootdirs,varargin)

if nargin < 1,
  rootdirs = {};
end

expdirs = {};
expdirsCreated = {};
expdirs_linux = {};

% ignore features arguments -- these will be computed on the cluster
[expdirlistfile,doforce,linuxroot,args] = myparse_nocheck(varargin,'expdirlistfile','','doforce',false,...
  'linuxroot','/groups/hantman/hantmanlab');

% file to output directories to process to
if isempty(expdirlistfile),
  expdirlistfile = sprintf('JAABADirsForCluster%s.txt',datestr(now,'yyyymmddTHHMMSS'));
end

argisremove = find(strcmpi(args(1:2:end-1),'features'));
if ~isempty(argisremove),
  args([argisremove,argisremove+1]) = [];
end
args = [args,'features',false,'doforce',doforce];

% select root directories if not given
if isempty(rootdirs),
  p = fileparts(mfilename('fullpath'));
  rcfilename = fullfile(p,'.setUpDir.mat');
  startdir = '.';
  if exist(rcfilename,'file'),
    try %#ok<TRYNC>
      rc = load(rcfilename);
      if exist(rc.startdir,'dir'),
        startdir = rc.startdir;
      end
    end
  end
  rootdirs = uipickfiles('FilterSpec',startdir,'DirsOnly',true,'Output','cell');
  if isnumeric(rootdirs) || isempty(rootdirs),
    fprintf('No root directories selected, returning\n');
    return;
  end
end

% if only one root directory is given
if ~iscell(rootdirs),
  rootdirs = {rootdirs};
end

if ~isempty(rootdirs),
  p = fileparts(mfilename('fullpath'));
  rcfilename = fullfile(p,'.setUpDir.mat');
  p = fileparts(rootdirs{end});
  if exist(p,'dir'),
    startdir = p; %#ok<NASGU>
    try %#ok<TRYNC>
      save(rcfilename,'startdir');
    end
  end
end

% run the annotation and directory creating steps
expdirsCreated = {};
for i = 1:numel(rootdirs),
  expdirs1 = setUpDir(rootdirs{i},args{:});
  if isempty(expdirs1),
    fprintf('%d: No directories created within root directory %s.\n',i,rootdirs{i});
  else
    fprintf('%d: Created the following directories within root directory %s:\n',i,rootdirs{i});
    fprintf('  %s\n',expdirs1{:});
    expdirsCreated = [expdirsCreated,expdirs1(:)']; %#ok<AGROW>
  end
end

% get a list of experiment directories to compute features for
expdirs = {};
for i = 1:numel(rootdirs),
  expdirs1 = genAllFeaturesExpDirList(rootdirs{i},'doforce',doforce,args{:});
  if isempty(expdirs1),
    fprintf('%d: No directories within root directory %s to compute features for.\n',i,rootdirs{i});
  else
    fprintf('%d: The following directories within root directory %s need processing:\n',i,rootdirs{i});
    fprintf('  %s\n',expdirs1{:});
    expdirs = [expdirs,expdirs1]; %#ok<AGROW>
  end
end

if isempty(expdirs),
  fprintf('No directories to process.\n');
  return;
end

expdirs_linux = {};
if ispc,
  for i = 1:numel(expdirs),
    % strip off the <driveletter>:\
    m = regexp(expdirs{i},'^[A-Z]:\\(.*)$','tokens','once');
    if isempty(m),
      fprintf('JAABA directory %s does not start with <driveletter>:\ -- not sure how to make this compatible with the cluster, skipping.\n',expdirs{i});
      continue;
    end
    % change file separator
    m = strrep(m{1},'\','/');
    expdirs_linux{end+1} = [linuxroot,'/',m]; %#ok<AGROW>
  end
elseif ismac,
  % file share is in the Mac path
  [~,fileshare] = fileparts(linuxroot);
  for i = 1:numel(expdirs),
    % strip off the /Volumes part
    m = regexp(expdirs{i},'^/Volumes/([^/]*)/(.*)','tokens','once');
    if isempty(m),
      fprintf('JAABA directory %s could not be parsed as /Volumes/(something)/(rest) -- not sure how to make this compatible with the cluster, skipping.\n',expdirs{i});
      continue;
    end
    if ~strcmp(fileshare,m{1}),
      fprintf('JAABA directory %s does not match specified file share %s -- not sure how to make this compatible with the cluster, skipping.\n',expdirs{i},fileshare);
      continue;
    end
    expdirs_linux{end+1} = fullfile(linuxroot,m{2}); %#ok<AGROW>
  end
else
  expdirs_linux = cell(size(expdirs));
  for i = 1:numel(expdirs),
    expdirs_linux{i} = absolutifyFileName(expdirs{i},pwd);
  end
end

fprintf('Outputting list of JAABA directories to process on the cluster to file %s...\n',expdirlistfile);
fid = fopen(expdirlistfile,'w');
if fid < 0,
  error('Could not write to file %s',expdirlistfile);
end

fprintf(fid,'%s\n',expdirs_linux{:});
fclose(fid);

fprintf('\nOutput %d JAABA experiments to file %s to be processed on the cluster.\n\n',numel(expdirs_linux),expdirlistfile);

if isunix && ~ismac,
  expdirlistfile_abs = absolutifyFileName(expdirlistfile,pwd);
  fprintf('To process on the cluster, do the following:\n');
  fprintf('1. Log into login2 (this is done with the terminal command "ssh login2")\n\n');
  fprintf('2. On login2, run the command:\n');
  fprintf('    /groups/branson/bransonlab/share/qsub_genAllFeatures.pl %s\n\n',expdirlistfile_abs);
  fprintf('To check on the progress of your jobs, you can type "qstat" at the command prompt to get a list of jobs running.\n');
else
  fprintf('To process on the cluster, do the following:\n');
  fprintf('1. Put the file created by this function, %s, on the Janelia file system, e.g. in the hantmanlab file share.\n',expdirlistfile);
  fprintf('2. Log into login2 (this is done with the terminal command "ssh login2")\n\n');
  fprintf('3. On login2, run the command:\n');
  fprintf('    /groups/branson/bransonlab/share/qsub_genAllFeatures.pl <JAABADirectoryListFile>\n');
  [~,n,e] = fileparts(expdirlistfile);
  n = [n,e];
  fprintf('where <JAABADirectoryListFile> is the *full Linux path* to the location of the file %s on the Janelia file server,\n',n);
  fprintf('Example: /groups/branson/bransonlab/share/qsub_GenAllFeatures.pl /groups/hantman/hantmanlab/JAABADirLists/%s\n\n',n);
  fprintf('To check on the progress of your jobs, you can type "qstat" at the command prompt to get a list of jobs running.\n');
end


%--- help for mdd.global_options ---
%
%mdd.global_options is a function.
%    opts = global_options(opts0)
%


function varargout = rts_PropConsole(varargin)
% RTS_PROPCONSOLE MATLAB code for rts_PropConsole.fig
%      RTS_PROPCONSOLE, by itself, creates a new RTS_PROPCONSOLE or raises the existing
%      singleton*.
%
%      H = RTS_PROPCONSOLE returns the handle to a new RTS_PROPCONSOLE or the handle to
%      the existing singleton*.
%
%      RTS_PROPCONSOLE('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in RTS_PROPCONSOLE.M with the given input arguments.
%
%      RTS_PROPCONSOLE('Property','Value',...) creates a new RTS_PROPCONSOLE or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before rts_PropConsole_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to rts_PropConsole_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 rts_PropConsole

% Last Modified by GUIDE v2.5 03-Jan-2014 18:04:48

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @rts_PropConsole_OpeningFcn, ...
                   'gui_OutputFcn',  @rts_PropConsole_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
end

% --- Executes just before rts_PropConsole is made visible.
function rts_PropConsole_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 rts_PropConsole (see VARARGIN)

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

    hRtsMainGUI = varargin{1};
    vesselGUID = varargin{2};
    handles.mainGUI = hRtsMainGUI;
    handles.vesselGUID = vesselGUID;

    if(ishandle(handles.resSumLabel1))
        rts_initRTSPropPanel(hRtsMainGUI, hObject, handles.clockLabel, handles.connStatusLabel, vesselGUID, handles.resUITable1, handles.resSumLabel1, ...
                             handles.resUITable2, handles.resSumLabel2, handles.resourceCombo1, handles.resourceCombo2, handles.mainEngineUITable,...
                             handles.rcsEngineUITable, handles.resourcePanel1, handles.resourcePanel2);
    end

    % Update handles structure
    guidata(hObject, handles);

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

% --- Outputs from this function are returned to the command line.
function varargout = rts_PropConsole_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;
end

% --- Executes on selection change in resourceCombo2.
function resourceCombo2_Callback(hObject, eventdata, handles)
% hObject    handle to resourceCombo2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns resourceCombo2 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from resourceCombo2
end

% --- Executes during object creation, after setting all properties.
function resourceCombo2_CreateFcn(hObject, eventdata, handles)
% hObject    handle to resourceCombo2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
end

% --- Executes on selection change in resourceCombo1.
function resourceCombo1_Callback(hObject, eventdata, handles)
% hObject    handle to resourceCombo1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns resourceCombo1 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from resourceCombo1
end

% --- Executes during object creation, after setting all properties.
function resourceCombo1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to resourceCombo1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
    if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
        set(hObject,'BackgroundColor','white');
    end
end

% --- Executes on selection change in resourceCombo2.
function popupmenu4_Callback(hObject, eventdata, handles)
% hObject    handle to resourceCombo2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns resourceCombo2 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from resourceCombo2
end

% --- Executes during object creation, after setting all properties.
function popupmenu4_CreateFcn(hObject, eventdata, handles)
% hObject    handle to resourceCombo2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
    if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
        set(hObject,'BackgroundColor','white');
    end
end

% --- Executes when user attempts to close rts_PropConsole.
function rts_PropConsole_CloseRequestFcn(hObject, eventdata, handles)
% hObject    handle to rts_PropConsole (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: delete(hObject) closes the figure
    rts_pageCloseStopTimers(hObject);
    delete(hObject);
end


function hRD = plugin_rd_tx
% Reference design definition

%   Copyright 2014-2015 The MathWorks, Inc.

% Call the common reference design definition function
hRD = AnalogDevices.fmcomms2.common.plugin_rd('ZC706', 'Tx');
AnalogDevices.fmcomms2.zc706.add_io(hRD,'Tx');


function [ns_RESULT, TimeStamp, Data, DataSize] = ns_GetEventData(hFile, EntityID, Index);

%ns_GetEventData   Retrieves event data by index
%
%   Usage:
%      [ns_RESULT, TimeStamp, Data, DataSize] =
%                                   ns_GetEventData(hFile, EntityID, Index)
%
%   Description:
%       Returns the data values from the file referenced by hFile and the
%       Event Entity EntityID.  The Event data entry specified by Index
%       is written to Data and the timestamp of the entry is returned to
%       TimeStamp.  Upon return of the function, the value at DataSize
%       contains the number of bytes actually written to Data.
%
%   Parameters:
%       hFile	        Handle/Indentification number to an open file.
%       EntityID	    Identification number of the entity in the data
%                       file.
%       Index	        The index number of the requested Event data item.
%
%   Return Values:
%       TimeStamp	    Variable that receives the timestamp of the Event
%                       data item.
%       Data	        Variable that receives the data for the Event entry.
%                       The format of Event data is specified by the member
%                       EventType in ns_EVENTINFO.
%       DataSize	    Variable that receives the actual number of bytes
%                       of data retrieved in the data buffer.
%       ns_RESULT   This function returns ns_OK if the file is successfully
%                   opened. Otherwise one of the following error codes is
%                   generated:
%
%                       ns_BADFILE	    Invalid file handle passed to
%                                       function
%                       ns_BADENTITY	Invalid or inappropriate entity
%                                       identifier specified
%                       ns_BADINDEX	    Invalid entity index specified
%                       ns_FILEERROR	File access or read error
%
%   Copyright (C) 2003 Neuroshare Project
%   Author: Almut Branner
%   Last modification: 8/11/2003

[ns_RESULT, TimeStamp, Data, DataSize] = mexprog(6, hFile, EntityID - 1, Index - 1);


incl = {'ucm', 'COM', 'utils', ...
	'semantics', 'segmentation', ...
	'ucmGT', 'classify', 'sceneClassification', 'allBenchmarks', ...
	'external', 'external/vlfeat/toolbox/', 'external/BSR/grouping/lib', 'external/BSR/bench/benchmarks'};
for i = 1:length(incl)
	addpath(incl{i});
end
vl_setup();
fprintf('Set up and ready to use...!\n');


%% flandmark_compilemex.m
% Compilation script for flandmark mex-files.
% Tested with OpenCV version 2.3 (linux, )
%
% 09-12-12, Michal Uricar

clc;
clearvars; close all;

% Change this to your version of opencv
OpenCVmajor = 2;
OpenCVminor = 4;

% Setup paths accpording to system platform
if (isunix&&~ismac)
    fprintf('Compiling mex-files on Unix platform...\n');

    include = ' -I/usr/include/opencv/ -I/usr/include/ ';
    libpath = '/usr/lib/';
    libflandmark = ' -L../bin/libflandmark/ -lflandmark_static ';

    if (OpenCVminor < 3)
        cxcore = dir([libpath 'libcxcore.so.' num2str(OpenCVmajor) '.' num2str(OpenCVminor)]);
        cxcore = cxcore.name;
        cv = dir([libpath 'libcv.so.' num2str(OpenCVmajor) '.' num2str(OpenCVminor)]);
        cv = cv.name;
        cvaux = dir([libpath 'libcvaux.so.' num2str(OpenCVmajor) '.' num2str(OpenCVminor)]);
        cvaux = cvaux.name;

        cvlibs = [libpath cxcore ' ' libpath cv ' ' libpath cvaux ' '];
    else
        opencv_core = dir([libpath 'libopencv_core.so.' num2str(OpenCVmajor) '.' num2str(OpenCVminor)]);
        opencv_core = opencv_core.name;
        opencv_imgproc = dir([libpath 'libopencv_imgproc.so.' num2str(OpenCVmajor) '.' num2str(OpenCVminor)]);
        opencv_imgproc = opencv_imgproc.name;

        cvlibs = [libpath opencv_core ' ' libpath opencv_imgproc ' '];
    end;

    % compile mexfiles
    eval(['mex -O -largeArrayDims ./mex/flandmark_detector_mex.cpp -I../libflandmark/' include libflandmark cvlibs ' -o ../matlab_toolbox/mex/flandmark_detector']);
    eval(['mex -O -largeArrayDims ./mex/flandmark_detector_base_mex.cpp -I../libflandmark/' include libflandmark cvlibs ' -o ../matlab_toolbox/mex/flandmark_detector_base']);
    eval(['mex -O -largeArrayDims ./mex/flandmark_write_model_mex.cpp -I../libflandmark/' include libflandmark cvlibs ' -o ../matlab_toolbox/mex/flandmark_write_model']);
    eval(['mex -O -largeArrayDims ./mex/flandmark_load_model_mex.cpp -I../libflandmark/' include libflandmark cvlibs ' -o ../matlab_toolbox/mex/flandmark_load_model']);
    eval(['mex -O -largeArrayDims ./mex/lbp2sparse_mex.cpp -I../libflandmark/' libflandmark ' -o ../matlab_toolbox/mex/lbp2sparse']);
    eval(['mex -O -largeArrayDims ./mex/argmax_mex.cpp -I../libflandmark/ ' include libflandmark cvlibs ' -output ../matlab_toolbox/mex/argmax_mex']);
    eval(['mex -O -largeArrayDims ./mex/getNormalizedFrame_mex.cpp -I../libflandmark/' include libflandmark cvlibs ' -o ../matlab_toolbox/mex/getNormalizedFrame']);

    fprintf('Compilation finished.\n');
end;

if (ispc)
    fprintf('Compiling mex-files on Windows platform...\n');

    include = [' -Ic:\OpenCV' num2str(OpenCVmajor) '.' num2str(OpenCVminor) '\build\include\opencv\', ...
               ' -Ic:\OpenCV' num2str(OpenCVmajor) '.' num2str(OpenCVminor) '\build\include\' ];
    libpath = ['c:\OpenCV' num2str(OpenCVmajor) '.' num2str(OpenCVminor) '\build\x64\vc10\lib\'];
    libflandmark = ' -L../bin7/libflandmark/Release -lflandmark_static ';

    if (OpenCVminor < 3)
        cxcore = dir([libpath 'cxcore' num2str(OpenCVmajor) num2str(OpenCVminor) '*.lib']);
        cxcore = cxcore.name;
        cv = dir([libpath 'cv' num2str(OpenCVmajor) num2str(OpenCVminor) '*.lib']);
        cv = cv.name;
        cvaux = dir([libpath 'cvaux' num2str(OpenCVmajor) num2str(OpenCVminor) '*.lib']);
        cvaux = cvaux.name;

        cvlibs = [libpath cxcore ' ' libpath cv ' ' libpath cvaux ' '];
    else
        opencv_core = dir([libpath 'opencv_core' num2str(OpenCVmajor) num2str(OpenCVminor) '*.lib']);
        opencv_core = opencv_core.name;
        opencv_imgproc = dir([libpath 'opencv_imgproc' num2str(OpenCVmajor) num2str(OpenCVminor) '*.lib']);
        opencv_imgproc = opencv_imgproc.name;

        cvlibs = [libpath opencv_core ' ' libpath opencv_imgproc ' '];
    end;

    % compile mexfiles
    eval(['mex -O -largeArrayDims ./mex/flandmark_detector_mex.cpp -I../libflandmark/' include libflandmark cvlibs ' -output ../matlab_toolbox/mex/flandmark_detector']);
    eval(['mex -O -largeArrayDims ./mex/flandmark_detector_base_mex.cpp -I../libflandmark/' include libflandmark cvlibs ' -output ../matlab_toolbox/mex/flandmark_detector_base']);
    eval(['mex -O -largeArrayDims ./mex/flandmark_write_model_mex.cpp -I../libflandmark/' include libflandmark cvlibs ' -output ../matlab_toolbox/mex/flandmark_write_model']);
    eval(['mex -O -largeArrayDims ./mex/flandmark_load_model_mex.cpp -I../libflandmark/' include libflandmark cvlibs ' -output ../matlab_toolbox/mex/flandmark_load_model']);
    eval(['mex -O -largeArrayDims ./mex/lbp2sparse_mex.cpp -I../libflandmark/' libflandmark ' -output ../matlab_toolbox/mex/lbp2sparse']);
    eval(['mex -O -largeArrayDims ./mex/argmax_mex.cpp -I../libflandmark/ ' include libflandmark cvlibs ' -output ../matlab_toolbox/mex/argmax_mex']);
    eval(['mex -O -largeArrayDims ./mex/getNormalizedFrame_mex.cpp -I../libflandmark/' include libflandmark cvlibs ' -output ../matlab_toolbox/mex/getNormalizedFrame']);

    fprintf('Compilation finished.\n');
end;

if (ismac)
    fprintf('Compiling mex-files on Mac platform...\n');

    include = ' -I/opt/local/include/opencv/ -I/opt/local/include/ -I/usr/local/include/opencv/ -I/usr/local/include/';
    if(numel(dir('/usr/local/lib/libopencv*')))
        libpath = '/usr/local/lib/';
    else
        libpath = '/opt/local/lib/';
    end
    libflandmark = ' -L../bin/libflandmark/ -lflandmark_static ';

    % files = dir([libpath 'libopencv*.dylib']);
    % e.g. libopencv_core.2.4.2.dylib

    if (OpenCVminor < 3)
        cxcore = dir([libpath 'libcxcore.' num2str(OpenCVmajor) '.' num2str(OpenCVminor) '.dylib']);
        cxcore = cxcore.name;
        cv = dir([libpath 'libcv.' num2str(OpenCVmajor) '.' num2str(OpenCVminor) '.dylib']);
        cv = cv.name;
        cvaux = dir([libpath 'libcvaux.' num2str(OpenCVmajor) '.' num2str(OpenCVminor) '.dylib']);
        cvaux = cvaux.name;

        cvlibs = [libpath cxcore ' ' libpath cv ' ' libpath cvaux ' '];
    else
        opencv_core = dir([libpath 'libopencv_core.' num2str(OpenCVmajor) '.' num2str(OpenCVminor) '.dylib']);
        opencv_core = opencv_core.name;
        opencv_imgproc = dir([libpath 'libopencv_imgproc.' num2str(OpenCVmajor) '.' num2str(OpenCVminor) '.dylib']);
        opencv_imgproc = opencv_imgproc.name;

        cvlibs = [libpath opencv_core ' ' libpath opencv_imgproc ' '];
    end;

    % compile mexfiles
    eval(['mex -O -largeArrayDims ./mex/flandmark_detector_mex.cpp -I../libflandmark/' include libflandmark cvlibs ' -o ../matlab_toolbox/mex/flandmark_detector']);
    eval(['mex -O -largeArrayDims ./mex/flandmark_detector_base_mex.cpp -I../libflandmark/' include libflandmark cvlibs ' -o ../matlab_toolbox/mex/flandmark_detector_base']);
    eval(['mex -O -largeArrayDims ./mex/flandmark_write_model_mex.cpp -I../libflandmark/' include libflandmark cvlibs ' -o ../matlab_toolbox/mex/flandmark_write_model']);
    eval(['mex -O -largeArrayDims ./mex/flandmark_load_model_mex.cpp -I../libflandmark/' include libflandmark cvlibs ' -o ../matlab_toolbox/mex/flandmark_load_model']);
    eval(['mex -O -largeArrayDims ./mex/lbp2sparse_mex.cpp -I../libflandmark/' libflandmark ' -o ../matlab_toolbox/mex/lbp2sparse']);
    eval(['mex -O -largeArrayDims ./mex/argmax_mex.cpp -I../libflandmark/ ' include libflandmark cvlibs ' -output ../matlab_toolbox/mex/argmax_mex']);
    eval(['mex -O -largeArrayDims ./mex/getNormalizedFrame_mex.cpp -I../libflandmark/' include libflandmark cvlibs ' -o ../matlab_toolbox/mex/getNormalizedFrame']);

    fprintf('Compilation finished.\n');
end;


function sout = cvx_profile( flag )

% CVX_PROFILE	CVX-specific profiler control.
%    This is a function used for internal CVX development to help determine
%    performance limits within the CVX code itself, by turning off the profiler
%    when the solver is being called. End users will likely not find this
%    function to be useful.

global cvx___
cvx_global
s = cvx___.profile;
if nargin == 1,
    if isnumeric(flag) || islogical(flag),
        ns = double(flag) ~= 0;
    elseif ischar(flag) && size(flag,1) == 1,
        switch lower(flag),
            case 'true',
                ns = true;
            case 'false',
                ns = false;
            otherwise,
                error( 'String arugment must be ''true'' or ''false''.' );
        end
    else
        error( 'Argument must be a numeric scalar or a string.' );
    end
    if cvx___.profile ~= ns,
        cvx___.profile = ns;
        stat = profile('status');
        if ns && ~isempty( cvx___.problems ) && ~isequal( stat.ProfilerStatus, 'on' ),
            profile on
        elseif ~ns && isequal( stat.ProfilerStatus, 'on' ),
            profile off
        end
    end
end
if nargin == 0 || nargout > 0,
    sout = s;
end

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


function [sts, vind] = checksubs_job(item, subs, dflag)

% function [sts vind] = checksubs_job(item, subs, dflag)
% Check whether a subscript reference is a valid reference in a job
% structure starting at item. subs(1) should have a subscript type of
% '.', and the subscript reference should be a tagname from item.val or
% item.values, depending on dflag.
%
% This function is identical for cfg_branch and cfg_(m)choice classes.
%
% 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: checksubs_job.m 5678 2013-10-11 14:58:04Z volkmar $

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

if strcmp(subs(1).type, '.')
    vind = find(strcmp(subs(1).subs, tagnames(item, dflag)),1);
    sts  = ~isempty(vind);
else
    sts = false;
    vind = [];
end


function tpl = set(tpl,action,varargin)
%TEMPLATE/SET Edit data stored in a Template object
%  TPL = SET(TPL,ACTION,VARARGIN)
%     ACTION 'root'
%     ACTION 'unknowns'
%     ACTION 'file'
%     ACTION 'block'
%     ACTION 'var'

%  Copyright (C) 2003 Guillaume Flandin <Guillaume@artefact.tk>
%  $Revision: 1.0 $Date: 2003/05/05 22:19:51 $

error(nargchk(3,5,nargin));

switch lower(action)
	case 'root'
		error(nargchk(3,3,nargin));
		if exist(varargin{1},'dir')
			tpl.root = varargin{1};
		else
			error('[Template] No such directory.');
		end
	case 'unknowns'
		error(nargchk(3,3,nargin));
		if ismember(varargin{1},{'remove' 'comment' 'keep'})
			tpl.unknowns = varargin{1};
		else
			error('[Template] Unknowns: ''remove'', ''comment'' or ''keep''.');
		end
	case 'file'
		error(nargchk(4,4,nargin));
		if iscellstr(varargin{1})
			for i=1:length(varargin{1})
				ind = find(ismember(tpl.handles,varargin{1}{i}));
				if isempty(ind)
					tpl.handles{end+1} = varargin{1}{i};
					if strcmp(varargin{2}{i}(1),filesep) %- absolute path (Unix)
						tpl.file{end+1} = varargin{2}{i};
					else %- relative path
						tpl.file{end+1} = fullfile(tpl.root,varargin{2}{i});
					end
				else
					if strcmp(varargin{2}{i}(1),filesep) %- absolute path (Unix)
						tpl.file{ind} = varargin{2}{i};
					else %- relative path
						tpl.file{ind} = fullfile(tpl.root,varargin{2}{i});
					end
				end
			end
		elseif ischar(varargin{1})
			tpl = set(tpl,'file',cellstr(varargin{1}),cellstr(varargin{2}));
		else
			error('[Template] Badly formed handles.');
		end
	case 'block'
		error(nargchk(4,5,nargin));
		tpl = loadtpl(tpl,varargin{1});
		if nargin == 4
			name = varargin{2};
		else
			name = varargin{3};
		end
		str = get(tpl,'var',varargin{1});
		blk = '';
		%- look like this (keep the same number (1) of spaces between characters!)
		%  <!-- BEGIN ??? -->
		%  <!-- END ??? -->

		%%%%%%%%%%%%%%%%%%%%%%%%% WIH REGEXP %%%%%%%%%%%%%%%%%%%%%%%%
		% reg = ['<!--\s+BEGIN ' varargin{2} '\s+-->(.*)\n\s*<!--\s+END ' varargin{2} '\s+-->'];
		% [b, e] = regexp(str,reg,'once');
		% if ~isempty(b), blk = str(b:e); end %- should also remove BEGIN and END comments
		% str = regexprep(str,reg,['{' name '}']);
		%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

		%%%%%%%%%%%%%%%%%%%%%% WIHTOUT REGEXP %%%%%%%%%%%%%%%%%%%%%%%
		indbegin = findstr(str,['<!-- BEGIN ' varargin{2} ' -->']);
		indend   = findstr(str,['<!-- END ' varargin{2} ' -->']);
		if ~isempty(indbegin) & ~isempty(indend)
		   blk = str(indbegin+length(['<!-- BEGIN ' varargin{2} ' -->'])+1:indend-1);
		   str = [str(1:indbegin-1) '{' name '}' str(indend+length(['<!-- END ' varargin{2} ' -->'])+1:end)];
		end
		%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

		tpl = set(tpl,'var',varargin{2},blk);
		tpl = set(tpl,'var',varargin{1},str);
	case 'var'
		error(nargchk(3,4,nargin));
		if iscellstr(varargin{1})
			for i=1:length(varargin{1})
				ind = find(ismember(tpl.varkeys,varargin{1}{i}));
				if isempty(ind)
					tpl.varkeys{end+1} = varargin{1}{i};
					if nargin == 4
						tpl.varvals{end+1} = varargin{2}{i};
					else
						tpl.varvals{end+1} = '';
					end
				else
					tpl.varvals{ind} = varargin{2}{i};
				end
			end
		elseif ischar(varargin{1})
			tpl = set(tpl,'var',cellstr(varargin{1}),cellstr(varargin{2}));
		else
			error('[Template] Badly formed variable names.');
		end
	otherwise
		error('[Template] Unknown action to perform.');
end


function prov = hcp_provenance

% HCP_PROVENANCE returns a structure with provenance information

% Copyright (C) 2011-2014 by the Human Connectome Project, WU-Minn Consortium (1U54MH091657)
%
% This file is part of megconnectome.
%
% megconnectome 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.
%
% megconnectome 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 megconnectome.  If not, see <http://www.gnu.org/licenses/>.

prov.version.matlab = ver('MATLAB');

prov.version.megconnectome = ver('megconnectome');
if isempty(prov.version.megconnectome)
  prov.version.megconnectome = 'unknown'; % otherwise struct2xml fails
end

prov.version.fieldtrip = ver('fieldtrip');
if isempty(prov.version.fieldtrip)
  prov.version.fieldtrip = 'unknown'; % otherwise struct2xml fails
end

if isdeployed
  prov.compiled   = 'true';
else
  prov.compiled   = 'false';
end

% it is not desired to keep the date and time of execution of the analysis pipeline
% see https://github.com/Washington-University/megconnectome/issues/126
% prov.time           = datestr(now);

prov.username       = getusername;
prov.hostname       = gethostname;
prov.architecture   = computer('arch');
if isdeployed
  % the buildtimestamp function is created on the fly by the compile script
  prov.buildtimestamp = buildtimestamp;
else
  prov.buildtimestamp = [];
end
prov.pwd            = pwd;
prov.matlabstack    = printstack(dbstack); % using private helper function
prov.Attributes.xmlns_colon_xsi = 'http://www.w3.org/2001XMLSchema-instance';
prov.Attributes.xsi_colon_noNamespaceSchemaLocation = 'megconnectome.xsd';

function str = printstack(s)
str = sprintf('\n');
% skip the first, it is always hcp_provenance and not interesting
for i=2:length(s)
  str = [str sprintf('In %s at %d\n', s(i).name, s(i).line)];
end


% errordlg2() - Makes a popup dialog box with the specified message and (optional)
%               title.
%
% Usage:
%   errordlg2(Prompt, Title);
%
% Example:
%   errordlg2('Explanation of error','title of error');
%
% Input:
%   Prompt  -   A text string explaning why the user is seeing this error message.
%   Title   _   A text string that appears in the title bar of the error message.
%
% Author: Arnaud Delorme, CNL / Salk Institute, 12 August 2002
%
% See also: inputdlg2(), questdlg2()

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

function errordlg2(Prompt, Title);

if exist('beep') == 5
	beep;
else
	disp(char(7));
end;
if nargin <2
	Title = 'Error';
end;
if ~ismatlab, error(Prompt); end;
questdlg2(Prompt, Title, 'OK', 'OK');


%kkgentb 'kgentb: Creates a toolbox'
% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros kgentb.pane file
%
% Parameters:
% String: tb 'Toolbox Name', default: ' ': 'toolbox to create'
% String: path 'Toolbox Path', default: ' ': 'toolbox path'
% String: title 'Toolbox Title ', default: ' ': 'toolbox title'
% String: info 'Toolbox Info ', default: ' ': 'toolbox description file'
% String: author 'Toolbox Author', default: ' ': 'toolbox author'
% String: email 'Author Email ', default: ' ': 'toolbox author email'
% Toggle: add 'Add Toolbox Instead of Generate', default: 0: 'add toolbox instead of generate?'
%
% Example: kkgentb( {'tb',' ';'path',' ';'title',' ';'info',' ';'author',' ';'email',' ';'add',0})
%
% Khoros helpfile follows below:
%
%  PROGRAM
% kgentb - Creates a toolbox from scratch.
%
%  DESCRIPTION
% This program takes the specifications provided, and creates a new toolbox
% object.  If a toolbox by the name given (or located at the path given)
% already exists an error message will be given and the program will exit.
%
% If the [-add] flag is specified, the appropriate toolbox entry will be
% added to the toolbox table, without generating the toolbox object (in this
% case, it is understood that the toolbox in question already exists).
% This allows users to add newly-acquired toolboxes to their list of available
% toolboxes automatically.  Note that the entry will not be added if the
% specified path is not the top level path to a real (existing) toolbox.
%
%
%
%  EXAMPLES
% None
%
%  "SEE ALSO"
% None
%
%  RESTRICTIONS
%
%  REFERENCES
%
%  COPYRIGHT
% Copyright (C) 1993 - 1997, Khoral Research, Inc. ("KRI")  All rights reserved.
%

function varargout = kkgentb(varargin)
Inputs={};
if nargin ==0
  arglist={'',''};
elseif nargin ==1
  arglist=varargin{1};
else error('Usage: [out1,..] = kkgentb(arglist).');
end
if size(arglist,2)~=2
  error('arglist must be of form {''ParameterTag1'',value1;''ParameterTag2'',value2}')
 end
narglist={'tb', ' ';'path', ' ';'title', ' ';'info', ' ';'author', ' ';'email', ' ';'add', 0};
maxval={0,0,0,0,0,0,0};
minval={0,0,0,0,0,0,0};
istoggle=[0,0,1,1,1,1,1];
was_set=istoggle * 0;
paramtype={'String','String','String','String','String','String','Toggle'};
% identify the input arrays and assign them to the arguments as stated by the user
if ~iscell(Inputs)
Inputs = {Inputs};
end
NumReqOutputs=0; nextinput=1; nextoutput=1;
  for ii=1:size(arglist,1)
  wasmatched=0;
  for jj=1:size(narglist,1)
   if strcmp(arglist{ii,1},narglist{jj,1})  % a given argument was matched to the possible arguments
     wasmatched = 1;
     was_set(jj) = 1;
     if strcmp(narglist{jj,2}, '__input')
      if (nextinput > length(Inputs))
        error(['Input ' narglist{jj,1} ' has no corresponding input!']);
      end
      narglist{jj,2} = 'OK_in';
      nextinput = nextinput + 1;
     elseif strcmp(narglist{jj,2}, '__output')
      if (nextoutput > nargout)
        error(['Output nr. ' narglist{jj,1} ' is not present in the assignment list of outputs !']);
      end
      if (isempty(arglist{ii,2}))
        narglist{jj,2} = 'OK_out';
      else
        narglist{jj,2} = arglist{ii,2};
      end

      nextoutput = nextoutput + 1;
      if (minval{jj} == 0)
         NumReqOutputs = NumReqOutputs - 1;
      end
     elseif isstr(arglist{ii,2})
      narglist{jj,2} = arglist{ii,2};
     else
        if strcmp(paramtype{jj}, 'Integer') & (round(arglist{ii,2}) ~= arglist{ii,2})
            error(['Argument ' arglist{ii,1} ' is of integer type but non-integer number ' arglist{ii,2} ' was supplied']);
        end
        if (minval{jj} ~= 0 | maxval{jj} ~= 0)
          if (minval{jj} == 1 & maxval{jj} == 1 & arglist{ii,2} < 0)
            error(['Argument ' arglist{ii,1} ' must be bigger or equal to zero!']);
          elseif (minval{jj} == -1 & maxval{jj} == -1 & arglist{ii,2} > 0)
            error(['Argument ' arglist{ii,1} ' must be smaller or equal to zero!']);
          elseif (minval{jj} == 2 & maxval{jj} == 2 & arglist{ii,2} <= 0)
            error(['Argument ' arglist{ii,1} ' must be bigger than zero!']);
          elseif (minval{jj} == -2 & maxval{jj} == -2 & arglist{ii,2} >= 0)
            error(['Argument ' arglist{ii,1} ' must be smaller than zero!']);
          elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} < minval{jj})
            error(['Argument ' arglist{ii,1} ' must be bigger than ' num2str(minval{jj})]);
          elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} > maxval{jj})
            error(['Argument ' arglist{ii,1} ' must be smaller than ' num2str(maxval{jj})]);
          end
        end
     end
     if ~strcmp(narglist{jj,2},'OK_out') &  ~strcmp(narglist{jj,2},'OK_in')
       narglist{jj,2} = arglist{ii,2};
     end
   end
   end
   if (wasmatched == 0 & ~strcmp(arglist{ii,1},''))
        error(['Argument ' arglist{ii,1} ' is not a valid argument for this function']);
   end
end
% match the remaining inputs/outputs to the unused arguments and test for missing required inputs
 for jj=1:size(narglist,1)
     if  strcmp(paramtype{jj}, 'Toggle')
        if (narglist{jj,2} ==0)
          narglist{jj,1} = '';
        end;
        narglist{jj,2} = '';
     end;
     if  ~strcmp(narglist{jj,2},'__input') && ~strcmp(narglist{jj,2},'__output') && istoggle(jj) && ~ was_set(jj)
          narglist{jj,1} = '';
          narglist{jj,2} = '';
     end;
     if strcmp(narglist{jj,2}, '__input')
      if (minval{jj} == 0)  % meaning this input is required
        if (nextinput > size(Inputs))
           error(['Required input ' narglist{jj,1} ' has no corresponding input in the list!']);
        else
          narglist{jj,2} = 'OK_in';
          nextinput = nextinput + 1;
        end
      else  % this is an optional input
        if (nextinput <= length(Inputs))
          narglist{jj,2} = 'OK_in';
          nextinput = nextinput + 1;
        else
          narglist{jj,1} = '';
          narglist{jj,2} = '';
        end;
      end;
     else
     if strcmp(narglist{jj,2}, '__output')
      if (minval{jj} == 0) % this is a required output
        if (nextoutput > nargout & nargout > 1)
           error(['Required output ' narglist{jj,1} ' is not stated in the assignment list!']);
        else
          narglist{jj,2} = 'OK_out';
          nextoutput = nextoutput + 1;
          NumReqOutputs = NumReqOutputs-1;
        end
      else % this is an optional output
        if (nargout - nextoutput >= NumReqOutputs)
          narglist{jj,2} = 'OK_out';
          nextoutput = nextoutput + 1;
        else
          narglist{jj,1} = '';
          narglist{jj,2} = '';
        end;
      end
     end
  end
end
if nargout
   varargout = cell(1,nargout);
else
  varargout = cell(0);
end
global KhorosRoot
if exist('KhorosRoot') && ~isempty(KhorosRoot)
w=['"' KhorosRoot];
else
if ispc
  w='"C:\Program Files\dip\khorosBin\';
else
[s,w] = system('which cantata');
w=['"' w(1:end-8)];
end
end
callKhoros([w 'kgentb"  '],Inputs,narglist);


classdef CoreCompiledFileInfo < handle
    % CoreCompiledFileInfo. Structure for caching information about compiled files.
    %
    %     CoreCompiledFileInfo is used by CoreMex and its related files to manage
    %     dependencies on mex files. You typically create a map of
    %     CoreMexInfo objects, each of which defines a file to be
    %     compiled, and pass it into CoreMex. You can also use CoreCudaInfo
    %     for cuda files.
    %
    %     The basic rule you must follow is to increment the version number
    %     of your CoreMexInfo object whenever you change the corresponding
    %     mex file. This will force recompilation of any older versions.
    %
    %
    %     Licence
    %     -------
    %     Part of CoreMat. https://github.com/tomdoel/coremat
    %     Author: Tom Doel, 2013.  www.tomdoel.com
    %     Distributed under the MIT licence. Please see website for details.
    %

    properties
        Name
        Extension
        Path
        CompilerOptions
        OtherCompilerFiles
        CurrentVersion

        LastSuccessfulCompiledVersion
        LastSuccessfulCompileDatenum
        LastAttemptedCompiledVersion
        LastAttemptedCompileDatenum
        LastSuccessfulCompiler
        LastAttemptedCompiler
        LastCompileFailed

        NeedsRecompile
        StatusID
    end

    methods
        function obj = CoreCompiledFileInfo(current_version, filename, extension, file_path, compiler_options, other_files)
            if nargin > 0
                obj.Name = filename;
                obj.Extension = extension;
                obj.Path = file_path;
                obj.CompilerOptions = compiler_options;
                obj.OtherCompilerFiles = other_files;
                obj.CurrentVersion = current_version;
            end
        end
    end

end


function gitInfo=getGitInfo()
% Matlab script to get information about the Git repository in the current directory, including:
%          - branch name of the current Git Repo
%          -Git SHA1 HASH of the most recent commit
%          -url of corresponding remote repository, if one exists
%
% The function first checks to see if a .git/ directory is present. If so it
% reads the .git/HEAD file to identify the branch name and then it looks up
% the corresponding commit.
%
% It then reads the .git/config file to find out the url of the
% corresponding remote repository. This is all stored in a gitInfo struct.
%
% Note this uses only file information, it makes no external program
% calls at all.
%
% This function must be in the base directory of the git repository
%
% Released under a BSD open source license. Based on a concept by Marc
% Gershow.
%
% Andrew Leifer
% Harvard University
% Program in Biophysics, Center for Brain Science,
% and Department of Physics
% leifer@fas.harvard.edu
% http://www.andrewleifer.com
% 12 September 2011
%
%
%

% Copyright 2011 Andrew Leifer. All rights reserved.
%
% Redistribution and use in source and binary forms, with or without modification, are
% permitted provided that the following conditions are met:
%
%    1. Redistributions of source code must retain the above copyright notice, this list of
%       conditions and the following disclaimer.
%
%    2. Redistributions in binary form must reproduce the above copyright notice, this list
%       of conditions and the following disclaimer in the documentation and/or other materials
%       provided with the distribution.
%
% THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ''AS IS'' AND ANY EXPRESS OR IMPLIED
% WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
% FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR
% CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
% SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
% ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
% NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
% ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
%
% The views and conclusions contained in the software and documentation are those of the
% authors and should not be interpreted as representing official policies, either expressed
% or implied, of <copyright holder>.

gitpath = mtex_path;

 gitInfo=[];
if ~exist(fullfile(gitpath,'.git'),'file') || ~exist(fullfile(gitpath,'.git','HEAD'),'file')
    %Git is not present
    return
end

%Read in the HEAD information, this will tell us the location of the file
%containing the SHA1
text=fileread(fullfile(gitpath,'.git','HEAD'));
parsed=textscan(text,'%s');

if ~strcmp(parsed{1}{1},'ref:') || ~length(parsed{1})>1
        %the HEAD is not in the expected format.
        %give up
        return
end

path=parsed{1}{2};
[pathstr, name, ext]=fileparts(path);
branchName=name;

%save branchname
gitInfo.branch=branchName;

%Read in SHA1
SHA1text=fileread(fullfile(gitpath,'.git', pathstr,[name ext]));
SHA1=textscan(SHA1text,'%s');
gitInfo.hash=SHA1{1}{1};

%Read in config file
config=fileread(fullfile(gitpath,'.git/config'));
%Find everything space delimited
temp=textscan(config,'%s','delimiter','\n');
lines=temp{1};

remote='';
%Lets find the name of the remote corresponding to our branchName
for k=1:length(lines)

    %Are we at the section describing our branch?
    if strcmp(lines{k},['[branch "' branchName '"]'])
        m=k+1;
        %While we haven't run out of lines
        %And while we haven't run into another section (which starts with
        % an open bracket)
        while (m<=length(lines) && ~strcmp(lines{m}(1),'[') )
            temp=textscan(lines{m},'%s');
            if length(temp{1})>=3
                if strcmp(temp{1}{1},'remote') && strcmp(temp{1}{2},'=')
                    %This is the line that tells us the name of the remote
                    remote=temp{1}{3};
                end
            end

            m=m+1;
        end

    end
end
gitInfo.remote=remote;

url='';
%Find the remote's url
for k=1:length(lines)

    %Are we at the section describing our branch?
    if strcmp(lines{k},['[remote "' remote '"]'])
        m=k+1;
        %While we haven't run out of lines
        %And while we haven't run into another section (which starts with
        % an open bracket)
        while (m<=length(lines) && ~strcmp(lines{m}(1),'[') )
            temp=textscan(lines{m},'%s');
            if length(temp{1})>=3
                if strcmp(temp{1}{1},'url') && strcmp(temp{1}{2},'=')
                    %This is the line that tells us the name of the remote
                    url=temp{1}{3};
                end
            end

            m=m+1;
        end

    end
end

gitInfo.url=url;


function fout = gwaitbar(x,whichbar, varargin)
%WAITBAR Display wait bar.
%   H = WAITBAR(X,'message', property, value, property, value, ...)
%   creates and displays a waitbar of fractional length X.  The
%   handle to the waitbar figure is returned in H.
%   X should be between 0 and 1.  Optional arguments property and
%   value allow to set corresponding waitbar figure properties.
%   Property can also be an action keyword 'CreateCancelBtn', in
%   which case a cancel button will be added to the figure, and
%   the passed value string will be executed upon clicking on the
%   cancel button or the close figure button.
%
%   WAITBAR(X) will set the length of the bar in the most recently
%   created waitbar window to the fractional length X.
%
%   WAITBAR(X,H) will set the length of the bar in waitbar H
%   to the fractional length X.
%
%   WAITBAR(X,H,'message') will update the message text in
%   the waitbar figure, in addition to setting the fractional
%   length to X.
%
%   WAITBAR is typically used inside a FOR loop that performs a
%   lengthy computation.
%
%   Example:
%       h = waitbar(0,'Please wait...');
%       for i=1:1000,
%           % computation here %
%           waitbar(i/1000,h)
%       end
%
%   See also DIALOG, MSGBOX.

%   Copyright 1984-2015 The MathWorks, Inc.

% Error in -nojvm mode
if ~usejava('jvm')
    error(message('MATLAB:HandleGraphics:noJVM'));
end

inWaitbarCreate = true;

if (nargin == 0)
    error(message('MATLAB:waitbar:InvalidArguments'));
elseif (nargin > 0)
    % Must be a numeric value
    if ~isnumeric(x) || ~isscalar(x)
        error(message('MATLAB:waitbar:InvalidFirstInput'));
    elseif ((x < 0) || (x > 1))
        % Throw a warning in this case, clamp it down and keep going
        % this is a behavior change and we want to eventually error out in this scenario,
        % but want to do that gradually
        if (x < 0)
            x = 0;
        elseif (x > 1)
            x = 1;
        end
        % This warning will be enabled when callers no longer send in values
        % outside the allowed range
        % warning('MATLAB:waitbar:invalidValue', '%s\n%s%s', ...
        %    'The first argument must be a numeric value between 0 and 1.',...
        %    'Setting the value to: ', num2str(x));
    end

    if (nargin == 1)
        % A waitbar handle is not provided. Look for one.
        f = findobj(allchild(0),'flat','Tag','TMWWaitbar');

        if isempty(f)
            % No waitbar found. Create a new waitbar with a default string
            name = getString(message('MATLAB:uistring:waitbar:WaitbarLabel'));
        else
            % Found waitbar(s). Update the first (current) waitbar with the new value
            inWaitbarCreate = false;
            f = f(1);
            % Get handles from the saved appdata
            handles = extractHandles(f);
        end
    elseif (nargin > 1)
        % A waitbar message or handle to an existing waitbar has been
        % provided
        if ischar(whichbar) || iscellstr(whichbar)
            % The second arg is a message, we are creating a waitbar
            name = whichbar;
        elseif all(ishghandle(whichbar, 'figure'))
            % The second arg is a handle, we are updating the value
            inWaitbarCreate = false;
            % Get handles from the saved appdata
            handles = extractHandles(whichbar);
        else
            error(message('MATLAB:waitbar:InvalidSecondInput'));
        end
    end
end

x = max(0,min(100*x,100)); % Map any value of x to a value between 0 and 100
try
    if inWaitbarCreate
        % waitbar(x,name)  initialize
        createWaitbar(varargin{:});
    else
        % waitbar(x)    update
        updateWaitbar(varargin{:});
    end  % inWaitbarCreate
catch ex
    err = MException('MATLAB:waitbar:InvalidArguments','%s',...
        getString(message('MATLAB:waitbar:ImproperArguments')));
    err = err.addCause(ex);
    close(findobj(allchild(0),'flat','Tag','TMWWaitbar'));
    throw(err);
end
drawnow;

if nargout==1,
    fout = handles.figure;
end

    function createWaitbar(varargin)
        vertMargin = 0;
        if nargin > 0,
            % we have optional arguments: property-value pairs
            if rem (nargin, 2 ) ~= 0
                error(message('MATLAB:waitbar:InvalidOptionalArgsPass'));
            end
        end

        oldRootUnits = get(0,'Units');
        % Restore the Units safely
        c = onCleanup(@()set(0, 'Units', oldRootUnits));

        set(0, 'Units', 'points');
        screenSize = get(0,'ScreenSize');
        delete(c);

        pointsPerPixel = 72/get(0,'ScreenPixelsPerInch');

        width = 360 * pointsPerPixel;
        height = 75 * pointsPerPixel;
        pos = [screenSize(3)/2-width/2 screenSize(4)/2-height/2 width height];

        handles.figure = figure(...
            'Units', 'points', ...
            'BusyAction', 'queue', ...
            'WindowStyle', 'normal', ...
            'Position', pos, ...
            'Resize','off', ...
            'CreateFcn','', ...
            'NumberTitle','off', ...
            'IntegerHandle','off', ...
            'MenuBar', 'none', ...
            'Tag','TMWWaitbar',...
            'Interruptible', 'off', ...
            'DockControls', 'off', ...
            'Visible','off');

        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        % set figure properties as passed to the fcn
        % pay special attention to the 'cancel' request
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        visValue = 'on';
        cancelBtnCreated = 0;
        if nargin > 0,
            propList = varargin(1:2:end);
            valueList = varargin(2:2:end);

            visibleExist = strmatch('vis',lower(propList));
            if ~isempty(visibleExist)
                visValue = valueList{visibleExist};
            end

            for ii = 1:length( propList )
                try
                    if strcmpi(propList{ii}, 'createcancelbtn' ) && ~cancelBtnCreated
                        cancelBtnHeight = 23 * pointsPerPixel;
                        cancelBtnWidth = 60 * pointsPerPixel;
                        newPos = pos;
                        vertMargin = vertMargin + cancelBtnHeight;
                        newPos(4) = newPos(4)+vertMargin;
                        callbackFcn = [valueList{ii}];
                        set( handles.figure, 'Position', newPos, 'CloseRequestFcn', callbackFcn );
                        cancelButt = uicontrol('Parent',handles.figure, ...
                            'Units','points', ...
                            'Callback',callbackFcn, ...
                            'ButtonDownFcn', callbackFcn, ...
                            'Enable','on', ...
                            'Interruptible','off', ...
                            'Position', [pos(3)-cancelBtnWidth*1.4, 7,  ...
                            cancelBtnWidth, cancelBtnHeight], ...
                            'String',getString(message('MATLAB:uistring:waitbar:Cancel')), ...
                            'Tag','TMWWaitbarCancelButton'); %#ok<NASGU>
                        cancelBtnCreated = 1;
                    else
                        % simply set the prop/value pair of the figure
                        set( handles.figure, propList{ii}, valueList{ii});
                    end
                catch ex
                   warning(message('MATLAB:uistring:waitbar:WarningCouldNotSetPropertyValue',propList{ii}, num2str(valueList{ii})));
                end
            end
        end

        axNorm=[.05 .3 .9 .2];
        axPos=axNorm.*[pos(3:4),pos(3:4)] + [0 vertMargin 0 0];

        handles.axes = axes('Parent', handles.figure, ...
            'XLim',[0 100],...
            'YLim',[0 1],...
            'Box','on', ...
            'Units','Points',...
            'Position',axPos,...
            'XTickMode','manual',...
            'YTickMode','manual',...
            'XTick',[],...
            'YTick',[],...
            'XTickLabelMode','manual',...
            'XTickLabel',[],...
            'YTickLabelMode','manual',...
            'YTickLabel',[],...
            'Visible', 'off');

        handles.axesTitle = get(handles.axes,'Title');
        oldTitleUnits=get(handles.axesTitle,'Units');
        set(handles.axesTitle,...
            'Units',      'points',...
            'FontSize', 'factory',...
            'FontName', 'factory',...
            'FontWeight', 'factory',...
            'FontAngle', 'factory',...
            'FontUnits', 'factory',...
            'String',     name,...
            'Visible',    'on');

        tExtent=get(handles.axesTitle,'Extent');
        set(handles.axesTitle,'Units',oldTitleUnits);

        titleHeight=tExtent(4)+axPos(2)+axPos(4)+5;
        if titleHeight>pos(4)
            pos(4)=titleHeight;
            pos(2)=screenSize(4)/2-pos(4)/2;
            figPosDirty=true;
        else
            figPosDirty=false;
        end

        if tExtent(3)>pos(3); % If extent width is greater than the width of figure. change the figure width.
            pos(3)=min(tExtent(3)*1.10,screenSize(3));
            pos(1)=screenSize(3)/2-pos(3)/2;

            axPos([1,3])=axNorm([1,3])*pos(3);
            set(handles.axes,'Position',axPos);

            figPosDirty=true;
        end

        if figPosDirty
            set(handles.figure,'Position',pos);
            if (cancelBtnCreated)
                cancelButtonPos = get(cancelButt, 'Position');
                cancelButtonPos(1) = pos(3)-cancelButtonPos(3)*1.4;
                set(cancelButt, 'Position', cancelButtonPos);
            end
        end

        uiwaitbar(handles, 'create', x, axPos);

        set(handles.figure,'HandleVisibility','Callback','Visible', visValue);
    end

    function updateWaitbar(varargin)
        uiwaitbar(handles, 'update', x);

        if nargin>0
            % Update waitbar title:
            set(handles.axesTitle,'String',varargin{1});
        end
    end
end

function handles = extractHandles(fighandle)
% Used to get the handles structure from the given waitbar figure and
% also to check if the structure is of the right size.
handles = getappdata(fighandle,'TMWWaitbar_handles');
if isempty(handles) || (length(fieldnames(handles))~=5)
    error(message('MATLAB:waitbar:WaitbarHandlesNotFound'));
end
end
%%
% _*GIBBON footer text*_
%
% License: <https://github.com/gibbonCode/GIBBON/blob/master/LICENSE>
%
% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for
% image segmentation, image-based modeling, meshing, and finite element
% analysis.
%
% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.


% SERVER Write a message over the specified port
%
% Usage - server(message, output_port, number_of_retries)
function server(port, number_of_retries)

    import java.net.ServerSocket
    import java.io.*

    if (nargin < 2)
        number_of_retries = 2; % set to -1 for infinite
    end
    retry             = 0;

    server_socket  = [];
    output_socket  = [];

    port

    while true

        retry = retry + 1;

        try
            if ((number_of_retries > 0) && (retry > number_of_retries))
                fprintf(1, 'Too many retries\n');
                break;
            end

            fprintf(1, ['Try %d waiting for client to connect to this ' ...
                        'host on port : %d\n'], retry, port);

            % wait for 1 second for client to connect server socket
            server_socket = ServerSocket(port);
            server_socket.setSoTimeout(10000);

            fprintf(1, 'Waiting for client to connect\n');

            output_socket = server_socket.accept;

            fprintf(1, 'Client connected\n');

            input_stream   = output_socket.getInputStream;
            %d_output_stream = DataOutputStream(output_stream);

            for i=1:10
                % read data from the socket - wait a short time first
            pause(0.5);
            bytes_available = input_stream.available;
            fprintf(1, 'Reading %d bytes\n', bytes_available);
            end

            % clean up
            server_socket.close;
            output_socket.close;
            break;

        catch me
            me
            if ~isempty(server_socket)
                server_socket.close
            end

            if ~isempty(output_socket)
                output_socket.close
            end

            % pause before retrying
            pause(1);
   end
end
end


function collectObjects(fig)
% Helper function for browseFigure.m

% Get handles of already present objects
objHandle = get(fig, 'UserData');
% Find handles of new objects
newObjects  = findobj(fig,'Visible','on','-not','Type','figure');
% Make new objects invisible
set(newObjects, 'Visible', 'off');
% Add new objects handles
objHandle{end+1} = newObjects;
% Pass object handles to figure's UserData
set(fig, 'UserData', objHandle);
axHandle = findobj(newObjects, 'Type', 'axes');
% Make handles invisible to avoid overwriting of the axes
set(axHandle, 'HandleVisibility', 'off');


classdef BaseApp < matlab.apps.AppBase & matlab.mixin.SetGetExactNames & ...
        wt.mixin.ErrorHandling
    % Base class for Widgets Toolbox apps

    % Copyright 2020-2021 The MathWorks, Inc.

    %% Properties
    properties (AbortSet)

        % Name of the app
        Name (1,1) string = "My App"

    end %properties

    properties (SetAccess = protected)

        % Model class for App preferences
        %(may subclass wt.model.Preferences to add more prefs)
        Preferences (1,1) wt.model.Preferences

        % Name of group to store preferences (defaults to class name)
        PreferenceGroup (1,1) string

    end %properties

    properties (AbortSet, Dependent)

        % Position of the app window
        Position

        % Visibility of the app window
        Visible

        % State of the app window
        WindowState

    end %properties

    %% Internal properties
    properties (Hidden, Transient, NonCopyable, SetAccess = immutable)

        % Figure window of the app
        Figure matlab.ui.Figure

        % Primary grid to place contents
        Grid matlab.ui.container.GridLayout

    end %properties

    properties (Transient, NonCopyable, ...
            Access = {?wt.apps.BaseApp, ?wt.test.BaseWidgetTest} )

        % Last used folder (for file operations)
        LastFolder (1,1) string = pwd

        % Is setup complete?
        SetupComplete (1,1) logical = false;

    end %properties

    %% Abstract methods (subclass must implement these)
    methods (Abstract, Access = protected)

        setup(app)

        update(app)

    end %methods

    %% Debugging Methods
    methods

        function forceUpdate(app)
            % Forces update to run (For debugging only!)

            app.update();

        end %function

    end %methods

    %% Constructor / destructor
    methods (Access = public)

        function app = BaseApp(varargin)
            % Constructor

            % Create the figure and hide until components are created
            app.Figure = uifigure( ...
                'AutoResizeChildren','off',...
                'Units','pixels', ...
                'DeleteFcn',@(h,e)delete(app), ...
                'CloseRequestFcn',@(h,e)close(app), ...
                'Visible','off');

            % Create MainGridLayout
            app.Grid = uigridlayout(app.Figure,[1 1]);
            app.Grid.Padding = [0 0 0 0];

            % Check for preference input and assign it first, in case
            % Preferences was subclassed
            % [splitArgs,varargin] = app.splitArgs('Preferences', varargin{:});
            % if ~isempty(splitArgs)
            %     app.Preferences = splitArgs{2};
            % end

            % Retrieve preferences
            app.loadPreferences();

            % Load last figure position
            % Note app.Figure.Position is inner position, where
            % app.Position is outer position. Inner position is the same
            % regardless of any menubar or toolbar, while outer position
            % changes if either is added. Use inner position for this
            % purpose so it does not depend on if/when any menubar or
            % toolbar is added to the figure.
            app.Figure.Position = app.getPreference('Position',[100 100 1000 700]);

            % Set up components
            app.setup_internal();
            app.setup();

            % Set any P-V pairs
            if ~isempty(varargin)
                set(app, varargin{:});
            end

            % Register the app with App Designer
            registerApp(app, app.Figure)

            % Ensure it's on screen
            app.moveOnScreen();

            % Mark the setup complete
            app.SetupComplete = true;

            % Update the app
            app.update();

            % Update the title
            app.updateTitle();

            % Force drawing to finish
            drawnow

            % Now, make it visible
            app.Figure.Visible = 'on';

        end %function

        function delete(app)
            % Destructor

            % Store last position in preferences
            if isscalar(app.Figure) && isvalid(app.Figure)
                app.setPreference('Position',app.Figure.Position)
            end

            % Save preferences
            app.savePreferences();

            % Now, delete the figure
            delete(app.Figure)

        end %function

    end %methods

    %% Public Methods
    methods

        function close(app)
            % Triggered on figure closed

            app.delete();

        end %function

        function selection = promptYesNoCancel(app, message, title, default, icon)
            % Prompt the user with a yes/no/cancel selection

            % Define arguments
            arguments
                app (1,1) wt.apps.BaseApp
                message (1,1) string = "Are you sure?"
                title (1,1) string = ""
                default (1,1) string = "Cancel"
                icon (1,1) string = "question"
            end

            % Launch the prompt
            selection = uiconfirm(app.Figure, message, title,...
                "Options",["Yes","No","Cancel"],...
                "DefaultOption",default,...
                "CancelOption","Cancel",...
                "Icon",icon);

        end %function

        function filePath = promptToSaveAs(app, filePath, filter, title)
            % Prompt the user to save a file

            % Define arguments
            arguments
                app (1,1) wt.apps.BaseApp
                filePath (1,1) string = pwd
                filter = ["*.mat","MATLAB MAT File"];
                title (1,1) string = "Save as"
            end

            % Prompt for the file
            [fileName,pathName] = uiputfile(filter, title, filePath);

            % Did the user cancel?
            if isequal(fileName,0)
                filePath = string.empty(0);
            else
                filePath = fullfile(pathName,fileName);
                app.LastFolder = pathName;
            end %if isequal(fileName,0)

        end %function

        function filePath = promptToLoad(app, filter, title)
            % Prompt the user to load a file

            % Define arguments
            arguments
                app (1,1) wt.apps.BaseApp
                filter = ["*.mat","MATLAB MAT File"];
                title (1,1) string = "Open"
            end

            % Prompt for the file
            [fileName,pathName] = uigetfile(filter, title, app.LastFolder);

            % Did the user cancel?
            if isequal(fileName,0)
                filePath = string.empty(0);
            else
                filePath = fullfile(pathName,fileName);
                app.LastFolder = pathName;
            end %if isequal(fileName,0)

        end %function

    end %methods

    %% Sealed Public methods
    methods (Sealed)

        function value = getPreference(app,propName,defaultValue)
            % Get an app preference from the Preferences object

            if isprop(app.Preferences, propName)
                value = app.Preferences.(propName);
            elseif nargin>2
                value = defaultValue;
            else
                value = [];
            end

        end %function

        function setPreference(app,propName,value)
            % Set an app preference in the Preferences object

            if ~isprop(app.Preferences,propName)
                addprop(app.Preferences,propName);
            end
            app.Preferences.(propName) = value;

        end %function

        function moveOnScreen(app)
            % Ensure the figure is placed on screen

            if strcmp(app.Figure.Units,'pixels')

                % Get the corners of each screen
                g = groot;
                screenPos = g.MonitorPositions;
                screenCornerA = screenPos(:,1:2);
                screenCornerB = screenPos(:,1:2) + screenPos(:,3:4) - 1;

                % Buffer for title bar
                titleBarHeight = 30;

                % Get the corners of the figure (bottom left and top right)
                figPos = app.Figure.OuterPosition;
                figCornerA = figPos(1:2);
                figCornerB = figPos(1:2) + figPos(:,3:4) - 1;

                % Are the corners on any screen?
                aIsOnScreen = all( figCornerA >= screenCornerA & ...
                    figCornerA <= screenCornerB, 2 );
                bIsOnScreen = all( figCornerB >= screenCornerA & ...
                    figCornerB <= screenCornerB, 2);

                % Are corners on a screen?

                % Are both corners fully on any screen?
                if any(aIsOnScreen) && any(bIsOnScreen)
                    % Yes - do nothing

                elseif any(bIsOnScreen)
                    % No - only upper right corner is on a screen

                    % Calculate the adjustment needed, and make it
                    figAdjust = max(figCornerA, screenCornerA(bIsOnScreen,:)) ...
                        - figCornerA;
                    figPos(1:2) = figPos(1:2) + figAdjust;

                    % Ensure the upper right corner still fits
                    figPos(3:4) = min(figPos(3:4), ...
                        screenCornerB(bIsOnScreen,:) - figPos(1:2) - [0 titleBarHeight] + 1);

                    % Move the figure
                    app.Figure.Position = figPos;

                elseif any(aIsOnScreen)
                    % No - only lower left corner is on a screen

                    % Calculate the adjustment needed, and make it
                    figAdjust = min(figCornerB, screenCornerB(aIsOnScreen,:)) ...
                        - figCornerB;
                    figPos(1:2) = max( screenCornerA(aIsOnScreen,:),...
                        figPos(1:2) + figAdjust );

                    % Ensure the upper right corner still fits
                    figPos(3:4) = min(figPos(3:4), ...
                        screenCornerB(aIsOnScreen,:) - figPos(1:2) - [0 titleBarHeight] + 1);

                    % Move the figure
                    app.Figure.Position = figPos;

                else
                    % No - Not on any screen

                    % This is slower, but uncommon anyway
                    movegui(app.Figure,'onscreen');

                end %if any( all(aIsOnScreen,2) & all(bIsOnScreen,2) )

            else

                % This is slower, but uncommon anyway
                movegui(app.Figure,'onscreen');

            end %if strcmp(app.Figure.Units,'pixels')

        end %function

    end %methods

    %% Protected Methods
    methods (Access = protected)

        function setup_internal(~)
            % Preform internal pre-setup necessary

            % This is used for session managed apps

        end %function

        function loadPreferences(app)
            % Load stored preferences

            app.Preferences.load(app.PreferenceGroup);

        end %function

        function savePreferences(app)
            % Save preferences

            app.Preferences.save(app.PreferenceGroup);

        end %function

        function updateTitle(app)
            % Update the figure title

            app.Figure.Name = app.Name;

        end %function

    end %methods

    %% Accessors
    methods

        function set.Name(app,value)
            app.Name = value;
            app.updateTitle();
        end

        function value = get.PreferenceGroup(app)
            value = app.PreferenceGroup;
            if isempty(value)
                value = class(app);
            end
            value = matlab.lang.makeValidName(value);
        end

        function value = get.Position(app)
            value = app.Figure.Position;
        end

        function set.Position(app,value)
            app.Figure.Position = value;
        end

        function value = get.Visible(app)
            value = app.Figure.Visible;
        end

        function set.Visible(app,value)
            app.Figure.Visible = value;
        end

        function value = get.WindowState(app)
            value = app.Figure.WindowState;
        end

        function set.WindowState(app,value)
            app.Figure.WindowState = value;
        end

    end %methods

end % classdef


function tname = treepart(item, dflag)

% function tname = treepart(item, dflag)
% tree part to search - for cfg_repeat/cfg_choice this is val for filled
% cfg_items and values for default cfg_items.
%
% This code is part of a batch job configuration system for MATLAB. See
%      help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging

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

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

if dflag
    tname = 'values';
else
    tname = 'val';
end;


function fgrabm_init
%FGRABM_INIT FrameGrabM Initialization routine
%   FGRABM_INIT is the first activity that must be performed to start up
%   the underlying video capture library.  This produces a global variable
%   FGRABM that will be used by other FrameGrabM functions.  Most other
%   FrameGrabM functions will call FGRABM_INIT automatically if needed.
%
%   Version 0.8 - 06 March 2012
global FGRABM

% Declare our Java classpath:
import com.academiken.framegrabm.util.*;

% Create our persistent structure:
if isempty(FGRABM)
    FGRABM = struct();
end

% Instanciate the Java object:
if ~isfield(FGRABM, 'class')
    FGRABM.class = GrabCore;
end

% Set the default device:
if ~isfield(FGRABM, 'defaultDevice')
    FGRABM.defaultDevice = 1;
end

% Prune off formats field so formats can be refreshed:
if isfield(FGRABM, 'formats')
    FGRABM = rmfield(FGRABM, 'formats');
end

% Initialize:
FGRABM.class.init()


function cstr= str_tail(cstr,varargin)
%tail= strtail(str,<delim>)
%
% returns the string after (not including) the first space
% works also for cells of strings
% 'delim' -  delimiter of the string head, e.g. '_' (default ' ')
%
% See also strhead

if nargin<2
    delim = ' ';
else
    delim = varargin{1};
end

if ~iscell(cstr),
  cstr= str_tail({cstr},delim);
  cstr= cstr{1};
  return
end

for il= 1:length(cstr),
  cstr{il}= cstr{il}(max([1 findstr(delim, cstr{il})+1]):end);
end


function clearDirectory(rootdir)

if exist(fullfile(rootdir,'movie.avi'),'file')

  rmdir(rootdir,'s');

else

  dd = dir(rootdir);
  for ndx =1:numel(dd)
    if strcmp(dd(ndx).name(1),'.'), continue; end
    curd = fullfile(rootdir,dd(ndx).name);
    if isdir(curd)
       clearDirectory(curd);
    end

  end

end


%GETDATA Get data fields in mapping
%
%    DATA = GETDATA(W)
%
% Get content of data field of W
%
%    DATA = GETDATA(W,N)
%
% Get content of N-th cell in W.DATA.
%
%    DATA = GETDATA(W,FIELD)
%
% Get content of desired field if W.DATA is structure


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

    enumeration
        No('No','no')
        Yes('Yes','yes')
    end

    properties
        name(1,:) char
        optStr(1,:) char
    end

    methods
        function obj = IpOptRecalcYEnum(name, optStr)
            obj.name = name;
            obj.optStr = optStr;
        end
    end

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

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


function RevertDirEdit(topH)

% dirS = RevertDirEdit(topH);
%
% Returns all the editable fields in the dialog to their original values,
% and reverts the directory structure.
%
% DBR 6/99

% Revert the session and directory structures:
uiData = get(topH, 'UserData');
dirS = uiData.origDirS;
uiData.dirS = dirS;
set(topH, 'UserData', uiData)

% Revert the directory dialog fields
nDir = length(uiData.dirData);
for iField=1:nDir
  editFlag = uiData.dirData(iField).edit;
  if editFlag
    evalStr = ['dirS.', uiData.dirData(iField).field];
    set(uiData.dirData(iField).handle, 'string', mat2str(eval(evalStr)));
  end
end