%kkclrgetargs 'Clear the main_get_args_call field in the main of a kroutine or xvroutine'
% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros kclrgetargs.pane file
%
% Parameters:
% String: tb 'Toolbox Name', default: ' ': 'Toolbox to search'
% String: oname 'Object Name ', default: ' ': 'Software object name'
% Toggle: rgw 'Run Ghostwriter?', default: 0: 'Run ghostwriter after stripping the get args section'
%
% Example: kkclrgetargs( {'tb',' ';'oname',' ';'rgw',0})
%
% Khoros helpfile follows below:
%
%  PROGRAM
% kclrgetargs - Clear the main_get_args_call field in the main of a kroutine or xvroutine
%
%  DESCRIPTION
% This program can be used to clear the -main_get_args_call field in the
% main routine of kroutines and xvroutines.  The optional flag -rgw tells
% kclrgetargs to run the code generators after clearing this field, thereby
% putting the latest version of the call to the clui and pane parsing API.
% It was developed primarily to help migrate kroutines that were developed
% before the Khoros code generators supported the generation of continuous
% run processes.  All new kroutines and xvroutines use the new API clui
% initialize API that supports continuous run, and with this program it
% is easy to update existing kroutines and xvroutines.
%
%
%
%  EXAMPLES
%
% % kclrgetargs -tb testtoolbox -oname myobject -rgw
% The -main_get_args_call section of myobject has been cleared
% ghostwriter: done generating myobject man page
% ghostwriter: done generating myobject.h
% ghostwriter: done generating myobject.c
% ghostwriter: done generating usage.c
% ghostwriter: done generating myobject help page
% ghostwriter: updating object database [TESTTOOLBOX::myobject]
%
%
%  "SEE ALSO"
% ghostwriter(1), kcodegen(3)
%
%  RESTRICTIONS
% Since the -main_get_args_call section of a kroutine or xvroutine is
% one of the fields that users are allowed to edit, running this
% program can potentially remove special code the user put in that
% section so that their program would do some special handling of
% the command line parameters.
%
%  REFERENCES
% None
%
%  COPYRIGHT
% Copyright (C) 1993 - 1997, Khoral Research, Inc. ("KRI")  All rights reserved.
%

function varargout = kkclrgetargs(varargin)
Inputs={};
if nargin ==0
  arglist={'',''};
elseif nargin ==1
  arglist=varargin{1};
else error('Usage: [out1,..] = kkclrgetargs(arglist).');
end
if size(arglist,2)~=2
  error('arglist must be of form {''ParameterTag1'',value1;''ParameterTag2'',value2}')
 end
