function [status, message]=xlwrite(filename,A,sheet, range)
% XLWRITE Write to Microsoft Excel spreadsheet file using Java
%   XLWRITE(FILE,ARRAY) writes ARRAY to the first worksheet in the Excel
%   file named FILE, starting at cell A1. It aims to have exactly the same
%   behaviour as XLSWRITE. See also XLSWRITE.
%
%   XLWRITE(FILE,ARRAY,SHEET) writes to the specified worksheet.
%
%   XLWRITE(FILE,ARRAY,RANGE) writes to the rectangular region
%   specified by RANGE in the first worksheet of the file. Specify RANGE
%   using the syntax 'C1:C2', where C1 and C2 are opposing corners of the
%   region.
%
%   XLWRITE(FILE,ARRAY,SHEET,RANGE) writes to the specified SHEET and
%   RANGE.
%
%   STATUS = XLWRITE(FILE,ARRAY,SHEET,RANGE) returns the completion
%   status of the write operation: TRUE (logical 1) for success, FALSE
%   (logical 0) for failure.  Inputs SHEET and RANGE are optional.
%
%   Input Arguments:
%
%   FILE    String that specifies the file to write. If the file does not
%           exist, XLWRITE creates a file, determining the format based on
%           the specified extension. To create a file compatible with Excel
%           97-2003 software, specify an extension of '.xls'. If you do not
%           specify an extension, XLWRITE applies '.xls'.
%   ARRAY   Two-dimensional logical, numeric or character array or, if each
%           cell contains a single element, a cell array.
%   SHEET   Worksheet to write. One of the following:
%           * String that contains the worksheet name.
%           * Positive, integer-valued scalar indicating the worksheet
%             index.
%           If SHEET does not exist, XLWRITE adds a new sheet at the end
%           of the worksheet collection.
%   RANGE   String that specifies a rectangular portion of the worksheet to
%           read. Not case sensitive. Use Excel A1 reference style.
%           * If you specify a SHEET, RANGE can either fit the size of
%             ARRAY or specify only the first cell (such as 'D2').
%           * If you do not specify a SHEET, RANGE must include both
%             corners and a colon character (:), even for a single cell
%             (such as 'D2:D2').
%           * If RANGE is larger than the size of ARRAY, Excel fills the
%             remainder of the region with #N/A. If RANGE is smaller than
%             the size of ARRAY, XLWRITE writes only the subset that fits
%             into RANGE to the file.
%
%   Note
%   * This function requires the POI library to be in your javapath.
%     To add the Apache POI Library execute commands:
%     (This assumes the POI lib files are in folder 'poi_library')
%       javaaddpath('poi_library/poi-3.8-20120326.jar');
%       javaaddpath('poi_library/poi-ooxml-3.8-20120326.jar');
%       javaaddpath('poi_library/poi-ooxml-schemas-3.8-20120326.jar');
%       javaaddpath('poi_library/xmlbeans-2.3.0.jar');
%       javaaddpath('poi_library/dom4j-1.6.1.jar');
%   * Excel converts Inf values to 65535. XLWRITE converts NaN values to
%     empty cells.
%
%   EXAMPLES
%   % Write a 7-element vector to testdata.xls:
%   xlwrite('testdata.xls', [12.7, 5.02, -98, 63.9, 0, -.2, 56])
%
%   % Write mixed text and numeric data to testdata2.xls
%   % starting at cell E1 of Sheet1:
%   d = {'Time','Temperature'; 12,98; 13,99; 14,97};
%   xlwrite('testdata2.xls', d, 1, 'E1')
%
%
%   REVISIONS
%   20121004 - First version using JExcelApi
%   20121101 - Modified to use POI library instead of JExcelApi (allows to
%           generate XLSX)
%   20121127 - Fixed bug: use existing rows if present, instead of
%           overwrite rows by default. Thanks to Dan & Jason.
%   20121204 - Fixed bug: if a numeric sheet is given & didn't exist,
%           an error was returned instead of creating the sheet. Thanks to Marianna
%   20130106 - Fixed bug: use existing cell if present, instead of
%           overwriting. This way original XLS formatting is kept & not
%           overwritten.
%   20130125 - Fixed bug & documentation. Incorrect working of NaN. Thanks Klaus
%   20130227 - Fixed bug when no sheet number given & added Stax to java
%               load. Thanks to Thierry
%
%   Copyright 2012-2013, Alec de Zegher
%==============================================================================

% Check if POI lib is loaded
if exist('org.apache.poi.ss.usermodel.WorkbookFactory', 'class') ~= 8 ...
    || exist('org.apache.poi.hssf.usermodel.HSSFWorkbook', 'class') ~= 8 ...
    || exist('org.apache.poi.xssf.usermodel.XSSFWorkbook', 'class') ~= 8

    error('xlWrite:poiLibsNotLoaded',...
        'The POI library is not loaded in Matlab.\nCheck that POI jar files are in Matlab Java path!');
end

% Import required POI Java Classes
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;

import org.apache.poi.ss.util.*;

status=0;

% If no sheet & xlrange is defined, attribute an empty value to it
if nargin < 3; sheet = []; end
if nargin < 4; range = []; end

% Check if sheetvariable contains range data
if nargin < 4 && ~isempty(strfind(sheet,':'))
    range = sheet;
    sheet = [];
end

% check if input data is given
if isempty(A)
    error('xlwrite:EmptyInput', 'Input array is empty!');
end
% Check that input data is not bigger than 2D
if ndims(A) > 2
	error('xlwrite:InputDimension', ...
        'Dimension of input array should not be higher than two.');
end

% Set java path to same path as Matlab path
java.lang.System.setProperty('user.dir', pwd);

% Open a file
xlsFile = java.io.File(filename);

% If file does not exist create a new workbook
if xlsFile.isFile()
    % create XSSF or HSSF workbook from existing workbook
    fileIn = java.io.FileInputStream(xlsFile);
    xlsWorkbook = WorkbookFactory.create(fileIn);
else
    % Create a new workbook based on the extension.
    [~,~,fileExt] = fileparts(filename);

    % Check based on extension which type to create. If no (valid)
    % extension is given, create XLSX file
    switch lower(fileExt)
        case '.xls'
            xlsWorkbook = HSSFWorkbook();
        case '.xlsx'
            xlsWorkbook = XSSFWorkbook();
        otherwise
            xlsWorkbook = XSSFWorkbook();

            % Also update filename with added extension
            filename = [filename '.xlsx'];
    end
end

% If sheetname given, enter data in this sheet
if ~isempty(sheet)
    if isnumeric(sheet)
        % Java uses 0-indexing, so take sheetnumer-1
        % Check if the sheet can exist
        if xlsWorkbook.getNumberOfSheets() >= sheet && sheet >= 1
            xlsSheet = xlsWorkbook.getSheetAt(sheet-1);
        else
            % There are less number of sheets, that the requested sheet, so
            % return an empty sheet
            xlsSheet = [];
        end
    else
        xlsSheet = xlsWorkbook.getSheet(sheet);
    end

    % Create a new sheet if it is empty
    if isempty(xlsSheet)
        warning('xlwrite:AddSheet', 'Added specified worksheet.');

        % Add the sheet
        if isnumeric(sheet)
            xlsSheet = xlsWorkbook.createSheet(['Sheet ' num2str(sheet)]);
        else
            % Create a safe sheet name
            sheet = WorkbookUtil.createSafeSheetName(sheet);
            xlsSheet = xlsWorkbook.createSheet(sheet);
        end
    end

else
    % check number of sheets
    nSheets = xlsWorkbook.getNumberOfSheets();

    % If no sheets, create one
    if nSheets < 1
        xlsSheet = xlsWorkbook.createSheet('Sheet 1');
    else
        % Select the first sheet
        xlsSheet = xlsWorkbook.getSheetAt(0);
    end
end

% if range is not specified take start row & col at A1
% locations are 0 indexed
if isempty(range)
    iRowStart = 0;
    iColStart = 0;
    iRowEnd = size(A, 1)-1;
    iColEnd = size(A, 2)-1;
else
    % Split range in start & end cell
    iSeperator = strfind(range, ':');
    if isempty(iSeperator)
        % Only start was defined as range
        % Create a helper to get the row and column
        cellStart = CellReference(range);
        iRowStart = cellStart.getRow();
        iColStart = cellStart.getCol();
        % End column calculated based on size of A
        iRowEnd = iRowStart + size(A, 1)-1;
        iColEnd = iColStart + size(A, 2)-1;
    else
        % Define start & end cell
        cellStart = range(1:iSeperator-1);
        cellEnd = range(iSeperator+1:end);

        % Create a helper to get the row and column
        cellStart = CellReference(cellStart);
        cellEnd = CellReference(cellEnd);

        % Get start & end locations
        iRowStart = cellStart.getRow();
        iColStart = cellStart.getCol();
        iRowEnd = cellEnd.getRow();
        iColEnd = cellEnd.getCol();
    end
end

% Get number of elements in A (0-indexed)
nRowA = size(A, 1)-1;
nColA = size(A, 2)-1;

% If data is a cell, convert it
if ~iscell(A)
    A = num2cell(A);
end

% Iterate over all data
for iRow = iRowStart:iRowEnd
    % Fetch the row (if it exists)
    currentRow = xlsSheet.getRow(iRow);
    if isempty(currentRow)
        % Create a new row, as it does not exist yet
        currentRow = xlsSheet.createRow(iRow);
    end

    % enter data for all cols
    for iCol = iColStart:iColEnd
        % Check if cell exists
        currentCell = currentRow.getCell(iCol);
        if isempty(currentCell)
            % Create a new cell, as it does not exist yet
            currentCell = currentRow.createCell(iCol);
        end

        % Check if we are still in array A
        if (iRow-iRowStart)<=nRowA && (iCol-iColStart)<=nColA
            % Fetch the data
            data = A{iRow-iRowStart+1, iCol-iColStart+1};

            if ~isempty(data)
                % if it is a NaN value, convert it to an empty string
                if isnumeric(data) && isnan(data)
                    data = '';
                end

                % Write data to cell
                currentCell.setCellValue(data);
            end

        else
            % Set field to NA
            currentCell.setCellErrorValue(FormulaError.NA.getCode());
        end
    end
end

% Write & close the workbook
fileOut = java.io.FileOutputStream(filename);
xlsWorkbook.write(fileOut);
fileOut.close();

status = 1;

end


