function msh = mrmInitHostWindow(msh)
% Initialize the host and window for a mesh.
%
%   msh = mrmInitHostWindow(msh)
%
% The msh structure contains slots for the windowID and the local host. If
% the currently identified windowID is open and the server is running on
% the host, nothing happens.
%
% If the current windowID is not open, then a new one is opened and the
% windowID field is updated.
%
% If the server is not running and the window is not opened, both are
% started and assigned.
%
% Examples:
%   msh = viewGet(VOLUME{1},'mesh');
%   msh = mrmInitHostWindow(msh);
%
% BW (c) Stanford VISTASOFT Team, many moons ago

if ieNotDefined('msh'), error('You must define a mesh.'); end

windowID = meshGet(msh,'id');
host = meshGet(msh,'host');

% If the server is not started, start it with windowID 1
if ~mrmCheckServer,  windowID = mrmStart(1); end

% Open the window.
msh = meshSet(msh,'windowID',mrmOpenWindow(host,windowID));

return


classdef MockDatasetDiskCache < handle
    % MockDatasetDiskCache. Part of the PTK test framework
    %
    % This class is used in tests in place of a PTKDatasetDiskCache. It allows
    % expected calls to be verified, while maintaining some of the expected
    % behaviour of a PTKDatasetDiskCache object.
    %
    %
    %     Licence
    %     -------
    %     Part of the TD Pulmonary Toolkit. https://github.com/tomdoel/pulmonarytoolkit
    %     Author: Tom Doel, 2012.  www.tomdoel.com
    %     Distributed under the GNU GPL v3 licence. Please see website for details.
    %

    properties (Access = private)
        StoredData
    end

    methods
        function obj = MockDatasetDiskCache()
            obj.StoredData = containers.Map;
        end

        function AddEntry(obj, name, value, context)
            obj.StoredData([name char(context)]) = value;
        end

        % Test methods

        function [value, cache_info] = LoadPluginResult(obj, plugin_name, context, reporting)
        end

        % Stores a plugin result in the disk cache and updates cached dependency
        % information
        function SavePluginResult(obj, plugin_name, result, cache_info, context, disk_cache_policy, memory_cache_policy, reporting)
        end

        % Saves additional data associated with this dataset to the cache
        function SaveData(obj, data_filename, value, reporting)
            obj.StoredData(data_filename) = value;
        end

        % Loads additional data associated with this dataset from the cache
        function value = LoadData(obj, data_filename, reporting)
        end

        function cache_path = GetCachePath(obj, ~)
        end

        function RemoveAllCachedFiles(obj, remove_framework_files, reporting)
        end

        function exists = Exists(obj, name, context, reporting)
            exists = obj.StoredData.isKey([name char(context)]);
        end

        function valid = CheckDependencyValid(obj, next_dependency, reporting)
        end
    end
end


function [output,status] = urlread(urlChar,method,params)
%URLREAD Returns the contents of a URL as a string.
%   S = URLREAD('URL') reads the content at a URL into a string, S.  If the
%   server returns binary data, the string will contain garbage.
%
%   S = URLREAD('URL','method',PARAMS) passes information to the server as
%   part of the request.  The 'method' can be 'get', or 'post' and PARAMS is a
%   cell array of param/value pairs.
%
%   [S,STATUS] = URLREAD(...) catches any errors and returns 1 if the file
%   downloaded successfully and 0 otherwise.
%
%   Examples:
%   s = urlread('http://www.mathworks.com')
%   s = urlread('ftp://ftp.mathworks.com/README')
%   s = urlread(['file:///' fullfile(prefdir,'history.m')])
%
%   From behind a firewall, use the Preferences to set your proxy server.
%
%   See also URLWRITE.

%   Matthew J. Simoneau, 13-Nov-2001
%   Copyright 1984-2011 The MathWorks, Inc.
%   $Revision: 1.3.2.12 $ $Date: 2011/09/03 22:43:00 $

% This function requires Java.
if ~usejava('jvm')
   error(message('MATLAB:urlread:NoJvm'));
end

import com.mathworks.mlwidgets.io.InterruptibleStreamCopier;

% Be sure the proxy settings are set.
com.mathworks.mlwidgets.html.HTMLPrefs.setProxySettings

% Check number of inputs and outputs.
if ~ischar(urlChar)
    error('MATLAB:urlread:InvalidInput','The first input, the URL, must be a character array.');
end
if (nargin > 1) && ~strcmpi(method,'get') && ~strcmpi(method,'post')
    error('MATLAB:urlread:InvalidInput','Second argument must be either "get" or "post".');
end

% Do we want to throw errors or catch them?
if nargout == 2
    catchErrors = true;
else
    catchErrors = false;
end

% Set default outputs.
output = '';
status = 0;

% GET method.  Tack param/value to end of URL.
if (nargin > 1) && strcmpi(method,'get')
    if mod(length(params),2) == 1
        error('MATLAB:urlread:InvalidInput','Invalid parameter/value pair arguments.');
    end
    for i=1:2:length(params)
        if (i == 1), separator = '?'; else separator = '&'; end
        param = char(java.net.URLEncoder.encode(params{i}));
        value = char(java.net.URLEncoder.encode(params{i+1}));
        urlChar = [urlChar separator param '=' value];
    end
end

% Create a urlConnection.
[urlConnection,errorid,errormsg] = plugin_urlreadwrite(mfilename,urlChar);
if isempty(urlConnection)
    if catchErrors, return
    else error(errorid,errormsg);
    end
end
urlConnection.setReadTimeout(5000); % timeout in 5 seconds

% POST method.  Write param/values to server.
if (nargin > 1) && strcmpi(method,'post')
    try
        urlConnection.setDoOutput(true);
        urlConnection.setRequestProperty( ...
            'Content-Type','application/x-www-form-urlencoded');
        printStream = java.io.PrintStream(urlConnection.getOutputStream);
        for i=1:2:length(params)
            if (i > 1), printStream.print('&'); end
            param = char(java.net.URLEncoder.encode(params{i}));
            value = char(java.net.URLEncoder.encode(params{i+1}));
            printStream.print([param '=' value]);
        end
        printStream.close;
    catch
        if catchErrors, return
        else error('MATLAB:urlread:ConnectionFailed','Could not POST to URL.');
        end
    end
end

