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

% This file is part of the Matlab Toolbox for Dimensionality Reduction v0.7.2b.
% The toolbox can be obtained from http://homepage.tudelft.nl/19j49
% You are free to use, change, or redistribute this code in any way you
% want for non-commercial purposes. However, it is appreciated if you
% maintain the name of the original author.
%
% (C) Laurens van der Maaten, 2010
% University California, San Diego / Delft University of Technology

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

% Last Modified by GUIDE v2.5 30-Jul-2008 11:02:27

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

% Choose default command line output for not_calculated
handles.output = 'Yes';

% Update handles structure
guidata(hObject, handles);

% Insert custom Title and Text if specified by the user
% Hint: when choosing keywords, be sure they are not easily confused
% with existing figure properties.  See the output of set(figure) for
% a list of figure properties.
if(nargin > 3)
    for index = 1:2:(nargin-3),
        if nargin-3==index, break, end
        switch lower(varargin{index})
         case 'title'
          set(hObject, 'Name', varargin{index+1});
         case 'string'
          set(handles.text1, 'String', varargin{index+1});
        end
    end
end

% Determine the position of the dialog - centered on the callback figure
% if available, else, centered on the screen
FigPos=get(0,'DefaultFigurePosition');
OldUnits = get(hObject, 'Units');
set(hObject, 'Units', 'pixels');
OldPos = get(hObject,'Position');
FigWidth = OldPos(3);
FigHeight = OldPos(4);
if isempty(gcbf)
    ScreenUnits=get(0,'Units');
    set(0,'Units','pixels');
    ScreenSize=get(0,'ScreenSize');
    set(0,'Units',ScreenUnits);

    FigPos(1)=1/2*(ScreenSize(3)-FigWidth);
    FigPos(2)=2/3*(ScreenSize(4)-FigHeight);
else
    GCBFOldUnits = get(gcbf,'Units');
    set(gcbf,'Units','pixels');
    GCBFPos = get(gcbf,'Position');
    set(gcbf,'Units',GCBFOldUnits);
    FigPos(1:2) = [(GCBFPos(1) + GCBFPos(3) / 2) - FigWidth / 2, ...
                   (GCBFPos(2) + GCBFPos(4) / 2) - FigHeight / 2];
end
FigPos(3:4)=[FigWidth FigHeight];
set(hObject, 'Position', FigPos);
set(hObject, 'Units', OldUnits);

% Show a question icon from dialogicons.mat - variables questIconData
% and questIconMap
load dialogicons.mat

IconData=questIconData;
questIconMap(256,:) = get(handles.figure1, 'Color');
IconCMap=questIconMap;

Img=image(IconData, 'Parent', handles.axes1);
set(handles.figure1, 'Colormap', IconCMap);

set(handles.axes1, ...
    'Visible', 'off', ...
    'YDir'   , 'reverse'       , ...
    'XLim'   , get(Img,'XData'), ...
    'YLim'   , get(Img,'YData')  ...
    );

% Make the GUI modal
set(handles.figure1,'WindowStyle','modal')

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

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

% The figure can be deleted now
delete(handles.figure1);

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

handles.output = get(hObject,'String');

% Update handles structure
guidata(hObject, handles);

% Use UIRESUME instead of delete because the OutputFcn needs
% to get the updated handles structure.
uiresume(handles.figure1);

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

handles.output = get(hObject,'String');

% Update handles structure
guidata(hObject, handles);

% Use UIRESUME instead of delete because the OutputFcn needs
% to get the updated handles structure.
uiresume(handles.figure1);

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

if isequal(get(handles.figure1, 'waitstatus'), 'waiting')
    % The GUI is still in UIWAIT, us UIRESUME
    uiresume(handles.figure1);
else
    % The GUI is no longer waiting, just close it
    delete(handles.figure1);
end

% --- Executes on key press over figure1 with no controls selected.
function figure1_KeyPressFcn(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)

% Check for "enter" or "escape"
if isequal(get(hObject,'CurrentKey'),'escape')
    % User said no by hitting escape
    handles.output = 'No';

    % Update handles structure
    guidata(hObject, handles);

    uiresume(handles.figure1);
end

if isequal(get(hObject,'CurrentKey'),'return')
    uiresume(handles.figure1);
end


function [ objectsCV, files ] = loadCV( file )

    %% Load files
    files = dir([file '/Cross*.mat' ]);

%     nFiles = length(files);
%     count_imgs = 0;
%     for i = 1:nFiles
%         disp(['Reading file ' files(i).name]);
%         load([file '/' files(i).name]); % objectsCV
%         nImgs = length(objectsCV);
%         for j = 1:nImgs
%             objectsCV_aux(count_imgs+1) = objectsCV(j);
%             count_imgs = count_imgs+1;
%         end
%     end
%
%     objectsCV = objectsCV_aux;

    if(length(files) > 1)
        load([file '/' files(1).name]); % objectsCV
    else
        error('No CV files found.');
    end

end


a=VideoReader("train_vid.mp4");
for img=1:a.NumberOfFrames;
    filename=strcat('frame',num2str(img),'.jpg');
       b = read(a, img);
    imwrite(b,filename);
end


%% Example of using KST class for interfacing with KUKA iiwa robots

% Collaborative pick and place application, the robot detects collision
% with its surrounding while performing the pick and place application,
% when a collision is detected, the robots stops its motion, when the
% operator gives the robot a double touch on the end-effector in the Z
% direcdtion, the robot returns back to doing its operation.

% First start the server on the KUKA iiwa controller
% Then run this script using Matlab

% This example works with Sunrise application version KST_1.7  and higher.
% Copyright Mohammad SAFEEA, 26th-June-2018

close all;clear;clc;
warning('off')
%% Create the robot object
ip='172.31.1.147'; % The IP of the controller
arg1=KST.LBR7R800; % choose the robot iiwa7R800 or iiwa14R820
arg2=KST.Medien_Flansch_elektrisch; % choose the type of flange
Tef_flange=eye(4); % transofrm matrix of EEF with respect to flange
iiwa=KST(ip,arg1,arg2,Tef_flange); % create the object

%% Start a connection with the server
flag=iiwa.net_establishConnection();
if flag==0
    return;
end
pause(1);
disp('An example on using the interruptible PTP motion functions for Human robot collaboration')

%% Move PTP in joint space to some inital position
jPos={0,0,0,-pi/2,0,pi/2,0};
relVel=0.15;
iiwa.movePTPJointSpace(jPos, relVel); % move to initial configuration
%% Move PTP in joint space with torque limits
[ Pos ] = iiwa.getEEFPos();
deltaY=250;
deltaZ=332-150;

joints_indices=[1,2,3,4,5,6,7]; % joint index start from one
max_torque=ones(7,1)*8;
max_torque(1)=3;
min_torque=-max_torque;
VEL=175;
w=17; % weight of tool newton
%% Go down near the table
Pos{3}=Pos{3}-150;
iiwa.moveWaitForDTWhenInterrupted(  ...
     Pos, VEL,joints_indices,max_torque,min_torque,w);
%% Open gripper
iiwa.setPin1Off();
pause(1);
iiwa.setPin11On();
pause(1);
%% Motion twards the box
Pos{2}=Pos{2}-deltaY;
iiwa.moveWaitForDTWhenInterrupted( ...
     Pos, VEL,joints_indices,max_torque,min_torque,w);

Pos{3}=Pos{3}-deltaZ;
iiwa.moveWaitForDTWhenInterrupted(  ...
     Pos, VEL,joints_indices,max_torque,min_torque,w);
%% Close gripper
iiwa.setPin1On();
pause(1);
iiwa.setPin11Off();
pause(1);
%% Picking the box twards the goal
Pos{3}=Pos{3}+deltaZ;
iiwa.moveWaitForDTWhenInterrupted(  ...
     Pos, VEL,joints_indices,max_torque,min_torque,w);

Pos{2}=Pos{2}+2*deltaY;
iiwa.moveWaitForDTWhenInterrupted(  ...
     Pos, VEL,joints_indices,max_torque,min_torque,w);

Pos{3}=Pos{3}-deltaZ;
iiwa.moveWaitForDTWhenInterrupted(  ...
     Pos, VEL,joints_indices,max_torque,min_torque,w);
%% Release the box
% Open gripper
iiwa.setPin1Off();
pause(1);
iiwa.setPin11On();
pause(1);

Pos{3}=Pos{3}+deltaZ;
iiwa.moveWaitForDTWhenInterrupted(  ...
     Pos, VEL,joints_indices,max_torque,min_torque,w);

%% Turn off the server
iiwa.net_turnOffServer();


function updatelarvacontour(hfly,hfly_extra,pos)

if isempty(pos.xcontour),
  set(hfly,'XData',[],'YData',[]);
else
  set(hfly,'XData',[pos.xcontour(:);pos.xcontour(1)],'YData',[pos.ycontour(:);pos.ycontour(1)]);
end
if all(isfield(pos,{'xspine','yspine'})),
  set(hfly_extra(1),'XData',pos.xspine,'YData',pos.yspine);
  set(hfly_extra(2),'XData',pos.xspine(1),'YData',pos.yspine(1));
end


function sF = volume(sF1,center,radius)

sF = sF1;

sF.values = sF1.values;

sF = volume(sF.values, center, radius);

end


% run all example sequences
%
% Stefan Kroboth <stefan.kroboth@uniklinik-freiburg.de>

% avoid cwd madness
od = cd(fileparts(which(mfilename)));
addpath(genpath('../matlab'));

% list of sequences to execute
fid
gre
epi_rs

% just in case the change of the cwd persists in the parent shell
cd(od);


function varargout=writehtk(varargin)
%
% For calling details please see v_writehtk.m
%
% This dummy routine is included for backward compatibility only
% and will be removed in a future release of voicebox. Please use
% v_writehtk.m in future and/or update with v_voicebox_update.m
%
%      Copyright (C) Mike Brookes 2018
%      Version: $Id: writehtk.m 10863 2018-09-21 15:39:23Z dmb $
%
if nargout
    varargout=cell(1,nargout);
    [varargout{:}]=v_writehtk(varargin{:});
else
    v_writehtk(varargin{:});
end


function test_failed=test_demos
%TEST_DEMOS  Test if all the demos runs without errors.

  test_failed=0;

  s=dir([ltfatbasepath,filesep,'demos',filesep,'demo_*.m']);

  for ii=1:numel(s)
     filename = s(ii).name;

     disp(filename);

     % The demo is run in separate function to avoid
     % variable name clash
     rundemo(filename(1:end-2));

  end

function rundemo(demoname)
   close all;
   eval(demoname);
   clear all;


function format_string = guess_tiff_sensor(tiff_filename)
% GUESS_TIFF_SENSOR Given a TIFF this function tries to look for other
% sensor-specific files in relative paths to the main tiff file that may
% provide more metadata.
%
% Assumes a set of test functions (all of the format istiff*.m) are in the
% same directory.  If format is unrecognized, an empty string is returned.
%
% Written by: Wade Schwartzkopf, NGA/IDT
%
% //////////////////////////////////////////
% /// CLASSIFICATION: UNCLASSIFIED       ///
% //////////////////////////////////////////

fullname=which(mfilename('fullpath'));
path=fileparts(fullname);
filelist=dir([path filesep 'istiff*.m']);

format_string=[];
for i=1:length(filelist)
    str_ind=strfind(filelist(i).name,'.m');
    if ~isempty(str_ind)&&(str_ind(end)>1)
        test_format=filelist(i).name(1:(str_ind(end)-1)); % Strip off .m extension
        if(feval(test_format, tiff_filename))
            format_string=test_format(7:end);
            return
        end
    end
end

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


function n = numberFrames(view,scan)
%
%    n = numberFrames(view,scan)
%
% Returns the number of frames of a selected scan
%
% gb 03/30/2005
if ieNotDefined('scan')
    scan = viewGet(view,'curScan');
