function  [results] = VerifyError(expr, results)
wasError = 0;
try
    eval(expr);
catch ex
    wasError=1;
end
if wasError == 0
    disp ([expr ' <-- expected error, but was no error'])
    count = 0;
    if(isfield(results, 'failedTests'))
        count = size(results.failedTests, 1);
    end
    results.failedTests{count+1,1} = expr;
    results.allTestsPassed = 0;
end
return


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

% Last Modified by GUIDE v2.5 03-Dec-2018 17:15:45

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

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

    centerUIFigure(hObject);

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

	populateGUI(handles, stage);

    % Update handles structure
    guidata(hObject, handles);

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

function populateGUI(handles, stage)
    set(handles.stageNameText,'String',stage.name);
    set(handles.dryMassText,'String',fullAccNum2Str(stage.getStageDryMass()));

    optVar = stage.getExistingOptVar();
	if(isempty(optVar))
        optVar = stage.getNewOptVar();
	end

    handles.optCheckbox.Value = double(optVar.getUseTfForVariable());

    [lb, ub] = optVar.getAllBndsForVariable();
    handles.lbText.String = fullAccNum2Str(lb);
    handles.ubText.String = fullAccNum2Str(ub);

    optCheckbox_Callback(handles.optCheckbox, [], handles);

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

        name = handles.stageNameText.String;
        dryMass = str2double(handles.dryMassText.String);

        stage.name = name;
        stage.dryMass = dryMass;

        optVar = stage.getExistingOptVar();
        if(not(isempty(optVar)))
            stage.launchVehicle.lvdData.optimizer.vars.removeVariable(optVar);
        end
        optVar = stage.getNewOptVar();

        optDryMass = logical(handles.optCheckbox.Value);
        lbDryMass = str2double(handles.lbText.String);
        ubDryMass = str2double(handles.ubText.String);

        optVar.setUseTfForVariable(optDryMass);
        optVar.setBndsForVariable(lbDryMass,ubDryMass);
        stage.launchVehicle.lvdData.optimizer.vars.addVariable(optVar);

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

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

    dryMass = str2double(get(handles.dryMassText,'String'));
    enteredStr = get(handles.dryMassText,'String');
    numberName = 'Dry Mass';
    lb = 0;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(dryMass, numberName, lb, ub, isInt, errMsg, enteredStr);

    lwrBnd = str2double(get(handles.lbText,'String'));
    enteredStr = get(handles.lbText,'String');
    numberName = 'Dry Mass (Lower Bound)';
    lb = 0;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(lwrBnd, numberName, lb, ub, isInt, errMsg, enteredStr);

    uprBnd = str2double(get(handles.ubText,'String'));
    enteredStr = get(handles.ubText,'String');
    numberName = 'Dry Mass (Upper Bound)';
    lb = 0;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(uprBnd, numberName, lb, ub, isInt, errMsg, enteredStr);

    if(isempty(errMsg))
        uprBnd = str2double(get(handles.ubText,'String'));
        enteredStr = get(handles.ubText,'String');
        numberName = 'Dry Mass (Upper Bound)';
        lb = lwrBnd;
        ub = Inf;
        isInt = false;
        errMsg = validateNumber(uprBnd, numberName, lb, ub, isInt, errMsg, enteredStr);
    end

% --- 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_EditStageGUI);

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

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

