function vl_setupnn()
% VL_SETUPNN  Setup the MatConvNet toolbox
%    VL_SETUPNN() function adds the MatConvNet toolbox to MATLAB path.

% Copyright (C) 2014 Andrea Vedaldi.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).

root = vl_rootnn() ;
addpath(fullfile(root, 'matlab')) ;
addpath(fullfile(root, 'matlab', 'mex')) ;
addpath(fullfile(root, 'matlab', 'xtest')) ;


function res = isfield(this, varargin)
% Returns true if the string fieldname is the name of a field in the
% substructure 'other' in the meeg object 'this'.
% FORMAT res = isfield(this,fieldname)
%
% An overloaded function...
% _______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging

% Christophe Phillips
% $Id: isfield.m 2720 2009-02-09 19:50:46Z vladimir $

res = isfield(this.other, varargin{:});


%EQ Dataset overload


%Help file for INTLAB Version 4.1
%
%Program demointlab added.
%
%Few minor changes and corrections.
%


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

% Last Modified by GUIDE v2.5 24-Sep-2008 14:10:14

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

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

% Update handles structure
guidata(hObject, handles);

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

% --- Outputs from this function are returned to the command line.
function varargout = scope_gui_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 autoscaleButton.
function autoscaleButton_Callback(hObject, eventdata, handles)
% hObject    handle to autoscaleButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

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

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

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

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

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

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