end

global dataTYPES;
n = dataTYPES(view.curDataType).scanParams(scan).nFrames;

return


function plot_updatePlot(hFig, idxPC)

% PC in UserData of figure -> PC -----------------------------------------------

PC = hFig.UserData.PC{idxPC};

% Delete points and normals of previous plot -----------------------------------

% Delete points
if ~iscell(PC.U.hPlot)
    delete(PC.U.hPlot);
else
    for j = 1:numel(PC.U.hPlot)
        delete(PC.U.hPlot{j});
    end
end

% Delete normals
delete(PC.U.hPlotNormals);

% Consider parameter 'MaxPoints' -----------------------------------------------

if sum(PC.act) > PC.U.p.MaxPoints
    PC.U.percentOfVisiblePoints = PC.U.p.MaxPoints/sum(PC.act)*100;
    idxAct = find(PC.act); % indices of active points
    idxRandom = randperm(numel(idxAct), PC.U.p.MaxPoints); % indices of randomly selected points
    act4plot = false(PC.noPoints,1);
    act4plot(idxAct(idxRandom)) = true; % reactivate randomly selected points
else
    PC.U.percentOfVisiblePoints = 100;
    act4plot = PC.act;
end

% Plot -------------------------------------------------------------------------

if PC.U.Visible && sum(act4plot) > 0

    % Axes handle
    hAxes = findobj('Parent', hFig, 'Type', 'Axes');

    % Colorize points according to an attribute
    if numel(PC.U.p.Color) > 1 && strcmp(PC.U.p.Color(1:2), 'A.') && ~strcmpi(PC.U.p.Color, 'A.RGB') % if p.Color begins with 'A.'

        % Values of attribute to plot
        attribute2plot = PC.U.p.Color(3:end); % attribute name
        if strcmpi(attribute2plot, 'x') % attribute = x coordinate
            A = PC.X(act4plot,1);
        elseif strcmpi(attribute2plot, 'y') % attribute = y coordinate
            A = PC.X(act4plot,2);
        elseif strcmpi(attribute2plot, 'z') % attribute = z coordinate
            A = PC.X(act4plot,3);
        else
            A = PC.A.(attribute2plot)(act4plot);
        end

        % Plot!
        PC.U.hPlot = scatter3(hAxes, PC.X(act4plot,1), PC.X(act4plot,2), PC.X(act4plot,3), PC.U.p.MarkerSize^2, A, '.');

        % Colormap
        colormap(PC.U.p.ColormapName);

        % CAxisLim
        if strcmpi(PC.U.p.ColormapName, 'classpal') % for visualization of classes with maximum distiguishable colors

            caxis([-0.5 50.5]); % for no. of classes = 50, see classpal.m

        else % usual case

            if isempty(PC.U.p.CAxisLim)
                CAxisLim = [min(A) max(A)];
            else
                CAxisLim = PC.U.p.CAxisLim;
            end
            caxis(CAxisLim);

        end

        % % Colorbar
        % hColorbar = findobj('Type', 'Colorbar', 'Parent', gcf);
        % if ~isempty(hColorbar) % applies if min and max of CAxisLim is equal (e.g. if attribute contains only a single value)
        %     PC.U.p.CAxisLim = [hColorbar.Limits(1) hColorbar.Limits(2)];
        %     hColorbar.Label.String = PC.label;
        %     hColorbar.Label.Interpreter = 'none';
        % end

    % RGB plot
    elseif strcmpi(PC.U.p.Color, 'A.RGB')

        colorbar off;

        % Check how colors are saved
        if isfield(PC.A, 'r') && isfield(PC.A, 'g') && isfield(PC.A, 'b')
            r = PC.A.r;
            g = PC.A.g;
            b = PC.A.b;
        elseif isfield(PC.A, 'red') && isfield(PC.A, 'green') && isfield(PC.A, 'blue')
            r = PC.A.red;
            g = PC.A.green;
            b = PC.A.blue;
        elseif isfield(PC.A, 'Red') && isfield(PC.A, 'Green') && isfield(PC.A, 'Blue')
            r = PC.A.Red;
            g = PC.A.Green;
            b = PC.A.Blue;
        elseif isfield(PC.A, 'diffuse_red') && isfield(PC.A, 'diffuse_green') && isfield(PC.A, 'diffuse_blue')
            r = PC.A.diffuse_red;
            g = PC.A.diffuse_green;
            b = PC.A.diffuse_blue;
        end

        % Check if colors were found
        if ~exist('r', 'var') | ~exist('g', 'var') | ~exist('b', 'var')
            errordlg('No RGB attributes found!');
            return;
        end

        % Conversion of colors
        if max(r) <= 1
            % do nothing
        elseif max(r) > 1 && max(r) <= 2^8-1
            r = r/(2^8-1); g = g/(2^8-1); b = b/(2^8-1);
        elseif max(r) > 255 && max(r) <= 2^16-1
            r = r/(2^16-1); g = g/(2^16-1); b = b/(2^16-1);
        end

        % Plot!
        PC.U.hPlot = scatter3(hAxes, PC.X(act4plot,1), PC.X(act4plot,2), PC.X(act4plot,3), PC.U.p.MarkerSize^2, [r(act4plot) g(act4plot) b(act4plot)], '.');

    % Unicolor plot
    else

        colorbar off;

        % Plot!
        if strcmpi(PC.U.p.Color, 'by PC')
            nColor = size(hFig.UserData.colors,1);
            idxColor = mod(idxPC,nColor); if idxColor == 0, idxColor = nColor; end % get color index
            PC.U.p.Color = hFig.UserData.colors{idxColor,1};
        end

        PC.U.hPlot = plot3(hAxes, PC.X(act4plot,1), PC.X(act4plot,2), PC.X(act4plot,3), '.', 'MarkerSize', PC.U.p.MarkerSize, 'Color', PC.U.p.Color);

    end

    % Plot normals
    if hFig.UserData.PC{idxPC}.U.plotNormals
        PC.U.hPlotNormals = PC.plotNormals('Scale', hFig.UserData.options.NormalsScale, 'Color', hFig.UserData.options.NormalsColor, 'Axes', hAxes); % plot normals!
    end

end

% PC -> UserData of figure -----------------------------------------------------

hFig.UserData.PC{idxPC} = PC;

% Update menus -----------------------------------------------------------------

plot_updateMenus(hFig)

% Update histogram -------------------------------------------------------------

plot_updateHisto(hFig)

end


function GUI = sessionGUI_removeStudy(study, forceRemove);
% Remove a study from the mrVista GUI.
%
% <GUI> = sessionGUI_removeStudy(<study=current>, <forceRemove=0>);
%
% This function will update or create the saved studies file
% (saved in the mrVista 2 repository: mrVista2/study/studies.mat).
%
% If the forceRemove flag is set to 1, will remove without prompting.
% Otherwise, asks the user to confirm first.
%
% ras, 07/06.
mrGlobals2;

if notDefined('study'),    study = GUI.settings.study;      end
if notDefined('forceRemove'), forceRemove = 0;              end

% N will index the index for this study
if isnumeric(study)
    N = study;
    study = GUI.studies(N).name;

elseif ischar(study)
    N = cellfind({GUI.studies.name}, study);

else
    error('Invalid study specification.')

end

% can't remove the first study (recent sessions); check that we're not
% trying:
if N==1
    myWarnDlg('Sorry, you can not remove the Recent Sessions study.');
    return
end

% Ask the user if he/she is sure, if not forcing the removal:
if ~forceRemove
    q = sprintf('Permanently delete study %s? ', study);
    resp = questdlg(q, mfilename);
    if ~isequal(resp, 'Yes'), return; end
end

% remove the study
ok = setdiff(1:length(GUI.studies), N);
GUI.studies = GUI.studies(ok);

% save the updated studies file
studyPath = studySave(GUI.studies);
fprintf('Studies file %s updated.\n', studyPath);

% select the previous study in the study list
GUI = sessionGUI_selectStudy(N-1);

return


function Z = uplus(Y)
%UPLUS (overloaded)

if isa(Y,'blkvar')
    Y = sdpvar(Y);
end

switch Y.typeflag
case {0,5}
	Z = Y;
case {1,3,4}
	error('Relational objects canot be manipulated')
otherwise
	error('Please report internal bug in sdpvar/uplus')
end


%error('Tracker not configured! Please edit the tracker_MFT.m file.'); % Remove this line after proper configuration

% The human readable label for the tracker, used to identify the tracker in reports
% If not set, it will be set to the same value as the identifier.
% It does not have to be unique, but it is best that it is.
tracker_label = ['MFT'];
tracker_repo_path = 'your MFT path'
% For MATLAB implementations we have created a handy function that generates the appropritate
% command that will run the matlab executable and execute the given script that includes your
% tracker implementation.
%
% Please customize the line below by substituting the first argument with the name of the
% script (not the .m file but just the name of the script as you would use it in within Matlab)
% of your tracker and also provide the path (or multiple paths) where the tracker sources
% are found as the elements of the cell array (second argument).
tracker_command = generate_matlab_command('MFT()', {[tracker_repo_path, 'vot2018_main']});

tracker_interpreter = 'matlab';

% tracker_linkpath = {}; % A cell array of custom library directories used by the tracker executable (optional)


function [status] = execute_hash_stage(status, ipp)
    % test stage: check recorded hash checksum
    calculated = '';
    expected = '';
    try
        expected = getReferenceHash(status, ipp);
        calculated = calculateMD5Hash(status.tikzStage.texFile);

        % do the actual check
        if ~strcmpi(expected, calculated)
            % throw an error to signal the testing framework
            error('testMatlab2tikz:HashMismatch', ...
                'The hash "%s" does not match the reference hash "%s"', ...
                calculated, expected);
        end
    catch %#ok
        e = lasterror('reset'); %#ok
        [status.hashStage] = errorHandler(e);
    end
    status.hashStage.expected = expected;
    status.hashStage.found    = calculated;
end
% ==============================================================================
function hash = getReferenceHash(status, ipp)
    % retrieves a reference hash from a hash table
    % WARNING: do not make `hashTable` persistent, since this is slower

    hashTable = loadHashTable(ipp.Results.testsuite);
    if isfield(hashTable.contents, status.function)
        hash = hashTable.contents.(status.function);
    else
        hash = '';
    end
end


function [movieInfo] = getMovieInfo(inputMovie,varargin)
	% Wrapper to quickly get movie information. Options are the same as loadMovieList.
	% Biafra Ahanonu
	% started: 2020.09.29 [13:23:57]
	% inputs
		% inputMovie - [x y frames] or char string (path to movie).
	% outputs
		%

	% changelog
		% 2021.08.08 [19:30:20] - Updated to handle CIAtah v4.0 switch to all functions inside ciapkg package.
        % 2022.01.20 [22:50:25] - Directly call loadMovieList and bypass ciapkg.api.
	% TODO
		%

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

	% ========================
	% DESCRIPTION
	% OPTIONS ARE THE SAME AS loadMovieList.
	% options.exampleOption = '';
	% get options
	% options = getOptions(options,varargin);
	% display(options)
	% unpack options into current workspace
	% fn=fieldnames(options);
	% for i=1:length(fn)
	% 	eval([fn{i} '=options.' fn{i} ';']);
	% end
	% ========================

	try
		movieInfo = [];
		movieInfo = ciapkg.io.loadMovieList(inputMovie,'getMovieDims',1,'passArgs',varargin);
	catch err
		disp(repmat('@',1,7))
		disp(getReport(err,'extended','hyperlinks','on'));
		disp(repmat('@',1,7))
	end
end