narglist={'tb', ' ';'oname', ' ';'rgw', 0};
maxval={0,0,0};
minval={0,0,0};
istoggle=[0,0,1];
was_set=istoggle * 0;
paramtype={'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 'kclrgetargs"  '],Inputs,narglist);


function s = mfileparse(mfile, mdirs, names, options)
%MFILEPARSE Parsing of an M-file to obtain synopsis, help and references
%  S = MFILEPARSE(MFILE, MDIRS, NAMES, OPTIONS) parses the M-file MFILE looking
%  for synopsis (function), H1 line, subroutines and todo tags (if any).
%  It also fills in a boolean array indicating whether MFILE calls M-files
%  defined by MDIRS (M-files directories) AND NAMES (M-file names).
%  The input OPTIONS comes from M2HTML: fields used are 'verbose', 'global'
%  and 'todo'.
%  Output S is a structure whose fields are:
%     o synopsis: char array (empty if MFILE is a script)
%     o h1line: short one-line description into the first help line
%     o subroutine: cell array of char containing subroutines synopsis
%     o hrefs: boolean array with hrefs(i) = 1 if MFILE calls mdirs{i}/names{i}
%     o todo: structure containing information about potential todo tags
%
%  See also M2HTML

%  Copyright (C) 2003 Guillaume Flandin <Guillaume@artefact.tk>
%  $Revision: 1.0 $Date: 2003/29/04 17:33:43 $

narginchk(3,4);
if nargin == 3,
	options = struct('verbose',1, 'globalHypertextLinks',0, 'todo',0);
end

%- Delimiters used in strtok: some of them may be useless (% " .), removed '.'
strtok_delim = sprintf(' \t\n\r(){}[]<>+-*~!|\\@&/,:;="''%%');

%- Open for reading the M-file
fid = openfile(mfile,'r');
it = 0; % line number

%- Initialize Output
s = struct('synopsis',   '', ...
		   'h1line',     '', ...
		   'subroutine', {{}}, ...
		   'hrefs',      sparse(1,length(names)), ...
		   'todo',       struct('line',[],'comment',{{}}), ...
		   'ismex',      zeros(size(mexexts)));

%- Initialize flag for synopsis cont ('...')
flagsynopcont = 0;
%- Look for synopsis and H1 line
%  Help is the first set of contiguous comment lines in an m-file
%  The H1 line is a short one-line description into the first help line
while 1
	tline = fgetl(fid);
	if ~ischar(tline), break, end
	it = it + 1;
	tline = deblank(fliplr(deblank(fliplr(tline))));
	%- Synopsis line
	if ~isempty(strmatch('function',tline))
		s.synopsis = tline;
		if ~isempty(strmatch('...',fliplr(tline)))
			flagsynopcont = 1;
			s.synopsis = deblank(s.synopsis(1:end-3));
		end
	%- H1 Line
	elseif ~isempty(strmatch('%',tline))
		% allow for the help lines to be before the synopsis
		if isempty(s.h1line)
			s.h1line = fliplr(deblank(tline(end:-1:2)));
		end
		if ~isempty(s.synopsis), break, end
	%- Go through empty lines
	elseif isempty(tline)

	%- Code found. Stop.
	else
		if flagsynopcont
			if isempty(strmatch('...',fliplr(tline)))
				s.synopsis = [s.synopsis tline];
				flagsynopcont = 0;
			else
				s.synopsis = [s.synopsis deblank(tline(1:end-3))];
			end
		else
			break;
		end
	end
end

%- Global Hypertext Links option
%  If false, hypertext links are done only among functions in the same
%  directory.
if options.globalHypertextLinks
	hrefnames = names;
else
	indhref = find(strcmp(fileparts(mfile),mdirs));
	hrefnames = {names{indhref}};
end

%- Compute cross-references and extract subroutines
%  hrefs(i) is 1 if mfile calls mfiles{i} and 0 otherwise
while ischar(tline)
	% Remove blanks at both ends
	tline = deblank(fliplr(deblank(fliplr(tline))));

	% Split code into meaningful chunks
	splitc = splitcode(tline);
	for j=1:length(splitc)
		if isempty(splitc{j}) | ...
			splitc{j}(1) == '''' | ...
			~isempty(strmatch('...',splitc{j}))
			% Forget about empty lines, char strings or conts
		elseif splitc{j}(1) == '%'
			% Cross-references are not taken into account in comments
			% Just look for potential TODO line
			if options.todo
				if ~isempty(strmatch('% TODO %',splitc{j}))
					s.todo.line   = [s.todo.line it];
					s.todo.comment{end+1} = splitc{j}(9:end);
				end
			end
		else
			% detect if this line is a declaration of a subroutine
			if ~isempty(strmatch('function',splitc{j}))
				s.subroutine{end+1} = splitc{j};
			else
				% get list of variables and functions
				symbol = {};
				while 1
					[t,splitc{j}] = strtok(splitc{j},strtok_delim);
					if isempty(t), break, end;
					symbol{end+1} = t;
				end
				if options.globalHypertextLinks
					s.hrefs = s.hrefs + ismember(hrefnames,symbol);
				else
					s.hrefs(indhref) = s.hrefs(1,indhref) + ...
									   ismember(hrefnames,symbol);
				end
			end
		end
	end
	tline = fgetl(fid);
	it = it + 1;
end

fclose(fid);

%- Look for Mex files
[pathstr,name] = fileparts(mfile);
samename = dir(fullfile(pathstr,[name	'.*']));
samename = {samename.name};
ext = {};
for i=1:length(samename)
	[dummy, dummy, ext{i}] = fileparts(samename{i});
end
s.ismex = ismember(mexexts,ext);


function definput = arg_fwtcommon(definput)

%definput.flags.ansy = {'syn','ana'};
definput.keyvals.a = [];


addpath /n/fs/vision/www/pvt/

FrameHeight = 630;
TemplateFileName = 'template.html';
TemplateString = file2string(TemplateFileName);
amazonHead = '<?xml version="1.0"?><HTMLQuestion xmlns="http://mechanicalturk.amazonaws.com/AWSMechanicalTurkDataSchemas/2011-11-11/HTMLQuestion.xsd"><HTMLContent><![CDATA[<!DOCTYPE html><title>HIT</title><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/><form name="mturk_form" method="post" id="mturk_form" action="https://www.mturk.com/mturk/externalSubmit"><input type="hidden" value="" name="assignmentId" id="assignmentId" />';
amazonTail = ['</form>]]></HTMLContent><FrameHeight>' num2str(FrameHeight) '</FrameHeight></HTMLQuestion>'];
QuestionTemplate = [amazonHead TemplateString amazonTail];

% put your stuff here
for questionID=1:1000
    Question = QuestionTemplate;
    Question = strrep(Question,'${questionID}',num2str(questionID));
    Question = strrep(Question,'${data}','yinda fillin');
    Question = strrep(Question,'${examples}','yinda fillin');
    Question = strrep(Question,'${definition}','yinda fillin');
    Question = strrep(Question,'${question}','yinda fillin');
    Question = strrep(Question,'${listname}','yinda fillin');
end


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


function cleanDataType(dataTypeName, query)
%
%  cleanDataType(dataTypeName, [query])
%
% Deletes:
%   Inplane/dataType/*.mat
%   Inplane/dataType/TSeries/Scan*/*.mat
%   Likewise for Volume, Gray, and Flat*
%
% If you change this function make parallel changes in:
%     cleanGray, cleanFlat
%
% djh, 2/2001
% We could remove the directory for that data type, too.  Maybe we should.
% ras, 03/07: agreed. now nukes everything in the deleted data type dir.
global HOMEDIR
if ~exist('query','var')
    query = 0;
end
if query
	q = sprintf('Completely delete data type %s?', dataTypeName);
    confirm = questdlg(q, mfilename);
else
    confirm = 'Yes';
end
if strcmp(confirm,'Yes')
    disp(['Deleting dataType: ',dataTypeName]);
    [nDirs,dirList] = countDirs(fullfile(HOMEDIR,'Flat*'));
    dirList{nDirs+1} = 'Inplane';
    dirList{nDirs+2} = 'Gray';
    dirList{nDirs+3} = 'Volume';
    for d = 1:nDirs+3
        datadir = fullfile(HOMEDIR,dirList{d},dataTypeName);
        if exist(datadir,'dir')
            if isunix
                unix(sprintf('rm -r %s', datadir))
			else
				try
					rmdir(datadir, 's');
				catch
					disp('Couldn''t remove the directory.')
				end
            end
        end
    end
end
return


function []= mdp_verbose()

% mdp_verbose   Ask for running resolution functions of the MDP Toolbox
%               in verbose mode

% MDPtoolbox: Markov Decision Processes Toolbox
% Copyright (C) 2009  INRA
% Redistribution and use in source and binary forms, with or without modification,
% are permitted provided that the following conditions are met:
%    * Redistributions of source code must retain the above copyright notice,
%      this list of conditions and the following disclaimer.
%    * Redistributions in binary form must reproduce the above copyright notice,
%      this list of conditions and the following disclaimer in the documentation
%      and/or other materials provided with the distribution.
%    * Neither the name of the <ORGANIZATION> nor the names of its contributors
%      may be used to endorse or promote products derived from this software
%      without specific prior written permission.
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
% ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
% WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
% IN NO EVENT SHALL THE COPYRIGHT 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.

global mdp_VERBOSE;

mdp_VERBOSE = 1;


%% Standard ODFs
% predefined ODFs
%%
%


 function zwhite
%function zwhite
%	in black background mode, the z axis does not show up properly
%	and this fixes it for current plot
set(gca, 'zcolor', [1 1 1])


function rts_propUpdateFunc(~, ~, hFig, tcpipClientRes, tcpipClientMainEng, tcpipClientRcsEng, hResUITable1, hResSumProgBar1, hResUITable2, hResSumProgBar2, hResourceCombo1, hResourceCombo2, hMainEngineUITable, hRcsEngineUITable)
%rts_propUpdateFunc Summary of this function goes here
%   Detailed explanation goes here

    try
        data = get(tcpipClientRes,'UserData');
        resources = getResourcesStruct(data{1}, 3);

        if(~isempty(resources))
            %UPDATE RESOURSE COMBOBOX 1
            if(~isempty(hResourceCombo1))
                updateResComboKeepSelection(hResourceCombo1, resources);
            end

            %UPDATE RESOURSE COMBOBOX 2
            if(~isempty(hResourceCombo2))
                updateResComboKeepSelection(hResourceCombo2, resources);
            end

            %UPDATE RESOURCE TABLE 1
            resource = getResourceNameFromCombo(hResourceCombo1);
            if(~isempty(hResUITable1) && ~isempty(hResSumProgBar1) && isfield(resources, resource))
                generateResourceStorageTable(hResUITable1, resources.(resource));
                [progBar1Str,percent] = generateResourceSummaryStr(resources, resource);
                hResSumProgBar1.setValue(percent);
                hResSumProgBar1.setString(progBar1Str);
                hResSumProgBar1.setStringPainted(true);
            end

            %UPDATE RESOURCE TABLE 2
            resource = getResourceNameFromCombo(hResourceCombo2);
            if(~isempty(hResUITable2) && ~isempty(hResSumProgBar2) && isfield(resources, resource))
                generateResourceStorageTable(hResUITable2, resources.(resource));
                [progBar2Str,percent] = generateResourceSummaryStr(resources, resource);
                hResSumProgBar2.setValue(percent);
                hResSumProgBar2.setString(progBar2Str);
                hResSumProgBar2.setStringPainted(true);
            end
        end

        %UPDATE MAIN ENGINE TABLE
        data = get(tcpipClientMainEng,'UserData');
        r = readPartStrAndDblsFromDblArr(data{1}, 6);
        if(~isempty(r))
            if(~isempty(hMainEngineUITable))
                generateMainEngineStatusTable(hMainEngineUITable, r);
            end
        end

        %UPDATE RCS ENGINE TABLE
        data = get(tcpipClientRcsEng,'UserData');
        r = readPartStrAndDblsFromDblArr(data{1}, 3);
        if(~isempty(r))
            if(~isempty(hRcsEngineUITable))
                generateRCSEngineStatusTable(hRcsEngineUITable, r);
            end
        end

    catch ME
%         disp('----');
%         disp(ME.message);
%         disp(ME.stack(1));
%         disp(ME.stack(2));
%         disp('----');
    end

end

function generateRCSEngineStatusTable(hRcsEngineUITable, tData)
    tableData = {};
    for(i=1:size(tData,1))
        row = tData(i,:);
        split = strsplit(row{1}, '/_/_/');

        tableData{i,1} = split{1};
        tableData{i,2} = row{2};
        tableData{i,3} = row{3};
        tableData{i,4} = row{4};
    end

    setTableData(hRcsEngineUITable, tableData);
end

function generateMainEngineStatusTable(hMainEngineUITable, tData)
    tableData = {};
    for(i=1:size(tData,1))
        row = tData(i,:);
        split = strsplit(row{1}, '/_/_/');

        tableData{i,1} = split{1};
        tableData{i,2} = row{2}*100;
        tableData{i,3} = row{3};
        tableData{i,4} = row{4};
        tableData{i,5} = row{5};
    end

    setTableData(hMainEngineUITable, tableData);
end

function str = getResourceNameFromCombo(hResourceCombo)
    contents = cellstr(get(hResourceCombo,'String'));
    str = contents{get(hResourceCombo,'Value')};
end

function updateResComboKeepSelection(hResourceCombo, resources)
    contents = cellstr(get(hResourceCombo,'String'));
    if(get(hResourceCombo,'Value') <= length(contents))
        sel = contents{get(hResourceCombo,'Value')};
    else
        sel = '';
    end

    res = sort(fieldnames(resources));
    if(~isempty(res))
        set(hResourceCombo,'String', res);
        ind=find(ismember(res,sel));
    else
        return;
    end

    if(isempty(ind) || ind<=0)
        value = 1;
    else
        value = ind;
    end

    set(hResourceCombo,'Value', value);
end

function [str,percent] = generateResourceSummaryStr(resources, resource)
    [current, max] = getCurrentMaxResource(resources, resource);

    percent = uint32(round(100*(current/max)));
    resStr = cap1stLetter(resource);

    strT = ['Total ', resStr ,' = ',num2str(current),' / ',num2str(max)];
    str = java.lang.String(strT);
end

function generateResourceStorageTable(hResUITable, resArr)
    tableData = {};
    for(i=1:size(resArr,1))
        if(resArr{i,6} == 1)
            connected = 'True';
        else
            connected = 'False';
        end

        tableData{i,1} = resArr{i,2};
        tableData{i,2} = connected;
        tableData{i,3} = resArr{i,4};
        tableData{i,4} = resArr{i,5};
    end

    setTableData(hResUITable, tableData);
end


function d =  testing(a,d)

  eval([a.func ';']);
  d=set_name(d,[get_name(d) ' -> ' get_name(a)]);


classdef FileLoadSaveClass < matlab.mixin.Copyable

    properties (Access = private)
        filename;
        fileformat;
        supportedFomats;
        err;
        dataStorageScheme;
    end

    methods

        % ----------------------------------------------------------------------------------
        function obj = FileLoadSaveClass()
            obj.filename = '';
            obj.fileformat = '';
            obj.supportedFomats = struct( ...
                'matlab', {{'.mat','matlab','mat'}}, ...
                'hdf5', {{'hdf','.hdf','hdf5','.hdf5','hf5','.hf5','h5','.h5'}} ...
                );
            obj.err = 0;
            obj.dataStorageScheme = 'memory';
        end

        % ---------------------------------------------------------
        function Load(obj, filename, params, format)
            if ~exist('filename','var')
                filename = obj.filename;
            end
            if ~exist('format','var')
                format = obj.fileformat;
            elseif obj.Supported(format)
                obj.fileformat = format;
            end
            if ~exist('params','var')
                params = [];
            end

            switch(lower(format))
                case obj.supportedFomats.matlab
                    if ismethod(obj, 'LoadMat')
                        obj.err = obj.LoadMat(filename, params);
                    end
                case obj.supportedFomats.hdf5
                    if ismethod(obj, 'LoadHdf5')
                        obj.err = obj.LoadHdf5(filename, params);
                    end
            end
        end

        % ---------------------------------------------------------
        function Save(obj, filename, params, format)
            if ~exist('filename','var')
                filename = obj.filename;
            end
            if ~exist('params','var')
                params = [];
            end
            if ~exist('format','var')
                format = obj.fileformat;
            end

            switch(lower(format))
                case obj.supportedFomats.matlab
                    if ismethod(obj, 'SaveMat')
                        obj.SaveMat(filename, params);
                    end
                case obj.supportedFomats.hdf5
                    if ismethod(obj, 'SaveHdf5')
                        obj.SaveHdf5(filename, params);
                    end
            end
        end

        % ---------------------------------------------------------
        function b = Supported(obj, format)
            b = true;
            switch(lower(format))
                case obj.supportedFomats.matlab
                    return;
                case obj.supportedFomats.hdf5
                    return;
            end
            b = false;
        end

        % -------------------------------------------------------
        function B = ne(obj, obj2)
            if obj==obj2
                B = false;
            else
                B = true;
            end
        end

        % -------------------------------------------------------
        function SetFileFormat(obj, fmt)
            obj.fileformat = fmt;
        end

        % -------------------------------------------------------
        function fmt = GetFileFormat(obj)
            fmt = obj.fileformat;
        end

        % -------------------------------------------------------
        function SetFilename(obj, fname)
            obj.filename = fname;
        end

        % -------------------------------------------------------
        function fname = GetFilename(obj)
            fname = obj.filename;
        end

        % -------------------------------------------------------
        function SetDataStorageScheme(obj, scheme)
            obj.dataStorageScheme = scheme;
        end

        % -------------------------------------------------------
        function scheme = GetDataStorageScheme(obj)
            scheme = obj.dataStorageScheme;
        end

        % -------------------------------------------------------
        function SetError(obj, err)
            obj.err = err;
        end

        % -------------------------------------------------------
        function err = GetError(obj)
            err = [];
            if isempty(obj)
                return
            end
            err = obj.err;
        end

        % -------------------------------------------------------
        function supportedFomats = GetSupportedFormats(obj)
            supportedFomats = obj.supportedFomats;
        end

    end

end


%% The Class vector3d
%
%%
%


min_cost_0_1000 = min_cost_0;
min_cost_1_1000 = min_cost_1;
min_cost_2_1000 = min_cost_2;
min_cost_3_1000 = min_cost_3;
min_cost_4_1000 = min_cost_4;
min_cost_5_1000 = min_cost_5;
min_cost_6_1000 = min_cost_6;

totalNum_0_1000 = totalNum_0;
totalNum_1_1000 = totalNum_1;
totalNum_2_1000 = totalNum_2;
totalNum_3_1000 = totalNum_3;
totalNum_4_1000 = totalNum_4;
totalNum_5_1000 = totalNum_5;
totalNum_6_1000 = totalNum_6;


function [root] = bsdsRoot()
% function [root] = bsdsRoot()
%
% Return the root directory for the BSDS data.
%
% David R. Martin <dmartin@eecs.berkeley.edu>
% March 2003

root = '/home/cs/dmartin/public_html/segbench/BSDS300';


classdef SettingsFilterP0 < AbstractSettings
    properties
        shape
        conec
        quadr
    end
    methods
    end
end


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

% Last Modified by GUIDE v2.5 20-Jan-2019 16:22:40

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @ma_InsertAerobrake_OpeningFcn, ...
                   'gui_OutputFcn',  @ma_InsertAerobrake_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 ma_InsertAerobrake is made visible.
function ma_InsertAerobrake_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 ma_InsertAerobrake (see VARARGIN)

% Choose default command line output for ma_InsertAerobrake
handles.output = hObject;
handles.ma_MainGUI = varargin{1};

% Update handles structure
guidata(hObject, handles);

if(length(varargin)>1)
    event = varargin{2};
    populateGUIWithEvent(handles, event);
end

dragModelCombo_Callback(handles.dragModelCombo, [], handles);

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

function populateGUIWithEvent(handles, event)
    set(handles.titleLabel, 'String', 'Edit Aerobrake');
    set(handles.ma_InsertAerobrakeGUI, 'Name', 'Edit Aerobrake');
    set(handles.nameText, 'String', event.name);

    set(handles.dragCoeffText,'String', num2str(event.dragCoeff,10));

    colorStr = getStringFromLineSpecColor(event.lineColor);
    colorValue = findValueFromComboBox(colorStr, handles.lineColorCombo);
    set(handles.lineColorCombo,'value',colorValue);

    styleStr = getLineStyleFromString(event.lineStyle);
    styleValue = findValueFromComboBox(styleStr, handles.aerobrakeLineStyleCombo);
 	set(handles.aerobrakeLineStyleCombo,'Value',styleValue);

    contents = handles.lineWidthCombo.String;
    contentsDouble = str2double(contents);
    ind = find(contentsDouble == event.lineWidth);
    set(handles.lineWidthCombo,'Value',ind);

    if(~isfield(event,'dragModel'))
        event.dragModel = 'Stock';
    end
    value = findValueFromComboBox(event.dragModel, handles.dragModelCombo);
    set(handles.dragModelCombo,'Value',value);

% --- Outputs from this function are returned to the command line.
function varargout = ma_InsertAerobrake_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
    if(isempty(handles))
        varargout{1} = [];
    else
        name = get(handles.nameText,'String');
        dragCoeff = str2double(get(handles.dragCoeffText,'String'));

        contents = cellstr(get(handles.dragModelCombo,'String'));
        dragModel = contents{get(handles.dragModelCombo,'Value')};

        contents = cellstr(get(handles.lineColorCombo,'String'));
        colorStr = contents{get(handles.lineColorCombo,'Value')};
        lineSpecColor = getLineSpecColorFromString(colorStr);

        contents = cellstr(get(handles.aerobrakeLineStyleCombo,'String'));
        lineStyleStr = contents{get(handles.aerobrakeLineStyleCombo,'Value')};
        lineStyle = getLineStyleStrFromText(lineStyleStr);

        contents = handles.lineWidthCombo.String;
        contentsDouble = str2double(contents);
        contensInd = get(handles.lineWidthCombo,'Value');
        lineWidth = contentsDouble(contensInd);

        varargout{1} = ma_createAerobrake(name, dragCoeff, dragModel, lineSpecColor, lineStyle, lineWidth);
        close(handles.ma_InsertAerobrakeGUI);
    end

% --- Executes on button press in saveAndCloseButton.
function saveAndCloseButton_Callback(hObject, eventdata, handles)
% hObject    handle to saveAndCloseButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    errMsg = validateInputs(handles);

    if(isempty(errMsg))
        uiresume(handles.ma_InsertAerobrakeGUI);
    else
        msgbox(errMsg,'Errors were found while inserting an aerobrake.','error');
    end

function errMsg = validateInputs(handles)
    errMsg = {};

    dragCoeff = str2double(get(handles.dragCoeffText,'String'));
    enteredStr = get(handles.dragCoeffText,'String');
    numberName = 'Drag Coefficient';
    lb = 0;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(dragCoeff, numberName, lb, ub, isInt, errMsg, enteredStr);

% --- Executes on button press in cancelButton.
function cancelButton_Callback(hObject, eventdata, handles)
% hObject    handle to cancelButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    close(handles.ma_InsertAerobrakeGUI);

function nameText_Callback(hObject, eventdata, handles)
% hObject    handle to nameText (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of nameText as text
%        str2double(get(hObject,'String')) returns contents of nameText as a double

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

% Hint: edit 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

function dragCoeffText_Callback(hObject, eventdata, handles)
% hObject    handle to dragCoeffText (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of dragCoeffText as text
%        str2double(get(hObject,'String')) returns contents of dragCoeffText as a double
newInput = get(hObject,'String');
newInput = attemptStrEval(newInput);
set(hObject,'String', newInput);

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

% Hint: edit 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

% --- Executes on key press with focus on ma_InsertAerobrakeGUI or any of its controls.
function ma_InsertAerobrakeGUI_WindowKeyPressFcn(hObject, eventdata, handles)
% hObject    handle to ma_InsertAerobrakeGUI (see GCBO)
% eventdata  structure with the following fields (see FIGURE)
%	Key: name of the key that was pressed, in lower case
%	Character: character interpretation of the key(s) that was pressed
%	Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed
% handles    structure with handles and user data (see GUIDATA)
    switch(eventdata.Key)
        case 'return'
            saveAndCloseButton_Callback(handles.saveAndCloseButton, [], handles);
        case 'enter'
            saveAndCloseButton_Callback(handles.saveAndCloseButton, [], handles);
        case 'escape'
            close(handles.ma_InsertAerobrakeGUI);
    end

% --- Executes on button press in openCdCalcButton.
function openCdCalcButton_Callback(hObject, eventdata, handles)
% hObject    handle to openCdCalcButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    ma_AerobrakingCdCalcGUI(handles.ma_MainGUI);

% --- Executes on selection change in dragModelCombo.
function dragModelCombo_Callback(hObject, eventdata, handles)
% hObject    handle to dragModelCombo (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 dragModelCombo contents as cell array
%        contents{get(hObject,'Value')} returns selected item from dragModelCombo
    contents = cellstr(get(hObject,'String'));
    dragModel = contents{get(hObject,'Value')};

    switch(dragModel)
        case 'Stock'
%             set(handles.cdLabel,'String','');
            set(handles.cdLabel,'String','m^2');
        case 'FAR'
            set(handles.cdLabel,'String','m^2');
        case 'NEAR'
            set(handles.cdLabel,'String','m^2');
    end

% --- Executes during object creation, after setting all properties.
function dragModelCombo_CreateFcn(hObject, eventdata, handles)
% hObject    handle to dragModelCombo (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

% --- Executes on selection change in lineColorCombo.
function lineColorCombo_Callback(hObject, eventdata, handles)
% hObject    handle to lineColorCombo (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 lineColorCombo contents as cell array
%        contents{get(hObject,'Value')} returns selected item from lineColorCombo

% --- Executes during object creation, after setting all properties.
function lineColorCombo_CreateFcn(hObject, eventdata, handles)
% hObject    handle to lineColorCombo (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

% --- Executes on selection change in aerobrakeLineStyleCombo.
function aerobrakeLineStyleCombo_Callback(hObject, eventdata, handles)
% hObject    handle to aerobrakeLineStyleCombo (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 aerobrakeLineStyleCombo contents as cell array
%        contents{get(hObject,'Value')} returns selected item from aerobrakeLineStyleCombo

% --- Executes during object creation, after setting all properties.
function aerobrakeLineStyleCombo_CreateFcn(hObject, eventdata, handles)
% hObject    handle to aerobrakeLineStyleCombo (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

% --- Executes on selection change in lineWidthCombo.
function lineWidthCombo_Callback(hObject, eventdata, handles)
% hObject    handle to lineWidthCombo (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 lineWidthCombo contents as cell array
%        contents{get(hObject,'Value')} returns selected item from lineWidthCombo

% --- Executes during object creation, after setting all properties.
function lineWidthCombo_CreateFcn(hObject, eventdata, handles)
% hObject    handle to lineWidthCombo (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


% GETTEXT - This function prints a dialog box on screen and waits for
%             the user to enter a string. There is a cancel button which
%             returns a value of [].
% Usage:
%   >> out = gettext(label1,label2,...,label7);
%
% Author: Colin Humphries, CNL / Salk Institute, La Jolla, 1997

% Copyright (C) 1997 Colin Humphries, Salk Institute
%
% This file is part of EEGLAB, see http://www.eeglab.org
% for the documentation and details.
%
% 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 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 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.

% 01-25-02 reformated help & license -ad

function out = gettext(label1,label2,label3,label4,label5,label6,label7);

global is_text_entered
is_text_entered = 0;

for i = 1:nargin
   eval(['leng(i) = length(label',num2str(i),');'])
end
figurelength = 15*1.0*max(leng);

if figurelength < 240
   figurelength = 290;
end

figureheight = 80+nargin*18;
% Set figure

figure('Position',[302 396 figurelength figureheight],'color',[.6 .6 .6],'NumberTitle','off')
f1 = gcf;

ax = axes('Units','Pixels','Position',[0 0 figurelength figureheight],'Visible','off','XLim',[0 figurelength],'YLim',[0 figureheight]);

for i = 1:nargin

   eval(['text(figurelength/2,',num2str(figureheight-(i-1)*18-20),',label',num2str(i),',''color'',''k'',''FontSize'',16,''HorizontalAlignment'',''center'')'])

end
% Set up uicontrols

TIMESTRING = ['global is_text_entered;is_text_entered = 1;clear is_text_entered'];

u = uicontrol('Style','Edit','Units','Pixels','Position',[15 20 figurelength-95 25],'HorizontalAlignment','left','Callback',TIMESTRING);

TIMESTRING = ['global is_text_entered;is_text_entered = 2;clear is_text_entered'];
v = uicontrol('Style','Pushbutton','Units','Pixels','Position',[figurelength-70 20 55 25],'String','Cancel','Callback',TIMESTRING);

while(is_text_entered == 0)
   drawnow
end

if is_text_entered == 1
   out = get(u,'string');
else
   out = [];
end

clear is_text_entered
delete(f1)


classdef MimSetWLTool < MimGuiPlugin
    % MimSetWLTool. Gui Plugin for using a preset bone window/level
    %
    %     You should not use this class within your own code. It is intended to
    %     be used by the gui of the TD MIM Toolkit.
    %
    %     MimSetWLTool 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 = 'Window / Level'
        SelectedText = 'Window / Level'
        ToolTip = 'Adjust window and level by dragging mouse over image'
        Category = 'Tools'
        Visibility = 'Dataset'
        Mode = 'Toolbar'

        HidePluginInDisplay = false
        PTKVersion = '1'
        ButtonWidth = 6
        ButtonHeight = 1
        Icon = 'windowlevel.png'
        Location = 12
    end

    methods (Static)
        function RunGuiPlugin(gui_app)
            if strcmp(gui_app.ImagePanel.Mode, MimModes.View3DMode)
                gui_app.ChangeMode([]);
            end
            gui_app.ImagePanel.SetControl('W/L');
        end

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

        function is_selected = IsSelected(gui_app)
            is_selected = strcmp(gui_app.ImagePanel.SelectedControl, 'W/L');
        end

    end
end


%function [path, filename] = splitpath(str)
function [path, filename] = splitpath(str)
  slashidx = strfind(str, '/');

  if isempty(slashidx)
    path = [];
    filename = str;
  else
    path = str(1:slashidx(end)-1);
    filename = str(slashidx(end)+1:end);
  end

end


function el = export_gsps_module_field(args)
%"export_gsps_module_field"
%   Given a single planC.structures struct and a tag in the ROI_contour
%   module, return a properly populated and formatted instance of
%   that tag.
%
%   For speed, tag must be a decimal representation of the 8 digit
%   hexidecimal DICOM tag desired, ie instead of '00100010', pass
%   hex2dec('00100010');
%
%   Arguments are passed in a structure, arg:
%       arg.tag         = decimal tag of field to fill
%       arg.data        = CERR structure(s) to fill from
%       arg.template    = an empty template of the module created by the
%                         function build_module_template.m
%
%   This function requires arg.data is a planC.structures.
%
%JRA 06/19/06
%NAV 07/19/16 updated to dcm4che3
%
%Usage:
%   dcmobj = export_roi_contour_module_field(args)
%
% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.
%
% This file is part of The Computational Environment for Radiotherapy Research (CERR).
%
% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.
%
% CERR has been financially supported by the US National Institutes of Health under multiple grants.
%
% CERR is distributed under the terms of the Lesser GNU Public License.
%
%     This version of CERR 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.
%
% CERR 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 CERR.  If not, see <http://www.gnu.org/licenses/>.

%Init output element to empty.
el = [];

%Unpack input data.
tag         = args.tag;
gspsS       = args.data{1};
scanS       = args.data{2};
template    = args.template;

switch tag
    %Class 1 Tags -- Required, must have data.
    case  7340162  %0070,0082 Presentation Creation Date
        data = datestr(now,'yyyymmdd');
        el = data2dcmElement(data, tag);

    case  7340163   % 0070,0083 Presentation Creation Time
        data = datestr(now,'hhmmss');
        el = data2dcmElement(data, tag);

    case 542113824  % 2050,0020  Presentation LUT Shape
        data = 'IDENTITY'; % or 'INVERSE'
        el = data2dcmElement(data, tag);

    case 7340122  % 0070,005A  Displayed Area Selection Sequence
        templateEl  = template.getValue(tag);
        fHandle = @export_displayed_area_selection_sequence;

        %New null sequence
        tmp = javaObject('org.dcm4che3.data.Attributes');
        el = tmp.newSequence(tag, 0);

        % Only one item since all images use the displayed area selection
        % Might need to add additional items when generating annotations
        % belonging to different series.

        % for i=1:length(gspsS)
        i = 1; % only one item
        dcmobj = export_sequence(fHandle, templateEl, {gspsS,scanS});
        el.add(i-1, dcmobj);
        % end
        %get attribute to return
        el = el.getParent();

    case 528661   % 0008,1115  Referenced Series Sequence
        templateEl  = template.getValue(tag);
        fHandle = @export_referenced_series_sequence;

        %New null sequence
        tmp = javaObject('org.dcm4che3.data.Attributes');
        el = tmp.newSequence(tag, 0);

        % Only one item since all images use the displayed area selection
        % Might need to add additional items when generating annotations
        % belonging to different series.

        % for i=1:length(gspsS)
        i = 1; % only one item
        dcmobj = export_sequence(fHandle, templateEl, {gspsS,scanS});
        el.add(i-1, dcmobj);
        % end
        %get attribute to return
        el = el.getParent();

    case 7340033  %0070,0001 Graphic Annotation Sequence

        templateEl  = template.getValue(tag);
        fHandle = @export_graphic_annotation_sequence;

        %New null sequence
        tmp = javaObject('org.dcm4che3.data.Attributes');
        el = tmp.newSequence(tag, 0);

        scanSopInstanceUIDc = {scanS.scanInfo.sopInstanceUID};

        for i=1:length(gspsS)
            slcNum = strncmp(gspsS(i).referenced_SOP_instance_uid,...
                scanSopInstanceUIDc,length(gspsS(i).referenced_SOP_instance_uid));
            dcmobj = export_sequence(fHandle, templateEl, {gspsS(i),scanS.scanInfo(slcNum)});
            %dcmobj = export_sequence(fHandle, tag, {structS(i), i});
            el.add(i-1, dcmobj);
        end
        %get attribute to return
        el = el.getParent();

    case 7340128   %0070,0060 Graphic Layer sequence
        templateEl  = template.getValue(tag);
        fHandle = @export_graphic_layer_sequence;

        %New null sequence
        tmp = javaObject('org.dcm4che3.data.Attributes');
        el = tmp.newSequence(tag, 0);

        [uniqLabelC,indUniqV] = unique({gspsS.presentLabel});
        numLabels = length(uniqLabelC);

        for i = 1:numLabels
            presentColor = gspsS(indUniqV(i)).presentRGBColor;
            dcmobj = export_sequence(fHandle, templateEl, {uniqLabelC{i},i,presentColor});
            el.add(i-1, dcmobj);
        end

        %get attribute to return
        el = el.getParent();

    %Class 2 Tags -- Must be present, can be NULL.
    %Class 3 Tags -- presence is optional, currently undefined.
    %Class 1C Tags -- presence is required under special circumstances
    %Class 2C Tags -- presence is required under special circumstances

    otherwise
        warning(['No methods exist to populate DICOM GSPS module field ' dec2hex(tag,8) '.']);
end


% Set Program Path
function	set_dir

%root_dir = getenv('MFILE');
%prog_dir = [root_dir '/VBtool/prediction'];
prog_dir = pwd;

addpath([prog_dir]);
addpath([prog_dir '/test']);
addpath([prog_dir '/basic_func']);
addpath([prog_dir '/../mex_prog']);


%  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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
function kayttht
%KAYTTHT Unit test for function KAYTTH.

%	O. Lemoine - August 1996.


function planMergeGui(command, varargin)
%"planMergeGui"
%   Raises a GUI to merge two plans together, usually for the purpose of
%   fusion.
%
%JRA 2/28/04
% copyright (c) 2001-2006, Washington University in St. Louis.
% Permission is granted to use or modify only for non-commercial,
% non-treatment-decision applications, and further only if this header is
% not removed from any file. No warranty is expressed or implied for any
% use whatever: use at your own risk.  Users can request use of CERR for
% institutional review board-approved protocols.  Commercial users can
% request a license.  Contact Joe Deasy for more information
% (radonc.wustl.edu@jdeasy, reversed).
%
%Usage:
%   Access through the CERR Gui, OR
%   load a plan and type: planMergeGui('init');

global stateS

if nargin == 0
    command = 'INIT';
end

%Find old planMerge figures.
hFig = findobj('Tag', 'CERR_PlanMergeGui');

if isempty(hFig) && ~strcmpi(command, 'init')
    warning('planMergeGui was not initialized.  Initializing now.');
    command = 'init';
end

switch upper(command)
    case 'INIT'
        %Wipe out old plan merge figures;
        if ~isempty(hFig)
            delete(hFig);
        end

        screenSize = get(0,'ScreenSize');
        units = 'pixels';
        y = 520;
        x = 520;

        %dx for each of 2 columns.
        dx = floor((x-30)/2);

        %Create figure and UI controls.
        hFig = figure('Name','Plan Merge', 'units', 'pixels', ...
            'position',[(screenSize(3)-x)/2 (screenSize(4)-y)/2 x y], ...
            'MenuBar', 'none', 'NumberTitle', 'off', 'resize', 'off',...
            'Tag', 'CERR_PlanMergeGui','CloseRequestFcn','planMergeGui(''QUIT'')');

        %Status frame.
        bartop = 40;
        statusFrame             = uicontrol(hFig, 'units',units,'Position',[10 10 x-20 30], 'style', 'frame');
        frameColor              = get(statusFrame, 'BackgroundColor');
        statusLabel             = uicontrol(hFig, 'units',units,'Position',[10 25 65 15], 'style', 'text', 'String', 'Status', 'fontweight', 'bold');
        ud.handles.statusBar    = uicontrol(hFig, 'units',units,'Position',[70 14 2*dx-165 18], 'style', 'text', 'string', 'Ready.', 'enable', 'inactive', 'backgroundcolor', frameColor, 'horizontalAlignment', 'right');

        %Load plan frame and label.
        loadbot = y-65-10;
        uicontrol(hFig, 'units',units,'Position',[10 loadbot dx*2+10 65], 'style', 'frame');
        uicontrol(hFig, 'units',units,'Position',[10 loadbot+65-15 100 15], 'style', 'text', 'String', 'Select Plan', 'fontweight', 'bold', 'backgroundcolor', frameColor);

        %Doses frame and label.
        dy = floor((loadbot-bartop-30)/2);
        uicontrol(hFig, 'units',units,'Position',[10 bartop+10 dx dy], 'style', 'frame');
        uicontrol(hFig, 'units',units,'Position',[10 bartop+10+dy-15 65 15], 'style', 'text', 'String', 'Doses', 'fontweight', 'bold', 'backgroundcolor', frameColor);

        %Scans frame and label.
        uicontrol(hFig, 'units',units,'Position',[10 bartop+20+dy dx dy], 'style', 'frame');
        uicontrol(hFig, 'units',units,'Position',[10 bartop+20+2*dy-15 65 15], 'style', 'text', 'String', 'Scans', 'fontweight', 'bold', 'backgroundcolor', frameColor);

        %Structures frame and label
        uicontrol(hFig, 'units',units,'Position',[dx+20 bartop+10 dx 2*dy+10], 'style', 'frame');
        uicontrol(hFig, 'units',units,'Position',[dx+20 bartop+20+2*dy-15 90 15], 'style', 'text', 'String', 'Structures', 'fontweight', 'bold', 'backgroundcolor', frameColor);

        ud.handles.dosesSlider   = uicontrol(hFig, 'units',units,'Position',[dx-15 bartop+10+5 20 dy-10], 'style', 'slider', 'enable', 'off');
        ud.handles.scansSlider   = uicontrol(hFig, 'units',units,'Position',[dx-15 bartop+20+5+dy 20 dy-10], 'style', 'slider', 'enable', 'off', 'tag','scanSlider','callback','scanSlider_clk(''clicked'')');
        ud.handles.structsSlider = uicontrol(hFig, 'units',units,'Position',[2*dx-5 bartop+10+5 20 2*dy], 'style', 'slider', 'enable', 'off','tag','structSlider','callback','structSlider_clk(''clicked'')');

        ud.handles.Browse       = uicontrol(hFig, 'units',units, 'Position',[20  loadbot+10 dx/2-15 25], 'style', 'pushbutton', 'string', 'Browse...', 'callback', 'planMergeGui(''BROWSE'')');
        ud.handles.filenameText = uicontrol(hFig, 'units',units, 'Position',[130 loadbot+5 375 25], 'fontsize', 8, 'style', 'text', 'string', {'Click Browse to find a plan to merge with the plan currently loaded in CERR.'}, 'backgroundcolor', frameColor);
        ud.handles.pathText     = uicontrol(hFig, 'units',units, 'Position',[130 loadbot+30 375 25], 'fontsize', 8, 'style', 'text', 'string', {''}, 'backgroundcolor', frameColor);

        %Create scan UIControls.
        uicontrol(hFig, 'units',units,'Position',[12 bartop+10+2*dy-25 12 15], 'style', 'text', 'String', '#', 'backgroundcolor', frameColor);
        uicontrol(hFig, 'units',units,'Position',[25 bartop+10+2*dy-25 80 15], 'style', 'text', 'String', 'Modality', 'backgroundcolor', frameColor);
        uicontrol(hFig, 'units',units,'Position',[120 bartop+10+2*dy-25 60 15], 'style', 'text', 'String', 'Size', 'backgroundcolor', frameColor);
        uicontrol(hFig, 'units',units,'Position',[180 bartop+10+2*dy-25 50 15], 'style', 'text', 'String', 'Merge?', 'backgroundcolor', frameColor);

        uicontrol(hFig, 'units',units,'Position',[15 bartop+10+2*dy-45 80 15], 'style', 'text', 'String', 'ALL', 'backgroundcolor', frameColor, 'fontweight', 'bold');
        uicontrol(hFig, 'units',units,'Position',[100 bartop+10+2*dy-45 60 15], 'style', 'text', 'String', '', 'backgroundcolor', frameColor);
        ud.handles.scanALLCheck = uicontrol(hFig, 'units',units,'Position',[200 bartop+10+2*dy-45 25 15], 'style', 'checkbox', 'backgroundcolor', frameColor, 'horizontalAlignment', 'center', 'callback', 'planMergeGui(''ALLCHECK'')', 'tag', 'scan', 'enable', 'off');

        numRows = 6;
        for i=1:numRows
            ud.handles.scanNumber(i)  = uicontrol(hFig, 'units',units,'Position',[12 bartop+10+2*dy-45-i*20 20 15], 'style', 'text', 'String', '1', 'backgroundcolor', frameColor, 'visible', 'off');
            ud.handles.scanName(i)    = uicontrol(hFig, 'units',units,'Position',[30 bartop+10+2*dy-45-i*20 90 15], 'style', 'text', 'String', 'CT Scan', 'backgroundcolor', frameColor, 'visible', 'off');
            ud.handles.scanSize(i)    = uicontrol(hFig, 'units',units,'Position',[125 bartop+10+2*dy-45-i*20 60 15], 'style', 'text', 'String', '100', 'backgroundcolor', frameColor, 'visible', 'off');
            ud.handles.scanCheck(i)   = uicontrol(hFig, 'units',units,'Position',[200 bartop+10+2*dy-45-i*20 25 15], 'style', 'checkbox', 'backgroundcolor', frameColor, 'horizontalAlignment', 'center', 'userdata', i, 'Tag', 'ScanCheck', 'callback', 'planMergeGui(''Check'')', 'visible', 'off');
        end
        ud.numScanRows = numRows;

        %Create dose UICONTROLS.
        uicontrol(hFig, 'units',units,'Position',[15 bartop+dy-25 80 15], 'style', 'text', 'String', 'Name', 'backgroundcolor', frameColor);
        uicontrol(hFig, 'units',units,'Position',[100 bartop+dy-25 60 15], 'style', 'text', 'String', 'Size', 'backgroundcolor', frameColor);
        uicontrol(hFig, 'units',units,'Position',[165 bartop+dy-25 60 15], 'style', 'text', 'String', 'Merge?', 'backgroundcolor', frameColor);

        uicontrol(hFig, 'units',units,'Position',[15 bartop+dy-45 80 15], 'style', 'text', 'String', 'ALL', 'backgroundcolor', frameColor, 'fontweight', 'bold');
        uicontrol(hFig, 'units',units,'Position',[100 bartop+dy-45 60 15], 'style', 'text', 'String', '', 'backgroundcolor', frameColor);
        ud.handles.doseALLCheck = uicontrol(hFig, 'units',units,'Position',[185 bartop+dy-45 25 15], 'style', 'checkbox', 'backgroundcolor', frameColor, 'horizontalAlignment', 'center', 'callback', 'planMergeGui(''ALLCHECK'')', 'tag', 'dose', 'enable', 'off');

        numRows = 6;
        for i=1:numRows
            ud.handles.doseName(i)  = uicontrol(hFig, 'units',units,'Position',[15 bartop+dy-45-i*20 80 15], 'style', 'text', 'String', 'CT Scan', 'backgroundcolor', frameColor, 'visible', 'off');
            ud.handles.doseSize(i)  = uicontrol(hFig, 'units',units,'Position',[100 bartop+dy-45-i*20 60 15], 'style', 'text', 'String', '100', 'backgroundcolor', frameColor, 'visible', 'off');
            ud.handles.doseCheck(i) = uicontrol(hFig, 'units',units,'Position',[185 bartop+dy-45-i*20 25 15], 'style', 'checkbox', 'backgroundcolor', frameColor, 'horizontalAlignment', 'center', 'userdata', i, 'Tag', 'DoseCheck', 'callback', 'planMergeGui(''Check'')', 'visible', 'off');
        end
        ud.numDoseRows = numRows;

        %Create struct UICONTROLS.
        uicontrol(hFig, 'units',units,'Position',[dx+10+15 loadbot-46 80 15], 'style', 'text', 'String', 'Name', 'backgroundcolor', frameColor);
        uicontrol(hFig, 'units',units,'Position',[dx+10+100 loadbot-46 60 15], 'style', 'text', 'String', 'AssocScan', 'backgroundcolor', frameColor);
        uicontrol(hFig, 'units',units,'Position',[dx+10+165 loadbot-46 60 15], 'style', 'text', 'String', 'Merge?', 'backgroundcolor', frameColor);

        uicontrol(hFig, 'units',units,'Position',[dx+10+15 loadbot-66 80 15], 'style', 'text', 'String', 'ALL', 'backgroundcolor', frameColor,'fontweight', 'bold');
        uicontrol(hFig, 'units',units,'Position',[dx+10+100 loadbot-66 60 15], 'style', 'text', 'String', '', 'backgroundcolor', frameColor);
        ud.handles.strALLCheck = uicontrol(hFig, 'units',units,'Position',[dx+10+185 loadbot-66 25 15], 'style', 'checkbox', 'backgroundcolor', frameColor, 'horizontalAlignment', 'center', 'callback', 'planMergeGui(''ALLCHECK'')', 'tag', 'struct', 'enable', 'off');

        numRows = 16;
        for i=1:numRows
            ud.handles.strName(i)  = uicontrol(hFig, 'units',units,'Position',[dx+10+15 loadbot-66-i*20 80 15], 'style', 'text', 'String', 'CT Scan', 'backgroundcolor', frameColor, 'visible', 'off');
            ud.handles.strScan(i)  = uicontrol(hFig, 'units',units,'Position',[dx+10+100 loadbot-66-i*20 60 15], 'style', 'text', 'String', '1', 'backgroundcolor', frameColor, 'visible', 'off');
            ud.handles.strCheck(i) = uicontrol(hFig, 'units',units,'Position',[dx+10+185 loadbot-66-i*20 25 15], 'style', 'checkbox', 'backgroundcolor', frameColor, 'horizontalAlignment', 'center', 'userdata', i, 'Tag', 'StructCheck', 'callback', 'planMergeGui(''Check'')', 'visible', 'off');
        end
        ud.numStructRows = numRows;

        ud.firstVisStruct   = 1;
        ud.firstVisScan     = 1;
        ud.firstVisDose     = 1;

        ud.handles.merge = uicontrol(hFig, 'units',units, 'Position', [2*dx-85 14 100 20], 'style', 'pushbutton', 'string', 'Merge', 'callback', 'planMergeGui(''MERGE'')', 'enable', 'off');
%         uicontrol(hFig, 'units',units, 'Position', [2*dx-100 20 dx/2-15 20], 'style', 'pushbutton', 'string', 'Cancel', 'callback', 'planMergeGui(''CANCEL'')');
%
        set(hFig, 'userdata', ud);

        stateS.handle.planMergeGui = hFig;

    case 'STATUS'
        ud = get(hFig, 'userdata');
        statusString = varargin{1};
        set(ud.handles.statusBar, 'string', statusString);
        drawnow;

    case 'CANCEL'
        close(hFig);

    case 'BROWSE'
        ud = get(hFig, 'userdata');
        [fname, pathname] = uigetfile({'*.mat;*.mat.bz2', 'CERR Plans (*.mat, *.mat.bz2)';'*.*', 'All Files (*.*)'}, 'Select CERR .mat .mat.bzip2 archive to merge.');

        if fname == 0
            return;
        else
            set(ud.handles.pathText, 'string', pathname);
            set(ud.handles.filenameText, 'string', fname, 'userdata', fullfile(pathname, fname));
        end

        planMergeGui('STATUS', 'Loading selected plan and analyzing its contents...');
        planMergeGui('LOADPLAN');

    case 'LOADPLAN'
        hFig = get(gcbo, 'parent');
        ud = get(hFig, 'userdata');
        fullName = get(ud.handles.filenameText, 'userdata');

        %Get temporary directory to extract uncompress
        optS = stateS.optS;
        if isempty(optS.tmpDecompressDir)
            tmpExtractDir = tempdir;
        elseif isfolder(optS.tmpDecompressDir)
            tmpExtractDir = optS.tmpDecompressDir;
        elseif ~isfolder(optS.tmpDecompressDir)
            error('Please specify a valid directory within CERROptions.m for optS.tmpDecompressDir')
        end

        try
            planC = loadPlanC(fullName,tmpExtractDir);
            planC = updatePlanFields(planC);
            planC = quality_assure_planC(fullName,planC);
%             indexS=planC{end};
%             for i=1:length(planC{indexS.scan}(1).scanInfo)
%                 planC{indexS.scan}(1).scanInfo(i).planDir = fullName;
%             end
        end

        if ~exist('planC','var')
            planMergeGui('status', 'UNABLE TO LOAD SPECIFIED PLAN. Try another plan.');
            return;
        end
        [planInfo, planC]= getPlanInfo(planC);
        if isempty(planInfo)
            return;
        end
        ud.planInfo = planInfo;
        setappdata(hFig, 'MERGEPLAN', planC);

        indexS = planC{end};
        nStructs = length(planC{indexS.structures});
        ud.checkedStructs = ones(nStructs, 1);
        ud.nStructs = nStructs;

        nDoses = length(planC{indexS.dose});
        ud.checkedDoses = ones(nDoses, 1);

        nScans = length(planC{indexS.scan});
        ud.checkedScans = ones(nScans, 1);

        set(ud.handles.doseALLCheck, 'enable', 'on', 'value', 1);
        set(ud.handles.scanALLCheck, 'enable', 'on', 'value', 1);
        set(ud.handles.strALLCheck, 'enable', 'on', 'value', 1);

        set(hFig, 'userdata', ud);
        planMergeGui('refresh');
        planMergeGui('STATUS', 'Plan loaded.  Select elements to merge and click MERGE button.');
        set(ud.handles.merge, 'enable', 'on')

    case 'REFRESH'
        ud = get(hFig, 'userdata');
        planInfo = ud.planInfo;

        planC = getappdata(hFig, 'MERGEPLAN');
        indexS = planC{end};

        %Refresh Struct UIelements.
        set(ud.handles.strScan,  'visible', 'off');
        set(ud.handles.strName,  'visible', 'off');
        set(ud.handles.strCheck, 'visible', 'off');
        firstVisStruct = ud.firstVisStruct;
        nStructs = length(ud.checkedStructs);

        if nStructs > 16
            hSlider = findobj('tag','structSlider');
            set(hSlider,'enable', 'on','BackgroundColor',[0 0 0]);
            set(hSlider,'min',1,'max',nStructs,'value',nStructs,'sliderstep',[1/(nStructs-1) 1/(nStructs-1)]);
            structSlider_clk('init',planC);
        else
            for i=1:length(planC{indexS.structures})
                structNum  = firstVisStruct+i-1;
                structName = planC{indexS.structures}(structNum).structureName;
                assocScan  = getStructureAssociatedScan(structNum, planC);
                set(ud.handles.strName(i), 'string', structName, 'visible', 'on');
                set(ud.handles.strScan(i), 'string', num2str(assocScan), 'visible', 'on');
                set(ud.handles.strCheck(i), 'visible', 'on', 'value', ud.checkedStructs(structNum));
            end
        end

        %Refresh scan struct UIelements.
        set(ud.handles.scanSize,  'visible', 'off');
        set(ud.handles.scanName,  'visible', 'off');
        set(ud.handles.scanCheck, 'visible', 'off');
        nScans = length(ud.checkedScans);
        firstVisScan = ud.firstVisScan;

        if nScans > 6
            hSlider = findobj('tag','scanSlider');
            set(hSlider,'enable', 'on','BackgroundColor',[0 0 0]);
            set(hSlider,'min',1,'max',nScans,'value',nScans,'sliderstep',[1/(nScans-1) 1/(nScans-1)]);
            scanSlider_clk('init', planInfo, planC);
        else
            for i=1:min(length(ud.handles.scanName), nScans)
                scanNum  = firstVisScan+i-1;
                modality = planInfo.scans(scanNum).modality;
                size     = planInfo.scans(scanNum).sizeInMB;
                set(ud.handles.scanNumber(i), 'string', num2str(scanNum), 'visible', 'on');
                set(ud.handles.scanName(i), 'string', modality, 'visible', 'on');
                set(ud.handles.scanSize(i), 'string', [num2str(round(size)) ' MB'], 'visible', 'on');
                set(ud.handles.scanCheck(i), 'visible', 'on', 'value', ud.checkedScans(scanNum));
            end
        end

        %Refresh dose struct UIelements.
        set(ud.handles.doseSize,  'visible', 'off');
        set(ud.handles.doseName,  'visible', 'off');
        set(ud.handles.doseCheck, 'visible', 'off');
        nDoses = length(ud.checkedDoses);
        firstVisDose = ud.firstVisDose;
        for i=1:min(length(ud.handles.doseName), nDoses)
            doseNum  = firstVisDose+i-1;
            doseName = planC{indexS.dose}(doseNum).fractionGroupID;
            size     = planInfo.doses(doseNum).sizeInMB;
            set(ud.handles.doseName(i), 'string', doseName, 'visible', 'on');
            set(ud.handles.doseSize(i), 'string',[num2str(round(size)) ' MB'], 'visible', 'on');
            set(ud.handles.doseCheck(i), 'visible', 'on', 'value', ud.checkedDoses(doseNum));
        end
        set(hFig, 'userdata',ud);

    case 'CHECK'
        checkNum = get(gcbo, 'userdata');
        type     = get(gcbo, 'Tag');
        value    = get(gcbo, 'value');

        ud = get(hFig, 'userdata');
        totStruct = ud.nStructs;
        switch upper(type)
            case 'DOSECHECK'
                ud.checkedDoses(checkNum+ud.firstVisDose-1) = value;
            case 'SCANCHECK'
                ud.checkedScans(checkNum+ud.firstVisScan-1) = value;
            case 'STRUCTCHECK'
                slidStat = get(findobj('tag','structSlider'),'enable');
                if strcmpi(slidStat,'off')
                    ud.checkedStructs(checkNum+ud.firstVisStruct-1) = value;
                elseif strcmpi(slidStat,'on')
                    val = get(findobj('tag','structSlider'),'value');
                    if val == totStruct
                        startPt = totStruct-val;
                    else
                        startPt = totStruct-val-1;
                    end
                    ud.checkedStructs(checkNum+startPt+ud.firstVisStruct-1) = value;
                end
        end

        set(hFig, 'userdata', ud);

    case 'ALLCHECK'
        type     = get(gcbo, 'Tag');
        value    = get(gcbo, 'value');

        ud = get(hFig, 'userdata');

        switch upper(type)
            case 'DOSE'
                if ~isempty(ud.checkedDoses)
                    ud.checkedDoses(1:end) = value;
                end
            case 'SCAN'
                if ~isempty(ud.checkedScans)
                    ud.checkedScans(1:end) = value;
                end
            case 'STRUCT'
                if ~isempty(ud.checkedStructs)
                    ud.checkedStructs(1:end) = value;
                end
        end

        set(hFig, 'userdata', ud);
        planMergeGui('REFRESH');

    case 'MERGE'
        ud = get(hFig, 'userdata');
        mergePlan = getappdata(hFig, 'MERGEPLAN');

        global planC
        fileName = fullfile(get(ud.handles.pathText,'string'),get(ud.handles.filenameText,'string'));
        planMergeGui('status', 'Merging, please wait...');
        planC = planMerge(planC, mergePlan, find(ud.checkedScans), find(ud.checkedDoses), find(ud.checkedStructs), fileName);

        clear mergePlan;
        rmappdata(hFig, 'MERGEPLAN');

        planMergeGui('CANCEL');
        stateS.planMerged = 1;

        %refresh navigation montage if it exists
        navFig = findobj('tag','navigationFigure');
        if ~isempty(navFig)
            navigationMontage('refresh')
        end

        %Refresh the Viewer
        currentAxis = stateS.currentAxis;
        for iAxis = 1:length(stateS.handle.CERRAxis)
            axView = getAxisInfo(stateS.handle.CERRAxis(iAxis),'view');
            if ismember(axView,{'transverse','sagittal','coronal'})
                stateS.currentAxis = iAxis;
                sliceCallBack('CHANGESLC','PREVSLICE')
                sliceCallBack('CHANGESLC','NEXTSLICE')
            end
        end
        stateS.currentAxis = currentAxis;

    case 'QUIT'
        stateS.handle.planMergeGui = [];
        closereq;

end


%% OPENMAS EVENT HANDLER (OMAS_eventHandler.m) %%%%%%%%%%%%%%%%%%%%%%%%%%%%
% This function is designed to handle an event occuring between objectA and
% objectB. An EVENT object is created at the current time, based on the two
% objects and the enumerated event type.

% Author: James A. Douthwaite 06/10/17

function [EVENT] = OMAS_eventHandler(time_event,metaObjectA,metaObjectB,eventEnumeration)
% INPUTS:
% time_event         - The time the event are occurred
% metaobjectA        - The reference object (entity or meta)
% metaobjectB        - The detected/collision object (entity or meta)
% eventEnumeration   - The type of event indicated by the simulator

% OUTPUTS:
% EVENT              - The generated detection event structure

% INPUT HANDLING
% if ~exist('eventEnumeration','var')
%     error('[ERROR]\tEvent "type" unspecified.\n');
% end

% /////////////// GENERATE THE APPROPRIATE EVENT CLASS ////////////////////
% The simulation will generate one of the following events inreponse to the
% request. The result is an event object and the associated updated meta
% object.
switch eventEnumeration
% DETECTION EVENTS
    case eventType.detection
        % GENERATE C-FRIENDLY NOTIFICATION STRING
        infoString = char(['Detection notification [',metaObjectA.name,':',metaObjectB.name,']']);
        EVENTobj = detectionEvent(time_event,metaObjectA,metaObjectB,infoString);
% DETECTION-LOSS EVENTS
    case eventType.null_detection
        % GENERATE C-FRIENDLY NOTIFICATION STRING
        infoString = char(['Detection-loss notification [',metaObjectA.name,':',metaObjectB.name,']']);
        EVENTobj = detectionEvent(time_event,metaObjectA,metaObjectB,infoString,eventType.null_detection);
 % WARNING/NEAR-MISS EVENTS
    case eventType.warning
        % GENERATE C-FRIENDLY NOTIFICATION STRING
        infoString = char(['Proximity warning notification [',metaObjectA.name,':',metaObjectB.name,']']);
        EVENTobj = warningEvent(time_event,metaObjectA,metaObjectB,infoString);
% A WARNING/NEAR MISS CONDITION NULLIFICATION
    case eventType.null_warning
        % GENERATE C-FRIENDLY NOTIFICATION STRING
        infoString = char(['Proximity warning-clear notification [',metaObjectA.name,':',metaObjectB.name,']']);
        EVENTobj = warningEvent(time_event,metaObjectA,metaObjectB,infoString,eventType.null_warning);
% COLLISION/GEOMETRIC VIOLATION EVENTS
    case eventType.collision
        % GENERATE C-FRIENDLY NOTIFICATION STRING
        infoString = char(['Collision notification [',metaObjectA.name,':',metaObjectB.name,']']);
        EVENTobj = collisionEvent(time_event,metaObjectA,metaObjectB,infoString);
% COLLISION/GEOMETRIC VIOLATION NULLIFICATION EVENTS
    case eventType.null_collision
        % GENERATE C-FRIENDLY NOTIFICATION STRING
        infoString = char(['Collision-clear notification [',metaObjectA.name,':',metaObjectB.name,']']);
        EVENTobj = collisionEvent(time_event,metaObjectA,metaObjectB,infoString,eventType.null_collision);
% WAYPOINT ACHIEVED EVENTS
    case eventType.waypoint
        % GENERATE C-FRIENDLY NOTIFICATION STRING
        infoString = char(['Waypoint notification [',metaObjectA.name,':',metaObjectB.name,']']);
        EVENTobj = waypointEvent(time_event,metaObjectA,metaObjectB,infoString);
% WAYPOINT-LOSS EVENTS
    case eventType.null_waypoint
        % A WAYPOINT RESET EVENT (NON-WAYPOINT)
        infoString = sprintf('Waypoint-reset notification [%s:%s]',metaObjectA.name,metaObjectB.name);
        EVENTobj = waypointEvent(time_event,metaObjectA,metaObjectB,infoString,eventType.null_waypoint);
% EVENT UNKNOWN
    otherwise
        fprintf('[ERROR]\tEvent type not recognised.');
        EVENT = [];
        return
end
% OUTPUT EVENT STRUCTURE
EVENT = [];
% CONVERT THE EVENT OBJECT INTO A REPORT STRUCTURE
if ~isempty(EVENTobj)
    % GENERATE THE SIMULATION EVENT STRUCTURE
    [EVENT] = event2Struct(EVENTobj);
    % IF VERBOSE, GENERATE NOTIFICATION OF EVENT CREATION
%     if verbosity > 2
%         fprintf('[%s]\tevent created (ID:%d @t=%.2fs):\t%s\n',EVENTobj.name,EVENTobj.eventID,EVENTobj.time,EVENTobj.info);
%     end
end
end

% GENERATE EVENT RECORD
function [EVENT] = event2Struct(EVENTobject)
% This function converts the event object into a structure for the
% simulation log.
% INPUT
% EVENTobject - The EVENT class object
% OUTPUT
% EVENT       - The EVEN log structure

% Append EVENT CLASS TO STRUCTURE FOR REPORTING
EVENT = struct('eventID',EVENTobject.eventID,...
                  'time',EVENTobject.time,...
                  'type',EVENTobject.type,...
                  'name',EVENTobject.name,...
            'objectID_A',EVENTobject.objectID_A,...
                'name_A',EVENTobject.name_A,...
               'state_A',EVENTobject.state_A,...
            'objectID_B',EVENTobject.objectID_B,...
                'name_B',EVENTobject.name_B,...
               'state_B',EVENTobject.state_B,...
            'separation',EVENTobject.separation,...
                  'info',EVENTobject.info);
% clear EVENTobject
end


function [r,ElapsedTime] = RunCaisFile(FileName,AnsysPath)
%FileName: File of .cai type, only File Name, No Extension!!!!!
%%
%if nargin<2
%    AnsysPath='"E:\CloudCache\3E46DDDB3C282A64C62650819BF418D0A3B645F6\0\##PROGRAM_FILES##\ANSYS Inc\v110\ANSYS\bin\intel\ansys110"';
%end
%FileName='test';
%% .cai to .inp
r1=Cai2Ansys(FileName);
%% run .inp
[r2 ElapsedTime]=RunAnsys(AnsysPath,FileName);
%% Return Value
r=r1+r2;


%kTimer 'Timer Object Menuform'
% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros Timer.pane file
%
% Parameters:
%
% Example: kTimer( {})
%
% Khoros helpfile follows below:
% .begin tagged
%
% .item "The Timer Visual Object"
% The timer object is provided for use as a stopwatch.  It displays the current
% time (including seconds) according to the system clock of the computer.  It can
% be started and stopped as desired, and the update time can be specified
% to fractions of a second.  The timer object is a specialized annotation
% subclassed from the string visual object.  The (x, y) location of the lower
% left corner of the timer timer may be specified in device coordinates or
% world coordinates by the application.  The menuform, however, displays the
% world coordinate location of the timer, regardless of whether the application
% used world or device coordinates to specify that location.  Attributes of the
% timer object that can be interactively specified in addition to its world
% coordinate placement include its start time, and update time, in addition to
% its justification, style, font, and colors.
%
% .item "Update Time"
% This double selection specifies, in fractions of a second, how often
% the timer is updated.  For example, an update time of 5 would cause the timer
% to update every 5 seconds, while an update time of 0.25 would cause the timer
% to update 4 times every second.
%
% .item "Start Time"
% This double selection gives the start time of the timer.  By default it
% is time = 0.0, but it can be set to any number greater than zero.
%
% .item "Justification"
% This attribute specifies the justification of the string displaying the
% time "with respect to the width and height of the timer object itself,
% not its parent".
% Thus, if the timer object is just large enough to accomodate the time,
% justification will have little (if any) effect, as the time string has no
% room to "move" within its boundaries.  However, if the width and height are
% set to "larger" than what is necessary to display the time, the
% justification will take effect.  Justification may be set to "Center",
% "Top", "Bottom", "Left", "Right", "TopRight", "TopLeft", "BottomRight",
% or "BottomLeft".
%
% .item "Fill Background"
% When set to true, this attribute indicates that the background of the timer
% object should appear in the fill color (background color).
%
% .item "String Style"
% The date can be displayed in one of four styles: plain, emphasized, embossed
% in, or embossed out.  When the "plain" style is used, the date is drawn once,
% in the foreground color. When the date is "emphasized", it is double-drawn
% using both the foreground and highlight colors;  this causes it to have a bold,
% or emphasized, effect. When the "embossed in" style is used, the date will
% appear embossed "into" the background; both the foreground and highlight
% colors are used in embossing.  The "embossed out" style also causes the date
% to appear embossed, but the date will seem to come "out of" rather than
% "into" the background.
%
% .item "Font"
% Some of the fonts that are most commonly used with the date object are
% available in the stringlist menu;  or, you may provide your own in the text
% parameter box.
% .so  $DESIGN/manual/shared/xvobjects/general/FontName.sec
%
% .item "Foreground Color"
% This stringlist selection lets you set the foreground color of the timer object.
% The foreground color is always used to draw the time string,
% regardless of the "String Style".
%
% .item "Background Color"
% This stringlist selection lets you set the background color (fill color) of
% the timer object.  It is only used when "Fill Background" is set to true.
%
% .item "Highlight Color"
% This stringlist selection lets you set the highlight color; the highlight
% color is an additional color used in drawing the time string when the
% "String Style" is set to "Emphasized", "Embossed In", or "Embossed Out".
%
% .item "X Placement, Y Placement"
% This pair of double values specifies the (x, y) location of the lower left
% hand corner of the timer visual object in world coordinates.
%
% .end tagged

function varargout = kTimer(varargin)
Inputs={};
if nargin ==0
  arglist={'',''};
elseif nargin ==1
  arglist=varargin{1};
else error('Usage: [out1,..] = kTimer(arglist).');
end
if size(arglist,2)~=2
  error('arglist must be of form {''ParameterTag1'',value1;''ParameterTag2'',value2}')
 end
narglist={};
maxval={};
minval={};
istoggle=[];
was_set=istoggle * 0;
paramtype={};
% 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 'Timer" '],Inputs,narglist);


function view = makeHemisphereButtons(view)
%
% view = makeHemisphereButtons(view)
%
% Installs push buttons that set curSlice.
%
% djh, 1/97

% Left button Callback:
%   selectButton(view.ui.sliceButtons,1);
%   view=refreshScreen(view);
% The hemisphere buttons pass a '2' in the recompute field of refreshView.
% This lets refreshView deal with the image rotation slider bar.
callbackStr = ...
    ['selectButton(',view.name,'.ui.sliceButtons,1); ',...
	view.name,'=refreshScreen(',view.name,',2);'];
view.ui.sliceButtons(1) = ...
    uicontrol('Style','radiobutton',...
    'String','Left',...
	'BackgroundColor', get(gcf, 'Color'), ...
    'Units','normalized',...
    'Position',[.1 .01 .1 .05],...
    'Callback', callbackStr);

% Right button Callback:
%   selectButton(view.ui.sliceButtons,1);
%   view=refreshScreen(view);
callbackStr = ...
    ['selectButton(',view.name,'.ui.sliceButtons,2); ',...
	view.name,'=refreshScreen(',view.name,',2);'];
view.ui.sliceButtons(2) = ...
    uicontrol('Style','radiobutton',...
    'String','Right',...
    'Units','normalized',...
	'BackgroundColor', get(gcf, 'Color'), ...
    'Position',[.25 .01 .1 .05],...
    'Callback', callbackStr);
return;


classdef SettingsMeshPlotter < AbstractSettings

    properties (Access = protected)
        defaultParamsName = 'paramsMeshPlotter.json'
    end

    properties (Access = public)
        mesh
        isBackground
        faceColor
        faceAlpha
        edgeAlpha
    end

    methods (Access = public)

        function obj = SettingsMeshPlotter(varargin)
            switch nargin
                case 1
                    obj.loadParams(varargin{1});
            end
        end

    end

end


function [B, A] = swap(A, B)
%SWAP Swap two variables without an intermediate copy.
% Usage:
%   [B, A] = swap(A, B)

end