classdef MimDatasetStackItem < handle
    % MimDatasetStackItem. Part of the internal framework of the TD MIM Toolkit.
    %
    %     You should not use this class within your own code. It is intended to
    %     be used internally within the framework of the TD MIM Toolkit.
    %
    %     Used to store the dependency information of a plugin as it is being
    %     build up during execution. MimDatasetStackItem are created
    %     temporarily by the class MimDatasetStack and used to build up the
    %     dependency list. See MimDatasetStack for more information.
    %
    %
    %     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 (SetAccess = private)
        InstanceIdentifier     % A unique identifier for this plugin result
        IgnoreDependencyChecks % Certain types of plugin do not cached their results and so are exempt from dependency checking
        DependencyList         % Current list of plugin results this plugin depends on
        IsEdited
        IsManual
        IsMarkerSet
        Schema                 % The disk cache version
    end

    properties (SetAccess = private, Transient = true)
        ExecutionTimer         % Times the execution time for this plugin
    end

    properties (Access = private, Transient)
        DiskCacheSchema = '0.1'
    end

    methods
        function obj = MimDatasetStackItem(instance_id, dependency_list, ignore_dependency_checks, start_timer, reporting)
            if nargin > 0
                if ~isa(instance_id, 'PTKDependency')
                    reporting.Error('MimDatasetStackItem:BadInstanceID', 'instance_id must be a PTKDependency object');
                end

                if ~isa(dependency_list, 'PTKDependencyList')
                    reporting.Error('MimDatasetStackItem:BadDependencyList', 'dependency_list must be a PTKDependencyList object');
                end

                obj.InstanceIdentifier = instance_id;
                obj.DependencyList = dependency_list;
                obj.IgnoreDependencyChecks = ignore_dependency_checks;
                obj.Schema = obj.DiskCacheSchema;
                obj.IsEdited = false;
                obj.IsManual = false;
                obj.IsMarkerSet = false;

                if start_timer
                    obj.ExecutionTimer = MimTimer(reporting);
                    obj.ExecutionTimer.Start;
                end
            end
        end

        function AddDependencies(obj, dependencies, reporting)
            % Adds more plugin result which this particular plugin result depends on.

            obj.DependencyList.AddDependenciesList(dependencies, reporting);
        end

        function StopAndDeleteTimer(obj)
            if ~isempty(obj.ExecutionTimer)
                obj.ExecutionTimer.Stop;
                obj.InstanceIdentifier.Attributes.ExecutionTime = obj.ExecutionTimer.TotalElapsedTime;
                obj.InstanceIdentifier.Attributes.SelfTime = obj.ExecutionTimer.SelfTime;
                obj.ExecutionTimer = [];
            end
        end

        function MarkEdited(obj)
            obj.IsEdited = true;
        end

        function MarkManual(obj)
            obj.IsManual = true;
        end

        function MarkMarkerSet(obj)
            obj.IsMarkerSet = true;
        end
    end

    methods (Static)
        function obj = loadobj(a)
            % This method is called when the object is loaded from disk.

            if isa(a, 'MimDatasetStackItem')
                obj = a;
            else
                % In the case of a load error, loadobj() gives a struct
                obj = MimDatasetStackItem;
                for field = fieldnames(a)'
                    if isprop(obj, field{1})
                        mp = findprop(obj, (field{1}));
                        if (~mp.Constant) && (~mp.Dependent) && (~mp.Abstract)
                            obj.(field{1}) = a.(field{1});
                        end
                    end
                end
            end

        end
    end
end


%% Classes representing Tensors
%
%%
%


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

% Last Modified by GUIDE v2.5 12-Jan-2021 18:10:17

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

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

    centerUIFigure(hObject);

    refFrame = varargin{1};
    setappdata(hObject, 'refFrame', refFrame);

    lvdData = varargin{2};
    setappdata(hObject, 'lvdData', lvdData);

	populateGUI(handles, lvdData, refFrame);

    % Update handles structure
    guidata(hObject, handles);

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

function populateGUI(handles, lvdData, refFrame)
    set(handles.refFrameNameText,'String',refFrame.getName());

    pointsListBoxStr = lvdData.geometry.points.getListboxStr();
    handles.frameOriginCombo.String = pointsListBoxStr;
    handles.frameOriginCombo.Value = lvdData.geometry.points.getIndsForPoints(refFrame.origin);

    coordSysListBoxStr = lvdData.geometry.coordSyses.getListboxStr();
    handles.coordSysCombo.String = coordSysListBoxStr;
    handles.coordSysCombo.Value = lvdData.geometry.coordSyses.getIndsForCoordSyses(refFrame.coordSys);

    handles.xColorCombo.String = ColorSpecEnum.getListboxStr();
    handles.xColorCombo.Value = ColorSpecEnum.getIndForName(refFrame.xAxisColor.name);

    handles.yColorCombo.String = ColorSpecEnum.getListboxStr();
    handles.yColorCombo.Value = ColorSpecEnum.getIndForName(refFrame.yAxisColor.name);

    handles.zColorCombo.String = ColorSpecEnum.getListboxStr();
    handles.zColorCombo.Value = ColorSpecEnum.getIndForName(refFrame.zAxisColor.name);

    handles.xLineStyleCombo.String = LineSpecEnum.getListboxStr();
    handles.xLineStyleCombo.Value = LineSpecEnum.getIndForName(refFrame.xAxisLineSpec.name);

    handles.yLineStyleCombo.String = LineSpecEnum.getListboxStr();
    handles.yLineStyleCombo.Value = LineSpecEnum.getIndForName(refFrame.yAxisLineSpec.name);

    handles.zLineStyleCombo.String = LineSpecEnum.getListboxStr();
    handles.zLineStyleCombo.Value = LineSpecEnum.getIndForName(refFrame.zAxisLineSpec.name);

    handles.xLineWidthText.String = fullAccNum2Str(refFrame.xAxisLineWidth);
    handles.yLineWidthText.String = fullAccNum2Str(refFrame.yAxisLineWidth);
    handles.zLineWidthText.String = fullAccNum2Str(refFrame.zAxisLineWidth);

    handles.scaleFactorText.String = fullAccNum2Str(refFrame.scaleFactor);