function  [pl2] = PL2GetFileIndex(filename)
% PL2GetFileIndex(filename): gets pl2 file index. File indexes are cached.
%        If cached file index for the specified filename exists, returns cached file index,
%       otherwise, calls PL2ReadFileIndex(filename)
%
% [pl2] = PL2GetFileIndex(filename)
%
% INPUT:
%   filename - pl2 file path. If empty string, will clear all cached file indexes.
%
% OUTPUT:
%   pl2 - pl2 file index object (described in detail in PL2ReadFileIndex.m)
%       keeps pl2 file indexes cached in memory.
%       To clear indexes, use this command:
%       PL2GetFileIndex('')
%       or
%       clear PL2GetFileIndex
%

% this array of pl2 indexes is persisted between calls to this function
persistent PL2Indexes;

if nargin ~= 1
    error 'expected 1 input argument';
end

if isempty(filename)
    pl2 = 0;
    PL2Indexes={};
    return
end

if exist(filename,'file') ~= 2
    error('file does not exist');
end

if isempty(PL2Indexes)
    PL2Indexes={};
    PL2Indexes{1}.Index = PL2ReadFileIndex(filename);
    PL2Indexes{1}.Name = filename;
    pl2 = PL2Indexes{1}.Index;
    return;
else
    n = size(PL2Indexes,2);
    for i=1:n
        if strcmp(PL2Indexes{i}.Name, filename) == 1
            % we found Index with specified file Name
            if isfield(PL2Indexes{i}, 'Index')
                % if the index structure has pl2 index assigned, return it
                pl2 = PL2Indexes{i}.Index;
                return;
            else
                % read pl2 index from file, assign to persistent indexes and return
                PL2Indexes{i}.Index = PL2ReadFileIndex(filename);
                pl2 = PL2Indexes{i}.Index;
                return;
            end
        end
    end
    % we did not find persisted Index.
    % read the index from file
    PL2Indexes{n+1}.Index = PL2ReadFileIndex(filename);
    PL2Indexes{n+1}.Name = filename;
    pl2 = PL2Indexes{n+1}.Index;
end

end


% Create folder if it doesn't exist
%
function mkfolder(folder)
    if exist(folder, 'dir') == 0
        mkdir(folder);
        if exist(folder, 'dir') == 0
            error('Failed to create output directory. Check the argument or create the directory manually');
        end
    end
end


function title = p00_title ( problem )

%*****************************************************************************80
%
%% P00_TITLE returns the title for any problem.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    28 December 2011
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer PROBLEM, the index of the problem.
%
%    Output, string TITLE, the title of the problem.
%
  if ( problem == 1 )
    title = p01_title ( );
  elseif ( problem == 2 )
    title = p02_title ( );
  elseif ( problem == 3 )
    title = p03_title ( );
  elseif ( problem == 4 )
    title = p04_title ( );
  elseif ( problem == 5 )
    title = p05_title ( );
  elseif ( problem == 6 )
    title = p06_title ( );
  elseif ( problem == 7 )
    title = p07_title ( );
  elseif ( problem == 8 )
    title = p08_title ( );
  elseif ( problem == 9 )
    title = p09_title ( );
  elseif ( problem == 10 )
    title = p10_title ( );
  elseif ( problem == 11 )
    title = p11_title ( );
  elseif ( problem == 12 )
    title = p12_title ( );
  elseif ( problem == 13 )
    title = p13_title ( );
  elseif ( problem == 14 )
    title = p14_title ( );
  elseif ( problem == 15 )
    title = p15_title ( );
  elseif ( problem == 16 )
    title = p16_title ( );
  elseif ( problem == 17 )
    title = p17_title ( );
  elseif ( problem == 18 )
    title = p18_title ( );
  elseif ( problem == 19 )
    title = p19_title ( );
  elseif ( problem == 20 )
    title = p20_title ( );
  else
    fprintf ( 1, '\n' );
    fprintf ( 1, 'P00_TITLE - Fatal error!\n' );
    fprintf ( 1, '  Illegal problem number = %d\n', problem );
    error ( 'P00_TITLE - Fatal error!' );
  end

  return
end


