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

% Last Modified by GUIDE v2.5 06-Mar-2020 17:08:32

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

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

    centerUIFigure(hObject);

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

    handles = populateGUI(optionsObj, handles);

    % Update handles structure
    guidata(hObject, handles);

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

function handles = populateGUI(options, handles)
    setOptsDoubleValueStrInGUI(handles, options, 'integratorStepSize', 'integratorOutputStepText');

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

        setOptsDoubleValueInObject(handles, options, 'integratorStepSize', 'integratorOutputStepText');

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

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

    errMsg = validateDoubleValue(handles, errMsg, 'integratorOutputStepText', 'Integrator Output Step', 1E-6, Inf, false);

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

    if(isempty(errMsg))
        uiresume(handles.lvd_builtInIntegratorOptionsGUI);
    else
        msgbox(errMsg,'Invalid Integrator Options Inputs','error');
    end

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

% Hints: get(hObject,'String') returns contents of integratorOutputStepText as text
%        str2double(get(hObject,'String')) returns contents of integratorOutputStepText as a double
    newInput = get(hObject,'String');
    newInput = attemptStrEval(newInput);
    set(hObject,'String', newInput);

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

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


classdef MimEditDelete < MimGuiPlugin
    % MimEditDelete. Gui Plugin for setting paint colour to transparent
    %
    %     You should not use this class within your own code. It is intended to
    %     be used by the gui of the TD MIM Toolkit.
    %
    %     MimEditDelete 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 = 'Delete'
        SelectedText = 'Delete'
        ToolTip = 'Paint over edits'
        Category = 'Segmentation label'
        Visibility = 'Dataset'
        Mode = 'Edit'

        HidePluginInDisplay = false
        PTKVersion = '1'
        ButtonWidth = 5
        ButtonHeight = 1
        Icon = 'paint.png'
        IconColour = GemMarkerPoint.DefaultColours{8}
        Location = 38
    end

    methods (Static)
        function RunGuiPlugin(gui_app)
            gui_app.ImagePanel.PaintBrushColour = 0;
        end

        function enabled = IsEnabled(gui_app)
             enabled = gui_app.IsDatasetLoaded && gui_app.ImagePanel.OverlayImage.ImageExists && ...
                isequal(gui_app.ImagePanel.SelectedControl, 'Paint');
        end

        function is_selected = IsSelected(gui_app)
            is_selected = gui_app.ImagePanel.PaintBrushColour == 0;
        end
    end
end


function [metabolite_structure,IDsAdded] = getCas2CTD(metabolite_structure)
%
%
% The input file was obtained from http://ctdbase.org/reports/CTD_chemicals.csv.gz
% 1st col: ctd id, 3rd col cas

% INPUT
% metabolite_structure  metabolite structure
%
% OUTPUT
% metabolite_structure  Updated metabolite structure
%
%
% Ines Thiele, 2020-2021

[NUM,TXT,RAW]=xlsread('CTD_chemicals.xlsx');
annotationSource = 'CTD_id mapping from CasRegistry';
annotationType = 'automatic';

Mets = fieldnames(metabolite_structure);
for i = 1 : length(Mets)
    Cas{i,1} = Mets{i};
    Cas{i,2} = num2str(metabolite_structure.(Mets{i}).casRegistry);
end

% listing starts at row 28
b =1;
for i = 28 : size(RAW,1)
    casRAW{b,1} = num2str(RAW{i,3});
    casRAWList{b,1} = RAW{i,2};
    b = b+1;
end
a = 1;
IDsAdded = '';

for i = 1 : size(Cas,1)

    % no keggId exists
    if ~isempty(metabolite_structure.(Cas{i,1}).casRegistry) && isempty(find(isnan(metabolite_structure.(Cas{i,1}).casRegistry),1))
        if isempty(metabolite_structure.(Cas{i,1}).ctd) || ~isempty(find(isnan(metabolite_structure.(Cas{i,1}).ctd),1))
            match = strmatch(Cas{i,2},casRAW,'exact');
            if ~isempty(match)
                metabolite_structure.(Cas{i,1}).ctd = casRAWList{match};
                metabolite_structure.(Cas{i,1}).ctd_source =  [annotationSource,':',annotationType,':',datestr(now)];
                IDsAdded{a,1} = Cas{i,1};
                IDsAdded{a,2} = 'ctd';
                IDsAdded{a,3} =  metabolite_structure.(Cas{i}).ctd;
                a = a + 1;
            end
        end
    end
end
[metabolite_structure] = cleanUpMetabolite_structure(metabolite_structure);