% --- Executes on slider movement.
function timeBaseSlider_Callback(hObject, eventdata, handles)
% hObject    handle to timeBaseSlider (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,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider

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

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

% --- Executes on slider movement.
function vscaleSlider_Callback(hObject, eventdata, handles)
% hObject    handle to vscaleSlider (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,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider

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

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

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

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

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


function flag=deletemeshfile(fname)
%
% flag=deletemeshfile(fname)
%
% delete a given work mesh file under the working directory
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
%
% input:
%     fname: specified file name (without path)
%
% output:
%     flag: not used
%
% -- this function is part of iso2mesh toolbox (http://iso2mesh.sf.net)
%

try
    if(exist(fname))
	delete(fname);
    end
catch
    error(['You do not have permission to delete temporary files. If you are working in a multi-user ',...
         'environment, such as Unix/Linux and there are other users using iso2mesh, ',...
         'you may need to define ISO2MESH_SESSION=''yourstring'' to make your output ',...
         'files different from others; if you do not have permission to ',mwpath(''),...
         ' as the temporary directory, you have to define ISO2MESH_TEMP=''/path/you/have/write/permission'' ',...
         'in matlab/octave base workspace.']);
end


function x = flush(x)
x.leftfactors = [];
x.rightfactors = [];
x.midfactors = [];


function header=make_image_http_header(html,found)
if(found)
    header.HTTP='200 OK';
else
    header.HTTP='404 Not Found';
end
header.Date='Tue, 12 Oct 2010 09:19:05 GMT';
header.Server='Matlab Webserver';
header.LastModified='Last-Modified: Thu, 21 Jun 2007 14:56:37 GMT';
header.AcceptRanges='Accept-Ranges: bytes';
header.ContentLength=num2str(length(html));
header.ETag='"948921-15ae-c0dbf340"';
%header.KeepAlive='Keep-Alive: timeout=15, max=100';
header.ContentType='image/png';


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

% Last Modified by GUIDE v2.5 15-Jan-2021 12:17:00

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

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

    centerUIFigure(hObject);

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

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

	populateGUI(handles, coordSys);

    % Update handles structure
    guidata(hObject, handles);

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

function populateGUI(handles, coordSys)
    set(handles.coordSysNameText,'String',coordSys.getName());
    setappdata(handles.lvd_EditFixedInFrameVectorGUI,'frame',coordSys.frame);

    frame = coordSys.frame;
    handles.refFrameTypeCombo.String = ReferenceFrameEnum.getListBoxStr();
    handles.refFrameTypeCombo.Value = ReferenceFrameEnum.getIndForName(frame.typeEnum.name);
    handles.setFrameOptionsButton.TooltipString = sprintf('Current Frame: %s', frame.getNameStr());

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

        coordSys.setName(handles.coordSysNameText.String);

        coordSys.frame = getappdata(hObject,'frame');

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

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

    if(isempty(errMsg))
        uiresume(handles.lvd_EditFixedInFrameVectorGUI);
    else
        msgbox(errMsg,'Invalid Coordinate System Inputs','error');
    end

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

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

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

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

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

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

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

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

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

function frameUpdated(handles)
    lvdData = getappdata(handles.lvd_EditFixedInFrameVectorGUI, 'lvdData');

    frame = getappdata(handles.lvd_EditFixedInFrameVectorGUI,'frame'); %curElemSet
    bodyInfo = frame.getOriginBody();

    contents = cellstr(get(handles.refFrameTypeCombo,'String'));
    selFrameType = contents{get(handles.refFrameTypeCombo,'Value')};
    refFrameEnum = ReferenceFrameEnum.getEnumForListboxStr(selFrameType);

    switch refFrameEnum
        case ReferenceFrameEnum.BodyCenteredInertial
            newFrame = bodyInfo.getBodyCenteredInertialFrame();

        case ReferenceFrameEnum.BodyFixedRotating
            newFrame = bodyInfo.getBodyFixedFrame();

        case ReferenceFrameEnum.TwoBodyRotating
            if(frame.typeEnum == ReferenceFrameEnum.TwoBodyRotating)
                newFrame = frame;
            else
                if(not(isempty(bodyInfo.childrenBodyInfo)))
                    primaryBody = bodyInfo;
                    secondaryBody = bodyInfo.childrenBodyInfo(1);
                else
                    primaryBody = bodyInfo.getParBodyInfo();
                    secondaryBody = bodyInfo;
                end

                originPt = TwoBodyRotatingFrameOriginEnum.Primary;

                newFrame = TwoBodyRotatingFrame(primaryBody, secondaryBody, originPt, bodyInfo.celBodyData);
            end

        case ReferenceFrameEnum.UserDefined
            numFrames = lvdData.geometry.refFrames.getNumRefFrames();
            if(numFrames >= 1)
                geometricFrame = lvdData.geometry.refFrames.getRefFrameAtInd(1);
                newFrame = UserDefinedGeometricFrame(geometricFrame, lvdData);
            else
                newFrame = bodyInfo.getBodyCenteredInertialFrame();
                warndlg('There are no geometric frames available.  A body-centered inertial frame will be selected instead.');
            end

        otherwise
            error('Unknown reference frame type: %s', string(refFrameEnum));
    end

    if(not(isempty(newFrame)) && newFrame.typeEnum ~= refFrameEnum)
        refFrameEnum = newFrame.typeEnum;
        handles.refFrameTypeCombo.Value = ReferenceFrameEnum.getIndForName(refFrameEnum.name);
    end

    setappdata(handles.lvd_EditFixedInFrameVectorGUI,'frame',newFrame);
    handles.setFrameOptionsButton.TooltipString = sprintf('Current Frame: %s', newFrame.getNameStr());

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

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

% --- Executes on button press in setFrameOptionsButton.
function setFrameOptionsButton_Callback(hObject, eventdata, handles)
% hObject    handle to setFrameOptionsButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    frame = getappdata(handles.lvd_EditFixedInFrameVectorGUI,'frame');

    newFrame = frame.editFrameDialogUI(EditReferenceFrameContextEnum.ForGeometry);

    setappdata(handles.lvd_EditFixedInFrameVectorGUI,'frame',newFrame);

    frameUpdated(handles);


function ini_zmap_sys()
    %    This is the  ZMAP default file used for LINUX systems.
    %    It's purpose is to modify the ZmapGlobal variables as necessary
    %    to fit the system.
    report_this_filefun();

    ZG=ZmapGlobal.Data;
    % Marker sizes
    ZG.ms6 = 3;

    %set the recursion slightly, to avoid error (specialy with ploop functions)
    set(0,'RecursionLimit',750)

    set(0,'DefaultAxesFontName','Arial');
    set(0,'DefaultTextFontName','Arial');
    set(0,'DefaultAxesTickLength',[0.01 0.01]);
    set(0,'DefaultFigurePaperPositionMode','auto');

end


function [success] = viewAcceptedRejectedCellExtraction(inputImages,inputSignals,valid,inputMovie,varargin)
	% Plots cell image, peak transients, and image from activity in movie for accepted and rejected cells, useful for publications.
	% Biafra Ahanonu
	% started: 2014.01.03 [19:13:01]
	% inputs
		%
	% outputs
		%

	[success] = ciapkg.view.viewAcceptedRejectedCellExtraction(inputImages,inputSignals,valid,inputMovie,'passArgs', varargin);
end


% create metabolite database

metabolite_structure = struct();
if 1
    % this file seems to contain a lot of errors
    % [NUM,TXT,RAW]=xlsread('VMH_Metabolites.xlsx');

    % use instead as starting point as it comes from rBioNet
    [NUM,TXT,RAW]=xlsread('MetabolitesAGORA2_1.xlsx');
    for i = 2 : size(RAW,1)
        Ori = RAW{i,1};
        RAW{i,1} = regexprep(RAW{i,1},'-','_minus_');
        RAW{i,1} = regexprep(RAW{i,1},'(','_parentO_');
        RAW{i,1} = regexprep(RAW{i,1},')','_parentC_');
        metabolite_structure.(strcat('VMH_',RAW{i,1})) = struct();

        for j = 2:size(RAW,2)
            if j ~= 3
                metabolite_structure.(strcat('VMH_',RAW{i,1})).(RAW{1,j}) = RAW{i,j};
                metabolite_structure.(strcat('VMH_',RAW{i,1})).VMHId = Ori;
            end
        end
    end
    [metabolite_structure] = cleanUpMetabolite_structure(metabolite_structure)
    removeErrors = 1;
    [metabolite_structure,errorFlag] = sanityCheckMetIds(metabolite_structure,removeErrors);
    metabolite_structureStart = metabolite_structure;

end
if 1
    % add fields
    field2Add={
        'phenolExplorer'
        'neutralFormula'
        'chembl'
        'miriam'
        'hepatonetId'
        'iupac'
        'echa_id'
        'fda_id'
        'iuphar_id'
        'mesh_id'
        'chodb_id'
        'gtopdb'
        'inchiKey'
        'avgmolweight'
        'monoisotopicweight'
        'keggId'
        'inchiString'
        'pubChemId'
        'cheBIId'
        'hmdb'
        'pdmapName'
        'reconMap'
        'reconMap3'
        'food_db'
        'chemspider'
        'biocyc'
        'biggId'
        'wikipedia'
        'drugbank'
        'seed'
        'metanetx'
        'knapsack'
        'metlin'
        'casRegistry'
        'epa_id'
        'inchiKey'
        'smile'
        'lipidmaps'
        'reactome'
        'GNPS'
        'Recon3D'
        'Agora2'
        'massbank'
        'MoNa'
        'bindingdb'
        'metabolights'
        'rhea'
        'swisslipids'};
  %  field2Add = unique(field2Add);
    Mets = fieldnames(metabolite_structure);
    fields = fieldnames(metabolite_structure.(Mets{1}));

    [missingfields,map] = setdiff(field2Add,fields);
    for i = 1 : length(Mets)
        for j = 1 : length(missingfields)
            metabolite_structure.(Mets{i}).(missingfields{j}) = NaN;
        end
    end
end
cd FileDumps/
%[IDs,IDcountA,Table] = getStats(metabolite_structure);
%[metabolite_structure] = getMetIdsFromUniChemOffline(metabolite_structure);
assignMetaboliteIDs;
[IDs,IDcountB,Table] = getStats(metabolite_structure);
[metabolite_structure] = getMetIdsFromUniChemOffline(metabolite_structure);
[metabolite_structure,IDsAdded ] = parseChebiIdWebPage(metabolite_structure);
save vmh_met_anno
%assignMetaboliteIDs;
%[IDs,IDcountC,Table] = getStats(metabolite_structure);
%save vmh_met_anno
inchiKeyCheck = 1;
inchiStringCheck = 1;
inchiKeyAltCheck = 0;
cheBIIdCheck = 0;
drugBankCheck = 0;
pubChemIdCheck = 0;
keggIdCheck = 0;
hmdbCheck = 0;
vmhIdCheck = 0;
[metabolite_structure,IDsAdded] = getMetIdsFromUniChem(metabolite_structure,vmhIdCheck,cheBIIdCheck,drugBankCheck, pubChemIdCheck,keggIdCheck,hmdbCheck, inchiKeyCheck, inchiStringCheck,inchiKeyAltCheck );
[IDs,IDcountD,Table] = getStats(metabolite_structure);
save vmh_met_anno
translation = {'keggId' 'kegg'
    'inchiKey'  'inchikey'
    'hmdb'  'Human%20Metabolome%20Database'
    'cheBIId'   'chebi'
    'pubChemId' 'PubChem%20CID'
    'inchiString'   'inchi%20code'
    'bindingdb' 'bindingdb'
    'drugbank'  'drugbank'
    'biocyc'    'biocyc'
    'chemspider'    'chemspider'
    'casRegistry'   'cas'
    'lipidmaps' 'lipidmaps'
    'epa_id'    'epa%20dsstox'
    };
for i = 1 : 5%size(translation,1)
    for j = 1:size(translation,1)
        if i~=j
            i
            j
            [metabolite_structure,IDsAdded] = getIDsfromFiehnLab(metabolite_structure, translation{i,1},translation{j,1});
            save vmh_met_anno
        end
    end
    done = i
end
save vmh_met_anno
inchiKeyCheck = 1;
inchiStringCheck = 1;
inchiKeyAltCheck = 1;
[metabolite_structure,IDsAdded] = getMetIdsFromInchiKeys(metabolite_structure, inchiKeyCheck, inchiStringCheck,inchiKeyAltCheck);
save vmh_met_anno
assignMetaboliteIDs;
[IDs,IDcountD,Table] = getStats(metabolite_structure);
save vmh_met_anno

writecell(Table);


function img_data=load_img_from_ds_info(img_data_info, img_idx)

assert(~isempty(img_idx));

img_file=img_data_info.img_files{img_idx};
one_data_dir_idx=img_data_info.data_dir_idxes_img(img_idx);
one_data_dir=img_data_info.data_dirs{one_data_dir_idx};

full_img_file=fullfile(one_data_dir, img_file);
img_data=read_img_rgb(full_img_file, 'uint8');

end


function write_nitf_security_tags(obj)
%WRITE_NITF_SECURITY_TAGS Writes the NITF security tags
%
% It's not expected that the typical user would call this function, rather
% it is called as part of a bigger NITF/SICD writer.
%
% Inputs:
%       obj:       This is the 'hidden' object-specific handle.  It is
%                  similar to 'this' in Java.
%
% References:
%       MIL-STD-2500C, Department of Defense Interface Standard
%                      National Imagery Transmission Format version 2.1
%                      01 May 2006
%
% Written by: Wade Schwartzkopf, NGA/IDT
%
% //////////////////////////////////////////
% /// CLASSIFICATION: UNCLASSIFIED       ///
% //////////////////////////////////////////

% Always writing version 2.1 NITF

% Security is limited in the SICD XML structure.  We fill in what we can.
if isfield(obj.sicdmeta,'CollectionInfo')&&isfield(obj.sicdmeta.CollectionInfo,'Classification')
    classification = obj.sicdmeta.CollectionInfo.Classification;
else
    classification = ' ';
end
code_index = regexp(classification,'/[^/]');
if isempty(code_index)
    code = '';
else
    code = classification((code_index(1)+1):end);
end
fwriten(obj.FID, classification(1), 1); % CLAS
fwriten(obj.FID, 'US',      2);  % CLSY
fwriten(obj.FID, code,      11); % CODE
fwriten(obj.FID, '',        2);  % CTLH
fwriten(obj.FID, '',        20); % REL
fwriten(obj.FID, '',        2);  % DCTP
fwriten(obj.FID, '',        8);  % DCDT
fwriten(obj.FID, '',        4);  % DCXM
fwriten(obj.FID, '',        1);  % DG
fwriten(obj.FID, '',        8);  % DGDT
fwriten(obj.FID, ''       , 43); % CLTX
fwriten(obj.FID, '',        1);  % CATP
fwriten(obj.FID, '',        40); % CAUT
fwriten(obj.FID, '',        1);  % CRSN
fwriten(obj.FID, '',        8);  % SRDT
fwriten(obj.FID, '',        15); % CTLN

end

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


% NOTE: DO NOT REMOVE THIS LINE XMAKEFILE_TOOL_CHAIN_CONFIGURATION
function toolChainConfiguration = arduinouno()
%ARDUINOUNO Defines a tool chain configuration

% Copyright 2012 The MathWorks, Inc.

try
hSetup = realtime.setup.PackageInfo;
    spPkg = hSetup.getSpPkgInfo('Arduino Uno');
    arduinoRootDir = hSetup.getTpPkgRootDir('ARDUINO', spPkg);
catch me
    toolChainConfiguration = {};
    return;
end

% General
toolChainConfiguration.Configuration = 'Arduinouno';
toolChainConfiguration.Version = '2.0';
toolChainConfiguration.Description = 'MS Visual Studio';
toolChainConfiguration.Operational = true;
toolChainConfiguration.Decorator = 'linkfoundation.xmakefile.decorator.eclipseDecorator';
% Make
toolChainConfiguration.MakePath = @(src) fullfile(arduinoRootDir, 'hardware', 'tools', 'avr', 'utils', 'bin', 'make');
toolChainConfiguration.MakeFlags = '-f "[|||MW_XMK_GENERATED_FILE_NAME[R]|||]" [|||MW_XMK_ACTIVE_BUILD_ACTION_REF|||]';
toolChainConfiguration.MakeInclude = '';
% Compiler
toolChainConfiguration.CompilerPath = @(src) fullfile(arduinoRootDir, 'hardware', 'tools', 'avr', 'bin', 'avr-gcc');
toolChainConfiguration.CompilerFlags = '-c -x none';
toolChainConfiguration.SourceExtensions = '.c,.cpp';
toolChainConfiguration.HeaderExtensions = '.h';
toolChainConfiguration.ObjectExtension = '.o';
% Linker
toolChainConfiguration.LinkerPath = @(src) fullfile(arduinoRootDir, 'hardware', 'tools', 'avr', 'bin', 'avr-gcc');
toolChainConfiguration.LinkerFlags = '-o [|||MW_XMK_GENERATED_TARGET_REF|||]';
toolChainConfiguration.LibraryExtensions = '.lib,.a';
toolChainConfiguration.TargetExtension = '.elf';
toolChainConfiguration.TargetNamePrefix = '';
toolChainConfiguration.TargetNamePostfix = '';
% Archiver
toolChainConfiguration.ArchiverPath = @(src) fullfile(arduinoRootDir, 'hardware', 'tools', 'avr', 'bin', 'avr-ar');
toolChainConfiguration.ArchiverFlags = '-crs $(TARGET_FILE)';
toolChainConfiguration.ArchiveExtension = '.a';
toolChainConfiguration.ArchiveNamePrefix = 'lib';
toolChainConfiguration.ArchiveNamePostfix = '';
% Pre-build
toolChainConfiguration.PrebuildEnable = false;
toolChainConfiguration.PrebuildToolPath = '';
toolChainConfiguration.PrebuildFlags = '';
% Post-build
toolChainConfiguration.PostbuildEnable = true;
toolChainConfiguration.PostbuildToolPath = @(src) fullfile(arduinoRootDir, 'hardware', 'tools', 'avr', 'bin', 'avr-objcopy');
toolChainConfiguration.PostbuildFlags = '-O ihex -R .eeprom $(TARGET)  [|||MW_XMK_MODEL_NAME|||].hex';
% Execute
toolChainConfiguration.ExecuteDefault = false;
toolChainConfiguration.ExecuteToolPath = '';
toolChainConfiguration.ExecuteFlags = '';
% Directories
toolChainConfiguration.DerivedPath = '[|||MW_XMK_SOURCE_PATH_REF|||]';
toolChainConfiguration.OutputPath = '';
% Custom
toolChainConfiguration.Custom1 = '';
toolChainConfiguration.Custom2 = '';
toolChainConfiguration.Custom3 = '';
toolChainConfiguration.Custom4 = '';
toolChainConfiguration.Custom5 = '';
end

% LocalWords:  XMAKEFILE Uno linkfoundation xmakefile avr utils XMK crs ihex
% LocalWords:  eeprom


classdef GemLabelEditBox < GemVirtualPanel
    % GemLabelEditBox GEM class for an edit box with label text
    %
    %     Licence
    %     -------
    %     Part of GEM. https://github.com/tomdoel/gem
    %     Author: Tom Doel, 2013.  www.tomdoel.com
    %     Distributed under the MIT licence. Please see website for details.
    %

    properties (Access = protected)
        Text
        EditBox
    end

    properties
        LabelWidth = 50
        LabelHeight = 20
        EditBoxWidth = 50
        EditBoxHeight = 20

        TextHeight = 15
        VerticalSpacing = 2
        LabelFontSize = 9
        EditBoxFontSize = 9
        EditBoxSpacing = 6
        EditBoxPosition

        StackVertically = false % When multiple controls are grouped, should they be stacked vertically or horizontally?
    end

    methods
        function obj = GemLabelEditBox(parent, text, tooltip, tag)
            obj = obj@GemVirtualPanel(parent);

            label_horizontal_alignment = 'center';

            obj.EditBox = GemEditBox(parent, tooltip);
            obj.AddChild(obj.EditBox);
            obj.AddEventListener(obj.EditBox, 'TextChanged', @obj.EditBoxCallback);
            obj.EditBox.HorizontalAlignment = 'left';
            obj.EditBox.FontSize = obj.EditBoxFontSize;
            text = [text ':'];

            obj.Text = GemText(parent, text, tooltip, tag);
            obj.Text.HorizontalAlignment = label_horizontal_alignment;
            obj.Text.FontSize = obj.LabelFontSize;
            obj.AddChild(obj.Text);
        end

        function Resize(obj, new_position)
            Resize@GemVirtualPanel(obj, new_position);

            control_width = round(new_position(3)/2);
            label_y_position = new_position(2) + obj.VerticalSpacing;
            label_x_position = new_position(1) + control_width - obj.LabelWidth;
            obj.Text.Resize([label_x_position, label_y_position, obj.LabelWidth, obj.LabelHeight]);

            edit_y_position = new_position(2) + obj.VerticalSpacing;
            edit_x_position = new_position(1) + control_width;
            obj.EditBox.Resize([edit_x_position, edit_y_position, obj.EditBoxWidth, obj.EditBoxHeight]);
        end

        function width = GetWidth(obj)
            width = obj.LabelWidth + obj.LabelWidth;
        end

        function height = GetRequestedHeight(obj, width)
            height = max(obj.EditBoxHeight, obj.LabelHeight);
        end

        function Enable(obj)
            Enable@GemVirtualPanel(obj);
            obj.Text.Enable;
            obj.EditBox.Enable;
        end

        function Disable(obj)
            Disable@GemVirtualPanel(obj);
            obj.Text.Disable;
            obj.EditBox.Disable;
        end

        function Select(obj, is_selected)
        end

    end

    methods (Access = protected)
        function EditBoxCallback(obj, hObject, ~)
        end
    end
end


function s = cvx_where

%CVX_WHERE    Returns the location of the CVX system.
%   CVX_WHERE returns a string containing the base directory of the CVX
%   modeling framework. Within that directory are some useful
%   subdirectories and files:
%       functions/    new functions
%       examples/     sample cvx models
%       LICENSE.txt   copyright information
%   The proper operation of this function assumes that it has not been
%   moved from its default position within the cvx distribution.

try
    s = dbstack('-completenames');
catch
    s = dbstack;
end
s = s(1);
if isfield( s, 'file' ),
    s = s.file;
else
    s = s.name;
end
if ispc,
    fs = '\';
else
    fs = '/';
end
temp = strfind( s, fs );
s( temp(end-1) + 1 : end ) = [];

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


classdef libad9361 < handle

    properties (Hidden)
        libad9361_win = 'https://github.com/analogdevicesinc/libad9361-iio/releases/download/v0.2/libad9361-0.2-win64.zip';
        libad9361_osx = 'https://github.com/analogdevicesinc/libad9361-iio/releases/download/v0.2/ad9361-0.2-Darwin.tar.gz';
        libad9361_linux= 'http://swdownloads.analog.com/cse/travis_builds/master_latest_libad9361-iio-trusty.tar.gz';
        os
        headerFileNames = {'ad9361.h','ad9361-wrapper.h'};
        libraryFileNames = {'ad9361','libad9361.so','libad9361.dll'};
        tmpdir = 'tmp_deps_install';
    end

    methods (Access=protected, Hidden)

        function loc = getDependencyTargetLocation(~)
            rootDir = fileparts(strtok(mfilename('fullpath'), '+'));
            loc = fullfile(rootDir,'deps','ad9361');
        end

        function [files,dlfn,fulltmp] = downloadFiles(obj)
            if ismac
                dlfn = websave('dl.tar.gz',obj.libad9361_osx);
                fulltmp = fullfile(pwd,obj.tmpdir);
                files = untar(dlfn,fulltmp);
            elseif ispc
                dlfn = websave('dl.zip',obj.libad9361_win);
                fulltmp = fullfile(pwd,obj.tmpdir);
                files = unzip(dlfn,fulltmp);
            else
                dlfn = websave('dl.tar.gz',obj.libad9361_linux);
                fulltmp = fullfile(pwd,obj.tmpdir);
                files = untar(dlfn,fulltmp);
            end
        end

    end

    methods

        function [check,lib,head] = checkForDependencies(obj)
            loc = getDependencyTargetLocation(obj);
            lib = false;
            for l = 1:length(obj.libraryFileNames)
                lib = lib || exist(fullfile(loc,obj.libraryFileNames{l}),'file');
            end
            head = true;
            for h = 1:length(obj.headerFileNames)
                head = head && exist(fullfile(loc,'include',obj.headerFileNames{h}),'file');
            end
            check = lib && head;
        end

        function download_libad9361(obj)
            if obj.checkForDependencies()
                fprintf('Dependencies already installed, not reinstalling\n');
                return
            end
            fprintf('Downloading libad9361 library\n');
            [files,dlfn,fulltmp] = downloadFiles(obj);
            target = obj.getDependencyTargetLocation();
            if ~exist(target,'dir')
                mkdir(target);
            end
            if ~exist(fullfile(target,'include'),'dir')
                mkdir(fullfile(target,'include'));
            end
            % Includes
            for f = 1:length(files)
                if contains(files{f},obj.headerFileNames)
                    copyfile(files{f},fullfile(target,'include'));
                end
            end
            % Libraries
            for f = 1:length(files)
                if exist(files{f},'dir')
                    continue;
                end
                fp = split(files{f}, '/'); fp = fp{end};
                s = dir(files{f});
                if contains(fp,obj.libraryFileNames) && s.bytes>0
                    if ismac && ~contains(fp,'.')
                        copyfile(files{f},fullfile(target,'libad9361.dylib'));
                    end
                    if ispc && contains(files{f},'.dll')
                        copyfile(files{f},target);
                    end
                    if isunix
                        copyfile(files{f},fullfile(target,'libad9361.so'));
                    end
                end
            end
            % Cleanup
            rmdir(fulltmp,'s');
            delete(dlfn);
            fprintf('Installing libad9361 complete\n');
            % Path stuff
            fprintf('Adding libad9361 to path\n');
            addpath(genpath(target));
            try
                warning('error','MATLAB:SavePath:PathNotSaved');
                savepath();
            catch
               warning(['savepath failed. libad9361 is currently on path, '...
                   'but is likely to not be across MATLAB restarts.',...
                   'Please add "',target,'" to path']);
            end
        end
    end
end


function cdmfile(file)
    [pathstr,fname,ext]=fileparts(which(file));
    cd (pathstr);
end


function save_im(hf)

% rszs=get(hf,'ResizeFcn');
% set(hf,'ResizeFcn','');

%set(hf,'UserData',[status status2]);
ss2=get(hf,'UserData');
status=ss2(1);
status2=ss2(2);
status3=ss2(3);

ssz=get(0,'ScreenSize');

% set(status,'FontUnits','points','FontSize',8*ssz(4)/768);
% set(status2,'FontUnits','points','FontSize',8*ssz(4)/768);
% set(status3,'FontUnits','points','FontSize',8*ssz(4)/768);
fs=get(status,'FontSize');
set(status,'FontSize',round(0.7*fs));
fs=get(status2,'FontSize');
set(status2,'FontSize',round(0.7*fs));
fs=get(status3,'FontSize');
set(status3,'FontSize',round(0.7*fs));
drawnow;

[file,path] = uiputfile({'*.png'; '*.jpg'; '*.tif'; '*.bmp'; '*.emf'; '*.eps'; '*.fig '; '*.mat'},'Save Image As');
%set(hf,'PaperPositionMode','manual','PaperOrientation','portrait');
saveas(hf,[path file],'png');
%set(hf,'PaperPositionMode','manual','PaperOrientation','Landscape');

% set(hf,'ResizeFcn',rszs);

% set(status,'FontUnits','points','FontSize',10*ssz(4)/768);
% set(status2,'FontUnits','points','FontSize',10*ssz(4)/768);
% set(status3,'FontUnits','points','FontSize',10*ssz(4)/768);

set(status,'FontSize',fs);
set(status2,'FontSize',fs);
set(status3,'FontSize',fs);


function handleExecErrorsWarnings(varargin)
%handleExecErrors Summary of this function goes here
%   Detailed explanation goes here
    global warn_error_label_handles warn_error_slider_handle;
    warnErrorLbls = warn_error_label_handles;
    hSlider = warn_error_slider_handle;

    execErrors = getExecutionErrors();
    execWarns = getExecutionWarnings();

    numWarnError = length(execErrors) + length(execWarns);

    if(~isempty(varargin))
        updateSlider = varargin{1};
    else
        updateSlider = true;
    end

    if(numWarnError <= 6)
        set(hSlider,'Max',1.0);
        set(hSlider,'Min',0.0);
        set(hSlider,'Value',1.0);
        set(hSlider,'Enable','off');
    else
        if(updateSlider)
            set(hSlider,'Min',0.0);
            set(hSlider,'Max',numWarnError-6);
            set(hSlider,'Value',numWarnError-6);
            set(hSlider,'SliderStep',[1/(numWarnError-6),1.0]);
            set(hSlider,'Enable','on');
        end
    end

    lblOffset = round(get(hSlider,'Max') - get(hSlider,'Value'));
    set(hSlider,'Value',round(get(hSlider,'Value')));

    lblUseCnt = 0;
    for(i=1+lblOffset:length(execErrors))
        if(lblUseCnt>=6)
            break;
        end
        errorStr = execErrors{i};
        styleLabelAsError(warnErrorLbls(lblUseCnt+1), errorStr);
        drawnow;
        lblUseCnt = lblUseCnt+1;
    end

    if(lblOffset >= length(execErrors))
        lblOffset = lblOffset - length(execErrors);
    else
        lblOffset = 0;
    end

    for(i=1+lblOffset:length(execWarns)) %#ok<*NO4LP>
        if(lblUseCnt>=6)
            break;
        end
        warnStr = execWarns{i};
        styleLabelAsWarn(warnErrorLbls(lblUseCnt+1), warnStr);
        drawnow;
        lblUseCnt = lblUseCnt+1;
    end

    if(numWarnError == 0)
        styleLabelAsValid(warnErrorLbls(1), 'No errors or warnings found.');
        drawnow;
    end
end


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

% Last Modified by GUIDE v2.5 19-Jun-2014 19:45:21

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

% Choose default command line output for ma_InsertMassDumpGUI
handles.output = hObject;
handles.ma_MainGUI = varargin{1};

% Update handles structure
guidata(hObject, handles);

if(length(varargin)>1)
    event = varargin{2};
    populateGUIWithEvent(handles, event);
end

% GUI Setup
setPropellantNameLabels(handles);
populateThrusterCombo(handles, handles.thrustersCombo);
massDumpTypeCombo_Callback(handles.massDumpTypeCombo, [], handles);
thrustersCombo_Callback(handles.thrustersCombo, [], handles);

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

function setPropellantNameLabels(handles)
    maData = getappdata(handles.ma_MainGUI,'ma_data');
    propNames = maData.spacecraft.propellant.names;

    set(handles.propName1Text,'String', propNames{1}, 'TooltipString', propNames{1});
    set(handles.propName2Text,'String', propNames{2}, 'TooltipString', propNames{2});
    set(handles.propName3Text,'String', propNames{3}, 'TooltipString', propNames{3});

function populateThrusterCombo(handles, hThrustersCombo)
    maData = getappdata(handles.ma_MainGUI,'ma_data');
    thrusters = maData.spacecraft.thrusters;

    thrusterComboStr = cell(length(thrusters),1);
    for(i=1:length(thrusters))
        thrusterComboStr{i} = thrusters{i}.name;
    end

    set(hThrustersCombo,'String',thrusterComboStr);

function populateGUIWithEvent(handles, event)
    maData = getappdata(handles.ma_MainGUI,'ma_data');

    set(handles.titleLabel, 'String', 'Edit Mass Dump');
    set(handles.ma_InsertMassDumpGUI, 'Name', 'Edit Mass Dump');
    set(handles.nameText, 'String', event.name);

    type = event.subType;
    switch type
        case 'basic'
            value = findValueFromComboBox('Mass Dump', handles.massDumpTypeCombo);
            set(handles.massDumpTypeCombo,'value',value);

            dmasses = event.dumpValue;

            set(handles.dryMassText,'String', fullAccNum2Str(dmasses(1)));
            set(handles.fuelOxMassText,'String', fullAccNum2Str(dmasses(2)));
            set(handles.monopropMassText,'String', fullAccNum2Str(dmasses(3)));
            set(handles.xenonMassText,'String', fullAccNum2Str(dmasses(4)));
        case 'delta-v'
            value = findValueFromComboBox('Delta-V Dump', handles.massDumpTypeCombo);
            set(handles.massDumpTypeCombo,'value',value);

            deltav = event.dumpValue;
            set(handles.deltavText,'String',fullAccNum2Str(deltav));

            thrusters = maData.spacecraft.thrusters;
            thrusterVal = 1;
            for(i=1:length(thrusters)) %#ok<*NO4LP>
                thrusterFromArr = thrusters{i};
                if(thrusterFromArr.id == event.thruster.id)
                    thrusterVal = i;
                    break;
                end
            end

            set(handles.thrustersCombo,'value',thrusterVal);
    end

% --- Outputs from this function are returned to the command line.
function varargout = ma_InsertMassDumpGUI_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} = [];
else
    maData = getappdata(handles.ma_MainGUI,'ma_data');

    name = get(handles.nameText, 'String');

    contents = cellstr(get(handles.massDumpTypeCombo,'String'));
    selected = contents{get(handles.massDumpTypeCombo,'Value')};

    switch selected
        case 'Mass Dump'
            subType = 'basic';

            dryMass = str2double(get(handles.dryMassText,'String'));
            fuelOxMass = str2double(get(handles.fuelOxMassText,'String'));
            monopropMass = str2double(get(handles.monopropMassText,'String'));
            xenonMass = str2double(get(handles.xenonMassText,'String'));

            massDumpValue = [dryMass fuelOxMass monopropMass xenonMass];

            thruster = [];
        case 'Delta-V Dump'
            subType = 'delta-v';

            deltav = str2double(get(handles.deltavText,'String'));

            massDumpValue = [deltav];

            thrusterNum = get(handles.thrustersCombo,'value');
            thruster = maData.spacecraft.thrusters{thrusterNum};
    end

    varargout{1} = ma_createMassDump(name, subType, massDumpValue, thruster);
    close(handles.ma_InsertMassDumpGUI);
end

% --- Executes on button press in saveCloseButton.
function saveCloseButton_Callback(hObject, eventdata, handles)
% hObject    handle to saveCloseButton (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.ma_InsertMassDumpGUI);
    else
        msgbox(errMsg,'Errors were found while inserting a mass dump.','error');
    end

function errMsg = validateInputs(handles)
    contents = cellstr(get(handles.massDumpTypeCombo,'String'));
    selected = contents{get(handles.massDumpTypeCombo,'Value')};

    errMsg = {};

    switch selected
        case 'Mass Dump'
            dryMass = str2double(get(handles.dryMassText,'String'));
            enteredStr = get(handles.dryMassText,'String');
            numberName = 'Dry Mass to Dump';
            lb = 0;
            ub = Inf;
            isInt = false;
            errMsg = validateNumber(dryMass, numberName, lb, ub, isInt, errMsg, enteredStr);

            fuelOxMass = str2double(get(handles.fuelOxMassText,'String'));
            enteredStr = get(handles.fuelOxMassText,'String');
            numberName = 'Fuel/Ox Mass to Dump';
            lb = 0;
            ub = Inf;
            isInt = false;
            errMsg = validateNumber(fuelOxMass, numberName, lb, ub, isInt, errMsg, enteredStr);

            monopropMass = str2double(get(handles.monopropMassText,'String'));
            enteredStr = get(handles.monopropMassText,'String');
            numberName = 'Monoprop Mass to Dump';
            lb = 0;
            ub = Inf;
            isInt = false;
            errMsg = validateNumber(monopropMass, numberName, lb, ub, isInt, errMsg, enteredStr);

            xenonMass = str2double(get(handles.xenonMassText,'String'));
            enteredStr = get(handles.xenonMassText,'String');
            numberName = 'Xenon Mass to Dump';
            lb = 0;
            ub = Inf;
            isInt = false;
            errMsg = validateNumber(xenonMass, numberName, lb, ub, isInt, errMsg, enteredStr);

        case 'Delta-V Dump'
            deltav = str2double(get(handles.deltavText,'String'));
            enteredStr = get(handles.deltavText,'String');
            numberName = 'Delta-V to Dump';
            lb = 0;
            ub = Inf;
            isInt = false;
            errMsg = validateNumber(deltav, numberName, lb, ub, isInt, errMsg, enteredStr);
    end

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

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

% Hints: get(hObject,'String') returns contents of nameText as text
%        str2double(get(hObject,'String')) returns contents of nameText as a double

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

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

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

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

    switch selected
        case 'Mass Dump'
            set(handles.dryMassText,'Enable','on');
            set(handles.fuelOxMassText,'Enable','on');
            set(handles.monopropMassText,'Enable','on');
            set(handles.xenonMassText,'Enable','on');
            set(handles.deltavText,'Enable','off');
            set(handles.thrustersCombo,'Enable','off');
        case 'Delta-V Dump'
            set(handles.dryMassText,'Enable','off');
            set(handles.fuelOxMassText,'Enable','off');
            set(handles.monopropMassText,'Enable','off');
            set(handles.xenonMassText,'Enable','off');
            set(handles.deltavText,'Enable','on');
            set(handles.thrustersCombo,'Enable','on');
    end

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

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

function fuelOxMassText_Callback(hObject, eventdata, handles)
% hObject    handle to fuelOxMassText (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 fuelOxMassText as text
%        str2double(get(hObject,'String')) returns contents of fuelOxMassText as a double
newInput = get(hObject,'String');
newInput = attemptStrEval(newInput);
set(hObject,'String', newInput);

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

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

function monopropMassText_Callback(hObject, eventdata, handles)
% hObject    handle to monopropMassText (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 monopropMassText as text
%        str2double(get(hObject,'String')) returns contents of monopropMassText as a double
newInput = get(hObject,'String');
newInput = attemptStrEval(newInput);
set(hObject,'String', newInput);

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

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

function xenonMassText_Callback(hObject, eventdata, handles)
% hObject    handle to xenonMassText (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 xenonMassText as text
%        str2double(get(hObject,'String')) returns contents of xenonMassText as a double
newInput = get(hObject,'String');
newInput = attemptStrEval(newInput);
set(hObject,'String', newInput);

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

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

function dryMassText_Callback(hObject, eventdata, handles)
% hObject    handle to dryMassText (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 dryMassText as text
%        str2double(get(hObject,'String')) returns contents of dryMassText as a double
newInput = get(hObject,'String');
newInput = attemptStrEval(newInput);
set(hObject,'String', newInput);

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

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

function deltavText_Callback(hObject, eventdata, handles)
% hObject    handle to deltavText (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 deltavText as text
%        str2double(get(hObject,'String')) returns contents of deltavText as a double
newInput = get(hObject,'String');
newInput = attemptStrEval(newInput);
set(hObject,'String', newInput);

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

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

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

% Hints: contents = cellstr(get(hObject,'String')) returns thrustersCombo contents as cell array
%        contents{get(hObject,'Value')} returns selected item from thrustersCombo
    maData = getappdata(handles.ma_MainGUI,'ma_data');
    propNames = maData.spacecraft.propellant.names;
    thrusters = maData.spacecraft.thrusters;

    thruster = thrusters{get(handles.thrustersCombo,'Value')};
    propTypeIndex = ma_getPropTypeIndexFromInternalPropName(thruster.propType);
    set(handles.fuelTypeBeingDumpedLabel,'String',propNames{propTypeIndex});

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

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

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


function figure = plotlygetfile(file_owner, file_id)

    [un, key, domain] = signin;

    headers = struct(...
                    'name',...
                        {...
                            'plotly-username',...
                            'plotly-apikey',...
                            'plotly-version',...
                            'plotly-platform',...
                            'user-agent'
                        },...
                    'value',...
                        {...
                            un,...
                            key,...
                            plotly_version,...
                            'MATLAB',...
                            'MATLAB'
                        });

    url = [domain, '/apigetfile/', file_owner, '/', num2str(file_id)];

    [response_string, extras] = urlread2(url, 'Post', '', headers);
    response_handler(response_string, extras);
    response_object = loadjson(response_string);
    figure = response_object.payload.figure;
end


function item = update_deps(item, oid, nid)

% function item = update_deps(item, varargin)
% This function will run cfg_dep/update_deps in all leaf (cfg_entry,
% cfg_menu, cfg_files) nodes of a configuration tree and update their
% dependency information (mod_job_ids) if necessary. It will also update
% cfg_exbranch mod_job_ids (item.id and ids in item.tdeps and item.sdeps).
%
% 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: update_deps.m 1716 2008-05-23 08:18:45Z volkmar $

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

id = subsref(item, substruct('.', 'id'));
for k = 1:numel(oid)
    if isequal(id, oid{k})
        item = subsasgn(item, substruct('.', 'id'), nid{k});
        for cs = 1:numel(item.sout)
            item.sout(cs).src_exbranch = nid{k};
        end;
        break;
    end;
end;
if ~isempty(item.tdeps)
    item.tdeps = update_deps(item.tdeps, oid, nid);
end;
if ~isempty(item.sdeps)
    item.sdeps = update_deps(item.sdeps, oid, nid);
end;

val = subsref(item, substruct('.','val'));
for k = 1:numel(val)
    val{k} = update_deps(val{k}, oid, nid);
end;
item = subsasgn(item, substruct('.','val'), val);


function dcmobj = build_module_template(moduleName)
% function tags = build_module_template(moduleName)
%"build_module_template"
%   Create a Java DICOM object containing fields used to represent the
%   specified module.
%
%   Valid moduleNames are currently 'patient'
%
%JRA 06/06/06
%NAV 07/19/16 updated to dcm4che3
% AI 11/20/2020 Added module subsets used in dcmdir_add to group images.
%
%Usage:
%   dcmobj = general_equipment_module_template;
%
% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.
%
% This file is part of The Computational Environment for Radiotherapy Research (CERR).
%
% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.
%
% CERR has been financially supported by the US National Institutes of Health under multiple grants.
%
% CERR is distributed under the terms of the Lesser GNU Public License.
%
%     This version of CERR is free software: you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation, either version 3 of the License, or
%     (at your option) any later version.
%
% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
% See the GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with CERR.  If not, see <http://www.gnu.org/licenses/>.

%Create a dcmobj to hold the structure and data.
%%dcmobj = org.dcm4che2.data.BasicDicomObject;
  %dcmobj = org.dcm4che3.data.Attributes;

%Done = 0;

switch lower(moduleName)
    %Get the top level tags used in this module.
    case 'patient'
        tagS = patient_module_tags;
    case 'patient_subset'
        tagS = patient_module_tags_subset;
    case 'general_study'
        tagS = general_study_module_tags;
    case 'general_study_subset'
        tagS = general_study_module_tags_subset;
    case 'general_series'
        tagS = general_series_module_tags;
    case 'general_series_subset'
        tagS = general_series_module_tags_subset;
    case 'frame_of_reference'
        tagS = frame_of_reference_module_tags;
    case 'general_equipment'
        tagS = general_equipment_module_tags;
    case 'content_identification'
        tagS = content_identification_module_tags;
    case 'general_image'
        tagS = general_image_module_tags;
    case 'image_plane'
        tagS = image_plane_module_tags;
    case 'image_pixel'
        tagS = image_pixel_module_tags;
    case 'ct_image'
        tagS = CT_image_module_tags;
    case 'pt_image'
        tagS = PT_image_module_tags;
    case 'mr_image'
        tagS = MR_image_module_tags;
    case 'mr_image_subset'
        tagS = MR_image_module_tags_subset;
    case 'sop_common'
        tagS = SOP_common_module_tags;
    case 'structure_set'
        tagS = structure_set_module_tags;
    case 'roi_contour'
        tagS = ROI_contour_module_tags;
    case 'rt_series'
        tagS = RT_series_module_tags;
    case 'rt_roi_observations'
        tagS = RT_ROI_observations_module_tags;
    case 'rt_dose'
        tagS = RT_dose_module_tags;
    case 'rt_dvh'
        tagS = RT_DVH_module_tags;
    case 'multi_frame'
        tagS = multi_frame_module_tags;
    case 'gsps'
        tagS = gsps_module_tags;
    otherwise
        error('Unrecognized or unsupported module template requested.')
end

%tags = hex2dec({tagS.tag});

%Create all top level tags in this object.
dcmobj = javaObject('org.dcm4che3.data.Attributes');
dcmobj = createEmptyFields(dcmobj, tagS);


function strMacro = macro_method()
% MACRO_METHOD: Script to insert at the beginning of all the brainstorm class functions

% @=============================================================================
% This function is part of the Brainstorm software:
% https://neuroimage.usc.edu/brainstorm
%
% Copyright (c) University of Southern California & McGill University
% This software is distributed under the terms of the GNU General Public License
% as published by the Free Software Foundation. Further details on the GPLv3
% license can be found at http://www.gnu.org/copyleft/gpl.html.
%
% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE
% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY
% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY
% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.
%
% For more information type "brainstorm license" at command prompt.
% =============================================================================@
%
% Authors: Francois Tadel, 2016

strMacro = [...
    'if (nargin >= 1), ' ...
        '[varargout{1:nargout}] = feval(varargin{1}, varargin{2:end});', ...
    'end'];


classdef uicontext < handle
%uicontext - Context menu with push buttons.

%------------------------------- Copyright --------------------------------
% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for
% research purposes. All publications which use this platform or any code
% in the platform should acknowledge the use of "PlatEMO" and reference "Ye
% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform
% for evolutionary multi-objective optimization [educational forum], IEEE
% Computational Intelligence Magazine, 2017, 12(4): 73-87".
%--------------------------------------------------------------------------

    properties(SetAccess = private)
        fig;        % The figure
        panel;      % The main panel
        items;      % The menu items
        gaps;       % Labels for covering the borders of items
        listener;	% Listener
    end
    methods
        %% Constructor
        function obj = uicontext(fig,width)
            obj.fig   = fig;
            obj.panel = uipanel(obj.fig,'Position',[0 0 width 0],'Visible',false);
        end
        %% Add a new item
        function add(obj,str,icon,cb)
        	obj.items = [obj.items,uibutton(obj.panel,'Position',[-2 0 obj.panel.Position(3)+5 25],'Text',str,'HorizontalAlignment','left','BackgroundColor',[.94 .94 .94],'Icon',icon,'ButtonPushedFcn',cb)];
            obj.gaps  = [obj.gaps,uipanel(obj.panel,'Position',[-2 0 obj.panel.Position(3)+5 3],'BorderType','none')];
            obj.panel.Children = obj.panel.Children([1,3:end,2]);
        end
        %% Flush the menu
        function flush(obj)
            if ~isempty(obj.items)
                obj.panel.Position(4) = 23*length(obj.items) - 2;
                loc = obj.panel.Position(4) + 1;
                for i = 1 : length(obj.items)
                    loc = loc - 23;
                    obj.items(i).Position(2) = loc;
                    obj.gaps(i).Position(2)  = loc - 1;
                end
            end
        end
        %% Show the menu
        function show(obj)
            if ~isempty(obj.items)
                if obj.fig.CurrentPoint(1)-10+obj.panel.Position(3) < obj.fig.Position(3)
                    obj.panel.Position(1) = obj.fig.CurrentPoint(1) - 10;
                else
                    obj.panel.Position(1) = obj.fig.CurrentPoint(1) + 10 - obj.panel.Position(3);
                end
                if obj.fig.CurrentPoint(2)+10-obj.panel.Position(4) > 0
                    obj.panel.Position(2) = obj.fig.CurrentPoint(2) + 10 - obj.panel.Position(4);
                else
                    obj.panel.Position(2) = obj.fig.CurrentPoint(2) - 10;
                end
                obj.panel.Visible = true;
                obj.listener      = obj.fig.addlistener('CurrentPoint','PostSet',@obj.cb_motion);
            end
        end
    end
    methods(Access = private)
        %% Hide the menu when moving out of it
        function cb_motion(obj,~,~)
            if obj.fig.CurrentPoint(1)<obj.panel.Position(1) || obj.fig.CurrentPoint(1)>sum(obj.panel.Position([1,3])) || obj.fig.CurrentPoint(2)<obj.panel.Position(2) || obj.fig.CurrentPoint(2)>sum(obj.panel.Position([2,4]))
                obj.panel.Visible = false;
                delete(obj.listener);
            end
        end
    end
end


% This script launches all the testUnits.

d = dir(pwd);
isub = [d(:).isdir];
nameFolds = {d(isub).name}';
nameFolds(ismember(nameFolds,{'.','..'})) = [];

for i=1:length(nameFolds)
    cd([pwd filesep nameFolds{i}]);
    eval([nameFolds{i} '_test_suite']);
    cd('..');
end


function db_close

% DB_CLOSE closes the connection to the database
%
% Use as
%   db_close

% Copyright (C) 2007, Robert Oostenveld
%
% $Log: db_close.m,v $
% Revision 1.1  2007/11/07 10:50:45  roboos
% created helper functions for easy access to a MySQL database table using a structure for representing the data
%

mysql('close');


function ft_create_buffer(port)

% FT_CREATE_BUFFER starts the thread with the TCP server attached to the local
% Matlab instance. The TCP server will listen to the specified network
% port, and accept incoming read and write requests.
%
% Use as
%   ft_create_buffer(port)
% where port is the TCP port to which the server listens. The default port
% number is 1972.
%
% See also FT_DESTROY_BUFFER

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

if nargin<1
  port = 1972;
end

try
  buffer('tcpserver', 'init', 'localhost', port);
  pause(1);
catch
  if ~isempty(strfind(lasterr, 'thread is already running'))
    warning('thread is already running');
  else
    rethrow(lasterror);
  end
end


%  This callback routine has to be an m-file, not a function
%  because it modifies the workspace.  We know which function to
%  execute by examining the label of the current menu item.
%
%  Keith Rogers 11/30/93

SavedFile = get(get(gcm2,'Parent'),'UserData');

if (strcmp(get(gcm2,'Label'),'Load'))
    [filename,pathname] = uigetfile('*.mat',...
        'Choose a MATLAB Data file',50,50);
    if (filename ~= 0)
        SavedFile = [pathname filename];
        clear filename pathname;
        eval(['load ' SavedFile ';']);
        set(get(gcm2,'Parent'),'UserData',SavedFile);
    end
elseif (strcmp(get(gcm2,'Label'),'Save'))
    if (strcmp(SavedFile,''))
        [filename,pathname] = uiputfile('*.mat','Data Filename',...
            50,50);
        if (filename ~= 0)
            SavedFile = [pathname filename];
            clear filename pathname;
            eval(['save ' SavedFile ';']);
            set(get(gcm2,'Parent'),'UserData',SavedFile);
        end
    else
        eval(['save ' SavedFile ';']);
    end
elseif (strcmp(get(gcm2,'Label'),'Save As'))
    if (strcmp(SavedFile,''))
        [filename,pathname] = uiputfile('*.mat','Data Filename',...
            50,50);
    else
        [filename,pathname] = uiputfile(SavedFile,'Data Filename',...
            50,50);
    end
    if (filename ~= 0)
        SavedFile = [pathname filename];
        clear filename pathname;
        eval(['save ' SavedFile ';']);
        set(get(gcm2,'Parent'),'UserData',SavedFile);
    end
elseif (strcmp(get(gcm2,'Label'),'New Figure'))
    figure;
    makemenus;
end


function makedir(dirname)

% create directory dirname

[path,name] = fileparts(dirname);

if ~exist(path,'dir')
    makedir(path);
end

if isunix
    if unix(['mkdir ' dirname])~=0
        error(['Cannot create directory ' dirname])
    end
else
    mkdir(path, name);
end


function SaveXMLParams(topNode,filename,name)

if nargin < 3,
  name = 'params';
end

docNode = com.mathworks.xml.XMLUtils.createDocument(name);
toc = docNode.getDocumentElement;
att = fieldnames(topNode);
for ndx = 1:numel(att)
  toc.appendChild(createXMLNode(docNode,att{ndx},topNode.(att{ndx})));
end
xmlwrite(filename,docNode);


classdef CoreTest < handle
    % CoreTest Base class for MTest unit tests
    %
    % Unit tests should inherit from this class
    %
    %     Licence
    %     -------
    %     Part of CoreMat. https://github.com/tomdoel/coremat
    %     Author: Tom Doel, 2013.  www.tomdoel.com
    %     Distributed under the MIT licence. Please see website for details.
    %

    properties
    end

    methods
        function Assert(obj, condition, message)
            if ~condition
                CoreErrorUtilities.ThrowException('CoreTest:AssertonFailure', ...
                    ['Assertion failure: ' message]);

            end
        end
    end
end


function myTab = findOrCreateTab(fig, look_here_containers, create_here_tabgroup, title, varargin)
    % FINDORCREATETAB return handle to a specified tab. if the tab doesn't exist, it is created
    %
    % tabH = FINDORCREATETAB( FIG, CONTAINER_TAG, TITLE, OPTS)
    %    FIG is a figure handle. The uitab with the Title "TITLE" will be returned only tabs
    %    belonging to this figure are returned. If the tab doesn't already exist, it will be
    %    created with the title TITLE within the container identified by the CONTAINER_TAG.
    %
    %    OPTS can be 'deleteable',
    %    CONTAINER_TAG can be the handle to a container, too.
    %

    import callbacks.copytab

    assert(isgraphics(look_here_containers) && isvalid(look_here_containers), 'expected valid container');

    deleteable= ismember('deleteable',varargin);
    if deleteable
        myTag='CopytabToFigDeleteable';
    else
        myTag='CopyTabToFig';
    end

    if ischarlike(create_here_tabgroup)
        myContainer=findobj(fig,'Type','uitabgroup','-and','Tag',create_here_tabgroup);
    elseif isgraphics(create_here_tabgroup) && isvalid(create_here_tabgroup)
        myContainer=create_here_tabgroup;
        assert(ancestor(myContainer,'figure')==fig);
    else
        error('unspecified container');
    end

    myTab=findobj(look_here_containers, 'Title', title, '-and', 'Type', 'uitab');

    if isempty(myTab)
        myTab=uitab(myContainer, 'Title',title);

        contextMenus = findobj(fig.Children,'flat','Tag',myTag,'-and','Type','uicontextmenu');

        if isempty(contextMenus)
            contextMenus=uicontextmenu(fig,'Tag',myTag);
            uimenu(contextMenus,'Label','Copy Contents to new figure (static)','Callback',@copytab)
            if deleteable
                uimenu(contextMenus,'Label','Close Tab','Callback',@(src,ev)delete(gco));
            end
        end
        myTab.UIContextMenu=contextMenus;
    end
end


function rootdirexamples = findexamplesdir()

rootdir = fileparts(which('SnirfClass.m'));
rootdirexamples = filesepStandard([rootdir, '/Examples/']);


classdef (Abstract) TrackInitiatorX < BaseX
% TrackInitiatorX Abstract class
%
% Summary of TrackInitiatorX:
% This is the base class for all TrackingX resamplers.
% Any custom defined Track Initiator should be derived from this TrackInitiatorX base class.
%
% TrackInitiatorX Properties:
%   None
%
% TrackInitiatorX Methods:
%   + TrackInitiatorX - Constructor method
%
% (+) denotes public properties/methods
%
% February 2018 Lyudmil Vladimirov, University of Liverpool.

    properties
    end

    methods
        function this = TrackInitiatorX(varargin)
        % TRACKINITIATORX Constructor method
        %
        % DESCRIPTION:
        % * TrackInitiatorX() returns a "TrackInitiatorX" object handle

            this@BaseX();
        end
    end
end


function str = hyperlink(url, label, msg)
%HYPERLINK  create a string that is displayable as hyperlink in Matlab console
%
% Usage examples:
%   fprintf('Search on %s\n', hyperlink('http://google.com','Google'));
%   fprintf(hyperlink('http://google.com','Google','Search on Google\n'));
%
% HYPERLINK converts the specified URL and text label into a string that is
% displayed as a hyperlink in the Matlab console (Command Window).
% In a deployed (compiled)  program, the URL and text label (if different
% from the URL) are displayed in a non-hyperlinked plain-text manner.
% If the optional 3rd input argument (msg) is specified, then all instances of
% the specified label within msg will be handled as above (hyperlinked etc.)
%
% IN:
%   url   - (mandatory) URL of webpage or Matlab command (e.g., 'matlab:which(...')
%   label - (optional)  text label of the hyperlink. Default: url
%   msg   - (optional)  string in which all label instances should be hyperlinked
%
% OUT:
%   str - string output

% Copyright: Yair Altman 2020-
%{
% 15/01/20 - Initial version
%}

    error(nargchk(1,3,nargin)); %#ok<NCHKN> narginchk is only available in R2011b+
    if nargin > 2 % msg was specified
        % replace all instances of label within msg with corresponding hyperlink
        str = strrep(msg, label, hyperlink(url,label));
        return
    end
    if nargin < 2, label = url; end
    isWebpage = strncmpi(url,'http',4);

    % Only hyperlink in interactive Matlab sessions, not in a deployed program
    if ~isdeployed  % interactive Matlab session
        if isWebpage  % open in a web browser
            str = ['' label ''];
        else  % Matlab command e.g. 'matlab:which(...'
            str = ['' label ''];
        end
    else  % deployed (compiled)
        if isWebpage && ~strcmp(label,url)  % display label next to url
            str = [label ' (' url ')'];
        elseif isWebpage  % text==url - display only the url
            str = url;
        else  % Matlab command (not a webpage) - just display the label
            str = label;
        end
    end
end


function s = structmerge(varargin)
% s = structmerge(s1,s2,s3,...)
% Merge structures into one combined structure.

s = struct();
for c = 1:numel(varargin)
    stmp = varargin{c};
    assert(isscalar(stmp) && isstruct(stmp),...
        'All input arguments must be scalar structures.');
    tmpflds = fieldnames(stmp);
    for fld = tmpflds(:)'
        fld = fld{1}; %#ok<FXSET>
        if isfield(s,fld)
            warning('structmerge:overlappingFields',...
                'Overwriting field ''%s''.',fld);
        end
        s.(fld) = stmp.(fld);
    end
end


function removed = plotlycleanup

% cleans up any old Plotly API MATLAB library files and folders

% initialize output
removed = {};

%----REMOVE WRAPPER FILES----%
REMOVEFILES = {'plotly.m'};

%----REMOVE WRAPPER FOLDERS----%
REMOVEFOLDERS = {'fig2plotly_aux'};

%----check for local Plotly instances----%
try
    plotlyScriptDirs = which('plotly.m','-all');

    if isempty(plotlyScriptDirs);
        error('plotly:missingScript',...
            ['\n\nWe were unable to locate plotly.m. Please Add this\n',...
            'script to your MATLAB search path and try again.\n\n']);
    end

catch exception %locating plotly error catch...
    fprintf(['\n\n' exception.identifier exception.message '\n\n']);
    return
end

% plotly toolbox directory
plotlyToolboxDir = fullfile(matlabroot,'toolbox','plotly');

% find the location of all plotly/ directories
dircount = 1;
for d = 1:length(plotlyScriptDirs)
    %parse filepath string at the Plotly directory
    plotlyLoc = strfind(fileparts(plotlyScriptDirs{d}),fullfile('MATLAB-api-master','plotly'));
    plotlyToolboxLoc = strfind(fileparts(plotlyScriptDirs{d}),plotlyToolboxDir);
    if ~isempty(plotlyLoc)
        plotlyDirs{dircount} = fullfile(plotlyScriptDirs{d}(1:plotlyLoc-1),'MATLAB-api-master','plotly');
        dircount = dircount + 1;
    elseif ~isempty(plotlyToolboxLoc)
        plotlyDirs{dircount} = plotlyToolboxDir;
        dircount = dircount + 1;
    end
end

for d = 1:length(plotlyDirs)

    % add plotlydirs to searchpath (will be removed in future once handled by plotlyupdate)
    addpath(genpath(plotlyDirs{d}));

    % delete files from plotly directory
    removefiles = fullfile(plotlyDirs{d}, REMOVEFILES);

    for f = 1:length(removefiles)

        % remove removefiles filepath from searchpath
        rmpath(fileparts(removefiles{f}));

        if exist(removefiles{f},'file')
            delete(removefiles{f});
            % update removed list
            removed = [removed removefiles{f}];
        end

        % add removefiles filepath back to searchpath
        addpath(fileparts(removefiles{f}));

    end

    % remove folders from plotly directory
    removefolders = fullfile(plotlyDirs{d},REMOVEFOLDERS);

    for f = 1:length(removefolders)
        if exist(removefolders{f},'dir')

            %remove folder from path
            rmpath(genpath(removefolders{f}));

            %delete folder/subfolders
            try
                status = rmdir(removefolders{f},'s');

                if (status == 0)
                    error('plotly:deletePlotlyAPI',...
                        ['\n\nShoot! It looks like something went wrong removing the Plotly API ' ...
                        'from the MATLAB toolbox directory \n' ...
                        'Please contact your system admin or post a topic on https://community.plotly.com/c/api/matlab/ for more information. \n\n']);
                end

                % update removed list
                removed = [removed removefolders{f}];

            end
        end
    end
end
end


function clearWarningErrorLabels()
%clearWarningErrorLabels Summary of this function goes here
%   Detailed explanation goes here
    global warn_error_label_handles;

    warnErrorLbls = warn_error_label_handles;
    for(i=1:length(warnErrorLbls)) %#ok<*NO4LP>
        h = warnErrorLbls(i);
        h.Visible = 'off';
    end
end


function hRD = plugin_rd_tx
% Reference design definition

%   Copyright 2014-2015 The MathWorks, Inc.

% Call the common reference design definition function
hRD = AnalogDevices.fmcomms5.common.plugin_rd('ZC702', 'Tx');
AnalogDevices.fmcomms5.zc702.add_io(hRD,'Tx');


function B = subsref(A, S)
B = builtin('subsref', A, S);


% VL_IHASHSUM


function dep = cfg_vout_fileparts(job)

% Define virtual outputs for cfg_run_fileparts. The path names can either
% be assigned to a cfg_files input or to an evaluated cfg_entry. File names
% and extensions can only be assigned to an evaluated cfg_entry.
%
% 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: cfg_vout_fileparts.m 4899 2012-09-05 13:44:17Z volkmar $

rev = '$Rev: 4899 $'; %#ok
dep(1)            = cfg_dep;
dep(1).sname      = sprintf('Directories');
dep(1).src_output = substruct('.','p');
dep(1).tgt_spec   = cfg_findspec({{'class','cfg_files', 'strtype','e'}});
dep(2)            = cfg_dep;
dep(2).sname      = sprintf('Directories (unique)');
dep(2).src_output = substruct('.','up');
dep(2).tgt_spec   = cfg_findspec({{'class','cfg_files', 'strtype','e'}});
dep(3)            = cfg_dep;
dep(3).sname      = sprintf('Filenames');
dep(3).src_output = substruct('.','n');
dep(3).tgt_spec   = cfg_findspec({{'strtype','e'}});
dep(4)            = cfg_dep;
dep(4).sname      = sprintf('Extensions');
dep(4).src_output = substruct('.','e');
dep(4).tgt_spec   = cfg_findspec({{'strtype','e'}});


classdef MimPluginGroupPanel < GemPanel
    % MimPluginGroupPanel. Part of the gui for the TD MIM Toolkit.
    %
    %     This class is used internally within the TD MIM Toolkit to help
    %     build the user interface.
    %
    %     MimPluginGroupPanel is a panel containing a group of Plugin buttons
    %
    %     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
        CachedMinY
        CachedMaxY
    end

    properties (Access = private)
        CachedPanelHeight
        CachedPanelWidth

        Category
        CurrentCategoryMap
        PluginButtonHandlesMap
        LoadManualSegmentationCallback;
    end

    methods
        function obj = MimPluginGroupPanel(parent, category, current_category_map, load_manual_segmentation_callback)
            obj = obj@GemPanel(parent);
            obj.LoadManualSegmentationCallback = load_manual_segmentation_callback;
            obj.Enabled = false;

            obj.Category = category;
            obj.CurrentCategoryMap = current_category_map;

            obj.AddPlugins(current_category_map);
        end

        function CreateGuiComponent(obj, position)
            CreateGuiComponent@GemPanel(obj, position);
            set(obj.GraphicalComponentHandle, 'Title', obj.Category, 'BorderType', 'etchedin');
        end

        function Resize(obj, new_position)
            Resize@GemPanel(obj, new_position);
            width = new_position(3);
            if isempty(obj.CachedPanelHeight) || (width ~= obj.CachedPanelWidth)
                obj.ResizePanel(width);
            end
        end

        function height = GetRequestedHeight(obj, width)
            if isempty(obj.CachedPanelHeight) || (width ~= obj.CachedPanelWidth)
                obj.ResizePanel(width);
            end
            height = obj.CachedPanelHeight;
        end

        function AddPlugins(obj, category_map)
            obj.CachedPanelHeight = [];
            obj.CachedPanelWidth = [];
            obj.PluginButtonHandlesMap = containers.Map;

            % Add the buttons to the panel
            for current_plugin_key = category_map.keys
                current_plugin = category_map(char(current_plugin_key));

                if isempty(current_plugin)
                    button_handle = MimSegmentationButton(obj, current_plugin_key{1}, obj.LoadManualSegmentationCallback);
                else
                    callback_function_handle = @current_plugin.RunPlugin;
                    button_handle = MimPluginButton(obj, callback_function_handle, current_plugin);
                end
                obj.AddChild(button_handle);

                obj.PluginButtonHandlesMap(char(current_plugin_key)) = button_handle;
            end
        end

        function UpdateForNewImage(obj, preview_fetcher, window, level)
            % Refresh the preview images for every button using the supplied dataset

            for button = obj.PluginButtonHandlesMap.values
                button{1}.AddPreviewImage(preview_fetcher, window, level);
            end
        end

        function plugin_found = AddPreviewImage(obj, plugin_name, preview_fetcher, window, level)
            % Refresh the preview image for the specified plugin

            plugin_found = obj.PluginButtonHandlesMap.isKey(plugin_name);
            if plugin_found
                plugin_button = obj.PluginButtonHandlesMap(plugin_name);
                plugin_button.AddPreviewImage(preview_fetcher, window, level);
            end
        end
    end

    methods (Access = private)
        function ResizePanel(obj, panel_width)

            category_map = obj.CurrentCategoryMap;
            button_spacing_w = 10;
            button_spacing_h = 5;
            header_height = 20;
            footer_height = 10;
            left_right_margins = 10;

            max_x = panel_width;
            position_x = left_right_margins;
            position_y = 0;

            last_y_coordinate = 0;
            row_height = 0;

            % Determine coordinates of buttons and the required panel size
            for current_plugin_key = category_map.keys
                current_plugin = category_map(char(current_plugin_key));

                button_handle = obj.PluginButtonHandlesMap(char(current_plugin_key));
                button_width = button_handle.ButtonWidth;
                button_height = button_handle.ButtonHeight;

                current_plugin.ParsedPluginInfo.X = position_x;
                current_plugin.ParsedPluginInfo.Y = position_y;
                current_plugin.ParsedPluginInfo.W = button_width;
                current_plugin.ParsedPluginInfo.H = button_height;

                last_y_coordinate = position_y;
                row_height = max(row_height, button_height);
                last_row_height = row_height;

                category_map(char(current_plugin_key)) = current_plugin;

                position_x = position_x + button_spacing_w + button_width;
                if (position_x + button_width) > (max_x - button_spacing_w)
                    position_y = position_y + button_spacing_h + row_height;
                    position_x = left_right_margins;
                    row_height = 0;
                end

            end

            obj.CachedPanelHeight = last_y_coordinate + last_row_height + header_height + footer_height;
            obj.CachedPanelWidth = panel_width;

            % Resize the buttons
            for current_plugin_key = category_map.keys
                current_plugin = category_map(char(current_plugin_key));

                position_x = current_plugin.ParsedPluginInfo.X;
                button_width = current_plugin.ParsedPluginInfo.W;
                button_height = current_plugin.ParsedPluginInfo.H;
                position_y = obj.CachedPanelHeight - button_height - header_height - current_plugin.ParsedPluginInfo.Y;

                new_position = [position_x, position_y, button_width, button_height];

                button_handle = obj.PluginButtonHandlesMap(char(current_plugin_key));
                button_handle.Resize(new_position);
            end
        end
    end
end