% Read the data from the connection.
try
    inputStream = urlConnection.getInputStream;
    byteArrayOutputStream = java.io.ByteArrayOutputStream;
    % This StreamCopier is unsupported and may change at any time.
    isc = InterruptibleStreamCopier.getInterruptibleStreamCopier;
    isc.copyStream(inputStream,byteArrayOutputStream);
    inputStream.close;
    byteArrayOutputStream.close;
    output = native2unicode(typecast(byteArrayOutputStream.toByteArray','uint8'),'UTF-8');
catch
    if catchErrors, return
    else error('MATLAB:urlread:ConnectionFailed','Error downloading URL. Your network connection may be down or your proxy settings improperly configured.');
    end
end

status = 1;


function javaudd=dftoolgetudd(uddcmd,varargin);

%   $Revision: 1.1.6.2 $  $Date: 2004/01/24 09:35:57 $
%   Copyright 2003-2004 The MathWorks, Inc.

% unwrap any UDD objects
for i=1:length(varargin)
   if isa(varargin{i}, 'com.mathworks.jmi.bean.UDDObject')
      varargin{i}=handle(varargin{i});
   end
end

% wrap the return UDD object
if nargin == 1
   javaudd=java(eval(uddcmd));
else
   javaudd=java(feval(uddcmd,varargin{:}));
end


% function checking if a specific file is a script%

function bool = isscript(fileName);

fid = fopen(fileName, 'r');
cont = true;
while cont && ~feof(fid)
    l = strtok(fgetl(fid));

    if ~isempty(l) && l(1) ~= '%'
        if strcmpi(l, 'function')
            bool = false; return;
        else
            bool = true; return;
        end;
    end;
end;
bool = true; return;


function [  ] = pipeline_release(  )
    caffe.reset_all();
end


%
% Description:
%
% The default behavior for an arbitrary function
% (ECGtask_arbitrary_function) of the strat function is to do nothing.
%
%
% See also default_finish_function, ECGtask_arbitrary_function
%
% Author: Mariano Llamedo Soria (llamedom at frba.utn.edu.ar)
% Version: 0.1 beta
% Birthdate  : 17/4/2015
% Last update: 17/4/2015
% Copyright 2008-2017
%
function bStarted = default_start_function(obj, ECG_header)

% Flag to indicate correct initialization.
bStarted = true;


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

%%
clear; close all; clc;

%% Syntax
% |[runFlag]=runMonitorFEBio(FEBioRunStruct);|

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


function [tag, val, typ, dep, chk, cj] = harvest(item, cj, dflag, rflag)

% function [tag, val, typ, dep, chk, cj] = harvest(item, cj, dflag, rflag)
% Generic harvest function, suitable for all const/entry items.
% The configuration tree cj is passed unmodified. If rflag is true and a
% dependency can be resolved, the resolved value will be returned,
% otherwise the cfg_dep object will be returned in val and dep.
% Input arguments:
% item  - item to be harvested
% cj    - configuration tree (passed unmodified)
% dflag - if true, harvest defaults tree, otherwise filled tree
% rflag - if true, resolve dependencies in leaf nodes
% Output arguments:
% tag - tag of harvested item
% val - harvested value
% typ - class of harvested item (currently unused)
% dep - list of unresolved dependencies
% chk - meaningful if ~dflag and all dependencies are resolved. Then it
%       returns success status of this items .check function and its
%       childrens check functions. A job is ready to run if all
%       dependencies are resolved and chk status is true.
%
% This code is part of a batch job configuration system for MATLAB. See
%      help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging

% Volkmar Glauche
% $Id: harvest.m 5678 2013-10-11 14:58:04Z volkmar $

rev = '$Rev: 5678 $'; %#ok

typ = class(item);
tag = item.tag;
val = '<UNDEFINED>';
dep = []; % Placeholder for dependencies. Will be classified during
          % dependency evaluation
chk = ~dflag && rflag;

if ~isempty(item.val)
    if isa(item.val{1},'cfg_dep')
        if dflag % do not harvest references if defaults are requested
            val = '<UNDEFINED>';
        else
            if rflag
                [val, sts] = resolve_deps(item, cj);
            else
                sts = false;
            end;
            if ~sts % deps not resolved
                dep = item.val{1}; % dep is a array of cfg_dep objects
                for k = 1:numel(dep) % we may have multiple dependencies
                    dep(k).tname = item.name; % set target name
                end;
                val = dep; % return deps also in val for saving
            end;
        end;
    else
        val = item.val{1};
    end;
end;
chk = chk && isempty(dep);
if chk
    chk = docheck(item, val);
end;


% Copy this template configuration file to your VOT workspace.
% Enter the full path to the ECO repository root folder.

ECO_repo_path = ########

tracker_label = 'ECO';
tracker_command = generate_matlab_command('benchmark_tracker_wrapper(''ECO'', ''VOT2016_DEEP_settings'', true)', {[ECO_repo_path '/VOT_integration/benchmark_wrapper']});
tracker_interpreter = 'matlab';
tracker_trax = false;


classdef TestGFTTDetector
    %TestGFTTDetector

    properties (Constant)
        im = fullfile(mexopencv.root(),'test','tsukuba_l.png');
        kfields = {'pt', 'size', 'angle', 'response', 'octave', 'class_id'};
    end

    methods (Static)
        function test_detect_img
            obj = cv.GFTTDetector('MaxFeatures',1000);
            assert(obj.MaxFeatures == 1000);
            typename = obj.typeid();

            img = imread(TestGFTTDetector.im);
            kpts = obj.detect(img);
            validateattributes(kpts, {'struct'}, {'vector'});
            assert(all(ismember(TestGFTTDetector.kfields, fieldnames(kpts))));
        end

        function test_detect_imgset
            img = imread(TestGFTTDetector.im);
            imgs = {img, img};
            obj = cv.GFTTDetector();

            kpts = obj.detect(imgs);
            validateattributes(kpts, {'cell'}, {'vector', 'numel',numel(imgs)});
            cellfun(@(kpt) validateattributes(kpt, {'struct'}, {'vector'}), kpts);
            cellfun(@(kpt) assert(all(ismember(TestGFTTDetector.kfields, fieldnames(kpt)))), kpts);
        end

        function test_detect_mask
            img = imread(TestGFTTDetector.im);
            mask = zeros(size(img), 'uint8');
            mask(:,1:end/2) = 255;  % only search left half of the image
            obj = cv.GFTTDetector();
            kpts = obj.detect(img, 'Mask',mask);
            validateattributes(kpts, {'struct'}, {'vector'});
            assert(all(ismember(TestGFTTDetector.kfields, fieldnames(kpts))));
            xy = cat(1, kpts.pt);
            assert(all(xy(:,1) <= ceil(size(img,2)/2)));
        end

        function test_error_1
            try
                cv.GFTTDetector('foobar');
                throw('UnitTest:Fail');
            catch e
                assert(strcmp(e.identifier,'mexopencv:error'));
            end
        end
    end

end


function vw = viewSetUI(vw,param,val,varargin)
%Organize methods for setting view parameters.
%
% This function is wrapped by viewSet. It should not be called by anything
% else other than viewSet.
%
% This function retrieves information from the view that relates to a
% specific component of the application.
%
% We assume that input comes to us already fixed and does not need to be
% formatted again.

if notDefined('vw'),  error('No view defined.'); end
if notDefined('param'), error('No parameter defined'); end
if notDefined('val'),   val = []; end

mrGlobals;

switch param

    case 'initdisplaymodes'
        vw = resetDisplayModes(vw);
    case 'ui'
        vw.ui = val;
    case 'anatomymode'
        vw.ui.anatMode = val;
    case 'coherencemode'
        vw.ui.coMode = val;
    case 'correlationmode'
        vw.ui.corMode = val;
    case 'phasemode'
        vw.ui.phMode = val;
    case 'fignum'
        vw.ui.figNum = val;
    case 'windowhandle'
        vw.ui.windowHandle = val;
    case 'mainaxishandle'
        vw.ui.mainAxisHandle = val;
    case 'colorbarhandle'
        vw.ui.colorbarHandle = val;
    case 'cbarrange'
        vw.ui.cbarRange = val;
    case 'amplitudemode'
        vw.ui.ampMode = val;
    case 'uiimage'
        vw.ui.image = val;
    case 'projectedamplitudemode'
        vw.ui.projampMode = val;
    case 'mapmode'
        vw.ui.mapMode = val;
    case 'displaymode'
        vw.ui.displayMode = val;
    case 'phasecma'
        nGrays = viewGet(vw, 'curnumgrays');

        % allow transposed version (3 x n) instead of usual matlab cmap order (n x 3)
        if size(val, 2) > 3 && size(val, 1)==3, val = val'; end
        if max(val(:)) > 1, val = val ./ 255;               end
        vw.ui.phMode.cmap((nGrays+1):end,:) = val ;

    case 'locs'
        % cursor location as [axi cor sag]
        vw.loc = val;
        if checkfields(vw, 'ui', 'sliceNumFields')  % set UI fields
            for n = 1:3
                set(vw.ui.sliceNumFields(n), 'String', num2str(val(n)));
            end
        end
    case 'crosshairs'
        vw.ui.crosshairs = val;
    case 'flipud'
        % Boolean indicating whether to invert the image u/d in
        % the graphical user interface.  It is sometimes convenient to do
        % this in the Inplane view if the top of the slice corresponds to
        % the bottom of the brain.
        % Example:
        %   vw = viewSet(vw, 'flip updown', true);
        if checkfields(vw, 'ui'),   vw.ui.flipUD = val; end
    case 'zoom'
        vw.ui.zoom = val;
    otherwise
        error('Unknown view parameter %s.', param);

end %switch

return


function loadmovz()

    report_this_filefun();

    [file1,path1] = uigetfile(['*.mat'],'Moviefile');

    if length(path1) > 1
        load([path1 file1])
        showmovi
    end   % if exist

end


function parsave(filename, structX)
    vl_xmkdir(fileparts(filename));
    save(filename,'-struct','structX');
end


function [branch, hash] = tapas_get_tapas_revision(verbose)
%%
%
% Input
%
% Output
%

%
% aponteeduardo@gmail.com
% copyright (C) 2017
%

n = 0;

n = n + 1;
if nargin < n
    verbose = 1;
end

% Get current location
f = mfilename('fullpath');

[tdir, ~, ~] = fileparts(f);

tdir = fullfile(tdir, '..');
try
    [branch, hash] = tapas_get_revision_info(tdir);
catch err
    if strcmp('tapas:get_revision_info', err.identifier)
        if verbose
            display(getReport(err))
        end
        branch = '';
        hash = '';
    else
        rethrow(err)
    end
end

end


% [INPUT]
% handle = A handle to the plotting function to be executed.

function safe_plot(varargin)

    persistent ip;

    if (isempty(ip))
        ip = inputParser();
        ip.addRequired('handle',@(x)validateattributes(x,{'function_handle'},{'scalar'}));
    end

    ip.parse(varargin{:});
    ipr = ip.Results;

    nargoutchk(0,0);

    safe_plot_internal(ipr.handle);

end

function safe_plot_internal(handle)

    persistent ids;

    name = func2str(handle);
    name = regexprep(name,'^@\([^)]*\)','');
    name = regexprep(name,'\([^)]*\)$','');

    try
        id = [upper(name) '-' upper(char(java.util.UUID.randomUUID()))];
    catch
        id = randi([0 10000000]);

        while (ismember(id,ids))
            id = randi([0 100000]);
        end

        ids = [ids; id];
        id = [upper(name) '-' sprintf('%08s',num2str(id))];
    end

    try
        handle(id);
    catch e
        delete(findobj('Type','Figure','Tag',id));

        try
            r = getReport(e,'Extended','Hyperlinks','off');
            r = strsplit(r,new_line());
            r = cellfun(@(x)['  ' x],r,'UniformOutput',false);
            r = strjoin(r,new_line());
            r = clear_text(r);

            warning('MATLAB:SystemicRisk',['The following exception occurred in the plotting function ''' name ''':' new_line() r]);
        catch
            warning('MATLAB:SystemicRisk',['The following exception occurred in the plotting function ''' name ''':' new_line() e.message]);
        end
    end

end


function varargout = addmissing(varargin)
% MATLAB code for addmissing.fig
% addmissing, by itself, creates a new object or raises the existing
% singleton*.
%
% USAGE:
%
%    varargout = addmissing(varargin)
%
% INPUTS:
%    varargin:    various input arguments
%
% OUTPUTS:
%    varargout:   various output arguments
%
% EXAMPLE:
%
%    H = addmissing() %returns the handle to a new addmissing or the handle to
%    %the existing singleton*.
%
%    addmissing('CALLBACK',hObject,eventData,handles,...) %calls the local
%    %function named `CALLBACK` in addmissing.M with the given input arguments.
%
%    addmissing('Property','Value',...) creates a new addmissing or raises the
%    %existing singleton*.  Starting from the left, property value pairs are
%    %applied to the GUI before `addmissing_OpeningFcn` gets called. An
%    %unrecognized property name or invalid value makes property application
%    %stop. All inputs are passed to `addmissing_OpeningFcn` via `varargin`.
%
% .. Author: - Stefan G. Thorleifsson 2011
%
% NOTE:
%    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 addmissing
% .. Last Modified by GUIDE v2.5 25-Nov-2010 00:19:22
%
% .. rBioNet is published under GNU GENERAL PUBLIC LICENSE 3.0+
% .. Thorleifsson, S. G., Thiele, I., rBioNet: A COBRA toolbox extension for
% .. reconstructing high-quality biochemical networks, Bioinformatics, Accepted.
% .. rbionet@systemsbiology.is
gui_Singleton = 1; % Begin initialization code - DO NOT EDIT
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @addmissing_OpeningFcn, ...
                   'gui_OutputFcn',  @addmissing_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 addmissing is made visible.
function addmissing_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 addmissing (see VARARGIN)
%Reaction pyk.
% Choose default command line output for addmissing
handles.output = hObject;
handles.step1 = [handles.uipanel1, handles.act_next, handles.act_cancel];
handles.step2 = [handles.uipanel2, handles.act_next, handles.act_cancel];
handles.step3 = [handles.uipanel3, handles.act_finish];

handles.mets = varargin{1}; %Abbrevitions of missing metabolites;
handles.rxns = varargin{2}; %abbreviation, formula, reversibility, EC number, kegggID, description.

if isempty(handles.mets{1})
    set(handles.step1,'Visible','off');
    set(handles.step3,'Visible','off');
    set(handles.step2,'Visible','on');
    handles.step = 2;
else
    set(handles.step2,'Visible','off');
    set(handles.step3,'Visible','off');
    set(handles.step1,'Visible','on');
    handles.step = 1;
end

% Update handles structure
guidata(hObject, handles);

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

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

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

% --- Executes on button press in act_next.
function act_next_Callback(hObject, eventdata, handles)
% hObject    handle to act_next (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
if handles.step == 1
    set(handles.figure1,'visible','off');
    out = addmetabolites(handles.mets);

    if ~isempty(handles.rxns)
            set(handles.step1,'Visible','off');
            set(handles.step3,'Visible','off');
            set(handles.step2,'Visible','on');
            set(handles.figure1,'visible','on');
            handles.step = 2;
        else
            set(handles.step1,'Visible','off');
            set(handles.step2,'Visible','off');
            set(handles.step3,'Visible','on');
            set(handles.figure1,'visible','on');
            handles.step = 3;
    end
else
    set(handles.figure1,'visible','off');
    load rxn.mat;
    load metab.mat;
    load compartments.mat;
    % 1:4 - abbreviation,description,formula, reversible,
    % 8 - CS, 11 - Notes, 10 - reference, 11:12 - EC number, KeggID
    reactions = [handles.rxns(:,1:4), handles.rxns(:,8), handles.rxns(:,11),...
        handles.rxns(:,10), handles.rxns(:,12:13)];
    out = addreactions(rxn,metab,compartments,reactions);%add reactions

    set(handles.step1,'Visible','off');
    set(handles.step2,'Visible','off');
    set(handles.step3,'Visible','on');
    handles.step = 3;
    set(handles.figure1,'visible','on');
end

guidata(hObject,handles)

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

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

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

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


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

%%
clear; close all; clc;

%% Syntax
% |[outputStruct]=import_ctgr(fileName);|

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


classdef (Abstract) ClustererX < BaseX  % Extends trackingX.BaseX
% ClustererX Abstract class
%
% Summary of ClustererX:
% This is the base class for all TrackingX clusterers.
% Any custom defined Clusterer should be derived from this ClustererX base class.
%
% ClustererX Properties:
%   ClusterList - A maintained list containing the last generated clusters
%   UnassocTrackInds - A maintained list of all tracks not associated to
%                      any measurements
%
% ClustererX Methods:
%   + ClustererX - Constructor method
%
% (+) denotes puplic properties/methods
%
% February 2018 Lyudmil Vladimirov, University of Liverpool.

    properties
        ClusterList
        UnassocTrackInds
    end

    methods (Abstract)
        cluster(this);
    end
    methods
        function this = ClustererX(varargin)
        % CLUSTERERX Constructor method
        %

        end
    end
end


function figure_size = getnicedialoglocation(figure_size, figure_units)
% adjust the specified figure position to fig nicely over GCBF
% or into the upper 3rd of the screen

%  Copyright 1999-2010 The MathWorks, Inc.

parentHandle = gcbf;
convertData.destinationUnits = figure_units;
if ~isempty(parentHandle)
    % If there is a parent figure
    convertData.hFig = parentHandle;
    convertData.size = get(parentHandle,'Position');
    convertData.sourceUnits = get(parentHandle,'Units');
    c = [];
else
    % If there is no parent figure, use the root's data
    % and create a invisible figure as parent
    convertData.hFig = figure('visible','off');
    convertData.size = get(0,'ScreenSize');
    convertData.sourceUnits = get(0,'Units');
    c = onCleanup(@() close(convertData.hFig));
end

% Get the size of the dialog parent in the dialog units
container_size = hgconvertunits(convertData.hFig, convertData.size ,...
    convertData.sourceUnits, convertData.destinationUnits, get(convertData.hFig,'Parent'));

delete(c);

figure_size(1) = container_size(1)  + 1/2*(container_size(3) - figure_size(3));
figure_size(2) = container_size(2)  + 2/3*(container_size(4) - figure_size(4));


function api = WizardProgressApi( api, firstPage )
%IMPORTGUIPROGRESS Summary of this function goes here
%   Detailed explanation goes here

state = {'off','on'};

gui = localCreateGUIControls();

% local progress api
progressApi.currentPage = firstPage;
progressApi.prevPage = {};
progressApi.leavePageCallback  = [];
progressApi.gotoPageCallback   = [];

% global available functions
api.Progress.enableNext   = @enableNext;
api.Progress.enablePrev   = @enablePrev;
api.Progress.enableFinish = @enableFinish;
api.Progress.enablePlot   = @enablePlot;

% some helper
api.initProgressApi       = @showPage;
% api.updateProgressApi     = @updateProgressApi;
api.setLeavePageCallback  = @setLeavePageCallback;
api.setGotoPageCallback   = @setGotoPageCallback;

api.nextCallback  = @localNextCallback;

% set callbacks
set(gui.hPlot   ,'CallBack',@localPlotDataCallback );
set(gui.hPrev   ,'Callback',@localPrevCallback   );
set(gui.hNext   ,'Callback',@localNextCallback   );
set(gui.hFinish ,'CallBack',@localFinishCallback   );

% initalize buttons
api.Progress.enableNext(false);
api.Progress.enablePrev(false);
api.Progress.enablePlot(false);
api.Progress.enableFinish(false);

  function showPage()

    api.clearPage();

    set(api.hPanel,'visible','off');

    progressApi.currentPage(api);
    try
      progressApi.gotoPageCallback();
    catch
    end
    set(api.hPanel,'visible','on');

  end

  function setLeavePageCallback(callback)

    progressApi.leavePageCallback = callback;

  end

  function setGotoPageCallback(callback)

    progressApi.gotoPageCallback = callback;

  end

  function localPrevCallback(varargin)

    if numel(progressApi.prevPage) > 0

      progressApi.currentPage = progressApi.prevPage{end};
      progressApi.prevPage(end) = [];

      enablePrev(numel(progressApi.prevPage)>0);

      showPage();

    end

  end

  function localNextCallback(varargin)

    nextPage = progressApi.leavePageCallback();

    if ~isempty(nextPage)

      progressApi.prevPage{end+1} = progressApi.currentPage;
      progressApi.currentPage = nextPage;

      enablePrev(numel(progressApi.prevPage)>0);

      showPage();

    end

  end

  function localPlotDataCallback(varargin)

    data = api.getDataTransformed();
    figure

    if isa(data,'EBSD') && strcmp('pageSS',char(progressApi.currentPage)) % && numel(data.indexedPhasesId) == 1

      counts = accumarray(data.phaseId,1);
      [~,maxPhaseId] = max(counts(2:end));
      ind = data.phaseId == (1+maxPhaseId);
      ori = data(ind).orientations;
      plot(data(ind),ori);
      set(gcf,'name',['IPF Z map of phase ' data.CSList{maxPhaseId+1}.mineral])

      figure
      h = ori.CS.basicHKL;
      plotPDF(ori,h(1:3),'contourf','antipodal');
      set(gcf,'name',['pole figures of phase ' data.CSList{maxPhaseId+1}.mineral])

    else

      plot(data,'silent');
    end

  end

  function localFinishCallback(varargin)

    e = WizardFinish(api);

    if ~e, close(api.hFigure); end

  end

  function gui = localCreateGUIControls()

    parent = api.hFigure;
    w    = api.Spacings.Width;
    m    = api.Spacings.Margin;

    bW   = api.Spacings.ButtonWidth;
    bH   = api.Spacings.ButtonHeight;
    pH   = api.Spacings.BottomHeight;
    fs   = api.Spacings.FontSize;

    pos = @(offset) [offset pH-bH-m bW bH];

    % navigation
    next =  uicontrol(...
      'Parent',parent,...
      'String','Next >>',...
      'FontSize',fs,...
      'Position',pos(w-2*bW-2*m));

    prev = uicontrol(...
      'Parent',parent,...
      'String','<< Previous',...
      'FontSize',fs,...
      'Position',pos(w-3*bW-2*m));

    finish = uicontrol(...
      'Parent',parent,...
      'String','Finish',...
      'Enable','off',...
      'FontSize',fs,...
      'Position',pos(w-bW-m));

    plot = uicontrol(...
      'Parent',parent,...
      'String','Plot',...
      'FontSize',fs,...
      'Position',pos(m),...
      'Visible','on');

    uipanel(...
      'BorderType','line',...
      'BorderWidth',1,...
      'units','pixel',...
      'parent',parent,...
      'FontSize',fs,...
      'HighlightColor',[0 0 0],...
      'Position',[m pH w-2*m 1]);

    gui.hNext    = next;
    gui.hPrev    = prev;
    gui.hFinish  = finish;
    gui.hPlot    = plot;

  end

  function enableNext(b)

    set(gui.hNext,'enable',state{1+b});

  end

  function enablePrev(b)

    set(gui.hPrev,'enable',state{1+b});

  end

  function enableFinish(b)

    set(gui.hFinish,'enable',state{1+b});

  end

  function enablePlot(b)

    set(gui.hPlot,'enable',state{1+b});

  end

end


function imgFrame(fig,file,ax)

% IMGFRAME  Exports figure graphics to image file.
%   IMGFRAME(FIG,FILE) creates from the graphics contents of FIG
%   a image file FILE.
%
%   IMGFRAME(FIG,FILE,AX) uses the contents of axes AX in
%   figure FIG instead.
%
%   Examples:
%       imgFrame(1,'image.png',gca) exports the current axes in figure 1.
%       imgFrame(gcf,'image.png') exports the current figure.
%       imgFrame(1,sprintf('image-%03d.png',t)) for loops governed by index
%           t, exports the figure 1 at time t. Use it to make movies.
%
%   See also GETFRAME, FRAME2IM, IMWRITE.

%   Copyright 2008-2009 Joan Sola @ LAAS-CNRS.

% figure(fig)
if nargin < 3
    frmh = fig;
else
    frmh = ax;
end

% drawnow
frm = getframe(frmh);
im  = frame2im(frm);
imwrite(im,file);

% ========== End of function - Start GPL license ==========

%   # START GPL LICENSE

%---------------------------------------------------------------------
%
%   This file is part of SLAMTB, a SLAM toolbox for Matlab.
%
%   SLAMTB 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.
%
%   SLAMTB 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 SLAMTB.  If not, see <http://www.gnu.org/licenses/>.
%
%---------------------------------------------------------------------

%   SLAMTB is Copyright:
%   Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,
%   Copyright (c) 2010-2013, Joan Sola,
%   Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,
%   SLAMTB is Copyright 2009
%   by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol
%   @ LAAS-CNRS.
%   See on top of this file for its particular copyright.

%   # END GPL LICENSE


function text2speech(str, lang, t_play)
% This is a command line demo on how to use the ActiveX VideoLAN.VLCPlugin.2 in combination with the
% unofficial google text to speech (TTS) engine to generate speech from text.
% You need to install the VLC-Media-Player and have a internetconnection to call the google service.
%
% The input parameters are:
%   - the string you want to convert:                       str
%   - then string of language code for the str:             lang   {'en','de','es', 'fr'}
%   - and the time in seconds until programm resumes:       t_play
%     if the time is to short, you'll maybe not hear everything
%
% Function call:
%     text2speech --> says 'Hello World' in english
%     text2speech('Guten Morgen!','de') --> says good morning in german
%     text2speech('Je t'aime.','fr')    --> says I love you in french
%
% Bugs and suggestions:
%    Please send to Sven Koerner: koerner(underline)sven(add)gmx.de
%
% You need to download and install first:
%    The VLC Media Player:  http://www.videolan.org/vlc/
%
%
% Programmed by Sven Koerner: koerner(underline)sven(add)gmx.de
% Date: 2011/11/04

% Standard time until close is 2 Seconds
if nargin < 3
    t_play = 2;
end
% Standard language is english
if nargin < 2
    lang = 'en';
end

% Standard sentence
if nargin < 1,
    str = 'Hello World!';
end;

% Create invisible figure
fig = figure('units','characters','position', [1 1 1 1] ,'Toolbar','none','DoubleBuffer', 'on', 'Name', 'Read it!', 'NumberTitle', 'off','MenuBar','none','Visible','off');

% Preapare String:
% limit string to at least 100 characters and replace blanks
try
    str = strrep(str(1:100),' ','+');
catch
    str = strrep(str,' ','+');
end;

% insert the vlc-component invisible to figure
vlc1 = actxcontrol('VideoLAN.VLCPlugin.2', [1 1 0 0], fig);
vlc1.Volume   = 50;   % Set Volume
vlc1.AutoLoop = 0;    % Set Autoloop
vlc1.playlist.add(['http://translate.google.com/translate_tts?tl=',lang ,'&q=', str] );  % Unofficial text to speech  by google
vlc1.playlist.play;   % play it
pause(t_play);        % wait a while
close();              % close the fig


% OtQueryPrior Move to the previous record of the query.
%
% Usage:
%    OtQueryPrior(hquery)

% OtMatlab: Matlab interface to the Omnitrans transport planning software

% Copyright (c) 2008, VORtech Computing
% Copyright (c) 2010, Omnitrans International

% All rights reserved.

% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are
% met:

%     * Redistributions of source code must retain the above copyright
%       notice, this list of conditions and the following disclaimer.
%     * Redistributions in binary form must reproduce the above copyright
%       notice, this list of conditions and the following disclaimer in
%       the documentation and/or other materials provided with the distribution
%     * Neither the name of VORtech Computing and Omnitrans International nor the names
%       of its contributors may be used to endorse or promote products derived
%       from this software without specific prior written permission.

% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
% POSSIBILITY OF SUCH DAMAGE.

% 2006-04-11 Created (Johan Meijdam, VORtech)

function iret = OtQueryPrior(hquery)
   iret = Ot('query.prior', hquery);
end


% ********************************************************************
% * mex File compiling code for Random Forest (for linux)
% * mex interface to Andy Liaw et al.'s C code (used in R package randomForest)
% * Added by Abhishek Jaiantilal ( abhishek.jaiantilal@colorado.edu )
% * License: GPLv2
% * Version: 0.02
% ********************************************************************/
function compile_linux

    system('rm *.mexglx *.mexa64;');

    system('make clean;make mex;');

    %the fortran code makes it hard to NOT use the Makefile


function par_filehost(varargin)
% This function starts a file host on the network.
%
% Notes:
%     The request format accepted by this host on a UDP broadcast port (default 34575) is (without <>'s)
%     <command>\n
%     <argument1>=<value1>
%     <argument2>=<value2>
%     <argument3>=<value3>
%     ...
%
%     Supported commands:
%     getfile -- return a file, either from memory cache or disk (if this host is responsible)
%     filname=<name of file to retrieve or expression that can be evaluated>
%     force=<whether to force-load the data even if it would exceed the allotted capacity>
%     return_address=<IP address or hostname to send the result to>
%     return_port=<port number of return endpoint>
%
%     evict -- evict file from memory cache if present
%     filename=<name of file to evict from memory cache>
%     anyhost=<evict even if not the responsible host>
%
%     terminate -- terminate this file host
%     return_address=<IP address or hostname to send the result to>
%     return_port=<port number of return endpoint>
%
%     getrank -- get the rank of this host among all known file server hosts
%     return_address=<IP address or hostname to send the result to>
%     return_port=<port number of return endpoint>
%
%     allhosts -- get the list of hosts as a cell array
%     return_address=<IP address or hostname to send the result to>
%     return_port=<port number of return endpoint>
%
%     hostname -- get the hostname of this machine
%     return_address=<IP address or hostname to send the result to>
%     return_port=<port number of return endpoint>
%
%     max_capacity -- get the allowed cache capacity of this machine in GB
%     return_address=<IP address or hostname to send the result to>
%     return_port=<port number of return endpoint>
%
%     clear -- clear cache
%     return_address=<IP address or hostname to send the result to>
%     return_port=<port number of return endpoint>
%
% See also:
%   par_fileclient, io_load
%
%                               Christian Kothe, Syntrogi
%                               2015-06-27

% the database (not persistent so we can change the code without erasing it)
global db;      % struct mapping of cache-tag --> data-blob
global lru;     % cell array of recently-used cache tags (sorted by increasing age)
if ~iscell(lru)
    lru = {}; end

fprintf('parsing arguments...');
settings = arg_define(varargin, ...
    arg({'all_hosts','AllHosts'}, {}, [], 'Hostnames where filehosts are running. Used for load-balancing. If this is set to empty, then we are only accepting connections from localhost.'), ...
    arg({'rank_override','RankOverride'}, 0, int32([0 1000]), 'Rank of this instance (1-based). Only used if the current hostname is not in the set AllHosts.'), ...
    arg({'max_capacity','MaxCapacity'}, 90, [1 10 256 100000], 'Maximum memory capacity. In Gigabytes.'), ...
    arg({'accept_pattern','AcceptPattern'}, '*', [], 'File name pattern that is accepted by this host.'), ...
    arg({'per_pattern_capacity','PerPatternCapacity'}, {}, [], 'Per-pattern capacity. This is a cell array of {pattern,capacity,pattern,capacity,...} where pattern are wildcard patterns.','type','expression'), ...
    arg({'evict_policy','EvictPolicy'}, 'lru', {'lru','none'}, 'Eviction policy. What entries will be evicted from memory if capacity is exceeded. If none, no more files will be cached after capacity has been exceeded.'), ...
    arg({'request_port','RequestPort'}, 34575, uint32([1 65535]), 'UDP port on which requests are being received.'), ...
    arg({'timeout_backconnect','TimeoutBackconnect',},1000,[],'Timeout for back-connection. In miliseconds. If it takes longer than this to connect back to the requester we give up.','guru',true), ...
    arg({'timeout_transmit','TimeoutTransmit',},60000,[],'Timeout for transmission. In miliseconds. If we get a hiccup during back-transmission that is longer than this we give up.','guru',true), ...
    arg({'accept_packet_size','AcceptPacketSize'},1400,uint32([1 508 1472 65507]),'Maximum packet size accepted by this host.','guru',true));
fprintf('done.\n');

% maximum amount of memory used inside the Java VM
max_java_memory = 2^26; % 64 MB

fprintf('Importing java packages...');
import java.io.*
import java.net.*
import java.lang.*
fprintf('done.\n');

myhost = hlp_hostname;
fprintf('This is par_filehost on %s.\n',myhost);

% determine which rank we have
matching = strcmp(settings.all_hosts,myhost);
if any(matching)
    myrank = find(matching);
    fprintf('Rank of this host is %i/%i (based on AllHosts).\n',myrank,length(matching));
    fprintf('Allhosts was: %s\n',hlp_tostring(settings.all_hosts));
elseif settings.rank_override
    myrank = settings.rank_override;
    fprintf('Rank of this host is %i (based on RankOverride).\n',myrank);
elseif isempty(settings.all_hosts)
    myrank = -1; % -1 encodes that we're operating in local mode
    fprintf('Neither AllHosts nor RankOverride given: responding only to localhost requests.\n');
else
    fprintf('Error: this host is not in AllHosts and no RankOverride was given. Exiting...\n');
    return;
end

% initialize request socket
fprintf('opening request socket...');
req_socket = DatagramSocket(settings.request_port,InetAddress.getByName('0.0.0.0')); %req_socket = DatagramSocket(settings.request_port,InetAddress.getByName('255.255.255.255'));
if myrank > 0
    req_socket.setBroadcast(true); end
req_socket.setSoTimeout(500);
closer = onCleanup(@()req_socket.close());
fprintf('done.\n');

% get own IP address
myaddr = char(InetAddress.getLocalHost());
myaddr = hlp_split(myaddr,'/');
myaddr = myaddr{2};
fprintf('listening on %s...\n',myaddr);

while true
    try
        % get next request
        fprintf('\n\nwaiting for next packet...');
        packet = DatagramPacket(uint8(zeros(1,settings.accept_packet_size)),settings.accept_packet_size);
        while true
            try
                req_socket.receive(packet);
                break;
            catch e
                if isempty(strfind(e.message,'timed out'))
                    rethrow(e); end
            end
        end
        content = char(packet.getData');
        srcport = packet.getPort();
        srcaddr = char(packet.getAddress());
        srcaddr = srcaddr(2:end);
        if myrank < 0 && ~(strcmp(srcaddr,myaddr) || strcmp(srcaddr,'127.0.0.1'))
            % not from this host while we're in local mode
            continue;
        else
            fprintf('got packet:\n%s\n\n',content);
        end

        % handle the request
        [command,args] = parse_request(content);
        fprintf('handling command %s; %i arguments.\n',command,length(fieldnames(args)));
        reply = [];
        switch command
            % --- primary commands ---
            case 'getfile'
                get_file(args);
            case 'evict'
                evict_file(args);
                % --- control commands ---
            case 'terminate'
                fprintf('  received termination command; exiting...\n');
                send_reply_udp(args,'ReplyContent',[myhost ' terminated']);
                return;
                % ---- diagnostics ---
            case 'getrank'
                reply = hlp_tostring(myrank);
            case 'allhosts'
                reply = hlp_tostring(settings.all_hosts);
            case 'hostname'
                reply = hlp_hostname;
            case 'max_capacity'
                reply = hlp_tostring(max_capacity);
            case 'clear'
                fprintf('  clearing database...');
                db = [];
                lru = {};
                fprintf('done.\n');
                reply = [myhost ' database cleared'];
            otherwise
                fprintf('  unrecognized command.\n');
        end
        % handle misc replies
        if ~isempty(reply)
            send_reply_udp(args,'ReplyContent',reply); end
    catch e
        fprintf('error: %s',hlp_handleerror(e));
        pause(2);
    end
end

    % === command handlers ===

    function get_file(varargin)
        import java.net.*
        import java.io.*
        % retrieve a file either from memory cache or from disk (if necessary)
        opts = hlp_varargin2struct(varargin, ...
            {'filename','FileName'},'', ...
            {'force','Force'},false, ...
            {'return_address','ReturnAddress'},'', ...
            {'return_port','ReturnPort'},'');

        % check if we're responsible, etc.
        [tag,namehash,responsible_host] = db_tag_if_responsible(opts.filename);
        try
            responsible_hostname = settings.all_hosts{responsible_host};
        catch
            responsible_hostname = 'N/A';
        end
        fprintf('Handling get_file request for file "%s" (hash: %s), responsible_host=%i (%s)...\n',opts.filename,namehash,responsible_host,responsible_hostname);
        if isempty(tag)
            fprintf('not responsible; ignoring.\n');
        else
            % got a request that we need to handle
            result = [];

            % check if the file matches our accept pattern
            pattern = ['^',strrep(strrep(settings.accept_pattern,'?','.'),'*','.{0,}'),'$'];
            if isempty(regexp(opts.filename,pattern, 'once'))
                fprintf('file does not match accept pattern; ignoring.\n');
            else
                if isfield(db, tag)
                    % record in cache: return it
                    fprintf('found record in cache.\n');
                    result = db.(tag);
                    lru = [{tag} lru(~strcmp(lru,tag))];
                else
                    % record not in cache
                    is_expression = any(opts.filename=='(') && any(opts.filename==')');
                    if ~is_expression && ~exist(opts.filename,'file')
                        fprintf('file does not exist.\n');
                    else
                        % check if it would fit in our DB, calculate itemsize and optionally result
                        capacity = settings.max_capacity*2^30;
                        if is_expression
                            fprintf('item appears to be a MATLAB expression, evaluating...');
                            % this is actually not a file name but an expression that we can
                            % evaluate
                            try
                                result = eval(opts.filename);
                                fprintf('success.\n');
                            catch e
                                fprintf('could not evaluate expression: %s',hlp_handleerror(e));
                                result = e;
                            end
                            if all(isfield(result,{'head','parts'}))
                                try
                                    fprintf('result is a BCILAB expression, evaluating...');
                                    result = exp_eval(result);
                                    fprintf('success.\n');
                                catch e
                                    fprintf('could not evaluate expression: %s',hlp_handleerror(e));
                                    result = e;
                                end
                            end
                            try
                                t0=tic; fprintf('serializing data structure into bytes...');
                                result = hlp_serialize(result);
                                fprintf('success (%.1f seconds).\n',toc(t0));
                            catch e
                                fprintf('could not serialize data structure: %s',hlp_handleerror(e));
                                result = hlp_serialize(e);
                            end
                            itemsize = getfield(whos('result'),'bytes');
                        else
                            % this is a file, check the size
                            itemsize = getfield(dir(opts.filename),'bytes');
                        end
                        dbsize = getfield(whos('db'),'bytes');
                        fprintf('\ndb parameters: capacity:%.3fGB, itemsize:%.3fGB, dbsize:%.3fGB, records:%f\n',capacity/2^30,itemsize/2^30,dbsize/2^30,length(lru));
                        % determine if this fits in our cache...
                        if (strcmp(settings.evict_policy,'lru') && (itemsize < capacity)) || (strcmp(settings.evict_policy,'none') && (dbsize+itemsize < capacity)) || opts.force
                            if isempty(result)
                                % don't have the result yet
                                t0=tic; fprintf('loading file...');
                                f = fopen(opts.filename,'r');
                                filecloser = onCleanup(@()fclose(f));
                                result = fread(f,inf,'*uint8');
                                fprintf('%.1f seconds (read bandwidth: %.2fMB/s).\n',toc(t0),itemsize/2^20/toc(t0));
                            else
                                % (have the result already, no need to load)
                            end
                            % cache it if applicable
                            if strcmp(settings.evict_policy,'none') && (dbsize+itemsize < capacity)
                                fprintf('committing to db.\n');
                                db.(tag) = result;
                                lru = [{tag} lru(~strcmp(lru,tag))];
                            elseif strcmp(settings.evict_policy,'lru') && (itemsize < capacity)
                                % evict least-recently used records until we're within the capacity limits
                                fprintf('committing to db.\n');
                                db.(tag) = result;
                                lru = [{tag} lru(~strcmp(lru,tag))];
                                if itemsize+dbsize > capacity
                                    fprintf('evicting least-recently used cache records');
                                    initialsize = getfield(whos('db'),'bytes');
                                    while ~isempty(fieldnames(db))
                                        fprintf('.');
                                        db = rmfield(db,lru(end));
                                        lru(end) = [];
                                        if getfield(whos('db'),'bytes') < capacity
                                            break; end
                                    end
                                    fprintf('done. Evicted %.3fGB of data.\n',(initialsize - getfield(whos('db'),'bytes'))/2^30);
                                end
                            end
                        else
                            fprintf('does not fit in allowed cache capacity; not loading.\n');
                        end
                    end
                end
            end

            % send off the result
            if isa(result,'uint8')
                [return_address,return_port] = get_return_endpoint(opts);
                fprintf('preparing to return result to requestor at %s:%i\n',char(return_address.toString()),return_port);
                % send the data back
                fprintf('opening back-connection to transmit data...');
                outconn = Socket();
                destination = InetSocketAddress(return_address, return_port);
                outconn.connect(destination, round(settings.timeout_backconnect));
                sockcloser = onCleanup(@()outconn.close());
                outconn.setSoTimeout(round(settings.timeout_transmit));
                outconn.setSoLinger(true,3);
                fprintf('connected.\nnow sending (%.0fkb)...',length(result)/1024);
                t0 = tic;
                out = DataOutputStream(outconn.getOutputStream());
                out.writeDouble(length(result));
                % we need to efficiently split the data into chunks no larger than max_java_memory
                num_blocks = ceil(length(result)/max_java_memory);
                rest_size = mod(length(result),max_java_memory);
                sizes = [max_java_memory*ones(1,num_blocks-1) rest_size];
                blocks = cell(length(sizes),1);
                [blocks{:}] = chopdeal(result,sizes);
                % send the blocks off
                for i=1:length(blocks)
                    out.write(blocks{i},0,sizes(i)); end
                out.flush();
                fprintf('done (%.1f seconds; %.2fMB/s bandwidth)\nnow closing...',toc(t0),length(result)/2^20/toc(t0));
                fprintf('done.\ntransaction complete.\n');
            end
        end
    end

    function evict_file(varargin)
        % evict a file record from cache
        opts = hlp_varargin2struct(varargin, ...
            {'filename','FileName'},'', ...
            {'anyhost','AnyHost'},false);
        [tag,namehash,responsible_host] = db_tag_if_responsible(opts.filename, opts.anyhost);
        fprintf('Handling evict request for file "%s" (hash: %s), responsible_host=%i (%s)...',opts.filename,namehash,responsible_host,settings.all_hosts{responsible_host});
        if isfield(db,tag)
            try
                db = rmfield(db,tag);
                lru(strcmp(lru,tag)) = [];
                fprintf('evicted record.\n');
            catch e
                fprintf('could not evict record (%s); database may now be inconsistent.\n', e.message);
            end
        elseif ~isempty(tag)
            fprintf('no record in database.\n');
        else
            fprintf('no record in database or not responsible.\n');
        end
    end

    % === helper functions ===

    function send_reply_udp(varargin)
        import java.net.*
        % send a reply message over UDP
        opts = hlp_varargin2struct(varargin, ...
            {'reply_content','ReplyContent'},'');
        [return_address,return_port] = get_return_endpoint(opts);
        fprintf('sending reply packet to %s:%i...',char(return_address.toString()),return_port);
        repl_sock = DatagramSocket();
        repl_packet = DatagramPacket(uint8(opts.reply_content),length(opts.reply_content),return_address,return_port);
        repl_sock.send(repl_packet)
        fprintf('done.\n')
    end

    function [return_address, return_port] = get_return_endpoint(varargin)
        import java.net.*
        % determine the return endpoint based on the global srcaddr/port or override options
        opts = hlp_varargin2struct(varargin, ...
            {'return_address','ReturnAddress'},'', ...
            {'return_port','ReturnPort'},'');
        % allow overriding the return address / port
        fprintf('determining return address/port...');
        if isfield(opts,'return_address') && ~isempty(opts.return_address)
            return_address = InetAddress.getByName(opts.return_address);
        else
            return_address = InetAddress.getByName(srcaddr);
        end
        if isfield(opts,'return_port') && ~isempty(opts.return_port)
            if ischar(opts.return_port)
                return_port = str2num(opts.return_port);
            else
                return_port = opts.return_port;
            end
        else
            return_port = srcport;
        end
        fprintf('done (%s:%i).\n', char(return_address), return_port);
    end

    function [tag,namehash,responsible_host] = db_tag_if_responsible(filename, anyhost)
        % returns a database tag if we're responsible for the given filename or empty otherwise
        % get a hash of the filename
        if nargin < 2
            anyhost = false; end
        namehash = hlp_cryptohash(filename);
        % check if we're responsible for this file
        responsible_host = 1+mod(hex2dec(namehash(1:5))+1,length(settings.all_hosts));
        if anyhost || myrank < 0 || responsible_host == myrank
            tag = ['x_' namehash];
        else
            tag = [];
        end

    end

    function [command,args] = parse_request(content)
        % parses HTTP-style requests (see top of this file for format) into command string and
        % argument struct
        content(content==0) = [];
        % parse a network request packet
        lines = hlp_split(content,sprintf('\n'));
        % first line is the command
        command = strtrim(lower(lines{1}));
        % followed by one argument per line
        args = [];
        for l=2:length(lines)
            line = strtrim(lines{l});
            % strip comments (beginning with ;)
            comment = find(line == ';',1);
            if ~isempty(comment)
                line = line(1:comment-1); end
            if isempty(line)
                continue; end
            % handle assignments
            equals = find(line == '=',1);
            if isempty(equals)
                fprintf('the line "%s" is not a valid argument declaration; ignoring.\n',line); end
            key = strtrim(line(1:equals-1));
            val = strtrim(line(equals+1:end));
            try
                args.(key) = val;
            catch
                fprintf('argument "%s" is not a valid field name; ignoring.\n',key);
            end
        end
    end
end


function [VMH_existance,rBioNet_existance,metab_rBioNet_online,rxn_rBioNet_online,metabolite_structure_rBioNet] = checkAbbrExists(list,metab_rBioNet_online,rxn_rBioNet_online,metabolite_structure_rBioNet)
% This function checks whether the abbreviations in the list exist already
% in the VMH or the most recent rBioNetDB either as reaction or metabolite
% abbr
%
% INPUT
% list                          List of abbreviations (either metabolite or reactions);
%                               Alternatively a metabolite structure can be given as input and more
%                               fields are compared
% metab_rBioNet_online
% rxn_rBioNet_online
% metabolite_structure_rBioNet
%
% OUTPUT
% VMH_existance                 Lists whether the abbreviation exists in VMH (online),
%                               as a reaction (2nd entry) or as a metabolite (3rd entry)
% rBioNet_existance             Lists whether the abbreviation exists in rBioNet (as deposited in cobra toolbox online),
%                               as a reaction (2nd entry) or as a metabolite (3rd entry)
%
%
% Ines Thiele 09/2021

% create temporary folder for the rBioNetDB
mkdir('data');

check4 = {
    'keggId'
    %     'biocyc'
    'hmdb'
    %     'cheBIId'
    %     'chembl'
    %    % 'chemspider'
    %     'drugbank'
    %     'lipidmaps'
    % %    'pubChemId'
    %     'seed'
    'inchiString'
    'inchiKey'
    };

if isstruct(list)
    metabolite_structure = list;
    clear list
    F = fieldnames(metabolite_structure);
    % get VMHId's from metabolite structure
    for i = 1 : length(F)
        % contains the VMDID's for check for uniqueness as if a list would have
        % provided only
        list{i,1} = metabolite_structure.(F{i}).VMHId;
        fieldList{i,1} = metabolite_structure.(F{i}).VMHId;
        fieldList{i,2} = F{i};
        for k = 1 : length(check4)
            if isnumeric(metabolite_structure.(F{i}).(check4{k}))
                fieldList{i,k+2} = num2str(metabolite_structure.(F{i}).(check4{k}));
                %if inchikey is incorrect
            elseif string(metabolite_structure.(F{i}).(check4{k}))=='InChI'
                fieldList{i,k+2}='NaN';
            else
                fieldList{i,k+2} = metabolite_structure.(F{i}).(check4{k});
            end
        end
    end
end

% load most recent version of rBioNetDB
if ~exist('metab_rBioNet_online','var') ||  ~exist('rxn_rBioNet_online','var')
    websave('data/MetaboliteDatabase.txt','https://raw.githubusercontent.com/opencobra/COBRA.papers/master/2021_demeter/input/MetaboliteDatabase.txt');
    websave('data/ReactionDatabase.txt','https://raw.githubusercontent.com/opencobra/COBRA.papers/master/2021_demeter/input/ReactionDatabase.txt');
    createRBioNetDBFromVMHDB('rBioNetDBFolder','data/');
    load('data/rxn.mat');
    load('data/metab.mat');
    metab_rBioNet_online = metab;
    rxn_rBioNet_online = rxn;
else
    metab = metab_rBioNet_online;
    rxn = rxn_rBioNet_online;
end

% load extended rBioNet -- Not implemented yet
if ~exist('metabolite_structure_rBioNet','var')
    load met_strc_rBioNet;
end
F = fieldnames(metabolite_structure_rBioNet);
for i = 1 : length(F)
    FR{i,1} = metabolite_structure_rBioNet.(F{i}).VMHId;
    FR{i,2} = F{i};
    for k = 1 : length(check4)
        if isnumeric(metabolite_structure_rBioNet.(F{i}).(check4{k}))
            FR{i,k+2} = num2str(metabolite_structure_rBioNet.(F{i}).(check4{k}));
        else
            if strcmp(check4{k},'hmdb')
                % preplace old style abbr with new style
                FR{i,k+2} = convertOld2NewHMDB(metabolite_structure_rBioNet.(F{i}).(check4{k}));
            else
                FR{i,k+2} = metabolite_structure_rBioNet.(F{i}).(check4{k});
            end
        end
    end
end

% check that rxn abbr does not exist in VMH or rBioNetDB
for i = 1 : size(list,1)
    % check by abbreviation
    % VMH check using the url
    VMH{i,1} = list{i};
    url1 = ['https://www.vmh.life/_api/reactions/?abbreviation=' list{i}];
    url2 = ['https://www.vmh.life/_api/metabolites/?abbreviation=' list{i}];
    output1 = webread(url1);
    output2 = webread(url2);
    if isempty(output1.results) %% rxn abbr does not exist
        VMH{i,2} = num2str(0);
    else
        VMH{i,2} = num2str(1);
    end
    if isempty(output2.results) %% met abbr does not exist
        VMH{i,3} = num2str(0);
    else
        VMH{i,3} = num2str(1);
    end
    % check by abbreviation
    % check rBioNet
    rBioNet{i,1} =  list{i};
    if ~isempty(find(ismember(rxn(:,1),list{i})))
        rBioNet{i,2} =  num2str(1);
    else
        rBioNet{i,2} =  num2str(0);
    end
    if ~isempty(find(ismember(metab(:,1),list{i})))
        rBioNet{i,3} =  num2str(1);
    else
        rBioNet{i,3} =  num2str(0);
    end
    % check against rBioNet structure
    if ~isempty(find(ismember(FR(:,1),list{i})))
        rBioNet{i,3} =  num2str(1);
        rBioNet{i,4} =  list{i};
    end
    % check using database ID's
    % against extended rBioNet structure
    if exist('metabolite_structure','var')
        for k = 1 : length(check4)
            if ~strcmp(fieldList{i,2+k},'NaN')
                if ~isempty(find(ismember(FR(:,2+k),fieldList(i,2+k))))
                    match = find(ismember(FR(:,2+k),fieldList(i,2+k)));
                    rBioNet{i,3}  =  num2str(1);
                    rBioNet{i,4}  = FR{match,1};
                    rBioNet{i,5}  = fieldList(i,2+k);
                else
                    % if there are multiple IDs possible per entry (happens a
                    % lot for HMDB). Prioritise 1. one
                    if strcmp(check4{k},'hmdb') && contains(fieldList(i,2+k),';')
                        [tok] = split(fieldList(i,2+k),';');
                        for r = 1 : length(tok)
                            if ~isempty(find(ismember(FR(:,2+k),tok{r})))
                                match = find(ismember(FR(:,2+k),tok{r}));
                                rBioNet{i,3}  =  num2str(1);
                                rBioNet{i,4}  = FR{match,1};
                                rBioNet{i,5}  = fieldList(i,2+k);
                                % once a hit is found, the others are not
                                % recorded anymore!
                                r = length(tok) + 1;
                            end
                        end
                    end
                end
            end
        end
    end
end
VMH_existance = VMH;
rBioNet_existance = rBioNet;

if ~isempty(find(contains(VMH_existance(:,2:3),'1')))
    % abbr exist in VMH
    fprintf('At least one abbrevation exists already in the VMH.\n');
else
    fprintf('All abbreviations are new to the VMH.\n');
end
if ~isempty(find(contains(rBioNet_existance(:,3),'1')))
    % abbr exist in VMH
    fprintf('At least one abbrevation exists already in rBioNet.\n');
else
    fprintf('All  abbreviations are new to rBioNet.\n ');
end

% remove temporary folder for the rBioNetDB
%warning off;
%rmdir('data','s');


function matches = dir_regex(path, expression, return_paths)
%DIR_REGEX Returns contents in the path matching a regular expression.
% Usage:
%   matches = dir_regex(path, expression)
%   matches = dir_regex(path, expression, true) % returns full paths
%
% See also: regexp, dir_ext, dir_paths

% Default: returns just filenames
if nargin < 3; return_paths = false; end

% Get directory listing
listing = dir_paths(path);

% Test regex
matches = listing(~areempty(regexp(listing, expression)));

% Singleton output
if iscell(matches) && numel(matches) == 1
    matches = matches{1};
end

% Return just the filenames
if ~return_paths
    matches = get_filename(matches);
end

end


function play(db,index)
%PLAY - plays a MatlabADT sentence.
%play(ADTobj,index)
%See also query, filterdb, read, play.
[data,smpr] = read(db,index);
for i=1:length(data)
    sound(data{i},smpr);
end
end


classdef VideoMaker < handle

    properties (GetAccess = private, SetAccess = public)
        iterations
    end

    properties (Access = private)
        gidPath
        tclFileName
        filesFolder
        tclFileWriter
        tclTemplateName
        fieldName
        outputName
    end

    properties (Access = private)
        outPutNames
        fileName
        designVariableName
        tclTemplateNames
    end

    methods (Access = public)

        function makeVideo(obj)
            obj.makeDesignVariableVideo();
            obj.makeRegularizedDesignVariableVideo();
        end

    end

    methods (Access = public, Static)

        function obj = create(cParams)
            f = VideoMakerFactory();
            obj = f.create(cParams);
        end

    end

    methods (Access = protected)

        function init(obj,cParams)
            obj.fileName           = cParams.caseFileName;
            obj.designVariableName = cParams.designVarType;
            obj.tclTemplateNames   = cParams.tclTemplateNames;
            obj.outPutNames        = cParams.outPutNames;
            obj.createPaths();
            obj.createFolder();
        end

    end

    methods (Access = private)

        function createFolder(obj)
            if ~exist(obj.filesFolder,'dir')
                mkdir(obj.filesFolder);
            end
        end

        function createPaths(obj)
            %obj.gidPath = '/home/alex/GiDx64/14.1.9d';
            obj.gidPath = '/home/alex/GiDx64/gid-15.0.3';
            obj.filesFolder = fullfile(pwd,'Output',obj.fileName);
        end

        function makeDesignVariableVideo(obj)
            for ivideo = 1:numel(obj.tclTemplateNames)
                obj.tclTemplateName = obj.tclTemplateNames{ivideo};
                obj.fieldName = obj.designVariableName;
                obj.outputName = [obj.fileName,obj.outPutNames{ivideo}];
                obj.makeFieldVideo();
            end
        end

        function makeRegularizedDesignVariableVideo(obj)
            obj.fieldName = 'DensityGauss';
            obj.tclTemplateName = 'Make_Video_density';
            obj.outputName = [obj.fileName,obj.fieldName];
            obj.makeFieldVideo();
        end

        function makeFieldVideo(obj)
            obj.createTclFileName();
            obj.createTclFileWriter();
            obj.writeTclFile();
            obj.executeTclFile();
            obj.deleteTclFile();
        end

        function createTclFileName(obj)
            fName = 'tcl_gid.tcl';
            obj.tclFileName = fullfile(obj.filesFolder,fName);
        end

        function createTclFileWriter(obj)
            s.type            = obj.fieldName;
            s.tclFileName     = obj.tclFileName;
            s.filesFolder     = obj.filesFolder;
            s.outputName      = obj.outputName;
            s.iterations      = obj.iterations;
            s.fileName        = obj.fileName;
            s.tclTemplateName = obj.tclTemplateName;
            obj.tclFileWriter = TclFileWriter(s);
        end

        function writeTclFile(obj)
            obj.tclFileWriter.write();
        end

        function executeTclFile(obj)
            tFile = replace(obj.tclFileName,'\','\\');
            gFile = fullfile(obj.gidPath,'gid_offscreen');
            executingLine = ['"',gFile,'"',' -offscreen', ' -t ' ,'"source ',tFile,'"'];
            system(executingLine);
        end

        function deleteTclFile(obj)
            tFile = obj.tclFileName;
            if ispc
                system(['DEL ',tFile]);
            elseif isunix
                system(['rm ',tFile]);
            elseif ismac
            end
        end

    end

end


function ieFontInit(fig)
%Initialize the font size based on the preference setting
%
%   ieFontInit(fig)
%
% Font sizes are managed using the preference mechanism in Matlab. The font
% size is a field, fontDelta, in the mrVista preference structure. That
% information is retrieved here and the font size is changed based on this
% setting. This setting is stored across sessions.
%

vistaPref = getpref('mrVista');
if ~isempty(vistaPref)
    if checkfields(vistaPref,'fontDelta')
        fontDelta = getpref('vistaPref','fontDelta');
        ieFontChangeSize(fig,fontDelta);
    end
end

return;


function [varargout] = istable(varargin)

% ISTABLE is a drop-in replacement for the same function that was
% introduced in MATLAB R2013b.
%
% In all MATLAB versions prior to 2013b this function returns false.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% try to automatically remove incorrect compat folders from the path, see https://github.com/fieldtrip/fieldtrip/issues/899

if isempty(strfind(mfilename('fullpath'), matlabroot))
  % automatic cleanup does not work when FieldTrip is installed inside the MATLAB path, see https://github.com/fieldtrip/fieldtrip/issues/1527

  alternatives = which(mfilename, '-all');
  if ~iscell(alternatives)
    % this is needed for octave, see https://github.com/fieldtrip/fieldtrip/pull/1171
    alternatives = {alternatives};
  end

  keep = true(size(alternatives));
  for i=1:numel(alternatives)
    keep(i) = keep(i) && ~any(alternatives{i}=='@');  % exclude methods from classes
    keep(i) = keep(i) && alternatives{i}(end)~='p';   % exclude precompiled files
  end
  alternatives = alternatives(keep);

  if exist(mfilename, 'builtin') || any(strncmp(alternatives, matlabroot, length(matlabroot)) & cellfun(@isempty, strfind(alternatives, fullfile('private', mfilename))))
    % remove this directory from the path
    p = fileparts(mfilename('fullpath'));
    warning('removing "%s" from your path, see http://bit.ly/2SPPjUS', p);
    rmpath(p);
    % call the original MATLAB function
    if exist(mfilename, 'builtin')
      [varargout{1:nargout}] = builtin(mfilename, varargin{:});
    else
      [varargout{1:nargout}] = feval(mfilename, varargin{:});
    end
    return
  end

end % automatic cleanup of compat directories

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% this is where the actual replacement code starts
% function tf = istable(input)

tf = false;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% deal with the output arguments

varargout = {tf};


function [metabolite_structure_rBioNet] = createrBioNetStructure(metabolite_structure_rBioNet,start,stop)
% for the moment rBioNet will serve as universal database, but I will
% update this
warning off;
mkdir('data/');
currentPath = pwd;

if ~exist('metabolite_structure_rBioNet','var')
    websave('data/MetaboliteDatabase.txt','https://raw.githubusercontent.com/opencobra/COBRA.papers/master/2021_demeter/input/MetaboliteDatabase.txt');
    websave('data/ReactionDatabase.txt','https://raw.githubusercontent.com/opencobra/COBRA.papers/master/2021_demeter/input/ReactionDatabase.txt');
   % websave('data/compartments.mat','https://raw.githubusercontent.com/opencobra/COBRA.papers/master/2021_demeter/input/compartments.mat');
   % cd data;
    createRBioNetDBFromVMHDB('rBioNetDBFolder','data');
    load('data/metab.mat');
    cd(currentPath);
end

molFileDirectory = 'C:\Users\0123322S\Documents\GitHub\chemTableFiles\ctf\mets\molFiles';

annotationType = 'automatic';

if ~exist('metabolite_structure_rBioNet','var')
    fprintf('Create metabolite structure \n');
    % create metabolite structure out of metab
    metab2={'VMHId' 'metNames' 'neutralFormula' 'chargedFormula' 'charge' 'keggId' 'pubChemID' 'cheBIId' 'inchiKey' 'smiles' 'hmdb','subsystem'};
    metab(:,end-1)=[];%remove date
    metab2 = [metab2;metab];
    [metabolite_structure_rBioNet] =createNewMetaboliteStructure(metab2,'rBioNet');

    %[metabolite_structure_rBioNet,hit] = searchMultipleUnknownMetOnline(metabolite_structure_rBioNet);

    % these files run at this point as they are all offline, loading files
    % deposited in /data/. It would take more time to open these files for each
    % metabolite.
    [IDsStart,IDcountStart,TableStart] = getStatsMetStruct(metabolite_structure_rBioNet);
end

F = fieldnames(metabolite_structure_rBioNet);
if ~exist('start','var')
    start = 1;
end
if ~exist('stop','var')
    stop = length(F);
end

if start == 1
% apparently rBioNet does not contain all recon metabolites, so I will add
% them here.
% However, I will retrieve VMH information on the metabolites at the next
% stage
% this function also assigns the presence/absence in AGORA/Recon to enable
% quick identification of currently human or microbe only metabolites
fprintf('Assign AGORA Recon Presence \n');
[metabolite_structure_rBioNet] = assignAGORAReconPresence(metabolite_structure_rBioNet);
fprintf('Metabolon mapping \n');
[metabolite_structure_rBioNet] = VMH2Metabolon(metabolite_structure_rBioNet);
fprintf('Add manually refined/corrected annotations \n');
[metabolite_structure_rBioNet] = replaceVMHIds(metabolite_structure_rBioNet);
fprintf('Assign Seed IDs \n');
[metabolite_structure_rBioNet] = VMH2Seed(metabolite_structure_rBioNet);
% offline file provided by seed/kbase
fprintf('Add Kegg IDs using Seed  \n');
[metabolite_structure_rBioNet] = getSeed2Kegg(metabolite_structure_rBioNet);
save met_strc_rBioNet_new_30_06_2022
end
inchiKey = 1;
smiles = 1;
formula = 1;

% do not query HMDB by name as it takes too much time right now.
retrievePotHMDB = 0;
retrievePotHMDB2 = 0;

for i = start:stop
    startSearch = i;
    endSearch = i;
    i
    progress = i/stop;
    fprintf([num2str(progress) '  ... Annotating metabolites from different resources ... \n']);

    % obtain info from the VMH api, this also fills the gaps from earlier
    % where recon only metabolites were added without additional
    % information
    fprintf('Connect to VMH \n');
    [metabolite_structure_rBioNet] = parseVMH4IDs(metabolite_structure_rBioNet,startSearch,endSearch);

    fprintf('Add information from mol files \n');
    [metabolite_structure_rBioNet] = addInfoFromMolFiles(metabolite_structure_rBioNet,molFileDirectory,startSearch,endSearch);

    fprintf('Find HMDB Ids \n');
    [metabolite_structure_rBioNet] = getMissingHMDBMolForm(metabolite_structure_rBioNet,molFileDirectory,retrievePotHMDB,startSearch,endSearch);

    fprintf('Collect information from different databases ... \n');
    [metabolite_structure_rBioNet] = parseDBCollection(metabolite_structure_rBioNet,startSearch,endSearch);

    fprintf('Collect more mol files \n');
    [metabolite_structure_rBioNet] = getMolFilesMultipleSources(metabolite_structure_rBioNet,molFileDirectory,startSearch,endSearch);

    fprintf('Generate database independent id from mol files \n');
    [metabolite_structure_rBioNet] = generateInchiFromMol(metabolite_structure_rBioNet,molFileDirectory, inchiKey, smiles,formula,startSearch,endSearch);

    fprintf('Collect more mol files - 2 \n');
    % now repeat the seearch for mol files again but skip the guessing of hmdb
    % ids from name

    [metabolite_structure_rBioNet] = getMissingHMDBMolForm(metabolite_structure_rBioNet,molFileDirectory,retrievePotHMDB2,startSearch,endSearch);
    [metabolite_structure_rBioNet] = getMissingDrugMolForm(metabolite_structure_rBioNet,molFileDirectory,startSearch,endSearch);
    [metabolite_structure_rBioNet] = getMolFilesMultipleSources(metabolite_structure_rBioNet,molFileDirectory,startSearch,endSearch);
    fprintf('Generate database independent id from mol files - 2 \n');

    [metabolite_structure_rBioNet] = generateInchiFromMol(metabolite_structure_rBioNet,molFileDirectory, inchiKey, smiles,formula,startSearch,endSearch);
    fprintf('Assign metabolite classification \n');

    [metabolite_structure_rBioNet] = assignClassyFire(metabolite_structure_rBioNet,startSearch,endSearch);
    %fprintf('Check that HMDB Ids are valid \n');
    % works only for HMDB right now
    % do it later, the last time only 16 out of 7900 were wrong - it takes
    % too much time
    % [metabolite_structure_rBioNet] = checkLinkValidity(metabolite_structure_rBioNet,startSearch,endSearch);
    if mod(i,10)==1
        save met_strc_rBioNet_new_30_06_2022
    end
end

% offline files
fprintf('Collecting information from Echa \n')
 [metabolite_structure_rBioNet] = getCas2Echa(metabolite_structure_rBioNet);
fprintf('Collecting information from CTD \n')
[metabolite_structure_rBioNet] = getCas2CTD(metabolite_structure_rBioNet);

% getIDsFromBIGG; --> I should use the online version --> neither one is
% accounted for in the last rBioNetX hence the final numbers are still
% lower

% sort the fields in the structure
F = fieldnames(metabolite_structure_rBioNet);
for i = 1 : length(F)
metabolite_structure_rBioNet.(F{i}) = orderfields(metabolite_structure_rBioNet.(F{i}));
end
[IDsEnd2,IDcountEnd2,TableEnd2] = getStatsMetStruct(metabolite_structure_rBioNet);
save met_strc_rBioNet_new_07_10_2021
writecell(TableEnd2,'rbionetMetStructure.xls');


function tf=moxunit_util_platform_is_octave
% return true if and only if the platform is GNU/Octave
%
% tf=moxunit_util_platform_is_octave()
%
% Output:
%   tf      true if the platform on which this function is run is
%           GNU/Octave, false otherwise (typically, if the platform is
%           Matlab)
%
% NNO Jan 2014

    persistent cached_tf;

    if islogical(cached_tf)
        tf=cached_tf;
        return;
    end

    tf=logical(exist('OCTAVE_VERSION', 'builtin'));
    cached_tf=tf;


%% panel for updating neuron parameters
panel_neuron = uipanel(...
'Parent',main_fig,...
'FontUnits',get(0,'defaultuipanelFontUnits'),...
'Units','characters',...
'Title','Neuron',...
'Position',[5 29 67 11],...
'BackgroundColor',get(0,'defaultuipanelBackgroundColor'),...
'BackgroundColorMode',get(0,'defaultuipanelBackgroundColorMode'),...
'ParentMode','manual',...
'Tag','data_panel',...
'FontSize',18,...
'FontWeight','bold');

% neuron size
text_gsiz = uicontrol(...
'Parent',panel_neuron,...
'FontUnits',get(0,'defaultuicontrolFontUnits'),...
'Units','characters',...
'String','Size',...
'Style','pushbutton',...
'Position',[2 7 10 1.75],...
'BackgroundColor',get(0,'defaultuicontrolBackgroundColor'),...
'BackgroundColorMode',get(0,'defaultuicontrolBackgroundColorMode'),...
'Callback','%automatic',...
'Children',[],...
'ParentMode','manual',...
'Tag','data_dir',...
'FontSize',14, 'fontweight', 'bold');

edit_gsiz = uicontrol(...
'Parent',panel_neuron,...
'FontUnits',get(0,'defaultuicontrolFontUnits'),...
'Units','characters',...
'String', 15,...
'Style','edit',...
'Position',[13 7 5 1.75],...
'BackgroundColor',get(0,'defaultuicontrolBackgroundColor'),...
'BackgroundColorMode',get(0,'defaultuicontrolBackgroundColorMode'),...
'Callback','%automatic',...
'Children',[],...
'ParentMode','manual',...
'Tag','data_dir',...
'FontSize',14, 'fontweight', 'bold');

% gaussian width
text_gsig = uicontrol(...
'Parent',panel_neuron,...
'FontUnits',get(0,'defaultuicontrolFontUnits'),...
'Units','characters',...
'String','sig',...
'Style','pushbutton',...
'Position',[20 7 10  1.75],...
'BackgroundColor',get(0,'defaultuicontrolBackgroundColor'),...
'BackgroundColorMode',get(0,'defaultuicontrolBackgroundColorMode'),...
'Callback','%automatic',...
'Children',[],...
'ParentMode','manual',...
'Tag','data_dir',...
'FontSize',14, 'fontweight', 'bold');

edit_gsig = uicontrol(...
'Parent',panel_neuron,...
'FontUnits',get(0,'defaultuicontrolFontUnits'),...
'Units','characters',...
'String', 4,...
'Style','edit',...
'Position',[31 7 5 1.75],...
'BackgroundColor',get(0,'defaultuicontrolBackgroundColor'),...
'BackgroundColorMode',get(0,'defaultuicontrolBackgroundColorMode'),...
'Callback','%automatic',...
'Children',[],...
'ParentMode','manual',...
'Tag','data_dir',...
'FontSize',14, 'fontweight', 'bold', 'callback', 'edit_gsig_callback;');

%% searching method
text_method = uicontrol(...
'Parent',panel_neuron,...
'FontUnits',get(0,'defaultuicontrolFontUnits'),...
'Units','characters',...
'String','Method',...
'Style','text',...
'Position',[2 4 12 1.75],...
'BackgroundColor',get(0,'defaultuicontrolBackgroundColor'),...
'BackgroundColorMode',get(0,'defaultuicontrolBackgroundColorMode'),...
'Callback','%automatic',...
'Children',[],...
'ParentMode','manual',...
'Tag','data_dir',...
'FontSize',14, 'fontweight', 'bold');

radio_ellipse = uicontrol(...
'Parent',panel_neuron,...
'FontUnits',get(0,'defaultuicontrolFontUnits'),...
'Units','characters',...
'String','ellipse',...
'Style','radiobutton',...
'value', 1, ...
'Position',[15 5 12 1.75],...
'BackgroundColor',get(0,'defaultuicontrolBackgroundColor'),...
'BackgroundColorMode',get(0,'defaultuicontrolBackgroundColorMode'),...
'Callback','%automatic',...
'Children',[],...
'ParentMode','manual',...
'Tag','data_dir',...
'FontSize',14, ...
'callback', 'radio_ellipse_callback;');

text_ellipse = uicontrol(...
'Parent',panel_neuron,...
'FontUnits',get(0,'defaultuicontrolFontUnits'),...
'Units','characters',...
'String','ratio',...
'Style','pushbutton',...
'Position',[30 5 10 1.75],...
'BackgroundColor',get(0,'defaultuicontrolBackgroundColor'),...
'BackgroundColorMode',get(0,'defaultuicontrolBackgroundColorMode'),...
'Callback','%automatic',...
'Children',[],...
'ParentMode','manual',...
'Tag','data_dir',...
'FontSize',14);

edit_ellipse = uicontrol(...
'Parent',panel_neuron,...
'FontUnits',get(0,'defaultuicontrolFontUnits'),...
'Units','characters',...
'String',3,...
'Style','edit',...
'Position',[41 5 5 1.75],...
'BackgroundColor',get(0,'defaultuicontrolBackgroundColor'),...
'BackgroundColorMode',get(0,'defaultuicontrolBackgroundColorMode'),...
'Callback','%automatic',...
'Children',[],...
'ParentMode','manual',...
'Tag','data_dir',...
'FontSize',14);

 radio_dilate = uicontrol(...
'Parent',panel_neuron,...
'FontUnits',get(0,'defaultuicontrolFontUnits'),...
'Units','characters',...
'String','dilate',...
'Style','radiobutton',...
'value', 0, ...
'Position',[15 3 12 1.75],...
'BackgroundColor',get(0,'defaultuicontrolBackgroundColor'),...
'BackgroundColorMode',get(0,'defaultuicontrolBackgroundColorMode'),...
'Callback','%automatic',...
'Children',[],...
'ParentMode','manual',...
'Tag','data_dir',...
'FontSize',14,...
'callback', 'radio_dilate_callback;');

text_dilate = uicontrol(...
'Parent',panel_neuron,...
'FontUnits',get(0,'defaultuicontrolFontUnits'),...
'Units','characters',...
'String','radius',...
'Style','pushbutton',...
'Position',[30 3 10 1.75],...
'BackgroundColor',get(0,'defaultuicontrolBackgroundColor'),...
'BackgroundColorMode',get(0,'defaultuicontrolBackgroundColorMode'),...
'Callback','%automatic',...
'Children',[],...
'ParentMode','manual',...
'Tag','data_dir',...
'FontSize',14);

edit_dilate = uicontrol(...
'Parent',panel_neuron,...
'FontUnits',get(0,'defaultuicontrolFontUnits'),...
'Units','characters',...
'String',3,...
'Style','edit',...
'Position',[41 3 5 1.75],...
'BackgroundColor',get(0,'defaultuicontrolBackgroundColor'),...
'BackgroundColorMode',get(0,'defaultuicontrolBackgroundColorMode'),...
'Callback','%automatic',...
'Children',[],...
'ParentMode','manual',...
'Tag','data_dir',...
'FontSize',14);