% --- Outputs from this function are returned to the command line.
function varargout = lvd_EditCoordSysOriginRefFrameGUI_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} = false;
    else
        lvdData = getappdata(hObject, 'lvdData');
        refFrame = getappdata(hObject, 'refFrame');

        refFrame.setName(handles.refFrameNameText.String);

        refFrame.origin = lvdData.geometry.points.getPointsForInds(handles.frameOriginCombo.Value);
        refFrame.coordSys = lvdData.geometry.coordSyses.getCoordSysesForInds(handles.coordSysCombo.Value);

        str = handles.xColorCombo.String{handles.xColorCombo.Value};
        refFrame.xAxisColor = ColorSpecEnum.getEnumForListboxStr(str);

        str = handles.xColorCombo.String{handles.yColorCombo.Value};
        refFrame.yAxisColor = ColorSpecEnum.getEnumForListboxStr(str);

        str = handles.xColorCombo.String{handles.zColorCombo.Value};
        refFrame.zAxisColor = ColorSpecEnum.getEnumForListboxStr(str);

        str = handles.xLineStyleCombo.String{handles.xLineStyleCombo.Value};
        refFrame.xAxisLineSpec = LineSpecEnum.getEnumForListboxStr(str);

        str = handles.xLineStyleCombo.String{handles.yLineStyleCombo.Value};
        refFrame.yAxisLineSpec = LineSpecEnum.getEnumForListboxStr(str);

        str = handles.xLineStyleCombo.String{handles.zLineStyleCombo.Value};
        refFrame.zAxisLineSpec = LineSpecEnum.getEnumForListboxStr(str);

        refFrame.xAxisLineWidth = str2double(handles.xLineWidthText.String);
        refFrame.yAxisLineWidth = str2double(handles.yLineWidthText.String);
        refFrame.zAxisLineWidth = str2double(handles.zLineWidthText.String);

        refFrame.scaleFactor = str2double(handles.scaleFactorText.String);

        varargout{1} = true;
        close(handles.lvd_EditCoordSysOriginRefFrameGUI);
    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.lvd_EditCoordSysOriginRefFrameGUI);
    else
        msgbox(errMsg,'Invalid Reference Frame Inputs','error');
    end

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

    if(isempty(strtrim(handles.refFrameNameText.String)))
        errMsg{end+1} = 'Reference frame name must contain more than white space and must not be empty.';
    end

    val = str2double(get(handles.xLineWidthText,'String'));
    enteredStr = get(handles.xLineWidthText,'String');
    numberName = 'X Axis Line Width';
    lb = 0.01;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(val, numberName, lb, ub, isInt, errMsg, enteredStr);

    val = str2double(get(handles.yLineWidthText,'String'));
    enteredStr = get(handles.yLineWidthText,'String');
    numberName = 'Y Axis Line Width';
    lb = 0.01;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(val, numberName, lb, ub, isInt, errMsg, enteredStr);

    val = str2double(get(handles.zLineWidthText,'String'));
    enteredStr = get(handles.zLineWidthText,'String');
    numberName = 'Z Axis Line Width';
    lb = 0.01;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(val, numberName, lb, ub, isInt, errMsg, enteredStr);

    val = str2double(get(handles.scaleFactorText,'String'));
    enteredStr = get(handles.scaleFactorText,'String');
    numberName = 'Axes Scale Factor';
    lb = 0.001;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(val, 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.lvd_EditCoordSysOriginRefFrameGUI);