function [k] = createStimCutMovieMontage(inputMovie,nAlignPts,timeVector,varargin)
	% Creates a montage movie aligned to specific timepoints.
	% Biafra Ahanonu
	% fxn started: 2014.08.13 - broke off from controllerAnalysis script from ~2014.03
	% inputs
		% inputMovie - path to movie file, in cell array, e.g. {'path.h5'}
		% inputAlignPts - vector containing the frames to align to
		% savePathName - path to save output movie, exclude the extension.
	% outputs
		% 2015.11.05

	[k] = ciapkg.video.createStimCutMovieMontage(inputMovie,nAlignPts,timeVector,'passArgs', varargin);
end


%% Example
% This script is used to detect the double touch of the kuka end effector
% in the Z direction

% Mohammad SAFEEA, 20th of May 2017

close all,clear all,clc

global binaryValArray
global averageVal
binaryValArray=zeros(40,1);
averageVal=0;

fprintf('Double touch the robot up to hear the event')

ip='172.31.1.147'; % The IP of the controller
% start a connection with the server
t=net_establishConnection( ip );

if ~exist('t','var') || isempty(t)
  warning('Connection could not be establised, script aborted');
  return;
else

    num=60*100; % for 1 minute
    for(i=1:num)
        pause(0.01);
        performEventFunctionAtDoubleHit(t);
    end

      %% turn off the server
       net_turnOffServer( t );

       fclose(t);
end


% ACQUIRE_LECROY_SCOPE_DATA M-Code for communicating with an instrument.
%
%   This is the machine generated representation of an instrument control
%   session using a device object. The instrument control session comprises
%   all the steps you are likely to take when communicating with your
%   instrument. These steps are:
%
%       1. Create a device object
%       2. Connect to the instrument
%       3. Configure properties
%       4. Invoke functions
%       5. Disconnect from the instrument
%
%   To run the instrument control session, type the name of the M-file,
%   acquire_LeCroy_scope_data, at the MATLAB command prompt.
%
%   The M-file, ACQUIRE_LECROY_SCOPE_DATA must be on your MATLAB PATH. For additional information
%   on setting your MATLAB PATH, type 'help addpath' at the MATLAB command
%   prompt.
%
%   Example:
%       acquire_LeCroy_scope_data;
%
%   See also ICDEVICE.

% Copyright 2009 - 2010 The MathWorks, Inc.
%   Creation time: 08-Jan-2009 14:37:45

% Create a TCPIP object.
interfaceObj = instrfind('Type', 'tcpip', 'RemoteHost', '127.0.0.1', 'RemotePort', 1861, 'Tag', '');

% Create the TCPIP object if it does not exist
% otherwise use the object that was found.
if isempty(interfaceObj)
    interfaceObj = tcpip('172.31.146.86', 1861);
else
    fclose(interfaceObj);
    interfaceObj = interfaceObj(1);
end

% Create a device object.
deviceObj = icdevice('lecroy_basic_driver.mdd', interfaceObj);

% Connect device object to hardware.
connect(deviceObj);

% Execute device object function(s).
groupObj = get(deviceObj, 'Waveform');
groupObj = groupObj(1);
[Y, T, XUNIT, YUNIT, HEADER] = invoke(groupObj, 'readwaveform', 'channel1');

% Disconnect device object from hardware.
disconnect(deviceObj);

% Delete objects.
delete([deviceObj interfaceObj]);


function LMthumbnailsbar(folderlist, filelist, pagename, HOMEIMAGES);
%
% LMthumbnailsbar(folderlist, filelist, pagename, HOMEIMAGES);
%
% HOMEIMAGES should be the path for the images in your local copy of the
% database.
%
% This function allows building an interface that communicates with the
% LabelMe web annotation tool.
%
% It can be used to label specific images. It adds a bar with thumbnails at
% the left side of the annotation tool.
%
% You can use this to label images that have some characteristic that you
% want. You can use this function in combination with the LMquery function.
%
% For instance, if you want to create a web page with images only of
% kitchens so that the thumbnails are connected to the LabelMe web
% annotation tool online, you can do the next thing:
%
% [D,j] = LMquery(database, 'folder', 'kitchen');
% for i = 1:length(D);
%    folderlist{i} = D(i).annotation.folder;
%    filelist{i} = D(i).annotation.filename;
% end
% LMthumbnailsbar(folderlist, filelist, 'myphotoalbum.html', HOMEIMAGES);
%
%
% See also LMphotoalbum
%

Nimages = length(folderlist);
webpage = 'http://labelme.csail.mit.edu/tool.html?collection=LabelMe&mode=i'
thumbpage = 'http://people.csail.mit.edu/brussell/research/LabelMe/Thumbnails/'

% Header
page = {};

