classdef AssessmentPerformanceMetricResult < handle
   properties (Access = public)
       algorithmName;
       segmentationPerformanceMetrics;
       featureExtractionPerformanceMetrics;
       classificationPerformanceMetrics;
       predictionPerformanceMetrics;
   end

end


function varargout = process_report_email( varargin )
% PROCESS_REPORT_EMAIL: Send current process report by email.
%
% For calling this function from a script, use directly bst_report.m:
% bst_report('Email', ReportFile, to, subject, isFullReport=1)

% @=============================================================================
% This function is part of the Brainstorm software:
% https://neuroimage.usc.edu/brainstorm
%
% Copyright (c) University of Southern California & McGill University
% This software is distributed under the terms of the GNU General Public License
% as published by the Free Software Foundation. Further details on the GPLv3
% license can be found at http://www.gnu.org/copyleft/gpl.html.
%
% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE
% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY
% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY
% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.
%
% For more information type "brainstorm license" at command prompt.
% =============================================================================@
%
% Authors: Francois Tadel, 2021

eval(macro_method);
end

%% ===== GET DESCRIPTION =====
function sProcess = GetDescription() %#ok<DEFNU>
    % Description the process
    sProcess.Comment     = 'Send report by email';
    sProcess.Category    = 'Custom';
    sProcess.SubGroup    = 'File';
    sProcess.Index       = 983;
    sProcess.Description = 'https://neuroimage.usc.edu/brainstorm/Tutorials/Scripting#Send_report_by_email';
    % Definition of the input accepted by this process
    sProcess.InputTypes  = {'raw', 'data', 'results', 'timefreq', 'matrix', 'dipoles', 'pdata', 'presults', 'ptimefreq', 'pmatrix', 'import'};
    sProcess.OutputTypes = {'raw', 'data', 'results', 'timefreq', 'matrix', 'dipoles', 'pdata', 'presults', 'ptimefreq', 'pmatrix', 'import'};
    sProcess.nInputs     = 1;
    sProcess.nMinFiles   = 0;
    sProcess.isSeparator = 1;
    % Definition of the options
    % === USERNAME
    sProcess.options.username.Comment = 'Brainstorm username: ';
    sProcess.options.username.Type    = 'text';
    sProcess.options.username.Value   = '';
    % === TO
    sProcess.options.cc.Comment = 'Send copy to (email address): ';
    sProcess.options.cc.Type    = 'text';
    sProcess.options.cc.Value   = '';
    % === SUBJECT
    sProcess.options.subject.Comment = 'Subject: ';
    sProcess.options.subject.Type    = 'text';
    sProcess.options.subject.Value   = 'Process completed';
    % === REPORTFILE
    sProcess.options.reportfile.Comment = 'ReportFile: ';
    sProcess.options.reportfile.Type    = 'text';
    sProcess.options.reportfile.Value   = 'current';
    sProcess.options.reportfile.Hidden  = 1;
    % === FULL REPORT
    sProcess.options.full.Comment = 'Send full report';
    sProcess.options.full.Type    = 'checkbox';
    sProcess.options.full.Value   = 1;
end

%% ===== FORMAT COMMENT =====
function Comment = FormatComment(sProcess) %#ok<DEFNU>
    Comment = sProcess.Comment;
end

%% ===== RUN =====
function OutputFiles = Run(sProcess, sInputs) %#ok<DEFNU>
    % Returned files: same as input
    OutputFiles = {sInputs.FileName};
    % Brainstorm username
    username = sProcess.options.username.Value;
    if isempty(username)
        bst_report('error', sProcess, [], 'Invalid Brainstorm username.');
        return;
    end
    % CC address
    cc = sProcess.options.cc.Value;
    if ~isempty(cc) && ~any(cc == '@')
        bst_report('error', sProcess, [], 'Invalid email address.');
        return;
    end
    % Email subject
    subject = sProcess.options.subject.Value;
    if isempty(subject)
        subject = 'Brainstorm report';
    end
    % Report file
    reportfile = sProcess.options.reportfile.Value;
    % Full report
    isFullReport = sProcess.options.full.Value;
    % Send email
    [isOk, resp] = bst_report('Email', reportfile, username, cc, subject, isFullReport);
    % Error handling
    if ~isOk
        bst_report('Error', sProcess, [], ['Email could not be sent: ' 10 resp]);
    end
end


function write_nitf_header(obj)
%WRITE_NITF_HEADER Writes the NITF file header
%
% It's not expected that the typical user would call this function, rather
% it is called as part of a bigger NITF/SICD writer.
%
% Inputs:
%       obj:        This is the 'hidden' object-specific handle.  It is
%                   similar to 'this' in Java.
%
% References:
%       MIL-STD-2500C, Department of Defense Interface Standard
%                      National Imagery Transmission Format version 2.1
%                      01 May 2006
%
% Written by: Tom Krauss, NGA/IDT
%
% //////////////////////////////////////////
% /// CLASSIFICATION: UNCLASSIFIED       ///
% //////////////////////////////////////////

%
% Note, the hard-coded numbers in the writeN calls are NITF field widths
% (in characters).  If the spec changes or we choose to use something other
% than NITF 2.1 these values must change.
%

% Always writing to NITF version 2.1
fwriten(obj.FID, 'NITF02.10', 9);  % FHDR and FVER
% Complexity level depends on the "size" of the image.
% Size of image data.  Note, we're converting the integer row/col counts to
% double because the multiplication may overflow normal Matlab integer
% arithmetic.  We also need to get the pixel size which is
if obj.image_data_size < (50*(1024*1024)) % Less than 50MB
    complexity = 3;
elseif obj.image_data_size < (1*(1024*1024*1024)) % Less than 1GB
    complexity = 5;
elseif obj.image_data_size < (2*(1024*1024*1024)) % Less than 2GB
    complexity = 6;
else
    complexity = 7;
end
fwriten(obj.FID, uint8(complexity),  2);  % CLEVEL
fwriten(obj.FID, 'BF01',      4);  % STYPE
fwriten(obj.FID, 'Unknown',   10); % OSTAID (not supposed to be blank)

if isfield(obj.sicdmeta,'ImageCreation')&&isfield(obj.sicdmeta.ImageCreation,'DateTime')
    fdt = datestr(obj.sicdmeta.ImageCreation.DateTime,'yyyymmddHHMMSS'); % Creation time of original image
else
    fdt = datestr(now,'yyyymmddHHMMSS'); % Creation time of this NITF
end
fwriten(obj.FID, fdt,         14); % FDT

if isfield(obj.sicdmeta,'CollectionInfo')&&isfield(obj.sicdmeta.CollectionInfo,'CoreName')
    FTITLE = obj.sicdmeta.CollectionInfo.CoreName;
else
    FTITLE = 'Unknown';
end
if obj.is_complex
    FTITLE = ['SICD: ' FTITLE];
end
fwriten(obj.FID, FTITLE, 80); % FTITLE

obj.write_nitf_security_tags(); % Security tags go here
fwriten(obj.FID,   '00000', 5);  % FSCOP - File Copy Number
fwriten(obj.FID,   '00000', 5);  % FSCPYS - File Number of Copies
fwriten(obj.FID,   '0', 1); % ENCRYP - Encryption. (0=none)
fwrite(obj.FID, 0, 'uint8'); % FBKGC 3-byte binary write for
fwrite(obj.FID, 0, 'uint8'); % background color
fwrite(obj.FID, 0, 'uint8'); % (red, green, blue)
fwriten(obj.FID,   '', 24); % ONAME
fwriten(obj.FID,   '', 18); % OPHONE

% File and header lengths

fwriten(obj.FID, uint64(obj.total_file_length), 12);   % File length
fwriten(obj.FID, uint64(obj.NITF_header_length), 6);   % Header length - fixed size for NITF 2.1

% Image Segment description
fwriten(obj.FID, uint64(1), 3);    % Always going to write a single image segment.
fwriten(obj.FID, uint64(obj.IS_subheader_size), 6);  % Length of image subheader - fixed size (512) for NITF 2.1
fwriten(obj.FID, uint64(obj.image_data_size), 10);

% Graphic segments (none)
fwriten(obj.FID, uint64(0), 3);

% Reserved extension segments (none)
fwriten(obj.FID, uint64(0), 3);

% Text Segments (none)
fwriten(obj.FID, uint64(0), 3);

% Data Extension segments.  This is where the SICD XML goes.  We'll make
% the XML string here so we can get its length even though we won't write
% the string until later.
fwriten(obj.FID, uint64(1), 3);
fwriten(obj.FID, uint64(obj.DES_header_length), 4);
fwriten(obj.FID, uint64(length(obj.DES_data)), 9);   % Length of DES data

% Reserved Extension segments (none)
fwriten(obj.FID, uint64(0), 3);

% User defined headers (none)
fwriten(obj.FID, uint64(0), 5);

% Extended headers (none)
fwriten(obj.FID, uint64(0), 5);

end

% //////////////////////////////////////////
% /// CLASSIFICATION: UNCLASSIFIED       ///
% //////////////////////////////////////////


function [varargout] = openDbConnection(view);
% [View,OK] = openDbConnection(view);
% OK = openDbConnection(view);
% openDbConnection(view);
%
% First overload is used for login, others - for  simple connection.
%
% In login mode: Check for session  existence. If  not exist - ask operator for his
% username, password etc. Then connect. If name doesn't exist - ask for  it  again and create
% a  new record  in the database.
% In simple mode: Just try to connect. If it fails - bring an error message.

defautValues = {'snarp.stanford.edu','vista','',''};

if(nargout<2) % SIMPLE MODE
  if(isfield(view,'mysqlsession')) % We are logged in already
    mysql('open',view.mysqlsession.hostname,view.mysqlsession.username,...
      view.mysqlsession.password);
    mysql('use','mrDataDB');
    varargout{1} = 1; % OK button
    return;
  else % Error Message
    myWarnDlg('You''re not logged in yet. Please, go to File/Login to database and log in.');
    varargout{1} = 0; % Cancel button
    return;
  end
else % ADVANCED MODE
  varargout{2} = 1; % OK button
  if(isfield(view, 'mysqlsession')) %  Connection was  already open
    Answer = questdlg('You have selected your database,username and password already. Do you wish to continue?',...
      'Alert','Cancel','OK','Cancel');
    if(strcomp(Answer,'Cancel'))
       varargout{1} = view;
       varargout{2} = 0;
       return;
    end
  end

  prompt={'Hostname:','Login:','Password:','Username (how are you listed in a database'};
  answer=inputdlg(prompt,'Connecting to database...',1,defautValues);

  if ~isempty(answer)
    mysqlsession = struct('hostname',answer{1},'username',answer{2},...
      'password',answer{3},'userId',0);
    view = setfield(view,'mysqlsession',mysqlsession);
    Flag = mysql('open',mysqlsession.hostname,mysqlsession.username,...
      mysqlsession.password);
    if(~exist('Flag')) % An error occured when opening a connection
      varargout{1} = view;
      varargout{2} = 0;
      return;
    end
    mysql('use','mrDataDB');
    view.mysqlsession.userId = checkForUser(answer{4}); % Transform nick name to an Id (see below)
    view.mysqlsession.userId
    varargout{1} = view;
    return;
  else % Cancel button
    varargout{1} = view;
    varargout{2} = 0;
    return;
  end