function [filename] = FAIRwrite(T,m,filename)
[p,f,e] = fileparts(filename);
filename = fullfile(p,[f,'.jpg']);
fprintf('write data to %s\n',filename)
imwrite(fliplr(uint8(reshape(T,m)))',filename,'jpeg');
%eval(['!open ',filename])


function outC = anonymize(inC,sensitiveString,replacement)
%outC = anonymize(inC,sensitiveString,replacement)
%Replace all field values in the cell array inC (usually a CERR planC archive)
%which contains the strings in 'sensitiveString' with the replacement string 'replacement'.
%This anonymizer function is useful for removing protected health information from CERR archives.
%Note:  *No warranty is expressed or implied*.  Use at your own risk.
%Created Dec 02, JOD.
%Example of use:
%str = '12383_4dec02'
%
%planC = anonymize(planC,'studyNumberOfOrigin',str)
%Normally one should loop over all cells with potential protected health information.
%The following fields should always be viewed suspiciously:
%PHI = {'studyNumberOfOrigin','patientName','caseNumber','archive'}.
%Last modified:  20 May 03, JOD, corrected loss of CERROptions cell.
%
% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.
%
% This file is part of The Computational Environment for Radiotherapy Research (CERR).
%
% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.
%
% CERR has been financially supported by the US National Institutes of Health under multiple grants.
%
% CERR is distributed under the terms of the Lesser GNU Public License.
%
%     This version of CERR is free software: you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation, either version 3 of the License, or
%     (at your option) any later version.
%
% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
% See the GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with CERR.  If not, see <http://www.gnu.org/licenses/>.

%Loop over all the cells

for i = 1 : length(inC)

    if i ~= inC{end}.CERROptions
        if length(inC{i})~= 0
            entry = inC{i}(1);

            if ~isempty(entry)
                %Get all struct field names
                fields = subfieldnames(entry);
                %which have the string sensitiveString

                for j = 1 : length(fields)
                    name = fields{j};
                    indV = strfind(lower(name),lower(sensitiveString));
                    if ~isempty(indV)
                        if length(indV) ~= 1
                            error(['On field name:  ' name])
                        end
                        %anonymize!
                        disp(['Found Patient Name in ' num2str(name)])
                        %eval([ ['[' name ']'] '= deal(replacement);']);
                        for k = 1:2
                            [nameCell{k} name] = strtok(name,'.');
                        end
                        for k = 1 : length(inC{i})
                            if isempty(name(2:end))
                                eval(['inC{i}' '(',num2str(k),').' nameCell{2} '= deal(replacement);' ])
                            else
                                for l = 1 : length(eval([nameCell{1} '.' nameCell{2}]))
                                    eval(['inC{i}' '(',num2str(k),').' nameCell{2} '(',num2str(l),').' name(2:end) '= deal(replacement);' ])
                                end

                            end
                        end
                    end

                end
            end
        end
        outC{i} =inC{i};
    end
end
outC{inC{end}.CERROptions} = inC{inC{end}.CERROptions};  %Put in options


function idx = FindRoute(to)
% return the list of joint number connecting ROOT to 'to'
global uLINK

i = uLINK(to).mother;
%if i == 0
%    idx = [];    % search failed
%    fprintf('FindRoute: search failed\n');
%else
if i == 1
    idx = [to];
else
    idx = [FindRoute(i) to];
%     idx2 = FindRoute(i);
%     if isempty(idx2)
%         idx = [];
%     else
%         idx = [idx2 to];
%     end
end


function plot_createMenu(hFig, firstCall, idxPC)

% Menu for all point clouds ----------------------------------------------------

if firstCall

    hFig.MenuBar = 'none';

    % Create menu for all PCs
    hFig.UserData.hMenuAll = uimenu(hFig, 'Label', 'All PCs');
    hFig.UserData.hMenuAll.UserData.idxPC = idxPC; % save index of PC in UserData of menu
    fillmenu(hFig.UserData.hMenuAll, hFig);

    % Menu for adding a new PC
    hFig.UserData.hMenuAddPC = uimenu(hFig, 'Label', 'Add PC...', 'Callback', @plot_addPC);

else

    % Add only idxPC to menu for all PCs
    hFig.UserData.hMenuAll.UserData.idxPC = [hFig.UserData.hMenuAll.UserData.idxPC idxPC]; % save index of PC in UserData of menu

end

% Menu for actual point cloud --------------------------------------------------

hFig.UserData.PC{idxPC}.U.hMenu = uimenu(hFig, 'Label', hFig.UserData.PC{idxPC}.label);
hFig.UserData.PC{idxPC}.U.hMenu.UserData.idxPC = idxPC; % save index of PC in UserData of menu
hFig.UserData.PC{idxPC}.U.hMenu.Position = hFig.UserData.PC{idxPC}.U.hMenu.Position - 1; % move menu
pause(0.001) % without this line position of menu doesn't change (bug???)

fillmenu(hFig.UserData.PC{idxPC}.U.hMenu, hFig);

end

function fillmenu(parentMenu, hFig)

% Menu for all PCs?
if strcmp(parentMenu.Label, 'All PCs'), menu4allPCs = true; else menu4allPCs = false; end

% Visible ----------------------------------------------------------------------

if ~menu4allPCs, h = uimenu(parentMenu, 'Label', 'Visible', 'Checked', 'On', 'Callback', @plot_setVisible); end

% Color ------------------------------------------------------------------------

h = uimenu(parentMenu, 'Label', 'Color');
if ~menu4allPCs, h.Separator = 'On'; end

% Unicolor
hUnicolor = uimenu(h, 'Label', 'Unicolor');
for i = 1:size(hFig.UserData.colors,1)
    uimenu('Parent', hUnicolor, 'Label', hFig.UserData.colors{i,2}, 'Callback', @plot_setColor, 'ForegroundColor', hFig.UserData.colors{i,1});
end
uimenu('Parent', hUnicolor, 'Label', 'by PC' , 'Callback', @plot_setColor, 'Separator', 'On');
uimenu('Parent', hUnicolor, 'Label', 'custom', 'Callback', @plot_setColor);

% Attributes
hAttributes = uimenu(h, 'Label', 'Attribute');
uimenu('Parent', hAttributes, 'Label', 'x'  , 'Callback', @plot_setColor);
uimenu('Parent', hAttributes, 'Label', 'y'  , 'Callback', @plot_setColor);
uimenu('Parent', hAttributes, 'Label', 'z'  , 'Callback', @plot_setColor);
uimenu('Parent', hAttributes, 'Label', 'RGB', 'Callback', @plot_setColor);

if ~menu4allPCs

    % Add attribute to menu for actual PC
    if isstruct(hFig.UserData.PC{parentMenu.UserData.idxPC}.A)
        att = fields(hFig.UserData.PC{parentMenu.UserData.idxPC}.A);
        if ~isempty(att)
            for i = 1:numel(att)
                h = uimenu('Parent', hAttributes, 'Label', att{i}, 'Callback', @plot_setColor);
                if i == 1, h.Separator = 'On'; end
            end
        end
    end

    % Update attributes in menu for all PCs
    updateAttributesInMenu4allPCs(hFig)

else % if menu4allPCs is true

    hFig.UserData.hMenuAllAttributes = hAttributes; % save handle to attributes menu (for adding attributes later)

end

% MarkerSize -------------------------------------------------------------------

h = uimenu(parentMenu, 'Label', 'MarkerSize');
for i = 1:10
    uimenu(h, 'Label', num2str(i), 'Callback', @plot_setMarkerSize);
end
uimenu(h, 'Label', 'custom', 'Callback', @plot_setMarkerSize, 'Separator', 'On');

% MaxPoi -----------------------------------------------------------------------

h = uimenu(parentMenu, 'Label', 'MaxPoints', 'Callback', @plot_setMaxPoints);

% ColormapName -----------------------------------------------------------------

colormaps = {'parula' 'jet' 'jetinv' 'hsv' 'hot' 'cool' 'spring' 'summer' 'autumn' 'winter' 'gray' 'bone' 'copper' 'pink' 'lines' 'colorcube' 'prism' 'flag' 'difpal' 'classpal'}; % from 'doc colormap'
h = uimenu(parentMenu, 'Label', 'ColormapName');
for i = 1:numel(colormaps)
    uimenu('Parent', h, 'Label', colormaps{i}, 'Callback', @plot_setColormapName);
end
uimenu('Parent', h, 'Label', 'custom', 'Callback', @plot_setColormapName, 'Separator', 'On');

% CAxisLim ---------------------------------------------------------------------

h = uimenu(parentMenu, 'Label', 'CAxisLim', 'Callback', @plot_setCAxisLim);

% Select -----------------------------------------------------------------------

h = uimenu(parentMenu, 'Label', 'Select', 'Separator', 'on');

% Limits
hLimits = uimenu(h, 'Label', 'Limits');

           uimenu('Parent', hLimits, 'Label', 'Set'     , 'Callback', @plot_selectLimits);
hChoose  = uimenu('Parent', hLimits, 'Label', 'Choose'  , 'Callback', @plot_selectLimits);
           uimenu('Parent', hLimits, 'Label', 'Zoom out', 'Callback', @plot_selectLimits);
hShowAll = uimenu('Parent', hLimits, 'Label', 'Show all', 'Callback', @plot_selectLimits);
if menu4allPCs % shortcuts
    hChoose.Accelerator  = 's';
    hShowAll.Accelerator = 'a';
end

% Profile
hProfile = uimenu('Parent', h, 'Label', 'Profile', 'Callback', @plot_selectProfile);

% InPolygon
hInPolygon = uimenu('Parent', h, 'Label', 'InPolygon', 'Callback', @plot_selectInPolygon);

% Modify -----------------------------------------------------------------------

h = uimenu(parentMenu, 'Label', 'Modify');

% transform
hProfile = uimenu('Parent', h, 'Label', 'transform', 'Callback', @plot_transform);

% ecef2mapTrafo
hProfile = uimenu('Parent', h, 'Label', 'ecef2mapTrafo', 'Callback', @plot_ecef2mapTrafo);

% map2ecefTrafo
hProfile = uimenu('Parent', h, 'Label', 'map2ecefTrafo', 'Callback', @plot_map2ecefTrafo);

% Plot normals -----------------------------------------------------------------

if ~menu4allPCs

    if isstruct(hFig.UserData.PC{parentMenu.UserData.idxPC}.A)
        att = fields(hFig.UserData.PC{parentMenu.UserData.idxPC}.A);
        if ~isempty(att)
            if any(strcmpi(att, 'nx'))
                uimenu(parentMenu, 'Label', 'Plot normals', 'Separator', 'on', 'Callback', @plot_plotNormals);
            end
        end
    end

end

end

function updateAttributesInMenu4allPCs(hFig)
% Update attributes in menu for all PCs
% (not in plot_updateMenus, as plot_updateMenus is called on each plot and this is only necessary when a new PC is added)

for i = 1:numel(hFig.UserData.hMenuAllAttributes.Children) % delete all attributes (except x, y, z, RGB)
    if i == 1, idx2del = []; end
    if all(~strcmp(hFig.UserData.hMenuAllAttributes.Children(i).Label, {'x' 'y' 'z' 'RGB'}))
        idx2del = [idx2del; i];
    end
end
delete(hFig.UserData.hMenuAllAttributes.Children(idx2del));

for idxPC = 1:numel(hFig.UserData.PC) % find attributes common to all PCs
    if isstruct(hFig.UserData.PC{idxPC}.A)
        att{idxPC} = fields(hFig.UserData.PC{idxPC}.A);
    else
        att{idxPC} = {};
    end
    if idxPC == 1
        commonAtt = att{idxPC};
    else
        commonAtt = intersect(commonAtt, att{idxPC});
    end
end

for i = 1:numel(commonAtt) % add attributes common to all PCs
    if i == 1, separator = 'On'; else separator = 'Off'; end
    uimenu(hFig.UserData.hMenuAllAttributes, 'Label', commonAtt{i}, 'Callback', @plot_setColor, 'Separator', separator);
end

end


function [onOff] = convertTfToOnOff(tf)
    if(tf)
        onOff = 'on';
    else
        onOff = 'off';
    end
end


%% S2AxisField


function motionCompPlayMeanMovie(slice,view)
%
%    gb 04/30/05
%
%    motionCompPlayMeanMovie(view,slice)
%
% Plays the movie of the mean maps of the choosen slice, or creates the
% movie if it does not exist.
%
% The argument view is optional but an error in thrown if it is not
% passed in and the movie does not exist
%
if ~ieNotDefined('view')
    cd(dataDir(view))
end

if ieNotDefined('slice')
    slice = 18;
end

if ~exist(['movie_' num2str(slice) '.avi'])
    try
        motionCompMeanMovie(view,slice)
    catch
        error('The movie has not been created. Please insert a view argument');
    end
end

aviobj = aviread(['movie_' num2str(slice)]);
mplay(aviobj);


function edl_writescript(filename, guid, workdir, ctrlpath, props)
%EDL_WRITESCRIPT Writes an EDL script
%
% $ Syntax $
%   - edl_writescript(filename, guid, workdir, ctrlpath, props)
%
% $ Arguments $
%   - filename:     the filename of the destination script
%   - guid:         the guid string assigned to the script
%   - workdir:      the root working directory of the experiments
%   - ctrlpath:     the path of control file (r.t. script's parent)
%   - props:        the properties of the experiment parameters
%                   (no need of internal_index)
%
% $ Description $
%   - edl_writescript(filename, guid, workdir, ctrlpath, props) writes the
%     script according to the information provided. It will also add the
%     internal index to each entry.
%
% $ Remarks $
%   - The function will also creates the initial control file.
%
% $ History $
%   - Created by Dahua Lin, on Aug 14, 2006
%

%% parse and verify input

if nargin < 5
    raise_lackinput('edl_writescript', 5);
end

%% Prepare elements

doctag = 'ExpScript';
nodetag = 'Entry';

attribs.guid = guid;
attribs.workdir = workdir;
attribs.ctrlpath = ctrlpath;

n = length(props);
for i = 1 : n
    props(i).internal_index = i;
end

%% Write

edl_writeprops(doctag, attribs, nodetag, props, filename);
cpath = sladdpath(ctrlpath, slfilepart(filename, 'parent'));
edl_initctrlfile(cpath, guid, n);


function tmp_str=cat_str(cellstrs)

tmp_str=[];
for c_idx=1:length(cellstrs)
    if ~isempty(tmp_str)
        tmp_str=[tmp_str '_'];
    end
    tmp_str=[tmp_str cellstrs{c_idx}];
end

end


clear all; clc;

newlineInAscii1 = [13 10];
spaceInInAscii = 32;
% for printing, newline causes much confusion in matlab and is provided here as an alternative
newline = char(newlineInAscii1);
spaceChar = char(spaceInInAscii);

targetFolder = 'images';


function allbbs = show_top_transfers(models,grid,target_directory,finalstruct)%final_boxes,final_maxos)
%Show the top detections on a set of images
%NOTE his also writes out bus transfer files (which can clobber
%good results!)

VOCinit;

%finalstruct.basedir = sprintf('/nfs/baikal/tmalisie/labelme400/www/voc/iccv11/%s/',...
%                  VOCopts.dataset);

%finalstruct.basedir = '/nfs/baikal/tmalisie/labelme400/www/voc/iccv11/VOC2007/newones/';
models = add_sizes_to_models(models);

gridsave = grid;
if isfield(finalstruct,'friendclass')
  for i = 1:length(models)
    models{i}.friendclass = finalstruct.friendclass;
  end
end

allbbs = cell(0,1);
%final_boxes = final.final_boxes;
final_boxes = finalstruct.unclipped_boxes;
final_maxos = finalstruct.final_maxos;

VOCinit;

%if enabled we show images
saveimages = 0;

%% prune grid to contain only images from target_directory
[cur_set, gt] = textread(sprintf(VOCopts.imgsetpath,target_directory),['%s' ...
                    ' %d']);

if 0
  fprintf(1,'HACK: choosing only the subset which contains true positives\n');
  %% prune grid to contain only images from target_directory
  [cur_set, gt] = textread(sprintf(VOCopts.clsimgsetpath,models{1}.cls,target_directory),['%s' ...
                    ' %d']);
  cur_set = cur_set(gt==1);
end

gridids = cellfun2(@(x)x.curid,grid);
goods = find(ismember(gridids,cur_set));
grid = grid(goods);

imids = cell(1,length(final_boxes));
for i = 1:length(final_boxes)
  imids{i} = [];
  if size(final_boxes{i},1) > 0
    imids{i} = i * ones(size(final_boxes{i},1),1);
    %final_boxes{i}(:,5) = i;
  end
end

bbs = cat(1,final_boxes{:});
imids = cat(1,imids{:});
moses = [final_maxos{:}];
[aa,bb] = sort(bbs(:,end),'descend');

%% only good ones now!
%bb = bb(moses(bb)>.5);

if 0
  fprintf(1,'Only segmentation ones here\n');
  %% get ones with segmentation only
  ids = cellfun2(@(x)x.curid,models(bbs(bb,6)));
  VOCinit
  has_seg = cellfun(@(x)fileexists(sprintf('%s/%s/SegmentationObject/%s.png',...
                                           VOCopts.datadir, ...
                                           VOCopts.dataset,x)),ids);
  bb = bb(find(has_seg));
end

if 0
  %% get ones with 3d model only
  ids = cellfun2(@(x)sprintf('%s.%d.png',x.curid,x.objectid),models(bbs(bb,6)));
  VOCinit

  extradir = '/nfs/hn22/tmalisie/ddip/renderings/';
  has_3d = cellfun(@(x)fileexists(sprintf('%s/%s.%d.chair-3d.png', ...
                                          extradir,...
                                          x.curid, ...
                                          x.objectid)),models(bbs(bb,6)));

  bb = bb(find(has_3d));
end

counter = 1;
maxk = 40;
KKK = [1 1];

counter = 1;%20;
for k = 1:maxk
  k
  %figure(1)
  %clf
  for i = 1:prod(KKK)
    if counter > length(bb)
      break;
    end
    curb = bb(counter);
    curid = grid{imids(curb)}.curid;
    %curid = grid{bbs(curb,5)}.curid;
    I = im2double(imread(sprintf(VOCopts.imgpath,curid)));
    gtrecs = PASreadrecord(sprintf(VOCopts.annopath,curid));
    businds = find(ismember({gtrecs.objects.class},{'bus'}) & ~[gtrecs.objects.difficult]);
    gtbbs = cat(1,gtrecs.objects.bbox);
    gtbbs = gtbbs(businds,:);

    bbox = bbs(curb,:);

    TARGET_BUS = -1;
    if length(businds) > 0

      [alpha,beta] = max(getosmatrix_bb(gtbbs,bbox));
      TARGET_BUS = businds(beta);
    end

    if length(moses) > 0
      stuff.os = moses(curb);
    else
      stuff.os = 0;
    end
    stuff.score = bbs(curb,end);
    stuff.curid = curid;
    stuff.rank = counter;

    extra = '';

    if ismember(models{1}.models_name,{'dalal'})
      extra='-dalal';
    end

    estring = '';
    if exist('betas','var')
      estring = 'withbetas';
    end

    stuff.filer = sprintf(['/nfs/baikal/tmalisie/labelme400/www/voc/'...
                    'segxfer/%s%s-on-%s-%s-%d.eps'],...
                          models{1}.cls,extra,target_directory,estring,k);

    ccc = bbox(6);

    %curb = final_boxes{imids(curb)};
    %curb = final_boxes{bbox(5)};

    %curb = grid{bbox(5)}.bboxes;
    %curb = nms_within_exemplars(curb,.5);

    %[alpha,beta] = sort(curb(:,end),'descend');
    %curb = curb(beta(1:min(5,length(beta))),:);

    target_image_id = imids(bb(counter));
    target_cluster_id = bbs(bb(counter),5);

    allbb = finalstruct.raw_boxes{target_image_id};
    osmat = getosmatrix_bb(allbb,bbs(bb(counter),:));
    goods = find(osmat>.5);
    allbb = allbb(goods,:);
    allbb(:,end) = allbb(:,end);
    %allbb = calibrate_boxes(allbb,finalstruct.M.betas);
    allbb = esvm_nms_within_exemplars(allbb,.5);
    [alpha,beta] = sort(allbb(:,end),'descend');
    allbb = allbb(beta,:);

    %rawhits = ...
    %    finalstruct.nbrlist{target_image_id}{target_cluster_id};
    %curb = finalstruct.pre_nms_boxes{target_image_id}(rawhits,:);

    %[alpha,beta] = sort(curb(:,end),'descend');
    %curb = curb(beta,:);

    sumI = I*0;
    countI = zeros(size(I,1),size(I,2),1);
    ooo = cell(0,1);

    mean0 = mean(allbb,1);
    curoses = getosmatrix_bb(mean0(1,:),allbb);

    if 0
    for zzz = 1:min(1,size(allbb,1))

      exemplar_overlay = exemplar_inpaint(allbb(zzz,:), ...
                                          models{allbb(zzz,6)}, ...
                                          stuff);

      ooo{end+1} = exemplar_overlay;
      %if sum(1-exemplar_overlay.alphamask(:)) > 0
      try
      sumI = sumI + curoses(zzz)*allbb(zzz,end)* ...
             exemplar_overlay.segI;
      catch
      end
      %keyboard

      countI = countI + ...
               curoses(zzz)*allbb(zzz,end);%*exemplar_overlay.mask;
                                           %   break;
                                           % end
    end
    sumI = sumI ./ repmat(countI,[1 1 3]);

    end
    exemplar_overlay = exemplar_inpaint(allbb(1,:), ...
                                        models{allbb(1,6)}, ...
                                        stuff);

    allbb(1,end)

    if TARGET_BUS > -1
      %% load GT for test
      %gtfiles = dir(sprintf(['/nfs/baikal/tmalisie/buslabeling/' ...
      %                '%s*mat'],curid));
      gtmat = load(sprintf(['/nfs/baikal/tmalisie/finalbuslabeling/' ...
                    '%s.%d.mat'],curid,TARGET_BUS));

      %   clear gtmat
      % for i = 1:length(gtfiles)
      %   gtmat{i} = load(sprintf('/nfs/baikal/tmalisie/buslabeling/%s',gtfiles(i).name));
      % end
      %segs = cellfun2(@(x)x.res.seg,gtmat);
      %seg=sum(cat(3,segs{:}),3);
      seg = gtmat.res.seg;
      gtim = faces2colors(seg);

      shower = I;
      fg = repmat(double(seg~=0),[1 1 3]);

      shower(find(fg)) = shower(find(fg))*.0 + 1.0*gtim(find(fg));
      gtim = shower;
      gtim(repmat(seg==0,[1 1 3]))=0;

    else
      gtim = zeros(size(I,1),size(I,2));
    end

    if 0 %size(exemplar_overlay.friendbb,1) == 0
      counter = counter + 1;
      continue
    end

    figure(1)
    clf

    NR=show_hits_figure_iccv(models,allbb(1,:),I, ...
                          exemplar_overlay.segI,exemplar_overlay,gtim);

    %NR=show_hits_figure_iccv(models,allbb(zzz,:),I, ...
    %                      exemplar_overlay.segI,exemplar_overlay,gtim);

    drawnow

     output.I = I;
     output.result = exemplar_overlay.segI;

     if 0
       %% WARNING this is for buses
     imagesc(exemplar_overlay.overlay2.segI)
     masky = exemplar_overlay.overlay2.mask;
     [uu,vv] = find(masky);
     masky(min(uu):max(uu),min(vv):max(vv)) = ...
         imresize(exemplar_overlay.overlay2.alphamask,[range(uu)+1 range(vv)+1],'nearest');

     %masky(find(masky)) = exemplar_overlay.overlay2.alphamask(i2);
     output.result = (exemplar_overlay.overlay2.segI.*repmat(masky,[1 1 3]));
     output.WARNINGgt = gtim;
    end
     % try
     %   dfile = sprintf('/nfs/onega_no_backups/users/ashrivas/buses/%s.mat',curid);
     %   dresult = load(dfile);
     %   output.dresult = dresult.rim;
     % catch
        output.dresult = []; %2*ones(size(output.I,1),size(output.I,2));
     % end

     save(sprintf('/nfs/baikal/tmalisie/iccvres/finalbusmats/%05d.mat', ...
                  k),'output');

     %if isfield(finalstruct,'basedir')
     calib_string = '';
     if isfield(finalstruct,'M') && length(finalstruct.M)>0 && isfield(finalstruct.M,'betas')
       calib_string = '-calibrated';
     end

     filer = sprintf('%s/transfers/%s_%s%s_%05d.pdf',VOCopts.wwwdir,models{1}.cls,models{1}.models_name,calib_string,k);
     set(gcf,'PaperPosition',[0 0 2*NR(1) 2*NR(2)],...
             'PaperSize',[2*NR(1) 2*NR(2)]);

     %print(gcf,'-dpdf',filer);
     filer2 = filer;
     filer2(end-2:end) = 'png';
     [bd,tmp,tmp] = fileparts(filer2);
     if ~exist(bd,'dir')
       mkdir(bd);
     end
     print(gcf,'-dpng',filer2);

     allbbs{end+1} = allbb;
     allbb(1,7)

    %paintfiler = ...
    %     sprintf('%s/%s.%d.%s.png',basedir, ...
    %             curm.curid, curm.objectid, curm.cls);
    % imwrite(Ipaint,paintfiler);

    % curm = models{bbox(6)};
    % basedir = '/nfs/baikal/tmalisie/labelme400/www/voc/exemplars/';
    % paintfiler = ...
    %     sprintf('%s/%s.%d.%s.png',basedir, ...
    %             curm.curid, curm.objectid, curm.cls);
    % imwrite(Ipaint,paintfiler);

    %imagesc(I)
    %plot_bbox(bbox,'',color,color);

    %plot_bbox(bbs(curb,:));
    %axis image
    %axis off
    %title(sprintf('I=%s\nE=%s.%d s=%.3f os=%.3f',grid{bbs(curb,5)}.curid,models{bbs(curb,6)}.curid,models{bbs(curb,6)}.objectid,bbs(curb,end),moses(curb)));
    counter = counter+1;

  end
end


function varargout = lvd_EditVectorPlaneAngleGUI(varargin)
% LVD_EDITVECTORPLANEANGLEGUI MATLAB code for lvd_EditVectorPlaneAngleGUI.fig
%      LVD_EDITVECTORPLANEANGLEGUI, by itself, creates a new LVD_EDITVECTORPLANEANGLEGUI or raises the existing
%      singleton*.
%
%      H = LVD_EDITVECTORPLANEANGLEGUI returns the handle to a new LVD_EDITVECTORPLANEANGLEGUI or the handle to
%      the existing singleton*.
%
%      LVD_EDITVECTORPLANEANGLEGUI('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in LVD_EDITVECTORPLANEANGLEGUI.M with the given input arguments.
%
%      LVD_EDITVECTORPLANEANGLEGUI('Property','Value',...) creates a new LVD_EDITVECTORPLANEANGLEGUI or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before lvd_EditVectorPlaneAngleGUI_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to lvd_EditVectorPlaneAngleGUI_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

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

% Last Modified by GUIDE v2.5 23-Feb-2021 08:38:27

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @lvd_EditVectorPlaneAngleGUI_OpeningFcn, ...
                   'gui_OutputFcn',  @lvd_EditVectorPlaneAngleGUI_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before lvd_EditVectorPlaneAngleGUI is made visible.
function lvd_EditVectorPlaneAngleGUI_OpeningFcn(hObject, eventdata, handles, varargin)
    % This function has no output args, see OutputFcn.
    % hObject    handle to figure
    % eventdata  reserved - to be defined in a future version of MATLAB
    % handles    structure with handles and user data (see GUIDATA)
    % varargin   command line arguments to lvd_EditVectorPlaneAngleGUI (see VARARGIN)

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

    centerUIFigure(hObject);

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

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

	populateGUI(handles, lvdData, angle);

    % Update handles structure
    guidata(hObject, handles);

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

function populateGUI(handles, lvdData, angle)
    set(handles.nameText,'String',angle.getName());

    [vectorsListBoxStr, ~] = lvdData.geometry.vectors.getListboxStr();
    [planesListBoxStr, ~] = lvdData.geometry.planes.getListboxStr();

    handles.vectorCombo.String = vectorsListBoxStr;
    handles.vectorCombo.Value = lvdData.geometry.vectors.getIndsForVectors(angle.vector);

    handles.planeCombo.String = planesListBoxStr;
    handles.planeCombo.Value = lvdData.geometry.planes.getIndsForPlanes(angle.plane);

    handles.lineColorCombo.String = ColorSpecEnum.getListboxStr();
    handles.lineColorCombo.Value = ColorSpecEnum.getIndForName(angle.lineColor.name);

    handles.lineSpecCombo.String = LineSpecEnum.getListboxStr();
    handles.lineSpecCombo.Value = LineSpecEnum.getIndForName(angle.lineSpec.name);

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

% Get default command line output from handles structure
    if(isempty(handles))
        varargout{1} = false;
    else
        lvdData = getappdata(hObject, 'lvdData');
        angle = getappdata(hObject, 'angle');

        angle.setName(handles.nameText.String);

        angle.vector = lvdData.geometry.vectors.getVectorAtInd(handles.vectorCombo.Value);
        angle.plane = lvdData.geometry.planes.getPlaneAtInd(handles.planeCombo.Value);

        str = handles.lineColorCombo.String{handles.lineColorCombo.Value};
        angle.lineColor = ColorSpecEnum.getEnumForListboxStr(str);

        str = handles.lineSpecCombo.String{handles.lineSpecCombo.Value};
        angle.lineSpec = LineSpecEnum.getEnumForListboxStr(str);

        varargout{1} = true;
        close(handles.lvd_EditVectorPlaneAngleGUI);
    end

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

    if(isempty(errMsg))
        uiresume(handles.lvd_EditVectorPlaneAngleGUI);
    else
        msgbox(errMsg,'Invalid Angle Inputs','error');
    end

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

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

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

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

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

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

% --- Executes on key press with focus on lvd_EditVectorPlaneAngleGUI or any of its controls.
function lvd_EditVectorPlaneAngleGUI_WindowKeyPressFcn(hObject, eventdata, handles)
% hObject    handle to lvd_EditVectorPlaneAngleGUI (see GCBO)
% eventdata  structure with the following fields (see MATLAB.UI.FIGURE)
%	Key: name of the key that was pressed, in lower case
%	Character: character interpretation of the key(s) that was pressed
%	Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed
% handles    structure with handles and user data (see GUIDATA)
    switch(eventdata.Key)
        case 'return'
            saveAndCloseButton_Callback(handles.saveAndCloseButton, [], handles);
        case 'enter'
            saveAndCloseButton_Callback(handles.saveAndCloseButton, [], handles);
        case 'escape'
            close(handles.lvd_EditVectorPlaneAngleGUI);
    end

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

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

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

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

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

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

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

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

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

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

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


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

%%
clear; close all; clc;

%% Syntax
% |D=pathLength(V);|

%% 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 Callbacks_p_Tube_VT_GUI25(f,C)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
x=C{1,1};
y=C{1,2};
a=C{1,3};
b=C{1,4};
u=C{1,5};
v=C{1,6};
m=C{1,7};
n=C{1,8};
lengthbutton=C{1,9};
widthbutton=C{1,10};
enterType=C{1,11};
enterString=C{1,12};
enterLabel=C{1,13};
noPanels=C{1,14};
noGraphicPanels=C{1,15};
noButtons=C{1,16};
labelDist=C{1,17};%distance that the label is below the button
noTitles=C{1,18};
buttonTextSize=C{1,19};
labelTextSize=C{1,20};
textboxFont=C{1,21};
textboxString=C{1,22};
textboxWeight=C{1,23};
textboxAngle=C{1,24};
labelHeight=C{1,25};
fileName=C{1,26};
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%PANELS
for j=0:noPanels-1
uipanel('Parent',f,...
'Units','Normalized',...
'Position',[x(1+4*j) y(1+4*j) x(2+4*j)-x(1+4*j) y(3+4*j)-y(2+4*j)]);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%GRAPHIC PANELS
for i=0:noGraphicPanels-1
switch (i+1)
case 1
graphicPanel1 = axes('parent',f,...
'Units','Normalized',...
'Position',[a(1+4*i) b(1+4*i) a(2+4*i)-a(1+4*i) b(3+4*i)-b(2+4*i)],...
'GridLineStyle','--');
case 2
graphicPanel2 = axes('parent',f,...
'Units','Normalized',...
'Position',[a(1+4*i) b(1+4*i) a(2+4*i)-a(1+4*i) b(3+4*i)-b(2+4*i)],...
'GridLineStyle','--');
case 3
graphicPanel3 = axes('parent',f,...
'Units','Normalized',...
'Position',[a(1+4*i) b(1+4*i) a(2+4*i)-a(1+4*i) b(3+4*i)-b(2+4*i)],...
'GridLineStyle','--');
case 4
graphicPanel4 = axes('parent',f,...
'Units','Normalized',...
'Position',[a(1+4*i) b(1+4*i) a(2+4*i)-a(1+4*i) b(3+4*i)-b(2+4*i)],...
'GridLineStyle','--');
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%TITLE BOXES
for k=0:noTitles-1
switch (k+1)
case 1
titleBox1 = uicontrol('parent',f,...
'Units','Normalized',...
'Position',[u(1+4*k) v(1+4*k) u(2+4*k)-u(1+4*k) v(3+4*k)-v(2+4*k)],...
'Style','text',...
'FontSize',textboxFont{k+1},...
'String',textboxString(k+1),...
'FontWeight',textboxWeight{k+1},...
'FontAngle',textboxAngle{k+1});
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%BUTTONS
for i=0:(noButtons-1)
enterColor='w';
if strcmp(enterType{i+1},'pushbutton')==1 ||strcmp(enterType{i+1},'text')==1
enterColor='default';
end
if (strcmp(enterLabel{1,(i+1)},'')==0 &&...
        strcmp(enterLabel{1,(i+1)},'...')==0) %i.e. there is a label
%creating a label for some buttons
uicontrol('Parent',f,...
'Units','Normalized',...
'Position',[m(1+2*i) n(1+2*i)-labelDist-labelHeight(i+1) ...
(m(2+2*i)-m(1+2*i)) labelHeight(i+1)],...
'Style','text',...
'String',enterLabel{i+1},...
'FontSize', labelTextSize(i+1),...
'HorizontalAlignment','center');
end
switch (i+1)
case 1
button1=uicontrol('Parent',f,...
'Units','Normalized',...
'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...
'Style',enterType{i+1},...
'String',enterString{i+1},...
'FontSize', buttonTextSize(1+i),...
'BackgroundColor',enterColor,...
'HorizontalAlignment','center',...
'Callback',@button1Callback);
case 2
button2=uicontrol('Parent',f,...
'Units','Normalized',...
'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...
'Style',enterType{i+1},...
'String',enterString{i+1},...
'FontSize', buttonTextSize(1+i),...
'BackgroundColor',enterColor,...
'HorizontalAlignment','center',...
'Callback',@button2Callback);
case 3
button3=uicontrol('Parent',f,...
'Units','Normalized',...
'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...
'Style',enterType{i+1},...
'String',enterString{i+1},...
'FontSize', buttonTextSize(1+i),...
'BackgroundColor',enterColor,...
'HorizontalAlignment','center',...
'Callback',@button3Callback);
case 4
button4=uicontrol('Parent',f,...
'Units','Normalized',...
'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...
'Style',enterType{i+1},...
'String',enterString{i+1},...
'FontSize', buttonTextSize(1+i),...
'BackgroundColor',enterColor,...
'HorizontalAlignment','center',...
'Callback',@button4Callback);
case 5
button5=uicontrol('Parent',f,...
'Units','Normalized',...
'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...
'Style',enterType{i+1},...
'String',enterString{i+1},...
'FontSize', buttonTextSize(1+i),...
'BackgroundColor',enterColor,...
'HorizontalAlignment','center',...
'Callback',@button5Callback);
case 6
button6=uicontrol('Parent',f,...
'Units','Normalized',...
'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...
'Style',enterType{i+1},...
'String',enterString{i+1},...
'FontSize', buttonTextSize(1+i),...
'BackgroundColor',enterColor,...
'HorizontalAlignment','center',...
'Callback',@button6Callback);
case 7
button7=uicontrol('Parent',f,...
'Units','Normalized',...
'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...
'Style',enterType{i+1},...
'String',enterString{i+1},...
'FontSize', buttonTextSize(1+i),...
'BackgroundColor',enterColor,...
'HorizontalAlignment','center',...
'Callback',@button7Callback);
case 8
button8=uicontrol('Parent',f,...
'Units','Normalized',...
'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...
'Style',enterType{i+1},...
'String',enterString{i+1},...
'FontSize', buttonTextSize(1+i),...
'BackgroundColor',enterColor,...
'HorizontalAlignment','center',...
'Callback',@button8Callback);
case 9
button9=uicontrol('Parent',f,...
'Units','Normalized',...
'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...
'Style',enterType{i+1},...
'String',enterString{i+1},...
'FontSize', buttonTextSize(1+i),...
'BackgroundColor',enterColor,...
'HorizontalAlignment','center',...
'Callback',@button9Callback);
case 10
button10=uicontrol('Parent',f,...
'Units','Normalized',...
'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...
'Style',enterType{i+1},...
'String',enterString{i+1},...
'FontSize', buttonTextSize(1+i),...
'BackgroundColor',enterColor,...
'HorizontalAlignment','center',...
'Callback',@button10Callback);
case 11
button11=uicontrol('Parent',f,...
'Units','Normalized',...
'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...
'Style',enterType{i+1},...
'String',enterString{i+1},...
'FontSize', buttonTextSize(1+i),...
'BackgroundColor',enterColor,...
'HorizontalAlignment','center',...
'Callback',@button11Callback);
end
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%USER CODE FOR THE VARIABLES AND CALLBACKS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Initialize Variables
rG=0.7; rL=0.7;
fs=10000; ls=1.75;
fno=1;
% area=ones(1,10);
c=35000;
nfft=4000;
p=10;
ipd=100;
fileout='out_p_tube';
sliderpos1=0.7;
sliderpos2=0.7;
filename='area_1';
source='figure5.40';
seq_length=4001;

% Name the GUI
    set(f,'Name','p_Tube_VT_GUI');

% CALLBACKS
% Callback for button1 -- mat file with areas and other parameters

set_slider_pos()

 function button1Callback(h,eventdata)
     fno=get(button1,'val');
     set(button6,'val',(rG+1)/2);
     set(button7,'val',(rL+1)/2);
 end

% Callback for button2 -- read in sampling rate, fs, of vocal tract
% synthesis
 function button2Callback(h,eventdata)
     fs=str2num(get(button2,'string'));
 end

% Callback for button3 -- report length of each uniform tube, ls
 function button3Callback(h,eventdata)
     ls=str2num(get(button3,'string'));
 end

% Callback for button4 -- glottal reflection coefficient, rG, edit button
 function button4Callback(h,eventdata)
     set(button4,'string',num2str(sliderpos1));
     rG=sliderpos1;
 end

% Callback for button5 -- lips reflection coefficient, rL, edit button
 function button5Callback(h,eventdata)
     set(button5,'string',num2str(sliderpos2));
     rL=sliderpos2;
 end

% Callback for button6 -- rG slider (range of -1 to +1) edit button
 function button6Callback(h,eventdata)
     sliderpos1=get(button6,'val')*2-1;
     button4Callback(h,eventdata);
 end

% Callback for button7 -- rL slider  (range of -1 to +1) edit button
 function button7Callback(h,eventdata)
     sliderpos2=get(button7,'val')*2-1;
     button5Callback(h,eventdata);
 end

% Callback for button8 -- name of output text file, fileout, for saving
% p-tube vocal tract resonances
 function button8Callback(h,eventdata)
     fileout=get(button8,'string');
 end

% Callback for button11 -- ipd:  pitch period in samples
    function button11Callback(h,eventdata)
        ipd=num2str(get(button11,'string'));
    end

% Callback for button9 -- run the p-tube VT model code
 function button9Callback(h,eventdata)

% send message to change either rG or rL to be less than 1 for realistic
% vowel sound
    if (rG == 1 & rL == 1)
    uiwait(msgbox('change rG or rL to be less than 1 for correct vowel sound',...
        'set rG, rL','modal'));
    end

% read in source file for areas and other parameters
     clear area;
     filename=['area_',num2str(fno),'.mat'];
     areas=load(filename);

% extract p-tube vocal tract information from areas structure, including the
% p-tube areas, areas.area. the source of the area data, areas.source,
% the number of tubes, areas.p, the size of fft for synthesis,
% areas.nfft, the sampling rate of the simulation, areas.fs, the
% speed of sound in cm/sec, areas.c, and the length of each of the
% p-uniform tubes, areas.ls
     area=areas.area;
     source=areas.source;
     p=areas.p;
     nfft=areas.nfft;
     fs=areas.fs;
     c=areas.c;
     ls=areas.ls;

% update buttons for fs and ls by writing the values obtained above into
% the appropriate edit buttons (button2 and button3)
    set(button2,'string',num2str(fs));
    set(button3,'string',num2str(ls));

% open text file for saving vocal tract resonance information
    fid=fopen(fileout,'wt');

% create input for plotting vocal tract area function across p sections
    yc=[area(1) area(1) area(1)];
    xc=[0 1 1 1 1];
    for index=2:p-1
        yc=[yc area(index) area(index) area(index) area(index)];
        xc=[xc index index index index];
    end
    yc=[yc area(p) area(p) area(p)];
    xc=[xc p];

% plot vocal tract area function in Graphics Panel 1
    grid off;
    reset(graphicPanel1);
    axes(graphicPanel1);

% plot p-tube area function
    amax=max(yc);
    plot(xc,yc,'b','LineWidth',2);
    hold on,plot(xc,-yc,'b','LineWidth',2);
    plot([0 p],[0 0],'r--','LineWidth',2);
    axis ([0 p -amax*1.1 amax*1.1]);
    xlabel('Distance from Glottis');
    ylabel('Area(square cm)');
    stitle=sprintf(' source: %s, p: %d, ls: %6.2f',source,p,ls);

% set title in titleBox1; adjust font size to 20
    stitle1=strcat('p-Tube Vocal Tract -- ',stitle);
    set(titleBox1,'String',stitle1);
    set(titleBox1,'FontSize',20);

% transform from vocal tract areas areas(1:p-1) to reflection coefficients,
% k(1:p-1)
    clear k;
    k(1:p-1)=(-area(2:p)+area(1:p-1))./(area(2:p)+area(1:p-1));
    r(1:p-1)=-k(1:p-1);
    k=[rG -r rL];

% plot set of reflection coefficients on Graphics Panel 2
    reset(graphicPanel2);
    axes(graphicPanel2);
    stem(0:p,k,'r','LineWidth',2);
    axis([0 p -1 1]);
    xlabel('Distance from Glottis'); ylabel('Reflection Coefficients');

% print out (to ascii text file) the set of reflection coefficients and areas
    fprintf(fid,'areas-to-spectrum using p: %d, nfft: %d,',p,nfft);
    fprintf(fid,' fs: %d \n',fs);
    for index=1:p-1
        fprintf(fid,'index: %d, k:%6.4f,',index,k(index));
        fprintf(fid,' areas:%6.3f, %6.3f \n',area(index+1),area(index));
    end

%
% solve nodal equations for the p tubes
%
% matrix1 columns are uG, u1+, u2+, ..., up+, u(p+1)+
% matrix1 rows are n=0,1,2,...,NL
% matrix2 columns are u1-, u2-, ...,up-
% matrix2 rows are n=1,2,...,NL+1
%
    NL=3000; % number of time slots for solution

% initialize nodal equations
    uplus=zeros(p+2,NL+1);
    uminus=zeros(p,NL+1);
    uplus(1:2,1)=[1,(1+rG)/2];

% solve nodal equations for NL iterations
    for n=1:NL
        uminus(p,n+1)=-rL*uplus(p+1,n);
        for node=p-1:-1:1
            uminus(node,n+1)=-r(node)*uplus(node+1,n)+...
                (1-r(node))*uminus(node+1,n+1);
        end
        uplus(2,n+1)=uminus(1,n+1)*rG;
        for node=3:p+1
            uplus(node,n+1)=uplus(node-1,n)*(1+r(node-2))+...
                uminus(node-1,n+1)*r(node-2);
        end
        uplus(p+2,n+1)=(1+rL)*uplus(p+1,n);
    end

% save output as vocal tract impulse response
    h(1:NL+1)=uplus(p+2,1:NL+1);

% truncate impulse response to nl=500 samples
    nl=500;
    nir=0:nl-1;

% plot resulting vocal tract impulse response in Figure 3
    reset(graphicPanel3);
    axes(graphicPanel3);

    plot(nir,h(1:nl),'b','LineWidth',2);
    xpp=['Time in Samples;  fs=',num2str(fs),' samples/second'];
    xlabel(xpp),ylabel('Amplitude');
    grid on, axis tight;
    s1=sprintf('source: %s, p: %d,',source,p);
    s2=sprintf(' rG,rL: %6.3f, %6.3f, fs:%6.1f',rG,rL,fs);
    stitle=strcat(s1,s2);
    legend('Vocal Tract Impulse Response');

% transform to spectral domain and plot log magnitude response
    h=[h, zeros(1,nfft-NL-1)];

% convert to log magnitude spectrum
    hs=fft(h,nfft);
    spectrum(1:nfft/2+1)=20*log10(1.e-1+abs(hs(1:nfft/2+1)));
    vmin=min(spectrum);
    vmax=max(spectrum);

% plot log magnitude spectrum in graphics Panel 4
    reset(graphicPanel4);
    axes(graphicPanel4);

    freq=0:fs/nfft:fs/2;
    npts=nfft/2+1;
    plot(freq(1:npts),spectrum(1:npts),'g','LineWidth',2); grid;
    xlabel('Frequency(kHz)'); ylabel('Log Magnitude(dB)');
    axis([freq(1) freq(npts) vmin-2 vmax+2]);
    hold on;

% find formant locations and include on plot
    fmt=[];
    loc=[];
    nfmt=0;
    for index=10:npts-2
        if (spectrum(index+1) > spectrum(index) && ...
                spectrum(index+1) > spectrum(index+2))
            fmt=[fmt freq(index+1)];
            loc=[loc index];
            nfmt=nfmt+1;
        end
    end

% next estimate formant bandwidths
    bwlevel=6; % (db) range of bandwidth around formant peak
    if (nfmt <= 10)
        for nf=1:nfmt
            f=fmt(nf);
            index=loc(nf);
            peak=spectrum(index);
            [peakl,peakh]=findpeak(spectrum,index,peak,bwlevel);
            fr(nf)=f;
            bw(nf)=freq(peakh)-freq(peakl);
        end
    else
        peakspectrum=max(spectrum);
        nfe=1;
        for nf=1:nfmt
            f=fmt(nf);
            index=loc(nf);
            peak=spectrum(index);
            if (peak >= peakspectrum-20)
                fr(nfe)=f;
                bw(nfe)=0;
                fmt(nfe)=f;
                nfe=nfe+1;
            end
        end
        nfmt=nfe-1;
    end

% print out results to output text file
    fprintf(fid,'p-tube model results: \n');
    fprintf(fid,'rL,rG: %4.1f %4.1f \n',rL,rG);
    for formant=1:nfmt
        fprintf(fid,'formant frequency: %6.1f,',fr(formant));
        fprintf(fid,' formant bandwidth: %6.1f \n',bw(formant));
    end
    fprintf(fid,'\n \n');

% print formant locations on plots
    for nf=1:nfmt
        frfmt=[fmt(nf) fmt(nf)];
        vrfmt=[vmin vmax];
        plot(frfmt,vrfmt,'r','LineWidth',2);
        string=strcat('fmt',int2str(nf),':',int2str(fmt(nf)));
        if (mod(nf,2) == 0)
            text(fmt(nf)-200,vmax*.9,string);
        else
            text(fmt(nf)-200,vmin*1.1,string);
        end
    end

% convolve p-tube impulse response with periodic pulse train of period ipd
% samples (default is 100 Hz fundamental at fs=10000 Hz), and play out resulting
% speech waveform -- note wierd sound for rG=rL=1 since impulse response
% never dies out with no loss
        ipd=str2num(get(button11,'string'));
                   if (ipd < 0)
            waitfor(errordlg('IPD must be positive'));
        end
        seq_length=40*ipd;  % sequence length in samples
        xin=zeros(1,seq_length);
        xin(1:ipd:seq_length)=1;
        yout=conv(xin,h);
        soundsc(yout,fs);

% close up printing file
    fclose('all');
 end

% Callback for button10 -- close the GUI
 function button10Callback(h,eventdata)
     close(gcf);
 end

function set_slider_pos()
    set(button6,'val',rG+0.15); %when set at exactly rG, slider bar is at 0.4
    set(button7,'val',rL+0.15); %when set at exactly rL, slider bar is at 0.4
end
end


function pars=extractpars(vars,default);
% function pars=extractpars(vars,default);
%
%

if(nargin<2)
  default=[];
end;

pars=default;
if(length(vars)==1)
 p=vars{1};
 s=fieldnames(p);
 for i=1:length(s)
   eval(['pars.' s{i} '=p.' s{i}]);
 end;

else

 for i=1:2:length(vars)
  if(isstr(vars{i}))
    if(i+1>length(vars)) error(sprintf('Parameter %s has no value\n',vars{i}));else val=vars{i+1};end;
    if(isstr(val))
     eval(['pars.' vars{i} '=''' val ''';']);
    else
     eval(['pars.' vars{i} '=' sprintf('%i',val) ';']);
    end;
  end;
 end;

end;


function demo_sds_benchmark(imgdir, cachedir, sbddir)

fid=fopen('val_debug.txt');
imnames=textscan(fid, '%s');
imnames=imnames{1};
if(~exist(cachedir, 'file')) mkdir(cachedir); end
mcgdir=fullfile(cachedir, 'mcg');
ovoutdir=fullfile(cachedir, 'overlaps');
sptextdir=fullfile(cachedir, 'sptextdir');
regspimgdir=fullfile(cachedir, 'reg2spimgdir');
featdir=fullfile(cachedir, 'featdir');
refinedoutdir=fullfile(cachedir, 'refinement_out');
scorefile=fullfile(cachedir, 'scores.mat');

imagelist_to_sds(imnames, imgdir, mcgdir, ovoutdir, sptextdir, regspimgdir, featdir, refinedoutdir, scorefile,2000);
tmp=load(scorefile);
chosen=tmp.topchosen;
chosenscores=tmp.topscores;

output=run_benchmark(imnames, chosen, chosenscores, sptextdir, regspimgdir, sbddir, 15);
pause;
output=run_benchmark(imnames, chosen, chosenscores, sptextdir, regspimgdir, sbddir, 15, refinedoutdir);


name_list = {'bunny' 'david50kf' 'hand' 'lion-head' 'david_head' 'aphro' 'gargoyle' 'screwdriver' 'elephant-50kv'};

for itname = 1:length(name_list)
    name = name_list{itname};
    test_levelset_mesh;
end


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

    enumeration
        Simple('Simple Power Sink');
    end

    properties
        name(1,:) char
    end

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

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

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

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


function [dicomInfo] = SiemensCsaParse(dicomInfo)
% Read values from the 'SIEMENS CSA HEADER' private group in a
% DICOM file produced by a Siemens MR scanner.
%
% [dicomInfo] = SiemensCsaParse(dicomInfo)
%
% dicomInfo is a Siemens MR DICOM file loaded using Matlab's dicominfo()
%        OR a string specifying the filename of a DICOM file to load.
%
% output is the original structure with an extra field 'csa' that contains
% the decoded 'SIEMENS CSA HEADER' block

% Inspiration for this comes from the gdcm tool (http://gdcm.sf.net/),
% specifically gdcmCSAHeader.cxx lines 490-65.

% Possible TODO:
% 1. Migrate to C++ MEX file.
% 2. Investigate whether there's a Siemens product .dll file (e.g.
%    Z:\n4\pkg\MrServers\MrProtSrv) for parsing these headers.
% 3. Understand meaning of syngodt (Syngo Datatype ???) field.

% Copyright: Chris Rodgers (University of Oxford), 2008-11.
% All rights reserved.

% $Id: SiemensCsaParse.m 5022 2012-02-01 11:26:39Z will $

if ischar(dicomInfo)
    dicomInfo = dicominfo(dicomInfo);
end

%% Locate SIEMENS CSA HEADER
tagId = getDicomPrivateTag(dicomInfo,'0029','SIEMENS CSA HEADER');

if isempty(tagId)
    % Give warning and return with unmodified dicomInfo
    warning('RodgersSpectroTools:NoSiemensCsaHeader','This DICOM file does not contain a ''SIEMENS CSA HEADER''.')
    return
end

%% Process the two parameter fields
SiemensCsaParse_ReadDicomTag(['Private_0029_' tagId '10']);
SiemensCsaParse_ReadDicomTag(['Private_0029_' tagId '20']);

return

%% Main code
function SiemensCsaParse_ReadDicomTag(strTag)
    currdx=0;

    if ~strcmp(char(private_read(4)),'SV10') || ~all(private_read(4)==[4 3 2 1])
        error('Unsupported CSA block format');
    end

    % This parsing code is translated from gdcm (http://gdcm.sf.net/)
    numElements = double(private_readuint32(1));

    % Sanity check
    if private_readuint32(1)~=77
        error('Unsupported CSA block format');
    end

    for tagdx=1:numElements
        tagName = private_readstring(64);

        % Fix up tagName
        tagName(tagName == '-') = [];

        vm = private_readuint32(1);
        vr = private_readstring(4);
        syngodt = private_readuint32(1);
        nitems = double(private_readuint32(1));

        checkbit = private_readuint32(1);

        if checkbit ~= 77 && checkbit ~= 205
            error('Unsupported CSA block format');
        end

        data = {};
        for itemdx=1:nitems
            header = double(private_readuint32(4));

            if (header(3) ~= 77 && header(3) ~= 205) || ...
                    (header(1) ~= header(2)) || ...
                    (header(1) ~= header(4))
                error('Unsupported CSA block format');
            end

            data{itemdx} = private_readstring(header(1));

            % Dump junk up to DWORD boundary
            private_read(mod(mod(4-header(1),4),4));
        end

        % Store this in the csa structure
        switch vr
            case {'CS', 'LO', 'LT', 'SH', 'SS', 'UI', 'UT', 'UN'} % Strings and unknown byte string
                if numel(data) < vm
                    % Pad if necessary. Siemens CSA format omits null strings.
                    data{vm} = '';
                end

                if vm == 1
                    dicomInfo.csa.(tagName) = data{1};
                else
                    dicomInfo.csa.(tagName) = data(1:vm);
                end
            case {'DS', 'FD', 'FL', 'IS', 'SL', 'ST', 'UL', 'US'} % Numbers
                dataNumeric = arrayfun(@str2double,data);

                if numel(dataNumeric) < vm
                    % Zero pad if necessary. Siemens CSA format omits zeros.
                    dataNumeric(vm) = 0;
                end

                dicomInfo.csa.(tagName) = dataNumeric(1:vm);
            otherwise
                warning('RodgersSpectroTools:UnknownVrType','Unknown VR type: "%s".',vr)
        end
    end

    %% Helper functions to simulate file I/O
    function [out] = private_read(numBytes)
        out = dicomInfo.(strTag)(currdx+(1:numBytes)).';
        currdx=currdx+numBytes;
    end

    function [out] = private_readuint32(num)
        out=typecast(private_read(4*num),'uint32');
    end

    function [out] = private_readstring(maxchar)
        out = reshape(char(private_read(maxchar)),1,[]);
        terminator = find(out==0,1);
        if numel(terminator)>0
            out=out(1:(terminator-1));
        end
    end

end

end


function nameList = fixNames(nameList)
% Standardizes names, ie, met, rxn and long names for them as well.
% `fixNames` makes the names lowercase, removes obtuse characters and
% whitespace and replaces them with underscores, and then removes starting
% and trailing underscores. Called by `compareCbModels`, `verifyModel`, `addSEEDInfo`.
%
% USAGE:
%
%    nameList = fixNames(nameList)
%
% INPUTS:
%    nameList:      Cell array of names.
%
% OUTPUTS:
%    nameList:      Same cell array but with fixed names.
%
% Please cite:
% `Sauls, J. T., & Buescher, J. M. (2014). Assimilating genome-scale
% metabolic reconstructions with modelBorgifier. Bioinformatics
% (Oxford, England), 30(7), 1036?8`. http://doi.org/10.1093/bioinformatics/btt747
%
% ..
%    Edit the above text to modify the response to help addMetInfo
%    Last Modified by GUIDE v2.5 06-Dec-2013 14:19:28
%    This file is published under Creative Commons BY-NC-SA.
%
%    Correspondance:
%    johntsauls@gmail.com
%
%    Developed at:
%    BRAIN Aktiengesellschaft
%    Microbial Production Technologies Unit
%    Quantitative Biology and Sequencing Platform
%    Darmstaeter Str. 34-36
%    64673 Zwingenberg, Germany
%    www.brain-biotech.de

nameList = lower(nameList) ; % Fix those names! Make everything lowercase.

% Remove wierd characters.
nameList = regexprep(nameList, ' |-(?!($|\||\[))|,|:|\(|\)', '_') ;

% Remove [ and ] that aren't part of the compartment lable.
% ie ] that are not at the end of the word.
nameList = regexprep(nameList, '\](?!($|\|))', '_') ;

% And [ that don't look ahead do a letter and a ].
nameList = regexprep(nameList, '\[(?!.\]$)', '_') ;

% Consolodate resulting underscores.
nameList = regexprep(nameList, '_____|____|___|__', '_') ;

% Delete ones at beginning and end of names.
nameList = regexprep(nameList, '^_|\|_|_\||_$|_(?=\[\w\]$)', '') ;


%% Copyright (C) 2014-2018 Colin B. Macdonald
%%
%% This file is part of OctSymPy.
%%
%% OctSymPy 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 software 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 software; see the file COPYING.
%% If not, see <http://www.gnu.org/licenses/>.

function convert_comments (basedir, subdir, dirout)
% this slightly strange way of doing things (basedir, subdir) is
% b/c I must "chdir" into base, but get_first_help_sentence() must
% not be in the class dir...

  %basedir, subdir, dirout
  files = dir([basedir subdir]);
  chdir(basedir)

  for i=1:length(files)
    if (~files(i).isdir)
      [dir, name, ext] = fileparts(files(i).name);
      if (strcmp(ext, '.m'))
        if isempty(subdir)
          octname = [name ext];
        else
          octname = [subdir '/' name ext];
        end
        fprintf('Converting texinfo to Matlab-style documentation: %s\n', octname)
        r = convert_oct_2_ml (octname, [dirout octname]);
        if ~r
          [status, msg, msgid] = copyfile (octname, [dirout octname], 'f');
          if (status ~= 1)
            error(msg)
          end
          fprintf('**** COPYING %s UNMODIFIED ****\n', octname)
        end
      end
    end
  end
end

function success = convert_oct_2_ml (fname, foutname)

  [dir, fcn, ext] = fileparts(fname);

  newl = sprintf('\n');

  [fi,msg] = fopen(fname, 'r');
  if (fi < 0)
    error(msg)
  end

  ins = {}; i = 0;
  while (1)
    temp = fgets(fi);
    if ~ischar(temp) && temp == -1
      break
    end
    i = i + 1;
    ins{i} = temp;
    % todo, possible strip newl
  end

  fclose(fi);

  % trim newlines
  ins = deblank(ins);

  %% find the actual function [] = ... line
  Nfcn = [];
  for i = 1:length(ins)
    I = strfind (ins{i}, 'function');
    if ~isempty(I) && I(1) == 1
      %disp ('found function header')
      Nfcn = i;
      break
    end
  end
  if isempty(Nfcn)
    disp('AFAICT, this is a script, not a function')
    success = false;
    return
  end

  %% copyright block
  [cr,N] = findblock(ins, 1);
  if (Nfcn < N)
    warning('function header in first block (where copyright block should be), not converting')
    success = false;
    return
  end
  cr = ltrim(cr, 3);

  % cut 2nd line if empty
  if isempty(cr{2})
    cr2 = cell(1,length(cr)-1);
    cr2(1) = cr(1);
    cr2(2:end) = cr(3:end);
    cr = cr2;
  end

  cr = prepend_each_line(cr, '%', ' ');
  cr{1} = ['%' cr{1}];
  copyright_summary = 'This is free software under the GPL, see .m file for full details.';
  % alternative for BSD:
  %copyright_summary = 'This is free software, see .m file for license.';

  %% use block
  % we don't parse this, just call get_help_text
  temp = ins{N};
  if ~strcmp(temp, '%% -*- texinfo -*-')
    error('can''t find the texinfo line, aborting')
    %success = false;
    %return
  end

  %% the "lookfor" line
  lookforstr = get_first_help_sentence (fname);
  if (~isempty(strfind(lookforstr, newl)))
    lookforstr
    error('lookfor string contains newline: missing period? too long? some other issue?')
    %success = false;
    %return
  end
  if (length(lookforstr) > 76)
    error(sprintf('lookfor string of length %d deemed too long', length(lookforstr)))
  end

  %% get the texinfo source, and format it
  [text, form] = get_help_text(fname);
  if ~strcmp(form, 'texinfo')
    text
    form
    error('formatted incorrectly, help text not texinfo')
  end
  usestr = __makeinfo__(text, 'plain text');

  %% remove the lookforstr from the text
  I = strfind(usestr, lookforstr);
  if length(I) ~= 1
    I
    lookforstr
    usestr
    error('too many lookfor lines?')
  end
  len = length(lookforstr);
  J = I + len;

  % if usestr has only a lookfor line then no need to see what's next
  if (J < length(usestr))
    % find next non-empty char
    %while isspace(usestr(J))
    %  J = J + 1;
    %end

    % let's be more conservative trim newline in usual case:
    if ~isspace(usestr(J))
      error('no space or newline after lookfor line?');
    end
    J = J + 1;
  end

  usestr = usestr([1:(I-1) J:end]);

  use = strsplit(usestr, newl, 'CollapseDelimiters', false);

  %% 2017: we have more choices than "-- Function File"
  % just trim "--" so it doesn't break indents
  def_line_has_function_name = false;
  for i=1:length(use)
    if regexp(use{i}, '^ -- ')
      if (~ isempty(strfind(use{i}, [' ' fcn])))
        def_line_has_function_name = true;
      end
    end
    use{i} = regexprep(use{i}, '^ -- ', '     ');
  end
  %usestr = strrep(usestr, lookforstr, '');
  if (~ def_line_has_function_name)
    warning('function @deftypefn line may not include function name:')
    use{i}
  end

  use = ltrim(use, 2);
  while isempty(use{end})
    use = use(1:end-1);
  end

  %% the rest
  N = Nfcn;
  fcn_line = ins{N};

  % sanity checks
  I = strfind(ins{N+1}, '%');
  if ~isempty(I) && I(1) == 1
    ins{N}
    ins{N+1}
    error('possible duplicate comment header following function')
  end

  therest = ins(N+1:end);

  %% Output
  [f, msg] = fopen(foutname, 'w');
  if (f < 0)
    msg
    error('failed to open file for writing')
  end

  fdisp(f, fcn_line)

  fprintf(f, '%%%s  %s\n', upper(fcn), lookforstr)

  for i=1:length(use)
    fprintf(f, '%%%s\n', use{i});
  end

  fdisp(f, '%');
  fprintf(f, '%%   %s\n', copyright_summary);

  %fdisp(f, '%');
  %fdisp(f, '%   [Genereated from a GNU Octave .m file, edit that instead.]');

  %fprintf(f,(s)

  fdisp(f, '');
  fdisp(f, '%% Note for developers');
  fdisp(f, '% This file is autogenerated from a GNU Octave .m file.');
  fdisp(f, '% If you want to edit, please make changes to the original instead');

  fdisp(f, '');
  for i=1:length(cr)
    fprintf(f, '%s\n', cr{i});
  end

  fdisp(f, '');

  for i=1:length(therest)
    fprintf(f, '%s\n', therest{i});
  end

  fclose(f);

  success = true;

end

function [block,endl] = findblock(f, j)
  block = {}; c = 0;
  %newl = sprintf('\n');
  for i = j:length(f)
    temp = f{i};
    %if (strcmp(temp, newl))
    if (isempty(temp))
      endl = i + 1;
      break
    end
    c = c + 1;
    block{c} = temp;
  end
end

function g = ltrim(f, n)
  g = {};
  for i = 1:length(f)
    temp = f{i};
    if length(temp) < n
      g{i} = '';
    else
      g{i} = substr(temp, n+1);
    end
  end
end

function g = prepend_each_line(f, pre, pad)
  g = {};
  for i = 1:length(f)
    temp = f{i};
    if isempty(temp)
      g{i} = pre;
    else
      g{i} = [pre pad temp];
    end
  end
end


% return a get batch function
% -------------------------------------------------------------------------
function fn = getBatchWrapper_augVOC2012(opts)
fn = @(images, mode) getBatch_dict(images, mode, opts) ;
end

function [imBatch, semanticMaskBatch, instanceMaskBatch, weightBatch] = getBatch_dict(images, mode, opts)
[imBatch, semanticMaskBatch, instanceMaskBatch, weightBatch] = getImgBatch_augVOC2012(images, mode, opts, 'prefetch', nargout == 0) ;
end