% Create links for each image
for i = 1:Nimages
    imageline = sprintf('', thumbpage, folderlist{i}, filelist{i});
    page = addline(page, sprintf('%d
',i));
    page = addline(page, ...
        [sprintf('%s', ...
        webpage, folderlist{i}, filelist{i}, imageline)]);
end

% Close web page
page = addline(page, '');

% write web page
fid = fopen(['bar' pagename],'w');
for i = 1:length(page);
    fprintf(fid, [page{i} '\n']);
end
fclose(fid);

% Header
page = {};
page = addline(page, '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN"');
page = addline(page, '"http://www.w3.org/TR/html4/frameset.dtd">');
page = addline(page, '<title>LabelMe thumbnail bar</title>');
page = addline(page, '<FRAMESET cols="154, *">');
page = addline(page, sprintf('<FRAME src="%s">', ['bar' pagename]));
page = addline(page, sprintf('<FRAME src = "%s&folder=%s&image=%s" name="labelme">', webpage, folderlist{1}, filelist{1}));
page = addline(page, '</FRAMESET>');

% write web page
fid = fopen(pagename,'w');
for i = 1:length(page);
    fprintf(fid, [page{i} '\n']);
end
fclose(fid);

function page = addline(page, line)

page = [page {line}];


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

%%
clear; close all; clc;

%% Syntax
% |writeMtrFile_tetGen(inputStruct,bOpt);|

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


function sz = sizeJava(jv)
% sizeJava(jv) returns the size of a java array, in a manner corresponding
% to 'size' on matlab arrays.

% Written by Tom Minka
% (c) Microsoft Corporation. All rights reserved.

sz(1) = size(jv,1);
sz(2) = size(jv(1,:),1);
if sz(2) == 0
  % workaround matlab's bug
  sz(2) = 1;
end


function [ret]=realTime_startVelControlJoints( t_Kuka )
%% Applicable to KST 1.6

%% Syntax:
% realTime_startVelControlJoints( t_Kuka )

%% About:
% This function is used to turn on the soft real-time control at joints
% velocities level

%% Check also
% ((sendJointsVel)), refer also to the function
% ((realTime_stopVelControlJoints)).

%% Arreguments
% t_Kuka: is the TCP/IP connection object

%% Return value:
% ret: 'true' if the joints positions message has been received and processed
% successfully by the server, otherwise 'false' is returned.

% Copy right, Mohammad SAFEEA, 1st of April 2018

theCommand='stVelDcJoint_';
fprintf(t_Kuka, theCommand);
message=fgets(t_Kuka);

[ret]=checkAcknowledgment(message);
if ret==true
	disp('Acknowledge, realtime control turned on');
end
delay(0.5); % introduce some time delay, so the robot turns on the direct servo before starting the motion
end


function [P,P2,d] = get_filename2(dwcard,varargin)
% :Usage:
% ::
%
%     function [P,P2,d] = get_filename2(search string (as with ls command),[verbose])
%
% Start in directory above individual subject directories
%
% :Inputs:
%
%   **dwcard:**
%        Enter dwcard for wildcard of directories to look in; e.g. '02*'
%
%   **wcard:**
%        Enter wcard for image or file to get - e.g., 'beta_0001.img'
%        This can also include subdirectories (no *'s) 'anatomy/beta*img'
%
% :Outputs:
%
%     Returns list of all files in individual directories  in string matrix
%
%   **P:**
%        file names with full paths
%
%   **P2:**
%        file names only
%
%   **d:**
%        list of directories searched for files
%
% Missing files, or entries in directory that do not contain files, are
% removed from the list.
% NOT entering a * in dwcard seems to produce an error.
%
% :Examples:
% ::
%
%    P = get_filename2('02*/beta_0001*')
%
% one * is allowed in the directory structure right now,
% multiple *'s in the filename.
%
% ..
%    Tor Wager 5/2/03
% ..

if length(varargin) > 0, verb = varargin{1};, else, verb = 0;,end

clear d, clear D

P = []; P2 = [];

[dd,fstr,ext] = fileparts(dwcard);

% get list of directories to search

if any(dd == '*')
    d = dir(dd);

    [CWD,newd] = fileparts(dd);

    if ~isempty(d),
        for i = 1:length(d), d(i).name = fullfile(CWD,d(i).name);,end
    end

    pdname = newd;
    while any(CWD == '*')
        d = [d dir(CWD)];

        if ~isempty(d),
            for i = 1:length(d), d(i).name = fullfile(fileparts(CWD),d(i).name,pdname);,end
        end

        [CWD,newd] = fileparts(newd);
        pdname = fullfile(pdname,newd);
        if verb, disp(['Looking in ' CWD]);,end
    end

    if verb, disp('List of dirs to search:'),str2mat(d.name),disp(' '),end
else
    clear d,
    d(1).name = dd; if isdir(d(1).name), d(1).isdir = 1;, else, d(1).isdir = 0;,end
end

% search for files in dirs

for i = 1:length(d),
	if d(i).isdir,
		D = fullfile(d(i).name,[fstr ext]);,

        if verb, str = ['dir(''' D ''')'];, disp(str),end
        f = dir(D);

        % file name only
        if ~isempty(f), P2 = str2mat(P,str2mat(f(~cat(1,f.isdir)).name));,end

        % full path name
        for j = 1:length(f)
            if ~f(j).isdir,
                if isempty(P)
                    P = fullfile(fileparts(D),f(j).name);
                else
                    P = str2mat(P,fullfile(fileparts(D),f(j).name));,
                end
            end
        end
    end
end

return


function colors = prtPlotUtilLightenColors(colors)
% Internal function,
% xxx Need Help xxx

colors = colors + 0.2;
colors(colors > 1) = 1;


function p = cvx_create_problem( varargin )
global cvx___

error( nargchk( 0, 2, nargin ) );
cvx_global
cvx_problem = evalin( 'caller', 'cvx_problem', '[]' );
if isa( cvx_problem, 'cvxprob' ) && cvx___.problems( index( cvx_problem ) ).depth == length( dbstack ) - 2,
    error( 'A cvx problem already exists in this scope.\n(To clear it and start a new one, use the command ''cvx_clear''.)', 1 ); %#ok
end
cvx_problem = cvxprob;
if nargin > 0,
    p = index( cvx_problem );
    for k = 1 : nargin,
        mode = varargin{k};
        if isempty( mode ),
            continue;
        elseif ~ischar( mode ) || size( mode, 1 ) ~= 1,
            cvx_pop( cvx_problem, 'clear' );
            error( 'Arguments must be strings.' );
        end
        switch lower( mode ),
            case 'quiet',
                cvx___.problems( p ).quiet = true;
            case 'set',
                cvx___.problems( p ).complete  = false;
                cvx___.problems( p ).direction = 'find';
            case 'sdp',
                if cvx___.problems( p ).gp,
                    cvx_pop( cvx_problem, 'clear' );
                    error( 'The GP and SDP modifiers cannot be used together.' );
                end
                cvx___.problems( p ).sdp = true;
            case 'gp',
                if cvx___.problems( p ).sdp,
                    cvx_pop( cvx_problem, 'clear' );
                    error( 'The GP and SDP modifiers cannot be used together.' );
                end
                cvx___.problems( p ).gp = true;
            case 'separable',
                cvx___.problems( p ).separable = true;
        end
    end
end
assignin( 'caller', 'cvx_problem', cvx_problem );

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


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% This file is part of OLPS: http://OLPS.stevenhoi.org/
% Original authors: Doyen Sahoo
% Contributors: Bin LI, Steven C.H. Hoi
% Change log:
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [ ] = configurationMenu( )

    % This will be used to add and delete algorithms to the configuration

    menuId = 8; % Configuration Menu
    displayMenu(menuId);
    prompt = 'Please enter your choice (1-6):';
    choice = input(prompt);
    switch(choice),
        case 1,
            % Adding a Strategy
            cd ../GUI/config/;
            disp('Instructions:');
            disp('1. Create new strategy, and save it in folder /Strategy');
            disp('2. If file name is ''newStrategy.m'', create and appropritely populate ''newStrategy_config.m'' in the same folder');
            disp('3. An example of this type of files is shown in ''template.m'' and ''template_config.m''');
            newStrategyFileName = input('Enter name of file that you want to add (e.g. ''newStrategy''):');
            configFile          = input('Enter name of configuration you want to change (e.g. ''config_myconfig''):');
            addStrategy( newStrategyFileName, configFile );
            cd ../../PGUI/;
            configurationMenu;
        case 2,
            % Removing a Strategy
            prompt = ('Name of config file do you want to update (e.g. ''config_myconfig''):');
            configFile = input(prompt);
            cd ../GUI/config/;
            load(configFile);

            % Display all Strategies
            disp('Strategies in current config:');
            nAlgo = length(algorithmList);
            for i = 1:1:nAlgo
                msg = strcat(num2str(i), '.');
                msg = strcat(msg, algorithmList{i});
                fprintf(msg);
                fprintf('\n');
            end

            prompt = ('Enter ID of Strategy to be removed:');
            strategyId = input(prompt);
            removeStrategy( strategyId, configFile );

            cd ../../PGUI/;
            configurationMenu;
        case 3,
            % Adding a dataset
            cd ../GUI/config/;
            disp('First, save new dataset in folder /Data, in the correct format.');
            prompt              = 'Enter name of file (e.g. ''newData''):';
            dataFileName        = input(prompt);
            prompt              = 'Enter Data Description (e.g. '' New Data - 1st Jan, 2014 to 1st Jan, 2015):';
            dataDescriptionName = input(prompt);
            prompt              = 'Enter frequency (e.g. 1 for daily data):';
            newDataFrequency    = input(prompt);
            prompt              = 'Enter name of config file do you want to update (e.g. ''config_myconfig''):';
            configFile          = input(prompt);
            addData( dataFileName, dataDescriptionName, newDataFrequency, configFile );
            cd ../../PGUI/;
            configurationMenu;
        case 4,
            % Removing a dataset
            cd ../GUI/config/;
            prompt = ('Name of config file do you want to update (e.g. ''config_myconfig''):');
            configFile = input(prompt);
            load(configFile);

            % Display all data sets
            disp('Datasets in current config:');
            nData = length(dataList);
            for i = 1:1:nData
                msg = strcat(num2str(i), '.');
                msg = strcat(msg, dataList{i});
                fprintf(msg);
                fprintf('\n');
            end

            prompt = ('Enter ID of Data to be removed:');
            dataId = input(prompt);
            removeData( dataId, configFile );
            cd ../../PGUI/;
            configurationMenu;
        case 5,
            prompt = ('Name of config file do you want to make active (e.g. ''config_myconfig''):');
            configFile = input(prompt);
            cd ../GUI/config/;
            load(configFile);
            save('config', 'algorithmList', 'algorithmName', 'algorithmParameters', 'dataFrequency', 'dataList', 'dataName', 'defaultParameters', 'windowRisk');
            disp('Update Configuration. Restart toolbox to read the updated configuration');
            cd ../../PGUI/;
            configurationMenu;
        case 6,
            disp('Exiting Configuration Manager --> to Home');
            homeMenu;
        otherwise,
            disp('ERROR: Please enter a valid input');
            configurationMenu;
    end
end


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

% Last Modified by GUIDE v2.5 09-May-2016 17:18:03

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

%MERGESTUPDATED

handles.data = varargin{1};
clsParams = handles.data.classifier_params;
tf = cellfun(@(x)isequal(x,clsParams{1}),clsParams(2:end));
if ~all(tf)
  warning('ClassifierOptions:multiclass',...
    'Multiple classifiers do not share common parameters. This interface will set all classifiers to have the same parameters.');
end
params = clsParams{1};

handles.classifier_params = params;
set(handles.edit_iter,'String',num2str(params.iter));
set(handles.iter_updates,'String',num2str(params.iter_updates));
set(handles.edit_sample,'String',num2str(params.numSample));
set(handles.edit_bins,'String',num2str(params.numBins));
set(handles.folds,'String',num2str(params.CVfolds));
set(handles.edit_nftrs,'String',num2str(params.nselfeatures));
set(handles.popup_baseclassifier,'String',params.baseClassifierTypes);

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

% Update handles structure
guidata(hObject, handles);

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

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

% Get default command line output from handles structure
varargout{1} = handles.output;
delete(handles.figure1);

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

% Hints: get(hObject,'String') returns contents of edit_iter as text
%        str2double(get(hObject,'String')) returns contents of edit_iter as a double
val = str2double(get(hObject,'String'));
if isempty(val) || double(uint64(val))~=val
  warndlg('Enter positive value for number of iterations');
  set(hObject,'String',sprintf('%d',handles.classifier_params.iter));
  return;
end;
handles.classifier_params.iter = val;
guidata(hObject,handles);

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

% Hints: get(hObject,'String') returns contents of edit_sample as text
%        str2double(get(hObject,'String')) returns contents of edit_sample as a double
val = str2double(get(hObject,'String'));
if isempty(val) || double(uint64(val))~=val
  warndlg('Enter positive value for number of sample points');
  set(hObject,'String',sprintf('%d',handles.classifier_params.numSample));
  return;
end;
handles.classifier_params.numSample = val;
guidata(hObject,handles);

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

% Hints: get(hObject,'String') returns contents of edit_bins as text
%        str2double(get(hObject,'String')) returns contents of edit_bins as a double
val = str2double(get(hObject,'String'));
if isempty(val) || double(uint64(val))~=val
  warndlg('Enter positive integer value for number of iterations');
  set(hObject,'String',sprintf('%d',handles.classifier_params.numBins));
  return;
end;

if val>255 || val<10
  warndlg('Maximum number of bins is 255 and minimum number is 10');
  set(hObject,'String',sprintf('%d',handles.classifier_params.numBins));
  return;
end;
handles.classifier_params.numBins = val;
guidata(hObject,handles);

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

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

paramCell = repmat({handles.classifier_params},1,handles.data.nclassifiers);
handles.data.setClassifierParams(paramCell);
uiresume(handles.figure1);

% --- Executes on selection change in popup_baseclassifier.
function popup_baseclassifier_Callback(hObject, eventdata, handles)
% hObject    handle to popup_baseclassifier (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns popup_baseclassifier contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popup_baseclassifier
handles.classifier_params.baseClassifierSelected = get(hObject,'Value');

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

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

function folds_Callback(hObject, eventdata, handles)
% hObject    handle to folds (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 folds as text
%        str2double(get(hObject,'String')) returns contents of folds as a double
val = str2double(get(hObject,'String'));
if isempty(val) || double(uint64(val))~=val
  warndlg('Enter positive value for number of iterations');
  set(hObject,'String',sprintf('%d',handles.classifier_params.iter));
  return;
end;
handles.classifier_params.CVfolds = val;
guidata(hObject,handles);

% --- Executes during object creation, after setting all properties.
function folds_CreateFcn(hObject, eventdata, handles)
% hObject    handle to folds (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 iter_updates_Callback(hObject, eventdata, handles)
% hObject    handle to iter_updates (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 iter_updates as text
%        str2double(get(hObject,'String')) returns contents of iter_updates as a double
val = str2double(get(hObject,'String'));
if isempty(val) || double(uint64(val))~=val
  warndlg('Enter positive value for number of iterations');
  set(hObject,'String',sprintf('%d',handles.classifier_params.iter_updates));
  return;
end;
handles.classifier_params.iter_updates = val;
guidata(hObject,handles);

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

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

% --- Executes when user attempts to close figure1.
function figure1_CloseRequestFcn(hObject, eventdata, handles)
% hObject    handle to figure1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: delete(hObject) closes the figure
uiresume(hObject);
% delete(hObject);

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

% Hints: get(hObject,'String') returns contents of edit_nftrs as text
%        str2double(get(hObject,'String')) returns contents of edit_nftrs as a double
val = str2double(get(hObject,'String'));
if isempty(val) || double(uint64(val))~=val
  warndlg('Enter positive integer value for number of sample points');
  set(hObject,'String',sprintf('%d',handles.classifier_params.numSample));
  return;
end;
handles.classifier_params.nselfeatures = val;
guidata(hObject,handles);

% --- Executes during object creation, after setting all properties.
function edit_nftrs_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_nftrs (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 q = reshape(q,varargin)
% overloads reshape

q.a = reshape(q.a,varargin{:});
q.b = reshape(q.b,varargin{:});
q.c =  reshape(q.c,varargin{:});
q.d = reshape(q.d,varargin{:});


% findInstrument - Finds an instrument by model name, vendor name or VISA resource
%
%    obj = findInstrument('STR') returns an interface object to an
%       instrument whose model name, vendor name or VISA resource matches
%       any part of the string STR. If there is no unique match, obj is []
%       and a list of available instruments is displayed.
%
%       findInstrument currently only works with USB and GPIB instruments
%       and requires a VISA adaptor.
%
%       STR is first compared to the model and vendor names. If none of
%       these match, STR is then compared to the VISA resource names. The
%       matching ignores the case of the strings (i.e., upper/lower case)
%
%    obj = findInstrument('STR', 'ADAPTOR') uses the specified VISA
%       adaptor. This is only applicable if you have multiple VISA
%       installations (by default, findInstrument picks one of the VISA
%       adaptors).
%
%    Examples:
%      % see a list of all the available instruments
%      findInstrument;
%
%      % find an instrument by model number
%      obj = findInstrument('34405');
%      fopen(obj)
%      query(obj,'*IDN?')
%      fclose(obj)
%
%      % find an instrument by model number, using Agilent VISA
%      obj = findInstrument('34405', 'agilent');
%
%      % find an instrument by matching a manufacturer name
%      obj = findInstrument('tek');
%
%      % find an instrument by the model code in the VISA resource
%      obj = findInstrument('0x0618')
%
%    If your instrument doesn't show up with findInstrument, use
%    this Troubleshooting checklist
%
%   Related Functions:
%     instrfindall (Find existing interface objects)
%     instrreset   (Close and delete all interface objects)
%     obj2mfile    (Generate MATLAB code for re-creating an interface object)

% Copyright 2009, The MathWorks, Inc.

function out = findInstrument(searchstr, adaptor)

if exist('instrhwinfo', 'file') ~= 2
    error('This function requires Instrument Control Toolbox');
end

if ~exist('searchstr', 'var')
    searchstr = '';
end
searchstr = strtrim(lower(searchstr));

if strcmp(searchstr, '##troubleshoot')
    helpstr = troubleshootHelp;
    disp(helpstr);
    return;
end

visainfo = instrhwinfo('visa');

if numel(visainfo.InstalledAdaptors) == 0
    error('No VISA adaptors found\n');
end

if ~exist('adaptor', 'var')
    adaptor = visainfo.InstalledAdaptors{end};
end

try
    instr = instrhwinfo('visa', adaptor);
catch %#ok<CTCH>
    error('VISA Adaptor ''%s'' is not installed on this system', adaptor);
end

out = [];

%% Scan over all the instruments returned by the VISA adaptor
% For each instrument: match its VISA resource; try to get its
% ID string; match its vendor or model name

info = []; cnt = 0;
for j=1:numel(instr.ObjectConstructorName)
    constructor = instr.ObjectConstructorName{j};

    res = regexpi(constructor, '[a-z]*\(''[a-z]+''[ ]*,[ ]*''(?<resource>[A-Z0-9:]+)''', 'names');
    if (numel(res) == 0) || strcmpi(res.resource(1:4),'ASRL')
        % serial port, ignore
        continue;
    end

    cnt = cnt + 1;
    info(cnt).resource = res.resource; %#ok<*AGROW>
    info(cnt).constructor = constructor;
    info(cnt).resourceMatched = ~isempty(findstr(searchstr, lower(res.resource)));
    info(cnt).idMatched = false;

    obj = eval(constructor);

    % visa resource strings have "::". For ICT objects, this is replaced
    % by "-". Get the ICT resource name so that we can search for other
    % interface objects for the same resource
    info(cnt).ICT_resource = get(obj, 'RsrcName');

    try
        fopen(obj);
        idString = query(obj, '*IDN?');
        fclose(obj);
        delete(obj);
        info(cnt).connectStatus = true;
    catch %#ok<CTCH>
        % open failed, probably because the connection is already
        % open from within MATLAB or another program
        delete(obj);
        info(cnt).connectStatus = false;
        continue;
    end

    % idString will have the following format
    %   <manufacturer>, <model name>, <serial number>, <firmware revision>
    % we only care about manufacturer and model name
    strs = regexp(idString, '[ ]*,[ ]*', 'split');
    if numel(strs) < 4
        strs{4} = '';
    end
    id.vendor = strs{1};
    id.model = strs{2};

    modelMatched = ~isempty(findstr(searchstr, lower(id.model)));
    vendorMatched = ~isempty(findstr(searchstr, lower(id.vendor)));
    info(cnt).idMatched = modelMatched || vendorMatched;

    info(cnt).id = id;
end % loop over each instrument

if numel(info) == 0
    out = [];
    fprintf('No USB or GPIB instruments found using ''%s'' VISA\n', adaptor);
    return;
end

%% Collate the match information.
% Only create an interface object if there is a unique match

idMatches = find( [info.idMatched] );
numIdMatches = numel(idMatches);

resourceMatches = find( [info.resourceMatched] );
numResourceMatches = numel(resourceMatches);

if numIdMatches == 1
    % A match to vendor or model supersedes any VISA resource matches
    % i.e., from the user's perspective, we'll only examine resource
    % strings if there is no vendor or model match
    idx = idMatches(1);
    if ~isempty(instrfindall('RsrcName', info(idx).ICT_resource))
        warning('findInstrument:MultipleInterfaceObjects', ...
            'Preexisting interface objects for ''%s''', info(idx).resource);
    end
    out = eval(info(idx).constructor);

elseif numIdMatches > 1
    out = [];
    fprintf('%d instruments matched ''%s''\n\n', numIdMatches, searchstr);
    showInstrumentInfo(info, idMatches);
    noConn = find([info.connectStatus] == false);

    if numel(noConn) > 0
        fprintf('%d instrument(s) could not be reached\n\n', numel(noConn));
        showInstrumentInfo(info, noConn);
    end

elseif numIdMatches == 0 && numResourceMatches == 1
    idx = resourceMatches(1);
    if info(idx).connectStatus == false
        out = [];
        fprintf('One instrument matched ''%s'' (VISA resource), but it cannot be reached\n\n', searchstr);
        showInstrumentInfo(info, idx);
        return;
    end
    if ~isempty(instrfindall('RsrcName', info(idx).ICT_resource))
        warning('findInstrument:MultipleInterfaceObjects', ...
            'Preexisting interface objects for ''%s''', info(idx).resource);
    end
    out = eval(info(idx).constructor);

elseif numIdMatches == 0 && numResourceMatches > 0
    out = [];
    fprintf('%d instrument(s) matched ''%s'' (VISA Resource)\n\n', numResourceMatches, searchstr);
    showInstrumentInfo(info, resourceMatches);

elseif numIdMatches == 0 && numResourceMatches == 0
    out = [];
    fprintf('No instruments matched ''%s''. Available instruments:\n\n', searchstr);
    showInstrumentInfo(info, 1:numel(info));

end

end

%%
    function showInstrumentInfo(info, indexList)
        for i=1:numel(indexList)
            idx = indexList(i);
            fprintf('  VISA Resource: %s\n', info(idx).resource);
            if info(idx).connectStatus == false
                fprintf('         Unable to connect (instrument may be in use)\n');
            else
                id = info(idx).id;
                fprintf('         Vendor: %s\n', id.vendor);
                fprintf('          Model: %s\n', id.model);
            end
            fprintf('\n');
        end
    end

 %%
    function out = troubleshootHelp
s = {
'    Troubleshooting:'
'      If your instrument doesn''t show up with findInstrument, use the '
'      following checklist:'
''
'      1) Is the instrument turned on and connected to your computer?'
''
'      2) Check if you have multiple VISAs installed, by typing:'
'            instrhwinfo(''visa'')'
'         If you do have multiple VISAs, explicitly specify the VISA adaptor'
'            obj = findInstrument(''34405'', ''agilent'');'
'            obj = findInstrument(''34405'', ''ni'');'
''
'      3) Does any other program have an open connection to the instrument?'
'         If yes, close that program and try again.'
''
'      4) Do you have an open connection to the instrument from MATLAB?'
'         You can verify this by typing ''instrfindall'' at the command line.'
'         Type ''instrreset'' to close and delete the existing connections'
''
'      5) If the problem persists,'
'         - type ''instrreset'' at the MATLAB command line'
'         - unplug the instrument from the PC,'
'         - wait a few seconds, and'
'         - plug the instrument back in'
};
out = char(s);
    end

% Format of a VISA resource string
% GPIB[board]::primary address[::GPIB secondary address][::INSTR]
% USB[board]::manufacturer-id::model-id::serial #[::USB interface #][::INSTR]
%
% Examples
% USB0::0x0957::0x0588::CN49140544::INSTR
% USB0::0x0957::0x0618::TW46000285::INSTR
% GPIB0::24::INSTR

% Format of an identification string returned by an instrument
% <manufacturer>, <model name>, <serial number>, <firmware revision>
%
% -- Examples
% Agilent Technologies,33210A,MY48000278,1.03-1.02-26-2
% Agilent Technologies,34405A,TW46000285,1.40-3.08
% Agilent Technologies,DSO1014A,CN49140544,00.04.02
% HEWLETT-PACKARD,E3631A,0,2.1-5.0-1.0
% HEWLETT-PACKARD,33120A,0,2.0-2.0-1.0
% TEKTRONIX,TDS 210,0,CF:91.1CT FV:v2.03 TDS2MM:MMV:v1.04
% TEKTRONIX,TDS 3034B,0,CF:91.1CT FV:v3.41 TDS3FFT:v1.00 TDS3TRG:v 1.00
% TEKTRONIX,TDS 3034C,0,CF:91.1CT FV:v4.01 TDS3FFT:v1.00 TDS3TRG:v1.00
% KEITHLEY INSTRUMENTS INC.,MODEL 2701,1216866,A09 /A02
% *IDN LECROY,9354AL,935408135,07.3.0
% *IDN LECROY, WM8300, WAVEMASTER00112,0.5.0 n


try
    EEGDATA.marker_buffer(:,1+mod(EEGDATA.mmax:EEGDATA.mmax+size(EEGDATA_marker_chunk,2)-1,EEGDATA.marker_buffer_len)) = EEGDATA_marker_chunk;
catch e
    if any(strcmp(e.identifier,{'MATLAB:heterogeneousStrucAssignment','MATLAB:heterogenousStrucAssignment'}))
        EEGDATA.marker_buffer = EEGDATA_marker_chunk(ones(1,EEGDATA.marker_buffer_len));
        EEGDATA.marker_buffer(:,1+mod(EEGDATA.mmax:EEGDATA.mmax+size(EEGDATA_marker_chunk,2)-1,EEGDATA.marker_buffer_len)) = EEGDATA_marker_chunk;
    else
        rethrow(e);
    end
end


function bbm = bbmean(x,B,w)
% BBMEAN  Bayesian bootstrap mean
%
%    Description
%    bbm = bbmean(x,B,w)
%    x NxM matrix of data
%    B number of bootstrap replicates
%    w Nx1 vector of weights
%
% Copyright (c) Aki Vehtari, 1998-2004

% This software is distributed under the GNU General Public
% License (version 3 or later); please refer to the file
% License.txt, included with the software, for details.

error('No mex-file for this architecture. See Matlab help and convert.m in ./linuxCsource or ./winCsource for help.')


function roidb = roidb_from_voc(imdb)
% roidb = roidb_from_voc(imdb)
%   Builds an regions of interest database from imdb image
%   database. Uses precomputed selective search boxes available
%   in the R-CNN data package.
%
%   Inspired by Andrea Vedaldi's MKL imdb and roidb code.

% AUTORIGHTS
% ---------------------------------------------------------
% Copyright (c) 2014, Ross Girshick
%
% This file is part of the R-CNN code and is available
% under the terms of the Simplified BSD License provided in
% LICENSE. Please retain this notice and LICENSE if you use
% this file (or any portion of it) in your project.
% ---------------------------------------------------------
% Change by Ning Zhang

cache_file = ['./imdb/cache/roidb_' imdb.name];
try
  load(cache_file);
catch
  roidb.name = imdb.name;

  fprintf('Loading region proposals...');

  regions_file = sprintf('./data/selective_search_data/%s', roidb.name);
  % follow the selective search instructions and run selective search on bird images.
  try
    regions = load(regions_file);
  catch
    disp('Run selective search on cub2011 images first.');
    exit(-1);
  end
  fprintf('done\n');
  % if config file doesn't exist. run config = get_bird_data;
  load('caches/cub2011_config.mat');
  for i = 1:length(imdb.image_ids)
    tic_toc_print('roidb (%s): %d/%d\n', roidb.name, i, length(imdb.image_ids));
    voc_rec = get_pascal_format(config, imdb.image_ids{i});
    roidb.rois(i) = attach_proposals(voc_rec, regions.boxes{i}, imdb.class_to_id);
  end

  fprintf('Saving roidb to cache...');
  save(cache_file, 'roidb', '-v7.3');
  fprintf('done\n');
end

function voc_rec = get_pascal_format(config, img_path)
  % find image id for img_path
  full_path = [config.img_base img_path];
  train_idx = find(ismember(config.impathtrain, full_path));
  test_idx = find(ismember(config.impathtest, full_path));
  assert(isempth(train_idx) || isempty(test_idx));
  assert(~isempty(train_idx) || ~isempty(test_idx));
  if ~isempty(train_idx)
    voc_rec.object(1).bbox = config.train_box{1}(train_idx,:);
    voc_rec.object(1).class = 'bbox';
    count = 2;
    if config.train_box{2}(train_idx,1) ~= -1
      voc_rec.object(count).bbox = config.train_box{2}(train_idx,:);
      voc_rec.object(count).class = 'head';
      count = count + 1;
    end
    if config.train_box{3}(train_idx,1) ~= -1
      voc_rec.object(count).bbox = config.train_box{3}(train_idx,:);
      voc_rec.object(count).class = 'body';
    end
  end
  if ~isempty(test_idx)
    voc_rec.object(1).bbox = config.test_box{1}(test_idx,:);
    voc_rec.object(1).class = 'bbox';
    count = 2;
    if config.test_box{2}(test_idx,1) ~= -1
      voc_rec.object(count).bbox = config.test_box{2}(test_idx,:);
      voc_rec.object(count).class = 'head';
      count = count + 1;
    end
    if config.test_box{3}(test_idx,1) ~= -1
      voc_rec.object(count).bbox = config.test_box{3}(test_idx,:);
      voc_rec.object(count).class = 'body';
    end
  end
end

% ------------------------------------------------------------------------
function rec = attach_proposals(voc_rec, boxes, class_to_id)
% ------------------------------------------------------------------------

% change selective search order from [y1 x1 y2 x2] to [x1 y1 x2 y2]
boxes = boxes(:, [2 1 4 3]);

%           gt: [2108x1 double]
%      overlap: [2108x20 single]
%      dataset: 'voc_2007_trainval'
%        boxes: [2108x4 single]
%         feat: [2108x9216 single]
%        class: [2108x1 uint8]
if isfield(voc_rec, 'objects')
  gt_boxes = cat(1, voc_rec.objects(:).bbox);
  all_boxes = cat(1, gt_boxes, boxes);
  gt_classes = class_to_id.values({voc_rec.objects(:).class});
  gt_classes = cat(1, gt_classes{:});
  num_gt_boxes = size(gt_boxes, 1);
else
  gt_boxes = [];
  all_boxes = boxes;
  gt_classes = [];
  num_gt_boxes = 0;
end
num_boxes = size(boxes, 1);

rec.gt = cat(1, true(num_gt_boxes, 1), false(num_boxes, 1));
rec.overlap = zeros(num_gt_boxes+num_boxes, class_to_id.Count, 'single');
for i = 1:num_gt_boxes
  rec.overlap(:, gt_classes(i)) = ...
      max(rec.overlap(:, gt_classes(i)), boxoverlap(all_boxes, gt_boxes(i, :)));
end
rec.boxes = single(all_boxes);
rec.feat = [];
rec.class = uint8(cat(1, gt_classes, zeros(num_boxes, 1)));


function [stop, options] = msOutFcn(optimValues, ~, totIterExpect, hWaitBar, iniMessage, ticID)
    elapsedTime = toc(ticID);
    avgTimePerRun = elapsedTime/optimValues.localrunindex;
    runsRemaining = totIterExpect - optimValues.localrunindex;
    estTimeRemaining = runsRemaining*avgTimePerRun;

    [timeRemainingStr] = getDurationStr(estTimeRemaining);
%     timeRemainingStr =  num2str(estTimeRemaining, '%8.3f');
%     timeRemainingStr = paddStr(timeRemainingStr, 7);

    if(isnan(estTimeRemaining) || ~isempty(strfind(timeRemainingStr,'NaN')))
        estTimeStr = '';
    else
        estTimeStr = ['Est. Time Left: ', timeRemainingStr];
    end

    msgStr = {[iniMessage, ' [',num2str(optimValues.localrunindex),'/',num2str(totIterExpect),']'],...
              estTimeStr};

    if(isa(hWaitBar, 'matlab.ui.dialog.ProgressDialog'))
        hWaitBar.Message = msgStr;
        hWaitBar.Value = optimValues.localrunindex/totIterExpect;
    else
        waitbar(optimValues.localrunindex/totIterExpect, hWaitBar, msgStr);
    end

    stop = false;
    if(nargout == 2)
        options=[];
    end
end


function []=plot_sb_baselines(vargin)
% PLOT_SB_BASELINES replaced by SB_BASELINE_PLOT
% Optional an input argument ix can be specified containing a vector of the
% small baseline interferograms to keep which will be plotted in the baseline plot.
%
% Modifications:
% DB 12/2012    fix error for input arguments and add the some syntax
% DB 01/2016    Suppress the warning. Alternative remove the function.

% warning('name of this function changed to sb_baseline_plot')

if nargin>0                     % [DB] changed to nargin > 0, as ix cannot be specified otherwize
    sb_baseline_plot(vargin)
else
    sb_baseline_plot
end


function [filesInCurDir,dirsInCurDir]=rdir(apath)
%Recursively search directories for all files and directories contained
%therein
% Example call: [filesInWorkingDir,dirsInWorkingDir]=rdir(pwd)
%
% 05/09/2013, http://www.matlabexperthelp.com/2012/08/15/recursive-directory-listing/

%% recursively get file contents of all directories
dirInfo=dir(apath);
dirInfo=dirInfo(~(strcmp({dirInfo.name},'..') | strcmp({dirInfo.name},'.' )));
for i=1:length(dirInfo)
    dirInfo(i).fullpath=fullfile(apath,dirInfo(i).name);
end
dirsInCurDir  = dirInfo([dirInfo.isdir]);
filesInCurDir = dirInfo(~[dirInfo.isdir]);

%% loop through dirs and get files and dirs inside of current dirs contents
for i=1:length(dirsInCurDir)
    % Call this function again and concatenate results
    [filesInThisDir, dirsInThisDir]=rdir(dirsInCurDir(i).fullpath);
    if ~isempty(filesInThisDir)
        filesInCurDir=[filesInCurDir; filesInThisDir ];
    end
    if ~isempty(dirsInThisDir)
        dirsInCurDir=[dirsInCurDir; dirsInThisDir];
    end
end


% read_eeglabevent() - import EEGLAB dataset events
%
% Usage:
%     >> event = read_eeglabevent(filename, ...);
%
% Inputs:
%     filename - [string] file name
%
% Optional inputs:
%     'header' - FILEIO structure header
%
% Outputs:
%     event - FILEIO toolbox event structure
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, 2008-

%123456789012345678901234567890123456789012345678901234567890123456789012

% Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD, arno@salk.edu
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

function event = read_eeglabevent(filename, varargin)

if nargin < 1
  help read_eeglabheader
  return
end

hdr = ft_getopt(varargin, 'header');

if isempty(hdr)
  hdr = read_eeglabheader(filename);
end

event    = [];                % these will be the output in FieldTrip format
oldevent = hdr.orig.event;    % these are in EEGLAB format

if ~isempty(oldevent)
  nameList = fieldnames(oldevent);
else
  nameList = [];
end
nameList = setdiff(nameList, {'type','value','sample','offset','duration','latency'});

for index = 1:length(oldevent)

  if isfield(oldevent,'code')
    type = oldevent(index).code;
  elseif isfield(oldevent,'value')
    type = oldevent(index).value;
  else
    type = 'trigger';
  end

  % events can have a numeric or a string value
  if isfield(oldevent,'type')
    value  = oldevent(index).type;
  else
    value = 'default';
  end

  % this is the sample number of the concatenated data to which the event corresponds
  sample = oldevent(index).latency;

  % a non-zero offset only applies to trial-events, i.e. in case the data is
  % segmented and each data segment needs to be represented as event. In
  % that case the offset corresponds to the baseline duration (times -1).
  offset = 0;

  if isfield(oldevent, 'duration')
    duration = oldevent(index).duration;
  else
    duration = 0;
  end

  % add the current event in FieldTrip format
  event(index).type     = type;     % this is usually a string, e.g. 'trigger' or 'trial'
  event(index).value    = value;    % in case of a trigger, this is the value
  event(index).sample   = sample;   % this is the sample in the datafile at which the event happens
  event(index).offset   = offset;   % some events should be represented with a shifted time-axix, e.g. a trial with a baseline period
  event(index).duration = duration; % some events have a duration, such as a trial

  %add custom fields
  for iField=1:length(nameList)
    eval(['event(index).' nameList{iField} '=oldevent(index).' nameList{iField} ';']);
  end

end % for oldevent

if hdr.nTrials>1
  % add the trials to the event structure
  for i=1:hdr.nTrials
    event(end+1).type     = 'trial';
    event(end  ).sample   = (i-1)*hdr.nSamples + 1;
    if isfield(oldevent,'setname') && (length(oldevent) == hdr.nTrials)
      event(end  ).value  = oldevent(i).setname; % accommodate Widmann's pop_grandaverage function
    else
      event(end  ).value  = [];
    end
    event(end  ).offset   = -hdr.nSamplesPre;
    event(end  ).duration =  hdr.nSamples;
  end
end % if nTrials>1


% Display ASCII waiting bar
%
% Inputs
%  max_index : maximum index
%  -- or --
%  pb        : progress bar structure
%  i         : current
%  title     : text shown after the remaining time
%
% Outputs
%  pb        : progress bar structure
%
% Example
%  pb = progressbar(max_index);
%  for index=1:max_index;
%    [...]
%    pb = progressbar(pb, index);
%  end
%
% Copyright (c) 2008 Ircam-CNRS UMR9912-STMS
%
% License
%  This file is under the LGPL license,  you can
%  redistribute it and/or modify it under the terms of the GNU Lesser General
%  Public License as published by the Free Software Foundation, either version 3
%  of the License, or (at your option) any later version. This file 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 Lesser General Public License for more
%  details.
%
% This function is part of the Covarep project: http://covarep.github.io/covarep
%
% Author
%  Gilles Degottex <gilles.degottex@ircam.fr>
%

function pb = progressbar(pbin, i, text)

	if nargin==1
		pb.max_n = pbin;
		pb.history = [];
		pb.i_old = 0;
        pb.finished = false;
        pb.nbp = 0;
		tic;
		return;
	else
		pb = pbin;
	end

	if toc<1/16 && i<pb.max_n; return; end

%  	if nargin~=2
%  		return;
%  	end

    if ~pb.finished

	    pb.history = [pb.history, toc];
	    pb.iteration_time = mean(pb.history);

	    pos = i / pb.max_n;
	    str='|=';
	    for c = 1:floor(pos*50)
		    str = [str, '='];
	    end
	    for c = floor(pos*50):50-1
		    str = [str, ' '];
	    end

	    di = i - pb.i_old;
	    nrest = (pb.max_n-i)/di;
	    minutes = floor(sum(pb.history)/60);
	    seconds = rem(sum(pb.history), 60);
	    str_times = ['  elapsed: ', num2str(minutes), ':', num2str(floor(seconds))];
	    if nrest>0
		    rem_minutes = floor(pb.iteration_time*nrest/60);
		    rem_seconds = rem(pb.iteration_time*nrest, 60);
		    str_times = [str_times, ' remaining: ', num2str(rem_minutes), ':', num2str(round(rem_seconds))];
	    else
            str_times = [str_times, '               '];
        end

		str_full = [num2str(floor(pos * 100)),'%% ', str_times];
		if 1
			str_full = [repmat('\b',1,pb.nbp),str_full];
		else
			str_full = ['\r',str_full];
		end

        if nargin>2
        	str_full = [str_full, ': ', text];
        end
       	str_full = [str_full, '       '];
        nbp = fprintf(str_full);
        pb.nbp = nbp - pb.nbp;

	    pb.i_old = i;
	    tic;

        if i>=pb.max_n;
            pb.finished = true;
            disp(' ');
        end
    end

return


function view=segmentationMenu(view)
% view = segmentationMenu(view)
%
% Set up the callbacks for the segmentation/unfold menu
%
% djh, 2/14/2001
segmentationMenu = uimenu('Label','Segmentation','separator','on');

% Install new segmentation
%    installSegmentation;
callBackstr='installSegmentation;';
uimenu(segmentationMenu,'Label','(Re-)install segmentation','Separator','off',...
    'CallBack',callBackstr);

if strcmp(view.viewType,'Gray') || strcmp(view.viewType,'Volume')
    % Wrapper for mrFlatMesh
    %    flattenFromROI(view, ROI)
    callBackstr=['flattenFromROI(',view.name,');'];
    uimenu(segmentationMenu,'Label','Flatten (start from ROI)','Separator','on',...
        'CallBack',callBackstr);
end

% New flat callback:
%  newFlat;
callBackstr='newFlat;';
uimenu(segmentationMenu,'Label','Install New Unfold','Separator','off',...
    'CallBack',callBackstr);

% If flat view, pass arg to specify which flat to re-install
% Otherwise, user will be prompted to pick one of the flat subdirectories
if strcmp(view.viewType,'Flat')
    % Install new unfold
    %    installUnfold(view);
    callBackstr=['installUnfold(',view.name,'.subdir);'];
    uimenu(segmentationMenu,'Label','Reinstall unfold','Separator','off',...
        'CallBack',callBackstr);
else
    callBackstr='installUnfold;';
    uimenu(segmentationMenu,'Label','Reinstall unfold','Separator','off',...
        'CallBack',callBackstr);
end

if strcmp(view.viewType,'Volume') || strcmp(view.viewType,'Gray') || strcmp(view.viewType,'Flat')
    % Message box with segmentation information
    %    segInfo = segmentInfo(view)
    callBackstr=['segmentInfo(',view.name,');'];
    uimenu(segmentationMenu,'Label','Segmentation info','Separator','on',...
        'CallBack',callBackstr);
end

if strcmp(view.viewType,'Flat')
    % Xform Verify Gray-Flat correspondence callback:
    %    verifyGrayFlat(view);
    callBackstr=['checkCoordsNodes(',view.name,');'];
    uimenu(segmentationMenu,'Label','Verify Gray-Flat match','Separator','off',...
        'CallBack',callBackstr);
end

return


function exportModel(modelName)
% exportModel(modelName)
%
% Zips a trained model so that it can be uploaded to our homepage.
%
% Copyright by Holger Caesar, 2016

% Settings
global glBaseFolder;
if strcmp(modelName, 'frcn')
    exportName = 'FRCN_VOC2010_model';
    exportFiles = {'net-epoch-16.mat', 'net-train.pdf', 'log.txt', 'resultsEpochFinalTest.mat'};
    exportFilesPrefix = fullfile(glBaseFolder, 'Features', 'CNN-Models', 'FRCN', 'VOC2010', 'VOC2010-testRelease');
elseif strcmp(modelName, 'fcn')
    exportName = 'FCN_SiftFlow_model';
    exportFiles = {'labelings-test-epoch50', 'net-epoch-50.mat', 'net-opts.mat', 'net-train.pdf', 'log.txt', 'stats-test-epoch50.mat'};
    exportFilesPrefix = fullfile(glBaseFolder, 'Features', 'CNN-Models', 'FCN', 'SiftFlow', 'fcn16s-testRelease');
elseif strcmp(modelName, 'e2s2_fast')
    exportName = 'E2S2_SiftFlow_model_fast';
    exportFiles = {'labelings-test-epoch10', 'net-epoch-10.mat', 'net-opts.mat', 'net-train.pdf', 'log.txt', 'stats-test-epoch10.mat'};
    exportFilesPrefix = fullfile(glBaseFolder, 'Features', 'CNN-Models', 'E2S2', 'SiftFlow', 'Run1', 'SiftFlow_e2s2_run1_exp1');
elseif strcmp(modelName, 'e2s2_full')
    exportName = 'E2S2_SiftFlow_model_full';
    exportFiles = {'labelings-test-epoch25', 'net-epoch-25.mat', 'net-opts.mat', 'net-train.pdf', 'log.txt', 'stats-test-epoch25.mat'};
    exportFilesPrefix = fullfile(glBaseFolder, 'Features', 'CNN-Models', 'E2S2', 'SiftFlow', 'Run1', 'SiftFlow_e2s2_run1_exp2');
else
    error('Error: Unknown model: %s', modelName);
end

% Define paths
exportFolder = fullfile(glBaseFolder, 'Export');
if ~exist(exportFolder, 'dir')
    mkdir(exportFolder);
end

% Create zip file
exportFilePath = fullfile(exportFolder, [exportName, '.zip']);
if exist(exportFilePath, 'file')
    fprintf('Using existing zip file: %s\n', exportFilePath);
else
    fprintf('Creating zip file: %s\n', exportFilePath);
    zip(exportFilePath, strcat(exportFilesPrefix, filesep, exportFiles));
end


function handles = dtiLoadROI(hObject,handles,fileName);
%
%  handles = dtiLoadROI(hObject,handles,[fileName]);
%
%Author: Wandell, Dougherty
%Purpose:
%

persistent defaultPath;

if(~exist('fileName','var') | isempty(fileName))
    if(isempty(defaultPath))
        fn = handles.defaultPath;
        if(exist(fullfile(fn, 'ROIs'),'dir')) fn = fullfile(fn, 'ROIs', filesep); end
    else
        fn = defaultPath;
    end
    [f, p] = uigetfile({'*.mat';'*.*'}, 'Load ROI...', fn);
    if(isnumeric(f)), disp('Load ROI canceled.'); return; end
    defaultPath = p;
    fileName = fullfile(p,f);
    refreshFig = 1;
else
    refreshFig = 0;
end
if(isfield(handles, 't1NormParams'))
  roi = dtiReadRoi(fileName, handles.t1NormParams);
else
  roi = dtiReadRoi(fileName);
end

handles = dtiAddROI(roi,handles);
if(refreshFig) handles = dtiRefreshFigure(handles, 0); end
if(~isempty(hObject)) guidata(hObject, handles); end
return;


function[res] = matFileHasField(path, fieldName)
% [res] = matFileHasField(path, fieldName)
%
% Check whether a mat file includes a variable, without loading it.
% Returns true if it is included or else false.
%
% Copyright by Holger Caesar, 2015

matObj = matfile(path, 'Writable', false);
info = whos(matObj, fieldName);
res = numel(info) == 1;


function classString = classIDToString(classID)

labels = getClassLabels;

if classID<1 || classID>length(labels)
    classString='unknown';
else
    classString = char(labels{classID});
end

end


function [CAN_POOL] = generateObjHyps( aid, numhyp, rect_score )
%GENERATESEEDS Popup object hypothesis from 2D to 3D
%   Detailed explanation goes here
global config

%% load data
rectangle = [];
rectCuboid2 = [];

load([config.bufname config.roomHypoFile]);
load([config.bufname config.objHypoFileUpdate]);
% load([config.folderName config.IMGLIST(aid).name '/' config.roomHypoFile]);
% load([config.folderName config.IMGLIST(aid).name '/' config.objHypoFileUpdate]);
% load([config.folderName config.IMGLIST(aid).name '/' config.rectangleScore]);

load(config.classifierName);
if ~exist('ClassNames','var')
    ClassNames = B.ClassNames;
end
% load('./object_classifier/objectclassifier.mat');
% load('./living_room/objectClassifier_livingroom.mat');

%% update
% ALL_HYPS = cell(numhyp, numsample);

all_opScr = [hypothesis.opScr];
[S,I] = sort(all_opScr, 'descend');
hypothesis = hypothesis(I(1:config.sampleroomnum));
hypothesis_ori = hypothesis_ori(I(1:config.sampleroomnum));

CAN_POOL = cell(min(numhyp, length(hypothesis)),1);

for hid = 1:min(numhyp, length(hypothesis))
% while hid<=numhyp
    room_hyp = hypothesis(hid);
    camera_height = 160;
    [ room_obj ] = room3DFromHyp( room_hyp.hCorner, -camera_height );

    room_obj.omapScr = hypothesis(hid).omapScr;
    room_obj.gcScr = hypothesis(hid).gcScr;
    room_obj.mgScr = hypothesis(hid).mgScr;
    room_obj.opScr = hypothesis(hid).opScr;

    out_sign = sign(room_obj.out_points_w);
    if ~all(sum(out_sign,1)==0)
        continue;
    end

    %% get all hypotheses and project to 3D
    rectHyps = repmat(struct('objects',[],'scores',[],'valid',[],'bottomscore',[]), 14, 1);

    fprintf('Generaing cuboid: %d/%d, part 1\n', aid, hid);
    parfor rid = 1:5 %parfor
        objects = repmat(struct('out_points_w',[],'name',[],'type',[],'points',[],'x_w',[]),0,1);
        bottomscore = zeros(0,1);
        num = size(rectangle(rid).xyzBox,1);
        validIDs = find(rect_score{rid}>0.6);
        for bid = validIDs % 1:num
    %         fprintf('%d/%d\n', bid, num);
            if rid<=4
                newObj = rectangle2hypothesis( rectangle(rid).xyzBox(bid,:), rid, room_obj.out_points_w );
            elseif rid==5
                newObj = floorRectangle2hypothesis( rectangle(rid).xyzBox(bid,:), rid, room_obj.out_points_w );
            end
            objects(end+1:end+length(newObj)) = newObj;
            bottomscore(end+1:end+length(newObj),1) = rectangle(rid).score(bid);
    %         figure(1); clf; viewSingleRectangle(rotImg, rectangle, rid, bid);
    %         figure(2); clf; visualObject3D( [newObj;room_obj], 4, [1 1 1] );
        end
        rectHyps(rid).objects = objects;
        rectHyps(rid).bottomscore = bottomscore;
    end

    fprintf('Generaing cuboid: %d/%d, part 2\n', aid, hid);
    objects = repmat(struct('out_points_w',[],'name',[],'type',[],'points',[],'x_w',[]),0,1);
    bottomscore = zeros(0,1);
    for cid = 1:regionCuboid.count
    %     fprintf('%d/%d\n', cid, 100);
        views = regionCuboid.views(cid,:);
        if any(views==6)
            continue;
        end
        rects = regionCuboid.xyzBox(cid,:);
        rects = [rects(1:12); rects(13:24); rects(25:36)];
    %     newObj = obj3DFromHyp( rects, views, room_obj.out_points_w );
        newObj = rectangleCombo3Hypothesis( rects, views, room_obj.out_points_w );
        objects(end+1:end+length(newObj)) = newObj;
        bottomscore(end+1:end+length(newObj),1) = regionCuboid.score(cid);
    %     figure(1); clf; viewRegionHypothesisSubset( rotImg, regionCuboid, cid );
    %     figure(2); clf; visualObject3D( [newObj;room_obj], 4 );
    end
    rectHyps(6).objects = objects;
    rectHyps(6).bottomscore = bottomscore;

    fprintf('Generaing cuboid: %d/%d, part 3\n', aid, hid);
    parfor rid = 1:8 %parfor
    %     fprintf('%d/%d\n', rid, length(rectCuboid2));
        views = rectCuboid2(rid).views;
        views(views==0) = [];
        score1 = rectangle(views(1)).score;
        score2 = rectangle(views(2)).score;
        if any(views==5)
            num = length(rectCuboid2(rid).score);
            objects = repmat(struct('out_points_w',[],'name',[],'type',[],'points',[],'x_w',[]),0,1);
            bottomscore = zeros(0,1);
            for cid = 1:num
                combo = rectCuboid2(rid).combo(cid,:);
                rects = [rectangle(views(1)).xyzBox(combo(1),1:12); rectangle(views(2)).xyzBox(combo(2),1:12)];
                newObj = floorRectangleCombo2Hypothesis( rects, views, room_obj.out_points_w );

    %             figure(1); clf; viewRectHypothesisSubset(rotImg, rectCuboid2, rectangle, rid, cid);
    %             figure(2); clf; visualObject3D( [newObj;room_obj], 4 );
                objects(end+1:end+length(newObj)) = newObj;
                bottomscore(end+1:end+length(newObj),1) = max(score1(cid), score2(cid)); %rectCuboid2(rid).score(cid);
            end
        else
            num = length(rectCuboid2(rid).score);
            objects = repmat(struct('out_points_w',[],'name',[],'type',[],'points',[],'x_w',[]),0,1);
            bottomscore = zeros(0,1);
            for cid = 1:num
                combo = rectCuboid2(rid).combo(cid,:);
                rects = [rectangle(views(1)).xyzBox(combo(1),1:12); rectangle(views(2)).xyzBox(combo(2),1:12)];
                newObj = rectangleCombo2Hypothesis( rects, views, room_obj.out_points_w );

    %             figure(1); clf; viewRectHypothesisSubset(rotImg, rectCuboid2, rectangle, rid, cid);
    %             figure(2); clf; visualObject3D( [newObj;room_obj], 4 );
                objects(end+1:end+length(newObj)) = newObj;
                bottomscore(end+1:end+length(newObj),1) = max(score1(cid), score2(cid)); %rectCuboid2(rid).score(cid);
            end
        end

        rectHyps(rid+6).objects = objects;
        rectHyps(rid+6).bottomscore = bottomscore;
    end

    %% classify: semantic classifier, should move to DDsampling
    for rid = 1:14
        [ scores, valid ] = objectClassifier(room_obj, rectHyps(rid).objects, B, ClassNames);
        rectHyps(rid).scores = scores;
        rectHyps(rid).valid = valid;
%         num = length(rectHyps(rid).objects);
%         rectHyps(rid).scores = zeros(num,28);
%         rectHyps(rid).valid = false(num,1);
    end
    all_objects = repmat(struct('out_points_w',[],'name',[],'type',[],'points',[],'x_w',[]),0,1);
    scores = zeros(0,28);
    valid = false(0,1);
    obj_xyz = zeros(0,6);
    bottomscore = zeros(0,1);
    for rid = 1:14
        num = length(rectHyps(rid).objects);
        all_objects(end+1:end+num,:) = rectHyps(rid).objects;
        scores(end+1:end+num,:) = rectHyps(rid).scores ;
        valid(end+1:end+num,1) = rectHyps(rid).valid;
        bottomscore(end+1:end+num,1) = rectHyps(rid).bottomscore;
        xyz = zeros(num,6);
        for i = 1:num
            xyz(i,:) = [min(rectHyps(rid).objects(i).out_points_w, [], 1) ...
                max(rectHyps(rid).objects(i).out_points_w, [], 1)];
        end
        obj_xyz(end+1:end+num,:) = xyz;
    end

    scores(~valid,:) = 0;
    all_hyps.objects = addBoundingBox(all_objects(valid),'both'); %all_objects(valid);
    all_hyps.scores = scores(valid,:);
    all_hyps.valid = valid(valid);
    all_hyps.obj_xyz = obj_xyz(valid,:);
    all_hyps.bottomscore = bottomscore(valid);
    fprintf('%d:%d, %d-->%d\n', aid, hid, length(valid), sum(valid));

    %% prune weak cuboid hypothesis
%     t = 0;
%     sel_hyps = [];
%     for oid = 1:28
%         valid = bottomscore>0 & scores(:,oid)>t;
%         sel_hyps(oid).h_objects = all_hyps.objects(valid);
%         sel_hyps(oid).h_scores = all_hyps.scores(valid,:);
%         sel_hyps(oid).h_obj_xyz = all_hyps.obj_xyz(valid,:);
%         sel_hyps(oid).h_bottomscore = all_hyps.bottomscore(valid,:);
%         sel_hyps(oid).h_objID = find(valid);
%     end
% %     t = 0.60;
% %     sel_hyps = [];
% %     for oid = 1:28
% %         [S,I] = sort(all_hyps.scores(:,oid),'descend');
% %         obj_xyz = all_hyps.obj_xyz(I(S>t),:);
% %         [ outxyz, valid ] = nms3D( obj_xyz, 0.5 );
% %         sel_hyps(oid).objects = all_hyps.objects(I(valid));
% %         sel_hyps(oid).scores = all_hyps.scores(I(valid),:);
% %         sel_hyps(oid).obj_xyz = all_hyps.obj_xyz(I(valid),:);
% %         sel_hyps(oid).bottomscore = all_hyps.bottomscore(I(valid),:);
% %         sel_hyps(oid).objID = I(valid);
% %
% %         v = sel_hyps(oid).bottomscore>0;
% %
% %         sel_hyps(oid).h_objects = sel_hyps(oid).objects(v);
% %         sel_hyps(oid).h_objID = sel_hyps(oid).objID(v);
% %         sel_hyps(oid).h_scores = sel_hyps(oid).scores(v,:);
% %         sel_hyps(oid).h_obj_xyz = sel_hyps(oid).obj_xyz(v,:);
% %         sel_hyps(oid).h_bottomscore = sel_hyps(oid).bottomscore(v,:);
% %     end
%
%     % pack gnd
%     [ALL_HYPS(hid,:), CAN_POOL{hid}.sel_hyps, CAN_POOL{hid}.room] = getInitialWholeLayoutB( sel_hyps, room_obj, numsample );
    CAN_POOL{hid}.sel_hyps = all_hyps;
    CAN_POOL{hid}.room = room_obj;
end

% ALL_HYPS = ALL_HYPS(:);

% %% output candidate pool
% for tid = 1:12
%
% end

end


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

% Last Modified by GUIDE v2.5 16-Jan-2009 09:06:46

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

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

% Update handles structure
guidata(hObject, handles);

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

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

% Get default command line output from handles structure
varargout{1} = handles.output;

% --- Executes on selection change in popupmenu1.
function varargout = popupmenu1_Callback(hObject, eventdata, handles, varargin)
% hObject    handle to popupmenu1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns popupmenu1 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupmenu1

gdt = get(handles.popupmenu1,'value')

switch gdt
    case 1
         y=audiorecorder(8000,8,2);
         set(handles.text3,'string','SampleRate=8000, SampleSize=8, Stereo')
         handles.data=y;
    guidata(handles.popupmenu1,handles)
    case 2
        y=audiorecorder(8000,16,2);
        set(handles.text3,'string','SampleRate=8000, SampleSize=16, Stereo')
        handles.data=y;
    guidata(handles.popupmenu1,handles)
    case 3
        y=audiorecorder(11025,8,2);
        set(handles.text3,'string','SampleRate=11025, SampleSize=8, Stereo')
        handles.data=y;
    guidata(handles.popupmenu1,handles)
    case 4
        y=audiorecorder(11025,16,2);
        set(handles.text3,'string','SampleRate=11025, SampleSize=16, Stereo')
        handles.data=y;
    guidata(handles.popupmenu1,handles)
    case 5
        y=audiorecorder(22050,8,2);
        set(handles.text3,'string','SampleRate=22050, SampleSize=8, Stereo')
        handles.data=y;
    guidata(handles.popupmenu1,handles)
    case 6
        y=audiorecorder(22050,16,2);
        set(handles.text3,'string','SampleRate=22050, SampleSize=16, Stereo')
        handles.data=y;
    guidata(handles.popupmenu1,handles)
    case 7
        y=audiorecorder(44100,8,2);
        set(handles.text3,'string','SampleRate=44100, SampleSize=8, Stereo')
        handles.data=y;
    guidata(handles.popupmenu1,handles)
    case 8
        y=audiorecorder(44100,16,2);
        set(handles.text3,'string','SampleRate=44100, SampleSize=16, Stereo')
        handles.data=y;
    guidata(handles.popupmenu1,handles)
end

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

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

% --- Executes on button press in togglebutton1.
function varargout = togglebutton1_Callback(h, eventdata, handles, varargin)
% hObject    handle to togglebutton1 (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 togglebutton1

if (get(handles.togglebutton1,'value')) == get(handles.togglebutton1,'Max')

     y=audiorecorder(8000,16,2);
% y=handles.data;
% y.samplerate=za
% set(handles.text3,'string',za)
    record(y);
    set(handles.text3,'string','Now Recording...PLease speak into mic')
     handles.data=y;
     guidata(handles.togglebutton1,handles)
elseif (get(handles.togglebutton1,'value')) == get(handles.togglebutton1,'Min')
    y=handles.data;
    stop(y);
    set(handles.text3,'string','Recording Stopped')
    pd=getaudiodata(y,'int16');
%      t=0:0.001;100;
    plot(pd,'k')
    grid on;
%     axis([0 10])
    xlabel('Time (Second)');
    ylabel('Gain (Decibel)');
end

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

% % % y=handles.data;
% % % if (get(handles.togglebutton1,'value')) == get(handles.togglebutton1,'Max') && (get(handles.togglebutton2,'value')) == get(handles.togglebutton2,'Min')
% % %     set(handles.text3,'string','Cannot Play, Recording is in progress...')
% % % elseif (get(handles.togglebutton1,'value')) == get(handles.togglebutton1,'Max') && (get(handles.togglebutton2,'value')) == get(handles.togglebutton2,'Max')
% % %     play(y);
% % %     set(handles.text3,'string','Now Playing...')
% % % elseif (get(handles.togglebutton1,'value')) == get(handles.togglebutton1,'Min')
% % %     play(y);
% % %     set(handles.text3,'string','Now Playing...')
% % % end

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

sure

% --- Executes on button press in togglebutton2.
function varargout = togglebutton2_Callback(h, eventdata, handles, varargin)
% hObject    handle to togglebutton2 (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 togglebutton2

if (get(handles.togglebutton2,'value')) == get(handles.togglebutton2,'Max')
    y=handles.data;
    pause(y);
    set(handles.text3,'string','Recording Paused')
elseif (get(handles.togglebutton2,'value')) == get(handles.togglebutton2,'Min')
    y=handles.data;
    resume(y);
    set(handles.text3,'string','Recording Resumed')
end

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

% % % sure3

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

[F] = uigetfile('*.fig','Select any .fig file');
open(F);

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

close('VAudio');
close('sure');

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

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

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

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

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

y=audiorecorder(8000,16,2);
% y=handles.data;
% y.samplerate=za
% set(handles.text3,'string',za)
record(y);
set(handles.text3,'string','Now Recording...PLease speak into mic')
handles.data=y;
guidata(handles.togglebutton1,handles)

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

y=handles.data;
stop(y);
set(handles.text3,'string','Recording Stopped')
pd=getaudiodata(y,'int16');
%      t=0:0.001;100;
plot(pd,'k')
grid on;
%     axis([0 10])
xlabel('Time (Second)');
ylabel('Gain (Decibel)');

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

y=handles.data;
pause(y);
set(handles.text3,'string','Recording Paused')

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

y=handles.data;
resume(y);
set(handles.text3,'string','Recording Resumed')

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

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

open heelp.txt

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

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

sure


function cummomentplot(obj,tabgrouptag)
    %CUMMOMENTPLOT plot the Cumulative Moment into the specified tab group

    Tags.xs = 'CumMom xs contextmenu';
    Tags.bg = 'CumMom bg contextmenu';
    Tags.line = 'CumMom line contextmenu';
    Tags.ax = 'CumMom axes';

    myTab = findOrCreateTab(obj.fig, obj.fig, tabgrouptag, 'Moment');
    ax=findobj(myTab.Children,'flat','Tag',Tags.ax);
    if isempty(ax)
        ax              = axes(myTab);
        ax.TickDir      = 'out';
        ax.YMinorTick   = 'on';
        ax.Box          = 'on';
        ax.Tag          = Tags.ax;
        ax.UserData     = CumMomentAnalysisWindow(ax);
        grid(ax, 'on');
    end
    analy_win = ax.UserData;

    %% plot the main series
    lineProps.Color         = [0 0 0];
    lineProps.LineWidth     = 2.5;
    lineProps.UIContextMenu = line_plot_context_menu();
    lineProps.MinBigMag     = ZmapGlobal.Data.CatalogOpts.BigEvents.MinMag;
    lineProps.DisplayName   = obj.catalog.Name;

    analy_win.add_series(obj.catalog, 'catalog', lineProps);

    %% plot & synchronize cross sections

    plotted_xs = get(ax.Children,'Tag');
    plotted_xs = plotted_xs(startsWith(plotted_xs, 'Xsection'));

    if ~isempty(plotted_xs)
     existing_xs = obj.XSectionTitles;
        % delete cross sections that shouldn't exist
        todel = plotted_xs(~ismember(plotted_xs,existing_xs));
        analy_win.remove_series(todel);
    end
    %% if necessary, add context menu to figure
    cxs = findobj(obj.fig,'Tag',Tags.xs);
    if isempty(cxs)
        cxs = uicontextmenu(obj.fig,'tag',Tags.xs);
        uimenu(cxs,'Label','Open in new window', 'MenuSelectedFcn', @cb_xstimeplot);
    end

    obj.plot_xsections(@xsplotter, 'Xsection cummomplot');

    ax.YLabel.UIContextMenu = obj.sharedContextMenus.LogLinearYScale;

    %% add context menu to the axes
    cbg=findobj(obj.fig,'Tag',Tags.bg);

    if isempty(cbg)
        cbg=uicontextmenu(obj.fig,'Tag',Tags.bg);
        addLegendToggleContextMenuItem(cbg,'bottom','above');
        uimenu(cbg,'Label','Open in new window','Enable','off','MenuSelectedFcn',@obj.cb_timeplot);
    end

    if isempty(ax.UIContextMenu)
        ax.UIContextMenu=cbg;
    end

    function cln = line_plot_context_menu()
        % set up the context menu for these line plots
        cln=findobj(obj.fig,'Tag',Tags.line);
        if isempty(cln)
            cln=uicontextmenu(obj.fig,'tag',Tags.line);
            uimenu(cln, 'Label', 'start here',              'MenuSelectedFcn', @(~,~)obj.cb_starthere(ax));
            uimenu(cln, 'Label', 'end here',                'MenuSelectedFcn', @(~,~)obj.cb_endhere(ax));
            uimenu(cln, 'Label', 'trim to largest event',   'MenuSelectedFcn', @obj.cb_trim_to_largest);
            uimenu(cln, 'Label', 'Open in new window',      'MenuSelectedFcn', @obj.cb_timeplot);
        end
    end

    function h = xsplotter(xs, xscat)
        xsProps.LineWidth   = 1.5;
        xsProps.DisplayName = xs.Name;
        xsProps.Color       = xs.Color;
        mytag               = ['Xsection cummomplot ' xs.Name];
        h = analy_win.add_series(xscat, mytag, xsProps);

    end

    function cb_xstimeplot(~,~)
        myName = get(gco,'DisplayName');
        idx=strcmp(obj.XSectionTitles,myName);
        ZG=ZmapGlobal.Data;
        ZG.newt2=obj.catalog.subset(obj.CrossSections(idx).inside(obj.catalog));
        ZG.newt2.Name=sprintf('Events within %g km of %s',myName);
        ctp=CumTimePlot(ZG.newt2);
        ctp.plot();
    end
end