end

%%-------------------------------
function userId = checkForUser(userNick);
userId = mysql(['SELECT id FROM users WHERE username="',userNick,'"']);
if(max(size(userId))>1) % More than one user found
  userId = userId(1);
  myWarnDlg('More than one user with this username found. Using  the first one.');
  return;
elseif(min(size(userId))==0) % No such user in a database
  Answer = questdlg('There''re no users with this username in the database. Do you want to create a new record?',...
      'New record','Cancel','OK','Cancel');
  if(strcomp(Answer,'Cancel'))
    userId = 0;
    myWarnDlg('You''re listed as a GUEST user');
  else
    ResultFlag = 0;
    while(ResultFlag==0)
      answer=inputdlg({'First name:','Last name:','Organization:','E-mail:','Username:'}...
        ,'Create a new user',1,{'','','','',userNick});
      if(isempty(answer)) % Cancel button
        userId = 0;
        myWarnDlg('You''re listed as a GUEST user');
        return;
      end
      listedEmail = mysql(['SELECT id FROM users WHERE email="',answer{4},'"']);
      listedNick = mysql(['SELECT id FROM users WHERE username="',answer{5},'"']);
      if(~isempty(listedEmail))
        myWarnDlg('This e-mail is already in the database. Try again.');
      elseif(~isempty(listedNick))
        myWarnDlg('This username is already in the database. Try again.');
      else
        ResultFlag=1;
      end;
    end
    mysql(['INSERT INTO users (firstName,lastName,organization,email,username,notes) VALUES("',...
      answer{1},'","',answer{2},'","',answer{3},'","',answer{4},'","',answer{5},...
      '","mrLoadRet creation")']);
    disp(['New user ',answer{5},' might be created.']);
  end
  return;
else % Normal situation - one user found
  return;
end


classdef MimToolbarPanel < GemPanel
    % MimToolbarPanel. Part of the gui for the TD MIM Toolkit.
    %
    %     This class is used internally within the TD MIM Toolkit to help
    %     build the user interface.
    %
    %     MimToolbarPanel represents a dynamic panel containing tool
    %     controls that can enable or disable themselves when updated.
    %
    %
    %     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 (Access = private)
        ControlGroups
        ControlGroupSeparators
        OrderedControlGroupList
        GuiApp
        ModeTabName
        ModeToSwitchTo
        OrganisedPlugins
        ToolMap
        AppDef
        Visibility
        GroupVertically
        AllowWrapping
    end

    properties (Constant)
        ToolbarHeight = 85
        RowHeight = 85
        LeftMargin = 10
        RightMargin = 20
        HorizontalSpacing = 10
    end

    methods
        function obj = MimToolbarPanel(parent, organised_plugins, mode_tab_name, mode_to_switch_to, visibility, gui_app, app_def, group_vertically, allow_wrapping)
            obj = obj@GemPanel(parent);

            obj.ModeTabName = mode_tab_name;
            obj.ModeToSwitchTo = mode_to_switch_to;
            obj.Visibility = visibility;
            obj.TopBorder = ~group_vertically;
            obj.AppDef = app_def;
            obj.GuiApp = gui_app;
            obj.ControlGroups = containers.Map;
            obj.ControlGroupSeparators = containers.Map;
            obj.OrderedControlGroupList = {};
            obj.ToolMap = containers.Map;
            obj.OrganisedPlugins = organised_plugins;
            obj.GroupVertically = group_vertically;
            obj.AllowWrapping = allow_wrapping;

            obj.AddTools();
        end

        function Resize(obj, new_position)
            Resize@GemPanel(obj, new_position);

            % After calling Resize@GemPanel, the position will have been adjusted due to the border
            new_position = obj.InnerPosition;

            resize_list = obj.ComputeSizes(new_position(3));

            % Do the actual resize
            panel_height = max(1, new_position(4));
            panel_top = new_position(2) + panel_height;
            for resize_item = resize_list
                item = resize_item{1}{1};
                new_size = resize_item{1}{2};
                new_size(2) = new_size(2) + panel_top;
                item.Resize(new_size);
            end

        end

        function resize_list = ComputeSizes(obj, width)
            % Create a structure containing the new positions

            min_x = 1 + obj.LeftMargin;
            max_x = width - obj.RightMargin;
            x_position = min_x;

            row_height = obj.RowHeight;
            y_column_top = 0;
            y_column_base = y_column_top - row_height;

            is_first_separator = true;
            resize_list = [];

            for tool_group_key = obj.OrderedControlGroupList
                tool_group_panel = obj.ControlGroups(tool_group_key{1});

                if tool_group_panel.Enabled
                    group_panel_height = tool_group_panel.GetRequestedHeight;
                    group_panel_width = tool_group_panel.GetWidth;

                    if (obj.AllowWrapping) && (x_position > min_x) && (obj.GroupVertically || (x_position + group_panel_width > max_x))
                        x_position = min_x;
                        y_column_top = y_column_top - row_height;
                        y_column_base = y_column_top - row_height;
                    end

                    if obj.GroupVertically
                        separator = obj.ControlGroupSeparators(tool_group_key{1});
                        y_position = y_column_top - separator.GetRequestedHeight;
                        if is_first_separator
                            is_first_separator = false;
                            separator.TopBorder = false;
                        else
                            separator.TopBorder = true;
                        end
                        separator.Enable();

                        resize_list{end + 1} = {separator, [1, y_position, width, separator.GetRequestedHeight()]};
                        y_column_top = y_column_top - separator.GetRequestedHeight();
                        y_column_base = y_column_top - row_height;
                    end

                    y_offset = round((row_height - group_panel_height)/2);
                    y_position = y_column_base + y_offset;
                    resize_list{end + 1} = {tool_group_panel, [x_position, y_position, group_panel_width, group_panel_height]};
                    x_position = x_position + obj.HorizontalSpacing + group_panel_width;

                else
                    if obj.GroupVertically
                        separator = obj.ControlGroupSeparators(tool_group_key{1});
                        separator.Disable();
                    end
                end
            end
        end

        function Update(obj, gui_app)
            % Calls each group panel and updates the controls. In some cases, controls will
            % become enabled that were previously disabled; this requires the position
            % (since this may not have been set if this is the first time the control has been made visible)

            for tool_group_key = obj.OrderedControlGroupList
                tool_group_panel = obj.ControlGroups(tool_group_key{1});
                tool_group_panel.Update(gui_app);
            end

            if ~isempty(obj.Position)
                obj.Resize(obj.Position);
            end

        end

        function height = GetRequestedHeight(obj, width)
            if obj.GroupVertically
                resize_list = obj.ComputeSizes(width);
                if isempty(resize_list)
                    height = 0;
                else
                    height = abs(resize_list{end}{2}(2));
                end
            else
                height = obj.ToolbarHeight;
            end
        end

        function mode = GetModeTabName(obj)
            mode = obj.ModeTabName;
        end

        function visibility = GetVisibility(obj)
            visibility = obj.Visibility;
        end

        function mode = GetModeToSwitchTo(obj)
            mode = obj.ModeToSwitchTo;
        end

        function AddPlugins(obj, current_dataset)
        end

        function UpdateForNewImage(obj, current_dataset, window, level)
        end

        function AddPreviewImage(obj, plugin_name, preview_fetcher, window, level)
        end

        function RefreshPlugins(obj, current_dataset, window, level)
        end

    end

    methods (Access = private)
        function AddTools(obj)
            tools = obj.OrganisedPlugins.GetOrderedPlugins(obj.ModeTabName);
            for tool = tools
                obj.AddTool(tool{1});
            end
        end

        function AddTool(obj, tool_wrapper)
            tool = tool_wrapper.PluginObject;
            tool_name = class(tool);
            category_key = tool.Category;
            if ~obj.ControlGroups.isKey(category_key)
                new_group = GemLabelButtonGroup(obj, category_key, '', category_key);
                obj.ControlGroups(category_key) = new_group;
                obj.OrderedControlGroupList{end + 1} = category_key;
                obj.AddChild(new_group);

                if obj.GroupVertically
                    separator = GemSeparator(obj, category_key);
                    obj.ControlGroupSeparators(category_key) = separator;
                    obj.AddChild(separator);
                end
            end
            icon_found = false;

            if isprop(tool, 'Icon')
                icons_paths = obj.AppDef.GetIconsFolders;
                for icon_path = icons_paths
                    if CoreDiskUtilities.FileExists(icon_path{1}, tool.Icon)
                        icon = imread(fullfile(icon_path{1}, tool.Icon));
                        icon_found = true;
                        break;
                    end
                end
            end

            if ~icon_found
                icon = imread(obj.AppDef.GetDefaultPluginIcon);
            end

            % IconColour overrides greyscale
            if isprop(tool, 'IconColour')
                size_icon = size(icon);
                icon = double(icon/255);
                icon_bw = repmat(0.21*icon(:,:,1) + 0.72*icon(:,:,2) + 0.07*icon(:,:,3), [1,1,3]);
                colour_tint = repmat(shiftdim(double(tool.IconColour), -1), [size_icon(1:2), 1]);
                icon = uint8(255*colour_tint.*icon_bw);
            elseif obj.AppDef.ForceGreyscale
                icon = repmat(0.21*icon(:,:,1) + 0.72*icon(:,:,2) + 0.07*icon(:,:,3), [1,1,3]);
            end

            tool_group = obj.ControlGroups(category_key);
            if isa(tool, 'MimGuiPluginSlider')
                new_control = MimPluginLabelSlider(obj, tool, icon, obj.GuiApp);
                new_control.StackVertically = tool.StackVertically;
            elseif isa(tool, 'MimGuiPluginEditBox')
                new_control = MimPluginLabelEditBox(obj, tool, icon, obj.GuiApp);
                new_control.StackVertically = tool.StackVertically;
            else
                new_control = MimPluginLabelButton(obj, tool, icon, @tool_wrapper.RunPlugin);
                new_control.ButtonWidth = 8*tool.ButtonWidth;
            end
            tool_group.AddControl(new_control);
            tool_struct = [];
            tool_struct.Control = new_control;
            tool_struct.ToolObject = tool;
            obj.ToolMap(tool_name) = tool_struct;
        end
    end
end