function x = is_search(x)
% Determine whether some object is a search() expression.
x = all(isfield(x,{'head','parts'})) && numel(x)==1 && strcmp(char(x.head),'search');


function a=DoSomethingFirst(c)
a=0;
DoSomething(c.samplebase);


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


function [thisFrame,movieFileID,inputMovieDims] = readFrame(inputMoviePath,frameNo,varargin)
	% Fast reading of frame from files on disk. This is an alternative to loadMovieList that is much faster when only a single frame needs to be read.
	% Biafra Ahanonu
	% started: 2020.10.19 [11:45:24]
	% inputs
		% inputMoviePath | Str: path to a movie. Supports TIFF, AVI, HDF5, NWB, or Inscopix ISXD.
		% frameNo | Int: frame number.
	% outputs
		%
	% Usage
		% For non-HDF5 file types, need to open a link to the
			% [thisFrame,movieFileID,inputMovieDims] = ciapkg.io.readFrame(inputMoviePath,frameNo);
			% Then for the second call, feed in movieFileID and inputMovieDims to improve read speed.
			% [thisFrame] = ciapkg.io.readFrame(inputMoviePath,frameNo,'movieFileID',movieFileID,'inputMovieDims',inputMovieDims);

	% changelog
		% 2021.06.30 [01:26:29] - Updated handling of no file path character input.
		% 2021.07.03 [09:02:14] - Updated to have backup read method for different tiff styles.
		% 2021.08.08 [19:30:20] - Updated to handle CIAtah v4.0 switch to all functions inside ciapkg package.
		% 2022.02.24 [10:24:28] - AVI now read(...,'native') is faster.
		% 2022.07.27 [13:48:43] - Ensure subfxn_loadFrame nested function outputs frame data (even if file does not contain the requested frame, e.g. empty matrix).
	% TODO
		%

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

	% ========================
	% Str: hierarchy name in hdf5 where movie data is located
	options.inputDatasetName = '/1';
	% Int vector: list of specific frames to load.
	options.frameList = [];
	% Pointer created by Tiff (tif), VideoReader (avi), or isx.Movie.read (Inscopix ISXD files).
	options.movieFileID = [];
	% Vector: [1st 2nd 3rd] dimension of movie.
	options.inputMovieDims = [];
	% Str: default NWB hierarchy names in HDF5 file where movie data is located, will look in the order indicates
	options.defaultNwbDatasetName = {'/acquisition/TwoPhotonSeries/data'};
	% Binary: 1 = whether to display info on command line.
	options.displayInfo = 1;
	% Binary: Whether to display diagnostic information
	options.displayDiagnosticInfo = 0;
	% Binary: allow RGB display, e.g. for AVI
	options.rgbDisplay = 0;
	% Int: [] = do nothing, 1-3 indicates R,G,B channels to take from multicolor RGB AVI
	options.rgbChannel = [];
	% get options
	options = getOptions(options,varargin);
	% display(options)
	% unpack options into current workspace
	% fn=fieldnames(options);
	% for i=1:length(fn)
	% 	eval([fn{i} '=options.' fn{i} ';']);
	% end
	% ========================

	try
		movieFileID = [];
		thisFrame = [];
		inputMovieDims = [];

		if ~isempty(options.frameList)
			frameNo = options.frameList(frameNo);
        end

        if iscell(inputMoviePath)==1&&length(inputMoviePath)==1
            inputMoviePath = inputMoviePath{1};
        end

		% Check if path to movie or uder
		if ischar(inputMoviePath)
			[movieType, supported, movieTypeSpecific] = ciapkg.io.getMovieFileType(inputMoviePath);
		else
			disp('Please input a file path.');
			return;
		end

		% Get the movie file identifier to faster access/reading during future calls.
		if isempty(options.movieFileID)
			options.movieFileID = subfxn_getMovieObj(inputMoviePath,options);
			movieFileID = options.movieFileID;
		end

		[thisFrame, inputMovieDims] = subfxn_loadFrame(inputMoviePath,options);

	catch err
		disp(repmat('@',1,7))
		disp(getReport(err,'extended','hyperlinks','on'));
		disp(repmat('@',1,7))
	end
	function [thisFrame, inputMovieDims] = subfxn_loadFrame(inputMoviePathHere,options)
		inputMovieDims = options.inputMovieDims;
		thisFrame = [];
		switch movieType
			case 'hdf5'
				% Much faster to input the existing movie dimensions.
				if isempty(options.inputMovieDims)
					[inputMovieDims] = ciapkg.io.getMovieInfo(inputMoviePath,'frameList',options.frameList,'inputDatasetName',options.inputDatasetName,'displayInfo',0,'displayDiagnosticInfo',0);
					inputMovieDims = [inputMovieDims.one inputMovieDims.two inputMovieDims.three];
				else
					inputMovieDims = options.inputMovieDims;
				end
				% inputMovieDims
				thisFrame = h5read(inputMoviePathHere,options.inputDatasetName,[1 1 frameNo],[inputMovieDims(1) inputMovieDims(2) 1]);
			case 'tiff'
				warning off;
				try
					if isempty(options.movieFileID)
						% Much slower, avoid.
						tiffID = subfxn_getMovieObj(inputMoviePathHere,options)
					else
						tiffID = options.movieFileID;
					end
					tiffID.setDirectory(frameNo);
					thisFrame = read(tiffID);
				catch
					try
						% thisFrame = imread(inputMoviePathHere, 'tif', 'Index', frameNo, 'Info', imgInfo);
						thisFrame = imread(inputMoviePathHere, 'tif', 'Index', frameNo);
					catch err
						disp(repmat('@',1,7))
						disp(getReport(err,'extended','hyperlinks','on'));
						disp(repmat('@',1,7))
						% fileInfo = imfinfo(filename);
					end
					% err
					% display(repmat('@',1,7))
					% disp(getReport(err,'extended','hyperlinks','on'));
					% display(repmat('@',1,7))
				end
				warning on;
			case 'avi'
				if isempty(options.movieFileID)
					% Much slower, avoid.
					xyloObj = subfxn_getMovieObj(inputMoviePathHere,options)
				else
					xyloObj = options.movieFileID;
				end
				thisFrame = read(xyloObj, frameNo,'native');
				thisFrame = thisFrame.cdata;
				if options.rgbDisplay==0
					if size(thisFrame,3)==3&isempty(options.rgbChannel)
						thisFrame = squeeze(thisFrame(:,:,1));
					elseif ~isempty(options.rgbChannel)
						thisFrame = squeeze(thisFrame(:,:,options.rgbChannel));
					end
				end
			case 'isxd'
				if isempty(options.movieFileID)
					% Much slower, avoid.
					inputMovieIsx = subfxn_getMovieObj(inputMoviePathHere,options)
				else
					inputMovieIsx = options.movieFileID;
				end
				thisFrame = inputMovieIsx.get_frame_data(frameNo-1);
			otherwise
				thisFrame = loadMovieList(inputMoviePathHere,'inputDatasetName',options.inputDatasetName,'displayInfo',0,'displayDiagnosticInfo',0,'displayWarnings',0,'frameList',frameNo);
		end
	end
	function movieFileID = subfxn_getMovieObj(inputMoviePathHere,options)
		% Setup connection to file to reduce I/O for file types that need it.
		movieFileID = [];
		switch movieTypeSpecific
			case 'hdf5'
				%
			case 'nwb'
				try
					h5info(inputMoviePathHere,options.inputDatasetName);
				catch
					for zCheck = 1:length(options.defaultNwbDatasetName)
						try
							options.inputDatasetName = options.defaultNwbDatasetName{zCheck};
							h5info(inputMoviePathHere,options.inputDatasetName);
							fprintf('Correct NWB dataset name: %s\n',options.inputDatasetName)
						catch
							fprintf('Incorrect NWB dataset name: %s\n',options.inputDatasetName)
						end
					end
				end
			case 'tiff'
				warning off;
				try
					tiffID = Tiff(inputMoviePathHere,'r');
					movieFileID = tiffID;
				catch
				end
				warning on;
			case 'avi'
				xyloObj = VideoReader(inputMoviePathHere);
				movieFileID = xyloObj;
			case 'isxd'
				try
					inputMovieIsx = isx.Movie.read(inputMoviePathHere);
				catch
					ciapkg.inscopix.loadIDPS();
					inputMovieIsx = isx.Movie.read(inputMoviePathHere);
				end
				movieFileID = inputMovieIsx;
			otherwise
				%
		end
	end
end


function pathNameFix=pathSepFix(pathName)

fileSepString=filesep;

switch fileSepString
    case '/' %i.e. PC so fix to MAC type
        pathNameFix=regexprep(pathName,'\','/');
    case'\' %i.e. LINUX or MAC so fix to PC type
        pathNameFix=regexprep(pathName,'/','\');
end

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


function logInfo(str, varargin)
% get caller function ID and display log msg
if nargin > 1
    cmd = 'sprintf(str';
    for i = 1:length(varargin)
        cmd = sprintf('%s, varargin{%d}', cmd, i);
    end
    str = eval([cmd, ');']);
end
[st, i] = dbstack();
caller = st(2).name;
fprintf('%s: %s\n', caller, str);
end