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

% Last Modified by GUIDE v2.5 17-Sep-2008 16:05:29

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

return;

% --- Executes just before ctrInit is made visible.
function ctrInit_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 ctrInit (see VARARGIN)

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

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes ctrInit wait for user response (see UIRESUME)
% uiwait(handles.figure1);
btnTimeStamp_Callback(hObject, eventdata, handles);

menuEditRefresh_Callback(hObject, eventdata, handles)

return;

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

return;

% --- Executes on button press in btnCreateContrackFiles.
function btnCreateContrackFiles_Callback(hObject, eventdata, handles)
% Button:  Generate Fibers

params = getParams(hObject);

% This does ALMOST EVERYTHING
% 1. Creates wmprob.nii.gz
% 2. Creates pdf.nii.gz
% 3. Create ROI mask.nii.gz
% 4. Create the ctrSampler_timestamp.txt file
params = ctrInitParamsFile(params);

% One last thing: make the ctrScript_timestamp.sh file
ctrScript(params);

return;

% --- Executes on button press in btnDT6file.
function btnDT6File_Callback(hObject, eventdata, handles)
% Button:  Browse for DT6 file
hndl = guihandles(hObject);
fullName = mrvSelectFile('r','*','DT6');
if isempty(fullName), return; end
set(hndl.editFilenameDti6,'String',fullName);
menuEditRefresh_Callback(gcbf);
return;

% --- Executes on button press in btnROI1file.
function btnROI1File_Callback(hObject, eventdata, handles)
% Button:  Browse for ROI1 file
hndl = guihandles(hObject);
startDir = fileparts(get(hndl.editFilenameDti6,'String'));
fullName = mrvSelectFile('r','*','ROI 1',startDir);
if isempty(fullName), return; end
set(hndl.editFilenameROI1,'String',fullName);
menuEditRefresh_Callback(gcbf);
return;

% --- Executes on button press in btnROI2file.
function btnROI2File_Callback(hObject, eventdata, handles)
% Button:  Browse for ROI1 file
hndl = guihandles(hObject);
startDir = fileparts(get(hndl.editFilenameROI1,'String'));
if(isempty(startDir))
    startDir = fileparts(get(hndl.editFilenameDti6,'String'));
end
fullName = mrvSelectFile('r','*','ROI 2',startDir);
if isempty(fullName), return; end
set(hndl.editFilenameROI2,'String',fullName);
menuEditRefresh_Callback(gcbf);
return;

function editFilenameDti6_Callback(hObject, eventdata, handles)
menuEditRefresh_Callback(gcbf);
return;

% --- Executes during object creation, after setting all properties.
function editFilenameDti6_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
return;

function editFilenameROI1_Callback(hObject, eventdata, handles)
menuEditRefresh_Callback(gcbf);
return;

% --- Executes during object creation, after setting all properties.
function editFilenameROI1_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
return;

% --- Executes during object creation, after setting all properties.
function editFilenameROI2_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
return;

function editFilenameROI2_Callback(hObject, eventdata, handles)
menuEditRefresh_Callback(gcbf);
return;

% --------------------------------------------------------------------
function menuEdit_Callback(hObject, eventdata, handles)
return;

% --------------------------------------------------------------------
function menuFile_Callback(hObject, eventdata, handles)
return;

% --------------------------------------------------------------------
function menuFileLoad_Callback(hObject, eventdata, handles)
% File | Load params
ctr = ctrLoad;
setParams(hObject,ctr);
return;
% --------------------------------------------------------------------
function menuFileSave_Callback(hObject, eventdata, handles)
% File | Save params
params = getParams(hObject);
ctrInitParamsFile(params);
return;

% --------------------------------------------------------------------
function menuFileClose_Callback(hObject, eventdata, handles)
% File | Close
closereq;
return;

% --------------------------------------------------------------------
function menuFileSaveClose_Callback(hObject, eventdata, handles)
% File | Save and close
params = getParams(hObject);
ctrInitParamsFile(params);
closereq;
return;

% --------------------------------------------------------------------
function menuHelpVistaWiki_Callback(hObject, eventdata, handles)
% Help | Vista Wiki ConTrack
web('http://white.stanford.edu/newlm/index.php/DTI#ConTrack','-browser');
return;

function editDesiredSamples_Callback(hObject, eventdata, handles)
menuEditRefresh_Callback(gcbf);
return

% --- Executes during object creation, after setting all properties.
function editDesiredSamples_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
return;

function editMaxNodes_Callback(hObject, eventdata, handles)
menuEditRefresh_Callback(gcbf);
return;
% --- Executes during object creation, after setting all properties.
function editMaxNodes_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
return;

function editMinNodes_Callback(hObject, eventdata, handles)
menuEditRefresh_Callback(gcbf);
return;

% --- Executes during object creation, after setting all properties.
function editMinNodes_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
return;

function editStepSize_Callback(hObject, eventdata, handles)
menuEditRefresh_Callback(gcbf);
return;

% --- Executes during object creation, after setting all properties.
function editStepSize_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
return;

% --------------------------------------------------------------------
function menuHelp_Callback(hObject, eventdata, handles)
return;

% --------------------------------------------------------------------
function menuEditClearFilenames_Callback(hObject, eventdata, handles)
% Edit | Clear file names

gd = guidata(hObject);

set(gd.editFilenameDti6,'String','');
set(gd.editFilenameROI1,'String','');
set(gd.editFilenameROI2,'String','');
set(gd.editWaypointFilename,'String','');

return;

% --------------------------------------------------------------------
function menuEditResetDefaultParameters_Callback(hObject, eventdata, handles)
disp('Todo: Reset default parameters');
return

% --- Executes on button press in checkboxROI1.
function checkboxROI1_Callback(hObject, eventdata, handles)
menuEditRefresh_Callback(gcbf);
return

% --- Executes on button press in checkboxROI2.
function checkboxROI2_Callback(hObject, eventdata, handles)
menuEditRefresh_Callback(gcbf);
return

% --- Executes on button press in checkboxPDDPDF.
function checkboxPDDPDF_Callback(hObject, eventdata, handles)
menuEditRefresh_Callback(gcbf);
return

% --- Executes on button press in checkboxWMFile.
function checkboxWMFile_Callback(hObject, eventdata, handles)
menuEditRefresh_Callback(gcbf);
return

% --------------------------------------------------------------------
function menuEditFullParameters_Callback(hObject, eventdata, handles)
disp('ToDO:  Bring up window with full parameter list and store the list');

params = getParams(hObject);
[params]=ctrSetParamsDlg(hObject,params);
menuEditRefresh_Callback(gcbf);
%guidata(hObject);
return;

% --------------------------------------------------------------------
function menuEditRefresh_Callback(hObject, eventdata, handles)
% Edit | Refresh
% Updates changes to the information panel

gd = guidata(hObject);

% File name section - Show user computed file names
str = get(gd.editFilenameDti6,'String');
if isempty(str), return; end

% Otherwise, we fill in some of the fields: Subject directory
subjDir = fileparts(str);
if length(subjDir) > 30, str = subjDir((end-30):end); else str = subjDir; end
txt = sprintf('Subject''s DT6 dir: ... %s\n\n',str);

% Processed ROI file, derived from names and a time stamp. We should
% probably store the time stamp in the guidata of the window. Perhaps we
% update the time stamp whenever we change a file name?
[p,str1] = fileparts(get(gd.editFilenameROI1,'String'));
[p,str2] = fileparts(get(gd.editFilenameROI2,'String'));
tString = get(gd.txtTimeStamp,'String');
str = ctrFilename(str1,str2,tString,'roi');
txt = sprintf('%sROI mask: %s\n\n',txt,str);

% Attach the text to the window
set(gd.txtInfo,'String',txt);

return;

% --- Executes on button press in btnTimeStamp.
function btnTimeStamp_Callback(hObject, eventdata, handles)
% Time Stamp button

gd  = guidata(hObject);
str = datestr(now,30);
set(gd.txtTimeStamp,'String',str);
menuEditRefresh_Callback(hObject);

return;

%---------------
function params = getParams(hObject)
% Create the parameters structure that we send to ctInitParams

hndl = guidata(hObject);

