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

% Last Modified by GUIDE v2.5 31-Jul-2020 17:15:00

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

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

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

    populateGUI(handles, lvdData);

    % Update handles structure
    guidata(hObject, handles);

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

function populateGUI(handles, lvdData)
    jScrollPane = findjobj(handles.lvSummaryText);
    jViewPort = jScrollPane.getViewport;
    jEditbox = jViewPort.getComponent(0);
    jEditbox.setWrapping(false);
    jScrollPane.setHorizontalScrollBarPolicy(32);
    jEditbox.setEditable(false);
    jEditbox.revalidate();
    setSummText(handles.lvSummaryText, lvdData.launchVehicle);

function setSummText(hSummText, lv)
    set(hSummText, 'String', lv.getLvSummaryStr());

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

% Get default command line output from handles structure
    if(isempty(handles))
        varargout{1} = [];
    else
        lvdData = getappdata(handles.lvd_editLaunchVehicle, 'lvdData');
        lvdData.initStateModel.clearAllTankStatesAndRegenerate();
        lvdData.initStateModel.clearDuplicateEngineStates();

        close(handles.lvd_editLaunchVehicle);
    end

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

% --- Executes during object creation, after setting all properties.
function lvSummaryText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to lvSummaryText (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 button press in editStagesButton.
function editStagesButton_Callback(hObject, eventdata, handles)
% hObject    handle to editStagesButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    lvdData = getappdata(handles.lvd_editLaunchVehicle, 'lvdData');
    lvd_EditStagesGUI(lvdData);
    setSummText(handles.lvSummaryText, lvdData.launchVehicle);

% --- Executes on button press in editEnginesButton.
function editEnginesButton_Callback(hObject, eventdata, handles)
% hObject    handle to editEnginesButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    lvdData = getappdata(handles.lvd_editLaunchVehicle, 'lvdData');
    lvd_EditEnginesGUI(lvdData);
    setSummText(handles.lvSummaryText, lvdData.launchVehicle);

% --- Executes on button press in editTanksButton.
function editTanksButton_Callback(hObject, eventdata, handles)
% hObject    handle to editTanksButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    lvdData = getappdata(handles.lvd_editLaunchVehicle, 'lvdData');
    lvd_EditTanksGUI(lvdData);
    setSummText(handles.lvSummaryText, lvdData.launchVehicle);

% --- Executes on button press in editEngineToTankConnsButton.
function editEngineToTankConnsButton_Callback(hObject, eventdata, handles)
% hObject    handle to editEngineToTankConnsButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    lvdData = getappdata(handles.lvd_editLaunchVehicle, 'lvdData');
    lvd_EditEngineToTanksConnsGUI(lvdData);
    setSummText(handles.lvSummaryText, lvdData.launchVehicle);

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

% --- Executes on key press with focus on lvd_editLaunchVehicle or any of its controls.
function lvd_editLaunchVehicle_WindowKeyPressFcn(hObject, eventdata, handles)
% hObject    handle to lvd_editLaunchVehicle (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'
            uiresume(handles.lvd_editLaunchVehicle);
        case 'enter'
            uiresume(handles.lvd_editLaunchVehicle);
        case 'escape'
            uiresume(handles.lvd_editLaunchVehicle);
    end

% --- Executes on button press in editTankToTankConnsButton.
function editTankToTankConnsButton_Callback(hObject, eventdata, handles)
% hObject    handle to editTankToTankConnsButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    lvdData = getappdata(handles.lvd_editLaunchVehicle, 'lvdData');
    lvd_EditTankToTankConnsGUI(lvdData);
    setSummText(handles.lvSummaryText, lvdData.launchVehicle);

% --- Executes on button press in editTankFluidTypesButton.
function editTankFluidTypesButton_Callback(hObject, eventdata, handles)
% hObject    handle to editTankFluidTypesButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    lvdData = getappdata(handles.lvd_editLaunchVehicle, 'lvdData');
    lvd_EditTankFluidTypesGUI(lvdData);
    setSummText(handles.lvSummaryText, lvdData.launchVehicle);

% --- Executes on button press in editEpsSrcsButton.
function editEpsSrcsButton_Callback(hObject, eventdata, handles)
% hObject    handle to editEpsSrcsButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    lvdData = getappdata(handles.lvd_editLaunchVehicle, 'lvdData');
    lvd_EditElectricalPowerSrcsGUI(lvdData);
    setSummText(handles.lvSummaryText, lvdData.launchVehicle);

% --- Executes on button press in editEpsStorageButton.
function editEpsStorageButton_Callback(hObject, eventdata, handles)
% hObject    handle to editEpsStorageButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    lvdData = getappdata(handles.lvd_editLaunchVehicle, 'lvdData');
    lvd_EditElectricalPowerStoragesGUI(lvdData);
    setSummText(handles.lvSummaryText, lvdData.launchVehicle);

% --- Executes on button press in editEpsSinksButton.
function editEpsSinksButton_Callback(hObject, eventdata, handles)
% hObject    handle to editEpsSinksButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    lvdData = getappdata(handles.lvd_editLaunchVehicle, 'lvdData');
    lvd_EditElectricalPowerSinksGUI(lvdData);
    setSummText(handles.lvSummaryText, lvdData.launchVehicle);


function errstring = checkstructfields(ds,varargin)

% CHECKSTRUCTFIELDS Checks if a data structure has the required fields.
%
%   errstring = checkstructfields(ds, field1, field2, ...)
%
%   This function checks if data structure 'ds' has the fields specified by the
%   character arrays (strings) 'field1', 'field2', ... e.g.
%
%        missing_fields = checkstructfields(ds, 'field1', 'field2', 'field3');
%
%   The names of the missing fields are returned in 'errstring'.
%
%   Copyright (c) Oregon Health & Science University (2006)
%
%   This file is part of the ReBEL Toolkit. The ReBEL Toolkit is available free for
%   academic use only (see included license file) and can be obtained from
%   http://choosh.csee.ogi.edu/rebel/.  Businesses wishing to obtain a copy of the
%   software should contact rebel@csee.ogi.edu for commercial licensing information.
%
%   See LICENSE (which should be part of the main toolkit distribution) for more
%   detail.

%===============================================================================================

errstring = '';

%-- Check existence of required data structure fields
for j=1:length(varargin),
  if ~ischar(varargin{j})
    error(' [ checkstructfields ]   The field name arguments should be character arrays (strings).');
  end
  if ~isfield(ds,varargin{j}),
    errstring = [varargin{j} ' '];
  end
end


classdef Enableable < handle
    % Mixin for component with Enable property

    % Copyright 2020-2021 The MathWorks Inc.

    %% Properties
    properties (AbortSet)

        % Enable of the component
        Enable (1,1) matlab.lang.OnOffSwitchState = 'on'

    end %properties

    %% Internal properties
    properties (AbortSet, Transient, NonCopyable, ...
            Access = {?wt.abstract.BaseWidget, ?wt.test.BaseWidgetTest} )

        % List of graphics controls to apply to
        EnableableComponents (:,1) matlab.graphics.Graphics

    end %properties

    %% Accessors
    methods

        function set.Enable(obj,value)
            obj.Enable = value;
            obj.updateEnableableComponents()
        end

        function set.EnableableComponents(obj,value)
            obj.EnableableComponents = value;
            obj.updateEnableableComponents()
        end

    end %methods

    %% Methods
    methods (Access = protected)

        function updateEnableableComponents(obj)

            wt.utility.fastSet(obj.EnableableComponents,"Enable",obj.Enable);

        end %function

    end %methods

end %classdef


%  H1 line
%
%  ::
%
%
%  Args:
%
%  Returns:
%     :
%
%  Note:
%
%  Example:
%
%     See also:
%


function varargout = mrmMakeMovieGUI(varargin)
% mrmMakeMovieGUI(meshID)
%   Given a mesh ID #, opens a GUI allowing you to set up a series of
%   events to be displayed in a .avi file.
%
%   Events consist of waypoints, transitions, and pauses.  All pauses must
%   follow waypoints.  Transitions must appear with waypoints on either
%   side.  Move the mesh manually to find the desired waypoint location, or
%   use the presets.
%
% Usage:
%   mrmMakeMovieGUI(meshID);
%
% Known issues:
%   Jump to view isn't accurate with diffusion meshes for whatever reason.
%   Probably need to edit mrmRotateCamera and add a conditional for when
%   we're rotating such meshes, providing different coordinates (should
%   they be consistent across diffusion meshes).
%
% [renobowen@gmail.com 2010]
%

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

function mrmMakeMovieGUI_OpeningFcn(hObject, eventdata, handles, meshID)
    if (~exist('meshID', 'var')), meshID = []; end

    % Choose default command line output for mrmMakeMovieGUI
    handles.output      = hObject;
    handles.meshID      = meshID;
    handles.events      = {};
    handles.isSaved     = true;
    handles.filename    = [];
    handles.filedir     = [];
    handles.clipboard   = [];
    handles.index       = 0;

    set(handles.EventTypeMenu, 'String', {'Waypoint', 'Transition', 'Pause'});

    % Update handles structure
    handles = UpdateFileStatus(handles, true);
    guidata(hObject, handles);

end

function varargout = mrmMakeMovieGUI_OutputFcn(hObject, eventdata, handles)
    if (isempty(handles.meshID))
        fprintf(1, 'No mesh ID # specified - closing GUI.\n');
        close(handles.MakeMovieGUI);
    end
end

function handles = TurnOffInvalidButtons(handles)
    if (isempty(handles.clipboard))
        enablePaste = 'off';
    else
        enablePaste = 'on';
    end
    if (length(handles.events) < 1)
        enableEventDependent = 'off';
    else
        enableEventDependent = 'on';
    end
    % Paste buttons
    set(handles.EventMenu_Paste, 'Enable', enablePaste);
    set(handles.EventContextMenu_Paste, 'Enable', enablePaste);

    % Buttons dependent on existence of events
    set(handles.ExportButton, 'Enable', enableEventDependent);
    set(handles.EditEventButton, 'Enable', enableEventDependent);

    set(handles.PreviewButton, 'Enable', enableEventDependent);
    set(handles.DeleteEventButton, 'Enable', enableEventDependent);

    set(handles.MoveDownButton, 'Enable', enableEventDependent);
    set(handles.MoveUpButton, 'Enable', enableEventDependent);

    set(handles.MovieMenu_Export, 'Enable', enableEventDependent);
    set(handles.MovieMenu_Preview, 'Enable', enableEventDependent);
    set(handles.EventMenu_Delete, 'Enable', enableEventDependent);
    set(handles.EventMenu_Edit, 'Enable', enableEventDependent);

    set(handles.EventMenu_Copy, 'Enable', enableEventDependent);
    set(handles.EventMenu_Cut, 'Enable', enableEventDependent);

    set(handles.EventContextMenu_Delete, 'Enable', enableEventDependent);
    set(handles.EventContextMenu_Edit, 'Enable', enableEventDependent);

    set(handles.EventContextMenu_Copy, 'Enable', enableEventDependent);
    set(handles.EventContextMenu_Cut, 'Enable', enableEventDependent);

    set(handles.FileMenu_SaveAs, 'Enable', enableEventDependent);
    set(handles.FileMenu_Save, 'Enable', enableEventDependent);
end

function handles = UpdateFileStatus(handles, saving)
    if (~isempty(handles.filename))
        if (saving)
            handles.isSaved = true;
            set(handles.FilenameText, 'String', handles.filename);
        else
            handles.isSaved = false;
            set(handles.FilenameText, 'String', [handles.filename '*']);
        end
    else
        if (saving)
            handles.isSaved = true;
        else
            handles.isSaved = false;
        end
        set(handles.FilenameText, 'String', 'No save file.');
    end
    handles = TurnOffInvalidButtons(handles);
end

function EventList_Callback(hObject, eventdata, handles)
    if (length(handles.events) < 1), return; end

    index = get(handles.EventList, 'Value');
    event = handles.events{index};
    if (strcmp(event.eventType,'waypoint'))
        mrmRotateCamera(handles.meshID, event.rotation, [], event.frustum, [], event.origin);
    end
end

function MoveUpButton_Callback(hObject, eventdata, handles)
    index = get(handles.EventList, 'Value');

    ExchangeEvents(hObject, handles, index, index - 1);

end

function MoveDownButton_Callback(hObject, eventdata, handles)
    index = get(handles.EventList, 'Value');

    ExchangeEvents(hObject, handles, index, index + 1);

end

function ExchangeEvents(hObject, handles, selected, exchanged)
    strings = get(handles.EventList, 'String');
    if ((exchanged > length(strings)) || exchanged < 1), return; end

    tmpString           = strings{exchanged};
    strings{exchanged}  = strings{selected};
    strings{selected}   = tmpString;

    tmpEvent                    = handles.events{exchanged};
    handles.events{exchanged}   = handles.events{selected};
    handles.events{selected}    = tmpEvent;

    selected = exchanged;
    set(handles.EventList, 'String', strings);
    set(handles.EventList, 'Value', selected);

	handles = UpdateFileStatus(handles, false);
    guidata(hObject, handles);

end

function AddEvent_Callback(hObject, eventdata, handles, eventType, doInsert)
    % Navigating around a godawful bug with single selection GUIs
    if (length(handles.events) < 1), set(handles.EventList, 'Value', 1); end

    % Get event type from drop down if it's not specified
    if (~exist('eventType', 'var') || isempty(eventType))
        eventTypes = get(handles.EventTypeMenu, 'String');
        eventType = eventTypes{get(handles.EventTypeMenu, 'Value')};
    end

    % Ship off task of getting parameters about event to smaller GUIs
    switch lower(eventType)
        case 'waypoint'
            waitfor(mrmMakeMovieGUI_Waypoint(handles.MakeMovieGUI, handles.meshID));

        case 'transition'
            waitfor(mrmMakeMovieGUI_Transition(handles.MakeMovieGUI));

        case 'pause'
            waitfor(mrmMakeMovieGUI_Pause(handles.MakeMovieGUI));

        otherwise
            fprintf(1, 'Unrecognized radio button selected.\n');

    end

    % Get data back from the GUIs, if any
    data = get(handles.MakeMovieGUI, 'UserData'); % Get the data back from the pop up
    if (isempty(data)), return; end % We're done if there are no params

    % If we're not inserting, tack it after current selection
    numEvents = length(handles.events);
    if (~exist('doInsert', 'var') || isempty(doInsert) || (numEvents < 1))
        index = numEvents + 1;
    else
        index = get(handles.EventList, 'Value') + 1;
    end

    handles = InsertEvent(hObject, handles, data, index);

    set(handles.MakeMovieGUI, 'UserData', []); % Done with the GUI data, clear it
    guidata(hObject, handles);
end

function handles = InsertEvent(hObject, handles, event, position)
% Insert event into visible list and storage array at specified position
    handles.events = CellInsert(handles.events, event, position);
    strings = get(handles.EventList, 'String');
    strings = CellInsert(strings, GetListString(event), position);
    set(handles.EventList, 'Value', position);
    set(handles.EventList, 'String', strings);
    handles = UpdateFileStatus(handles, false);
end

function cells = CellInsert(cells, value, index)
% Insert a value into a cell, shifting over the values in its place if
% necessary
    numCells = length(cells);
    if (numCells >= index)
        for i = numCells:-1:index
            cells{i+1} = cells{i};
        end
    end
    cells{index} = value;
end

function listString = GetListString(data)
    switch (data.eventType)
        case 'waypoint'
            string = '[WAYPOINT]';

        case 'transition'
            string = '[TRANSITION]';

        case 'pause'
            string = '[PAUSE]';

        otherwise
            fprintf(1, 'Unrecognized event type ''%s''', data.eventType);
            listString = [];
            return;

    end

    listString = sprintf('%s %s', string, data.label);
end

function DeleteEvent_Callback(hObject, eventdata, handles)
    index = get(handles.EventList, 'Value');

    strings = get(handles.EventList, 'String');

    strings{index}              = [];
    handles.events{index}       = [];

    strings             = cellRemoveEmpty(strings);
    handles.events      = cellRemoveEmpty(handles.events);

    set(handles.EventList, 'String', strings);

    numEvents = length(handles.events);
    if (numEvents == 0)
        index = 1;
    else
        if (index > numEvents)
            index = numEvents;
        end
    end

    set(handles.EventList, 'Value', index);

	handles = UpdateFileStatus(handles, false);
    guidata(hObject, handles);

end

function frames = CountFrames(events)
    frames = 0;
    numEvents = length(events);
    for i = 1:numEvents
        event = events{i};
        if (isfield(event, 'frames'))
            frames = frames + event.frames;
        end
    end
end

function RenderMovie_Callback(hObject, eventdata, handles, preview)
    if (AreEventsWellFormed(handles))
        frames = CountFrames(handles.events);
        framesPerSec    = str2num(get(handles.FPSTextField, 'String'));
        events          = handles.events;
        nEvents         = length(events);
        lastWaypoint    = [];

        if (~preview) % Set up for saving out movie
            [movFile, movDir]   = uiputfile('brainMovie.avi');
            if (movFile == 0), return; end

        	host                = 'localhost';
            f.filename          = 'nosave';
            frame               = 1;
            ShowProgress(handles, movFile, 0);
            % Skipping preallocation of M, will do so if it's too slow
        end

        for i = 1:nEvents
            event = handles.events{i};
            switch (event.eventType)
                case 'transition'
                    [rotation frustum origin] = BuildTransition(event, lastWaypoint, GetNextWaypoint(events, i));
                    for j = 1:event.frames
                        mrmRotateCamera(handles.meshID, rotation(j, :), [], frustum(j, :), [], origin(j, :));
                        if (~preview)
                            [id,stat,res] = mrMesh(host, handles.meshID, 'screenshot', f);
                            ShowProgress(handles, movFile, frame/frames * 100);
                            M(frame) = im2frame(permute(res.rgb, [2,1,3])./255);
                            frame = frame + 1;
                        end
                    end
                case 'waypoint'
                    lastWaypoint = event;
                    mrmRotateCamera(handles.meshID, event.rotation, [], event.frustum, [], event.origin);
                case 'pause'
                    if (preview)
                        pause(event.frames/framesPerSec);
                    else
                        [id,stat,res] = mrMesh(host, handles.meshID, 'screenshot', f);
                        for j = 1:event.frames
                            ShowProgress(handles, movFile, frame/frames * 100);
                            M(frame) = im2frame(permute(res.rgb, [2,1,3])./255);
                            frame = frame + 1;
                        end
                    end
                otherwise
                    fprintf(1, 'Unrecognized event type ''%s''', data.eventType);
                    return;
            end
        end

        if (~preview)
            if ispc
                % Compressors for Windows are annoying.  None works.  Not
                % sure if the others in doc movie2avi work.
                movie2avi(M, fullfile(movDir,movFile), ...
                    'FPS', framesPerSec, ...
                    'Compression','RLE');
            else
                % Unix/Mac
                movie2avi(M, fullfile(movDir,movFile), ...
                    'FPS', framesPerSec, ...
                    'Compression','None');

            end

            set(handles.ProgressText, 'String', []);
        end

    else
        errordlg('Invalid events list.  See wiki for guidelines.');
    end

end

function ShowProgress(handles, filename, percent)
    set(handles.ProgressText, 'String', sprintf('Exporting %s... %2.0f%%', filename, percent));
end

function [rotation frustum origin] = BuildTransition(transition, waypointStart, waypointEnd)
    nFrames     = transition.frames;
    rotation    = zeros(nFrames, 3);
    rotStart    = waypointStart.rotation;
    rotEnd      = waypointEnd.rotation;

    for i = 1:3
        if (rotEnd(i) == rotStart(i))
            rotation(:, i) = rotStart(i);
            continue;
        end

        switch (transition.rotate{i})
            case '+'
                if (rotEnd(i) < rotStart(i))
                    rotEnd(i) = pi + (pi + rotEnd(i));
                end

            case '-'
                if (rotEnd(i) > rotStart(i))
                    rotEnd(i) = -pi - (pi - rotEnd(i));
                end

            case 'FIX'
                rotation(:,i) = rotStart(i);
                continue;

            otherwise
                fprintf(1, 'Unrecognized rotation direction ''%s''', transition.rotate{i});
        end

        if (rotEnd(i) == rotStart(i))
            rotation(:, i) = rotStart(i);
            continue;
        end

        delta           = rotEnd(i) - rotStart(i);
        rotation(:, i)  = rotStart(i):(delta/(nFrames - 1)):rotEnd(i);
    end

    frustum = InterpolateFrames(waypointStart.frustum, waypointEnd.frustum, nFrames);
    origin  = InterpolateFrames(waypointStart.origin, waypointEnd.origin, nFrames);

end

function vector = InterpolateFrames(start, finish, nFrames)
    nEntries = length(start);
    vector = zeros(nFrames, nEntries);
    for i = 1:nEntries
        if (start(i) == finish(i))
            vector(:,i) = start(i);
            continue;
        end

        delta       = finish(i) - start(i);
        vector(:,i) = start(i):(delta/(nFrames - 1)):finish(i);
    end

end

function waypoint = GetNextWaypoint(events, startInd)
    waypoint = [];
    for i = startInd:length(events)
       if (strcmp(events{i}.eventType, 'waypoint'))
           waypoint = events{i};
           return;
       end
    end
end

function bool = AreEventsWellFormed(handles)
    events  = handles.events;
    nEvents = length(events);

    if (nEvents < 2) % Need at least 2 events (waypoint + pause) to proceed
        bool = false;
        return;
    end

    event = events{1};
    if (~(strcmp(event.eventType, 'waypoint'))) % First event needs to be a waypoint
        bool = false;
        return;
    end

    balanceCounter  = 0;
    hasFrames       = 0;
    for i = 2:nEvents
        event = events{i};
        if (~hasFrames && (strcmp(event.eventType, 'pause') || strcmp(event.eventType, 'transition')))
            hasFrames = 1;
        end

        if (strcmp(event.eventType, 'transition'))
            if (balanceCounter), bool = false; return; end
            balanceCounter = balanceCounter + 1;
        elseif (strcmp(event.eventType, 'waypoint'))
            if (~balanceCounter), continue; end
            balanceCounter = balanceCounter - 1;
        elseif (strcmp(event.eventType, 'pause'))
            if (balanceCounter), bool = false; return; end
        end
    end
    if (~hasFrames || balanceCounter), bool = false; return; end
    bool = true;
end

function EditEvent_Callback(hObject, eventdata, handles)
    events = handles.events;
    nEvents = length(events);
    if (nEvents < 1), return; end
    selected = get(handles.EventList, 'Value');
    editData = events{selected};

    switch (editData.eventType)
        case 'waypoint'
            waitfor(mrmMakeMovieGUI_Waypoint(handles.MakeMovieGUI, handles.meshID, editData));

        case 'transition'
            waitfor(mrmMakeMovieGUI_Transition(handles.MakeMovieGUI, editData));

        case 'pause'
            waitfor(mrmMakeMovieGUI_Pause(handles.MakeMovieGUI, editData));

        otherwise
            fprintf(1, 'Unrecognized radio button selected.\n');

    end

    editData = get(handles.MakeMovieGUI, 'UserData');
    if (isempty(editData)), return; end

    handles.events{selected} = editData;

    strings = get(handles.EventList, 'String');
    strings{selected} = GetListString(editData);
    set(handles.EventList, 'String', strings);

    handles = UpdateFileStatus(handles, false);
    set(handles.MakeMovieGUI, 'UserData', []); % Clear it out to not muck up future use of this var
    guidata(hObject, handles);
end

function SaveData(handles)
    if (~isempty(handles.filename))
        fileID      = 'EventsList';
        version     = 1;
        events      = handles.events;
        save(fullfile(handles.filedir,handles.filename), 'fileID', 'version', 'events');
    end
end

function SaveCheck(hObject, eventdata, handles)
    if (~handles.isSaved)
        buttonChosen = questdlg('Save changes?', 'MakeMovieGUI', 'Yes', 'No', 'Yes');
        if (strcmp(buttonChosen,'Yes'))
            Save_Callback(hObject, eventdata, handles);
        end
    end
end

function New_Callback(hObject, eventdata, handles)
    SaveCheck(hObject, eventdata, handles);
    handles.events = [];
    set(handles.EventList, 'String', []);
    set(handles.EventList, 'Value', 1);
    handles.filename = [];
    handles.filedir = [];
    handles = UpdateFileStatus(handles, true);
    guidata(hObject, handles);
end

function Open_Callback(hObject, eventdata, handles)
    [filename filedir] = uigetfile('*.mat');
    if (filename == 0), return; end

    file = load(fullfile(filedir,filename));
    if (strcmp(file.fileID, 'EventsList'))
        if (file.version <= 1)
            handles.filename    = filename;
            handles.filedir     = filedir;
            handles.events      = {};
            set(handles.EventList, 'String', []);
            set(handles.EventList, 'Value', 1);

            for i = 1:length(file.events)
                handles = InsertEvent(hObject, handles, file.events{i}, i);
            end

            handles = UpdateFileStatus(handles, true);
            guidata(hObject, handles);
        else
            errordlg('Incompatible eventsList file.');
        end
    else
        errordlg('Corrupt/invalid eventsList file.');
    end
end

function Save_Callback(hObject, eventdata, handles)
    if (isempty(handles.filename))
        SaveAs_Callback(hObject, eventdata, handles);
    else
        handles = UpdateFileStatus(handles, true);
        SaveData(handles);
        guidata(hObject, handles);
    end
end

function SaveAs_Callback(hObject, eventdata, handles)
    [filename, filedir]   = uiputfile('brainMovie.mat');
    if (filename == 0), return; end

    handles.filename    = filename;
    handles.filedir     = filedir;
    handles             = UpdateFileStatus(handles, true);

    SaveData(handles);
    guidata(hObject, handles);
end

function Quit_Callback(hObject, eventdata, handles)
    SaveCheck(hObject, eventdata, handles);
    close(handles.MakeMovieGUI);
end

function EventList_KeyPressFcn(hObject, eventdata, handles)
    if (~isempty(cellfind(eventdata.Modifier, 'control')) || ...
            ~isempty(cellfind(eventdata.Modifier, 'command'))) % done to support mac as well as linux
        switch (eventdata.Key)
            case 'x'
                CutEvent_Callback(hObject, eventdata, handles);
            case 'c'
                CopyEvent_Callback(hObject, eventdata, handles);
            case 'v'
                PasteEvent_Callback(hObject, eventdata, handles);
            case 'm'
                EditEvent_Callback(hObject, eventdata, handles);
            case 'd'
                DeleteEvent_Callback(hObject, eventdata, handles);
            case 'n'
                New_Callback(hObject, eventdata, handles);
            case 'o'
                Open_Callback(hObject, eventdata, handles);
            case 's'
                Save_Callback(hObject, eventdata, handles);
            case 'q'
                Quit_Callback(hObject, eventdata, handles);
            case 'p'
                RenderMovie_Callback(hObject, eventdata, handles, 1);
            case 'e'
                RenderMovie_Callback(hObject, eventdata, handles, 0);
            otherwise
        end
    else
        switch (eventdata.Key)
            case 'a'
                MoveUpButton_Callback(hObject, eventdata, handles);
            case 'z'
                MoveDownButton_Callback(hObject, eventdata, handles);
            case 'delete'
                DeleteEvent_Callback(hObject, eventdata, handles);
            otherwise
        end
    end
end

function CutEvent_Callback(hObject, eventdata, handles)
    if (length(handles.events) < 1), return; end
    selected = get(handles.EventList, 'Value');
    handles.clipboard = handles.events{selected};
    DeleteEvent_Callback(hObject, eventdata, handles);
end

function CopyEvent_Callback(hObject, eventdata, handles)
    if (length(handles.events) < 1), return; end
    selected = get(handles.EventList, 'Value');
    handles.clipboard = handles.events{selected};
    handles = TurnOffInvalidButtons(handles);
    guidata(hObject, handles);
end

function PasteEvent_Callback(hObject, eventdata, handles)
    if (~isempty(handles.clipboard))
        if (length(handles.events) < 1)
            handles = InsertEvent(hObject, handles, handles.clipboard, 1);
        else
            selected = get(handles.EventList, 'Value');
            handles = InsertEvent(hObject, handles, handles.clipboard, selected + 1);
        end
        guidata(hObject, handles);
    end
end


function str = makeValidFieldName(str)
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
    isoct=exist('OCTAVE_VERSION','builtin');
    pos=regexp(str,'^[^A-Za-z]','once');
    if(~isempty(pos))
        if(~isoct)
            str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
        else
            str=sprintf('x0x%X_%s',toascii(str(1)),str(2:end));
        end
    end
    if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return;  end
    if(~isoct)
        str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
    else
        pos=regexp(str,'[^0-9A-Za-z_]');
        if(isempty(pos)) return; end
        str0=str;
        pos0=[0 pos(:)' length(str)];
        str='';
        for i=1:length(pos)
            str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
        end
        if(pos(end)~=length(str))
            str=[str str0(pos0(end-1)+1:pos0(end))];
        end
    end


%% unimodalComponent_index.m


function [tcpipClient] = createTcpIpClient(varargin)
%createTcpIpClient Summary of this function goes here
%   Detailed explanation goes here
    global rHost;

    if(isempty(varargin))
        port = 8282;
        role = 'Client';
        if(isempty(rHost))
            rHost = 'localhost';
        end
    else
        port = varargin{1};
        role = varargin{2};
        try
            rHost = varargin{3};
        catch
            if(isempty(rHost))
                rHost = 'localhost';
            end
        end
    end

    tcpipClient = tcpip(rHost,port,'NetworkRole',role);

    tcpipClient.ByteOrder = 'bigEndian';
    set(tcpipClient, 'InputBufferSize',120480);
    set(tcpipClient, 'OutputBufferSize',120480);
    set(tcpipClient, 'Timeout',10);
    set(tcpipClient, 'ReadAsyncMode', 'continuous');
    set(tcpipClient, 'BytesAvailableFcnMode', 'byte');
    set(tcpipClient, 'BytesAvailableFcnCount', 120240);
end


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

% Last Modified by GUIDE v2.5 19-Jan-2008 23:51:34

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

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

% Update handles structure
guidata(hObject, handles);

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

im=imread('osc.jpg');
axis(handles.axes1);
imshow(im);
axis off;

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

set(handles.text3,'string','Initializing.....Please Wait');
pause(2)
set(handles.text3,'string',' ');
query
close('VScope_start');

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

close('VScope_start');


function colorbarAxis = findColorbarAxis(obj,colorbarHandle)
    if isHG2
        colorbarAxisIndex = find(arrayfun(@(x)(isequal(getappdata(x.Handle,'ColorbarPeerHandle'),colorbarHandle)),obj.State.Axis));
    else
        colorbarAxisIndex = find(arrayfun(@(x)(isequal(getappdata(x.Handle,'LegendColorbarInnerList'),colorbarHandle) + ...
            isequal(getappdata(x.Handle,'LegendColorbarOuterList'),colorbarHandle)),obj.State.Axis));
    end
    if isempty(colorbarAxisIndex)
        colorbarAxisIndex = 1;
    end
    colorbarAxis = obj.State.Axis(colorbarAxisIndex).Handle;
end


%--- help for solve_first_order ---
%
%  INTERNAL FUNCTION
%
%
%    Other functions named solve_first_order
%
%       dsge/solve_first_order
%


function rts_initRTSPropPanel(hRtsMainGUI, hPropFig, hClockLabel, connStatusLabel, vesselGUID, hResUITable1, hResSumLabel1, hResUITable2, hResSumLabel2, hResourceCombo1, hResourceCombo2, hMainEngineUITable, hRcsEngineUITable, resourcePanel1, resourcePanel2)
%rts_initRTSPropPanel Summary of this function goes here
%   Detailed explanation goes here

    hResSumProgBar1 = javacomponent('javax.swing.JProgressBar',get(hResSumLabel1,'Position'), resourcePanel1);
    hResSumProgBar2 = javacomponent('javax.swing.JProgressBar',get(hResSumLabel2,'Position'), resourcePanel2);

    hResSumProgBar1.setMinimum(0);
    hResSumProgBar1.setMaximum(100);
    hResSumProgBar2.setMinimum(0);
    hResSumProgBar2.setMaximum(100);

    delete(hResSumLabel1);
    delete(hResSumLabel2);

    timers = getappdata(hRtsMainGUI,'timers');
    utTcpipClient = instrfind('Name','TM_UT');
    resourcesTcpipClient = instrfind('Name','TM_VESSEL_RESOURCES');
    tcpipClientMainEng = instrfind('Name','TM_VESSEL_MAIN_ENGINES');
    tcpipClientRcsEng = instrfind('Name','TM_VESSEL_RCS_ENGINES');

    rtsOpts = getappdata(hRtsMainGUI,'RTSOptions');
    procExecPeriod = 1/str2double(rtsOpts.processFreq);
    procExecMode = rtsOpts.procExecMode;

    clockUpdtFunc = @(obj, event) rts_mainGUIClockUpdateFunc(obj, event, hClockLabel, utTcpipClient);
   	propClockTimer = timer('Name', 'RTSPropClockUpdate',...
                                    'ExecutionMode', 'fixedRate', ...   % Run timer repeatedly
                                    'Period', 1, ...                % Initial period is 1 sec.
                                    'StartDelay',0.1, ...
                                    'TimerFcn', clockUpdtFunc); % Specify callback
	set(propClockTimer,'UserData',{false}); %disallow user edits

    connUpdtFunc = @(obj, event) rts_pageGetConnStatus(obj, event, vesselGUID, hRtsMainGUI, connStatusLabel);
    connStopFcn = @(obj, event) rts_pageGetConnStatus(obj, event, vesselGUID, hRtsMainGUI, connStatusLabel, false);
   	propConnStatusTimer = timer('Name', 'RTSPropConnStatusUpdate',...
                                    'ExecutionMode', 'fixedRate', ...   % Run timer repeatedly
                                    'Period', 1, ...                % Initial period is 1 sec.
                                    'StartDelay',0.3, ...
                                    'StopFcn', connStopFcn, ...
                                    'TimerFcn', connUpdtFunc); % Specify callback
	set(propConnStatusTimer,'UserData',{false}); %disallow user edits

    resUpdt1Func = @(obj, event) rts_propUpdateFunc(obj, event, hPropFig, resourcesTcpipClient, tcpipClientMainEng, tcpipClientRcsEng, hResUITable1, hResSumProgBar1, hResUITable2, hResSumProgBar2, hResourceCombo1, hResourceCombo2, hMainEngineUITable, hRcsEngineUITable);
   	resUpt1Timer = timer('Name', 'RTSPowerThermResourceUpdate',...
                                    'ExecutionMode', procExecMode, ...   % Run timer repeatedly
                                    'Period', procExecPeriod, ...                % Initial period is 1 sec.
                                    'StartDelay',0.0, ...
                                    'TimerFcn', resUpdt1Func); % Specify callback
    set(resUpt1Timer,'UserData',{true}); %allow user edits

    start(propClockTimer);
    start(propConnStatusTimer);
    start(resUpt1Timer);

    timers(end+1) = propClockTimer;
    timers(end+1) = propConnStatusTimer;
    timers(end+1) = resUpt1Timer;
    setappdata(hRtsMainGUI,'timers', timers);

    timersProp = timer.empty(1,0);
    timersProp(end+1) = propClockTimer;
    timersProp(end+1) = propConnStatusTimer;
    timersProp(end+1) = resUpt1Timer;
    setappdata(hPropFig,'timers', timersProp);
end


function siftroot = hlp_getSiftRoot
% get the root path for SIFT

siftroot = fileparts(utl_whichfile('StartSIFT'));


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

% Last Modified by GUIDE v2.5 21-Jan-2019 13:19:19

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

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

    centerUIFigure(hObject);

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

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

    populateGUI(handles, action, lv);

    % Update handles structure
    guidata(hObject, handles);

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

function populateGUI(handles, action, lv)
    [t2TConnStr, t2TConns] = lv.getTankToTankConnectionsListBoxStr();
    set(handles.refConnCombo,'String',t2TConnStr);

    if(not(isempty(action.conn)))
        ind = find(t2TConns == action.conn,1,'first');
    else
        ind = [];
    end

    if(not(isempty(ind)))
        set(handles.refConnCombo,'Value',ind);
    end

    handles.flowRateText.String = fullAccNum2Str(action.flowRateToSet);

% --- Outputs from this function are returned to the command line.
function varargout = lvd_EditActionSetTankToTankConnFlowRateGUI_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
        action = getappdata(hObject,'action');
        lv = getappdata(hObject,'lv');

        [~, t2TConns] = lv.getTankToTankConnectionsListBoxStr();
        ind = get(handles.refConnCombo,'Value');
        action.conn = t2TConns(ind);

        action.flowRateToSet = str2double(handles.flowRateText.String);

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

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

    val = str2double(get(handles.flowRateText,'String'));
    enteredStr = get(handles.flowRateText,'String');
    numberName = 'Flow Rate';
    lb = 0;
    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_EditActionSetTankToTankConnFlowRateGUI);

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

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

% --- Executes during object creation, after setting all properties.
function stateCombo_CreateFcn(hObject, eventdata, handles)
% hObject    handle to stateCombo (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 key press with focus on lvd_EditActionSetTankToTankConnFlowRateGUI or any of its controls.
function lvd_EditActionSetTankToTankConnFlowRateGUI_WindowKeyPressFcn(hObject, eventdata, handles)
% hObject    handle to lvd_EditActionSetTankToTankConnFlowRateGUI (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_EditActionSetTankToTankConnFlowRateGUI);
    end

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

% --- Executes during object creation, after setting all properties.
function flowRateText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to flowRateText (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 setdefaultbutton(figHandle, btnHandle)
% WARNING: This feature is not supported in MATLAB and the API and
% functionality may change in a future release.

%SETDEFAULTBUTTON Set default button for a figure.
%  SETDEFAULTBUTTON(BTNHANDLE) sets the button passed in to be the default button
%  (the button and callback used when the user hits "enter" or "return"
%  when in a dialog box.
%
%  This function is used by inputdlg.m, msgbox.m, questdlg.m and
%  uigetpref.m.
%
%  Example:
%
%  f = figure;
%  b1 = uicontrol('style', 'pushbutton', 'string', 'first', ...
%       'position', [100 100 50 20]);
%  b2 = uicontrol('style', 'pushbutton', 'string', 'second', ...
%       'position', [200 100 50 20]);
%  b3 = uicontrol('style', 'pushbutton', 'string', 'third', ...
%       'position', [300 100 50 20]);
%  setdefaultbutton(b2);
%

%  Copyright 2005-2007 The MathWorks, Inc.

%--------------------------------------- NOTE ------------------------------------------
% This file was copied into matlab/toolbox/local/private.
% These two files should be kept in sync - when editing please make sure
% that *both* files are modified.

% Nargin Check
if nargin<1, error('MATLAB:setdefaultbutton:InvalidNumberOfArguments','Too few arguments for setdefaultbutton'); end
if nargin>2, error('MATLAB:setdefaultbutton:InvalidNumberOfArguments','Too many arguments for setdefaultbutton'); end

try
    ujava = feature('javafigures');
catch
    ujava = true;
end
if ujava && (usejava('awt') == 1)
    % We are running with Java Figures
    useJavaDefaultButton(figHandle, btnHandle)
else
    % We are running with Native Figures
    useHGDefaultButton(figHandle, btnHandle);
end

    function useJavaDefaultButton(figH, btnH)
        % Get a UDD handle for the figure.
        fh = handle(figH);
        % Call the setDefaultButton method on the figure handle
        fh.setDefaultButton(btnH);
    end

    function useHGDefaultButton(figHandle, btnHandle)
        % First get the position of the button.
        btnPos = getpixelposition(btnHandle);

        % Next calculate offsets.
        leftOffset   = btnPos(1) - 1;
        bottomOffset = btnPos(2) - 2;
        widthOffset  = btnPos(3) + 3;
        heightOffset = btnPos(4) + 3;

        % Create the default button look with a uipanel.
        % Use black border color even on Mac or Windows-XP (XP scheme) since
        % this is in natve figures which uses the Win2K style buttons on Windows
        % and Motif buttons on the Mac.
        h1 = uipanel(get(btnHandle, 'Parent'), 'HighlightColor', 'black', ...
            'BorderType', 'etchedout', 'units', 'pixels', ...
            'Position', [leftOffset bottomOffset widthOffset heightOffset]);

        % Make sure it is stacked on the bottom.
        uistack(h1, 'bottom');
    end
end


function varargout = ft_transform_headmodel(varargin)

% This function is a backward compatibility wrapper for existing MATLAB scripts
% that call a function that is not part of the FieldTrip toolbox any more.
%
% Please update your code to make it future-proof.

oldname = mfilename;
newname = 'ft_transform_geometry';

ft_warning('%s is only a backward compatibility wrapper, which will soon be removed. Please call %s instead.', upper(oldname), upper(newname));

[varargout{1:nargout}] = feval(newname, varargin{:});


function tname = treepart(item, dflag)

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

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

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

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


function [ output_args ] = net_turnOffServer( t )
%% This function is used to turn off the server on the robot
% function [ output_args ] = net_turnOffServer( t )
% t: is the TCP/IP connection object
% Copy right, Mohammad SAFEEA, 3rd of May 2017

theCommand='end';
fprintf(t, theCommand);
fclose(t);
%message=fgets(t);
end


function [nam] = get_name(dat)

%   get_name(DATA)      returns name describing the object
  nam=dat.algorithm.name;

%%%% SGE support
if isdeferred(dat), nam = get_name(dat.algorithm.deferred, nam, 1); end
%%%%


function x = relaxdouble(x)
%RELAXDOUBLE (overloaded sdpvar/relaxdouble on double)

% Do nothing, just return input.


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

% Copyright 2002-2003 The MathWorks, Inc.

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

% Last Modified by GUIDE v2.5 14-Nov-2005 01:26:22

%* Author: Ranjith Unnikrishnan                                          *
%* Carnegie Mellon University, Vision and Mobile Robotics Laboratory     *
%* THE MATERIAL EMBODIED IN THIS SOFTWARE IS PROVIDED TO YOU "AS-IS"     *
%* AND WITHOUT WARRANTY OF ANY KIND, EXPRESS, IMPLIED OR OTHERWISE,      *
%* INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY OR      *
%* FITNESS FOR A PARTICULAR PURPOSE.  IN NO EVENT SHALL CARNEGIE MELLON  *
%* UNIVERSITY BE LIABLE TO YOU OR ANYONE ELSE FOR ANY DIRECT,            *
%* SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY         *
%* KIND, OR ANY DAMAGES WHATSOEVER, INCLUDING WITHOUT LIMITATION,        *
%* LOSS OF PROFIT, LOSS OF USE, SAVINGS OR REVENUE, OR THE CLAIMS OF     *
%* THIRD PARTIES, WHETHER OR NOT CARNEGIE MELLON UNIVERSITY HAS BEEN     *
%* ADVISED OF THE POSSIBILITY OF SUCH LOSS, HOWEVER CAUSED AND ON        *
%* ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE     *
%* POSSESSION, USE OR PERFORMANCE OF THIS SOFTWARE.                      *
%

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

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

% Update handles structure
guidata(hObject, handles);

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

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


%--- help for potential_scale_reduction ---
%
%  INTERNAL FUNCTION
%
%
%    Other functions named potential_scale_reduction
%
%       dsge/potential_scale_reduction
%


function new_slide = pptTitle(op, ttlText, fontSize, fontName);
%
% new_slide = pptTitle(op, ttlText, [fontSize=32], [fontName]);
%
% Add a title slide to a PowerPoint presentation, with the provided
% text. The optional fontSize and fontName fields allow you to specify
% the type and size of the text font. The default fontSize is 32, the
% default fontName is whatever is saved in the power point file's template.
%
% SEE ALSO: pptOpen, pptPaste, pptClose.
%
% ras, 07/2007.
if ~exist('fontSize', 'var'),	fontSize = 32;		end
if notDefined('fontName'),	fontName = '';		end

slide_count = get(op.Slides, 'Count');

% Add a the title slide:
slide_count = int32(double(slide_count)+1);
new_slide = invoke(op.Slides, 'Add', slide_count, 1);

% Set the title text, font
set(new_slide.Shapes.Title.TextFrame.TextRange, 'Text', ttlText);

if ~isempty(fontSize)
	set(new_slide.Shapes.Title.TextFrame.TextRange.Font, 'Size', fontSize);
end

if ~isempty(fontName)
	set(new_slide.Shapes.Title.TextFrame.TextRange.Font, 'Name', fontName);
end

return


classdef GemCheckbox < GemUserInterfaceObject
    % GemCheckbox GEM class for a check box control
    %
    %
    %     Licence
    %     -------
    %     Part of GEM. https://github.com/tomdoel/gem
    %     Author: Tom Doel, 2013.  www.tomdoel.com
    %     Distributed under the MIT licence. Please see website for details.
    %

    properties
        FontSize
        FontColour
        BackgroundColour
        HorizontalAlignment
    end

    properties (Access = private)
        Text
        Tag
        ToolTip
        Checked
    end

    events
        CheckChanged
    end

    methods
        function obj = GemCheckbox(parent, text, tooltip, tag)
            obj = obj@GemUserInterfaceObject(parent);
            obj.Text = text;
            obj.ToolTip = tooltip;
            obj.Tag = tag;
            obj.FontSize = 11;
            obj.HorizontalAlignment = 'left';
            obj.Checked = false;
            obj.FontColour = obj.StyleSheet.TextPrimaryColour;
            obj.BackgroundColour = obj.StyleSheet.BackgroundColour;
        end

        function CreateGuiComponent(obj, position)
            obj.GraphicalComponentHandle = uicontrol('Style', 'checkbox', 'Parent', obj.Parent.GetContainerHandle, ...
                'Units', 'pixels', 'Position', position, 'Tag', obj.Tag, 'ToolTipString', obj.ToolTip, ...
                'ForegroundColor', obj.FontColour, 'BackgroundColor', obj.BackgroundColour, ...
                'FontUnits', 'pixels', 'FontSize', obj.FontSize, 'FontAngle', 'normal', ...
                'HorizontalAlignment', obj.HorizontalAlignment, 'String', obj.Text, ...
                'Callback', @obj.CheckboxCallback, 'Value', obj.Checked);
        end

        function ChangeChecked(obj, checked)
            obj.Checked = checked;
            if obj.ComponentHasBeenCreated && ishandle(obj.GraphicalComponentHandle)
                set(obj.GraphicalComponentHandle, 'Value', checked);
            end
        end
    end

    methods (Access = protected)
        function CheckboxCallback(obj, hObject, ~, ~)
            checked = get(hObject,'Value');
            obj.Checked = checked;
            notify(obj, 'CheckChanged', CoreEventData(checked));
        end
    end
end


function x = subsasgn( x, S, y )
error( 'Subscripted assignment not allowed for these objects.' );

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


function obj = modelVarsFromFilesCheck(obj,folderNo,varargin)
	% Checks whether a specific folder has variables loaded, if not loads them.
	% Biafra Ahanonu
	% started: 2021.06.18 [20:25:49]
	% inputs
		%
	% outputs
		%

	% changelog
		% 2021.06.21 [21:03:42] - Add check for objLocations
		% 2021.08.10 [09:57:36] - Updated to handle CIAtah v4.0 switch to all functions inside ciapkg package.
	% TODO
		%

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

	% ========================
	% DESCRIPTION
	options.baseOption = '';
	% get options
	options = getOptions(options,varargin);
	% display(options)
	% unpack options into current workspace
	% fn=fieldnames(options);
	% for i=1:length(fn)
	% 	eval([fn{i} '=options.' fn{i} ';']);
	% end
	% ========================

	try
		try
			max(1,round(obj.objLocations{folderNo}.(obj.signalExtractionMethod)(:,1)));
			[rawSignals rawImages signalPeaks signalPeaksArray, ~, ~, rawSignals2] = modelGetSignalsImages(obj,'returnType','raw');
			% obj.nSignals{fileNum}
			skipReload = 1;
		catch
			obj.guiEnabled = 0;
			% originalFileNum =
            oldTmp = obj.foldersToAnalyze;
            obj.foldersToAnalyze = folderNo;
			obj.modelVarsFromFiles();
            obj.foldersToAnalyze = oldTmp;
			obj.fileNum = folderNo;
			obj.guiEnabled = 1;
			skipReload = 0;
		end
	catch err
		display(repmat('@',1,7))
		disp(getReport(err,'extended','hyperlinks','on'));
		display(repmat('@',1,7))
	end

end


function sde_install(opt)
%SDE_INSTALL  Add or remove SDETools from Matlab search path and save path.
%   SDE_INSTALL adds the SDETools directory (where this function is located) to
%   the Matlab search path, saves the path, and prints the help for the toolbox.
%
%   SDE_INSTALL('remove') uninstalls SDETools by removing the SDETools directory
%   from the Matlab search path and saving the path. If SDETools is not
%   installed (on the path), a warning is issued.
%
%   See also: PATH, ADDPATH, RMPATH, SAVEPATH

%   Andrew D. Horchler, horchler @ gmail . com, Created 8-12-13
%   Revision: 1.2, 11-16-13

if nargin == 0 || any(strcmp(opt,{'add','install','addpath'}))
    addpath(fileparts(mfilename('fullpath')));
    status = true;
elseif any(strcmp(opt,{'remove','uninstall','rmpath'}))
    rmpath(fileparts(mfilename('fullpath')));
    status = false;
else
    error('SDETools:sde_install:UnknownOption',...
         ['Input argument must be the string ''install'' to install or '...
          '''remove'' to uninstall.']);
end

if savepath
    error('SDETools:sde_install:SavePathError',...
          'Unable to save pathdef.m file.');
end
rehash('toolbox');
clear('sde_install');

if status
    fprintf(1,'\n SDETools installed.\n\n');
    help('SDETools');
else
    fprintf(1,'\n SDETools uninstalled.\n');
end


function [status, errmsg] = ensureDirExists(pth)
% Make sure a directory exists, creating parent directories if needed
%
%  [status, errmsg] = ensureDirExists(pth);
%
% Status = 1 if the path exists or is successfully created, 0 otherwise.
%
% ras 06/06.

if ~ischar(pth), help(mfilename); error('Need a path string'); end

status = 0;
errmsg = '';

if exist(fullpath(pth),'dir') & ~isequal(pth(2),'\')
    % Person sent in a full path that exists.  We are done.
    status = 1;
    return
end

% The person sent in a path that doesn't fully exist.  So we are going to
% live dangerously and create the path for them.  Part of the path might
% exist, and we follow that down, until we start creating the new elements
% of the path.
%

% find all the directory strings
clear subdirs
if isequal(pth(2),'\')
    % Trap the case when we have a mount: \\white.stanford.edu, for example
    tmpPath = pth(3:end);
    tmpPath = ['C:\',tmpPath];  % Cheap hack to make explode work
    tmpSubDirs = explode(filesep,tmpPath);
    subdirs = cell(1,length(tmpSubDirs) - 1);
    for ii=2:length(tmpSubDirs)
        subdirs{ii-1} = tmpSubDirs{ii};
    end
    % Append the \\ in front of the computer name
    tmp = subdirs{1}; tmp = ['\\',tmp]; subdirs{1} = tmp;
else
    subdirs = explode(filesep, fullpath(pth));
end

% step through each subdir, progressively checking
% child directories within parent dirs
if isunix,  par = [filesep subdirs{1}];
else        par = subdirs{1};
end

for ii = 2:length(subdirs)
    if ~exist(fullfile(par,subdirs{ii}),'dir')
        try
            [status, errmsg] = mkdir(par,subdirs{ii});
        catch
            fprintf('ensureDir Exists: Creation of intermediate dir failed: ')
            fprintf('%s\n',errmsg)
            return
        end
        fprintf('Created directory %s%s%s\n',par,filesep,subdirs{ii});
    end

    par = fullfile(par,subdirs{ii});
end

status = 1;

return


function fid = openLogFile(filename,mode)

% OPENLOGFILE  Open log file.
%   FID = OPENLOGFILE(FILENAME,MODE) opens the file FILENAME in MODE mode.
%   The mode MODE is a string in {'r','read','w','write'}. FID is the file
%   identifer used in other IO functions.
%
%   See also WRITELOGHEADER, WRITELOGDATA, CLOSELOGFILE, FOPEN.

switch mode
    case {'r','read'}
        m = 'r';
    case {'w','write'}
        m = 'w';
end

fid =fopen(filename,m);

% ========== End of function - Start GPL license ==========

%   # START GPL LICENSE

%---------------------------------------------------------------------
%
%   This file is part of SLAMTB, a SLAM toolbox for Matlab.
%
%   SLAMTB 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.
%
%   SLAMTB 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 SLAMTB.  If not, see <http://www.gnu.org/licenses/>.
%
%---------------------------------------------------------------------

%   SLAMTB is Copyright:
%   Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,
%   Copyright (c) 2010-2013, Joan Sola,
%   Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,
%   SLAMTB is Copyright 2009
%   by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol
%   @ LAAS-CNRS.
%   See on top of this file for its particular copyright.

%   # END GPL LICENSE


function out = runtests_xunit(varargin)
%runtests Run unit tests
%   runtests runs all the test cases that can be found in the current directory
%   and summarizes the results in the Command Window.
%
%   Test cases can be found in the following places in the current directory:
%
%       * An M-file function whose name starts or ends with "test" or
%         "Test" and that returns no output arguments.
%
%       * An M-file function whose name starts or ends with "test" or
%         "Test" and that contains subfunction tests and uses the
%         initTestSuite script to return a TestSuite object.
%
%       * An M-file defining a subclass of TestCase.
%
%   runtests(dirname) runs all the test cases found in the specified directory.
%
%   runtests(packagename) runs all the test cases found in the specified
%   package. (This option requires R2009a or later).
%
%   runtests(mfilename) runs test cases found in the specified function or class
%   name. The function or class needs to be in the current directory or on the
%   MATLAB path.
%
%   runtests('mfilename:testname') runs the specific test case named 'testname'
%   found in the function or class 'name'.
%
%   Multiple directories or file names can be specified by passing multiple
%   names to runtests, as in runtests(name1, name2, ...) or
%   runtests({name1, name2, ...}, ...)
%
%   runtests(..., '-verbose') displays the name and result, result, and time
%   taken for each test case to the Command Window.
%
%   runtests(..., '-logfile', filename) directs the output of runtests to
%   the specified log file instead of to the Command Window.
%
%   out = runtests(...) returns a logical value that is true if all the
%   tests passed.
%
%   Examples
%   --------
%   Find and run all the test cases in the current directory.
%
%       runtests
%
%   Find and run all the test cases in the current directory. Display more
%   detailed information to the Command Window as the test cases are run.
%
%       runtests -verbose
%
%   Save verbose runtests output to a log file.
%
%       runtests -verbose -logfile my_test_log.txt
%
%   Find and run all the test cases contained in the M-file myfunc.
%
%       runtests myfunc
%
%   Find and run all the test cases contained in the TestCase subclass
%   MyTestCase.
%
%       runtests MyTestCase
%
%   Run the test case named 'testFeature' contained in the M-file myfunc.
%
%       runtests myfunc:testFeature
%
%   Run all the tests in a specific directory.
%
%       runtests c:\Work\MyProject\tests
%
%   Run all the tests in two directories.
%
%       runtests c:\Work\MyProject\tests c:\Work\Book\tests

%   Steven L. Eddins
%   Copyright 2009-2010 The MathWorks, Inc.

verbose = false;
logfile = '';
if nargin < 1
    suite = TestSuite.fromPwd();
else
    [name_list, verbose, logfile] = getInputNames(varargin{:});
    if numel(name_list) == 0
        suite = TestSuite.fromPwd();
    elseif numel(name_list) == 1
        suite = TestSuite.fromName(name_list{1});
    else
        suite = TestSuite();
        for k = 1:numel(name_list)
            suite.add(TestSuite.fromName(name_list{k}));
        end
    end
end

if isempty(suite.TestComponents)
    error('xunit:runtests:noTestCasesFound', 'No test cases found.');
end

if isempty(logfile)
    logfile_handle = 1; % File handle corresponding to Command Window
else
    logfile_handle = fopen(logfile, 'w');
    if logfile_handle < 0
        error('xunit:runtests:FileOpenFailed', ...
            'Could not open "%s" for writing.', logfile);
    else
        cleanup = onCleanup(@() fclose(logfile_handle));
    end
end

fprintf(logfile_handle, 'Test suite: %s\n', suite.Name);
if ~strcmp(suite.Name, suite.Location)
    fprintf(logfile_handle, 'Test suite location: %s\n', suite.Location);
end
fprintf(logfile_handle, '%s\n\n', datestr(now));

if verbose
    monitor = VerboseTestRunDisplay(logfile_handle);
else
    monitor = TestRunDisplay(logfile_handle);
end
did_pass = suite.run(monitor);

if nargout > 0
    out = did_pass;
end

function [name_list, verbose, logfile] = getInputNames(varargin)
name_list = {};
verbose = false;
logfile = '';
k = 1;
while k <= numel(varargin)
    arg = varargin{k};
    if iscell(arg)
        name_list = [name_list; arg];
    elseif ~isempty(arg) && (arg(1) == '-')
        if strcmp(arg, '-verbose')
            verbose = true;
        elseif strcmp(arg, '-logfile')
            if k == numel(varargin)
                error('xunit:runtests:MissingLogfile', ...
                    'The option -logfile must be followed by a filename.');
            else
                logfile = varargin{k+1};
                k = k + 1;
            end
        else
            warning('runtests:unrecognizedOption', 'Unrecognized option: %s', arg);
        end
    else
        name_list{end+1} = arg;
    end
    k = k + 1;
end


function addToExecutionWarnings(warnStr, eventNum, bodyID, celBodyData)
%addToExecutionWarnings Summary of this function goes here
%   Detailed explanation goes here
    global script_execution_warnings;

    if(bodyID == -1)
        bNameStr = '';
    else
        bodyInfo = getBodyInfoByNumber(bodyID, celBodyData);
        bName = bodyInfo.name;
        bNameStr = [' (',bName ')'];
    end

    if(isempty(eventNum) || eventNum == -1)
        eventStr = '';
    else
        eventStr = ['Event ', num2str(eventNum), bNameStr, ': '];
    end

    execWarn = script_execution_warnings;
    execWarn{end+1} = [eventStr, warnStr];
    script_execution_warnings = execWarn;
end


function r = quantity(a)

r = a.quantity;


classdef Jab < handle
  % .jab files

  methods (Static)

    function J = load(jabfile)
      % J = load(jabfile)
      %
      % J: Modernized Macguffin object

      assert(ischar(jabfile) && exist(jabfile,'file')==2,...
        'Cannot find jabfile ''%s''.',jabfile);

      J = loadAnonymous(jabfile);
      if isstruct(J)
        J = Macguffin(J);
      end
      J.modernize();
    end

    function save(J,jabfile)
      saveAnonymous(jabfile,J);
    end

    function savePrompt(J,jabfile)
      if exist('jabfile','var')==0
        jabfile = [];
      end
      [fname,pname] = uiputfile('*.jab','Save',jabfile);
      fname = fullfile(pname,fname);
      Jab.save(J,fname);
    end

    function [tfsuccess,jabfiles] = uiGetJabFiles(varargin)
      % [tfsuccess,jabfiles] = uiGetJabFiles(p1,v1,...)
      %
      % Nice(r) GUI for multiple jab selection.
      %
      % Optional PVs:
      %  * promptstr, char.
      %
      % tfsuccess: if false, user canceled GUI
      % jabfiles: cellstr

      promptstr = myparse(varargin,...
        'promptstr','Select jab files');

      %jabpath = ExpPP.loadConfigVal('jabpath');
      jabpath = [];
      if isempty(jabpath)
        jabpath = pwd;
      end
      jabfiles = uipickfiles('Prompt',promptstr,...
        'FilterSpec',jabpath,'Type',{'*.jab','JAB-files'},'SmartAdd',true);
      if ~iscell(jabfiles) || isempty(jabfiles), % canceled
        tfsuccess = false;
        jabfiles = [];
      else
        tfsuccess = true;
        %jabpath = fileparts(jabfiles{1});
        %ExpPP.saveConfigVal('jabpath',jabpath);
      end
    end

    function clearLabels(jabfile,realbeh)
      % Clear all labels for realbeh and No-realbeh

      J = Jab.load(jabfile);

      jabrealbehs = J.behaviors.names(1:J.behaviors.nbeh);
      tf = strcmpi(realbeh,jabrealbehs);
      assert(any(tf),'Specified behavior ''%s'' not present in jabfile.',realbeh);
      assert(nnz(tf)==1);
      realbeh = jabrealbehs{tf}; % case could be different

      tfMultiCls = J.behaviors.nbeh>1;
      if tfMultiCls
        nobeh = Labels.noBehaviorName(realbeh);
      else
        nobeh = 'None';
      end

      J.labels = Labels.clearLabels(J.labels,realbeh,realbeh);
      J.labels = Labels.clearLabels(J.labels,nobeh,realbeh);

      J.savePrompt(J,jabfile);
    end

    function tf = isMultiClassifier(jabfile)
      % tf = isMultiClassifier(jabfile)
      J = Jab.load(jabfile);
      tf = J.isMultiClassifier();
    end

    function rmClassifier(jabfile,clsnames)
      % rmClassifier(jabfile,clsnames)
      %
      % jab: char, jab filename
      % clsname: char or cellstr

      J = Jab.load(jabfile);
      Jbeh = J.behaviors;
      Jclsnames = Jbeh.names(1:Jbeh.nbeh);

      if exist('clsnames','var')>0
        if ischar(clsnames)
          clsnames = cellstr(clsnames);
        end
        assert(iscellstr(clsnames),'Expected ''clsname'' argument to be a char or cellstr.');
      else
        [sel,ok] = listdlg('PromptString','Select classifiers to remove:',...
          'ListString',Jclsnames,...
          'ListSize',[240 240]);
        if ~ok
          return;
        end
        clsnames = Jclsnames(sel);
      end

      [tf,iClsRm] = ismember(clsnames,Jclsnames);
      if ~all(tf)
        clsmissing = clsnames(~tf);
        error('Jab:rmClassifier','Classifier(s) %s not present in jabfile.',...
          civilizedStringFromCellArrayOfStrings(clsmissing));
      end

      nClsRm = numel(iClsRm);
      nClsNew = Jbeh.nbeh - nClsRm;
      if nClsNew==0
        error('Jab:rmClassifier','Cannot remove all classifiers from a .jab file.');
      end

      iLblsRm = [iClsRm iClsRm+Jbeh.nbeh];
      origBehs = J.behaviors.names(iClsRm);
      origNoBehs = J.behaviors.names(iClsRm+Jbeh.nbeh);
      J.behaviors.names(iLblsRm) = [];
      J.behaviors.labelcolors(iLblsRm,:) = [];
      J.behaviors.nbeh = nClsNew;
      J.file.scorefilename(iClsRm) = [];
      J.windowFeaturesParams(iClsRm) = [];
      for iCls = 1:nClsRm
        J.labels = Labels.removeClassifier(J.labels,origBehs{iCls},origNoBehs{iCls});
        J.gtLabels = Labels.removeClassifier(J.gtLabels,origBehs{iCls},origNoBehs{iCls});
      end
      J.classifierStuff(iClsRm) = [];

      % Quirk, no-beh name for single-classifier projs
      if nClsNew==1
        oldNoBehavior = J.behaviors.names{2};
        newNoBehavior = 'None';
        J.behaviors.names{2} = newNoBehavior;

        J.labels = Labels.renameBehaviorRaw(J.labels,oldNoBehavior,newNoBehavior);
        J.gtLabels = Labels.renameBehaviorRaw(J.gtLabels,oldNoBehavior,newNoBehavior);

        % ALXXX to be fixed
        warning('Jab:rmClassifier',...
          'Going from multi-classifier to single-classifier project. Label importance may not be set correctly for GT mode.');
      end

      Jab.savePrompt(J,jabfile);
    end

    function tf = formatChangedBetweenVersions(v1,v2)
      % v2 should be later-than-or-equal-to-v1.
      %
      % This method introduced in version 0.6.0. Jabs saved in prior
      % versions have version prop enclosed in double-cell array. We avoid
      % the complications for now and just return true if v2 is 0.6.0 and
      % v1 is not. This will need to be updated with subsequent versions.

      tf = strcmp(v2,'0.6.0') && ~strcmp(v1,'0.6.0');
    end

    function merge(jabfiles,jabout)
      % jabMerge(jabfiles,jabout)
      % Merge two or more jab files.
      %
      % Behaviors with the same name (precisely, case-sensitive, etc) are
      % treated as the same classifier. Experiment names/directories should
      % be in a consistent format.
      %
      % jabfiles: optional. cellstr of jab filenames
      % jabout: optional. output jab filename

      if ~exist('jabfiles','var') || isempty(jabfiles)
        [tfsuccess,jabfiles] = Jab.uiGetJabFiles('promptstr','Select jab files to combine');
        if ~tfsuccess
          return;
        end
      end

      if ischar(jabfiles)
        jabfiles = cellstr(jabfiles);
      end
      assert(iscellstr(jabfiles),'Expected ''jabfiles'' to be a cellstr of jab filenames.');

      Js = cellfun(@Jab.load,jabfiles,'uni',0);
      Js = cat(1,Js{:});
      Jmerge = Macguffin(Js);

      % come up with a proposed name for combined jab
      if ~exist('jabout','var') || isempty(jabout)
        MAXFILENAMELENGTH = 45;
        behnames = Labels.verifyBehaviorNames(Jmerge.behaviors.names);
        combjabname = '';
        for i = 1:numel(behnames)
          combjabname = [combjabname behnames{i} '.']; %#ok<AGROW>
          if numel(combjabname)>MAXFILENAMELENGTH
            combjabname = [combjabname 'etc.']; %#ok<AGROW>
            break;
          end
        end
        combjabname = [combjabname 'jab'];

        %jabpath = ExpPP.loadConfigVal('jabpath');
        jabpath = [];
        if isempty(jabpath)
          jabpath = pwd;
        end
        [filename,pathname] = ...
          uiputfile({'*.jab','JAABA files (*.jab)'},'Save combined jabfile',fullfile(jabpath,combjabname));
        if ~ischar(filename),
          % user hit cancel
          return;
        end

        jabout = fullfile(pathname,filename);
      else
        if exist(jabout,'file')
          uiwait(warndlg(sprintf('Output file ''%s'' exists and will be overwritten.',jabout)));
        end
      end

      Jab.save(Jmerge,jabout);
      %ExpPP.saveConfigVal('jabpath',fileparts(jabout));
    end

    function [scorefiles,behaviors] = jabfileScoresBehs(jabname)
      % [scorefiles,behaviors] = jabfileScoresBehs(jabname)
      % scorefile: cellstr of score files
      % behaviors: cellstr of "real" behaviors (doesn't include No_<beh>)

      x = loadAnonymous(jabname);
      scorefiles = x.file.scorefilename;
      if ischar(scorefiles)
        scorefiles = cellstr(scorefiles);
      end
      behaviors = Labels.verifyBehaviorNames(x.behaviors.names);
      assert(numel(scorefiles)==numel(behaviors));
    end

  end

end


% VL_VERSION  Obtain VLFeat version information
%   VL_VERSION() prints VLFeat version number. VL_VERSION('VERBOSE')
%   prints additional information.
%
%   STR = VL_VERSION(...) returns the ouptut in a string rather than
%   printing it.
%
%   See also: VL_HELP().

% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).


function blkStruct = slblocks
% This function specifies that the library 'mylib'
% should appear in the Library Browser with the
% name 'My Library'

    Browser.Library = 'FMT_Model_Lib';
    % 'mylib' is the name of the library

    Browser.Name = 'FMT Toolbox';
    % 'My Library' is the library name that appears
    % in the Library Browser

    blkStruct.Browser = Browser;


function OutStruct = prtUtilClassParentRelationshipNamesOnly(varargin)
% prtUtilClassParentRelationship(baseClassName)
% xxx Need Help xxx
% Internal

I = meta.class.fromName(varargin{1});
if nargin == 1
    OutStruct.classNames = {I.Name};
%     OutStruct.propNames = cellfun(@(c)c.Name,I.Properties,'uniformOutput',false);
%     OutStruct.methodNames = cellfun(@(c)c.Name,I.Methods,'uniformOutput',false);
%     OutStruct.AllProperties = I.Properties;
%     OutStruct.AllMethods = I.Methods;

elseif nargin == 2
    OutStruct = varargin{2};
    % Add yourself to the list of class Names
    OutStruct.classNames = cat(1,OutStruct.classNames,{I.Name});

%     cSortedProperties = cell(length(OutStruct.propNames),1);
%     for iProp = 1:length(I.Properties)
%         %cInd = find(~cellfun(@isempty, strfind(OutStruct.propNames,I.Properties{iProp}.Name)),1);
%         cInd = find(cellfun(@(s)isequal(I.Properties{iProp}.Name,s),OutStruct.propNames),1);
%
%         if isempty(cInd)
%             error('Maximum property assumption invalid');
%         end
%
%         cSortedProperties{cInd} = I.Properties{iProp};
%     end
%
%     cSortedMethods = cell(length(OutStruct.methodNames),1);
%     for iMeth = 1:length(I.Methods)
%         if strcmpi(I.Methods{iMeth}.Name,varargin{1})
%             continue
%         end
%         if strcmpi(I.Methods{iMeth}.Access,'private');
%             continue
%         end
%
%         %cInd = find(~cellfun(@isempty, strfind(OutStruct.methodNames,I.Methods{iMeth}.Name)),1);
%         cInd = find(cellfun(@(s)isequal(I.Methods{iMeth}.Name,s),OutStruct.methodNames),1);
%         if isempty(cInd)
%             error('Maximum method assumption invalid');
%         end
%
%         cSortedMethods{cInd} = I.Methods{iMeth};
%     end
%
%     OutStruct.AllProperties = cat(2,OutStruct.AllProperties,cSortedProperties);
%     OutStruct.AllMethods = cat(2,OutStruct.AllMethods,cSortedMethods);
end

for iParent = 1:length(I.SuperClasses);
    OutStruct = prtUtilClassParentRelationshipNamesOnly(I.SuperClasses{iParent}.Name,OutStruct);
end

end


function mkdirOptional(dirName)
% Create directory if it doesn't exist
if(~exist(dirName,'dir'))
    mkdir(dirName);
end
end


%  Make Quotation
%
%  ::
%
%     document.quotation('option_name',option_value);
%
%  Args:
%
%     varargin: arguments need to come in pairs
%
%        - **log** : [char] the quote to insert
%        - **reference** : [char] reference of the quotation
%
%


%% ODFOverview.m


function setTableData(hTable, tableData)
%setTableData Summary of this function goes here
%   Detailed explanation goes here

    try
%         jScrollPane = findjobj(hTable);
%         jscroll = jScrollPane.getVerticalScrollBar();
%         sVal = get(jscroll,'value');
        set(hTable,'Data',tableData);
%         drawnow;
%         set(jscroll, 'value', sVal);
%         jScrollPane.repaint;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%         jScrollPane = findjobj(hTable);
%         jscroll = jScrollPane.getVerticalScrollBar();
%         sVal = get(jscroll,'value');
%
%         jTable = jScrollPane.getViewport.getView;
%         model = jTable.getModel();
%         if(model.getRowCount() == size(tableData,1))
%             for(i=1:size(tableData,1))
%                 for(j=1:size(tableData,2))
%                     value = tableData{i,j};
%                     if(isnumeric(value))
%                         value = num2str(value);
%                     end
% %                     javaMethodEDT('setValueAt', jTable, value,i-1,j-1);
%                     jTable.setValueAt(value,i-1,j-1);
%                 end
%             end
%             drawnow;
%         else
%             set(hTable,'Data',tableData);
%             drawnow;
%             set(jscroll, 'value', sVal);
%             jScrollPane.repaint;
%         end

    catch ME
        disp(ME.message);
        set(hTable,'Data',tableData);
    end
end


function [varargout] = calc_stiff_matrix_val(varargin)

% CALC_STIFF_MATRIX is implemented as mex file
%
% $Id$

error('The mex file %s is missing', [mfilename '.' mexext]);