% Launch AMS example selector
% Copywrite 2001-2013 The MathWorks, Inc.
cd \ams
example_sel2html('AMS_sel.txt')


function mfilelist = mfilegrep(searchstring,startpath,recurse,wholewords,casesens,showline)

% MFILELIST = MFILEGREP(SEARCHSTRING, STARTPATH, RECURSE, WHOLEWORDS, CASESENS, SHOWLINE)
% returns in a cell array the names of all m-files within the startpath
% (searching recursively or non-recursively), that contain the text searchstring.
%
% The function calls the embedded subfunction 'filesearch' to locate the files.
%
% Takes from 1 to 6 input arguments; at a minimum, the user must specify the desired searchstring.
% STARTPATH and RECURSE (= 0 or 1) may also be inputs; otherwise, a gui interface will prompt the
%       user for these values.
% WHOLEWORDS and CASESENS (= 0 or 1) may be indicated as well; if not, the default values of 0 and 0,
%       respectively, will be used. Wholewords == 1 specifies that only whole-word matches will be returned;
%       wholewords == 0 will also return partial matches. Casesens == 1 returns case-sensitive matches only;
%       casesens == 0 ignores case.
% The final (optional) input is SHOWLINE (= 0 or 1; default = 0). If showline == 1, the output also
%       shows the text of all lines found in the file(s) containing the search string.
%
% EXAMPLES:
%
% FILELIST = MFILEGREP('domct') prompts the user via uicontrols for starting path and inclusion or
%             exclusion of subdirectories, then searches all mfiles on the indicated path for 'domct'.
% FILELIST = MFILEGREP('domct', 'C:\Mfiles') searches specified directory for m-files; prompts the user for:
%             inclusion or exclusion of subdirectories.
% FILELIST = MFILEGREP('domct','C:\Mfiles',1) searches specified directory recursively for m-files.
% FILELIST = MFILEGREP('domct','C:\Mfiles',1, 0, 1) searches specified directory recursively for m-files;
%             in this case, the search returns partial word matches (e.g., 'examp' matches 'example'),
%             and the search is case sensitive.
% FILELIST = MFILEGREP('domct','C:\Mfiles',0, 0, 1, 1) searches specified directory non-recursively for m-files;
%             returns partial and case-sensitive word matches, and includes all lines containing the search string
%             in the output cell array.
%
% Copyright Brett Shoelson, Ph.D.
% Shoelson Consulting
% brett.shoelson@joslin.harvard.edu
% V1: 6/22/01. Based extensively on the new version of collectcode.m.
% V2. 9/30/01. Modified to include "showline" option.
% V3. 10/25/01. Modified to match default behavior to program description.

if ~nargin
	error('Requires at least one argument indicating desired searchstring.');