% Figure out what the user selected and send it to the script that
% generates the fibers.
params.dt6File      = get(hndl.editFilenameDti6,'String');
params.roi1File     = get(hndl.editFilenameROI1,'String');
params.roi2File     = get(hndl.editFilenameROI2,'String');
params.dSamples     = str2double(get(hndl.editDesiredSamples','string'));
params.maxNodes     = str2double(get(hndl.editMaxNodes','string'));
params.minNodes     = str2double(get(hndl.editMinNodes','string'));
params.stepSize     = str2double(get(hndl.editStepSize','string'));
params.pddpdf       = get(hndl.checkboxPDDPDF,'Value');
params.wm           = get(hndl.checkboxWMFile,'Value');
params.roi1Seed     = get(hndl.checkboxROI1,'Value');
params.roi2Seed     = get(hndl.checkboxROI2,'Value');
params.timeStamp    = get(hndl.txtTimeStamp,'String');

return;

%--------------

function setParams(hObject,ctr)
% Set the interface based on the contrack parameters structure

if notDefined('ctr'), error('contrack structure required.'); end

hndl = guidata(hObject);

%Copy the contrack structure to the interface
%The ctr structure could have more stuff, like this file information

% set(hndl.editFilenameDti6,'String',params.dt6File);
% set(hndl.editFilenameROI1,'String',params.roi1File);
% set(hndl.editFilenameROI2,'String',params.roi2File);
% set(hndl.editWaypointFilename,'String',params.wayPointFile);

set(hndl.editDesiredSamples,'string',num2str(ctrGet(ctr,'desired_samples')));
set(hndl.editMaxNodes,'string',num2str(ctrGet(ctr,'max_nodes')));
set(hndl.editMinNodes,'string',num2str(ctrGet(ctr,'min_nodes')));
set(hndl.editStepSize,'string',num2str(ctrGet(ctr,'step_size')));
set(hndl.checkboxWMFile,'Value',1);
set(hndl.checkboxROI1,'Value',1);
set(hndl.checkboxROI2,'Value',1);
set(hndl.txtTimeStamp,'String',datestr(now,30));

menuEditRefresh_Callback(hObject);

return;

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


function test_pull1271

% MEM 5gb
% WALLTIME 00:20:00
% DEPENDENCY ft_read_data ft_read_header ft_read_event

% the DCCNPATH function will take the file from the present working directory if possible
% otherwise it will search on /home/common/matlab (a DCCN specific linux network drive)
% and if that fails it will search on H:\common\matlab (the windows version of that network drive)
%
% cd '/Users/alan/Dropbox/Lab-BML/Code/[2020.04]Fieldtrip_Neuroomega_nsx_PR';

fname_nsx         = dccnpath('/home/common/matlab/fieldtrip/data/test/original/eeg/blackrock/test_data_blackrock.ns2');
fname_neuroomega  = dccnpath('/home/common/matlab/fieldtrip/data/test/original/eeg/neuroomega/LT1D0.000F0000.mat');

%% loading blackrock header and data
hdr_nsx=ft_read_header(fname_nsx);
ft_read_data(fname_nsx,'header',hdr_nsx);

%% loading neuroomega header, events and data
hdr_neuroomega=ft_read_header(fname_neuroomega,'chantype','micro');
ft_read_data(fname_neuroomega,'header',hdr_neuroomega);
ft_read_event(fname_neuroomega);


classdef AnimatorPointOfView < uint8
    % The list of animator point of view
    %
    % @author omar @date 2017-06-01
    %
    % Copyright (c) 2017, UMICH Biped Lab
    % All right reserved.
    %
    % Redistribution and use in source and binary forms, with or without
    % modification, are permitted only in compliance with the BSD 3-Clause
    % license, see
    % http://www.opensource.org/licenses/BSD-3-Clause

    enumeration
        North (0)
        South (1)
        East (2)
        West (3)
        Front (5)
        Back (6)
        Right (7)
        Left (8)
        TopSouthEast (9)
        TopFrontLeft (10)
        Free (256)
    end
end


% Main camera calibration toolbox:
format compact


function planC = quality_assure_planC(fileName, planC, forceSaveFlag)
%function planC = quality_assure_planC(fileName, planC, forceSaveFlag)
%
% This function quality assures planC.
%
%APA, 04/07/2011

if ~exist('planC','var')
    global planC
end
if ~exist('forceSaveFlag','var')
    forceSaveFlag = 0;
end

global stateS
indexS = planC{end};

% Quality Assurance
bug_found = 0;

% Detect and Fix incorrect rasterSegments
if length(planC{indexS.header})>0 && isfield(planC{indexS.header}(1), 'lastSavedInVer')
    lastSavedInVer = planC{indexS.header}(1).lastSavedInVer;
else
    lastSavedInVer = '';
end

if ~isempty(str2double(lastSavedInVer)) && (isempty(lastSavedInVer) || str2double(lastSavedInVer) < 4.1) && ~isempty(planC{indexS.structures})
    planC = reRasterAndUniformize(planC);
    bug_found = 1;
end

%Update imageType for CT scans where required
for nScan = 1:length(planC{indexS.scan})
    if strcmpi(planC{indexS.scan}(nScan).scanInfo(1).imageType,'CT')
        [planC{indexS.scan}(nScan).scanInfo(:).imageType] = deal('CT SCAN');
    end
end

% %Check for mesh representation and load meshes into memory
% currDir = cd;
% meshDir = fileparts(which('libMeshContour.dll'));
% cd(meshDir)
% for strNum = 1:length(planC{indexS.structures})
%     if isfield(planC{indexS.structures}(strNum),'meshRep') && ~isempty(planC{indexS.structures}(strNum).meshRep) && planC{indexS.structures}(strNum).meshRep
%         try
%             calllib('libMeshContour','loadSurface',planC{indexS.structures}(strNum).strUID,planC{indexS.structures}(strNum).meshS)
%         catch
%             planC{indexS.structures}(strNum).meshRep    = 0;
%             planC{indexS.structures}(strNum).meshS      = [];
%         end
%     end
% end
% cd(currDir)

if ~isfield(stateS,'optS')
    stateS.optS = opts4Exe([getCERRPath,'CERROptions.json']);
end

%Check color assignment for displaying structures
[assocScanV,relStrNumV] = getStructureAssociatedScan(1:length(planC{indexS.structures}),planC);
for scanNum = 1:length(planC{indexS.scan})
    scanIndV = find(assocScanV==scanNum);
    for i = 1:length(scanIndV)
        strNum = scanIndV(i);
        colorNum = relStrNumV(strNum);
        if isempty(planC{indexS.structures}(strNum).structureColor)
            color = stateS.optS.colorOrder( mod(colorNum-1, size(stateS.optS.colorOrder,1))+1,:);
            planC{indexS.structures}(strNum).structureColor = color;
        end
    end
    % Check for scanType field and populate it with Series description
    if isempty(planC{indexS.scan}(scanNum).scanType) && ...
            isfield(planC{indexS.scan}(scanNum).scanInfo(1),'DICOMHeaders') && ...
            isfield(planC{indexS.scan}(scanNum).scanInfo(1).DICOMHeaders,'SeriesDescription')
        planC{indexS.scan}(scanNum).scanType = planC{indexS.scan}(scanNum).scanInfo(1).DICOMHeaders.SeriesDescription;
    end
    % Save SOPInstanceUID and SOPClassUID within scanInfo
    if ~isfield(planC{indexS.scan}(scanNum).scanInfo(1),'sopInstanceUID') || ...
            isempty(planC{indexS.scan}(scanNum).scanInfo(1).sopInstanceUID) || ...
            isempty(planC{indexS.scan}(scanNum).scanInfo(1).patientID) || ...
            isempty(planC{indexS.scan}(scanNum).scanInfo(1).frameOfReferenceUID)
        if isfield(planC{indexS.scan}(scanNum).scanInfo(1),'DICOMHeaders') ...
                && ~isempty(planC{indexS.scan}(scanNum).scanInfo(1).DICOMHeaders)
            for slcNum = 1:length(planC{indexS.scan}(scanNum).scanInfo)
                planC{indexS.scan}(scanNum).scanInfo(slcNum).sopInstanceUID = ...
                    planC{indexS.scan}(scanNum).scanInfo(slcNum).DICOMHeaders.SOPInstanceUID;
                planC{indexS.scan}(scanNum).scanInfo(slcNum).sopClassUID = ...
                    planC{indexS.scan}(scanNum).scanInfo(slcNum).DICOMHeaders.SOPClassUID;
                planC{indexS.scan}(scanNum).scanInfo(slcNum).seriesInstanceUID = ...
                    planC{indexS.scan}(scanNum).scanInfo(slcNum).DICOMHeaders.SeriesInstanceUID;
                %                 planC{indexS.scan}(scanNum).scanInfo(slcNum).patientBirthDate = ...
                %                     planC{indexS.scan}(scanNum).scanInfo(slcNum).DICOMHeaders.PatientBirthDate;
                if isfield(planC{indexS.scan}(scanNum).scanInfo(slcNum).DICOMHeaders,'FrameofReferenceUID')
                    planC{indexS.scan}(scanNum).scanInfo(slcNum).frameOfReferenceUID = ...
                        planC{indexS.scan}(scanNum).scanInfo(slcNum).DICOMHeaders.FrameofReferenceUID;
                end
                if isfield(planC{indexS.scan}(scanNum).scanInfo(slcNum).DICOMHeaders,'PatientID')
                    planC{indexS.scan}(scanNum).scanInfo(slcNum).patientID = ...
                        planC{indexS.scan}(scanNum).scanInfo(slcNum).DICOMHeaders.PatientID;
                end
                if isfield(planC{indexS.scan}(scanNum).scanInfo(slcNum).DICOMHeaders,'StudyDate')
                    planC{indexS.scan}(scanNum).scanInfo(slcNum).studyDate = ...
                        planC{indexS.scan}(scanNum).scanInfo(slcNum).DICOMHeaders.StudyDate;
                end
                if isfield(planC{indexS.scan}(scanNum).scanInfo(slcNum).DICOMHeaders,'StudyTime')
                    planC{indexS.scan}(scanNum).scanInfo(slcNum).studyTime = ...
                        planC{indexS.scan}(scanNum).scanInfo(slcNum).DICOMHeaders.StudyTime;
                end

            end
        end
    end
    % Save StudyDate and StudyTime within scanInfo
    if ~isfield(planC{indexS.scan}(scanNum).scanInfo(1),'StudyDate') || ...
            isempty(planC{indexS.scan}(scanNum).scanInfo(1).StudyDate)
        if isfield(planC{indexS.scan}(scanNum).scanInfo(1),'DICOMHeaders') ...
                && ~isempty(planC{indexS.scan}(scanNum).scanInfo(1).DICOMHeaders)
            for slcNum = 1:length(planC{indexS.scan}(scanNum).scanInfo)
                if isfield(planC{indexS.scan}(scanNum).scanInfo(slcNum).DICOMHeaders,'StudyDate')
                    planC{indexS.scan}(scanNum).scanInfo(slcNum).studyDate = ...
                        planC{indexS.scan}(scanNum).scanInfo(slcNum).DICOMHeaders.StudyDate;
                end
                if isfield(planC{indexS.scan}(scanNum).scanInfo(slcNum).DICOMHeaders,'StudyTime')
                    planC{indexS.scan}(scanNum).scanInfo(slcNum).studyTime = ...
                        planC{indexS.scan}(scanNum).scanInfo(slcNum).DICOMHeaders.StudyTime;
                end
            end
        end
    end
    % Save image orientation to scanInfo
    if ~isfield(planC{indexS.scan}(scanNum).scanInfo(1),'imageOrientationPatient') || ...
            isempty(planC{indexS.scan}(scanNum).scanInfo(1).imageOrientationPatient)
        if isfield(planC{indexS.scan}(scanNum).scanInfo(1).DICOMHeaders,'ImageOrientationPatient')
            imgOriV = planC{indexS.scan}(scanNum).scanInfo(1).DICOMHeaders.ImageOrientationPatient;
            [planC{indexS.scan}(scanNum).scanInfo(:).imageOrientationPatient] = deal(imgOriV);
        end
    end
    if ~isfield(planC{indexS.scan}(scanNum).scanInfo(1),'imagePositionPatient') || ...
            isempty(planC{indexS.scan}(scanNum).scanInfo(1).imagePositionPatient)
        if isfield(planC{indexS.scan}(scanNum).scanInfo(1).DICOMHeaders,'ImagePositionPatient')
            for slc = 1:length(planC{indexS.scan}(scanNum).scanInfo)
                planC{indexS.scan}(scanNum).scanInfo(slc).imagePositionPatient = ...
                    planC{indexS.scan}(scanNum).scanInfo(slc).DICOMHeaders.ImagePositionPatient;
            end
        end
    end
end

%Check dose-grid
for doseNum = 1:length(planC{indexS.dose})
    if length(planC{indexS.dose}(doseNum).zValues) > 1
        if planC{indexS.dose}(doseNum).zValues(2) - planC{indexS.dose}(doseNum).zValues(1) < 0
            planC{indexS.dose}(doseNum).zValues = flipud(planC{indexS.dose}(doseNum).zValues);
            %planC{indexS.dose}(doseNum).doseArray = flipdim(planC{indexS.dose}(doseNum).doseArray,3);
            planC{indexS.dose}(doseNum).doseArray = flip(planC{indexS.dose}(doseNum).doseArray,3);
        end
    end
    % Save image orientation and position to dose field
    if ~isfield(planC{indexS.dose}(doseNum),'imageOrientationPatient') || ...
            isempty(planC{indexS.dose}(doseNum).imageOrientationPatient)
        if isfield(planC{indexS.dose}(doseNum).DICOMHeaders,'ImageOrientationPatient')
            imgOriV = planC{indexS.dose}(doseNum).DICOMHeaders.ImageOrientationPatient;
            planC{indexS.dose}(doseNum).imageOrientationPatient = imgOriV;
        end
    end
    if ~isfield(planC{indexS.dose}(doseNum),'imagePositionPatient') || ...
            isempty(planC{indexS.dose}(doseNum).imagePositionPatient)
        if isfield(planC{indexS.dose}(doseNum).DICOMHeaders,'ImagePositionPatient')
            imgPosV = planC{indexS.dose}(doseNum).DICOMHeaders.ImagePositionPatient;
            planC{indexS.dose}(doseNum).imagePositionPatient = imgPosV;
        end
    end
end

%Check whether uniformized data is in cellArray format.
if ~isempty(planC{indexS.structureArray}) && iscell(planC{indexS.structureArray}(1).indicesArray)
    planC = setUniformizedData(planC,planC{indexS.CERROptions});
    indexS = planC{end};
end

if length(planC{indexS.structureArrayMore}) ~= length(planC{indexS.structureArray})
    for saNum = 1:length(planC{indexS.structureArray})
        if saNum == 1
            planC{indexS.structureArrayMore} = struct('indicesArray', {[]},...
                'bitsArray', {[]},...
                'assocScanUID',{planC{indexS.structureArray}(saNum).assocScanUID},...
                'structureSetUID', {planC{indexS.structureArray}(saNum).structureSetUID});

        else
            planC{indexS.structureArrayMore}(saNum) = struct('indicesArray', {[]},...
                'bitsArray', {[]},...
                'assocScanUID',{planC{indexS.structureArray}(saNum).assocScanUID},...
                'structureSetUID', {planC{indexS.structureArray}(saNum).structureSetUID});
        end
    end
end

% Get CERR version of last save
if length(planC{indexS.header})>0 &&...
        isfield(planC{indexS.header},'lastSavedInVer')...
        && ~isempty(planC{indexS.header}.lastSavedInVer)
    CERRImportVersion = planC{indexS.header}.lastSavedInVer;
elseif length(planC{indexS.header})>0 && ...
        isfield(planC{indexS.header},'CERRImportVersion')...
        && ~isempty(planC{indexS.header}.CERRImportVersion)
    CERRImportVersion = planC{indexS.header}.CERRImportVersion;
else
    CERRImportVersion = '0';
end

%Check DSH Points for old CERR versions
if str2num(CERRImportVersion(1)) < 4
    bug_found = 1;
    for structNum = 1:length(planC{indexS.structures})
        if ~isempty(planC{indexS.structures}(structNum).DSHPoints)
            planC = getDSHPoints(planC, stateS.optS, structNum);
        end
    end
end

% Fix RTOG orientation for HFP scans
if str2num(strtok(CERRImportVersion, ',')) < 5.2
    for scanNum = 1:length(planC{indexS.scan})
        if isfield(planC{indexS.scan}(scanNum).scanInfo(1),'DICOMHeaders') ...
                && ~isempty(planC{indexS.scan}(scanNum).scanInfo(1).DICOMHeaders) ...
                && isfield(planC{indexS.scan}(scanNum).scanInfo(1).DICOMHeaders,'PatientPosition')
            %pPos = planC{indexS.scan}(scanNum).scanInfo(1).DICOMHeaders.PatientPosition;
            imgOriV = planC{indexS.scan}(scanNum).scanInfo(1).DICOMHeaders.ImageOrientationPatient;
        else
            %pPos = '';
            imgOriV = [];
        end
        if  ~isempty(imgOriV) && max(abs((imgOriV(:) - [-1 0 0 0 -1 0]'))) < 1e-3 % Position: HFP
            planC = flipAlongX(scanNum, planC);
            bug_found = 1;
        end
    end
end

% Add radiopharma params to scanInfo
for scanNum = 1:length(planC{indexS.scan})
    if isfield(planC{indexS.scan}(scanNum).scanInfo(1),'DICOMHeaders') ...
            && ~isempty(planC{indexS.scan}(scanNum).scanInfo(1).DICOMHeaders) ...
            && any(strcmpi(planC{indexS.scan}(scanNum).scanInfo(1).imageType,{'PT','PET'})) ...
            && isempty(planC{indexS.scan}(scanNum).scanInfo(1).decayCorrection)
        for slcNum = 1:size(planC{indexS.scan}(scanNum).scanArray,3)
            dicomhd = planC{indexS.scan}(scanNum).scanInfo(slcNum).DICOMHeaders;
            ptweight = [];
            if isfield(dicomhd,'PatientWeight')
                ptweight = dicomhd.PatientWeight;
            elseif isfield(dicomhd,'PatientsWeight')
                ptweight = dicomhd.PatientsWeight;
            end
            if isempty(dicomhd.RadiopharmaceuticalInformationSequence)
                continue;
            end
            injectionTime = ...
                dicomhd.RadiopharmaceuticalInformationSequence.Item_1.RadiopharmaceuticalStartTime;
            halfLife = ...
                dicomhd.RadiopharmaceuticalInformationSequence.Item_1.RadionuclideHalfLife;
            injectedDose = ...
                dicomhd.RadiopharmaceuticalInformationSequence.Item_1.RadionuclideTotalDose;
            seriesTime = dicomhd.SeriesTime;
            decayCorrection = dicomhd.DecayCorrection;
            correctedImage = dicomhd.CorrectedImage;
            imageUnits = dicomhd.Units;
            petActivityConcentrationScaleFactor = [];
            if isfield(dicomhd,'ActivityConcentrationScaleFactor')
                petActivityConcentrationScaleFactor = ...
                    dicomhd.ActivityConcentrationScaleFactor;
            end
            patientSize = [];
            if isfield(dicomhd,'PatientSize')
                patientSize = dicomhd.PatientSize;
            end

            planC{indexS.scan}(scanNum).scanInfo(slcNum).patientWeight = ...
                ptweight;
            planC{indexS.scan}(scanNum).scanInfo(slcNum).patientSize = ...
                patientSize;
            planC{indexS.scan}(scanNum).scanInfo(slcNum).petActivityConcentrationScaleFactor = ...
                petActivityConcentrationScaleFactor;
            planC{indexS.scan}(scanNum).scanInfo(slcNum).acquisitionTime = ...
                dicomhd.AcquisitionTime;
            planC{indexS.scan}(scanNum).scanInfo(slcNum).injectionTime = ...
                injectionTime;
            planC{indexS.scan}(scanNum).scanInfo(slcNum).halfLife = ...
                halfLife;
            planC{indexS.scan}(scanNum).scanInfo(slcNum).injectedDose = ...
                injectedDose;
            planC{indexS.scan}(scanNum).scanInfo(slcNum).seriesTime = ...
                seriesTime;
            planC{indexS.scan}(scanNum).scanInfo(slcNum).decayCorrection = ...
                decayCorrection;
            planC{indexS.scan}(scanNum).scanInfo(slcNum).correctedImage = ...
                correctedImage;
            planC{indexS.scan}(scanNum).scanInfo(slcNum).imageUnits = ...
                imageUnits;

        end
    end
end

% Check for GSPS and make it empty if no objects are present
if length(planC{indexS.GSPS}) == 1 && isempty(planC{indexS.GSPS}.SOPInstanceUID)
    planC{indexS.GSPS}(1) = [];
end

% Check for IM UIDs
if ~isempty(planC{indexS.IM}) && isfield(planC{indexS.IM}(1),'IMUID') && isempty(planC{indexS.IM}(1).IMUID)
    planC = createIMuids(planC);
end

% Check visible flag for structures. Set it to 1 if it is an empty string
for i = 1:length(planC{indexS.structures})
    if isempty(planC{indexS.structures}(i).visible)
        planC{indexS.structures}(i).visible = 1;
    end
end

% Overwrite the existing CERR file if a bug is found and fixed
if forceSaveFlag == 1 || (~isempty(stateS) && isfield(stateS.optS,'overwrite_CERR_File') && stateS.optS.overwrite_CERR_File == 1 && bug_found)
    try
        if exist('fileName','var')
            % do nothing
        elseif isfield(stateS,'CERRFile')
            fileName = stateS.CERRFile;
        end
        planC = save_planC(planC, stateS.optS, 'passed', fileName);
    catch
        disp('Could not overwrite the exisitng file. Please save manually')
    end
end


function r = uplus(p)
%UMINUS: this function applies a unary minus to the x, y, and z values of the structures that I use in
% the FVtool.
%
% SYNOPSIS:
%
%
% PARAMETERS:
%
%
% RETURNS:
%
%
% EXAMPLE:
%
% SEE ALSO:
%

% Copyright (c) 2012-2016 Ali Akbar Eftekhari
% See the license file

r=p;


function [success] = convertInscopixIsxdToHdf5(inputFilePath,varargin)
	% Converts Inscopix proprietary ISXD to HDF5.
	% By default all dropped frames are included in the output as a frame full of zeros.
	% Biafra Ahanonu
	% started: 2019.01.15 [21:17:45]
	% inputs
		% inputMoviePath - char: path to ISXD file.
	% outputs
		%
	% changelog
		% 2022.01.26 [07:46:01] - Update +image package to +inscopix.

	[success] = ciapkg.inscopix.convertInscopixIsxdToHdf5(inputFilePath,'passArgs', varargin);
end


base64 = org.apache.commons.codec.binary.Base64;
tsv_file = 'MsCelebV1-Faces-Cropped.Samples.tsv';

root_folder = 'data';
mkdir(root_folder);

tsv_fid = fopen(tsv_file, 'r');
total_lines = 3481187;
image_id = 1;
while ~feof(tsv_fid)
    line = fgetl(tsv_fid);%MID,EntityNameString,ImageURL,FaceID,FaceRectangle_Base64Encoded,FaceData_Base64Encoded
    C = strsplit(line,'\t');
    folder = fullfile(root_folder,C{1});
    if exist(folder,'dir')==0
        mkdir(folder);
    end;
    filename = fullfile(folder,[C{2} '-' C{5} '.jpg']);
    raw  = base64decode(C{7});
%     img_fid = fopen(filename, 'wb');
%     fwrite(img_fid, raw, 'uint8');
%     fclose(img_fid);
    jImg = javax.imageio.ImageIO.read(java.io.ByteArrayInputStream(raw));
    h = jImg.getHeight;
    w = jImg.getWidth;
    p = typecast(jImg.getData.getDataStorage, 'uint8');
    img = permute(reshape(p, [3 w h]), [3 2 1]);
    img = img(:,:,[3 2 1]);
    imshow(img);
    disp([num2str(image_id) '/' num2str(total_lines) ' ' filename]);
    image_id = image_id + 1;
end;
fclose(tsv_fid);


function spm_cli(varargin)
% Command line interface for SPM
%__________________________________________________________________________
% Copyright (C) 2016 Wellcome Trust Centre for Neuroimaging

% Guillaume Flandin
% $Id: spm_cli.m 6964 2016-12-07 16:50:41Z guillaume $

%-Input arguments
%--------------------------------------------------------------------------
if isempty(varargin), return; end
if nargin == 1 && ismember(varargin{1},{'help','--help'})
    cmd = lower(spm('Ver'));
    fprintf([...
        'Usage: %s [NODE] [arg...]\n',...
        '       %s [NODE] help\n',...
        '       %s [ help | --help ]\n',...
        '       %s help --verbose\n',...
        '\n',...
        '[NODE]         Batch node name\n',...
        '--verbose      List all available batch nodes\n',...
        '--help, help   Print usage statement\n'],...
        cmd, cmd, cmd, cmd);
        return
end
if nargin == 2 ...
        && all(ismember(strtok(varargin(1:2),'-'),{'help','verbose'}))
    c0 = cfg_util('getcfg');
    nodes = find_all_modules(c0.values{1})';
    for i=1:numel(nodes)
        [n, c] = find_module(strsplit(nodes{i},'.'), c0);
        h = normalise_help_text(c.help);
        if ~c.hidden, fprintf('  %s    %s\n',nodes{i},h{1}); end
    end
    return
end
node = strsplit(varargin{1},'.');
opts = varargin(2:end);

%-Get the configuration tree
%--------------------------------------------------------------------------
try
    c0 = cfg_util('getcfg');
catch
    spm_jobman('initcfg');
    c0 = cfg_util('getcfg');
end

%-Search module in configuration tree and allow for node shortcut
% (use first matching module if ambiguity)
%--------------------------------------------------------------------------
[n, c0, found] = find_module(node, c0);

if ~found
    error('Cannot find module %s.\n',strjoin(node,'.'));
else
    n = n(2:end); % first is matlabbatch
    if ~isequal(n,node)
        node = n;
        fprintf('Matching module %s.\n',strjoin(node,'.'));
    end
end

%-Help for a specific node
%--------------------------------------------------------------------------
if numel(opts) == 1 && ismember(opts{1},{'help','--help'})
    cmd = lower(spm('Ver'));
    fprintf([...
        'Usage: %s %s [OPTIONS]\n',...
        '\n',...
        'Options:\n'],...
        cmd,strjoin(node,'.'));
    [flags, h1s, ms] = get_items(c0);
    n = cellfun(@numel,flags);
    for i=1:numel(flags)
        if ms(i), m = '(*) '; else m = ''; end
        fprintf('    --%s%s%s%s\n',flags{i},repmat(' ',1,3+max(n)-n(i)),m,h1s{i});
    end
    fprintf([...
        '\n',...
        '    --help%sPrint usage statement\n'],repmat(' ',1,3+max(n)-4));
    return;
end

%-Get options
%--------------------------------------------------------------------------
i = 1;
params = {};
values = {};
while i <= numel(opts)
    flag = strtok(opts{i},'-');
    opt = {};
    i = i + 1;
    for j=i:numel(opts)
        if opts{j}(1) == '-', break; end
        opt{end+1} = opts{j};
        i = i + 1;
    end
    params{end+1} = flag;
    values{end+1} = opt;
end

%-Create batch job structure
%--------------------------------------------------------------------------
job = struct();
for i=1:numel(params)
    prm = params{i};
    if ~any(prm == '.')
        subs = substruct('.',prm);
    else
        clear subs
        p = strsplit(prm,'.');
        for j=1:numel(p)
            subs(j) = substruct('.',p{j});
        end
        prm = p{end};
    end
    job = subsasgn(job, subs, get_val(values{i},prm,c0));
end

%-Execute batch job
%--------------------------------------------------------------------------
subs = reshape([repmat({'.'},1,numel(node));node],1,[]);
subs = substruct(subs{:});
job  = subsasgn(struct(),subs,job);
cfg_message('none','destination','^matlabbatch:run:jobstart$');
cfg_message('none','destination','^matlabbatch:run:jobdone$');
cfg_message('none','destination','^matlabbatch:run:jobfailed$');
cfg_message('none','destination','^matlabbatch:run:modstart$');
cfg_message('none','destination','^matlabbatch:run:moddone$');
%cfg_message('none','destination','^matlabbatch:run:modfailed$');
try
    [out, job] = spm_jobman('run', {job});
catch
    err = lasterror;
    switch err.identifier
        case 'spm:spm_jobman:jobNotFilled'
            error('Incomplete job.');
        case 'matlabbatch:run:jobfailederr'
            error('Job failed.');
        otherwise
            error('Unknown error during job execution.');
    end
end

%==========================================================================
function [node, c0, found] = find_module(node, c0, found)

if nargin < 3, found = false; end
if found, return; end
if strcmp(node{1}, c0.tag)
    if numel(node) == 1
        if isa(c0,'cfg_exbranch'), found = true; end
    else
        if ~isa(c0,'cfg_exbranch')
            for i=1:numel(c0.values)
                [n, c1 , found] = find_module(node(2:end), c0.values{i});
                if found, node = [c0.tag n]; c0 = c1; return; end
            end
        end
    end
else
    if ~isa(c0,'cfg_exbranch')
        for i=1:numel(c0.values)
            [n, c1, found] = find_module(node, c0.values{i});
            if found, node = [c0.tag n]; c0 = c1; return; end
        end
    end
end

%==========================================================================
function [nodes,n] = find_all_modules(c0,nodes,n)

if nargin < 2, nodes = {}; end
if nargin < 3, n = {}; end
if isa(c0,'cfg_exbranch')
    nodes = [nodes strjoin([n c0.tag],'.')];
else
    m = n;
    for i=1:numel(c0.values)
        [nodes, n] = find_all_modules(c0.values{i},nodes,[m c0.tag]);
    end
end

%==========================================================================
function param = get_val(param,flag,c0)

for i=1:numel(c0.val)
    if strcmp(c0.val{i}.tag, flag)
        switch class(c0.val{i})
            case 'cfg_files'
                param = param(:);
            case 'cfg_entry'
                switch c0.val{i}.strtype
                    case {'n','w','r'}
                        param = str2num(char(param));
                    case {'s'}
                        param = char(param);
                end
            case 'cfg_menu'
                if numel(param) > 1
                    error('Only one value accepted for "%s".',flag);
                end
                param = char(param);
                labels = c0.val{i}.labels;
                j = find(ismember(labels,param));
                if nnz(j)
                    param = c0.val{i}.values{j};
                else
                    opts = sprintf('  "%s"\n',labels{:});
                    error(['Cannot translate option "%s": %s.\n',...
                        'Options are:\n%s'],flag, param, opts);
                end
            otherwise
        end
        return;
    end
end
for i=1:numel(c0.val)
    switch class(c0.val{i})
        case 'cfg_branch'
            param = get_val(param,flag,c0.val{i});
        case 'cfg_repeat'
        case 'cfg_choice'
    end
end

%==========================================================================
function [flags, h1s, ms] = get_items(c0)
flags = {}; h1s = {}; ms = [];
for i=1:numel(c0.val) % go recursive instead
    flag = {}; h1 = {}; m = [];
    if isa(c0.val{i},'cfg_repeat')
        % if more than one, they are not stored yet
        for j=1:numel(c0.val{i}.values)
            [flag, h1, m] = get_items(c0.val{i}.values{j});
            flag = [{c0.val{i}.values{j}.tag} flag];
            h1   = [{char(c0.val{i}.values{j}.help{:})} h1];
            m    = [is_mandatory(c0.val{i}.values{j}) m];
        end
    elseif isa(c0.val{i},'cfg_branch')
        [flag, h1, m] = get_items(c0.val{i});
        flag = [{c0.val{i}.tag} flag];
        h1   = [{char(c0.val{i}.help{:})} h1];
        m    = [is_mandatory(c0.val{i}) m];
    else
        flag = c0.val{i}.tag;
        h1   = char(c0.val{i}.help{:});
        m    = is_mandatory(c0.val{i});
    end
    h1    = normalise_help_text(h1);
    flags = [flags flag];
    h1s   = [h1s h1];
    ms    = [ms m];
end

%==========================================================================
function m = is_mandatory(item)
m = isempty(item.val) && isempty(item.def);

%==========================================================================
function h1 = normalise_help_text(h1)
h1 = cellstr(h1);
for i=1:numel(h1)
    if ~isempty(h1{i}) && h1{i}(end) == '.', h1{i} = h1{i}(1:end-1); end
    if numel(h1{i}) > 70 % use "stty size" to get the number of columns
        h1{i} = [h1{i}(1:70-3) '...'];
    end
end


classdef Tx < adi.AD9364.Tx
    % adi.FMComms4.Tx Transmit data from the FMComms4 evaluation board
    %   The adi.FMComms4.Tx System object is a signal sink that can
    %   transmit complex data from the FMComms4.
    %
    %   tx = adi.FMComms4.Tx;
    %   tx = adi.FMComms4.Tx('uri','192.168.2.1');
    %
    %   Product Page
    %
    %   See also adi.AD9364.Tx
    methods
        %% Constructor
        function obj = Tx(varargin)
            % Returns the matlabshared.libiio.base object
            coder.allowpcode('plain');
            obj = obj@adi.AD9364.Tx(varargin{:});
        end
    end

end


function writeMovie(path,vid)
% *************************************************************************
% Superresolution with Dictionary Technique
% writeMovie
%
% Saves an input video as an uncompressed grayscale video
%
% Version 1.0
%
% Created by:   Armin Kappeler
% Date:         03/27/2013
%
% Modifications:
%
% *************************************************************************
property = 'Uncompressed AVI';

writerObj = VideoWriter(path,property);
open(writerObj);

for k = 1:length(vid)
   writeVideo(writerObj,im2uint8(vid{k}));
end

% Create AVI file.
close(writerObj);

end


function planDBGUI(action, varargin)
% Gui to access and browse data in planDB.
% 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/>.

if(nargin == 0)
    action = 'init';
end

switch upper(action)
    case 'INIT'
		screenSize = get(0,'ScreenSize');
		y = 700; %Initial size of figure in pixels.
		x = 700;

		h = figure('position', [(screenSize(3)-x)/2 (screenSize(4)-y)/2 x y], 'units', 'normalized');
        set(h, 'resizefcn', 'myResize');

        ud = []; %init UD.
		%Make bottom Axis, table it
		ud.handles.botAxis = axes('position', [.25 .05 .7 .4]);
   		table(ud.handles.botAxis);
        table(ud.handles.botAxis, 'SETDBCALLBACK', 'planDBGUI(''planclicked'')');

        %Make top Axis, table it
		ud.handles.topAxis = axes('position', [.25 .67 .7 .28]);
  		table(ud.handles.topAxis);
        table(ud.handles.topAxis, 'SETDBCALLBACK', 'planDBGUI(''fieldclicked'')');

        ud.handles.midAxis = axes('position', [.25 .55 .7 .1]);
  		table(ud.handles.midAxis);
        table(ud.handles.midAxis,'SETDBCALLBACK',  'planDBGUI(''filterclicked'')');

        %Init upper planDB controls
        uicontrol('style', 'frame', 'units', 'normalized', 'position', [.025 .55 .2 .4]);
        ud.handles.searchBox = uicontrol('style', 'edit', 'units', 'normalized', 'position', [.05 .875 .15 .03], 'callback', 'planDBGUI(''SEARCHENTERED'');', 'backgroundcolor', [1 1 1]);
        uicontrol('style', 'text', 'units', 'normalized', 'position', [.05 .84 .15 .03], 'string', 'Search Fieldnames');
        ud.handles.clearFieldFilter = uicontrol('style', 'pushbutton', 'string', 'Clear Search', 'units', 'normalized', 'position', [.05 .78 .15 .05], 'callback', 'planDBGUI(''clearFieldFilter'');');

        ud.handles.planNameSearchBox = uicontrol('style', 'edit', 'units', 'normalized', 'position', [.05 .675 .15 .03], 'callback', 'planDBGUI(''PLANNAMESEARCH'');', 'backgroundcolor', [1 1 1]);
        uicontrol('style', 'text', 'units', 'normalized', 'position', [.05 .64 .15 .03], 'string', 'Search plan names');
        ud.handles.clearPlanSearchFilter = uicontrol('style', 'pushbutton', 'string', 'Clear Search', 'units', 'normalized', 'position', [.05 .58 .15 .05], 'callback', 'planDBGUI(''clearPlanSearchFilter'');');

        %Initialize lower planDB controls
        uicontrol('style', 'frame', 'units', 'normalized', 'position', [.025 .05 .2 .4]);
        uicontrol('style', 'text', 'units', 'normalized', 'position', [.05 .375 .1 .05], 'string', 'Database:', 'horizontalalignment', 'left');

        uicontrol('style', 'text', 'units', 'normalized', 'position', [.05 .265 .1 .05], 'string', '.mat files:', 'horizontalalignment', 'left');
        uicontrol('style', 'text', 'units', 'normalized', 'position', [.05 .235 .1 .05], 'string', 'plan files:', 'horizontalalignment', 'left');
        uicontrol('style', 'text', 'units', 'normalized', 'position', [.05 .205 .1 .05], 'string', 'present plans:', 'horizontalalignment', 'left');
        uicontrol('style', 'text', 'units', 'normalized', 'position', [.05 .175 .1 .05], 'string', 'num fields:', 'horizontalalignment', 'left');

        ud.handles.planNameTx = uicontrol('style', 'text', 'units', 'normalized', 'position', [.05 .355 .1 .05], 'string', '<None>', 'horizontalalignment', 'left');
        ud.handles.matFileTx = uicontrol('style', 'text', 'units', 'normalized', 'position', [.13 .265 .07 .05], 'string', '<N/A>', 'horizontalalignment', 'right');
        ud.handles.planFileTx = uicontrol('style', 'text', 'units', 'normalized', 'position', [.13 .235 .07 .05], 'string', '<N/A>', 'horizontalalignment', 'right');
        ud.handles.presPlanTx = uicontrol('style', 'text', 'units', 'normalized', 'position', [.13 .205 .07 .05], 'string', '<N/A>', 'horizontalalignment', 'right');
        ud.handles.numFieldTx = uicontrol('style', 'text', 'units', 'normalized', 'position', [.13 .175 .07 .05], 'string', '<N/A>', 'horizontalalignment', 'right');

        ud.handles.loadDBButton = uicontrol('style', 'pushbutton', 'string', 'Load planDB', 'units', 'normalized', 'position', [.05 .075 .15 .05], 'callback', 'planDBGUI(''loadplanDB'');');

        if nargin == 2
            planDB = varargin{1};
            setappdata(h, 'planDB', planDB);
        end
        set(h, 'userdata', ud);

    case 'LOADPLANDB'
        planDB = [];
        ud = get(gcbf, 'userdata');
        [filename, pathname] = uigetfile('*.mat', 'Pick a .mat planDB file');
        if filename == 0
            return;
        else
            load(fullfile(pathname, filename));
        end

        if exist('planDB')
            %planDB = updateplandb(planDB);
            setappdata(gcbf, 'planDB', planDB);
            ud.DB.filename = filename;
            ud.DB.path = pathname;
            set(gcbf, 'userdata', ud);
            planDBGUI('UPDATEPLANSTATS');
            planDBGUI('SHOWALLPLANS');
            planDBGUI('SHOWALLFIELDS');
            planDBGUI('SHOWFILTERS');
        else
            return;
        end

    case 'UPDATEPLANSTATS'
        planDB = getappdata(gcbf, 'planDB');
        ud = get(gcbf, 'userdata');

        set(ud.handles.planNameTx, 'String', ud.DB.filename);
        set(ud.handles.matFileTx, 'String', num2str(length(planDB.matFiles)));
        set(ud.handles.planFileTx, 'String', num2str(length(find([planDB.matFiles.isPlanC]))));
        set(ud.handles.presPlanTx, 'String', num2str(length(find([planDB.matFiles.isPlanC] & [planDB.matFiles.isPresent]))));
        set(ud.handles.numFieldTx, 'String', num2str(length(planDB.fieldIndex)));
        set(gcbf, 'userdata', ud);

    case 'CLEARFIELDFILTER'
        ud = get(gcbf, 'userdata');
        set(ud.handles.searchBox, 'string', '');
        planDBGUI('SHOWALLFIELDS');

    case 'SHOWALLPLANS'
        planDB = getappdata(gcbf, 'planDB');
        ud = get(gcbf, 'userdata');
        ud.planList = [planDB.matFiles([planDB.matFiles.isPlanC]).info]; %set planlist to file info.
        set(gcbf, 'userdata', ud);
        updatePlanList(gcbf);
        numPlans = length(ud.planList);
        title(['All Plans (' num2str(numPlans) ')'], 'interpreter', 'none');

    case 'SHOWALLFIELDS'
        planDB = getappdata(gcbf, 'planDB');
        ud = get(gcbf, 'userdata');
        ud.fieldStruct = searchFieldNames('.*', planDB.fieldIndex);
        set(gcbf, 'userdata', ud);
        updateFieldList(gcbf);
        numFields = length(ud.fieldStruct);
        title(['All Fields (' num2str(numFields) ')'], 'interpreter', 'none')

    case 'SHOWFILTERS'
        ud = get(gcbf, 'userdata');
        ud.filters = struct('Filters', {}, 'fieldname', {}, 'action', {}, 'regexp', {}, 'bool', {}, 'invert', {}, 'indices', {});
        set(gcbf, 'userdata', ud);

    case 'SEARCHENTERED'
        planDB = getappdata(gcbf, 'planDB');
        ud = get(gcbf, 'userdata');
        searchString = get(gcbo, 'String');
        if isempty(searchString)
            planDBGUI('showallfields');
            return;
        end
        fieldS = searchFieldNames(searchString, planDB.fieldIndex);
        ud.fieldStruct = fieldS;
        set(gcbf, 'userdata', ud);

        updateFieldList(gcbf);

        title(['Fields matching ''' searchString ''''], 'interpreter', 'none');

        set(gcbf, 'userdata', ud);

    case 'FIELDCLICKED'
        planDBGUI('newfilter', 'AND', 'exists', '0');

    case 'PLANCLICKED'
        ud = get(gcbf, 'userdata');
        element = table(ud.handles.botAxis, 'getcurrentelement');
        planDB = getappdata(gcbf, 'planDB');

        planList = ud.planList;
        name = planList(element).name;
        path = planList(element).path;

        file = fullfile(path, name);

        CERRSliceViewer('load', file);

    case 'FILTERCLICKED'
        ud = get(gcbf, 'userdata');
        index = table(gca, 'getcurrentelement');
        ud.filters(index) = [];
        set(gcbf, 'userdata', ud);
        updateFilterList(gcbf);

    case 'NEWFILTER'
        bool = varargin{1};
        action = varargin{2};
        invert = str2num(varargin{3});

        ud = get(gcbf, 'userdata');
        index = table(ud.handles.topAxis, 'getcurrentelement');
        field = ud.fieldStruct(index).fieldname;

        ud.filters(end+1).fieldname = field;
        ud.filters(end).bool = bool;
        ud.filters(end).action = action;
        ud.filters(end).indices = [];
        if strcmpi(action, 'contains') | strcmpi(action, 'does not contain')
            regexp = inputdlg('Regexp:','Enter a regular expression');
        else
            regexp = {''};
        end

        ud.filters(end).regexp = regexp;
        ud.filters(end).Filters = [bool ' ' field ' ' action ' ' regexp{:} '.'];

        set(gcbf, 'userdata', ud);
        updateFilterList(gcbf);

end

function hMenu = rtMenu()
%Create right click menu to be passed to table.
	h = uicontextmenu;

    hAnd = 	uimenu(h, 'label', 'AND this field...');
    hOr  = 	uimenu(h, 'label', 'OR this field...');

	uimenu(hAnd, 'label', 'contains <expression>.', 'separator', 'off', 'callback', 'planDBGUI(''newfilter'', ''AND'', ''contains'', ''0'')');
	uimenu(hAnd, 'label', 'does not contain <expression>.', 'callback', 'planDBGUI(''newfilter'', ''AND'', ''contains'', ''1'')');
	uimenu(hAnd, 'label', 'exists.', 'callback', 'planDBGUI(''newfilter'', ''AND'', ''exists'', ''0'')');
	uimenu(hAnd, 'label', 'does not exist.', 'callback', 'planDBGUI(''newfilter'', ''AND'', ''exists'', ''1'')');
	uimenu(hAnd, 'label', 'is empty.', 'callback', 'planDBGUI(''newfilter'', ''AND'', ''is empty'', ''0'')');
	uimenu(hAnd, 'label', 'is not empty.', 'callback', 'planDBGUI(''newfilter'', ''AND'', ''is empty'', ''1'')');

	uimenu(hOr, 'label', 'contains <expression>.', 'separator', 'off', 'callback', 'planDBGUI(''newfilter'', ''OR'', ''contains'', ''0'')');
	uimenu(hOr, 'label', 'does not contain <expression>.', 'callback', 'planDBGUI(''newfilter'', ''OR'', ''contains'', ''1'')');
	uimenu(hOr, 'label', 'exists.', 'callback', 'planDBGUI(''newfilter'', ''OR'', ''exists'', ''0'')');
	uimenu(hOr, 'label', 'does not exist.', 'callback', 'planDBGUI(''newfilter'', ''OR'', ''exists'', ''1'')');
	uimenu(hOr, 'label', 'is empty.', 'callback', 'planDBGUI(''newfilter'', ''OR'', ''is empty'', ''0'')');
	uimenu(hOr, 'label', 'is not empty.', 'callback',  'planDBGUI(''newfilter'', ''OR'', ''is empty'', ''1'')');
    hMenu = h;

function updateFieldList(hFigure)
    ud = get(hFigure, 'userdata');
    table(ud.handles.topAxis, 'data', rmfield(ud.fieldStruct, 'planIndices'));
    table(ud.handles.topAxis, 'SETRIGHTCLICKMENU', rtMenu);

function updateFilterList(hFigure)
    ud = get(hFigure, 'userdata');
    table(ud.handles.midAxis, 'data', rmfield(ud.filters, {'fieldname', 'bool', 'action', 'regexp', 'indices', 'invert'}));
    applyFilters(hFigure);

function updatePlanList(hFigure)
    ud = get(hFigure, 'userdata');
	table(ud.handles.botAxis);
    table( ud.handles.botAxis, 'SETDBCALLBACK', 'planDBGUI(''planclicked'')');
    table(ud.handles.botAxis, 'data', rmfield(ud.planList, {'path', 'lastMod'}));
    numPlans = length(ud.planList);
    title(['Filtered Plans (' num2str(numPlans) ')'], 'interpreter', 'none');

function applyFilters(hFigure)
    ud = get(hFigure, 'userdata');
    filters = ud.filters;
    if isempty(filters)
        planDBGUI('showallplans');
    else
        ud.planList = [];
        planDB = getappdata(gcbf, 'planDB');
        allFieldNames = {planDB.fieldIndex.fieldname};

        plans = [];
        for i=1:length(filters)
            if ~isempty(ud.filters(i).indices)
                indices = ud.filters(i).indices;
            else
                fIndex = find(strcmpi(allFieldNames, filters(i).fieldname));
                fieldS = planDB.fieldIndex(fIndex);
                filters(i) = runFilter(filters(i), planDB);
            end
            ud.filters(i).indices = filters(i).indices;
            if isempty(plans), plans = filters(i).indices;, end;
            if strcmpi(filters(i).bool, 'and')
                plans = intersect(plans, filters(i).indices);
            elseif strcmpi(filters(i).bool, 'or')
                plans = union(plans, filters(i).indices);
            end
        end

        fieldsToDisplay = unique({filters.fieldname});
        ud.planList = [planDB.matFiles(plans).info];
        for i=1:length(plans)
            for j=1:length(fieldsToDisplay)
                data = getFieldContents(fieldsToDisplay{j}, planDB.matFiles(plans(i)).extract);
                ud.planList(i).(['data' num2str(j)]) = data{1};
            end
        end
        set(hFigure, 'userdata', ud);
        updatePlanList(hFigure);
    end


function [stFiles] = ex_GetAllFiles(sBaseDir)
% function [stFiles] = ex_GetAllFiles(sBaseDir)
% ---------------------------------------------
% Collects all filenames form a given directory and its subdirectories
%
% Input parameter:
%   sBaseDir    Base directory for filesearch. Function looks into this directory and its subdirectories
%
% Output parameter:
%   stFiles     Vector of structure containing filenames. Filenames are stored in .name element
%
% Danijel Schorlemmer
% October 7, 2002

% Init return values
stFiles = [];

% Get the list of the base directory
files = dir(sBaseDir);

% Iterate through this list store the filenames
for nCnt = 1:(length(files))
  % If element is a directory, analyze it
  if files(nCnt).isdir == 1
    % If it doesn't point upwards, recurse into the subdirectory
    if ~strcmp(files(nCnt).name, '.')  &&  ~strcmp(files(nCnt).name, '..')
      sDir = fullfile(fileparts(sBaseDir), files(nCnt).name);
      stFiles = [stFiles; GetAllFiles(sDir)];
    end
  else
    stFiles = [stFiles; struct('name', fullfile(fileparts(sBaseDir), files(nCnt).name))];
  end
end


function varargout = scl_inter(varargin)
% Format
% For getting the value
% dat = scl_inter(obj)
%
% For setting the value
% obj = scl_inter(obj,dat)
% _______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging

%
% $Id$

if nargin==2,
    varargout{1} = asgn(varargin{:});
elseif nargin==1,
    varargout{1} = ref(varargin{:});
else
    error('Wrong number of arguments.');
end;
return;

function dat = ref(obj)
dat = obj.scl_inter;
return;

function obj = asgn(obj,dat)
if isnumeric(dat), % && numel(dat)<=1,
    obj.scl_inter = double(dat);
else
    error('"scl_inter" must be numeric.');
end;
return;


%
% FILE NAME:    Recon3Rxns2HMR.m
%
% PURPOSE: This script attempts to assign proper HMR id(s) to each
%          Recon3D rxn, and output the association into a defined
%          array structure.
%

% Load rxn association from HMR2 and Recon3D to MNX
load('Recon3Rxns2MNX.mat');    %Recon3D rxn association to MNX
load('ihumanRxns2MNX.mat');    %HMR rxn association to MNX

% Add assocation based on BiGG database
Recon3D.BiGG2HMR=cell(numel(Recon3D.rxns),1);
Recon3D.BiGG2HMR(:)={''};
index=find(~cellfun(@isempty,Recon3D.rxnBiGGID));
[a, b]=ismember(Recon3D.rxnBiGGID(index),ihuman.HMR2BiGG);
I=find(a);
Recon3D.BiGG2HMR(index(I))=ihuman.rxns(b(I));
numel(find(~cellfun(@isempty,Recon3D.BiGG2HMR)))  % ans = 4522
% Check consistency
indexBiGG=find(~cellfun(@isempty,Recon3D.BiGG2HMR));
indexHMR=find(~cellfun(@isempty,Recon3D.rxnHMRID));
overlap=intersect(indexBiGG,indexHMR);
ind=find(~cellfun(@isequal,Recon3D.BiGG2HMR(overlap),Recon3D.rxnHMRID(overlap)));
fprintf('%s: %s-%s\n',num2str(overlap(ind)),Recon3D.BiGG2HMR{overlap(ind)},Recon3D.rxnHMRID{overlap(ind)});
% 11741: HMR_8671-HMR_6533
% Keep the direct association based on Recon3 rxn id and remove the other one
Recon3D.BiGG2HMR{11741}='';
% These BiGG association seem to be problematic

% Add assocation based on MNX database

% Prepare the rxnCompIdx field to represent the rxn compartment info,
% because the rxnComps field cannot accurately descirbe cases, such as
% the reactions involve multiple compartments (e.g. exchagne/transport)

load('Recon3DRaven.mat');    %Load Recon3D in RAVEN format
Recon3D.rxnCompIdx=addRxnCompIdx(Recon3DRaven);
Recon3D.comps=Recon3DRaven.comps;
Recon3D.compNames=Recon3DRaven.compNames;
Recon3D.mets=Recon3DRaven.mets;
ihuman.rxnCompIdx=addRxnCompIdx(ihuman);

% Get additional Recon3D-HMR2 association using MNX association and
% compartment info, and then assign mapping results to rxnHMRID field
load('mergedModel.mat');
for i=1:numel(Recon3D.rxns)
		% Consider the rxns with MNX association and without HMR association
		if isempty(Recon3D.rxnHMRID{i}) && ~isempty(Recon3D.rxnMNXID{i})
				%attempt to get the HMR assoc
				for j=1:numel(mergedModel.rxns)
						if ismember(Recon3D.rxnMNXID{i},mergedModel.confirmedMNXID{j})
								rxns=[{};mergedModel.rxns{j}];
								if ~isempty(mergedModel.duplicateRxns{j}) && ....
								~ismember(mergedModel.rxns{j},{'HMR_8771','HMR_1592'})
										rxns=[rxns;transpose(strsplit(mergedModel.duplicateRxns{j},';'))];
								end

								% Specify rxn assoc using compartment index
								for k=1:numel(rxns)
										index=find(strcmp(rxns{k},ihuman.rxns));
										if isequal(ihuman.rxnCompIdx{index},Recon3D.rxnCompIdx{i})

												if isempty(Recon3D.rxnHMRID{i})
														Recon3D.rxnHMRID{i}=ihuman.rxns{index};
												else
														%Allow multiple HMR associations to one Recon3D rxn
														Recon3D.rxnHMRID{i}=strcat(Recon3D.rxnHMRID{i},';',ihuman.rxns{index});
												end
										end
								end

						end
				end
		end
end
numel(find(~cellfun(@isempty,Recon3D.rxnHMRID)))  % ans = 4998

save('Recon3Rxns2HMR.mat','Recon3D');    %Save the information for merging
save('ihumanRxns2MNX.mat','ihuman');     %2018-05-28

% flag the reactions with MNX association but without HMR association 2018-05-30
Recon3D.withMNXnoHMR=cell(numel(Recon3D.rxns),1);
Recon3D.withMNXnoHMR(:)={''};
for i=1:numel(Recon3D.rxns)
		if isempty(Recon3D.rxnHMRID{i}) && ~isempty(Recon3D.rxnMNXID{i})
				for j=1:numel(mergedModel.rxns)
						% locate these reactions extended to other compartments
						if ismember(Recon3D.rxnMNXID{i},mergedModel.confirmedMNXID{j}) & ~ismember(mergedModel.rxns{j},{'HMR_8771','HMR_1592'})
								Recon3D.withMNXnoHMR{i}=Recon3D.rxns{i};
								Recon3D.BiGG2HMR{i}='';   % clean off these HMR assoc
						end
				end
		end
end
numel(find(~cellfun(@isempty,Recon3D.withMNXnoHMR)))  % ans = 259
save('Recon3Rxns2HMR.mat','Recon3D');   % 2018-05-30

%===============
%% sub functions
% add compIdx field to accurately represent the rxn compartment info
function compIdx = addRxnCompIdx(model)
		compIdx=cell(numel(model.rxns),1);
		compIdx(:)={''};
		for i=1:numel(model.rxns)
				compIdx{i}=unique(model.metComps(find(model.S(:,i))));
		end
end


classdef StrainDescriptor < FieldNameDescriptor

    methods (Access = protected)

        function loadFieldVariable(obj)
            obj.fieldName = 'strain';
        end

    end

end


 function ob = ctranspose(ob)
%function ob = ctranspose(ob)
% "ctranspose" method for Fatrix class

ob.is_transpose = ~ob.is_transpose;

% [ob.index1 ob.index2] = deal(ob.index2, ob.index1);
ob.dim = fliplr(ob.dim);


function  ACFTB  = readACFTB(fid)
%
% <<<<<<<<<< CLASSIFICATION: UNCLASSIFIED >>>>>>>>>>
%
% READACFTB Create structure for metadata fields.
%   ACFTB = READACFTB(FID) returns a structure of fields and their
%   associated values.

% Written by Matt Donath, NGA, matthew.b.donath@nga.ic.gov
% References:
%  > MIL-STD-2500A, NATIONAL IMAGERY TRANSMISSION FORMAT VERSION 2.0
%  > MIL-STD-2500C, NATIONAL IMAGERY TRANSMISSION FORMAT VERSION 2.1
%  > STDI-0001,     NATIONAL SUPPORT DATA EXTENSIONS (SDE)(VERSION 1.3/CN2)
%                   FOR THE NATIONAL IMAGERY TRANSMISSION FORMAT (NITF)
%  > STDI-0002,     THE COMPENDIUM OF CONTROLLED EXTENSIONS (CE) FOR THE
%                   NATIONAL IMAGERY TRANSMISSION FORMAT (NITF) VERSION 2.1
%
% //////////////////////////////////////////
% /// CLASSIFICATION: UNCLASSIFIED       ///
% //////////////////////////////////////////

%% Create the metadata structure for ACFTB.

ACFTB.CETAG = fread(fid,6,'uint8=>char')';
ACFTB.CEL = str2double(fread(fid,5,'uint8=>char')');

ACFTB.AC_MSN_ID = fread(fid,20,'uint8=>char')';
ACFTB.AC_TAIL_NO = fread(fid,10,'uint8=>char')';
ACFTB.AC_TO = fread(fid,12,'uint8=>char')';
ACFTB.SENSOR_ID_TYPE = fread(fid,4,'uint8=>char')';
ACFTB.SENSOR_ID = fread(fid,6,'uint8=>char')';
ACFTB.SCENE_SOURCE = fread(fid,1,'uint8=>char')';
ACFTB.SCNUM = str2double(fread(fid,6,'uint8=>char')');
ACFTB.PDATE = fread(fid,8,'uint8=>char')';
ACFTB.IMHOSTNO = fread(fid,6,'uint8=>char')';
ACFTB.IMREQID = fread(fid,5,'uint8=>char')';
ACFTB.MPLAN = fread(fid,3,'uint8=>char')';
ACFTB.ENTLOC = fread(fid,25,'uint8=>char')';
ACFTB.LOC_ACCY = str2double(fread(fid,6,'uint8=>char')');
ACFTB.ENTELV = str2double(fread(fid,6,'uint8=>char')');
ACFTB.ELV_UNIT = fread(fid,1,'uint8=>char')';
ACFTB.EXITLOC = fread(fid,25,'uint8=>char')';
ACFTB.EXITELV = str2double(fread(fid,6,'uint8=>char')');
ACFTB.TMAP = str2double(fread(fid,7,'uint8=>char')');
ACFTB.ROW_SPACING = str2double(fread(fid,7,'uint8=>char')');
ACFTB.ROW_SPACING_UNITS = fread(fid,1,'uint8=>char')';
ACFTB.COL_SPACING = str2double(fread(fid,7,'uint8=>char')');
ACFTB.COL_SPACING_UNITS = fread(fid,1,'uint8=>char')';
ACFTB.FOCAL_LENGTH = str2double(fread(fid,6,'uint8=>char')');
ACFTB.SENSERIAL = fread(fid,6,'uint8=>char')';
ACFTB.ABSWVER = fread(fid,7,'uint8=>char')';
ACFTB.CAL_DATE = fread(fid,8,'uint8=>char')';
ACFTB.PATCH_TOT = str2double(fread(fid,4,'uint8=>char')');
ACFTB.MTI_TOT = str2double(fread(fid,3,'uint8=>char')');

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


classdef CalBatteryAndThermometerDataClass < BatteryAndThermometerDataBaseClass

    %% Public 'read-only' properties
    properties (SetAccess = private)
        FileNameAppendage = '_CalBattAndTherm.csv';
    end

    %% Public methods
    methods (Access = public)
        function obj = CalBatteryAndThermometerDataClass(varargin)
            fileNamePrefix = varargin{1};
            for i = 2:2:nargin
                if  strcmp(varargin{i}, 'SampleRate'), obj.SampleRate = varargin{i+1};
                else error('Invalid argument.');
                end
            end
            obj.Import(fileNamePrefix);

            % Set protected parent class variables
            obj.ThermometerUnits = '^\circC';
            obj.BatteryUnits = 'G';
        end
    end
end


function y=voicebox(f,v)
%VOICEBOX  set global parameters for Voicebox functions Y=(FIELD,VAL)
%
%  Inputs:  F   is a field name
%           V   is a new value for the field
%
% Outputs:  Y   is set equal to the structure of parameters if the
%               f and v inputs are both present or both absent. If only
%               input f is specified, then y is set to the value of the
%               corresponding field or null if it doesn't exist.
%
% This routine contains default values for constants that are used by
% other functions in the VOICEBOX toolbox. Values in the first section below,
% entitled "System-dependent directory paths" should be set as follows:
%    PP.dir_temp     directory for storing temporary files
%    PP.dir_data     default directory to preappend to speech data file names
%                    when the "d" option is specified in READWAV etc.
%    PP.shorten      location of SHORTEN executable. SHORTEN is a proprietary file compression
%                    algorithm that is used for some SPHERE-format files. READSPH
%                    will try to call an external decoder if it is asked to
%                    read such a compressed file.
%    PP.sfsbin       location of Speech Filing Sysytem binaries. If the "c" option
%                    is given to READSFS, it will try to create a requested item
%                    if it is not present in the SFS file. This parameter tells it
%                    where to find the SFS executables.
%    PP.sfssuffix    suffix for Speech Filing Sysytem binaries. READSFS uses this paremeter
%                    to create the name of an SFS executable (see PP.sfsbin above).
% Other values defined in this routine are the defaults for specific algorithm constants.
% If you want to change these, please refer to the individual routines for a fuller description.

% Bugs/Suggestions
%    (1)  Could allow a * at the end of F to act as a wildcard and return/print a part structure

%      Copyright (C) Mike Brookes 2003
%      Version: $Id: voicebox.m,v 1.17 2011/07/28 06:48:45 dmb Exp $
%
%   VOICEBOX is a MATLAB toolbox for speech processing.
%   Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   This program is free software; you can redistribute it and/or modify
%   it under the terms of the GNU General Public License as published by
%   the Free Software Foundation; either version 2 of the License, or
%   (at your option) any later version.
%
%   This program is distributed in the hope that it will be useful,
%   but WITHOUT ANY WARRANTY; without even the implied warranty of
%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%   GNU General Public License for more details.
%
%   You can obtain a copy of the GNU General Public License from
%   http://www.gnu.org/copyleft/gpl.html or by writing to
%   Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

persistent PP
if isempty(PP)

    % System-dependent directory paths and constants

    PP.dir_temp='F:\TEMP';                      % directory for storing temporary files
    PP.dir_data='E:\dmb\data\speech';           % default directory to preappend to speech data file names
    PP.shorten='C:\bin\shorten.exe';            % location of shorten executable
    PP.flac='C:\bin\flac.exe';                  % location of flac executable
    PP.sfsbin='F:\Program Files\SFS\Program';   % location of Speech Filing Sysytem binaries
    PP.sfssuffix='.exe';                        % suffix for Speech Filing Sysytem binaries
    PP.memsize=50e6;                            % Maximum amount of temporary memory to use (Bytes)

    % DYPSA glottal closure identifier

    PP.dy_cpfrac=0.3;           % presumed closed phase fraction of larynx cycle
    PP.dy_cproj=0.2;            % cost of projected candidate
    PP.dy_cspurt=-0.45;         % cost of a talkspurt
    PP.dy_dopsp=1;              % Use phase slope projection (1) or not (0)?
    PP.dy_ewdly=0.0008;         % window delay for energy cost function term [~ energy peak delay from closure] (sec)
    PP.dy_ewlen=0.003;          % window length for energy cost function term (sec)
    PP.dy_ewtaper=0.001;        % taper length for energy cost function window (sec)
    PP.dy_fwlen=0.00045;        % window length used to smooth group delay (sec)
    PP.dy_fxmax=500;            % max larynx frequency (Hz)
    PP.dy_fxmin=50;             % min larynx frequency (Hz)
    PP.dy_fxminf=60;            % min larynx frequency (Hz) [used for Frobenius norm only]
    PP.dy_gwlen=0.0030;         % group delay evaluation window length (sec)
    PP.dy_lpcdur=0.020;         % lpc analysis frame length (sec)
    PP.dy_lpcn=2;               % lpc additional poles
    PP.dy_lpcnf=0.001;          % lpc poles per Hz (1/Hz)
    PP.dy_lpcstep=0.010;        % lpc analysis step (sec)
    PP.dy_nbest=5;              % Number of NBest paths to keep
    PP.dy_preemph=50;           % pre-emphasis filter frequency (Hz) (to avoid preemphasis, make this very large)
    PP.dy_spitch=0.2;           % scale factor for pitch deviation cost
    PP.dy_wener=0.3;            % DP energy weighting
    PP.dy_wpitch=0.5;           % DP pitch weighting
    PP.dy_wslope=0.1;           % DP group delay slope weighting
    PP.dy_wxcorr=0.8;           % DP cross correlation weighting
    PP.dy_xwlen=0.01;           % cross-correlation length for waveform similarity (sec)

    % RAPT pitch tracker

    PP.rapt_f0min=50;           % Min F0 (Hz)
    PP.rapt_f0max=500;          % Max F0 (Hz)
    PP.rapt_tframe=0.01;        % frame size (s)
    PP.rapt_tlpw=0.005;         % low pass filter window size (s)
    PP.rapt_tcorw=0.0075;       % correlation window size (s)
    PP.rapt_candtr=0.3;         % minimum peak in NCCF
    PP.rapt_lagwt=0.3;          % linear lag taper factor
    PP.rapt_freqwt=0.02;        % cost factor for F0 change
    PP.rapt_vtranc=0.005;       % fixed voice-state transition cost
    PP.rapt_vtrac=0.5;          % delta amplitude modulated transition cost
    PP.rapt_vtrsc=0.5;          % delta spectrum modulated transition cost
    PP.rapt_vobias=0.0;         % bias to encourage voiced hypotheses
    PP.rapt_doublec=0.35;       % cost of exact doubling or halving
    PP.rapt_absnoise=0;         % absolute rms noise level
    PP.rapt_relnoise=2;         % rms noise level relative to noise floor
    PP.rapt_signoise=0.001;     % ratio of peak signal rms to noise floor (0.001 = 60dB)
    PP.rapt_ncands=20;          % max hypotheses at each frame
    PP.rapt_trms=0.03;                      % window length for rms measurement
    PP.rapt_dtrms=0.02;                     % window spacing for rms measurement
    PP.rapt_preemph=-7000;                  % s-plane position of preemphasis zero
    PP.rapt_nfullag=7;                      % number of full lags to try (must be odd)

    % now check some of the key values for validity

    if exist(PP.dir_temp)~=7        % check that temp directory exists
        PP.dir_temp = winenvar('temp');     % else use windows temp directory
    end

    [fnp,fnn,fne]=fileparts(mfilename('fullpath'));
    if exist(PP.shorten)~=2        % check that shorten executable exists
        PP.shorten=fullfile(fnp,'shorten.exe'); % next try local directory
        if exist(PP.shorten)~=2        % check if it exists in local directory
            PP.shorten='shorten.exe'; % finally assume it is on the search path
        end
    end

    if exist(PP.flac)~=2        % check that flac executable exists
        PP.flac=fullfile(fnp,'flac.exe'); % next try local directory
        if exist(PP.flac)~=2        % check if it exists in local directory
            PP.shorten='flac.exe'; % finally assume it is on the search path
        end
    end

end
if nargin==0
    if nargout==0
        % list all fields
        nn=sort(fieldnames(PP));
        cnn=char(nn);
        fprintf('%d Voicebox parameters:\n',length(nn));

        for i=1:length(nn);
            if ischar(PP.(nn{i}))
                fmt='  %s = %s\n';
            else
                fmt='  %s = %g\n';
            end
            fprintf(fmt,cnn(i,:),PP.(nn{i}));
        end
    else
        y=PP;
    end
elseif nargin==1
    if isfield(PP,f)
        y=PP.(f);
    else
        y=[];
    end
else
    if isfield(PP,f)
        PP.(f)=v;
        y=PP;
    else
        error(sprintf('''%s'' is not a valid voicebox field name',f));
    end
end


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

% Last Modified by GUIDE v2.5 25-Jan-2019 14:31:50

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

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

    centerUIFigure(hObject);

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

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

    populateGUI(handles, action, lv);

    % Update handles structure
    guidata(hObject, handles);

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

function populateGUI(handles, action, lv)
    lvdData = lv.lvdData;
    celBodyData = lvdData.celBodyData;

    [bodiesStr, sortedBodyInfo] = ma_getSortedBodyNames(celBodyData);
    handles.bodiesListBox.String = bodiesStr;

    sortedBodyInfoArr = KSPTOT_BodyInfo.empty(1,0);
    for(i=1:length(sortedBodyInfo))
        sortedBodyInfoArr(end+1) = sortedBodyInfo{i}; %#ok<AGROW>
    end

    curSelBodies = action.bodiesToSet;
    [~,inds,~] = intersect(sortedBodyInfoArr,curSelBodies);

    set(handles.bodiesListBox,'Value',inds);

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

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

        [~, sortedBodyInfo] = ma_getSortedBodyNames(celBodyData);
        inds = handles.bodiesListBox.Value;
        if(not(isempty(inds)))
            action.bodiesToSet = [sortedBodyInfo{inds}];
        else
            action.bodiesToSet = KSPTOT_BodyInfo.empty(1,0);
        end

        varargout{1} = true;
        close(handles.lvd_EditActionSetThirdBodyGravitySourcesGUI);
    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)
    uiresume(handles.lvd_EditActionSetThirdBodyGravitySourcesGUI);

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

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

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

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

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


function [erg,arg] = getopt(str,default,varargin)
%JM-16-mar-00
% [erg,arg] = getoption('dummy',default,'a',a,...,'dummy',dummyval,...,'z',z)
% erg = dummyval,
% arg = getoption('dummy','a',a,...,'z',z)
%
% (c) 2000 - Jan Modersitzki

  j   = max(find(strcmp(varargin,str)));
  if isempty(j),
    erg = default;
    arg = varargin;
  else
    erg = varargin{j+1};
    if j == length(varargin),
      arg = {varargin{1:j-1}};
    else
      arg = {varargin{1:j-1},varargin{j+2:end}};
    end;
  end;

  if ~strcmp(str,'getoptout'),
    out = getopt('getoptout',0,arg{:});
    if out, showopt(str,erg); end;
  end;

function showopt(str,erg)

  fprintf('%-20s ',str);

  if isnumeric(erg),

    if size(erg) == [1,1],
      if round(erg)==erg,
	fprintf('%d\n',erg);
      else
	fprintf('%12.6e\n',erg);
      end;

    else
      fprintf('is %dx%d\n',size(erg));
    end;

  elseif isstr(erg),

    fprintf('%s\n',erg);

  end;

return;
%----------------------------------------------------------------------


function val=getoptkey(key,default,varargin)
%
% val=getoptkey(key,default,opt)
%    or
% val=getoptkey(key,default,'key1',val1,'key2',val2, ...)
%
% query the value of a key from a structure or a list of key/value pairs
%
% author: Qianqian Fang, <q.fang at neu.edu>
%
% input:
%   key: a string name for the target struct field name
%   default: the default value of the key is not found
%   opt: a struct object; the field names will be searched to match the
%        key input, opt can be a list of 'keyname'/value pairs
%
% output:
%   val: val=opt.key if found, otherwise val=default
%
% -- this function is part of iso2mesh toolbox (http://iso2mesh.sf.net)
%

val=default;
if(nargin<=2) return; end
opt=varargin2struct(varargin{:});
if(isstruct(opt) && isfield(opt,key))
    val=getfield(opt,key);
end


function v = indexBy(idx, arr)
% VAL = INDEXBY(INDEX, ARRAY)
%   Get the INDEX'th of ARRAY regardless of if it is a cell or not.
%

  if iscell(arr)
    v = arr{idx};
  else
    v = arr(idx);
  end
end


function filename = dccnpath(filename)

% DCCNPATH manages the filename and path for test files. It helps to locate and read
% test file from Linux, Windows or macOS computers both inside and outside the DCCN.
%
% Use as
%  filename = dccnpath(filename)
%
% The default location for FieldTrip and its test data is '/home/common/matlab/fieldtrip'.
% This function will search-and-replace this string by the location that applies to
% your computer. It will replace '/home' by 'H:' and will replace forward by backward slashes.
%
% In case you have a local copy, you can override the default location by
%   global ft_default
%   ft_default.dccnpath = '/your/copy';
%
% Note that most test scripts expect data located at /home/common/matlab/fieldtrip/data/ftp
% or /home/common/matlab/fieldtrip/data/test, hence you should organize your local
% copy of the data under /your/copy/data/ftp and /your/copy/data/test.
%
% Copyright (C) 2012-2022, Donders Centre for Cognitive Neuroimaging, Nijmegen, NL

% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% for the documentation and details.
%
%    FieldTrip is free software: you can redistribute it and/or modify
%    it under the terms of the GNU General Public License as published by
%    the Free Software Foundation, either version 3 of the License, or
%    (at your option) any later version.
%
%    FieldTrip is distributed in the hope that it will be useful,
%    but WITHOUT ANY WARRANTY; without even the implied warranty of
%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%    GNU General Public License for more details.
%
%    You should have received a copy of the GNU General Public License
%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id$

global ft_default

% switch between linux and windows paths
if ispc
  filename = strrep(filename,'/home','H:');
  filename = strrep(filename,'/','\');
else
  filename = strrep(filename,'H:','/home');
  filename = strrep(filename,'\','/');
end

% alternative1 alllows to test with local files in the present working directory
% this is often convenient when initially setting up a new test script while the data is not yet uploaded
[p, f, x] = fileparts(filename);
alternative1 = [f x];

if strcmp(alternative1, 'test')
  % this should not be used when the filename is only "test", since that is too generic
  alternative1 = '';
elseif endsWith(pwd, alternative1)
  % exist(alternative1, 'file') also returns 7 in case the present working directory name matches alternative1
  % this is not the match we want
  alternative1 = '';
end

% alternative2 allows for the user to specify the path in the global ft_default variable
% see https://github.com/fieldtrip/fieldtrip/issues/1998
if isfield(ft_default, 'dccnpath')
  alternative2 = strrep(filename, '/home/common/matlab/fieldtrip', ft_default.dccnpath);
else
  alternative2 = '';
end

if ~exist(filename, 'file') && exist(alternative1, 'file')
  warning('using local copy %s instead of %s', alternative1, filename);
  filename = alternative1;
elseif ~exist(filename, 'file') && exist(alternative2, 'file')
  warning('using local copy %s instead of %s', alternative2, filename);
  filename = alternative2;
end


classdef MimMarkerLast < MimGuiPlugin
    % MimMarkerLast. Gui Plugin for switching transparency of zero
    %
    %     You should not use this class within your own code. It is intended to
    %     be used by the gui of the TD MIM Toolkit.
    %
    %     MimMarkerLast is a Gui Plugin for the MIM Toolkit.
    %
    %
    %     Licence
    %     -------
    %     Part of the TD MIM Toolkit. https://github.com/tomdoel
    %     Author: Tom Doel, Copyright Tom Doel 2014.  www.tomdoel.com
    %     Distributed under the MIT licence. Please see website for details.
    %

    properties
        ButtonText = 'Last marker'
        SelectedText = 'Last marker'
        ToolTip = 'Go to slice containing the last marker'
        Category = 'Slice navigation'
        Visibility = 'Dataset'
        Mode = 'Markers'

        HidePluginInDisplay = false
        PTKVersion = '1'
        ButtonWidth = 6
        ButtonHeight = 1
        Icon = 'fastforward.png'
        Location = 5
    end

    methods (Static)
        function RunGuiPlugin(gui_app)
            gui_app.ImagePanel.GotoLastMarker;
        end

        function enabled = IsEnabled(gui_app)
            enabled = gui_app.IsDatasetLoaded && isequal(gui_app.GetCurrentModeName, MimModes.MarkerMode);
        end

        function is_selected = IsSelected(gui_app)
            is_selected = false;
        end
    end
end


function newfp = slchangefilepart(fp, varargin)
%SLCHANGEFILEPART Changes some parts of the file path
%
% $ Syntax $
%   - newfp = slchangefilepart(fp, partname1, part1, ...)
%
% $ Description $
%   - newfp = slchangefilepart(fp, partname1, part1, ...) changes the
%     specified part of a path to a new value to form a new path.
%     Please refer to slfilepart for part names
%
% $ Remarks $
%   - If you specify the name, then you should be specify title and ext.
%
% $ History $
%   - Created by Dahua Lin, on Aug 12nd, 2006
%

%% Main body

if isempty(varargin)
    newfp = fp;
else

    opts.parent = '';
    opts.name = '';
    opts.title = '';
    opts.ext = '';
    opts = slparseprops(opts, varargin{:});

    if ~isempty(opts.ext)
        if opts.ext(1) ~= '.'
            error('sltoolbox:invalidarg', ...
                'The extension string should start with a dot . ');
        end
    end

    [p.parent, p.title, p.ext] = fileparts(fp);

    if isempty(opts.name)
        p = updatefields(p, opts, {'parent', 'title', 'ext'});
        newfp = fullfile(p.parent, [p.title, p.ext]);
    else
        if ~isempty(opts.title) || ~isempty(opts.ext)
            error('sltoolbox:invalidarg', ...
                'When name is specified, title and ext should not be');
        end
        p = updatefields(p, opts, {'parent', 'name'});
        newfp = fullfile(p.parent, p.name);
    end

end

%% Auxiliary functions

function S = updatefields(S, newS, fns)

nf = length(fns);
for i = 1 : nf
    f = fns{i};
    if ~isempty(newS.(f))
        S.(f) = newS.(f);
    end
end


function transpose(f) %#ok<*INUSD>
%TRANSPOSE   CHEBTECH objects are not transposable, so this method will throw an
%   error.

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

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

end


function disp( x, prefix ) %#ok
if nargin < 2, prefix = ''; end
disp( [ prefix, 'cvx base object' ] );

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


if ~exist('fig', 'dir')
    mkdir('fig');
end
fig1;
fig2;
fig3;
fig4;
fig5;


function l = list(varargin)

%tstoolbox/@list/list
%   Syntax:
%     * l = list
%       creates empty list
%     * l = list('Hello world')
%       create list with one entry, 'Hello world'
%     * l = list('Hello', 'My' , 'World')
%       create list with three entries
%     * l = list('Hello', 'My' , 'World')
%       create list with three entries
%
%   An object of type list contains a list of strings.
%
% Copyright 1997-2001 DPI Goettingen, License http://www.physik3.gwdg.de/tstool/gpl.txt

if nargin == 0 			% create an empty list
	l.data = {};		% implementation as one-dimensional cell array (columnwise)
	l.len = 0;
	l = class(l, 'list');
else					% create list from arguments
	if iscellstr(varargin)
		l = list(varargin);
	elseif ischar(varargin{1})
	    l = list(cellstr(varargin{1}));
	elseif isa(varargin{1}, 'list')
		l = varargin{1};
	elseif iscellstr(varargin{1})
		l.data = varargin{1}(:);
		l.len = length(varargin{1});
		l = class(l, 'list');
	else
		error('Wrong type of argument(s) given');
	end
end


function [status,datafiles] = writelevel(filename,datafiles)

% print count of renamings.
%datafiles=cell(10,10);

s=signal(filename);
str=history(s);
if ~isempty(datafiles)
  m=length(datafiles(:,1))+1;
else
  m=1;
end
n=0;
status=-1;
lasttoken='';
for i=1:length(str(:,1))
  [token,rem]=strtok(str(i,:),'>');
  rem=rem(2:length(rem));
  [token,rem]=strtok(rem,'<');
  if token & ~strcmp(lasttoken,token)
    lasttoken=token;
    if n
      m=m+1;
      for i1=1:n
	datafiles(m,i1)=datafiles(m-1,i1);
      end
    end
    n=n+1;
    datafiles(m,n)=cellstr(token);
    status=0;
  end
end

[path,fname,ext] = fileparts(filename);

if ~strcmp(lasttoken,fname)
    if n
      m=m+1;
      for i1=1:n
	datafiles(m,i1)=datafiles(m-1,i1);
      end
    end
    n=n+1;
    datafiles(m,n)=cellstr(fname);
end

datafiles(cellfun('isempty',datafiles))=cellstr('');

return;


function [fileList] = getFileList(inputDir, filterExp,varargin)
	% [fileList] = getFileList(inputDir, filterExp,varargin)
	% Gathers a list of files or folders in a directory based on an input regular expression.
	% Biafra Ahanonu
	% started: 2013.10.08 [11:02:31]
	% inputs
	%	inputDir - directory to gather files from and regexp filter for files
	%	filterExp - regexp used to find files/folders.
	% outputs
	%	fileList - cell array of strings containing identified files or folders.

	% changelog
		% 2014.03.21 - added feature to input cell array of filters
		% 2016.03.20 - added exclusion filter to function
		% 2019.03.08 [13:12:59] - added support for natural sorting of files
		% 2021.08.08 [19:30:20] - Updated to handle CIAtah v4.0 switch to all functions inside ciapkg package.
		% 2021.09.10 [03:17:56] - Added support to exclude adding the input directory to each file path.
		% 2022.05.26 [22:24:42] - Improved support multiple directory input.
		% 2022.06.12 [16:42:24] - Added folder filter.
	% TODO
		% [DONE] Fix "recusive" (sp) option to recursive in a backwards compatible way.

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

	%========================
	% Binary: 1 = recursively find files in all sub-directories. 0 = only find files in inputDir directory.
	options.recursive = '';
	% Append
	options.regexpWithFolder = 0;
	% String: filter to exclude.
	options.excludeFilter = '';
	% Binary: 1 = add inputDir to file paths, 0 = do not add input directory.
	options.addInputDirToPath = 1;
	% Char: lexicographic (e.g. 1 10 11 2 21 22 unless have 01 02 10 11 21 22) or numeric (e.g. 1 2 10 11 21 22) or natural (e.g. 1 2 10 11 21 22)
	% options.sortMethod = 'lexicographic';
	options.sortMethod = 'natural';
	% Binary: 1 = only include folders in the output. 0 = include folders and files.
	options.onlyFolders = 0;
	% DEPRECIATED 1 = recursively find files in all sub-directories. 0 = only find files in inputDir directory.
	options.recusive = 0;
	% 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
	%========================
	if ~isempty(options.recursive)
		options.recusive = options.recursive;
	end
	% options.recursive = options.recusive;

	if ~iscell(filterExp)
		filterExp = {filterExp};
	end
	if ischar(inputDir)
		inputDir = {inputDir};
	end

	fileList = {};
	nDirs = length(inputDir);
	%for thisDir = inputDir
	for i = 1:nDirs
		thisDir = inputDir{i};
		% thisDirHere = thisDir{i};
		thisDirHere = thisDir;
		if options.recusive==0
			files = dir(thisDirHere);
		else
			files = dirrec(thisDirHere)';
		end
		for file=1:length(files)
			if options.recusive==0
				filename = files(file,1).name;
				if options.regexpWithFolder==1
					filename = [options.regexpWithFolder filesep filename];
				end
				% If option selected, remove non-folders.
				if options.onlyFolders==1&&isfolder(filename)==0
					continue
				end
				% Add found file/folder to the list.
				if(~isempty(cell2mat(regexpi(filename, filterExp))))
					if options.addInputDirToPath==1
						fileList{end+1} = [thisDirHere filesep filename];
					else
						[~,filename,filenameExt] = fileparts(filename);
						filename = [filename filenameExt];
						fileList{end+1} = [filename];
					end
				end
			else
				filename = files(file,:);
				filename = filename{1};
				% If option selected, remove non-folders.
				if options.onlyFolders==1&&isfolder(filename)==0
					continue
				end
				% Add found file/folder to the list.
				if(~isempty(cell2mat(regexpi(filename, filterExp))))
					if options.addInputDirToPath==1
						fileList{end+1} = [filename];
					else
						[~,filename,filenameExt] = fileparts(filename);
						filename = [filename filenameExt];
						fileList{end+1} = [filename];
					end
				end
			end
		end
	end
	if ~isempty(options.excludeFilter)
		% excludeIdx = find(~cellfun(@isempty,(regexp(fileList,options.excludeFilter))));
		excludeIdx = ~cellfun(@isempty,(regexp(fileList,options.excludeFilter)));
		fileList(excludeIdx) = [];
		% includeIdx = setdiff(1:length(fileList),excludeIdx)
	end
	if ~isempty(fileList)&&(strcmp(options.sortMethod,'natural')|strcmp(options.sortMethod,'numeric'))
		fileList = natsortfiles(fileList);
	end
end


function esportspect_Callback(hObject, eventdata, handles)
% Plotting Defferntial Expression

[~,detectionName] = fileparts(handles.current_detection_file);
spectname = [detectionName ' Call ' num2str(handles.data.currentcall) '.png'];
[FileName,PathName] = uiputfile(spectname,'Save Spectrogram');

% Cancel if cancelled
if isnumeric(FileName)
    return
end

% Get the spectrogram from the display
I = get(handles.spect,'CData');
Ydata = get(handles.spect,'Ydata');
Ylim = get(handles.focusWindow,'Ylim');

% Set limits
Ymax = find(Ydata>=Ylim(2),1);
Ymin = find(Ydata>=Ylim(1),1);
I = flipud(I(Ymin:Ymax,:));

Clim = get(handles.focusWindow,'Clim');
I = mat2gray(I,Clim);
fullFileName = fullfile(PathName, FileName); % Add Figure Path
cmap = handles.data.cmap;
I2 = gray2ind(I,256);
RGB3 = ind2rgb(I2, inferno(255));
imwrite(RGB3,fullFileName,'png','BitDepth',8); % Re-change it to colored one


function so = tail(si)
% TAIL As streamCdr
so = streamCdr(si);


puntos=draw('UMH');


function [datafiles] = linsert(filename, handles,datafiles,s,nos)

% tstool/linsert
% status = linsert(filename, handles)
% Einfuegen eines Namens in die Liste, gleichzeitig wird die
% Selektion auf diesen Namen gesetzt

if isempty(s)
  [status,datafiles]=writelevel(filename,datafiles);
  [path,fname,ext] = fileparts(filename);
else
  [status,datafiles]=siglevel(s,datafiles);
  fname=name(s);
end

if ~nos
  datafiles=sortdatafiles(datafiles);
  filllistbox(datafiles,handles,fname);
end