function refFrameNameText_Callback(hObject, eventdata, handles)
% hObject    handle to refFrameNameText (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 refFrameNameText as text
%        str2double(get(hObject,'String')) returns contents of refFrameNameText as a double

% --- Executes during object creation, after setting all properties.
function refFrameNameText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to refFrameNameText 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 lvd_EditCoordSysOriginRefFrameGUI or any of its controls.
function lvd_EditCoordSysOriginRefFrameGUI_WindowKeyPressFcn(hObject, eventdata, handles)
% hObject    handle to lvd_EditCoordSysOriginRefFrameGUI (see GCBO)
% eventdata  structure with the following fields (see MATLAB.UI.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.lvd_EditCoordSysOriginRefFrameGUI);
    end

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

% --- Executes during object creation, after setting all properties.
function frameOriginCombo_CreateFcn(hObject, eventdata, handles)
% hObject    handle to frameOriginCombo (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 coordSysCombo.
function coordSysCombo_Callback(hObject, eventdata, handles)
% hObject    handle to coordSysCombo (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 coordSysCombo contents as cell array
%        contents{get(hObject,'Value')} returns selected item from coordSysCombo

% --- Executes during object creation, after setting all properties.
function coordSysCombo_CreateFcn(hObject, eventdata, handles)
% hObject    handle to coordSysCombo (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 xColorCombo.
function xColorCombo_Callback(hObject, eventdata, handles)
% hObject    handle to xColorCombo (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 xColorCombo contents as cell array
%        contents{get(hObject,'Value')} returns selected item from xColorCombo

% --- Executes during object creation, after setting all properties.
function xColorCombo_CreateFcn(hObject, eventdata, handles)
% hObject    handle to xColorCombo (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 xLineStyleCombo.
function xLineStyleCombo_Callback(hObject, eventdata, handles)
% hObject    handle to xLineStyleCombo (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 xLineStyleCombo contents as cell array
%        contents{get(hObject,'Value')} returns selected item from xLineStyleCombo

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

function xLineWidthText_Callback(hObject, eventdata, handles)
% hObject    handle to xLineWidthText (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 xLineWidthText as text
%        str2double(get(hObject,'String')) returns contents of xLineWidthText as a double
    newInput = get(hObject,'String');
    newInput = attemptStrEval(newInput);
    set(hObject,'String', newInput);

% --- Executes during object creation, after setting all properties.
function xLineWidthText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to xLineWidthText (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 selection change in yColorCombo.
function yColorCombo_Callback(hObject, eventdata, handles)
% hObject    handle to yColorCombo (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 yColorCombo contents as cell array
%        contents{get(hObject,'Value')} returns selected item from yColorCombo

% --- Executes during object creation, after setting all properties.
function yColorCombo_CreateFcn(hObject, eventdata, handles)
% hObject    handle to yColorCombo (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 yLineStyleCombo.
function yLineStyleCombo_Callback(hObject, eventdata, handles)
% hObject    handle to yLineStyleCombo (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 yLineStyleCombo contents as cell array
%        contents{get(hObject,'Value')} returns selected item from yLineStyleCombo

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

function yLineWidthText_Callback(hObject, eventdata, handles)
% hObject    handle to yLineWidthText (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 yLineWidthText as text
%        str2double(get(hObject,'String')) returns contents of yLineWidthText as a double
    newInput = get(hObject,'String');
    newInput = attemptStrEval(newInput);
    set(hObject,'String', newInput);

% --- Executes during object creation, after setting all properties.
function yLineWidthText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to yLineWidthText (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 selection change in zColorCombo.
function zColorCombo_Callback(hObject, eventdata, handles)
% hObject    handle to zColorCombo (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 zColorCombo contents as cell array
%        contents{get(hObject,'Value')} returns selected item from zColorCombo

% --- Executes during object creation, after setting all properties.
function zColorCombo_CreateFcn(hObject, eventdata, handles)
% hObject    handle to zColorCombo (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 zLineStyleCombo.
function zLineStyleCombo_Callback(hObject, eventdata, handles)
% hObject    handle to zLineStyleCombo (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 zLineStyleCombo contents as cell array
%        contents{get(hObject,'Value')} returns selected item from zLineStyleCombo

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

function zLineWidthText_Callback(hObject, eventdata, handles)
% hObject    handle to zLineWidthText (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 zLineWidthText as text
%        str2double(get(hObject,'String')) returns contents of zLineWidthText as a double
    newInput = get(hObject,'String');
    newInput = attemptStrEval(newInput);
    set(hObject,'String', newInput);

% --- Executes during object creation, after setting all properties.
function zLineWidthText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to zLineWidthText (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 scaleFactorText_Callback(hObject, eventdata, handles)
% hObject    handle to scaleFactorText (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 scaleFactorText as text
%        str2double(get(hObject,'String')) returns contents of scaleFactorText as a double
    newInput = get(hObject,'String');
    newInput = attemptStrEval(newInput);
    set(hObject,'String', newInput);

% --- Executes during object creation, after setting all properties.
function scaleFactorText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to scaleFactorText (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 item = setval(item, val, dflag)

% function item = setval(item, val, dflag)
% set item.val{1} to val. Validity checks are performed through subsasgn.
% If val == {}, set item.val to {}.
% If dflag is true, and item.def is not empty, set the default setting for
% this item instead by calling feval(item.def{:}, val). If val == {}, use
% the string '<UNDEFINED>' as in a harvested tree. If dflag is true, but
% no item.def defined, set item.val{1} instead.
%
% This code is part of a batch job configuration system for MATLAB. See
%      help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging

% Volkmar Glauche
% $Id: setval.m 5678 2013-10-11 14:58:04Z volkmar $

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

if iscell(val) && isempty(val)
    if dflag
        if ~isempty(item.def)
            try
                feval(item.def, {'<UNDEFINED>'});
            catch
                cfg_message('matlabbatch:setval:defaults', ...
                            '%s: unable to set default value.', ...
                            subsasgn_checkstr(item, substruct('.','val')));
            end
        else
            item = subsasgn(item, substruct('.','val'), {});
        end
    else
        item = subsasgn(item, substruct('.','val'), {});
    end
else
    if dflag
        [sts, val1] = subsasgn_check(item, substruct('.','val'), {val});
        if sts
            if ~isempty(item.def)
                try
                    feval(item.def, val1);
                catch
                    cfg_message('matlabbatch:setval:defaults', ...
                                '%s: unable to set default value.', ...
                                subsasgn_checkstr(item, substruct('.','val')));
                end
            else
                item = subsasgn(item, substruct('.','val'), {val});
            end
        end
    else
        item = subsasgn(item, substruct('.','val'), {val});
    end
end


classdef MivGui < MimGuiBase
    % MivGui Main class for the MIV 3D Medical Image Viewer for Matlab
    %
    %     To run MIV, type
    %
    %         miv
    %
    %     at the Matlab command prompt
    %
    %
    %     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.
    %

    methods
        function obj = MivGui(splash_screen)
            obj = obj@MimGuiBase(MivAppDef, splash_screen);
        end
    end
end


function serverStarted = quenchCheckServer(host)
%
%     serverStarted = quenchCheckServer(host)
%
% Author: dakers
% Purpose:
%   Test whether the Quench application has been started.
%
% mrmCheckServer

if(~exist('host','var')||isempty(host)) host = 'localhost:4001'; end

stat = mrMesh(host, 999, 'ping');

% If the status is not -1000, the window opened and the server is there.
% So, close the window and return.
if stat ~= -1000
    serverStarted = 1;
    return;
else
    serverStarted = 0;
end

return;


function  s = strtrim_improve(s0)
%
% strtrim handles only a limited number of whitespace types.
% But does NOT handle 0 for example. This function turns all
% whitespaces including 0 to plain old spaces which strtrim
% does handle.
%
%
s = s0;
s(s<33) = ' ';     % Replace all non-printable chracters with spaces

% Feed the digestable new string to strtrim.
s = strtrim(s);


 function printf(str, varargin)
%function printf(str, varargin)
% shorthand for disp(sprintf())
% note: fprintf() is overloaded to work without a file id, so i could have
% used it instead.  oh well.
% Jeff Fessler
if nargin < 1, ir_usage, end
disp(sprintf(str, varargin{:}))


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

% Last Modified by GUIDE v2.5 02-Dec-2013 19:58:32

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

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

% Update handles structure
guidata(hObject, handles);

%Possible fix for people with display issues.
% checkForCharUnitsInGUI(hObject);

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

% --- Outputs from this function are returned to the command line.
function [dummy, varargout] = departDisplayGUI_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;

dummy{1} = handles.departAxis;
dummy{2} = handles.hyperOrbitText;
dummy{3} = handles.mainOrbitText;
dummy{4} = handles.burnInfoText;
dummy{5} = handles.departDispGUI;
dummy{6} = handles.hyperOrbitLabel;
dummy{7} = handles.transOrbitLabel;
dummy{8} = handles.departureOrbitRadio;

function hyperOrbitText_Callback(hObject, eventdata, handles)
% hObject    handle to hyperOrbitText (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 hyperOrbitText as text
%        str2double(get(hObject,'String')) returns contents of hyperOrbitText as a double

% --- Executes during object creation, after setting all properties.
function hyperOrbitText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to hyperOrbitText (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 burnInfoText_Callback(hObject, eventdata, handles)
% hObject    handle to burnInfoText (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 burnInfoText as text
%        str2double(get(hObject,'String')) returns contents of burnInfoText as a double

% --- Executes during object creation, after setting all properties.
function burnInfoText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to burnInfoText (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 mainOrbitText_Callback(hObject, eventdata, handles)
% hObject    handle to mainOrbitText (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 mainOrbitText as text
%        str2double(get(hObject,'String')) returns contents of mainOrbitText as a double

% --- Executes during object creation, after setting all properties.
function mainOrbitText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to mainOrbitText (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 when selected object is changed in plotDisplayPanel.
function plotDisplayPanel_SelectionChangeFcn(hObject, eventdata, handles)
% hObject    handle to the selected object in plotDisplayPanel
% eventdata  structure with the following fields (see UIBUTTONGROUP)
%	EventName: string 'SelectionChanged' (read only)
%	OldValue: handle of the previously selected object or empty if none was selected
%	NewValue: handle of the currently selected object
% handles    structure with handles and user data (see GUIDATA)
hPlotBtnGrp = findobj(handles.departDispGUI,'Tag','plotDisplayPanel');
hTypeBtn = get(hPlotBtnGrp,'SelectedObject');
plotType = get(hTypeBtn, 'Tag');

departAxis = handles.departAxis;
axisUserData = get(departAxis,'UserData');
reset(departAxis);
set(departAxis,'UserData',axisUserData);
hLegend = findobj(handles.departDispGUI,'Type','axes','Tag','legend');
delete(hLegend);

switch plotType
    case 'departureOrbitRadio'
        plotBodyDepartOrbit(departAxis)
    case 'transferOrbitRadio'
        plotTransferOrbit(departAxis)
end

% --------------------------------------------------------------------
function generateReport_Callback(hObject, eventdata, handles)
% hObject    handle to generateReport (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
[hReport, handlesR] = genericReport(1, 'SINGLE DELTA-V MANEUVER', 'BALLISTIC TRANSFER APPLICATION');

    set(handlesR.rightTextBoxLabel,'String', 'Transfer Orbit Details');

    results = get(handles.departDispGUI,'UserData');
    results = results{1};

    paddLen = 29;
    form = '%9.5f';
    burnInfoTextstr = {};
    burnInfoTextstr{end+1} = [paddStr('Total Delta-V = ',paddLen), num2str(norm(results.burnVect), form), ' km/s'];
    burnInfoTextstr{end+1} = [paddStr('Prograde Delta-V = ',paddLen), num2str(1000*results.burnVect(1), form), ' m/s'];
    burnInfoTextstr{end+1} = [paddStr('Radial Delta-V = ',paddLen), num2str(1000*results.burnVect(3), form), ' m/s'];
    burnInfoTextstr{end+1} = [paddStr('Orbit Normal Delta-V = ',paddLen), num2str(1000*results.burnVect(2), form), ' m/s'];
    burnInfoTextstr{end+1} = '---------------------';
    burnInfoTextstr{end+1} = [paddStr('Departure True Anomaly = ',paddLen), num2str(rad2deg(results.burnTA), form), ' deg'];

    if(isfield(results,'burnTimeBeforePeri'))
        burnInfoTextstr{end+1} = [paddStr('Burn Time Before Peri. = ',paddLen), num2str(results.burnTimeBeforePeri, form), ' sec'];
    end

    if(isfield(results,'burnTimePastPeri'))
        burnInfoTextstr{end+1} = [paddStr('Burn Time Past Peri. = ',paddLen), num2str(results.burnTimeBeforePeri, form), ' sec'];
    end

    if(isfield(results,'iniOrbitPeriod'))
        burnInfoTextstr{end+1} = [paddStr('Ini. Orbit Period = ',paddLen), num2str(results.iniOrbitPeriod, form), ' sec'];
    end
    set(handlesR.leftTextBox, 'String', burnInfoTextstr);

    paddLen = 30;
    xferOrbitText = {};
    xferOrbitText{end+1} = ['Transfer Orbit about ', cap1stLetter(results.xferOrbitCBName)];
    xferOrbitText{end+1} = '-----------------------------------------------';
    xferOrbitText{end+1} = [paddStr('Semi-major Axis = ',paddLen), num2str(results.xferOrbit(1), form), ' km'];
    xferOrbitText{end+1} = [paddStr('Eccentricity = ', paddLen), num2str(results.xferOrbit(2))];
    xferOrbitText{end+1} = [paddStr('Inclination = ',paddLen), num2str(rad2deg(AngleZero2Pi(results.xferOrbit(3))), form), ' deg'];
    xferOrbitText{end+1} = [paddStr('Right Ascension of AN = ',paddLen), num2str(rad2deg(AngleZero2Pi(results.xferOrbit(4))), form), ' deg'];
    xferOrbitText{end+1} = [paddStr('Argument of Periapse = ',paddLen), num2str(rad2deg(AngleZero2Pi(results.xferOrbit(5))), form), ' deg'];
    xferOrbitText{end+1} = [paddStr([cap1stLetter(results.departBodyName), ' Depart True Anomaly = '],paddLen), num2str(rad2deg(AngleZero2Pi(results.xferOrbit(6))), form), ' deg'];
    xferOrbitText{end+1} = [paddStr([cap1stLetter(results.arrivalBodyName), ' Arrive True Anomaly = '],paddLen), num2str(rad2deg(AngleZero2Pi(results.xferOrbit(7))), form), ' deg'];

    set(handlesR.rightTextBox, 'String', xferOrbitText);

    set(handlesR.leftAxis,'UserData',results.axisUserData);
    set(handlesR.rightAxis,'UserData',results.axisUserData);

    plotBodyDepartOrbit(handlesR.leftAxis);
    plotTransferOrbit(handlesR.rightAxis, false);

% --------------------------------------------------------------------
function uploadManeuver_Callback(hObject, eventdata, handles)
% hObject    handle to uploadManeuver (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
guiData = get(handles.burnInfoText,'UserData');
uploadManeuverToKSP(guiData);


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

%%
clear; close all; clc;

%% Syntax
% |maxFig(varargin);|

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


classdef MimMarkerPointManager < CoreBaseClass
    % MimMarkerPointManager. Part of the internal gui for the TD MIM Toolkit.
    %
    %     You should not use this class within your own code. It is intended to
    %     be used internally within the gui of the TD 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 (Access = private)
        MarkerLayer
        MarkerPointImage
        BackgroundImageSource
        MarkerDisplayParameters
        ViewerPanel
        Gui
        GuiDataset
        AppDef
        Reporting

        MarkersHaveBeenLoaded = false
        MarkerImageHasUnsavedChanges = false
        MarkerSetInitialSave = false
    end

    events
        SavedMarkerListChanged
    end

    properties (SetObservable, SetAccess = private)
        CurrentMarkersName
    end

    methods
        function obj = MimMarkerPointManager(marker_layer, marker_image_source, marker_display_parameters, background_image_source, viewer_panel, gui, gui_dataset, app_def, reporting)
            obj.MarkerLayer = marker_layer;
            obj.MarkerPointImage = marker_image_source;
            obj.BackgroundImageSource = background_image_source;
            obj.MarkerDisplayParameters = marker_display_parameters;
            obj.ViewerPanel = viewer_panel;
            obj.Gui = gui;
            obj.GuiDataset = gui_dataset;
            obj.AppDef = app_def;
            obj.Reporting = reporting;
            obj.AddEventListener(marker_image_source, 'MarkerImageHasChanged', @obj.MarkerImageChangedCallback);
            obj.AddEventListener(background_image_source, 'NewImage', @obj.BackgroundImageChangedCallback);
            obj.AddEventListener(background_image_source, 'ImageModified', @obj.BackgroundImageChangedCallback);
        end

        function ClearMarkers(obj)
            obj.MarkersHaveBeenLoaded = false;
            obj.CurrentMarkersName = [];
            obj.MarkerPointImage.ClearMarkers();
            obj.ResetImageChangedFlag();
        end

        function AutoSaveMarkers(obj)
            if ~isempty(obj.MarkerLayer) && obj.MarkerImageHasUnsavedChanges && obj.MarkersHaveBeenLoaded
                saved_marker_points = obj.GuiDataset.LoadMarkers(obj.CurrentMarkersName);
                current_marker_points = obj.GetMarkersToSave();
                markers_changed = false;
                if isempty(saved_marker_points)
                    if ~isempty(current_marker_points.MarkerList)
                        markers_changed = true;
                    end
                else
                    if isa(saved_marker_points, 'PTKImage')
                        markers_changed = true;
                    else
                        if ~isequal(saved_marker_points.MarkerList, current_marker_points.MarkerList)
                            markers_changed = true;
                        end
                    end
                end

                if markers_changed

                    % Depending on the software settings, the user can be prompted before saving
                    % changes to the markers
                    if obj.AppDef.ConfirmBeforeSavingMarkers
                        choice = questdlg('Do you want to save the changes you have made to the current markers?', ...
                            'Unsaved changes to markers', 'Delete changes', 'Save', 'Save');
                        switch choice
                            case 'Save'
                                obj.SaveMarkers();
                            case 'Don''t save'
                                obj.SaveMarkersBackup();
                                disp('Abandoned changes have been stored in AbandonedMarkerPoints.mat');
                        end
                    else
                        obj.SaveMarkers();
                    end
                end
            end
        end

        function SaveMarkersManualBackup(obj)
            if obj.GuiDataset.DatasetIsLoaded()
                markers = obj.GetMarkersToSave();
                obj.GuiDataset.SaveMarkers('MarkerPointsLastManualSave', markers);
            end
        end

        function LoadMarkersIfRequired(obj, name)
            if obj.IsLoadMarkersRequired()
                obj.LoadMarkers(name);
            end
        end

        function load_required = IsLoadMarkersRequired(obj)
            load_required = ~obj.MarkersHaveBeenLoaded && (obj.MarkerDisplayParameters.ShowMarkers || obj.ViewerPanel.IsInMarkerMode);
        end

        function LoadMarkers(obj, name)
            obj.AutoSaveMarkers();
            new_marker_list = obj.GuiDataset.LoadMarkers(name);
            if isempty(new_marker_list)
                new_marker_image = GemMarkerPointImage(zeros(0,4));
            else
                new_marker_image = GemMarkerPointImage(new_marker_list.ConvertToMarkerList());
            end
            obj.MarkerPointImage.LoadMarkers(new_marker_image);
            if isempty(new_marker_list)
                obj.SaveMarkers();
            end
            obj.ResetImageChangedFlag();
            obj.MarkersHaveBeenLoaded = true;
            obj.CurrentMarkersName = name;
        end

        function current_markers = GetCurrentMarkerSetName(obj)
            current_markers = obj.CurrentMarkersName;
        end

        function AddMarkerSet(obj, name)
            obj.SaveMarkers();
            obj.LoadMarkers(name);
            obj.SaveMarkers();
            notify(obj, 'SavedMarkerListChanged');
        end

        function DeleteMarkerSet(obj, name)
            obj.GuiDataset.DeleteMarkerSet(name);
            if strcmp(name, obj.GetCurrentMarkerSetName())
                obj.ClearMarkers();
            end
            notify(obj, 'SavedMarkerListChanged');
        end
    end

    methods (Access = private)
        function SaveMarkers(obj)
            if obj.GuiDataset.DatasetIsLoaded()
                if isempty(obj.CurrentMarkersName)
                    if ~isempty(obj.MarkerPointImage.MarkerList)
                        obj.Reporting.Error('MimMarkerPointManager:NoMarkerFilename', 'The markers could not be saved as the marker filename has not been specified. ');
                    end
                else
                    obj.Reporting.ShowProgress('Saving Markers');
                    markers = obj.GetMarkersToSave();
                    obj.GuiDataset.SaveMarkers(obj.CurrentMarkersName, markers);
                    obj.ResetImageChangedFlag();
                    obj.Reporting.CompleteProgress();
                end
            end
        end

        function marker_list_to_save = GetMarkersToSave(obj)
            image_to_save = obj.MarkerPointImage.GetImageToSave(obj.BackgroundImageSource.Image);
            series_uid = obj.GuiDataset.GetUidOfCurrentDataset();
            marker_list_to_save = MimMarkerList(image_to_save, series_uid);
        end

        function SaveMarkersBackup(obj)
            if obj.GuiDataset.DatasetIsLoaded
                obj.Reporting.ShowProgress('Abandoning Markers');
                markers = obj.GetMarkersToSave();
                obj.GuiDataset.SaveMarkers('AbandonedMarkerPoints', markers);
                obj.Reporting.CompleteProgress;
            end
        end

        function BackgroundImageChangedCallback(obj, ~, ~)
            obj.MarkerPointImage.BackgroundImageChanged(obj.BackgroundImageSource.Image);
            obj.MarkerLayer.MarkerImageChanged();
            obj.ResetImageChangedFlag();
        end

        function MarkerImageChangedCallback(obj, ~, ~)
            obj.MarkerImageHasUnsavedChanges = true;
        end

        function ResetImageChangedFlag(obj)
            obj.MarkerImageHasUnsavedChanges = false;
        end
    end
end


function clearToolPanel(handles)
%
% 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/>.

   t = handles.toolPanel;
    tc = get(t, 'Children');
    delete(tc);

    fnames = fieldnames(handles);
    for i = 1:length(fnames)
        if ~ishandle(handles.(fnames{i})) && ~isstruct(handles.(fnames{i}))
            handles = rmfield(handles, fnames{i});
        end
    end
    guidata(handles.mainframe, handles);

%     for i=1:length(tc)
%         set(tc(i), 'visible', 'off');
%     end

end


%this class retrieves a preprocessing algorithm from the UI
classdef FeatureExtractionConfigurator < handle

    properties (Access = private)
        algorithmConfigurator;

        uiElements FeatureExtractionConfiguratorUIElements;

        selectedFeatures;
        currentSelectedFeature;
    end

    properties (Access = public)
        defaultFeatures;
        loadedFeatureExtractionFiles;
    end

    methods (Access = public)
        function obj = FeatureExtractionConfigurator(defaultFeatures,...
                loadedFeatureExtractionFiles, uiElements)

            obj.defaultFeatures = defaultFeatures;
            obj.loadedFeatureExtractionFiles = loadedFeatureExtractionFiles;

            obj.uiElements = uiElements;

            obj.uiElements.addFeatureButton.ButtonPushedFcn = @obj.handleAddButtonClicked;
            obj.uiElements.removeFeatureButton.ButtonPushedFcn = @obj.handleRemoveButtonClicked;
            obj.uiElements.featuresSourceButtonGroup.SelectionChangedFcn = @obj.handleSelectionTypeChanged;
            obj.uiElements.selectedFeaturesList.ValueChangedFcn = @obj.handleSelectedFeatureChanged;
            obj.uiElements.featureStartRangeEditText.ValueChangedFcn = @obj.handleStartValueChanged;
            obj.uiElements.featureEndRangeEditText.ValueChangedFcn = @obj.handleEndValueChanged;
            obj.uiElements.featureFullSegmentCheckBox.ValueChangedFcn = @obj.handleFullSegmentCheckBoxChanged;
            obj.uiElements.featureAxisEditText.ValueChangedFcn = @obj.handleAxisValueChanged;

            obj.selectedFeatures = [];
            if ~isempty(obj.loadedFeatureExtractionFiles)
                obj.fillLoadedFeaturesList();
                obj.uiElements.loadedFeatureExtractorsList.Value = obj.uiElements.loadedFeatureExtractorsList.Items{1};
            end

            if ~isempty(obj.defaultFeatures)
                obj.reloadUI();
            end
        end

        function reloadUI(obj)
            obj.fillDefaultFeaturesList();
        end

        function featureExtractor = createFeatureExtractorWithUIParameters(obj)
            if obj.isManualFeatureSelectionMode()
                featureExtractor = FeatureExtractor(obj.selectedFeatures);
            else
                fileIdx = obj.getSelectedLoadedFileIdx();
                featureExtractionFile = obj.loadedFeatureExtractionFiles{fileIdx};
                featureExtractor = DataLoader.LoadAlgorithm(featureExtractionFile);
            end
        end

        function idx = getDefaultSelectedFeatureIdx(obj)
            idxStr = obj.uiElements.defaultFeaturesList.Value;
            [~,idx] = ismember(idxStr,obj.uiElements.defaultFeaturesList.Items);
        end

        function feature = getDefaultSelectedFeature(obj)
            idx = obj.getDefaultSelectedFeatureIdx();
            feature = obj.defaultFeatures{idx};
        end

        function idx = getSelectedFeatureIdx(obj)
            idxStr = obj.uiElements.selectedFeaturesList.Value;
            [~,idx] = ismember(idxStr,obj.uiElements.selectedFeaturesList.Items);
        end

        function feature = getSelectedFeature(obj)
            if isempty(obj.uiElements.selectedFeaturesList.Items)
                feature = [];
            else
                idx = obj.getSelectedFeatureIdx();
                feature = obj.selectedFeatures{idx};
            end
        end
    end

    methods(Access = private)

        function updateSelectedFeatureUI(obj)
            if ~isempty(obj.currentSelectedFeature)
                axisSelector = obj.currentSelectedFeature.root;
                rangeSelector = axisSelector.nextAlgorithms{1};

                if isempty(rangeSelector.rangeEnd)
                    obj.uiElements.featureStartRangeEditText.Visible = false;
                    obj.uiElements.featureEndRangeEditText.Visible = false;
                    obj.uiElements.featureFullSegmentCheckBox.Value = true;
                else
                    obj.uiElements.featureStartRangeEditText.Visible = true;
                    obj.uiElements.featureEndRangeEditText.Visible = true;
                    obj.uiElements.featureFullSegmentCheckBox.Value = false;
                    obj.uiElements.featureStartRangeEditText.Value = rangeSelector.rangeStart;
                    obj.uiElements.featureEndRangeEditText.Value = rangeSelector.rangeEnd;
                end
                obj.uiElements.featureAxisEditText.Value = Helper.ArrayToString(axisSelector.axes,' ');
            end
        end

        function updateCurrentSelectedFeatureName(obj)
            idx = obj.getSelectedFeatureIdx();
            featureExtractor = obj.selectedFeatures{idx};
            obj.uiElements.selectedFeaturesList.Items{idx} = FeatureExtractionConfigurator.StringForFeature(featureExtractor);
            obj.uiElements.selectedFeaturesList.Value = obj.uiElements.selectedFeaturesList.Items{idx};
        end

        function addFeatureToSelectedList(obj, algorithm)
            obj.selectedFeatures{end+1} = algorithm;
            obj.uiElements.selectedFeaturesList.Items{end+1} = FeatureExtractionConfigurator.StringForFeature(algorithm);
            obj.uiElements.selectedFeaturesList.Value = obj.uiElements.selectedFeaturesList.Items(end);
            obj.currentSelectedFeature = algorithm;
            obj.updateSelectedFeatureUI();
        end

        function idx = getSelectedLoadedFileIdx(obj)
            idxStr = obj.uiElements.loadedFeatureExtractorsList.Value;
            [~,idx] = ismember(idxStr,obj.uiElements.loadedFeatureExtractorsList.Items);
        end

        function b = isManualFeatureSelectionMode(obj)
            selectedButton = obj.uiElements.featuresSourceButtonGroup.SelectedObject;
            b = (selectedButton == obj.uiElements.featuresSourceManuallyRadio);
        end

        function updateSegmentRangeVisibility(obj)
            visible = ~obj.uiElements.featureFullSegmentCheckBox.Value;
            obj.uiElements.featureStartRangeEditText.Visible = visible;
            obj.uiElements.featureEndRangeEditText.Visible = visible;
        end

        function handleSelectionTypeChanged(obj,~,~)
            if obj.isManualFeatureSelectionMode()
                obj.uiElements.manualFeatureExtractionPanel.Visible = true;
                obj.uiElements.loadedFeatureExtractorsList.Visible = false;
            else
                obj.uiElements.manualFeatureExtractionPanel.Visible = false;
                obj.uiElements.loadedFeatureExtractorsList.Visible = true;
            end
        end

        function handleAddButtonClicked(obj,~,~)

            axisSelector = AxisSelector();
            rangeSelector = RangeSelector();
            featureExtractor = obj.getDefaultSelectedFeature();

            Algorithm.AlgorithmWithSequence({axisSelector,rangeSelector,featureExtractor});

            compositeAlgorithm = CompositeAlgorithm(axisSelector,featureExtractor);
            compositeAlgorithm.name = featureExtractor.name;

            obj.addFeatureToSelectedList(compositeAlgorithm);
        end

        function handleRemoveButtonClicked(obj,~,~)
            idx = obj.getSelectedFeatureIdx();
            obj.selectedFeatures(idx) = [];
            obj.selectedFeaturesList.Items(idx) = [];
            obj.selectFirstAddedFeature();
        end

        function selectFirstAddedFeature(obj)
            if ~isempty(obj.selectedFeatures)
                obj.uiElements.selectedFeaturesList.Value = obj.uiElements.selectedFeaturesList.Items{1};
                obj.currentSelectedFeature = obj.selectedFeatures{1};
            end
        end

        function fillLoadedFeaturesList(obj)
            obj.uiElements.loadedFeatureExtractorsList.Items = obj.loadedFeatureExtractionFiles;
        end

        function fillDefaultFeaturesList(obj)
            obj.uiElements.defaultFeaturesList.Items = Helper.GenerateAlgorithmNamesArray(obj.defaultFeatures);
        end

        function handleSelectedFeatureChanged(obj,~,~)
            obj.currentSelectedFeature = obj.getSelectedFeature();
            obj.updateSelectedFeatureUI();
        end

        function handleStartValueChanged(obj,~,~)
            obj.currentSelectedFeature = obj.getSelectedFeature();

            if ~isempty(obj.currentSelectedFeature)
                rangeSelector = obj.currentSelectedFeature.root.nextAlgorithms{1};
                rangeSelector.rangeStart = obj.uiElements.featureStartRangeEditText.Value;
                obj.updateCurrentSelectedFeatureName();
            end
        end

        function handleEndValueChanged(obj,~,~)
            obj.currentSelectedFeature = obj.getSelectedFeature();

            if ~isempty(obj.currentSelectedFeature)
                rangeSelector = obj.currentSelectedFeature.root.nextAlgorithms{1};
                rangeSelector.rangeEnd = obj.uiElements.featureEndRangeEditText.Value;
                obj.updateCurrentSelectedFeatureName();
            end
        end

        function handleAxisValueChanged(obj,~,~)
            obj.currentSelectedFeature = obj.getSelectedFeature();

            if ~isempty(obj.currentSelectedFeature)
                axisSelector = obj.currentSelectedFeature.root;
                axisSelector.axes = str2num(obj.uiElements.featureAxisEditText.Value);
                obj.updateCurrentSelectedFeatureName();
            end
        end

        function handleFullSegmentCheckBoxChanged(obj,~,~)
            obj.updateSegmentRangeVisibility();

            obj.currentSelectedFeature = obj.getSelectedFeature();
            if ~isempty(obj.currentSelectedFeature)
                rangeSelector = obj.currentSelectedFeature.root.nextAlgorithms{1};

                value = obj.uiElements.featureFullSegmentCheckBox.Value;
                if (value)
                    rangeSelector.rangeEnd = [];
                else
                    rangeSelector.rangeEnd = obj.uiElements.featureEndRangeEditText.Value;
                end
                obj.updateCurrentSelectedFeatureName();
            end
        end
    end

    methods (Access = private, Static)
        function str = StringForFeature(featureAlgorithm)
            axisSelector = featureAlgorithm.root;
            rangeSelector = axisSelector.nextAlgorithms{1};
            featureExtractor = rangeSelector.nextAlgorithms{1};

            str = sprintf('%s_%s',featureExtractor.name,Helper.ArrayToString(axisSelector.axes,' '));
            if ~isempty(rangeSelector.rangeEnd)
                str = sprintf('%s (%d-%d)',str,rangeSelector.rangeStart,rangeSelector.rangeEnd);
            end
        end
    end
end


function filesize = GetFileSize(fileobject)

if ischar(fileobject)
    if exist(fileobject, 'file') == 2
        fd = fopen(fileobject);
    else
        filesize = -1;
        return;
    end
else
    fd = fileobject;
end

% Since we're changing file position, save the initial one, then restore
% it before exiting
p0 = ftell(fd);

fseek(fd, 0, 'eof');     % move the cursor to the end of the file
filesize = ftell(fd);

% Restore original file position
fseek(fd, p0, 'bof');

if ischar(fileobject)
    fclose(fd);
end


%% string gen_file_name(string,string)
% fileName - string
% extra - string
% newFileName - string
%
function [newFileName] = gen_file_name(fileName,extra)
  %ext = get_file_extension(fileName);
  %newFileName = [fileName(1:length(fileName)-4) extra ext];
  [pathstr,name,ext] = fileparts(fileName);
  newFileName = fullfile(pathstr,[name extra ext]);
end


function setImageRotate(view, imageRotate)
%
% setImageRotate(view, imageRotate)
%
% Sets imageRotate slider values.
if isequal(view.name, 'hidden')
	% instead of a handle to the slider, the ImageRotate field will
	% directly store the rotations for hidden views:
	view.ui.ImageRotate = imageRotate;
else
	% non-hidden view: view.ui.ImageRotate should be a slider struct
	setSlider(view,view.ui.ImageRotate, imageRotate);
end

return


function dbunmute
%dbunmute enables all breakpoints currently set in MATLAB.
% Copyright 2009 The MathWorks, Inc.

    % iterate over each entry in the result of dbstatus,
    % and enable each of the breakpoints.
    breakpoints = dbstatus('-completenames');
    for i=1 : length(breakpoints)
        unmuteDbStatusEntry(breakpoints(i));
    end
end

function unmuteDbStatusEntry(dbstatusEntry)
%muteDbStatusEntry disables each breapoint in the given entry.
    for i=1 : length(dbstatusEntry.line)
        file = dbstatusEntry.file;
        line = dbstatusEntry.line(i);
        anonymousIndex = dbstatusEntry.anonymous(i);
        expression = dbstatusEntry.expression{i};

        lineNumberString = [num2str(line) '@' num2str(anonymousIndex)];
        newExpression = stripDisablingPartOfExpression(expression);

        dbstop(file, lineNumberString, 'if', newExpression);
    end
end

function newExpression = stripDisablingPartOfExpression(expression)
%strips any disabling expresion from the given expression.
    if (~isDisabled(expression))
        newExpression = expression;
    elseif strcmp(expression, 'false')
        newExpression = '';
    else
        endPosition = length(expression) - 1;
        newExpression = expression(9:endPosition);
    end
end


  classdef MyProgressMonitorNew < matlab.net.http.ProgressMonitor
      properties
          ProgHandle
          Direction matlab.net.http.MessageType
          Value uint64
          NewDir matlab.net.http.MessageType = matlab.net.http.MessageType.Request
      end

      methods
          function obj = MyProgressMonitorNew
              obj.Interval = .01;
          end

          function done(obj)
              obj.closeit();
          end

          function delete(obj)
              obj.closeit();
          end

          function set.Direction(obj, dir)
              obj.Direction = dir;
              obj.changeDir();
          end

          function set.Value(obj, value)
              obj.Value = value;
              obj.update();
          end
      end

      methods (Access = private)
          function update(obj,~)
              % called when Value is set
              import matlab.net.http.*
              if ~isempty(obj.Value)
                  if isempty(obj.Max)
                      % no maximum means we don't know length, so message changes on
                      % every call
                      value = 0;
                      if obj.Direction == MessageType.Request
                          msg = sprintf('Sent %d bytes...', obj.Value);
                      else
                          msg = sprintf('Received %d bytes...', obj.Value);
                      end
                  else
                      % maximum known; update proportional value
                      value = double(obj.Value)/double(obj.Max);
                      if obj.NewDir == MessageType.Request
                          % message changes only on change of direction
                          if obj.Direction == MessageType.Request
                              msg = 'Sending...';
                          else
                              msg = 'Receiving...';
                          end
                      end
                  end
                  if isempty(obj.ProgHandle)
                      % if we don't have a progress bar, display it for first time
                      obj.ProgHandle = ...
                          waitbar(value, msg, 'CreateCancelBtn', @(~,~)cancelAndClose(obj));

                      obj.NewDir = MessageType.Response;
                  elseif obj.NewDir == MessageType.Request || isempty(obj.Max)
                      % on change of direction or if no maximum known, change message
                      waitbar(value, obj.ProgHandle, msg);
                      obj.NewDir = MessageType.Response;
                  else
                      % no direction change else just update proportional value
                      waitbar(value, obj.ProgHandle);
                  end
              end

              function cancelAndClose(obj)
                  % Call the required CancelFcn and then close our progress bar. This is
                  % called when user clicks cancel or closes the window.
                  obj.CancelFcn();
                  obj.closeit();
              end
          end

          function changeDir(obj,~)
              % Called when Direction is set or changed. Leave the progress bar displayed.
              obj.NewDir = matlab.net.http.MessageType.Request;
          end
      end

      methods (Access=private)
          function closeit(obj)
              % Close the progress bar by deleting the handle so CloseRequestFcn isn't
              % called, because waitbar calls our cancelAndClose(), which would cause
              % recursion.
              if ~isempty(obj.ProgHandle)
                  delete(obj.ProgHandle);
                  obj.ProgHandle = [];
              end
          end
      end
  end


function varargout = sl_synch_gui(varargin)
% SL_SYNCH_GUI M-file for sl_synch_gui.fig
%      SL_SYNCH_GUI, by itself, creates a new SL_SYNCH_GUI or raises the existing
%      singleton*.
%
%      H = SL_SYNCH_GUI returns the handle to a new SL_SYNCH_GUI or the handle to
%      the existing singleton*.
%
%      SL_SYNCH_GUI('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in SL_SYNCH_GUI.M with the given input arguments.
%
%      SL_SYNCH_GUI('Property','Value',...) creates a new SL_SYNCH_GUI or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before sl_synch_gui_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to sl_synch_gui_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
%
% Edited by Will Campbell, MathWorks Inc.
% will.campbell@mathworks.com
% January 7, 2010
% Copyright 2010 The MathWorks, Inc.

% Last Modified by GUIDE v2.5 19-Feb-2010 10:51:33

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

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

% Update handles structure
guidata(hObject, handles);

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

% Get the value of the manual switch and synch the GUI
value = get_param([bdroot '/Manual Switch'],'sw');
if strcmp(value,'0')
    set(handles.checkbox_switch,'Value',0)
else
    set(handles.checkbox_switch,'Value',1)
end

% Get the value of the gain edit box and synch the GUI
value = get_param([bdroot '/Gain'],'Gain');
set(handles.edit_Gain,'String',value);

% Set the value of the gain slider, with max/min of +10/-10
slider_position = max(0,min(1,(str2double(value) + 10)/20));
set(handles.slider_Gain,'Value',slider_position);

% Assign gui, startstop, switch, and gain handles to the base workspace
assignin('base','sl_synch_handles',handles)
assignin('base','startstop_hObject',handles.pushbutton_startstop)
assignin('base','switch_hObject',handles.checkbox_switch)
assignin('base','gain_hObject',handles.edit_Gain)

% --- Outputs from this function are returned to the command line.
function varargout = sl_synch_gui_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 button press in pushbutton_startstop.
function pushbutton_startstop_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton_startstop (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

mystring = get(hObject,'String');
status = get_param(bdroot,'simulationstatus');

if strcmp(mystring,'Start Simulation')

    % Check the status of the simulation and start it if it's stopped
    if strcmp(status,'stopped')
        set_param(bdroot,'simulationcommand','start')
    end

    % Update the string on the pushbutton
    set(handles.pushbutton_startstop,'String','Stop Simulation')

elseif strcmp(mystring,'Stop Simulation')

    % Check the status of the simulation and stop it if it's running
    if strcmp(status,'running')
        set_param(bdroot, 'SimulationCommand', 'Stop')
    end

    % Update the string on the pushbutton
    set(handles.pushbutton_startstop,'String','Start Simulation')

else
    warning('Unrecognized string for pushbutton_startstop') %#ok<WNTAG>
end

% Assign handles and the startstop object to the base workspace
assignin('base','sl_synch_handles',handles)
assignin('base','startstop_hObject',handles.pushbutton_startstop)

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

% Hint: get(hObject,'Value') returns toggle state of checkbox_switch

value = get(hObject,'Value');

if value == 0
    set_param([bdroot '/Manual Switch'],'sw','0')
else
    set_param([bdroot '/Manual Switch'],'sw','1')
end

% Assign handles and the switch object to the base workspace
assignin('base','sl_synch_handles',handles)
assignin('base','switch_hObject',handles.checkbox_switch)

function edit_Gain_Callback(hObject, eventdata, handles)
% hObject    handle to edit_Gain (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 edit_Gain as text
%        str2double(get(hObject,'String')) returns contents of edit_Gain as a double

value = get(hObject,'String');

% Update the model's gain value
set_param([bdroot '/Gain'],'Gain',value)

% Set the value of the gain slider, with max/min of +10/-10
slider_position = max(0,min(1,(str2double(value) + 10)/20));
set(handles.slider_Gain,'Value',slider_position);

% Update simulation if the model is running
status = get_param(bdroot,'simulationstatus');
if strcmp(status,'running')
    set_param(bdroot, 'SimulationCommand', 'Update')
end

% --- Executes during object creation, after setting all properties.
function edit_Gain_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_Gain (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 slider movement.
function slider_Gain_Callback(hObject, eventdata, handles)
% hObject    handle to slider_Gain (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,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider

% Get the value of the gain slider and determine what the gain value should be
slider_position = get(hObject,'Value');
value = num2str(slider_position*20 - 10);

% Update the model's gain value
set_param([bdroot '/Gain'],'Gain',value)

% Set the value of the gain edit box
set(handles.edit_Gain,'String',value);

% Update simulation if the model is running
status = get_param(bdroot,'simulationstatus');
if strcmp(status,'running')
    set_param(bdroot, 'SimulationCommand', 'Update')
end

% --- Executes during object creation, after setting all properties.
function slider_Gain_CreateFcn(hObject, eventdata, handles)
% hObject    handle to slider_Gain (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.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end


function varargout = transpose(varargin) %#ok<STOUT,*INUSD>
%TRANSPOSE   DELTAFUN objects are not transposable.

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

error('CHEBFUN:DELTAFUN:transpose:notPossible', ...
    'DELTAFUN objects are not transposable.')

end


function printpdf(fname)
%PRINTPDF Prints the current figure into a pdf document
set(gca, 'LooseInset', get(gca, 'TightInset'));
fname = [regexprep(fname, '^(.*)\.pdf$', '$1'), '.eps'];
% fname = [regexprep(fname, '^(.*)\.pdf$', '$1'), '.pdf'];
print('-depsc', fname) ;
% print('-dpdf', fname);
if ~system(['epstopdf ', fname])
% if ~system(['/usr/bin/epstopdf ', fname])
system(['rm ', fname]);
end


function [id, stop, val] = list(item, spec, tropts, fn)

% function [id, stop, val] = list(item, spec, tropts, fn)
% Find items in a cfg tree rooted at item that match a specification spec.
% By default, the filled configuration tree is searched (i.e. the
% val-branches of cfg_repeat and cfg_choice nodes).
% See MATCH for help about spec data structure.
%
% Traversal options
% struct with fields
% stopspec - match spec to stop traversal
% dflag    - traverse val or values tree
% clvl     - current level in tree
% mlvl     - maximum level to traverse - range 1 (top level only) to
%            Inf (all levels)
% cnt      - #items found so far
% mcnt    - max #items to find
% List will stop descending into subtrees if one of the conditions
% following conditions are met: item matches stopspec, clvl >= mlvl, cnt >=
% mcnt. Flag stop is true for nodes where traversal has stopped
% (i.e. items where tropts has stopped further traversal).
%
% A cell list of subsref ids to matching nodes will be returned. The id of
% this node is returned before the id of its matching children.
% If the root node of the tree matches, the first id returned will be an
% empty substruct.
% If a cell list of fieldnames is given, then the contents of these fields
% will be returned in the cell array val. If one of the fields does not
% exist, a cell with an empty entry will be returned.
% There are five pseudo-fieldnames which allow to obtain information useful
% to build e.g. a user interface for cfg trees:
% 'class' - returns the class of the current item
% 'level' - returns the level in the tree. Since data is collected
%           pre-order, children are listed after their parents. Identical
%           levels of subsequent nodes denote siblings, whereas decreasing
%           levels of subsequent nodes denote siblings of the parent node.
% 'all_set' - return all_set status of subtree rooted at item, regardless
%             whether list will descend into it or not
% 'all_set_item' - return all_set_item status of current node (i.e. whether
%                  all integrity conditions for this node are fulfilled).
%                  For in-tree nodes this can be different from all_set.
% 'showdoc' - calls showmydoc to display the help text and option hints for
%             the current item (without recursive calls for .val/.values
%             items).
%
% This function is identical for all cfg_intree classes.
%
% This code is part of a batch job configuration system for MATLAB. See
%      help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging

% Volkmar Glauche
% $Id: list.m 5678 2013-10-11 14:58:04Z volkmar $

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

if match(item, spec)
    id = {struct('type', {}, 'subs', {})};
    tropts.cnt = tropts.cnt + 1;
    stop = false;
    if nargin > 3
        val = cell(1,numel(fn));
        for k = 1:numel(fn)
            switch fn{k}
                case 'class'
                    val{k} = {class(item)};
                case 'level'
                    val{k} = {tropts.clvl};
                case 'all_set'
                    val{k} = {all_set(item)};
                case 'all_set_item'
                    val{k} = {all_set_item(item)};
                case 'showdoc'
                    val{k} = {showmydoc(item,'')};
                case fieldnames(item)
                    val{k} = {subsref(item, substruct('.', fn{k}))};
                otherwise
                    val{k} = {{}};
            end;
        end;
    else
        val = {};
    end;
    matched = true;
else
    id = {};
    stop = [];
    if nargin > 3
        val = cell(size(fn));
        [val{:}] = deal({});
    else
        val = {};
    end;
    matched = false;
end;

if (isempty(tropts.stopspec) || ~match(item, tropts.stopspec)) && (tropts.cnt < tropts.mcnt) && (tropts.clvl < tropts.mlvl)
    tname = treepart(item, tropts.dflag);
    % subscripts to child nodes
    idsubs = substruct('.', tname, '{}', {});
    citems = subsref(item, idsubs(1));
    tropts.clvl = tropts.clvl + 1;
    for k = 1:numel(citems)
        if nargin > 3
            [id1, stop1, val1] = list(citems{k}, spec, tropts, fn);
            for l = 1:numel(fn)
                val{l} = [val{l}(:); val1{l}(:)]';
            end;
        else
            [id1, stop1] = list(citems{k}, spec, tropts);
        end;
        if ~isempty(id1)
            idsubs(2).subs = {k};
            for l = 1:numel(id1)
                id = [id(:); {[idsubs id1{l}]}]';
            end;
            stop = [stop stop1];
            tropts.cnt = tropts.cnt + numel(id1);
            if tropts.cnt >= tropts.mcnt
                if matched
                    stop(1) = true;
                end;
                break;
            end;
        end;
    end;
else
    if matched
        stop = true;
    end;
end;


function [rd, boardName] = hdlcoder_ref_design_customization
% Reference design plugin registration file
% 1. The registration file with this name inside of a board plugin folder
%    will be picked up
% 2. Any registration file with this name on MATLAB path will also be picked up
% 3. The registration file returns a cell array pointing to the location of
%    the reference design plugins
% 4. The registration file also returns its associated board name
% 5. Reference design plugin must be a package folder accessible from
%    MATLAB path, and contains a reference design definition file

%   Copyright 2013-2014 The MathWorks, Inc.

rd = {...
    'AnalogDevices.fmcomms2.zed.plugin_rd_rx', ...
    'AnalogDevices.fmcomms2.zed.plugin_rd_tx', ...
    'AnalogDevices.fmcomms2.zed.plugin_rd_rxtx', ...
    };

boardName = 'AnalogDevices FMCOMMS2/3 ZED';

end


function CropImage(varargin)
% CROPIMAGE Taser wrapper for chipfile.m function
%
% Written by: Tim Cox, NRL
%
% //////////////////////////////////////////
% /// CLASSIFICATION: UNCLASSIFIED       ///
% //////////////////////////////////////////

p = inputParser; % Extract parameter-value pairs
p.KeepUnmatched=true;
p.addParamValue('filename','');
p.addParamValue('aoi',[0 0 0 0]);
p.addParamValue('segment',1);
p.parse(varargin{:});

filenames = p.Results.filename;
aoi = p.Results.aoi;
segment = p.Results.segment;

%get output folder
%load last path
if ispref('matlab_sar_toolbox','last_used_directory')
    pathstr = getpref('matlab_sar_toolbox','last_used_directory');
    if ~ischar(pathstr)||~exist(pathstr,'dir')
        pathstr = pwd;
    end
else
    pathstr = pwd;
end

outdir = uigetdir(pathstr,'Specify Output Folder');

if iscell(filenames)
    for i=1:length(filenames)
        %construct output filename
        [pathstr, name, ext] = fileparts(filenames{i});
        aoistr = sprintf('_%d_%d_%d_%d_seg_%d',aoi(1),aoi(2),aoi(3),aoi(4),segment);
        outname = [outdir filesep name aoistr '.nitf'];

        %crop image
        chipfile(filenames{i},outname,'azlimits',[aoi(1) aoi(1)+aoi(3)-1],'rnglimits',[aoi(2) aoi(2)+aoi(4)-1],...
                 'framenumber',segment,'file_format','SICD','block_size',2^21);
    end
else
    %construct output filename
    [pathstr, name, ext] = fileparts(filenames);
    aoistr = sprintf('_%d_%d_%d_%d_seg_%d',aoi(1),aoi(2),aoi(3),aoi(4),segment);
    outname = [outdir filesep name aoistr '.nitf'];

    %crop image
    chipfile(filenames,outname,'azlimits',[aoi(1) aoi(1)+aoi(3)-1],'rnglimits',[aoi(2) aoi(2)+aoi(4)-1],...
             'framenumber',segment,'file_format','SICD','block_size',2^21);
end

msgbox('Image Crop Completed');

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