elseif nargin == 1
	% Get starting path
	[filename,startpath]=uigetfile('*.m','Select any m-file in the desired starting pathname.');
	%Remove trailing '\' character
	if strcmp(startpath(end),'\'),startpath=startpath(1:end-1);end
	% Query for inclusion of subdirectories
	recurse=questdlg('Include subdirectories?','','YES','No','YES');
	if strcmp(recurse,'YES'),recurse=1;else;recurse=0;end
	wholewords = 0; casesens = 0; showline = 0;
elseif nargin == 2
	recurse=questdlg('Include subdirectories?','','YES','No','YES');
	if strcmp(recurse,'YES'),recurse=1;else;recurse=0;end
	wholewords = 0; casesens = 0; showline = 0;
elseif nargin == 3
	wholewords = 0; casesens = 0; showline = 0;
elseif nargin == 4
	casesens = 0; showline = 0;
elseif nargin == 5
    showline = 0;
elseif nargin > 6
	error('Too many input arguments.');
end

% Check for appropriateness of inputs:
if ~ischar(searchstring)
	error('searchstring must be a character string.');
end
if recurse ~= 1 & recurse ~= 0
	error('recurse must be 1 or 0.');
end
if wholewords ~= 1 & wholewords ~= 0
	error('wholewords must be 1 or 0.');
end
if casesens ~= 1 & casesens ~= 0
	error('casesens must be 1 or 0.');
end
if showline ~= 1 & showline ~= 0
	error('showline must be 1 or 0.');
end

currpath = cd;

% Compile filenames (calls subfunction filesearch)
files = filesearch('m', startpath, recurse);

cd(startpath);

line = 0;
mfilelist = {};

if ~ casesens
	searchstring = lower(searchstring);
end

if wholewords
	alphachars = ['A' ; 'B' ; 'C' ; 'D' ; 'E' ; 'F' ; 'G' ; 'H' ; 'I' ; 'J' ; 'K' ; 'L' ; ...
			'M' ; 'N' ; 'O' ; 'P' ; 'Q' ; 'R' ; 'S' ; 'T' ; 'U' ; 'V' ; 'W' ; 'X' ; ...
			'Y' ; 'Z'];
	alphachars = [alphachars; lower(alphachars); '1' ; '2' ; '3' ; '4' ; '5' ; '6' ; '7' ; '8' ; '9' ; '0'];
end

% Loop through all mfiles on search path

fprintf('Searching directory(ies)....\n');

for i = 1 : size(files, 1)
	filename = files{i};
	%fprintf('Searching %s....\n', filename);
	% Open mfile(i) and read contents line by line; write lines to codetext.txt
	fid3 = fopen(filename, 'rt');
	while line ~=-1
		line = fgets(fid3);
		if line ~= -1
			if ~ casesens
				line = lower(line);
			end
			if ~isempty(findstr(line, searchstring))
				% findstr finds the instance of the shorter string in the longer; the following if/then ensures that
				% the function won't return instances of subelements (eg., findstr('y','classify') is non-empty).
				if length(line) >= length(searchstring)
					if wholewords
						wholefound = iswhole(searchstring, line, alphachars);
						if wholefound
							if isempty(intersect(mfilelist,filename))
								mfilelist{size(mfilelist, 1) + 1, 1} = filename;
							end
							if showline
								mfilelist{size(mfilelist, 1) + 1, 1} = line;
							else
								break
							end
						end
					else
						if isempty(intersect(mfilelist,filename))
							mfilelist{size(mfilelist, 1) + 1, 1} = filename;
						end
						if showline
							mfilelist{size(mfilelist, 1) + 1, 1} = line;
						else
							break
						end
					end % if wholewords
				end % if length(line) >= length(searchstring)
			end % if ~isempty(findstr(line, searchstring))
		end % if line ~=- 1
	end % while line ~=- 1
	line = 0;
	% Close mfile(i) and continue
	fclose(fid3);
end % for i = 1 : size(files, 1)

cd(currpath);

function files = filesearch(extension,startpath,recurse)
%
%  Search a specified path (recursively or non-recursively) for all instances of files with a specified extension.
%  Results are returned in a cell array ('files').
%
%  FILES = FILESEARCH(EXTENSION,STARTPATH,1) searches for all instances of *.extension in the starting directory OR
%          in any subdirectory beneath the starting directory.
%  FILES = FILESEARCH(EXTENSION,STARTPATH,0) searches for all instances of *.extension in the starting directory ONLY,
%          and excludes files in subdirectories.
%  Examples:
%
%  files = filesearch('txt','C:\WinNT',1)
%  mfiles = filesearch('m','D:\Mfiles',0)

% Copyright Brett Shoelson, Ph.D., 5/29/2001
% brett.shoelson@joslin.harvard.edu

if recurse
	files = {};
	%Create string of recursive directories/subdirectories
	paths = genpath(startpath);
	%Find instances of the path separator
	seplocs = findstr(paths,pathsep);
	%Parse paths into individual (vertically catenated) directories
	if ~isempty(seplocs)
		directories = paths(1:seplocs(1)-1);
		for i = 1:length(seplocs)-1
			directories = strvcat(directories,paths(seplocs(i)+1:seplocs(i+1)-1));
		end
		%Search each directory for instances of *.extension, appending to current list
		for i = 1:size(directories,1)
			%Compile located files as vertically catenated strings
			tmp = dir([deblank(directories(i,:)) '\*.' extension]);
			if ~isempty(tmp),tmp = char(tmp.name);end
			%Update files to reflect newly detected files. (Omit trailing blanks.)
			for j = 1:size(tmp,1)
				files{size(files,1)+1,1} = [deblank(directories(i,:)) '\' deblank(tmp(j,:))];
			end
		end
	end
else %Search non-recursively
	files = {};
	tmp = dir([startpath '\*.' extension]);
	if ~isempty(tmp),tmp = char(tmp.name);end
	for j = 1:size(tmp,1)
		files{size(files,1)+1,1} = [startpath '\' deblank(tmp(j,:))];
	end
end

function wholefound = iswhole(searchstring, teststring, alphachars)
charlocs = findstr(searchstring, teststring);
prevlocs = charlocs - 1;
postlocs = charlocs + length(searchstring);
delprevposns = [find(prevlocs == 0)];
delpostposns = [find(postlocs >= length(teststring))];
prevlocs(delprevposns) = '';
postlocs(delpostposns) = '';
prevmbrs = ismember(teststring(prevlocs)', alphachars);
postmbrs = ismember(teststring(postlocs)', alphachars);
if ~ isempty(delprevposns), prevmbrs = [0; prevmbrs]; end
if ~ isempty(delpostposns), postmbrs = [postmbrs; 0]; end
wholefound = any(~ or (prevmbrs, postmbrs) );


function meta = metaAddData(fieldName, value, viewType);
%
%  meta = metaAddData(fieldName, value, [viewType='Inplane']);
%
% Add metadata to a session.
%
% ras, 11/02/06: wrote it.
if nargin<2, error('Not enough Input args.'); end
if notDefined('viewType'), viewType = 'Inplane'; end

switch lower(viewType)
    case 'inplane'

    case 'volume'

    case 'gray'

    case 'mr'

end


function planC = deleteStructure(planC, structNumV)
% function planC = deleteStructure(planC, structNumV)
%
% Function to delete structure in a batch mode.
%
% APA, 09/25/2012

indexS = planC{end};
planC = delUniformStr(structNumV, planC); %Update the uniform data.
planC{indexS.structures}(structNumV) = [];

%len = length(planC{indexS.structures});
%planC = delUniformStr(structNum, planC); %Update the uniform data.
%planC{indexS.structures}(structNum:len-1) = planC{indexS.structures}(structNum+1:len);
%planC{indexS.structures} = planC{indexS.structures}(1:len-1);


function env = spx_get_env();
    global spx_env;
    if isempty(spx_env)
        filepath = which(mfilename);
        root = fileparts(filepath);
        spx_settings_cache = fullfile(root, 'spx_local_settings.mat');
        data = load(spx_settings_cache);
        spx_env = data.globals;
    end
    env = spx_env;
end


classdef LaunchVehicleNonSeqEvents < matlab.mixin.SetGet & matlab.mixin.Copyable
    %LaunchVehicleNoneSeqEvents Summary of this class goes here
    %   Detailed explanation goes here

    properties
        nonSeqEvts LaunchVehicleNonSeqEvent

        lvdData LvdData
    end

    properties(Dependent)
        evts LaunchVehicleEvent
    end

    methods
        function obj = LaunchVehicleNonSeqEvents(lvdData)
            obj.lvdData = lvdData;
            obj.nonSeqEvts = LaunchVehicleNonSeqEvent.empty(1,0);
        end

        function values = get.evts(obj)
            values = LaunchVehicleEvent.empty(1,0);

            for(i=1:length(obj.nonSeqEvts))
                values(end+1) = obj.nonSeqEvts(i).evt; %#ok<AGROW>
            end
        end

        function activeNonSeqEvts = getNonSeqEventsForScriptEvent(obj, evt)
            activeNonSeqEvts = LaunchVehicleNonSeqEvent.empty(1,0);
            evtNum = evt.getEventNum();

            for(i=1:length(obj.nonSeqEvts))
                nonSeqEvt = obj.nonSeqEvts(i);

                if(nonSeqEvt.numExecsRemaining > 0)
                    if(not(isempty(nonSeqEvt.lwrBndEvt)))
                        lwrBndEvtNum = nonSeqEvt.lwrBndEvt.getEventNum();
                    else
                        lwrBndEvtNum = 0;
                    end

                    if(not(isempty(nonSeqEvt.uprBndEvt)))
                        uprBndEvtNum = nonSeqEvt.uprBndEvt.getEventNum();
                    else
                        uprBndEvtNum = Inf;
                    end

                    if(evtNum >= lwrBndEvtNum && evtNum <= uprBndEvtNum)
                        activeNonSeqEvts(end+1) = nonSeqEvt; %#ok<AGROW>
                    end
                end
            end
        end

        function addEvent(obj, newEvt)
            obj.nonSeqEvts(end+1) = newEvt;
        end

        function addEventAtInd(obj, newEvt, ind)
            if(not(isempty(obj.nonSeqEvts)))
                if(ind == length(obj.nonSeqEvts))
                    obj.nonSeqEvts(end+1) = newEvt;
                else
                    obj.nonSeqEvts = [obj.nonSeqEvts(1:ind), newEvt, obj.nonSeqEvts(ind+1:end)];
                end
            else
                obj.nonSeqEvts(end+1) = newEvt;
            end
        end

        function removeEvent(obj, nonSeqEvt)
            arguments
                obj(1,1) LaunchVehicleNonSeqEvents
                nonSeqEvt(1,1) LaunchVehicleNonSeqEvent
            end

            evt = nonSeqEvt.evt;

            termCondOptVar = evt.termCond.getExistingOptVar();
            if(not(isempty(termCondOptVar)))
                obj.lvdData.optimizer.vars.removeVariable(termCondOptVar);
            end

            actions = evt.actions;
            for(i=1:length(actions)) %#ok<*NO4LP>
                evt.removeAction(actions(i));
            end

            obj.nonSeqEvts(obj.nonSeqEvts == nonSeqEvt) = [];
        end

        function removeEventFromIndex(obj, ind)
            if(ind >= 1 && ind <= length(obj.nonSeqEvts))
                obj.removeEvent(obj.nonSeqEvts(ind));
            end
        end

        function evtNum = getNumOfEvent(obj, evt)
            evtNum = [];

            if(not(isempty(evt)))
                evtNum = find(obj.nonSeqEvts == evt);
            end
        end

        function evt = getEventForInd(obj, ind)
            evt = LaunchVehicleNonSeqEvent.empty(1,0);

            if(ind >= 1 && ind <= length(obj.nonSeqEvts))
                evt = obj.nonSeqEvts(ind);
            end
        end

        function numEvents = getTotalNumOfEvents(obj)
            numEvents = length(obj.nonSeqEvts);
        end

        function [listboxStr, events] = getListboxStr(obj)
            listboxStr = cell(length(obj.nonSeqEvts),1);

            for(i=1:length(obj.nonSeqEvts))
                listboxStr{i} = obj.nonSeqEvts(i).getListboxStr();
            end

            events = obj.nonSeqEvts;
        end

        function resetAllNumExecsRemaining(obj)
            for(i=1:length(obj.nonSeqEvts))
                obj.nonSeqEvts(i).resetNumExecsRemaining();
            end
        end

        function tf = usesStage(obj, stage)
            tf = false;

            for(i=1:length(obj.evts))
                tf = tf || obj.evts(i).usesStage(stage);
            end
        end

        function tf = usesEngine(obj, engine)
            tf = false;

            for(i=1:length(obj.evts))
                tf = tf || obj.evts(i).usesEngine(engine);
            end
        end

        function tf = usesTank(obj, tank)
            tf = false;

            for(i=1:length(obj.evts))
                tf = tf || obj.evts(i).usesTank(tank);
            end
        end

        function tf = usesEngineToTankConn(obj, engineToTank)
            tf = false;

            for(i=1:length(obj.evts))
                tf = tf || obj.evts(i).usesEngineToTankConn(engineToTank);
            end
        end

        function tf = usesStopwatch(obj, stopwatch)
            tf = false;

            for(i=1:length(obj.evts))
                tf = tf || obj.evts(i).usesStopwatch(stopwatch);
            end
        end

        function tf = usesExtremum(obj, extremum)
            tf = false;

            for(i=1:length(obj.evts))
                tf = tf || obj.evts(i).usesExtremum(extremum);
            end
        end

        function tf = usesCalculusCalc(obj, calculusCalc)
            tf = false;

            for(i=1:length(obj.evts))
                tf = tf || obj.evts(i).usesExtremum(calculusCalc);
            end
        end

        function tf = usesPwrSink(obj, powerSink)
            tf = false;

            for(i=1:length(obj.evts))
                tf = tf || obj.evts(i).usesPwrSink(powerSink);
            end
        end

        function tf = usesPwrSrc(obj, powerSrc)
            tf = false;

            for(i=1:length(obj.evts))
                tf = tf || obj.evts(i).usesPwrSrc(powerSrc);
            end
        end

        function tf = usesPwrStorage(obj, powerStorage)
            tf = false;

            for(i=1:length(obj.evts))
                tf = tf || obj.evts(i).usesPwrStorage(powerStorage);
            end
        end

        function tf = usesSensor(obj, sensor)
            tf = false;

            for(i=1:length(obj.evts))
                tf = tf || obj.evts(i).usesSensor(sensor);
            end
        end

        function tf = usesTankToTankConn(obj, tankToTank)
            tf = false;

            for(i=1:length(obj.nonSeqEvts))
                tf = tf || obj.nonSeqEvts(i).usesTankToTankConn(tankToTank);
            end
        end
    end

	methods(Access = protected)
        function cpObj = copyElement(obj)
            cpObj = copyElement@matlab.mixin.Copyable(obj);

            for(i=1:length(obj.nonSeqEvts))
                cpObj.nonSeqEvts(i) = obj.nonSeqEvts(i).copy();
            end
        end
	end
end


function [metabolite_structure,IDsAdded] = getSeed2Kegg(metabolite_structure)
% This function parses the file: ftp://ftp.kbase.us/assets/KBase_Reference_Data/Biochemistry/compounds.xls
% first column contains seed ID, 5th col contains Kegg ID. This file is
% provided in /data/ as 'compounds.xlsx'
%
% INPUT
% metabolite_structure  metabolite structure
%
% OUTPUT
% metabolite_structure  Updated metabolite structure
%
%
% Ines Thiele, 2020-2021

annotationSource = 'Seed mapping to Kegg';
annotationType = 'automatic';

Mets = fieldnames(metabolite_structure);
for i = 1 : length(Mets)
    SeedId{i,1} = Mets{i};
    SeedId{i,2} = metabolite_structure.(Mets{i}).seed;
end

a = 1;
IDsAdded = '';

[NUM,TXT,RAW]=xlsread('compounds.xlsx');
for i = 1 : size(SeedId,1)
    % no keggId exists
    if isempty(metabolite_structure.(SeedId{i,1}).keggId) || ~isempty(find(isnan(metabolite_structure.(SeedId{i,1}).keggId),1))
        match = strmatch(SeedId{i,2},RAW(:,1),'exact');
        if ~isempty(match)
            if contains(RAW(match,5),'|') % take only first kegg Id
                [RAW{match,5},rem]=strtok(RAW{match,5},'|');
            end
            if ~isempty(RAW{match,5})
                metabolite_structure.(SeedId{i,1}).keggId = RAW{match,5};
                metabolite_structure.(SeedId{i,1}).keggId_source =  [annotationSource,':',annotationType,':',datestr(now)];
                IDsAdded{a,1} = SeedId{i,1};
                IDsAdded{a,2} = 'keggId';
                IDsAdded{a,3} =  metabolite_structure.(SeedId{i,1}).keggId;
                a = a + 1;
            end
        end
    end
end


classdef Builder_DesignVarMonitor_3D < Builder_DesignVarMonitor_Abstract

    methods (Access = protected)

        function cam = createCamera(obj)
            cam = Camera_Rotatory(obj.monitor.axes);
        end

    end

end


function milktruck_demo
% This function is an example on how to integrate GoogleEarth Milktruckdemo in a Matlab figure or GUI and
% control it via Matlab controls.
%
% You need the GoogleEarth plugin to be installed. Therefore just visit a website, where the plugin is needed
% and install it, e.g.:  http://code.google.com/intl/de-DE/apis/earth/
%
% The rest is more simple:
%
% The workaround for integrating GE in Matlab GUI is simple to embed a Microsoft Internet ActiveX-Control in
% the GUI.
%
% Further Readings:
%   http://code.google.com/intl/de-DE/apis/earth/
%   http://code.google.com/intl/de-DE/apis/earth/documentation/reference/index.html
% see in Matlab Help: actx_explore for integrating Shell-Explorer
%
% Programmed by Sven Koerner: koerner(underline)sven(add)gmx.de
% Date: 2011/08/04

% run Demo
MilktruckMA


function varargout = linespec2prop(varargin)
% VL_LINESPEC2PROP  Convert PLOT style line specs to line properties
%  PROPR = VL_LINESPEC2PROP(SPEC) converts the string SPEC to a cell
%  array of properties PROPR. SPEC is in the format of PLOT().
%
%  If SPEC is not a line spec, the string SPEC is returned unaltered
%  as the only element of the cell array PROPR.
%
%  See also: VL_PLOTFRAME(), PLOT(), VL_HELP().
[varargout{1:nargout}] = vl_linespec2prop(varargin{:});


function isOpen = hlp_pll_openPool(numWorkers,profileName)
% open a parallel toolbox pool

if nargin<2
    profileName = 'local';
end

sz = matlabpool('size');
isOpen = (sz>0);
% check if matlabpool is open...
if ~isOpen
    % ... if not, open one
    matlabpool(profileName,numWorkers);
elseif sz~=numWorkers
    % wrong number of workers
    % ...restart pool
    matlabpool('close');
    matlabpool(profileName,numWorkers);
end


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

% Last Modified by GUIDE v2.5 13-Mar-2004 17:41:39

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

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

% Update handles structure
guidata(hObject, handles);

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

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

% --- Executes on slider movement.
function Slider1_Callback(hObject, eventdata, handles)
% hObject    handle to Slider1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Find the value of the slider
value = get(handles.Slider1,'Value');

% Place the value in the text field
str = sprintf('%.2f',value);
set (handles.Label1,'String',str);

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

% Hint: slider controls usually have a light gray background, change
%       'usewhitebg' to 0 to use default.  See ISPC and COMPUTER.
usewhitebg = 1;
if usewhitebg
    set(hObject,'BackgroundColor',[.9 .9 .9]);
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end


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

%%
clear; close all; clc;

%% Syntax
% |[F,V]=elephant;|

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


function varargout = chebguiEdit(varargin)
%CHEBGUIEDIT   CHEBGUI edittor.
%   A CHEBGUIEDIT figure gets created when a user right-clicks the input fields
%   of the CHEBGUI figure. It is not intended for use in any other context.

% Copyright 2017 by The University of Oxford and The Chebfun Developers.
% See http://www.chebfun.org/ for Chebfun information.

% Suppress irritating MLINT warnings:
%#ok<*INUSL,*DEFNU,*INUSD>

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @chebguiEdit_OpeningFcn, ...
                   'gui_OutputFcn',  @chebguiEdit_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 chebguiEdit is made visible.
function chebguiEdit_OpeningFcn(hObject, eventdata, handles, varargin)
% Choose default command line output for chebguiEdit

handles.output = hObject;
mainGuiInput = find(strcmp(varargin, 'chebguiWindow'));
if ( isempty(mainGuiInput) ...
     || (length(varargin) <= mainGuiInput) ...
     || ~ishandle(varargin{mainGuiInput+1}) )
    disp('-----------------------------------------------------');
    disp('Improper input arguments. ')
    disp('chebguiEdit should only be called from chebgui.')
    disp('-----------------------------------------------------');
end
% TODO: Why not throw an error here?

% Remember the handle, and adjust our position
handles.chebguiwindow = varargin{mainGuiInput+1};

% Obtain handles using GUIDATA with the caller's handle
mainHandles = guidata(handles.chebguiwindow);
% Set the edit text to the String of the main GUI's button
handles.outputTarget = varargin{3};
set(handles.edit1, 'String', ...
    get(mainHandles.(varargin{3}), 'String'));

% Get the default font size.
set(handles.edit1, 'FontSize', get(mainHandles.tempedit, 'FontSize'));

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes chebguiEdit wait for user response (see UIRESUME)
uiwait(hObject);

end

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

% --- Executes during object creation, after setting all properties.
function edit1_CreateFcn(hObject, eventdata, handles)
if ( ispc && isequal(get(hObject, 'BackgroundColor'), ...
        get(0, 'defaultUicontrolBackgroundColor')) )
    set(hObject, 'BackgroundColor', 'white');
end
end

function edit1_Callback(hObject, eventdata, handles)
end

% --- Executes on button press in buttonOK.
function buttonOK_Callback(hObject, eventdata, handles)
% Obtain handles using GUIDATA with the caller's handle
mainHandles = guidata(handles.chebguiwindow);
% Set the edit text to the String of the main GUI's button
set(mainHandles.(handles.outputTarget), 'String', ...
    get(handles.edit1, 'String'));
% Store the used fontsize
updateEditFontSize(hObject, eventdata, handles)
% Resume and close
uiresume(handles.figure1);
delete(handles.figure1)
end

% --- Executes on button press in buttonCancel.
function buttonCancel_Callback(hObject, eventdata, handles)
% Store the used fontsize
updateEditFontSize(hObject, eventdata, handles);
% Resume and close
uiresume(handles.figure1);
delete(handles.figure1)
end

% --- Executes on button press in buttonClear.
function buttonClear_Callback(hObject, eventdata, handles)
set(handles.edit1, 'String', '');
end

function figure_CloseRequestFcn(hObject, eventdata, handles)
% Store the used fontsize
updateEditFontSize(hObject, eventdata, handles);
% Resume and close
uiresume(hObject);
end

function fontplusbutton_Callback(hObject, eventdata, handles)
% Increase font size.
fs = get(handles.edit1, 'FontSize') + 1;
set(handles.edit1, 'FontSize', fs);
end

function fontmbutton_Callback(hObject, eventdata, handles)
% Decrease font size.
fs = get(handles.edit1, 'FontSize') - 1;
set(handles.edit1, 'FontSize', fs);
end

function edit1_ButtonDownFcn(hObject, eventdata, handles)
% Is the same as buttonCancel
buttonCancel_Callback(hObject, eventdata, handles)
end

function updateEditFontSize(hObject, eventdata, handles)
mainHandles = guidata(handles.chebguiwindow);
set(mainHandles.tempedit, 'FontSize', get(handles.edit1, 'FontSize'));
end


function fig = RlcResponse()
% This is the machine-generated representation of a Handle Graphics object
% and its children.  Note that handle values may change when these objects
% are re-created. This may cause problems with any callbacks written to
% depend on the value of the handle at the time the object was saved.
% This problem is solved by saving the output as a FIG-file.
%
% To reopen this object, just type the name of the M-file at the MATLAB
% prompt. The M-file and its associated MAT-file must be on your path.
%
% NOTE: certain newer features in MATLAB may not have been saved in this
% M-file due to limitations of this format, which has been superseded by
% FIG-files.  Figures which have been annotated using the plot editor tools
% are incompatible with the M-file/MAT-file format, and should be saved as
% FIG-files.
warning('off','MATLAB:dispatcher:InexactMatch')
load RlcResponse

h0 = figure('Units','normalized', ...
	'Color',[0.8 0.8 0.8], ...
	'Colormap',mat0, ...
	'FileName','C:\MATLABR11\Circuits\RlcResponse.m', ...
	'HitTest','off', ...
	'PaperPosition',[18 180 576.0000000000001 432.0000000000002], ...
	'PaperUnits','points', ...
	'Position',[0.09 0.04952380952380953 0.8 0.8], ...
	'Tag','Fig1', ...
	'ToolBar','none');
h1 = uicontrol('Parent',h0, ...
	'Units','normalized', ...
	'BackgroundColor',[1 1 0.501960784313725], ...
	'ListboxTop',0, ...
	'Position',[0.3284493284493285 0.04715447154471544 0.4932844932844932 0.09593495934959348], ...
	'Style','frame', ...
	'Tag','Frame1');
h1 = uicontrol('Parent',h0, ...
	'Units','normalized', ...
	'BackgroundColor',[1 0 0], ...
	'Callback','rlcparallel', ...
	'FontSize',10, ...
	'FontWeight','bold', ...
	'ForegroundColor',[0 0 0.627450980392157], ...
	'ListboxTop',0, ...
	'Position',[0.3401785714285714 0.05952380952380953 0.1794642857142857 0.06785714285714287], ...
	'String','Parallel Circuit', ...
	'Tag','Pushbutton1', ...
	'TooltipString','Parallel circuit response');
h1 = uicontrol('Parent',h0, ...
	'Units','normalized', ...
	'BackgroundColor',[1 0 0], ...
	'Callback','rlcseries', ...
	'FontSize',10, ...
	'FontWeight','bold', ...
	'ForegroundColor',[0 0 0.627450980392157], ...
	'ListboxTop',0, ...
	'Position',[0.5311355311355309 0.06025293586269195 0.1790123456790123 0.06811201445347785], ...
	'String','Series Circuit', ...
	'Tag','Pushbutton2', ...
	'TooltipString','Series circuit response');
h1 = uicontrol('Parent',h0, ...
	'Units','normalized', ...
	'BackgroundColor',[0 0.501960784313725 1], ...
	'FontName','Script MT Bold', ...
	'FontSize',14, ...
	'ForegroundColor',[1 0 0], ...
	'ListboxTop',0, ...
	'Position',mat1, ...
	'String','    Hadi Saadat', ...
	'Style','text', ...
	'Tag','StaticText7', ...
	'TooltipString','www.msoe.edu/~saadat');
h1 = uicontrol('Parent',h0, ...
	'Units','normalized', ...
	'BackgroundColor',[1 0 0], ...
	'FontName','Agaramond', ...
	'FontSize',16, ...
	'FontWeight','demi', ...
	'ForegroundColor',[1 1 1], ...
	'HorizontalAlignment','left', ...
	'ListboxTop',0, ...
	'Max',0, ...
	'Position',[0.06227106227106227 0.04552845528455284 0.0525030525030525 0.04715447154471544], ...
	'String','OE', ...
	'Style','text', ...
	'Tag','StaticText5', ...
	'TooltipString','Milwaukee School of Engineering');
h1 = uicontrol('Parent',h0, ...
	'Units','normalized', ...
	'BackgroundColor',[1 0 0], ...
	'FontName','Agaramond', ...
	'FontSize',16, ...
	'FontWeight','demi', ...
	'ForegroundColor',[1 1 1], ...
	'HorizontalAlignment','left', ...
	'ListboxTop',0, ...
	'Position',[0.06227106227106227 0.08943089430894309 0.0525030525030525 0.05203252032520326], ...
	'String','MS', ...
	'Style','text', ...
	'Tag','StaticText5', ...
	'TooltipString','Milwuakee School of Engineering');
h1 = uicontrol('Parent',h0, ...
	'Units','normalized', ...
	'BackgroundColor',[1 0 0], ...
	'Callback','close(gcbf)', ...
	'FontSize',10, ...
	'FontWeight','bold', ...
	'ForegroundColor',[0 0 0.627450980392157], ...
	'ListboxTop',0, ...
	'Position',[0.7219508886175551 0.06025293586269195 0.08262108262108259 0.06811201445347785], ...
	'String','Exit', ...
	'Tag','Pushbutton3', ...
	'TooltipString','Exit');
h1 = uicontrol('Parent',h0, ...
	'Units','normalized', ...
	'BackgroundColor',[0 0.501960784313725 1], ...
	'FontSize',9, ...
	'FontWeight','bold', ...
	'ForegroundColor',[1 0 0], ...
	'HorizontalAlignment','left', ...
	'ListboxTop',0, ...
	'Position',[0.1233211233211233 0.09105691056910568 0.0293040293040293 0.04390243902439023], ...
	'String','(c)', ...
	'Style','text', ...
	'Tag','StaticText6', ...
	'TooltipString','Copyright 1999');
h1 = axes('Parent',h0, ...
	'Box','on', ...
	'CameraUpVector',[0 1 0], ...
	'CameraUpVectorMode','manual', ...
	'Color',[1 1 1], ...
	'ColorOrder',mat2, ...
	'HitTest','off', ...
	'Position',[0.0702 0.1385 0.876 0.7662], ...
	'Tag','Axes1', ...
	'Visible','off', ...
	'XColor',[0 0 0], ...
	'XLim',[0 4], ...
	'XLimMode','manual', ...
	'YColor',[0 0 0], ...
	'YLim',[-3.5 1.5], ...
	'YLimMode','manual', ...
	'ZColor',[0 0 0]);
h2 = line('Parent',h1, ...
	'Color',[0 0 1], ...
	'EraseMode','none', ...
	'Tag','Axes1Line18', ...
	'XData',[0.2 0.2 1.1 1.1], ...
	'YData',[0.6 1 1 0.55]);
h2 = line('Parent',h1, ...
	'Color',[0 0 1], ...
	'EraseMode','none', ...
	'Tag','Axes1Line17', ...
	'XData',[0.2 0.2 1.1 1.1], ...
	'YData',[0.4 0 0 0.45]);
h2 = line('Parent',h1, ...
	'Color',[0 0 1], ...
	'Tag','Axes1Line16', ...
	'XData',mat3, ...
	'YData',mat4);
h2 = line('Parent',h1, ...
	'Color',[0 0 1], ...
	'Tag','Axes1Line15', ...
	'XData',mat5, ...
	'YData',mat6);
h2 = line('Parent',h1, ...
	'Color',[0 0 1], ...
	'Tag','Axes1Line14', ...
	'XData',mat7, ...
	'YData',mat8);
h2 = line('Parent',h1, ...
	'Color',[0 0 1], ...
	'Tag','Axes1Line13', ...
	'XData',[0.8 0.8], ...
	'YData',[0 0.3]);
h2 = line('Parent',h1, ...
	'Color',[0 0 1], ...
	'Tag','Axes1Line12', ...
	'XData',[0.8 0.8], ...
	'YData',[0.7 1]);
h2 = line('Parent',h1, ...
	'Color',[0 0 1], ...
	'Tag','Axes1Line11', ...
	'XData',[1.05 1.15], ...
	'YData',[0.45 0.45]);
h2 = line('Parent',h1, ...
	'Color',[0 0 1], ...
	'Tag','Axes1Line10', ...
	'XData',[1.05 1.15], ...
	'YData',[0.55 0.55]);
h2 = text('Parent',h1, ...
	'Color',[0 0 0], ...
	'HandleVisibility','off', ...
	'HorizontalAlignment','center', ...
	'Position',[1.995918367346939 1.55443234836703 17.32050807568877], ...
	'Tag','Axes1Text56', ...
	'VerticalAlignment','bottom');
set(get(h2,'Parent'),'Title',h2);
h2 = text('Parent',h1, ...
	'Color',[0 0 0.502], ...
	'FontSize',9, ...
	'Position',[0.025 0.5 0], ...
	'String','I_s', ...
	'Tag','Axes1Text55');
h2 = text('Parent',h1, ...
	'Color',[0 0 0.502], ...
	'FontSize',9, ...
	'Position',[0.375 0.5 0], ...
	'String','R', ...
	'Tag','Axes1Text54');
h2 = text('Parent',h1, ...
	'Color',[0 0 0.502], ...
	'FontSize',9, ...
	'Position',[0.75 0.5 0], ...
	'String','L', ...
	'Tag','Axes1Text53');
h2 = text('Parent',h1, ...
	'Color',[0 0 0.502], ...
	'FontSize',9, ...
	'Position',[1.015 0.36 0], ...
	'String','C', ...
	'Tag','Axes1Text52');
h2 = text('Parent',h1, ...
	'Color',[0 0 0.502], ...
	'FontSize',9, ...
	'Position',[0.425 0.825 0], ...
	'String','\downarrow', ...
	'Tag','Axes1Text51');
h2 = text('Parent',h1, ...
	'Color',[0 0 0.502], ...
	'FontSize',9, ...
	'Position',[0.725 0.825 0], ...
	'String','\downarrow', ...
	'Tag','Axes1Text50');
h2 = text('Parent',h1, ...
	'Color',[0 0 0.502], ...
	'FontSize',9, ...
	'Position',[1.025 0.825 0], ...
	'String','\downarrow', ...
	'Tag','Axes1Text49');
h2 = text('Parent',h1, ...
	'Color',[0 0 0.502], ...
	'FontSize',9, ...
	'Position',[0.175 0.485 0], ...
	'String','\uparrow', ...
	'Tag','Axes1Text48');
h2 = text('Parent',h1, ...
	'Color',[1 0 0], ...
	'Position',[0.725 0.65 0], ...
	'String','\downarrow', ...
	'Tag','Axes1Text47');
h2 = text('Parent',h1, ...
	'Color',[1 0 0], ...
	'FontSize',9, ...
	'Position',[0.65 0.65 0], ...
	'String','I_0', ...
	'Tag','Axes1Text46');
h2 = text('Parent',h1, ...
	'Color',[1 0 0], ...
	'FontSize',9, ...
	'Position',[0.925 0.5 0], ...
	'String','V_0', ...
	'Tag','Axes1Text45');
h2 = text('Parent',h1, ...
	'Color',[1 0 0], ...
	'FontSize',9, ...
	'Position',[0.925 0.725 0], ...
	'String','+', ...
	'Tag','Axes1Text44');
h2 = text('Parent',h1, ...
	'Color',[1 0 0], ...
	'FontSize',9, ...
	'Position',[0.925 0.35 0], ...
	'String','-', ...
	'Tag','Axes1Text43');
h2 = text('Parent',h1, ...
	'Color',[0 0 0.502], ...
	'FontSize',9, ...
	'Position',[1.2 0.5 0], ...
	'String','v', ...
	'Tag','Axes1Text42');
h2 = text('Parent',h1, ...
	'Color',[0 0 0.502], ...
	'FontSize',9, ...
	'Position',[1.15 0.9 0], ...
	'String','+', ...
	'Tag','Axes1Text41');
h2 = text('Parent',h1, ...
	'Color',[0 0 0.502], ...
	'FontSize',9, ...
	'Position',[1.15 0.1 0], ...
	'String','-', ...
	'Tag','Axes1Text40');
h2 = text('Parent',h1, ...
	'Color',[0 0 0.502], ...
	'FontSize',9, ...
	'Position',[0.35 0.9 0], ...
	'String','i_R', ...
	'Tag','Axes1Text39');
h2 = text('Parent',h1, ...
	'Color',[0 0 0.502], ...
	'FontSize',9, ...
	'Position',[0.65 0.9 0], ...
	'String','i_L', ...
	'Tag','Axes1Text38');
h2 = text('Parent',h1, ...
	'Color',[0 0 0.502], ...
	'FontSize',9, ...
	'Position',[0.95 0.9 0], ...
	'String','i_C', ...
	'Tag','Axes1Text37');
h2 = line('Parent',h1, ...
	'Color',[0 0 1], ...
	'EraseMode','none', ...
	'Tag','Axes1Line9', ...
	'XData',mat9, ...
	'YData',mat10);
h2 = line('Parent',h1, ...
	'Color',[0 0 1], ...
	'EraseMode','none', ...
	'Tag','Axes1Line8', ...
	'XData',[2.2 2.2 3.1 3.1], ...
	'YData',[0.4 0 0 0.45]);
h2 = line('Parent',h1, ...
	'Color',[0 0 1], ...
	'Tag','Axes1Line7', ...
	'XData',mat11, ...
	'YData',mat12);
h2 = line('Parent',h1, ...
	'Color',[0 0 1], ...
	'Tag','Axes1Line6', ...
	'XData',mat13, ...
	'YData',mat14);
h2 = line('Parent',h1, ...
	'Color',[0 0 1], ...
	'Tag','Axes1Line5', ...
	'XData',mat15, ...
	'YData',mat16);
h2 = line('Parent',h1, ...
	'Color',[0 0 1], ...
	'Tag','Axes1Line4', ...
	'XData',mat17, ...
	'YData',mat18);
h2 = line('Parent',h1, ...
	'Color',[0 0 1], ...
	'Tag','Axes1Line3', ...
	'XData',[3 3.1 3.1], ...
	'YData',[1 1 0.55]);
h2 = line('Parent',h1, ...
	'Color',[0 0 1], ...
	'Tag','Axes1Line2', ...
	'XData',[3.05 3.15], ...
	'YData',[0.45 0.45]);
h2 = line('Parent',h1, ...
	'Color',[0 0 1], ...
	'Tag','Axes1Line1', ...
	'XData',[3.05 3.15], ...
	'YData',[0.55 0.55]);
h2 = text('Parent',h1, ...
	'Color',[0 0 0.502], ...
	'FontSize',9, ...
	'Position',[2 0.5 0], ...
	'String','V_s', ...
	'Tag','Axes1Text36');
h2 = text('Parent',h1, ...
	'Color',[0 0 0.502], ...
	'FontSize',9, ...
	'Position',[2.375 1.15 0], ...
	'String','R', ...
	'Tag','Axes1Text35');
h2 = text('Parent',h1, ...
	'Color',[0 0 0.502], ...
	'FontSize',9, ...
	'Position',[2.75 1.15 0], ...
	'String','L', ...
	'Tag','Axes1Text34');
h2 = text('Parent',h1, ...
	'Color',[0 0 0.502], ...
	'FontSize',9, ...
	'Position',[3.025 0.35 0], ...
	'String','C', ...
	'Tag','Axes1Text33');
h2 = text('Parent',h1, ...
	'Color',[0 0 0.502], ...
	'FontSize',9, ...
	'Position',[2.6 1.1 0], ...
	'String','\rightarrow', ...
	'Tag','Axes1Text32');
h2 = text('Parent',h1, ...
	'Color',[0 0 0.502], ...
	'FontSize',9, ...
	'Position',[2.175 0.5 0], ...
	'String','\pm', ...
	'Tag','Axes1Text31');
h2 = text('Parent',h1, ...
	'Color',[1 0 0], ...
	'Position',[2.875 1.125 0], ...
	'String','\rightarrow', ...
	'Tag','Axes1Text30');
h2 = text('Parent',h1, ...
	'Color',[1 0 0], ...
	'FontSize',9, ...
	'Position',[2.85 1.275 0], ...
	'String','I_0', ...
	'Tag','Axes1Text29');
h2 = text('Parent',h1, ...
	'Color',[1 0 0], ...
	'FontSize',9, ...
	'Position',[2.9 0.5 0], ...
	'String','V_0', ...
	'Tag','Axes1Text28');
h2 = text('Parent',h1, ...
	'Color',[1 0 0], ...
	'FontSize',9, ...
	'Position',[2.95 0.725 0], ...
	'String','+', ...
	'Tag','Axes1Text27');
h2 = text('Parent',h1, ...
	'Color',[1 0 0], ...
	'FontSize',9, ...
	'Position',[2.95 0.3 0], ...
	'String','-', ...
	'Tag','Axes1Text26');
h2 = text('Parent',h1, ...
	'Color',[0 0 0.502], ...
	'FontSize',9, ...
	'Position',[3.175 0.5 0], ...
	'String','v_C', ...
	'Tag','Axes1Text25');
h2 = text('Parent',h1, ...
	'Color',[0 0 0.502], ...
	'FontSize',9, ...
	'Position',[3.15 0.9 0], ...
	'String','+', ...
	'Tag','Axes1Text24');
h2 = text('Parent',h1, ...
	'Color',[0 0 0.502], ...
	'FontSize',9, ...
	'Position',[3.15 0.1 0], ...
	'String','-', ...
	'Tag','Axes1Text23');
h2 = text('Parent',h1, ...
	'Color',[0 0 0.502], ...
	'FontSize',9, ...
	'Position',[2.425 0.85 0], ...
	'String','v_R', ...
	'Tag','Axes1Text22');
h2 = text('Parent',h1, ...
	'Color',[0 0 0.502], ...
	'FontSize',9, ...
	'Position',[2.3 0.875 0], ...
	'String','+', ...
	'Tag','Axes1Text21');
h2 = text('Parent',h1, ...
	'Color',[0 0 0.502], ...
	'FontSize',9, ...
	'Position',[2.55 0.875 0], ...
	'String','-', ...
	'Tag','Axes1Text20');
h2 = text('Parent',h1, ...
	'Color',[0 0 0.502], ...
	'FontSize',9, ...
	'Position',[2.625 1.2 0], ...
	'String','i', ...
	'Tag','Axes1Text19');
h2 = text('Parent',h1, ...
	'Color',[0 0 0.502], ...
	'FontSize',9, ...
	'Position',[2.825 0.85 0], ...
	'String','v_L', ...
	'Tag','Axes1Text18');
h2 = text('Parent',h1, ...
	'Color',[0 0 0.502], ...
	'FontSize',9, ...
	'Position',[2.7 0.875 0], ...
	'String','+', ...
	'Tag','Axes1Text17');
h2 = text('Parent',h1, ...
	'Color',[0 0 0.502], ...
	'FontSize',9, ...
	'Position',[2.95 0.875 0], ...
	'String','-', ...
	'Tag','Axes1Text16');
h2 = text('Parent',h1, ...
	'Color',[0 0 0.502], ...
	'FontSize',14, ...
	'Position',[0.5 1.95 0], ...
	'String',mat19, ...
	'Tag','Axes1Text15');
h2 = text('Parent',h1, ...
	'Color',[0 0 0.502], ...
	'FontSize',9, ...
	'Position',[0 -0.25 0], ...
	'String',mat20, ...
	'Tag','Axes1Text14');
h2 = text('Parent',h1, ...
	'Color',[0 0 0.502], ...
	'FontSize',9, ...
	'Position',[0 1.5 0], ...
	'String',mat21, ...
	'Tag','Axes1Text13');
h2 = text('Parent',h1, ...
	'Color',[0 0 0.502], ...
	'FontSize',9, ...
	'Position',[0 -0.525 0], ...
	'String',mat22, ...
	'Tag','Axes1Text12');
h2 = text('Parent',h1, ...
	'Color',[0 0 0.502], ...
	'FontSize',9, ...
	'Position',[0 -0.775 0], ...
	'String',mat23, ...
	'Tag','Axes1Text11');
h2 = text('Parent',h1, ...
	'Color',[0 0 0.502], ...
	'FontSize',9, ...
	'Position',[0 -1 0], ...
	'String',mat24, ...
	'Tag','Axes1Text10');
h2 = text('Parent',h1, ...
	'Color',[0 0 0.502], ...
	'FontSize',9, ...
	'Position',[0 -1.25 0], ...
	'String',mat25, ...
	'Tag','Axes1Text9');
h2 = text('Parent',h1, ...
	'Color',[0 0 0.502], ...
	'FontSize',9, ...
	'Position',[0 -1.65 0], ...
	'String',mat26, ...
	'Tag','Axes1Text8');
h2 = text('Parent',h1, ...
	'Color',[0 0 0.502], ...
	'FontSize',9, ...
	'Position',[0 -1.95 0], ...
	'String',mat27, ...
	'Tag','Axes1Text7');
h2 = text('Parent',h1, ...
	'Color',[0 0 0.502], ...
	'FontSize',9, ...
	'Position',[0 -2.175 0], ...
	'String',mat28, ...
	'Tag','Axes1Text6');
h2 = text('Parent',h1, ...
	'Color',[0 0 0.502], ...
	'FontSize',9, ...
	'Position',[0 -2.35 0], ...
	'String',mat29, ...
	'Tag','Axes1Text5');
h2 = text('Parent',h1, ...
	'Color',[1 0 0.502], ...
	'FontName','Roman', ...
	'FontSize',11, ...
	'Position',[0 -2.95 0], ...
	'String',mat30, ...
	'Tag','Axes1Text4');
h2 = text('Parent',h1, ...
	'Color',[0 0 0], ...
	'HandleVisibility','off', ...
	'HorizontalAlignment','center', ...
	'Position',[1.995918367346939 -3.686625194401245 17.32050807568877], ...
	'Tag','Axes1Text3', ...
	'VerticalAlignment','cap', ...
	'Visible','off');
set(get(h2,'Parent'),'XLabel',h2);
h2 = text('Parent',h1, ...
	'Color',[0 0 0], ...
	'HandleVisibility','off', ...
	'HorizontalAlignment','center', ...
	'Position',[-0.1346938775510204 -1.011664074650078 17.32050807568877], ...
	'Rotation',90, ...
	'Tag','Axes1Text2', ...
	'VerticalAlignment','baseline', ...
	'Visible','off');
set(get(h2,'Parent'),'YLabel',h2);
h2 = text('Parent',h1, ...
	'Color',[0 0 0], ...
	'HandleVisibility','off', ...
	'HorizontalAlignment','right', ...
	'Position',[-0.326530612244898 2.114307931570762 17.32050807568877], ...
	'Tag','Axes1Text1', ...
	'Visible','off');
set(get(h2,'Parent'),'ZLabel',h2);
if nargout > 0, fig = h0; end


function tagS = code_sequence_macro_tags
%"code_sequence_macro_tags"
%   Returns the tags associated with a code sequence, specified by section
%   8.8 in PS3.3 of 2006 DICOM.
%
%WARNING: The types of the tags specified in this function DO NOT MATCH the
%DICOM specification, since Type 1C and 2C elements whose only condition
%for existance is that the sequence is present have already had that
%requirement implicitly met; hence they are changed to Type 1 and 2
%respectively.
%
%JRA 06/06/06
%
%Usage:
%   tagS = code_sequence_macro_tags
%
% 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/>.

% Define tags
tagsC = {'00080100','00080102','00080103','00080104','0008010F','00080105',...
    '00080106','0008010B','00080107','0008010D'};
tagDecC = {524544, 524546, 524547, 524548, 524559, 524549, 524550,...
    524555, 524551, 524557};
% Define tag type
tagTypeC = {'1','1','1C','1','3','1C','1C','3','1C','1C'};

% Define children
childC = {[],[],[],[],[],[],[],[],[],[]};

tagS = struct('tag', tagsC, 'tagdec', tagDecC, 'type', tagTypeC, 'children', childC);

% %Initialize the tagS structure.
% tagS = struct('tag', {}, 'type', {}, 'children', {]);
%
% %Add tags based on PS3.3 attribute lists.
%
% %Code Value
% tagS(end+1) = struct('tag', ['00080100'], 'type', ['1'], 'children', []);
%
% %Coding Scheme Designator
% tagS(end+1) = struct('tag', ['00080102'], 'type', ['1'], 'children', []);
%
% %Coding Scheme Version
% tagS(end+1) = struct('tag', ['00080103'], 'type', ['1C'], 'children', []);
%
% %Code Meaning
% tagS(end+1) = struct('tag', ['00080104'], 'type', ['1'], 'children', []);
%
% %Context Identifer
% tagS(end+1) = struct('tag', ['0008010F'], 'type', ['3'], 'children', []);
%
% %Mapping Resource
% tagS(end+1) = struct('tag', ['00080105'], 'type', ['1C'], 'children', []);
%
% %Context Group Version
% tagS(end+1) = struct('tag', ['00080106'], 'type', ['1C'], 'children', []);
%
% %Context Group Extension Flag
% tagS(end+1) = struct('tag', ['0008010B'], 'type', ['3'], 'children', []);
%
% %Context Group Local Version
% tagS(end+1) = struct('tag', ['00080107'], 'type', ['1C'], 'children', []);
%
% %Context Group Extension Creator UID
% tagS(end+1) = struct('tag', ['0008010D'], 'type', ['1C'], 'children', []);


function string = user_string(string_name, string)
%USER_STRING  Get/set a user specific string
%
% Examples:
%   string  = user_string(string_name)
%   isSaved = user_string(string_name, new_string)
%
% Function to get and set a string in a system or user specific file. This
% enables, for example, system specific paths to binaries to be saved.
%
% The specified string will be saved in a file named <string_name>.txt,
% either in a subfolder named .ignore under this file's folder, or in the
% user's prefdir folder (in case this file's folder is non-writable).
%
% IN:
%   string_name - String containing the name of the string required, which
%                 sets the filename storing the string: <string_name>.txt
%   new_string  - The new string to be saved in the <string_name>.txt file
%
% OUT:
%   string  - The currently saved string. Default: ''
%   isSaved - Boolean indicating whether the save was succesful

% Copyright (C) Oliver Woodford 2011-2014, Yair Altman 2015-

% This method of saving paths avoids changing .m files which might be in a
% version control system. Instead it saves the user dependent paths in
% separate files with a .txt extension, which need not be checked in to
% the version control system. Thank you to Jonas Dorn for suggesting this
% approach.

% 10/01/2013 - Access files in text, not binary mode, as latter can cause
%              errors. Thanks to Christian for pointing this out.
% 29/05/2015 - Save file in prefdir if current folder is non-writable (issue #74)
% 09/01/2018 - Fix issue #232: if the string looks like a file/folder path, ensure it actually exists

    if ~ischar(string_name)
        error('string_name must be a string.');
    end
    % Create the full filename
    fname = [string_name '.txt'];
    dname = fullfile(fileparts(mfilename('fullpath')), '.ignore');
    file_name = fullfile(dname, fname);
    if nargin > 1
        % Set string
        if ~ischar(string)
            error('new_string must be a string.');
        end
        % Make sure the save directory exists
        %dname = fileparts(file_name);
        if ~exist(dname, 'dir')
            % Create the directory
            try
                if ~mkdir(dname)
                    string = false;
                    return
                end
            catch
                string = false;
                return
            end
            % Make it hidden
            try
                fileattrib(dname, '+h');
            catch
            end
        end
        % Write the file
        fid = fopen(file_name, 'wt');
        if fid == -1
            % file cannot be created/updated - use prefdir if file does not already exist
            % (if file exists but is simply not writable, don't create a duplicate in prefdir)
            if ~exist(file_name,'file')
                file_name = fullfile(prefdir, fname);
                fid = fopen(file_name, 'wt');
            end
            if fid == -1
                string = false;
                return;
            end
        end
        try
            fprintf(fid, '%s', string);
        catch
            fclose(fid);
            string = false;
            return
        end
        fclose(fid);
        string = true;
    else
        % Get string
        fid = fopen(file_name, 'rt');
        if fid == -1
            % file cannot be read, try to read the file in prefdir
            file_name = fullfile(prefdir, fname);
            fid = fopen(file_name, 'rt');
            if fid == -1
                string = '';
                return
            end
        end
        string = fgetl(fid);
        fclose(fid);

        % Fix issue #232: if the string looks like a file/folder path, ensure it actually exists
        if ~isempty(string) && any(string=='\' | string=='/') && ~exist(string) %#ok<EXIST>
            string = '';
        end
    end
end


%PARSEOPT Parse options.
%
%   [ GOT, VAL ] = PARSEOPT( COPTDEF, VARARGIN ) parses the property/value pairs
%   in VARARGIN, and adds the default options in the second column of
%   COPTDEF. The first column of COPTDEF contains strings of the field names.
%   Returns the got/val structs.

% Copyright 2013-2022 Precise Simulation, Ltd.


function value = cast_value_to_type(type,value,cls) %#ok<INUSD>
% Internal function for GUI parameter casting.

if isstruct(type)
    type = PropertyType(type.PrimitiveType,type.Shape,type.Domain); end

validateattributes(type, {'PropertyType'}, {'scalar'});
assert(type.CanAccept(value), ...
    'PropertyGridField:InvalidOperation', ...
    'Setting type "%s" would invalidate current property value.', char(type));
value = type.ConvertFromMatLab(value);


function batch_anonymize_CERR_plans(varargin)
%function batch_anonymize_CERR_plans(varargin)
%
%Type "function batch_anonymize_CERR_plans(varargin)" (without quotes) in Command window to run batch conversion. User will be
%prompted to select source and destination directories. This function anonymizes CERR plans under sourceDir and subdirectories
%and places them in destinationDir.
%
%APA, 10/05/2010
%
% 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/>.

% Example-run
% sourceDir = 'J:\bioruser\apte\batch code';
% destinationDir = 'J:\bioruser\apte\batch code\OUT';
% batchConvert(sourceDir,destinationDir)

feature accel off

anonymize_file_name_flag = 1; % 1:anonymize file name with research number, 0: retain file name.
researchNumber = 1000; %naming will start with this number + 3.
replacementName = 'LungDoseResponse';

persistent convertedC planNameC
if isempty(varargin)
    %init_ML_DICOM
    convertedC = {'Source Directory:'};
    planNameC = {'Converted Plan Name:'};
    researchNumberC = {'MedPhys Research Number:'};
    sourceDir = uigetdir(cd, 'Select Source directory');
    if isnumeric(sourceDir)
        return;
    end
    destinationDir = uigetdir(cd, 'Select Destination directory');
    if isnumeric(destinationDir)
        return;
    end
else
    convertedC = {'Source Directory:'};
    planNameC = {'Converted Plan Name:'};
    researchNumberC = {'MedPhys Research Number:'};
    sourceDir = varargin{1};
    destinationDir = varargin{2};
end

if ispc
    slashType = '\';
else
    slashType = '/';
end
if strcmpi(sourceDir(end),slashType)
    sourceDir(end) = [];
end
slashIndex = strfind(sourceDir,slashType);
allDirS = dir(sourceDir);
for dirNum = 1:length(allDirS)
    researchNumber = researchNumber + 1;
    [pathStr,nameStr,extStr] = fileparts(allDirS(dirNum).name);
    [pathStr,nameStr,extStr2] = fileparts(nameStr);
    if ~allDirS(dirNum).isdir && (strcmpi(extStr,'.bz2') || strcmpi(extStr,'.mat')) && ~ismember(sourceDir,convertedC)

        if ~strcmpi(sourceDir(end),slashType)
            sourceDir = [sourceDir,slashType];
        end

        fileName = fullfile(sourceDir, allDirS(dirNum).name);

        try

            disp(['Converting ',fileName,' ...'])
            planC = loadPlanC(fileName, tempdir);

            %Anonymize
            PHI = {'studyNumberOfOrigin','PatientName','caseNumber','archive','PatientID','scanDate','DICOMHeaders'};

            if ~isempty(replacementName)

                for i = 1 : length(PHI)
                    str = PHI{i};
                    %planC = anonymize(planC,str,replacementName);
                    planC = anonCERRplanC(planC);
                end

            end

            %Check for duplicate name of sourceDirName
            if anonymize_file_name_flag
                newFileName = [num2str(researchNumber),extStr];
            else
                sourceDirName = sourceDir;
                dirOut = dir(destinationDir);
                allOutNames = {dirOut.name};
                newFileName = allDirS(dirNum).name;
                indexSlash = 1;
                while indexSlash~=length(slashIndex) && any(strcmpi(newFileName, allOutNames))
                    newFileName = [sourceDirName,'_',newFileName];
                    sourceDirName = sourceDir(slashIndex(end-indexSlash)+1:end);
                    sourceDirName(strfind(sourceDirName,slashType)) = deal('_');
                    indexSlash = indexSlash + 1;
                end
                if any(strcmpi(newFileName,allOutNames))
                    newFileName = [newFileName,'duplicate_',num2str(rand(1)),extStr2,extStr];
                end
            end

            %save_planC(planC,[], 'passed', fullfile(destinationDir,[sourceDirName,'.mat.bz2']));
            save_planC(planC,[], 'passed', fullfile(destinationDir,newFileName));

            clear planC
            convertedC{end+1} = fileName;
            planNameC{end+1} = newFileName;
            researchNumberC{end+1} = num2str(researchNumber);
        catch
            convertedC{end+1} = fileName;
            planNameC{end+1} = 'NOT CONVERTED';
            researchNumberC{end+1} = num2str(researchNumber);
            disp(['NOT CONVERTED ',fileName,' ...'])
        end

    elseif allDirS(dirNum).isdir && ~strcmp(allDirS(dirNum).name,'.') && ~strcmp(allDirS(dirNum).name,'..')
        batch_anonymize_CERR_plans(fullfile(sourceDir,allDirS(dirNum).name),destinationDir)
    end
end

% Save keys to Excel file
xlswrite(fullfile(destinationDir,'batch_convert_results.xls'),convertedC','Sheet1','A1')
xlswrite(fullfile(destinationDir,'batch_convert_results.xls'),planNameC','Sheet1','B1')
xlswrite(fullfile(destinationDir,'batch_convert_results.xls'),researchNumberC','Sheet1','C1')


function [varargout] = myProcessOptions(options,varargin)
% Similar to processOptions, but case insensitive and
%   using a struct instead of a variable length list

options = toUpper(options);

for i = 1:2:length(varargin)
    if isfield(options,upper(varargin{i}))
        v = getfield(options,upper(varargin{i}));
        if isempty(v)
            varargout{(i+1)/2}=varargin{i+1};
        else
            varargout{(i+1)/2}=v;
        end
    else
        varargout{(i+1)/2}=varargin{i+1};
    end
end

end

function [o] = toUpper(o)
if ~isempty(o)
    fn = fieldnames(o);
    for i = 1:length(fn)
        o = setfield(o,upper(fn{i}),getfield(o,fn{i}));
    end
end
end


function CERRStatusString(str, dispFlag)
%"CERRStatusString"
%   Display a status string in the console and/or in the CERR Gui.
%
%LM:  JOD, 3 Jan 02.
%     JOD, 7 May 03, Changed CERRStatusString format.
%
%   If flag = 'both' or is undefined, status goes to console and CERR
%   GUI.  If flag = 'gui', status goes only to gui.  If flag = 'console'
%   status goes only to console.
%
%Usage:
%   CERRStatusString(str, dispFlag)
%
% 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/>.

global stateS

%Check options to see if StatusString should be muted, only display to the GUI.
if isempty(stateS)
    optS = opts4Exe([getCERRPath,'CERROptions.json']);
elseif isfield(stateS, 'optS')
    optS = stateS.optS;
else
    optS = [];
end

if ~isempty(optS) && isfield(optS, 'CERRStatusStringEnabled')
    if ~optS.CERRStatusStringEnabled
        dispFlag = 'gui';
    end
end

if ~exist('dispFlag','var')
    dispFlag = 'both';
end

if ishandle(1)
    g = gcf;
end

%Also write non-empty strings to the matlab console:
%if strcmpi(dispFlag, 'both') || strcmpi(dispFlag, 'console')
if any(ismember(lower(dispFlag),{'both','console'}))
    if ~strcmp(str,'')
        disp(['CERR>>  ' str])
    end
end

h = [];
%try
if ~isempty(stateS) && isfield(stateS,'handle') && ...
        isfield(stateS.handle,'CERRSliceViewer') && ishandle(stateS.handle.CERRSliceViewer)
    h = stateS.handle.CERRSliceViewer;
end
%end

if ishandle(h)
    set(0,'CurrentFigure',h);

    %if strcmpi(dispFlag, 'both') || strcmpi(dispFlag, 'gui')
    if any(ismember(lower(dispFlag),{'both','gui'}))
        %try
            set(stateS.handle.CERRStatus,'string',str)
        %    drawnow
        %end

        %return to old figure
        if ishandle(1)
            set(0,'CurrentFigure',g);
        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'};
end


function au_qmr_ilu_s_d(p)
%
%  Deletes the global data that has been generated by 'au_qmr_ilu_s_i'
%  or 'au_qmr_ilu_s'.
%
%  Calling sequence:
%
%    au_qmr_ilu_s_d
%
%  Input:
%
%    p         vector containing the ADI shift parameters.
%
%
%  LYAPACK 1.0 (Thilo Penzl, August 1999)

l = length(p);

                     % Delete them regardless if they have been
                     % created at all.
for i = 1:l

  eval(lp_e( 'global LP_L',i,' LP_U',i ));

  eval(lp_e( 'clear global LP_L',i,' LP_U',i ));

end

global LP_P
clear global LP_P