% --- Executes during object creation, after setting all properties.
function dryMassText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to dryMassText (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 optCheckbox.
function optCheckbox_Callback(hObject, eventdata, handles)
% hObject    handle to optCheckbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of optCheckbox
    if(get(hObject,'Value'))
        handles.lbText.Enable = 'on';
        handles.ubText.Enable = 'on';
    else
        handles.lbText.Enable = 'off';
        handles.ubText.Enable = 'off';
    end

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

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

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

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

% --- Executes on key press with focus on lvd_EditStageGUI or any of its controls.
function lvd_EditStageGUI_WindowKeyPressFcn(hObject, eventdata, handles)
% hObject    handle to lvd_EditStageGUI (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_EditStageGUI);
    end


function [warnings] = addplotlystartup(startupPaths)
%[1]looks at statup.m files specified by the entries of startupPaths
%[2]appends the addplotly function to startup.m files (if not already present)
%[3]checks for other plotly addpath calls within any startup.m and outputs warning

%output warnings
warnings = cell(size(startupPaths));

for locs = 1:size(startupPaths,1);
    %addpath string for Plotly API
    addString = 'addpath(genpath(fullfile(matlabroot,''toolbox'',''plotly'')),''-end'');';
    %open current startup.m to read
    currentStartupID = fopen(startupPaths{locs},'r');
    if currentStartupID == -1, error('plotly:startupRead',...
            ['\n\nShoot! It looks like something went wrong reading the file: ' ...
            '\n' startupPaths{locs} '\n' ...
            '\nPlease contact your system admin or post a topic on https://community.plotly.com/c/api/matlab/ for more \ninformation. In the ' ...
            'mean time you can add the Plotly API \nto your search path manually whenever you need it! \n\n']);
    end
    %check for any instances of the addplotlyapi function
    startupScan = textscan(currentStartupID, '%s', 'delimiter', '\n', 'whitespace', '');
    startupLines = startupScan{1};
    Index = find(strcmp(startupLines,addString));
    otherPlotlyOccurrence = findstr(fileread(startupPaths{locs}),'plotly');
    %if addString is not in startup.m add it
    if(~any(Index));
        %reopen current startup.m with new permission
        currentStartupID = fopen(startupPaths{locs},'a+');
        if currentStartupID == -1, error('plotly:startupWrite',...
            ['\n\nShoot! It looks like something went wrong writing to the file: ' ...
            '\n\n' startupPaths{locs} '\n' ...
            '\nPlease contact your system admin or post a topic on https://community.plotly.com/c/api/matlab/ for more \ninformation. In the ' ...
            'mean time you can add the Plotly API \nto your search path manually whenever you need it! \n']);
        end
        fprintf(currentStartupID,['\n' addString]);
    end
    if(length(Index) ~= length(otherPlotlyOccurrence));
        warnings{locs} = ['\n[WARNING]: \n\nWe found an addpath specification for another version of Plotly at: ' ...
                                '\n\n' startupPaths{locs} '\n\nyou may be forcing MATLAB to look for an older version of Plotly!\n\n'];
    else
        warnings{locs} = '';
    end
    fclose(currentStartupID);
end
end


function[res] = prependNotEmpty(str, prefix)
% [res] = prependNotEmpty(str, prefix)
%
% Prepend a prefix to a string, if it is not empty.
%
% Copyrights by Holger Caesar, 2015

if ~isempty(str),
    res = [prefix, str];
else
    res = '';
end;


function v = subsref( x, S )
try
    v = subsref( x.value_, S );
catch
    cvx_throw( 'Invalid tuple reference: %s%s', inputname(1), cvx_subs2str( S ) );
end

% Copyright 2005-2014 CVX Research, Inc.
% See the file LICENSE.txt for full copyright information.
% The command 'cvx_where' will show where this file is located.


%CLASSD Return labels of classified dataset, outdated, use LABELD instead

% $Id: classd.m,v 1.2 2006/03/08 22:06:58 duin Exp $

function labels = classd(a,w)

		global CLASSD_REPLACED_BY_LABELD

	if isempty(CLASSD_REPLACED_BY_LABELD)
		disp([newline 'CLASSD has been replaced by LABELD, please use it'])
		CLASSD_REPLACED_BY_LABELD = 1;
	end

	if (nargin == 0)

		labels = labeld;

	elseif (nargin == 1)

		labels = labeld(a);

	elseif (nargin == 2)

		labels = labeld(a,w);

	else
		error ('too many arguments');
	end

return


function F = ismember(x,F)
% Internal class for constraint list

F = replace(F,recover(depends(F)),x);


function labels = getClassLabels()

labels={'ped', ...			% 1
	'person_on_vhcl', ...	% 2
	'car', ...				% 3
	'bicycle', ...			% 4
	'mbike', ...			% 5
	'non_mot_vhcl', ...		% 6
	'static_person', ...	% 7
	'distractor', ...		% 8
	'occluder', ...			% 9
	'occluder_on_grnd', ...		%10
	'occluder_full', ...		% 11
	'reflection', ...		% 12
	'crowd' ...			% 13
	};

end


function s = s_cap ( s )

%*****************************************************************************80
%
%% S_CAP replaces any lowercase letters by uppercase ones in a string.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    17 November 2004
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, character S(*), the string to be transformed.
%
%    Output, character S(*), the capitalized string.
%
  nchar = s_len_trim ( s );

  for i = 1 : nchar

    s(i) = ch_cap ( s(i) );

  end

  return
end


function ui = mrViewInit(mr);
%
% ui = mrViewInit(mr);
%
% Initialize a ui struct, containing info needed for
% mrViewer.
%
% I have attempted to structure this such that analyses
% can be run outside the GUI, akin to hidden views in mrVista 1.0.
% In this case, running mrViewInit, without running mrViewer,
% would open the structure without opening a GUI. However, I
% haven't had a chance to test that everything would work
% without needing a handle -- please feel free to correct
% any dependence on a GUI.
%
% ras, 07/05.
if ~exist('mr','var') || isempty(mr),   mr = mrLoad;         end

% Key, important fields of the view:
ui.mr = mr;         % 'base' mr object, like the anatomy / underlay
ui.maps = [];       % overlays, or maps to use when thresholding
ui.tSeries = {};    % time series (paths / mr structs) files, cell
ui.stim = [];       % stimulus files
ui.session = [];    % optional session struct / handle to session viewer
                    % to which the data are attached (see sessionViewer)
ui.rois = [];       % ROIs defined on the viewer (but not necessarily
                    % saved yet
ui.fig = [];        % handle to the main figure for the GUI

% the GUI will comprise many uipanels (specifically, see mrvPanel for
% UI panels which can be toggled visible/hidden); the most important
% is the panel where the images of the data will be displayed:
ui.panels.display = [];  % display panel
ui.panels.nav = []; % navigation panel
ui.panels.roi = []; % ROI (region of interest) panel
ui.panels.grayscale = []; % grayscale (underlay image) panel
ui.panels.info = [];  % MR info panel
ui.panels.mesh = [];  % Mesh options panel
ui.panels.overlays = [];  % panels containing overlay info
ui.panels.colorbar = []; % panel containing colorbars for overlays

%%%%%%%%%%%%%
% settings: %
%%%%%%%%%%%%%
% (maybe we should sub-organize this, but I'm ok with having
% a long list...)
ui.settings.space = 1; % pixel space
ui.settings.segmentation = 0;  % selected segmentation
ui.settings.displayFormat = 3; % default is 3 -- single slice
ui.settings.ori = 3; % orientation / default is rows | columns
middleSlice = round(ui.mr.dims(3) / 2);
ui.settings.slice = middleSlice; % default slice for single / montage views
ui.settings.time = 1; % time point, for 4-D data
ui.settings.roi = 0; % index into current ROI (0 = none selected)
ui.settings.montageRows = 2; % # rows for montage view
ui.settings.montageCols = 2; % # cols for montage view
ui.settings.bounds = [1 1 1; ui.mr.dims([2 1 3])]';
ui.settings.cursorLoc = round(ui.mr.dims(1:3) ./ 2);
ui.settings.zoom = [1 size(mr.data,1); ...
                    1 size(mr.data,2); ...
                    1 size(mr.data,3);];
ui.settings.clim = []; % auto by default
ui.settings.cmap = gray(256); % underlay cmap
ui.settings.cbarColorScheme = 1;  % 1 = white-on-black, 2=black-on-white
ui.settings.brightness = 0; % how much to brighent the gray cmap
ui.settings.gamma = 2.0; % not implemented yet, but may be useful
ui.settings.labelAxes = 0; % show axis ticks and label axes
ui.settings.labelDirs = 0; % show direction text in display
ui.settings.labelSlices = 0; % label each slice in display
ui.settings.roiEditMode = 7; % mode for adding to / removing from ROIs:
                             % 1 -- rect
                             % 2 -- circle
                             % 3 -- cube
                             % 4 -- sphere
                             % 5 -- line
                             % 6 -- point
                             % 7 -- grow (3D)
ui.settings.roiViewMode = 3; % mode for showing / hiding ROIs
                             % 1 -- hide ROIs
                             % 2 -- show selected ROI
                             % 3 -- show all ROIs
ui.settings.eqAspect = 1; % preserve aspect ratio
ui.settings.showCursor = 0; % display cursor flag
ui.settings.cursorType = 4; % flag for cursor rendering style:
                            % 1 -- show + sign
                            % 2 -- show circle
                            % 3 -- show crosshairs
                            % 4 -- show crosshairs + gap
ui.settings.baseInterp = 'linear'; % Interpolation method for base
ui.settings.mapInterp = 'nearest'; % Interpolation method for maps

% ras 02/2007:
% instead of using 'auto' color limits for the object by default,
% I've found that it's easier to guess a good upper clip limit, but
% leave the lower limit at the min value.

% [ignore clipMin clipMax] = mrClipOptimal(ui.mr.data(:,:,:,1));
% ui.settings.clim = [ui.mr.dataRange(1) clipMax];
[tmp minVal maxVal] = histoThresh(ui.mr.data(:,:,:,1));
ui.settings.clim = [minVal maxVal];

% if the mr object itself has saved settings, load these into the UI:
if isfield(ui.mr,'settings')
    for f = fieldnames(ui.mr.settings)'
        ui.settings.(f{1}) = ui.mr.settings.(f{1});
    end
end

% form a unique object tag for this viewer
i = 1; ui.tag = sprintf('mrViewer%i',i);
while ~isempty(findobj('Tag',ui.tag))
    i = i + 1; ui.tag = sprintf('mrViewer%i',i);
end

return


function Obj = SOFAremoveVariable(Obj,Name)
%SOFAremoveVariable - Remove a variable, its dimension, and its attributes from a SOFA object
%  Usage: Obj = SOFAremoveVariable(Obj,Name)
%
%  SOFAremoveVariable(Obj,Name) removes the variable Name
%  from the SOFA structure Obj.
%

% #Author: Piotr Majdak: adapted from SOFAaddVariable (19.06.2019)
% #Author: Michael Mihocic: header documentation updated (28.10.2021)
% #Author: Michael Mihocic: removing variable attributes; minor bug fixed (20.09.2022)
%
% SOFA Toolbox - function SOFAremoveVariable
% Copyright (C) Acoustics Research Institute - Austrian Academy of Sciences
% Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European Commission - subsequent versions of the EUPL (the "License")
% You may not use this work except in compliance with the License.
% You may obtain a copy of the License at: https://joinup.ec.europa.eu/software/page/eupl
% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing  permissions and limitations under the License.

switch Name
    case {'API','PRIVATE','GLOBAL','Data'}
        error('This variable name is reserved.');
    otherwise
        if isfield(Obj,Name)
            Obj=rmfield(Obj,Name);
            if isfield(Obj.API.Dimensions,Name)
                Obj.API.Dimensions=rmfield(Obj.API.Dimensions,Name);
            end
            % check if fields "Name_*" are existing and remove them (variable attributes)
            ObjFields=fieldnames(Obj);

            if exist('OCTAVE_VERSION','builtin')
              % We're in Octave
              IndexC = strfind(ObjFields,[Name '_']);
              IndexContainsName = find(not(cellfun('isempty',IndexC))); % do not replace by 'contains' (not supported in Octave)
            else
              % We're in Matlab
              IndexContainsName = find(contains(ObjFields,[Name '_']));
            end

            for ii=length(IndexContainsName):-1:1 % loop is not entered if empty IndexContainsName; run backwards because of removed indices
                % check if field name starts with "Name_*"
                if startsWith(char(ObjFields(IndexContainsName(ii))),Name)
%                     disp(['removing field: ' char(ObjFields(IndexContainsName(ii)))]) % debug
                    Obj=rmfield(Obj,ObjFields(IndexContainsName(ii)));
                end
            end

        end
end


function r = issubfield(s, f)

% ISSUBFIELD tests for the presence of a field in a structure just like the standard
% Matlab ISFIELD function, except that you can also specify nested fields
% using a '.' in the fieldname. The nesting can be arbitrary deep.
%
% Use as
%   f = issubfield(s, 'fieldname')
% or as
%   f = issubfield(s, 'fieldname.subfieldname')
%
% This function returns true if the field is present and false if the field
% is not present.
%
% See also ISFIELD, GETSUBFIELD, SETSUBFIELD

% Copyright (C) 2005-2013, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% for the documentation and details.
%
%    FieldTrip 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.
%
%    FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id$

%try
%  getsubfield(s, f);    % if this works, then the subfield must be present
%  r = true;
%catch
%  r = false;                % apparently the subfield is not present
%end

if isempty(f) || isempty(s)
  r = false;
else
  t = textscan(f,'%s','delimiter','.');
  t = t{1};
  r = true;
  for k = 1:numel(t)
    if isfield(s, t{k})
      s = s.(t{k});
    else
      r = false;
      return;
    end
  end
end


classdef MimContextResultCombiner < CoreBaseClass
    % MimContextResultCombiner. Part of the internal framework of the TD MIM Toolkit.
    %
    %     This class is used to build up aggregate results combined from results for different contexts
    %
    %
    %
    %     Licence
    %     -------
    %     Part of the TD MIM Toolkit. https://github.com/tomdoel
    %     Author: Tom Doel, Copyright Tom Doel 2014.  www.tomdoel.com
    %     Distributed under the MIT licence. Please see website for details.
    %

    properties (Access = private)
        FirstRun = true
        CacheInfo
        ImageTemplates
        OutputImage
        OutputImageTemplate
        Result
        PluginHasBeenRun = false
    end

    methods
        function obj = MimContextResultCombiner(image_templates)
            obj.ImageTemplates = image_templates;
        end

        function AddParentResult(obj, parent_context, this_context_results, output_context, output_context_mapping, dataset_stack, reporting)
            obj.Result = MimReduceResultToContext(this_context_results.GetResult, output_context_mapping.Context, obj.ImageTemplates, dataset_stack, reporting);
            if ~isempty(this_context_results.GetOutputImage)
                obj.OutputImage = MimReduceResultToContext(this_context_results.GetOutputImage, output_context, obj.ImageTemplates, dataset_stack, reporting);
            else
                obj.OutputImage = [];
            end
            obj.CacheInfo = this_context_results.GetCacheInfo;
            obj.PluginHasBeenRun = obj.PluginHasBeenRun || this_context_results.GetPluginHasBeenRun;
        end

        function AddChildResult(obj, child_context, this_context_results, output_context, output_context_mapping, dataset_stack, reporting)
            if isempty(obj.OutputImageTemplate)
                obj.OutputImageTemplate = obj.ImageTemplates.GetTemplateImage(output_context, dataset_stack, reporting);
            end

            obj.Result = MimExpandResultToContext(obj.Result, this_context_results.GetResult, child_context, obj.OutputImageTemplate, obj.ImageTemplates, dataset_stack, reporting);
            if ~isempty(this_context_results.GetOutputImage)
                obj.OutputImage = MimExpandResultToContext(obj.OutputImage, this_context_results.GetOutputImage, child_context, obj.OutputImageTemplate, obj.ImageTemplates, dataset_stack, reporting);
            else
                obj.OutputImage = [];
            end
            if isempty(obj.CacheInfo)
                obj.CacheInfo = MimCompositeResult;
            end
            obj.CacheInfo.AddField(char(child_context), this_context_results.GetCacheInfo);
            obj.PluginHasBeenRun = obj.PluginHasBeenRun || this_context_results.GetPluginHasBeenRun;
        end

        function result = GetResult(obj)
            result = obj.Result;
        end

        function result = GetCacheInfo(obj)
            result = obj.CacheInfo;
        end

        function result = GetOutputImage(obj)
            result = obj.OutputImage;
        end

        function has_been_run = GetPluginHasBeenRun(obj)
            has_been_run = obj.PluginHasBeenRun;
        end

    end
end


function [wp_lat_deg, wp_lon_deg, wp_alt_ft]=get_wp(wp, host, port)
% [WP_LAT_DEG, WP_LON_DEG, WP_ALT_FT]=GET_WP(WP, HOST, PORT)
%
% Read waypoint WP from waypoint stack in Flightgear over socket
% connection (HOST, PORT).
% Run Flightgear on HOST (e.g. '127.0.0.1' = localhost) with
% parameter "--props = PORT".
%
% Function returns:
% - Lattitude degree
% - Longitude degree
% - Altitude feet

import java.net.Socket
import java.io.*

fg_socket = Socket(host, port);
out = PrintWriter(fg_socket.getOutputStream(), true);
in = BufferedReader(InputStreamReader(fg_socket.getInputStream()));

% Read waypoint wp
% Latitude degree
if wp == 1
    out.println(sprintf(...
    'get /autopilot/route-manager/route/wp/latitude-deg\r\n'));
else
    out.println(sprintf(...
    'get /autopilot/route-manager/route/wp[%d]/latitude-deg\r\n'...
    ,wp-1));
end
wp_lat_deg_str = char(in.readLine());
j = findstr(wp_lat_deg_str,'''');
wp_lat_deg = str2double(wp_lat_deg_str(j(1)+1:j(2)-1));

% Longitude degree
if wp == 1
    out.println(sprintf(...
    'get /autopilot/route-manager/route/wp/longitude-deg\r\n'));
else
    out.println(sprintf(...
    'get /autopilot/route-manager/route/wp[%d]/longitude-deg\r\n'...
    ,wp-1));
end
wp_lon_deg_str = char(in.readLine());
j = findstr(wp_lon_deg_str,'''');
wp_lon_deg = str2double(wp_lon_deg_str(j(1)+1:j(2)-1));

% Altitude feet
if wp == 1
    out.println(sprintf(...
    'get /autopilot/route-manager/route/wp/altitude-ft\r\n'));
else
    out.println(sprintf(...
    'get /autopilot/route-manager/route/wp[%d]/altitude-ft\r\n'...
    ,wp-1));
end
wp_alt_ft_str = char(in.readLine());
j = findstr(wp_alt_ft_str,'''');
wp_alt_ft = str2double(wp_alt_ft_str(j(1)+1:j(2)-1));

out.close();
in.close();
fg_socket.close();

end


function handle = bvhVisualise(channels, skel, padding)

% BVHVISUALISE For updating a bvh representation of 3-D data.
% FORMAT
% DESC draws a bvh representation in a 3-D plot.
% ARG channels : the channels to update the skeleton with.
% ARG skel : the skeleton structure.
% RETURN handle : a vector of handles to the plotted structure.
%
% SEEALSO : bvhModify, skelVisualise
%
% COPYRIGHT : Neil D. Lawrence, 2005, 2006

% MOCAP

if nargin < 3
  padding = 0;
end
handle = skelVisualise(channels, skel, padding);


%addpath(genpath('lib'));
%addpath(genpath('IO'));

addpath(genpath('lib/awf'));
addpath(genpath('lib/nyu'));
addpath(genpath('lib/visualindex'));
addpath(genpath('lib/estimateRigidTransform'));
addpath(genpath('lib/peter'));
addpath(genpath('lib/kdtree'));
addpath(genpath('lib/sift'));
addpath(genpath('lib/arcball'));
addpath(genpath('lib/icp'));

warning('off', 'images:imshow:magnificationMustBeFitForDockedFigure');

%fprintf('test\n');
dbstop if error
%clc;

run('lib/vlfeat/toolbox/vl_setup');


function varargout = Read_MapGUI(varargin)
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @Read_MapGUI_OpeningFcn, ...
                   'gui_OutputFcn',  @Read_MapGUI_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 Read_MapGUI is made visible.
function Read_MapGUI_OpeningFcn(hObject, eventdata, handles, varargin)
handles.output = hObject;
guidata(hObject, handles);
% --- Outputs from this function are returned to the command line.
function varargout = Read_MapGUI_OutputFcn(hObject, eventdata, handles)
varargout{1} = handles.output;

% --- Executes on button press in browser_button.
function browser_button_Callback(hObject, eventdata, handles)
[filename, pathname] = uigetfile('*.mat', 'Pick a .mat file');      %Browse for file
handles.fullpathname=strcat(pathname, filename);                    %Connect path name and file name to one string
handles.filename=filename;
set(handles.continue_button, 'Enable', 'Inactive');                 %Disable Continue button
data_type=lower(filename(end-2:end));                               %Extract data type and convert to string
if data_type =='mat'                                                 %#ok<BDSCA>
    set(handles.text4, 'String', handles.fullpathname);         %Set GUI.full_path to string fullpathname
    if filename(1:5)=="Track"
        set(handles.text4, 'String', 'ERROR');
    else
        set(handles.continue_button, 'Enable', 'On');                   %Enable Continue button
    end
else
    set(handles.text4, 'String', 'ERROR');                      %Display "ERROR"
end
guidata(hObject, handles);

% --- Executes on slider movement.
function yellow_slider_Callback(hObject, eventdata, handles)
a=get(handles.yellow_slider,'Value');                                       %Get slider value of "global slider"
a=round(a*100)/100;                                                               %Round value of "global slider" to 1/50
set(handles.yellow_slider,'Value', a);                                          %Set slider value of "global slider" to rounded value
set(handles.text_yellow,'String',num2str(a));                                   %Set text above "global slider" to slider value
% --- Executes during object creation, after setting all properties.
function yellow_slider_CreateFcn(hObject, eventdata, handles)
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

% --- Executes on slider movement.
function green_slider_Callback(~, eventdata, handles)
a=get(handles.green_slider,'Value');                                       %Get slider value of "global slider"
a=round(a*100)/100;                                                               %Round value of "global slider" to 1/50
set(handles.green_slider,'Value', a);                                          %Set slider value of "global slider" to rounded value
set(handles.text_green,'String',num2str(a));                                   %Set text above "global slider" to slider value
% --- Executes during object creation, after setting all properties.
function green_slider_CreateFcn(hObject, eventdata, handles)
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

% --- Executes on slider movement.
function blue_slider_Callback(hObject, eventdata, handles)
a=get(handles.blue_slider,'Value');                                       %Get slider value of "global slider"
a=round(a*100)/100;                                                               %Round value of "global slider" to 1/50
set(handles.blue_slider,'Value', a);                                          %Set slider value of "global slider" to rounded value
set(handles.text_blue,'String',num2str(a));                                   %Set text above "global slider" to slider value
% --- Executes during object creation, after setting all properties.
function blue_slider_CreateFcn(hObject, eventdata, handles)
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

% --- Executes on slider movement.
function red_slider_Callback(hObject, eventdata, handles)
a=get(handles.red_slider,'Value');                                       %Get slider value of "global slider"
a=round(a*100)/100;                                                               %Round value of "global slider" to 1/50
set(handles.red_slider,'Value', a);                                          %Set slider value of "global slider" to rounded value
set(handles.text_red,'String',num2str(a));                                   %Set text above "global slider" to slider value
% --- Executes during object creation, after setting all properties.
function red_slider_CreateFcn(hObject, eventdata, handles)
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

% --- Executes on slider movement.
function white_slider_Callback(hObject, eventdata, handles)
a=get(handles.white_slider,'Value');                                       %Get slider value of "global slider"
a=round(a*100)/100;                                                               %Round value of "global slider" to 1/50
set(handles.white_slider,'Value', a);                                          %Set slider value of "global slider" to rounded value
set(handles.text_white,'String',num2str(a));                                   %Set text above "global slider" to slider value
% --- Executes during object creation, after setting all properties.
function white_slider_CreateFcn(hObject, eventdata, handles)
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

% --- Executes on button press in continue_button.
function continue_button_Callback(~, eventdata, handles) %#ok<*INUSL>
assignin ('base', 'path_map', handles.fullpathname);         %Assignin referenceline path to workspace
assignin ('base', 'filename_map', handles.filename);
yellow=get(handles.yellow_slider,'Value');
green=get(handles.green_slider,'Value');
blue=get(handles.blue_slider,'Value');
red=get(handles.red_slider,'Value');
white=get(handles.white_slider,'Value');
assignin ('base', 'yellow', yellow);
assignin ('base', 'green', green);
assignin ('base', 'blue', blue);
assignin ('base', 'red', red);
assignin ('base', 'white', white);
set(handles.continue_button, 'Enable', 'Off');
set(handles.browser_button, 'Enable', 'Off');
set(findall(handles.uipanel5, '-property', 'enable'),'enable', 'off');
GIMP_Correction;


function b = ParseBatch(bfile)

%ParseBatch - Parse batch file.
%
%  USAGE
%
%    b = ParseBatch(bfile)
%
%    bfile          batch file listing the parameters for each iteration
%
%  SEE
%
%    See also StartBatch, ShowBatch, InitBatch.
%

% Copyright (C) 2007-2013 by Michaël Zugaro
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 3 of the License, or
% (at your option) any later version.

% Check number of parameters
if nargin < 1,
	error('Incorrect number of parameters (type ''help ParseBatch'' for details).');
end

% Make sure batch file is valid
s = dbstack;
if ~isstring_FMAT(bfile) || ~exist(bfile,'file'),
	error(['Batch file not found (type ''help ' s.name ''' for details).']);
end

% Open batch file
f = fopen(bfile,'r');
if f == -1, error(['Could not open file ''' bfile '''.']); end

item = 1;
l = 1;
nFields = 0;
b.field = {};
% Read batch file
while ~feof(f),
	field = 0;
	% Read next line
	line = fgetl(f);
	while ~isempty(line),
		% Get next field
		[token,line] = strtok(line);
		% Skip rest of line if this is a comment
		if isempty(token) | token(1) == '%', break; end
		field = field + 1;
		% Determine if this is a number, vector or string
		n = str2num(token);
		if ~isempty(n),
			% It is a number, convert it to numerical format
			b.field{item,field} = n;
		elseif token(1) ~= '[',
			% It is a string, keep it as it is
			b.field{item,field} = token;
		else
			% It is a vector (or matrix)
			[token,line] = strtok([token line],'[]');
			n = str2num(token);
			if isempty(n),
				error(['Incorrect vector or matrix in batch file (line ' int2str(l) ', element ' int2str(field) ').']);
			end
			b.field{item,field} = n;
			line = line(2:end);
		end
	end
	if field > 0,
		% Make sure all lines have the same number of elements
		if item == 1,
			nFields = field;
		elseif field ~= nFields,
			if l == 2,
				error(['Incoherent numbers of elements in batch file (' int2str(nFields)  ' elements on line 1, but ' int2str(field) ' elements on line 2).']);
			else
				error(['Incoherent numbers of elements in batch file (' int2str(nFields)  ' elements on lines 1-' int2str(l-1) ', but ' int2str(field) ' elements on line ' int2str(l) ').']);
			end
		end
		% Next item
		b.line(item) = l;
		item = item + 1;
	end
	% Update line counter (for error messages)
	l = l + 1;
end

% Close file
fclose(f);

% Reset iterator
b.currentItem = 0;
b.currentField = 0;

% Empty fields
b.log = -1;
b.mfile = [];


%EXPANDBDR Expand physics mode boundary coefficients.

% Copyright 2013-2022 Precise Simulation, Ltd.


function eeg_save_graphics(F,type,p,confirm)

% eeg_save_graphics - Save figure as graphics file
%
% Usage: eeg_save_graphics(F,type,p,confirm)
%
% 'F' is a figure handle, when empty uses 'gcf'
%
% 'type' is the format of the graphic file, eg:
%
%       'png'  - portable network graphics (default)
%       'jpg'  - JPEG image, quality level of 90
%       'tiff' - TIFF with packbits (lossless run-length encoding)
%       'eps'  - encapsulated postscript
%
% Note that tiff and eps files can be very large.
% The default resolution is 300 DPI.
%
% 'p' is the data struct of eeg_toolbox
%
% 'confirm' is a boolean to control direct or GUI
% based saving.  0 = direct, 1 = GUI confirmation.
%
% The output file is saved to p.volt.path with
% the filename of the voltage file and the timing
% of the graphic appended (assumes that the graphic
% is a topographic map).
%

% $Revision: 1.1 $ $Date: 2009-04-28 22:13:53 $

% Licence:  GNU GPL, no implied or express warranties
% History:  04/2002, Darren.Weber_at_radiology.ucsf.edu
%           - extracted out of eeg_contours_engine
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

if exist('F','var'),
    if isempty(F), F = gcf; end
else
    F = gcf;
end
if exist('type','var'),
    if isempty(type), type = 'png'; end
else
    type = 'png';
end
if exist('confirm','var'),
    if isempty(confirm), confirm = 0; end
else
    confirm = 0;
end

[path,file,ext] = fileparts(strcat(p.volt.path,filesep,p.volt.file));
if p.topoView,
    file = strcat(file, sprintf('_%s_%08.2f',p.topoView,p.volt.sampleTime),'.',type);
else
    file = strcat(file, sprintf('_%08.2f',p.volt.sampleTime),'.',type);
end
file = fullfile(path,file);

if confirm,
    [filename, filepath] = uiputfile(file, 'EEG Save Graphic');
    if ~isequal(filename,0),
        file = fullfile(filepath,filename);
        fprintf('EEG_SAVE_GRAPHIC: Saving to:...\n...%s\n',file);
        saveas(F,file);
    end

else
    type = lower(type);
    if strmatch(type,'png'),
        driver = '-dpng';
        option1 = '-noui';
        option2 = '-r300';
        %option3 = '-zbuffer';
        fprintf('EEG_SAVE_GRAPHIC: Saving to:...\n...%s\n',file);
        print(F,driver,option1,option2,file);
    elseif strmatch(type,'jpeg'),
        driver  = '-djpeg90'; % JPEG image, quality level of nn (90 here)
        option1 = '-r300';
        fprintf('EEG_SAVE_GRAPHIC: Saving to:...\n...%s\n',file);
        print(F,driver,option1,file);
    elseif strmatch(type,'eps'),
        driver = '-depsc2'; % Encapsulated Level 2 Color PostScript
        option1 = '-r300';
        option2 = '-tiff';
        fprintf('EEG_SAVE_GRAPHIC: Saving to:...\n...%s\n',file);
        print(F,driver,option1,option2,file);
    elseif strmatch(type,'tiff'),
        driver = '-dtiff'; % TIFF with packbits (lossless run-length encoding) compression
        option1 = '-r300';
        fprintf('EEG_SAVE_GRAPHIC: Saving to:...\n...%s\n',file);
        print(F,driver,option1,file);
    else
        fprintf('EEG_SAVE_GRAPHIC: Saving to:...\n...%s\n',file);
        saveas(F,file);
    end
end

return


%InterfaceUtil
% Checks if a class (or class instance) properly implements a specificed
% interface.
%
% Author: Jonathan Karr, jkarr@stanford.edu
% Affiliation: Covert Lab, Department of Bioengineering, Stanford University
% Last Updated: 9/12/2010
classdef InterfaceUtil_Test < TestCase
    methods
        function this = InterfaceUtil_Test(name)
            this = this@TestCase(name);
        end
    end

    %tests
    methods
        function testAssertInterface(~)
            import edu.stanford.covert.util.InterfaceUtil;

            %ex 1-4
            InterfaceUtil.assertInterface('double', 'double');
            InterfaceUtil.assertInterface('double', metaclass(zeros(0,0,'double')));
            InterfaceUtil.assertInterface('double', meta.class.fromName('double'));
            InterfaceUtil.assertInterface(zeros(1,1,'double'), 'double');

            %ex 5
            metadata = struct;
            metadata.Properties = cell(0,1);
            metadata.Methods = cell(0,1);
            metadata.Methods{1} = struct;
            metadata.Methods{1}.Name = 'plus';
            InterfaceUtil.assertInterface('double', metadata);

            %ex 6
            metadata = struct;
            metadata.Properties = cell(0,1);
            metadata.Methods = cell(0,1);
            metadata.Methods{1} = struct;
            metadata.Methods{1}.Name = 'plus';
            metadata.Methods{1}.Name2 = 'plus';
            assertExceptionThrown(@() InterfaceUtil.assertInterface('double', metadata), 'Interface:invalidInput');

            %ex 7
            metadata = struct;
            metadata.Properties = cell(0,1);
            metadata.Properties{1}.Name = 'data';
            metadata.Methods = cell(0,1);
            metadata.Methods{1} = struct;
            metadata.Methods{1}.Name = 'plus';
            assertExceptionThrown(@() InterfaceUtil.assertInterface('double', metadata), 'Interface:incompleteInterface');

            %ex 8
            metadata = struct;
            metadata.Properties = cell(0,1);
            metadata.Methods = cell(0,1);
            metadata.Methods{1} = struct;
            metadata.Methods{1}.Name = 'plus';
            metadata.Methods{1}.Access = 'protected';
            assertExceptionThrown(@() InterfaceUtil.assertInterface('double', metadata), 'Interface:incompatibleInterface');

            %ex 9
            metadata = struct;
            metadata.Properties = cell(0,1);
            metadata.Methods = cell(0,1);
            metadata.Methods{1} = struct;
            metadata.Methods{1}.Name = 'plus';
            metadata.Methods{1}.Access = 'protected';
            assertExceptionThrown(@() InterfaceUtil.assertInterface('double', metadata), 'Interface:incompatibleInterface');

            %ex 10
            metadata = struct;
            metadata.Properties = cell(0,1);
            metadata.Methods = cell(0,1);
            metadata.Methods{1} = struct;
            metadata.Methods{1}.Name = 'plus';
            metadata.Methods{1}.Access = {'protected','public'};
            InterfaceUtil.assertInterface('double', metadata);

            %ex 11
            metadata = struct;
            metadata.Properties = cell(0,1);
            metadata.Methods = cell(0,1);
            metadata.Methods{1} = struct;
            metadata.Methods{1}.Name = 'plus';
            metadata.Methods{1}.Abstract = 1;
            assertExceptionThrown(@() InterfaceUtil.assertInterface('double', metadata), 'Interface:incompatibleInterface');

            %ex 12
            metadata = struct;
            metadata.Properties = cell(0,1);
            metadata.Methods = cell(0,1);
            metadata.Methods{1} = struct;
            metadata.Methods{1}.Name = 'plus';
            metadata.Methods{1}.Abstract = [0 1];
            InterfaceUtil.assertInterface('double', metadata);

            %ex 13
            metadata = struct;
            metadata.Properties = cell(0,1);
            metadata.Methods = cell(0,1);
            metadata.Methods{1} = struct;
            metadata.Methods{1}.Name = 'plus';
            metadata.Methods{1}.Abstract = [];
            InterfaceUtil.assertInterface('double', metadata);

            %ex 14
            metadata = struct;
            metadata.Properties = cell(0,1);
            metadata.Methods = cell(0,1);
            metadata.Methods{1} = struct;
            metadata.Methods{1}.Name = 'ind2sub';
            metadata.Methods{1}.InputNames = 3;
            InterfaceUtil.assertInterface('edu.stanford.covert.util.SparseMat', metadata);

            %ex 15
            metadata = struct;
            metadata.Properties = cell(0,1);
            metadata.Methods = cell(0,1);
            metadata.Methods{1} = struct;
            metadata.Methods{1}.Name = 'ind2sub';
            metadata.Methods{1}.InputNames = 4;
            assertExceptionThrown(@() InterfaceUtil.assertInterface('edu.stanford.covert.util.SparseMat', metadata), 'Interface:incompatibleInterface');

            %ex 16
            metadata = struct;
            metadata.Properties = cell(0,1);
            metadata.Methods = cell(0,1);
            metadata.Methods{1} = struct;
            metadata.Methods{1}.Name = 'ind2sub';
            metadata.Methods{1}.InputNames = {'this','inds','siz'};
            InterfaceUtil.assertInterface('edu.stanford.covert.util.SparseMat', metadata);

            %ex 17
            metadata = struct;
            metadata.Properties = cell(0,1);
            metadata.Properties{1}.Name = 'inds';
            metadata.Properties{1}.GetMethod = 1;
            metadata.Methods = cell(0,1);
            InterfaceUtil.assertInterface('edu.stanford.covert.util.SparseMat', metadata);

            %ex 18
            metadata = struct;
            metadata.Properties = cell(0,1);
            metadata.Properties{1}.Name = 'inds';
            metadata.Properties{1}.GetMethod = 0;
            metadata.Methods = cell(0,1);
            assertExceptionThrown(@() InterfaceUtil.assertInterface('edu.stanford.covert.util.SparseMat', metadata), 'Interface:incompatibleInterface');

            %ex 19
            metadata = struct;
            metadata.Properties = cell(0,1);
            metadata.Properties{1}.Name = 'inds';
            metadata.Properties{1}.GetMethod = [0 1];
            metadata.Methods = cell(0,1);
            InterfaceUtil.assertInterface('edu.stanford.covert.util.SparseMat', metadata);

            %ex 20
            metadata = struct;
            metadata.Properties = cell(0,1);
            metadata.Properties{1}.Name = 'inds';
            metadata.Properties{1}.GetMethod = [];
            metadata.Methods = cell(0,1);
            InterfaceUtil.assertInterface('edu.stanford.covert.util.SparseMat', metadata);
        end
    end
end


function save_to_base(overwrite)
%
% save_to_base() copies all variables in the calling function to the base
% workspace.  This makes it possible to examine a function's internal
% variables from the Matlab command prompt after the calling function
% terminates.
%
% If the optional argument "overwrite" is present and has a non-zero value,
% variables in the workspace of the caller will overwrite variables in the
% base workspace having the same name.  Otherwise, preexisting variables in
% the base workspace will not be overwritten.
%
% Phillip M. Feldman

% Version 1.1, 18 Aug. 2009: Added fix to exclude 'ans' variable.
%
% Version 1.0, 2 June 2009: Initial version.
%
% Note: I'd like to acknowledge assistance from Sean Little of the
% MathWorks.

ws_caller= evalin('caller','who()');

if length(nargin) && overwrite
   % Overwrite preexisting variables:
   variables= ws_caller;
else
   % Do not overwrite preexisting variables:
   ws_base= evalin('base','who()');
   variables= setdiff(ws_caller, ws_base);
end

for i= 1 : length(variables)
   if ~strcmp(variables{i},'ans')
      tmp= evalin('caller',variables{i});
      assignin('base',variables{i},tmp);
   end
end


function cnn_update_net_group(net_config, update_fn, update_opts)

assert(~isempty(net_config));

group_num=length(net_config.ref.group_infos);

for g_idx=1:group_num

    one_group_info=net_config.ref.group_infos{g_idx};

    one_group_info=update_fn(one_group_info, update_opts);

    net_config.ref.group_infos{g_idx}=one_group_info;

end

end


function chrpak_test115 ( )

%*****************************************************************************80
%
%% TEST115 tests S_REPLACE_CH.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    30 January 2006
%
%  Author:
%
%    John Burkardt
%
  s_old = 'No pennies now.';

  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST115\n' );
  fprintf ( 1,'  S_REPLACE_CH replaces one character by another;\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '    C1  C2  Original String  Modified String\n' );
  fprintf ( 1, '\n' );

  c1 = 'n';
  c2 = 't';

  s = s_replace_ch ( s_old, c1, c2 );

  fprintf ( 1, '     %c   %c   %s  %s\n', c1, c2, s_old, s );

  return
end


function [isSessionInfo] = bz_isSessionInfo(SessionInfo)
% USAGE
% [isSessionInfo] = bz_isSessionInfo(SessionInfo)
%
% INPUT
%       SessionInfo   - struct with the following fields
%                   .channels
%                   .region
%                   .depth
%                   .nChannels
%                   .FileName
%                   .Date
%
%
% OUTPUT
%      logical true if struct meets event criteria, false if otherwise
%
% written by david tingley, 2017

if isfield(SessionInfo,'channels')
     if isvector(SessionInfo.channels)
         isSessionInfo = true;
     else
         warning('.channels field is not formatted correctly')
         isSessionInfo = false;
     end
end
if isfield(SessionInfo,'region')
     if iscell(SessionInfo.region)
         isSessionInfo = true;
     else
         warning('.region field is not formatted correctly')
         isSessionInfo = false;
     end
end
if isfield(SessionInfo,'depth')
     if isnumeric(SessionInfo.depth)
         isSessionInfo = true;
     else
         warning('.depth field is not formatted correctly')
         isSessionInfo = false;
     end
end
if isfield(SessionInfo,'spikeGroups')
     if isstruct(SessionInfo.spikeGroups) % should we go deeper here to check the struct?
         isSessionInfo = true;
     else
         warning('.spikeGroups field is not formatted correctly')
         isSessionInfo = false;
     end
end
if isfield(SessionInfo,'FileName')
     if ischar(SessionInfo.FileName)
         isSessionInfo = true;
     else
         warning('.FileName field is not formatted correctly')
         isSessionInfo = false;
     end
end
if isfield(SessionInfo,'Date')
     if ischar(SessionInfo.Date)
         isSessionInfo = true;
     else
         warning('.Date field is not formatted correctly')
         isSessionInfo = false;
     end
end


%% S2AxisFieldTri


function obj = loadobj(s)
% LOADOBJ  Initialize a DagNN object from a structure.
%   OBJ = LOADOBJ(S) initializes a DagNN objet from the structure
%   S. It is the opposite of S = OBJ.SAVEOBJ().
%   If S is a string, initializes the DagNN object with data
%   from a mat-file S. Otherwise, if S is an instance of `dagnn.DagNN`,
%   returns S.

% Copyright (C) 2015 Karel Lenc and Andrea Vedaldi.
% 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).

if ischar(s) s = load(s); end
if isstruct(s)
  assert(isfield(s, 'layers'), 'Invalid model.');
  if ~isstruct(s.layers)
    warning('The model appears to be `simplenn` model. Using `fromSimpleNN` instead.');
    obj = dagnn.DagNN.fromSimpleNN(s);
    return;
  end
  obj = dagnn.DagNN() ;
  for l = 1:numel(s.layers)
    constr = str2func(s.layers(l).type) ;
    block = constr() ;
    block.load(struct(s.layers(l).block)) ;
    obj.addLayer(...
      s.layers(l).name, ...
      block, ...
      s.layers(l).inputs, ...
      s.layers(l).outputs, ...
      s.layers(l).params) ;
  end
  if isfield(s, 'params')
    for f = setdiff(fieldnames(s.params)','name')
      f = char(f) ;
      for i = 1:numel(s.params)
        p = obj.getParamIndex(s.params(i).name) ;
        obj.params(p).(f) = s.params(i).(f) ;
      end
    end
  end
  if isfield(s, 'vars')
    for f = setdiff(fieldnames(s.vars)','name')
      f = char(f) ;
      for i = 1:numel(s.vars)
        p = obj.getVarIndex(s.vars(i).name) ;
        obj.vars(p).(f) = s.vars(i).(f) ;
      end
    end
  end
  for f = setdiff(fieldnames(s)', {'vars','params','layers'})
    f = char(f) ;
    obj.(f) = s.(f) ;
  end
elseif isa(s, 'dagnn.DagNN')
  obj = s ;
else
  error('Unknown data type %s for `loadobj`.', class(s));
end


function mia_Zpixval(arg1, arg2)
% mia_Zpixval display information about image pixels
% in coronal image in the case of 3Dcursor mode
%
% Matlab library function for mia_gui utility.
% University of Debrecen, PET Center/LB 2003

%   mia_Zpixval Display information about image pixels.
%   PIXVAL ON turns on interactive display of information about image pixels
%   in the current figure. PIXVAL installs a black bar at the bottom of the
%   figure which displays the (x,y) coordinates for whatever pixel the
%   cursor is currently over, and the color information for that pixel. If
%   the image is binary or intensity, the color information is a single
%   intensity value. If the image is indexed or RGB, the color information
%   is an RGB triplet. The values displayed are the actual data values,
%   regardless of the class of the image array, or whether the data is in
%   normal image range.
%
%   If you click on the image and hold down the mouse button while you move
%   the cursor, PIXVAL also displays the Euclidean distance between the
%   point you clicked on and current cursor location. PIXVAL draws a line
%   between these points to indicate the distance being measured. When you
%   release the mouse button, the line and the distance display disappear.
%
%   You can move the display bar by clicking on it and dragging it to
%   another place in the figure.
%
%   PIXVAL OFF turns interactive display off in the current figure. You can
%   also turn off the display by clicking the button on the right side of
%   the display bar.
%
%   PIXVAL toggles interactive display on or off in the current figure.
%
%   PIXVAL(FIG,OPTION) applies the PIXVAL command to the figure specified
%   by FIG. OPTION is string containing 'on' or 'off'.
%
%   See also IMPIXEL, IMPROFILE.

%   Copyright 1993-2001 The MathWorks, Inc.
%   $Revision: 1.19 $  $Date: 2001/01/18 15:30:19 $

error(nargchk(0,2,nargin));

if nargin==0
   arg1 = gcf;
end

if ischar(arg1) % execute a callback
   switch lower(arg1)
   case 'pixvalmotionfcn'
      PixvalMotionFcn;
   case 'buttondownonimage'
      ButtonDownOnImage;
   case 'backtonormalpixvaldisplay'
      BackToNormalPixvalDisplay;
   case 'movedisplaybar'
      MoveDisplayBar;
   case 'on'
      mia_Zpixval(gcf, 'on');
   case 'off'
      mia_Zpixval(gcf, 'off');
   case 'deletedisplaybar'
      DeleteDisplayBar;
   otherwise
      error(['Unknown PIXVAL command or callback: ' arg1 '.']);
   end

elseif ishandle(arg1)
   images = findobj(arg1, 'type', 'image');
   if isempty(images)
      return
   end

   figureHandle = get(get(images(1), 'parent'), 'parent');

   if nargin>1   % mia_Zpixval(handle, 'on|off')
      if ischar(arg2)
         if strcmp(lower(arg2), 'off')
            action = 'destroy';
         elseif strcmp(lower(arg2), 'on')
            action = 'create';
         else
            error(['Unknown PIXVAL input string: ' arg2]);
         end
      else
         error('Invalid input arguments');
      end
   else  % mia_Zpixval(handle) or mia_Zpixval
      % Toggle the state
      displayBar = findobj(figureHandle, 'tag', 'pixel value display bar');
      if isempty(displayBar)
         action = 'create';
      else
         action = 'destroy';
      end
   end

   % Put things in the Images' UserData so that pixel value display works
   switch action
   case 'destroy'
      displayBar = findobj(figureHandle, 'tag', 'pixel value display bar');
      if ~isempty(displayBar)
         DeleteDisplayBar(displayBar);
      end

   case 'create'
      otherDisplayBar = findobj(figureHandle, 'tag', 'pixel value display bar');
      if ~isempty(otherDisplayBar)
         % mia_Zpixval is already ON for this figure.
         return
      end

      % Save the interactive state of the figure. UICLEARMODE now
      % does everything that UISUSPEND used to do. It calls
      % SCRIBECLEARMODE to take care of SCRIBE.  We WILL be
      % restoring the state - this is a change.  UICLEARMODE also
      % registers a way to disable mia_Zpixval
      dbud.oldFigureUIState = uiclearmode(figureHandle,'mia_Zpixval',figureHandle,'off');
      AxisHandle = findobj(figureHandle, 'type', 'axes');
      dbud.xLim = get(AxisHandle,'XLim');% for zoom mode
      dbud.yLim = get(AxisHandle,'YLim');% for zoom mode
      dbud.old_pt = 0;% for zoom mode

      % Make sure the SCRIBE toolbar doesn't go away
      plotedit(figureHandle,'locktoolbarvisibility');

      % Make sure that the Motion function doesn't interrupt itself
      set(figureHandle, 'Interruptible', 'off', 'busyaction', 'queue');

      % Make sure that the Image's Button Down & Up functions will queue
      set(images, 'Interruptible', 'off', 'BusyAction', 'Queue');

      % dbud is the UserData structure which is going into the display bar
      dbud.figureHandle = figureHandle;
      dbud.displayMode = 'normal';

      figPos = get(dbud.figureHandle, 'position');
      tempStr = sprintf(' %g, %g = %6.4f,%6.4f,%6.4f  dist = %3.3f', ...
        -0.9999,-0.9999,pi/10,pi/10,pi/10,pi*100);

      % Calculate the position vector of the display bar
      tempTxt = uicontrol('Parent', dbud.figureHandle, 'horiz', 'left', ...
         'Style', 'text', 'Units', 'pixels', 'visible', 'off', 'fontname', ...
         'FixedWidth','String', tempStr, 'position', [0 0 figPos(3) 20]);
      extent= get(tempTxt, 'extent');
      txtHt = extent(4);
      txtWid = extent(3)+txtHt; % Leave room for the close button
      delete(tempTxt);

      % Create position vectors for Text, Frame, and Close Button
      pos = [0 0 (min(txtWid,figPos(3))-txtHt)*1/2 txtHt];
      btnSide = pos(4)-4;  % In pixels
      btnPos = [pos(1)+pos(3)+2 pos(2)+2 btnSide btnSide];
      frmPos = [pos(1)+pos(3) 0 txtHt txtHt];

      % Create a frame for the display bar. I do this because of a bug in
      % MATLAB 5.2 where the text field pops to the front of the button each
      % time it is updated.  It should stay behind in which case, all we would
      % need is the text uicontrol and the button.  We can take the frame out
      % if the bug gets fixed.  Make sure the frame doesn't fall behind the
      % text control, otherwise you can't execute the text control's buttondown
      % function (another MATLAB 5.2 bug).

      dbud.DisplayFrame = uicontrol('Parent', figureHandle, ...
         'style', 'frame', ...
         'Units', 'pixels', ...
         'Position', frmPos, ...
         'Background', [0 0 0], ...
         'BusyAction', 'queue', ...
         'Interruptible', 'off');

      % Create the display bar
      dbud.buttonDownImage = 0;  % Image 0 never exists
      DisplayBar = uicontrol('Parent', figureHandle, ...
         'Style','text', ...
         'Units','pixels', ...
         'Position',pos, ...
         'Foreground', [1 1 .5], ...
         'Background', [0 0 0], ...
         'Horiz','left', ...
         'Tag', 'pixel value display bar', ...
         'String','', ...
         'fontname', 'FixedWidth', ...
         'BusyAction', 'queue', ...
         'enable', 'inactive', ...
         'Interruptible', 'off');
%          'ButtonDownFcn', 'mia_Zpixval(''MoveDisplayBar'')', ...
%          'DeleteFcn', 'mia_Zpixval(''DeleteDisplayBar'')', ...

      % Create the close button
      dbud.CloseButton = uicontrol('Parent', figureHandle, ...
         'style', 'pushbutton', ...
         'units', 'pixels', ...
         'position', btnPos, ...
         'BusyAction', 'queue', ...
         'Interruptible', 'off');
%          'String', 'X', ...
%          'Callback', 'mia_Zpixval(''DeleteDisplayBar'')', ...
%          'DeleteFcn', 'mia_Zpixval(''DeleteDisplayBar'')', ...

      % Register the motion function and button up function
      set(figureHandle, 'WindowButtonMotionFcn',...
         'mia_Zpixval(''PixvalMotionFcn'')')

      set(DisplayBar, 'UserData', dbud);
      PixvalMotionFcn(DisplayBar);
   end

else
   error('Invalid input argument.')
end

%%%
%%%  Sub-function - PixvalMotionFcn
%%%

function PixvalMotionFcn(displayBar)

if nargin < 1
   displayBar = findobj(gcbf, 'Tag', 'pixel value display bar');
end

if isempty(displayBar)
   % Pixval is in a half-broken state.  Another function (like zoom) has
   % restored pixval callbacks and PIXVAL has already been uninstalled.
   % Call uisuspend to gracefully get rid of the callbacks.

   % Note 7/21/98 - Since we are now using UICLEARMODE instead of
   % UISUSPEND, I think that we should never get into this
   % state.  It will only happen if a user writes a function
   % which calls UIRESTORE without ever calling UICLEARMDOE or
   % SCRIBECLEARMODE.  We'll leave this code here just to be safe.
   uisuspend(gcbf);
   return
end

dbud = get(displayBar, 'UserData');
pt = get(dbud.figureHandle, 'CurrentPoint');
x = pt(1,1); y = pt(1,2);

if strcmp(dbud.displayMode, 'normal')
   % See if we're above the displayBar
   dbpos = get(displayBar, 'Position');
   left   = dbpos(1);
   bottom = dbpos(2);
   width  = dbpos(3);
   height = dbpos(4);
   % On the line below, we look to see if x<=left+width+height because
   % there is a frame next to the text object, see note above about the
   % MATLAB 5.2 bug we're working around
   if x>=left & x<=left+width+height & y>=bottom & y<=bottom+height
      % We're hovering above the display bar

      % Look to see if we are above the Close button
      cp = get(dbud.CloseButton, 'Position');
      if  x>=cp(1) & x<=cp(1)+cp(3) & y>=cp(2) & y<=cp(2)+cp(4)
         if isfield(dbud, 'oldPointer') % Switch back to the default pointer
            set(dbud.figureHandle, 'Pointer', dbud.oldPointer, ...
               'PointerShapeCData', dbud.oldPointerShapeCData, ...
               'PointerShapeHotSpot', dbud.oldPointerShapeHotSpot);
            dbud = rmfield(dbud, {'oldPointer', ...
                  'oldPointerShapeCData', 'oldPointerShapeHotSpot'});
         end
      else
         % Save the default pointer if there is one
         if ~isfield(dbud, 'oldPointer') % We still have the default pointer
            dbud.oldPointer = get(dbud.figureHandle, 'Pointer');
            dbud.oldPointerShapeCData = get(dbud.figureHandle, 'PointerShapeCData');
            dbud.oldPointerShapeHotSpot = get(dbud.figureHandle, 'PointerShapeHotSpot');
         end
         setptr(dbud.figureHandle, 'hand');
      end
   else
      % We're not hovering over the display bar
      [imageHandle,imageType,img,x,y] = OverImage(dbud.figureHandle);
      if imageHandle ~= 0
         % Save old pointer and get a new one (use Custom pointer for non-Windows machine)
         if ~isfield(dbud, 'oldPointer') % We still have the default pointer
            dbud.oldPointer = get(dbud.figureHandle, 'Pointer');
            dbud.oldPointerShapeCData = get(dbud.figureHandle, 'PointerShapeCData');
            dbud.oldPointerShapeHotSpot = get(dbud.figureHandle, 'PointerShapeHotSpot');
         end
         if strcmp(computer, 'PCWIN')
            set(dbud.figureHandle, 'Pointer', 'cross');
         else
            [pointerShape, pointerHotSpot] = CreatePointer;
            set(dbud.figureHandle, 'Pointer', 'custom', ...
               'PointerShapeCData', pointerShape, ...
               'PointerShapeHotSpot', pointerHotSpot);
         end

         % Update the Pixel Value display
         UpdatePixelValues(imageHandle, imageType, displayBar,img,x,y );
      else
         if isfield(dbud, 'oldPointer') % Switch back to the default pointer
            set(dbud.figureHandle, 'Pointer', dbud.oldPointer, ...
               'PointerShapeCData', dbud.oldPointerShapeCData, ...
               'PointerShapeHotSpot', dbud.oldPointerShapeHotSpot);
            dbud = rmfield(dbud, {'oldPointer', ...
                  'oldPointerShapeCData', 'oldPointerShapeHotSpot'});
            set(displayBar, 'String', '');
         end
      end
   end
elseif strcmp(dbud.displayMode, 'distance')
   % If we're in distance mode and in another image, clean up a bit.
   [imageHandle,imageType,img,x,y]= OverImage(dbud.figureHandle);
   if imageHandle~=0
      if imageHandle==dbud.buttonDownImage
         UpdatePixelValues(imageHandle, imageType, displayBar,img,x,y);
      end
   end
end
set(displayBar, 'UserData', dbud);

%%%
%%%  Sub-function - OverImage
%%%

function [imageHandle,imageType,img,x,y] = OverImage(figHandle)
% Return the index of which image we are over, and return a 0 if we
% aren't above an image.

images = findobj(figHandle, 'type', 'image');
if isempty(images)
   imageHandle=0; imageType=''; img=[]; x=0; y=0;
   return
end
% Make sure that the Image's Button Down & Up functions will queue
set(images, 'ButtonDownFcn', 'mia_Zpixval(''ButtonDownOnImage'')', ...
   'Interruptible', 'off', 'BusyAction', 'Queue');
axHandles = get(images, {'Parent'});
axPositions = get([axHandles{:}], {'Position'});
axCurPt = get([axHandles{:}], {'CurrentPoint'});

% Loop over the axes, see if we are above any of them
imageHandle = 0;
for k=1:length(axHandles)
   XLim = get(axHandles{k}, 'XLim');
   YLim = get(axHandles{k}, 'YLim');
   pt = axCurPt{k};
   x = pt(1,1); y = pt(1,2);
   if x>=XLim(1) & x<=XLim(2) & y>=YLim(1) & y<=YLim(2)
      imageHandle = images(k);
      break;
   end
end

% Figure out image type
if imageHandle ~= 0
   [img,flag] = getimage(imageHandle);

   switch flag
   case 1
      imageType = 'indexed';
   case {2,3}  % Grayscale or binary
      imageType = 'intensity';
   case 4
      imageType = 'rgb';
   otherwise
      error(['Invalid image, GETIMAGE returned flag = ' flag '.']);
   end
else
   imageHandle=0; imageType=''; img=[]; x=0; y=0;
end

%%%
%%%  Sub-function - UpdatePixelValues
%%%

function UpdatePixelValues(imageHandle, imageType, displayBar, img, x, y)
%   This is the motion callback for when we are displaying
%   pixels.  Either we are in automatic display mode and the
%   mouse pointer is moving around or we are in normal mode
%   and there has been a button-down but not yet a button up.
%   I get the current point and update the string.

global old_pt_zoom_z x0_pan_z;%temp for zoom and pan

dbud = get(displayBar, 'UserData');

[rows, cols, colors] = size(img);
y = min(y,rows);% y > rows happens in some case /LB
rp = axes2pix(rows, get(imageHandle,'YData'),y);
cp = axes2pix(cols, get(imageHandle,'XData'),x);
r = min(rows, max(1, round(rp)));
c = min(cols, max(1, round(cp)));

if strcmp(imageType,'indexed')
   map=get(dbud.figureHandle, 'Colormap');
   idx = img(r,c);
   if ~isa(idx, 'double'),
      idx = double(idx)+1;
   end
   idx = round(idx);
   if idx<=size(map,1)
      pixel = map(idx,:);
   else
      pixel = map(end,:);
   end
else
   pixel = double(img(r,c,:));
end

% figure out the new string
figureHandle = get(get(imageHandle, 'parent'), 'parent');
switch dbud.displayMode
case 'normal'   % Just display intensity information
	FigDataIn = get(figureHandle,'Userdata');
    ImVolume = get(FigDataIn.ImaHandlerX,'UserData');
    %x = ImVolume.X;
    %y = ImVolume.Y;
    %z = ImVolume.Z;
    %pixel(1) = ImVolume.PixInt;

	if isa(img, 'uint8')
     pixval_str = sprintf(' %g,%g,%g = %3d',round(x),round(y), round(ImVolume.Z),pixel(1));
	elseif isa(img, 'int16')
     pixval_str = sprintf(' %g,%g,%g = %5d',round(x),round(y), round(ImVolume.Z), pixel(1));
	else
     pixval_str = sprintf(' %g,%g,%g = %5.1f',round(x),round(y), round(ImVolume.Z),pixel(1));
	end
    set(displayBar, 'String', pixval_str, 'UserData', dbud);

case 'distance'
    mouseclick = get(gcf,'SelectionType');
    if strcmp(mouseclick,'normal')
		FigDataIn = get(figureHandle,'Userdata');
		fighandlerX = FigDataIn.ImaHandlerX;
		fighandlerY = FigDataIn.ImaHandlerY;
		FigData = FigDataIn.CData;

		set(fighandlerX,'CData',rot90(squeeze(FigData(:,round(cp),:,:))));
		set(fighandlerY,'CData',rot90(squeeze(FigData(round(rp),:,:))));

        ImVolume = get(FigDataIn.ImaHandlerX,'UserData');
        ImVolume.X = x;
        ImVolume.Y = y;
        ImVolume.PixInt = pixel(1);
        set(FigDataIn.ImaHandlerX,'UserData',ImVolume);

		if isa(img, 'uint8')
         pixval_str = sprintf(' %g,%g,%g = %3d',round(x),round(y), round(ImVolume.Z),pixel(1));
		elseif isa(img, 'int16')
         pixval_str = sprintf(' %g,%g,%g = %5d', round(x),round(y), round(ImVolume.Z), pixel(1));
		else
         pixval_str = sprintf(' %g,%g,%g = %5.1f',round(x),round(y), round(ImVolume.Z),pixel(1));
		end
        set(displayBar, 'String', pixval_str, 'UserData', dbud);
    elseif strcmp(mouseclick,'extend') % zoom mode
        CurrentAxes = findobj(figureHandle, 'type', 'axes');
        %set(CurrentAxes,'Units','pixel');
        new_pt = get(0,'PointerLocation');
        dy = (new_pt(2) - old_pt_zoom_z(2))/abs(old_pt_zoom_z(2))*5;
        zoomFactor = (1-dy);
        xLim=get(CurrentAxes,'XLim');
        yLim=get(CurrentAxes,'YLim');
     	xLimNew = [0 zoomFactor*diff(xLim)] + xLim(1) + (1-zoomFactor)*diff(xLim)/2;
        yLimNew = [0 zoomFactor*diff(yLim)] + yLim(1) + (1-zoomFactor)*diff(yLim)/2;
		set(CurrentAxes,'XLim',xLimNew,'YLim',yLimNew);
        old_pt_zoom_z  = new_pt;
    elseif strcmp(mouseclick,'alt') % pan mode
        currentPoint = get(figureHandle,'CurrentPoint');
        CurrentAxes = findobj(figureHandle, 'type', 'axes');
        set(CurrentAxes,'Units','pixel');
        dx = currentPoint - x0_pan_z;
        x0_pan_z = currentPoint;
        ap = get(CurrentAxes,'Position');
        xLim = get(CurrentAxes,'XLim');
        yLim = get(CurrentAxes,'YLim');
        set(CurrentAxes,'XLim',xLim-(diff(xLim)*dx(1)/ap(3)), ...
           'YLim',yLim+(diff(yLim)*dx(2)/ap(4)));
       set(CurrentAxes,'Units','normalized');
    elseif strcmp(mouseclick,'open')% restore the original image
        xLimNew = dbud.xLim;
        yLimNew = dbud.yLim;
        CurrentAxes = findobj(gcf, 'type', 'axes');
        set(CurrentAxes,'XLim',xLimNew,'YLim',yLimNew);
    end

end

%%%
%%%  Sub-function - ButtonDownOnImage
%%%

function ButtonDownOnImage

global old_pt_zoom_z x0_pan_z;%temp for zoom and pan operation

%imageHandle = gcbo;
currentHandle = gcbo;
if strcmp(get(currentHandle,'type'),'image')
    imageHandle = currentHandle;
else
    currentParentHandle = get(currentHandle,'Parent');
    currentChildrensHandles = get(currentParentHandle,'children');
    imageHandle = currentChildrensHandles(3);
end
figureHandle = get(get(imageHandle,'Parent'),'Parent');
displayBar = findobj(figureHandle, 'Tag', 'pixel value display bar');
dbud = get(displayBar, 'UserData');
axesHandle = get(imageHandle, 'Parent');

mouseclick = get(gcf,'SelectionType');
if strcmp(mouseclick,'normal')% case of distance measuring
	%
elseif strcmp(mouseclick,'alt') % pan mode
    setptr(figureHandle,'closedhand');
elseif strcmp(mouseclick,'extend') % zoom mode
    setptr(figureHandle,'glass');
end
%
% Turn on the PlotEdit options on X,Y slice images
%
FigDataIn = get(figureHandle,'Userdata');

%delete the positioning line
ImVolume = get(FigDataIn.ImaHandlerX,'UserData');
if ishandle(ImVolume.Xxline)
    delete(ImVolume.Zxline);
    delete(ImVolume.Zyline);
    delete(ImVolume.Yxline);
    delete(ImVolume.Yyline);
    delete(ImVolume.Xxline);
    delete(ImVolume.Xyline);
end
set(FigDataIn.ImaHandlerX,'UserData',ImVolume);

% Set the initial point (x0,y0)

%pt = get(axesHandle, 'CurrentPoint');
%dbud.x0 = pt(1,1);
%dbud.y0 = pt(1,2);
%dbud.line = line('Parent', axesHandle, ...
%  'erasemode', 'xor', ...
%   'color', [1 0 0], ...
%   'Xdata', [dbud.x0 dbud.x0], ...
%   'Ydata', [dbud.y0 dbud.y0]);
dbud.displayMode = 'distance';
old_pt_zoom_z = get(0,'PointerLocation');% for zoom mode
x0_pan_z = get(figureHandle,'CurrentPoint');% for pan mode
dbud.buttonDownImage = imageHandle;
set(displayBar, 'UserData', dbud);
set(dbud.figureHandle, 'WindowButtonUpFcn', 'mia_Zpixval(''BackToNormalPixvalDisplay'')');
PixvalMotionFcn(displayBar);

%%%
%%%  Sub-function - BackToNormalPixvalDisplay
%%%

function BackToNormalPixvalDisplay

displayBar = findobj(gcbo, 'Tag', 'pixel value display bar');
dbud = get(displayBar, 'UserData');
imageHandle = dbud.buttonDownImage;
%
% Turn off the PlotEdit options on X,Y slice images and
% write the last X,Y,Z coordinates to the FigDataIn struct
%
[imageHandleTmp,imageType,img,x,y]= OverImage(dbud.figureHandle);
figureHandle = get(get(imageHandle,'Parent'),'Parent');
FigDataIn = get(figureHandle,'Userdata');
axesHandleX = get(FigDataIn.ImaHandlerX, 'Parent');
axesHandleY = get(FigDataIn.ImaHandlerY, 'Parent');
axesHandleZ = get(FigDataIn.ImaHandlerZ, 'Parent');

%draw the positioning line
Xyrange = get(axesHandleX,'Ylim');
Xxrange = get(axesHandleX,'Xlim');
Yyrange = get(axesHandleY,'Ylim');
Yxrange = get(axesHandleY,'Xlim');
Zyrange = get(axesHandleZ,'Ylim');
Zxrange = get(axesHandleZ,'Xlim');

ImVolume = get(FigDataIn.ImaHandlerX,'UserData');
if ishandle(ImVolume.Xxline)
    delete(ImVolume.Xxline);
    delete(ImVolume.Xyline);
    delete(ImVolume.Yxline);
    delete(ImVolume.Yyline);
    delete(ImVolume.Zxline);
    delete(ImVolume.Zyline);
end

LineWidthCur = 2;
%lines in saggital slice
ImVolume.Xxline=line('Parent', axesHandleX,'color', [0 1 1],'EraseMode','xor', ....
    'LineWidth',LineWidthCur,'Xdata',[ImVolume.Y ImVolume.Y],'Ydata',[0 Xyrange(2)], ...
    'ButtonDownFcn','mia_Xpixval(''ButtonDownOnImage'')');
ImVolume.Xyline=line('Parent', axesHandleX,'color', [0 1 1],'EraseMode','xor', ...
'LineWidth',LineWidthCur,'Xdata',[0 Xxrange(2)],'Ydata', [ImVolume.Z ImVolume.Z], ...
    'ButtonDownFcn','mia_Xpixval(''ButtonDownOnImage'')');

%lines in axial slice
ImVolume.Zxline=line('Parent', axesHandleZ,'color', [0 1 1],'EraseMode','xor', ....
    'LineWidth',LineWidthCur,'Xdata',[ImVolume.X ImVolume.X],'Ydata',[0 Zyrange(2)], ...
    'ButtonDownFcn','mia_Zpixval(''ButtonDownOnImage'')');
ImVolume.Zyline=line('Parent', axesHandleZ,'color', [0 1 1],'EraseMode','xor', ...
    'LineWidth',LineWidthCur,'Xdata',[0 Zxrange(2)],'Ydata', [ImVolume.Y ImVolume.Y], ...
    'ButtonDownFcn','mia_Zpixval(''ButtonDownOnImage'')');

% set(FigDataIn.ImaHandlerX,'UserData',ImVolume);
%lines in coronal slice
ImVolume.Yxline=line('Parent', axesHandleY,'color', [0 1 1],'EraseMode','xor', ....
    'LineWidth',LineWidthCur,'Xdata',[ImVolume.X ImVolume.X],'Ydata',[0 Xyrange(2)], ...
    'ButtonDownFcn','mia_Ypixval(''ButtonDownOnImage'')');
ImVolume.Yyline=line('Parent', axesHandleY,'color', [0 1 1],'EraseMode','xor', ...
    'LineWidth',LineWidthCur,'Xdata',[0 Yxrange(2)],'Ydata', [ImVolume.Z ImVolume.Z], ...
    'ButtonDownFcn','mia_Ypixval(''ButtonDownOnImage'')');

set(FigDataIn.ImaHandlerX,'UserData',ImVolume);

%delete(dbud.line);
%dbud.line = [];
%dbud.x0 = []; dbud.y0 = [];
set(dbud.figureHandle, 'WindowButtonUpFcn', '');
dbud.displayMode = 'normal';
dbud.buttonDownImage = 0;
set(displayBar, 'UserData', dbud);
PixvalMotionFcn( displayBar);

%%%
%%%  Sub-function - MoveDisplayBar
%%%

function MoveDisplayBar

displayBar = gcbo;
dbud = get(displayBar, 'UserData');
oldWindowMotionFcn = get(dbud.figureHandle, 'WindowButtonMotionFcn');
set(dbud.figureHandle, 'WindowButtonMotionFcn', '');
oldPointer = get(dbud.figureHandle, 'Pointer');
oldPointerShapeCData = get(dbud.figureHandle, 'PointerShapeCData');
oldPointerShapeHotSpot = get(dbud.figureHandle, 'PointerShapeHotSpot');
setptr(dbud.figureHandle,'closedhand');

txtpos = get(displayBar, 'Position');
frmPos = get(dbud.DisplayFrame, 'Position');
position = txtpos + [0 0 frmPos(3) 0];
position2 = dragrect(position);
dx = position2(1)-position(1);
dy = position2(2)-position(2);

txtpos = txtpos + [dx dy 0 0];
set(displayBar, 'Position', txtpos);

frmPos = frmPos + [dx dy 0 0];
set(dbud.DisplayFrame, 'Position', frmPos);

btnPos = get(dbud.CloseButton, 'Position');
btnPos = btnPos + [dx dy 0 0];
set(dbud.CloseButton, 'Position', btnPos);

set(dbud.figureHandle, 'Pointer', oldPointer, ...
   'PointerShapeCData', oldPointerShapeCData, ...
   'PointerShapeHotSpot', oldPointerShapeHotSpot)
set(dbud.figureHandle, 'WindowButtonMotionFcn', oldWindowMotionFcn);

%%%
%%%  Sub-function - DeleteDisplayBar
%%%

function DeleteDisplayBar(displayBar)
%  Take apart the pixel value display - get rid of the text
%  uicontrol and clean up the image objects (remove their
%  UserData's and get rid of their ButtonDown & Delete Fcn's)

if nargin<1
   displayBar = findobj(gcbf, 'Tag', 'pixel value display bar');
end

if ~isempty(displayBar) % if it's empty, there's no work to do.
   dbud = get(displayBar, 'UserData');
   set(displayBar, 'DeleteFcn', '');  % Make sure there's no recursion
   if ishandle(displayBar)
      delete(displayBar);
   end
   if ishandle(dbud.CloseButton)
      delete(dbud.CloseButton);
   end
   if ishandle(dbud.DisplayFrame)
      delete(dbud.DisplayFrame);
   end

   % We are once again restoring the figure state, since
   % UIRESTORE also will reactivate the SCRIBE toolbar.
   uirestore(dbud.oldFigureUIState);

   % This is what we did for IPT 2.1/ML 5.2 :
   %   uisuspend(dbud.figureHandle);
end

%%%
%%%  Sub-function - CreatePointer
%%%

function [pointerShape, pointerHotSpot] = CreatePointer

pointerHotSpot = [8 8];
pointerShape = [ ...
      NaN NaN NaN NaN NaN   1   2 NaN   2   1 NaN NaN NaN NaN NaN NaN
   NaN NaN NaN NaN NaN   1   2 NaN   2   1 NaN NaN NaN NaN NaN NaN
   NaN NaN NaN NaN NaN   1   2 NaN   2   1 NaN NaN NaN NaN NaN NaN
   NaN NaN NaN NaN NaN   1   2 NaN   2   1 NaN NaN NaN NaN NaN NaN
   NaN NaN NaN NaN NaN   1   2 NaN   2   1 NaN NaN NaN NaN NaN NaN
   1   1   1   1   1   1   2 NaN   2   1   1   1   1   1   1   1
   2   2   2   2   2   2   2 NaN   2   2   2   2   2   2   2   2
   NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
   2   2   2   2   2   2   2 NaN   2   2   2   2   2   2   2   2
   1   1   1   1   1   1   2 NaN   2   1   1   1   1   1   1   1
   NaN NaN NaN NaN NaN   1   2 NaN   2   1 NaN NaN NaN NaN NaN NaN
   NaN NaN NaN NaN NaN   1   2 NaN   2   1 NaN NaN NaN NaN NaN NaN
   NaN NaN NaN NaN NaN   1   2 NaN   2   1 NaN NaN NaN NaN NaN NaN
   NaN NaN NaN NaN NaN   1   2 NaN   2   1 NaN NaN NaN NaN NaN NaN
   NaN NaN NaN NaN NaN   1   2 NaN   2   1 NaN NaN NaN NaN NaN NaN
   NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN];


function [D, j, key] = LMquery(D, fieldName, content, method)
%
% This function provides basic query functionalities. It allows you to
% locate images with certain objects.
%
% [Dout, j, key] = LMquery(D, fieldName, content, method)
%
%    D:         database struct
%    fieldName: can be any of the fields in the struct at the object level.
%    content:   a string describing the desired field you are looking for.
%               you can use the characters '+' and '-' within the content string in
%               order to perform 'and' and 'not' operations.
%    method:    when selected 'exact', the content must be match exactly
%             Methods:
%               [] = default = substring matching (air => chair)
%               'exact' = strings should match exactly
%               'word'  = the field should match words (air ~=> chair)
%
% Output:
%   Dout: new struct matching the query
%   j: indices to images that fit the query. Note Dout is not D(j). D(j)
%   contains all the objects in the original struct
%   key: pointers to images and objects in Dout with respect to D.
%       The first image in Dout is:
%         D(key(1).jimg).annotation.object(key(1).jobj)
%      [key(:).jimg] is the same as j
%
%
% The function LMquery searchs for images in the database.
% Queries can be done on any field of the struct array.
% The fields for an image are:
%    filename
%    folder
%    source.sourceImage
%    source.sourceAnnotation
%    object(:).name
%    object(:).deleted
%    object(:).verified
%    object(:).date
%    object(:).polygon.username
%    object(:).polygon.pt(:).x
%    object(:).polygon.pt(:).y
%    object(:).viewpoint.azimuth
%
% Look at the results of these two lines (HOMEIMAGES should be set with the path of the database):
% LMdbshowobjects(LMquery(D, 'object.name', 'plate+license'), HOMEIMAGES);
% LMdbshowobjects(LMquery(D, 'object.name', 'plate-license'), HOMEIMAGES);
%
% Performs an OR function. This will select objects that belong to one of this groups: 1) side views
% of cars, 2) buildings 3) roads or 4) trees.
% [D,j] = LMquery(D, 'object.name', 'car+side,building,road,tree');
%
% To make AND queries of different objects within an image, you can chain several queries.
% For instance, to get images that have cars, buildings and roads:
%    [Dfoo,j1] = LMquery(D, 'object.name', 'building');
%    [Dfoo,j2] = LMquery(D, 'object.name', 'road');
%    j = intersect(j1,j2);
%    LMshow(LMquery(D(j), 'object.name', 'car,building,road'));
%
% You can query other fields. The next lines allow you to select from the
% database, all the polygons that have been verified and that are not
% marked as deleted. This is something you might want to do often:
%    D = LMquery(D, 'object.verified', '1');
%    D = LMquery(D, 'object.deleted', '0');
%
% or D = LMquery(LMquery(D, 'object.verified', '1'), 'object.deleted', '0');
%
% You can also query based on the date of annotation:
%    LMshow(LMquery(database, 'date', '13-Jan'));
% [in the case of dates, D is an exception about the meaning of the
% character '-'. Here is just a separation between day and month].
%
% More examples:
% Queries for objects
% [Dj,j] = LMquery(D, 'object.name', 'building');
% LMdbshowscenes(D(j), HOMEIMAGES); % this shows all the objects in the images that contain buildings
% LMdbshowscenes(Dj, HOMEIMAGES); % this shows only the buildings
%
% Queries for images in specific folders.
% [Dj,j] = LMquery(D, 'folder', '05june05_static_indoor');
% LMdbshowscenes(D(j), HOMEIMAGES); % this shows all the objects
%
% The next example shows the annotated objects from images that come from the web:
% [Dj,j] = LMquery(D, 'folder', 'web');
% LMdbshowscenes(D(j), HOMEIMAGES); % this shows all the objects
%
% look for a specific image file:
% [Dj,j] = LMquery(D, 'filename', 'p1010843.jpg');
% LMdbshowscenes(D(j), HOMEIMAGES); % this shows all the objects
%
% look for objects annotated by one user:
% [Dj,j] = LMquery(D, 'object.polygon.username', 'atb');
% LMdbshowscenes(Dj, HOMEIMAGES); % this shows all the objects annotated by one user
%
% look for objects by viewpoint:
% [D,j] = LMquery(D, 'object.viewpoint.azimuth', '0', 'exact');
%

if (nargin < 4)
    method = '';
end

% Parse query
%if length(strfind(fieldName, 'date'))>0
%    query{1} = {['+' lower(content)]};
%else
%    query = parseContent(content);
%end

% Parse query
if ~isempty(strfind(fieldName, 'date')) || strcmp(method,'exact')
    query{1} = {['+' lower(content)]};
%elseif strcmp(method,'exact')
%    query{1} = {['+' lower(content)]};
else
    query = parseContent(content);
end

% Parse queried field
fieldName = ['annotation.' fieldName];
fieldName = parseContent(fieldName, '.');

% Locate the images that verify the query
Nimages = length(D);
queriedImages = logical(zeros(Nimages,1));

k=0;
for i = 1:Nimages
    v = D(i);

    [vn, jc] = queryfields(v, fieldName, query, method);

    if ~isempty(vn)
        queriedImages(i)=1;
        D(i) = vn;

        k = k + 1;
        key(k).jimg = i;
        key(k).jobj = jc;
    end
end

disp(sprintf('%d matches out of %d', sum(queriedImages), length(D)))

D = D(queriedImages);
j = find(queriedImages);

function [vn, jc] = queryfields(v, fieldName, query, method)

vn = [];
jc = [];
depthfield = length(fieldName);

if depthfield == 1
    % End recursion
    if isfield(v, fieldName{1}{1}(2:end))
        jc = findobject({v.(fieldName{1}{1}(2:end))}, query, method);
        vn = v(jc);
    else
        if strcmp(query{1}(1), '-')
            jc = 1:length(v);
            vn = v;
        end
    end
else
    if isfield(v, fieldName{1}{1}(2:end))
        % Recursive call
        N = length(v);
        q = logical(zeros(N,1));
        for i = 1:N
            vi = getfield(v, {i}, fieldName{1}{1}(2:end));
            [vi, jc] = queryfields(vi, fieldName(2:end), query, method);
            q(i) = ~isempty(vi);
            v(i).(fieldName{1}{1}(2:end)) = vi;
        end
        jq = find(q);
        vn = v(jq);
    else
        if strcmp(query{1}(1), '-')
            jc = 1:length(v);
            vn = v;
        end
    end
end


function  varargout = block_interface(varargin)
%BLOCK_INTERFACE Common block processing backend
%
%  Object-like interface for sharing data between block handling
%  functions.

if nargin<1
     error('%s: Too few input parameters.',upper(mfilename));
end

% Persistent data
persistent pos;
persistent datapos; % Second data pointer
persistent pageNo;
persistent sourceName;
persistent maxBufCount;
persistent pageList;
persistent playChanList;
persistent recChanList;
persistent skipCounter;

persistent classid;
persistent toPlayBlock;
persistent anaOverlap;
persistent synOverlap;
persistent dispLoad;

persistent Ls;
persistent Fs;

persistent loop;

% DEFAULTS
persistent bufLen;

persistent outFile;

persistent offline;

command = varargin{1};

switch command
   case {'reset','clearAll'}
      pos = 0;
      datapos = 0;
      sourceName = [];
      maxBufCount = 3;
      pageList = [];
      playChanList = [];
      recChanList = [];
      pageNo = 0;
      skipCounter = 0;
      classid = 'double';
      anaOverlap = [];
      synOverlap = [];
      toPlayBlock = [];
      dispLoad = 1;
      loop = 0;
      Ls = -1;
      bufLen = 1024;
      outFile = [];
      offline = 0;
      Fs = 0;
%% SETTERS %%%
   case 'setLs'
      Ls = varargin{2};
   case 'setFs'
      Fs = varargin{2};
   case 'setOutFile'
      outFile = varargin{2};
   case 'setOffline'
      offline = varargin{2};
   case 'setPos'
      pos = varargin{2};
   case 'setDatapos'
      datapos = varargin{2};
   case 'setBufCount'
      maxBufCount = varargin{2};
   case 'setPlayChanList'
      playChanList = varargin{2};
   case 'setRecChanList'
      recChanList = varargin{2};
   case 'setPageNo'
      pos = varargin{2};
   case 'setSkipped'
      skipCounter = varargin{2};
   case 'setBufLen'
      bufLen = varargin{2};
   case 'setClassId'
      classid = varargin{2};
   case 'setAnaOverlap'
      anaOverlap = varargin{2};
   case 'setSynOverlap'
      synOverlap = varargin{2};
   case 'setDispLoad'
      dispLoad = varargin{2};
   case 'setToPlay'
      toPlayBlock=varargin{2};
   case 'setIsLoop'
      loop = varargin{2};
   case 'setSource'
      sourceName = varargin{2};
%% GETTERS %%%
   case 'getLs'
      varargout{1}=Ls;
   case 'getFs'
      varargout{1}=Fs;
   case 'getOutFile'
      varargout{1}=outFile;
   case 'getOffline'
      varargout{1}=offline;
   case 'getPos'
      varargout{1}=pos;
   case 'getDatapos'
      varargout{1}=datapos;
   case 'getBufCount'
      varargout{1}= maxBufCount;
   case 'getPlayChanList'
      varargout{1}=playChanList;
   case 'getRecChanList'
      varargout{1}=recChanList;
   case 'getPageList'
      varargout{1}=pageList;
   case 'getPageNo'
      varargout{1}=pageNo;
   case 'getSkipped'
      varargout{1}=skipCounter;
   case 'getBufLen'
      varargout{1}=bufLen;
   case 'getClassId'
      varargout{1}=classid;
   case 'getAnaOverlap'
      varargout{1}=anaOverlap;
   case 'getSynOverlap'
      varargout{1}=synOverlap;
   case 'getDispLoad'
      varargout{1}=dispLoad;
   case 'getToPlay'
      varargout{1}=toPlayBlock;
      toPlayBlock = [];
   case 'getIsLoop'
      varargout{1}=loop;
   case 'getSource'
      if isnumeric(sourceName)
         varargout{1}='numeric';
      else
         varargout{1}=sourceName;
      end
   case 'getEnqBufCount'
      varargout{1}= numel(pageList);

%% OTHER %%%
   case 'incPageNo'
      pageNo = pageNo +1;
   case 'flushBuffers'
      anaOverlap = [];
      synOverlap = [];
   case 'popPage'
      varargout{1}=pageList(1);
      pageList = pageList(2:end);
   case 'pushPage'
      pageList = [pageList, varargin{2}];

%   case 'incSkipped'
%      skipCounter = skipCounter + varargin{2};
%   case 'readNumericBlock'
%      L = varargin{2};
%      varargout{1}=sourceName(pos+1:pos+1+L,:);
   otherwise
      error('%s: Unrecognized command.',upper(mfilename));
end


function pic = pptInsertInSlide(op, img, pos, units, slide_num);
% Paste an image matrix into an existing PowerPoint slide at a user-specified
% position.
%
%   pic = pptInsertInSlide(op, img, pos, [units='normalized'], [slide_num=last slide]);
%
% INPUTS:
%	op: ActiveX operation for PowerPoint. You get this by calling pptOpen.
%	img: image matrix. Can be 2D (grayscale) or 3D (truecolor), or can be a
%		handle to a MATLAB figure containing the contents to be pasted.
%	pos: 4-element matrix specifying the position of the image in the
%		slide. The format is:
%			[top left corner X, top left corner Y, widht, height]
%	units: either 'pixels' or 'norm' (or 'normalized'). Specifies the units
%		in the pos argument. If 'pixels', the units are pixels down or to the left
%		of the top-left corner of the slide. If 'norm', units are
%		normalized to the slide width (e.g., 0=at the top/left corner, 1=at
%		the bottom/right corner, .5=halfway). [Default 'norm']
%	slide_num: optional specification of the slide in which to insert the
%		image. Can also be the slide object itself.
%		[defaults to last slide in the PPT.]
%
% OUTPUTS:
%	pic: Microsoft shape object representing the inserted picture.
%
% SEE: pptOpen, pptPaste, pptClose.
%
% ras, 10/2008.
if notDefined('op'),	error('Need to run pptOpen first.');		end
if notDefined('img'),	error('Need an image to insert.');			end
if notDefined('pos'),	error('Need a position for the image.');	end
if notDefined('units'),	units = 'norm';								end
if notDefined('slide_num'),	slide_num = get(op.Slides, 'Count');	end

% copy the image into the clipboard
if length(img)==1 & ishandle(img)
	% 'img' is actually a handle to a figure: copy this figure
	figure(img)
	print('-dbitmap');
else
	% copy by making a figure, copying the image, then closing the
	% figure:
	hFig = figure('Units', 'norm', 'Position', [0 0 1 1], 'Color', 'w');
	imshow(img);
	print('-dbitmap');
	close(hFig);
end

%% get the selected slide
% allow the user to hand in a slide object
classType = 'Interface.Microsoft_PowerPoint_11.0_Object_Library._Slide';
if isequal( class(slide_num), classType )
	slide = slide_num;
else
	% get the slide based on the slide ID
	% (I think this is the way to do it, but I'm not 100% sure:
	%  it seems like the SlideID is 255 + the slide num...
	slide = invoke(op.Slides, 'FindBySlideID', (255 + slide_num));
end

% paste into the powerpoint slide
pic = invoke(slide.Shapes,'Paste');

% if using normalized units, convert into pixels
if strncmp( lower(units), 'norm', 4 )==1
	pos([1 3]) = pos([1 3]) .* op.PageSetup.SlideWidth;
	pos([2 4]) = pos([2 4]) .* op.PageSetup.SlideHeight;
end

% set the position in the slide
set(pic, 'Left', pos(1));
set(pic, 'Top', pos(2));
set(pic, 'Height', pos(4));
set(pic, 'Width', pos(3));

return


function view = rmInitView(viewPointer,roiFileName)
% rmInitView - initiate view struct from key pointers
%
% view = rmInitView(view,roiFileName);
%
% These key pointers now are:
%         pointer(1): viewType
%         pointer(2): dataType
%         roiFileName: if defined roi will be loaded
%
% SOD: wrote it.

if ~exist('viewPointer','var') || isempty(viewPointer), error('Need viewPointers'); end;
if ~exist('roiFileName','var'), roiFileName = []; end;

% default vista stuff
mrGlobals;
loadSession;

% set viewType
if viewPointer(1)==1
    view=initHiddenGray;
else
    view=initHiddenInplane;
end

% set dataType
view = viewSet(view,'curdatatype',viewPointer(2));
fprintf(1,'[%s]:DataType: %s\n',mfilename, ...
    dataTYPES(view.curDataType).name);

% if roiFileName load roi
if ~isempty(roiFileName)
    if ~strcmp(roiFileName,'0')
        view = loadROI(view,roiFileName,[],[],[],1);
    end
end

return;


function W = todouble(W)

for j = 1:numel(W)
  if (iscell(W(j).W))
    for k=1:numel(W(j).W)
      W(j).W{k} = double(W(j).W{k});
    end
  else
    W(j).W = double(W(j).W);
  end
  W(j).params.l = double(W(j).params.l);
end


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

    enumeration
        PlotContinuous('Plot Continuous');
        SkipFirstState('Skip First State');
        DoNotPlot('Do Not Plot');
    end

    properties
        name
    end

    methods
        function obj = EventPlottingMethodEnum(name)
            obj.name = name;
        end
    end

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

        function [ind, enum] = getIndForName(name)
            m = enumeration('EventPlottingMethodEnum');
            [~,I] = sort({m.name});
            m = m(I);
            ind = find(ismember({m.name},name),1,'first');
            enum = m(ind);
        end

        function [enum, ind] = getEnumForListboxStr(nameStr)
            m = enumeration('EventPlottingMethodEnum');
            ind = find(ismember({m.name},nameStr),1,'first');
            enum = m(ind);
        end
    end
end


function	profile_end(profile_on, profile_dir)

if ~exist('profile_on','var'), profile_on = 0; end;

switch profile_on
case	0,
    ptime(toc)
case	1,
    ptime(toc)

    if str2num(strtok(version,'.')) > 6
%        profile off
		if ~exist('profile_dir','var'), profile_dir = 'profile'; end;
        profile viewer
        p = profile('info');
        profsave( p, profile_dir)
    else
		if ~exist('profile_dir','var'), profile_dir = './profile'; end;
	    pwd_dir = pwd;
		if ~exist(profile_dir,'dir'),
			flag=mkdir(profile_dir);
		end
	    cd(profile_dir)
        profile report profile_job
	    cd(pwd_dir)
    end

case	2,
    ptime(toc)
    profile viewer
end