function attr = export_module(moduleName, varargin)
%"export_module"
%   Returns a populated Java attr representing a requested module,
%   given its moduleName string and the data required to populate the
%   fields.
%
%   Currently supported module names and their parameters are:
%       'patient'               scanS
%       'general_study'         scanS
%       'general_series'        scanS, doseS, structureS
%       'frame_of_reference'    scanS
%       'general_equipment'     'scan', scanS
%                               'structures', structureS
%       'general_image'         scanInfoS, scanS
%       'image_plane'           scanInfoS, scanS
%       'image_pixel'           scanInfoS, scanS
%       'ct_image'              scanInfoS, scanS
%       'sop_common'            'scan', scanS
%                               'structures', structureS
%       'structure_set'         structureS
%       'roi_contour'           structureS
%       'rt_series'             'structure', structureS
%       'rt_roi_observations'   structureS
%       'rt_dose'
%       'rt_dvh'
%
%JRA 06/19/06
%NAV 07/19/16 updated to dcm4che3
%    Used addAll over copyTo
%
%Usage:
%   attr = export_module(moduleName, varargin)
%
% 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/>.

%convert to dcm4che3 attribute
attr = javaObject('org.dcm4che3.data.Attributes');

switch lower(moduleName)
    %Get the top level tags used in this module.
    case 'patient'
        tagS = patient_module_tags;
        export_function = @export_patient_module_field;
    case 'general_study'
        tagS = general_study_module_tags;
        export_function = @export_general_study_module_field;
    case 'general_series'
        tagS = general_series_module_tags;
        export_function = @export_general_series_module_field;
    case 'frame_of_reference'
        tagS = frame_of_reference_module_tags;
        export_function = @export_frame_of_reference_module_field;
    case 'general_equipment'
        tagS = general_equipment_module_tags;
        export_function = @export_general_equipment_module_field;
    case 'content_identification'
        tagS = content_identification_module_tags;
        export_function = @export_content_identification_module_field;
    case 'general_image'
        tagS = general_image_module_tags;
        export_function = @export_general_image_module_field;
    case 'image_plane'
        tagS = image_plane_module_tags;
        export_function = @export_image_plane_module_field;
    case 'image_pixel'
        tagS = image_pixel_module_tags;
        export_function = @export_image_pixel_module_field;
    case 'ct_image'
        tagS = CT_image_module_tags;
        export_function = @export_CT_image_module_field;
    case 'pt_image'
        tagS = PT_image_module_tags;
        export_function = @export_PT_image_module_field;
    case 'mr_image'
        tagS = MR_image_module_tags;
        export_function = @export_MR_image_module_field;
    case 'sop_common'
        tagS = SOP_common_module_tags;
        export_function = @export_SOP_common_module_field;
    case 'structure_set'
        tagS = structure_set_module_tags;
        export_function = @export_structure_set_module_field;
    case 'roi_contour'
        tagS = ROI_contour_module_tags;
        export_function = @export_roi_contour_module_field;
    case 'rt_series'
        tagS = RT_series_module_tags;
        export_function = @export_rt_series_module_field;
    case 'rt_roi_observations'
        tagS = RT_ROI_observations_module_tags;
        export_function = @export_rt_roi_observations_module_field;
    case 'rt_dose'
        tagS = RT_dose_module_tags;
        export_function = @export_rt_dose_module_field;
    case 'rt_dvh'
        tagS = RT_DVH_module_tags;
        export_function = @export_RT_DVH_module_field;
    case 'multi_frame'
        tagS = multi_frame_module_tags;
        export_function = @export_multi_frame_module_field;
    case 'gsps'
        tagS = gsps_module_tags;
        export_function = @export_gsps_module_field;
%     case 'graphic_layer'
%         tagS = graphic_layer_module_tags;
%         export_function = @export_graphic_layer_module_field;
    otherwise
        error('Unrecognized or unsupported module export requested.')
end

%Prepare a attr template to be used by the export function for blank
%elements.
template = build_module_template(moduleName);

%Convert top level tags to decimal form.
%allTags = hex2dec({tagS.tag});
allTags = [tagS.tagdec];

%Iterate over all tags, calling the appropriate export function.
for i=1:length(allTags)

   %Prepare argments struct to pass to export function.
   args = [];
   args.tag         = allTags(i);
   args.data        = varargin;
   args.template    = template;

   %Get the Attributes object with data properly filled.
   %In this line "export_function" is a function HANDLE not an actual
   %function.  Need to check backwards compatibility with previous ML vers.

   el = export_function(args);

   if (~isempty(el))
       attr.addAll(el);
   else
       %Data in planC was insufficent to construct this element.
   end
end


%% Delete path
%
% Delete all subdirectories under pathstr to search path.
%
% Copyright (C) Long Chen. See COPYRIGHT.txt for details.

rmpath(genpath(pwd));
savepath;


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

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

% Last Modified by GUIDE v2.5 22-Jul-2014 15:37:16

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

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

set(handles.metaicon,'XTick',[]);
set(handles.metaicon,'YTick',[]);
set(handles.metaicon,'Box','on');
set(handles.metaicon,'Color',[51/255 102/255 153/255]);

set(handles.GroundOverlayCheck,'Value',1);
handles.DecType = 'none';
handles.DecSize = 3000;

set(handles.PlotSRP,'Value',1);
set(handles.PlotPath,'Value',1);
set(handles.PlotGroundTrack,'Value',1);
set(handles.PlotCollectionWedge,'Value',1);
set(handles.PlotCenterApVector,'Value',1);
set(handles.PlotPRFLines,'Value',1);

% Update handles structure
guidata(hObject, handles);

p = inputParser; % Extract parameter-value pairs
p.KeepUnmatched=true;
p.addParamValue('filename','');
p.parse(varargin{:});

if ~isempty(p.Results.filename)
    handles = LoadImage(p.Results.filename,handles);
end

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

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

% --- Executes during object creation, after setting all properties.
function filename_CreateFcn(hObject, eventdata, handles)
% hObject    handle to filename (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 button press in BrowseFile.
function BrowseFile_Callback(hObject, eventdata, handles)
% hObject    handle to BrowseFile (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

%load last path
if ispref('matlab_sar_toolbox','last_used_directory')
    pathstr = getpref('matlab_sar_toolbox','last_used_directory');
    if ~ischar(pathstr)||~exist(pathstr,'dir')
        pathstr = pwd;
    end
else
    pathstr = pwd;
end

%get iq filename
[fname, path] = uigetfile(sar_file_extensions({'complex','phd'}),'Open SAR Data File',pathstr);
if isnumeric(fname)
    return;
end

setpref('matlab_sar_toolbox','last_used_directory',path); %store path

filename = strcat(path,fname);
handles = LoadImage(filename,handles);

% Update handles structure
guidata(hObject, handles);

function handles = LoadImage(filename,handles)

set(handles.filename,'String',filename);

% determine if input file is complex image or phase history data
if ~isempty(guess_ph_format(filename))
    MetaIcon_PHD(filename,'handle',handles.metaicon);
    % Should disable all of the image controls here (overlay, boundary, and fill)
else
    MetaIcon_Complex(filename,'handle',handles.metaicon);
end

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

%get kml name from user
%load last path
if ispref('matlab_sar_toolbox','last_used_directory')
    pathstr = getpref('matlab_sar_toolbox','last_used_directory');
    if ~ischar(pathstr)||~exist(pathstr,'dir')
        pathstr = pwd;
    end
else
    pathstr = pwd;
end

%open input file
filename = get(handles.filename,'String');
if ~exist(filename,'file')
    return;
end
is_phase_history = ~isempty(guess_ph_format(filename));
if is_phase_history
    reader_obj = open_ph_reader(filename);
else
    reader_obj = open_reader(filename);
end
if ~iscell(reader_obj) % Assure cell array format
    reader_obj = {reader_obj};
end
meta = reader_obj{1}.get_meta();
[path_ignore, fnameNoExt] = fileparts(filename);
% Open output file
if get(handles.GroundOverlayCheck,'Value')
    [fname, path] = uiputfile( {'*.kmz','KMZ Files (*.kmz)'},'Save KMZ File',[pathstr fnameNoExt]);
else
    [fname, path] = uiputfile( {'*.kml','KML Files (*.kml)'},'Save KML File',[pathstr fnameNoExt]);
end
if ~fname, return; end; % Cancel was pressed
k = kml(meta.CollectionInfo.CoreName); %create an kmltoolbox object
k.filename = fullfile(path, fname);
k.zip = get(handles.GroundOverlayCheck,'Value'); % Only zip if we have overlay images

%set border values
if get(handles.PlotImageBorder,'Value')
    BorderColor = 'Red';
    FillColor = 'Red';
else
    BorderColor = [];
    FillColor = [];
end

%loop through segments
NumSegments = length(reader_obj);
if NumSegments>1
    wb = waitbar(0);
end
for i=1:NumSegments
    if NumSegments>1
        waitbar(i/NumSegments,wb,sprintf('Processing segment %d of %d',i,NumSegments));
    end

    if get(handles.GroundOverlayCheck,'Value')
        %image filename is state with path relative to KML
        ImName = sprintf('Overlay_%d.png',i); % Will be put in same directory where KML is
    else
        ImName = '';
    end
    add_sar_2kml(k,reader_obj{i},...
        'srp',get(handles.PlotSRP,'Value'),...
        'border_color',BorderColor,...
        'border_thickness',1,...
        'fill_color',FillColor,...
        'transparency',0.25,...
        'overlay_max_size',handles.DecSize,...
        'overlay_decimate',handles.DecType,...
        'overlay_filename',ImName,...
        'sensor_path',get(handles.PlotPath,'Value'),...
        'sensor_ground_track',get(handles.PlotGroundTrack,'Value'),...
        'collection_wedge',get(handles.PlotCollectionWedge,'Value'),...
        'center_aperture_vector',get(handles.PlotCenterApVector,'Value'),...
        'ambiguity_bounds',get(handles.PlotPRFLines,'Value'),...
        'description_function',@(x) default_SICD_description(x,get(handles.English,'Value')));
end

k.save();
if ~isempty(k.includeFiles)
    delete(k.includeFiles{:});
end
reader_obj{1}.close; % Multiple segments, but only a single file to close
if NumSegments>1
    close(wb); % Waitbar
end

msgbox('Done creating shapefile');

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

% Hint: get(hObject,'Value') returns toggle state of GroundOverlayCheck

if get(handles.GroundOverlayCheck,'Value')
    %set size of output overlay image based on Quality specified
    switch get(handles.OverlayQualityCombo,'Value');
        case 1
            handles.DecSize = 5000;
        case 2
            handles.DecSize = 3000;
        otherwise
            handles.DecSize = 1000;
    end

    %remap, max decimated typically looks better with "brighter" remap
    if get(handles.MaxDecimateCheck,'Value')
        handles.DecType = 'max';
    else
        handles.DecType = 'none';
    end
else
    handles.DecSize = 0;
    handles.DecType = '';
end
guidata(hObject, handles);

% --- Executes during object creation, after setting all properties.
function OverlayQualityCombo_CreateFcn(hObject, eventdata, handles)
% hObject    handle to OverlayQualityCombo (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 PlotSRP.
function PlotSRP_Callback(hObject, eventdata, handles)
% hObject    handle to PlotSRP (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of PlotSRP

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

% Hint: get(hObject,'Value') returns toggle state of PlotPath

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

% Hint: get(hObject,'Value') returns toggle state of PlotGroundTrack

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

% Hint: get(hObject,'Value') returns toggle state of PlotCollectionWedge

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

% Hint: get(hObject,'Value') returns toggle state of PlotCenterApVector

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

% Hint: get(hObject,'Value') returns toggle state of PlotPRFLines

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

%load last path
if ispref('matlab_sar_toolbox','last_used_directory')
    pathstr = getpref('matlab_sar_toolbox','last_used_directory');
    if ~ischar(pathstr)||~exist(pathstr,'dir')
        pathstr = pwd;
    end
else
    pathstr = pwd;
end

data_dir = uigetdir(pathstr, 'Select directory of SAR data');
if ~data_dir, return; end; % Cancel
setpref('matlab_sar_toolbox','last_used_directory',data_dir); %store path

if get(handles.GroundOverlayCheck,'Value')
    [fname, path] = uiputfile( {'*.kmz','KMZ Files (*.kmz)'},'Save KMZ File',pathstr);
else
    [fname, path] = uiputfile( {'*.kml','KML Files (*.kml)'},'Save KML File',pathstr);
end
if ~fname, return; end; % Cancel was pressed
[path_ignore, fname_no_extension] = fileparts(fname);

%set border values
if get(handles.PlotImageBorder,'Value')
    BorderColor = 'Red';
    FillColor = 'Red';
else
    BorderColor = [];
    FillColor = [];
end

image2kmlbatch(data_dir, strcat(path,fname), ...
    'name',fname_no_extension,...
    'srp',get(handles.PlotSRP,'Value'),...
    'border_color',BorderColor,...
    'border_thickness',1,...
    'fill_color',FillColor,...
    'transparency',0.25,...
    'overlay_max_size',handles.DecSize,...
    'overlay_decimate',handles.DecType,...
    'sensor_path',get(handles.PlotPath,'Value'),...
    'sensor_ground_track',get(handles.PlotGroundTrack,'Value'),...
    'collection_wedge',get(handles.PlotCollectionWedge,'Value'),...
    'center_aperture_vector',get(handles.PlotCenterApVector,'Value'),...
    'ambiguity_bounds',get(handles.PlotPRFLines,'Value'),...
    'description_function',@(x) default_SICD_description(x,get(handles.English,'Value')));
msgbox('Done creating shapefile');

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

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

% Hint: get(hObject,'Value') returns toggle state of PlotImageBorder

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


function outLink = hyperlink(url, urlText, altText1, altText2)
% Converts a url to a clickable link in order to improve usability
% when using the MATLAB desktop environment
%
% USAGE:
%   outLink = hyperlink(url, urlText, altText1, altText2)
%
% INPUTS:
%    url:         url address
%    urlText:     url for java
%    altText1:    alternative text before link
%    altText2:    alternative text after link
%
% OUTPUT:
%    outLink:     clickable link

    if nargin < 2
        urlText = url;
    end
    if nargin < 3
        altText1 = '';
    end
    if nargin < 4
        altText2 = '';
    end

    outLink = [altText1, url, altText2];
    if usejava('desktop')
        outLink = ['', urlText, ''];
    end
end


%ISNAN Datafile overload


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

% Last Modified by GUIDE v2.5 13-Mar-2004 14:59:53

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @test_edit2_OpeningFcn, ...
                   'gui_OutputFcn',  @test_edit2_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin & isstr(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 test_edit2 is made visible.
function test_edit2_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 test_edit2 (see VARARGIN)

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

% Update handles structure
guidata(hObject, handles);

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

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

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

% Find the value typed into the edit box
str = get (handles.EditBox2,'String');

% Place the value into the text field
set (handles.TextBox2,'String',str);

% --- Executes during object creation, after setting all properties.
function EditBox2_CreateFcn(hObject, eventdata, handles)
% hObject    handle to EditBox2 (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
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end


function copyDataToCluster(localLoc, remoteLoc, clusterHost)
%COPYDATATOCLUSTER Copies files or directories from the local machine
% to a location on a remote host.

% Copyright 2006 The MathWorks, Inc.

% Use scp to copy files.
copyCmd = sprintf('scp -r %s "%s:%s"', localLoc, clusterHost, remoteLoc);

[s, r] = system(copyCmd);
if s ~= 0
    error('distcomp:scheduler:FailedRemoteOperation', ...
        ['Failed to copy files from "%s"\n' ...
        'to "%s" on the host "%s".\n' ...
        'Command Output:\n' ...
        '"%s"\n' ...
        ], localLoc, remoteLoc, clusterHost, r);
end


%% The class fibre
%
%%
%


function saveresults_data(res,peval, name_res_file)
fprintf('saving data \n');
dir_res = [peval.path_res];
if ~(strcmp(peval.path_res, peval.path_data)) %not identical
    mkdir (dir_res);
end
save ([dir_res '/' name_res_file],'res', 'peval', 'p')


function unimplemented_error(varargin)
    % provide error dialog (if interactive) and error message for unimplemented features
    %
    % see also under_construction

    beep;
    if ZmapDialog.Data.Interactive
        errordlg('Under Construction','Not reimplemented yet');
    end
    error('ZMAP:UNIMPLEMENTED','Under Construction : Not yet implemented / reimplemented');
end


function cfg_defaults = cfg_mlbatch_defaults

% function cfg_defaults = cfg_mlbatch_defaults
% This file contains defaults that control the behaviour and appearance
% of matlabbatch.
%
% 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_mlbatch_defaults.m 6641 2015-12-11 10:17:11Z volkmar $

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

try
    % Font definition for cfg_ui user interface
    % cfg_defaults.cfg_ui.Xfont is a param/value list of property values as returned by uisetfont
    % lfont: used in lists, value edit dialogues etc.
    cfg_defaults.cfg_ui.lfont = {'FontAngle','normal',...
        'FontName',get(0,'factoryTextFontName'),...
        'FontSize',12,...
        'FontUnits','points',...
        'FontWeight','normal'};
    % bfont: used for buttons
    cfg_defaults.cfg_ui.bfont = {'FontAngle',get(0, 'factoryUicontrolFontAngle'),...
        'FontName',get(0,'factoryUicontrolFontName'),...
        'FontSize',get(0, 'factoryUicontrolFontSize'),...
        'FontUnits',get(0, 'factoryUicontrolFontUnits'),...
        'FontWeight',get(0, 'factoryUicontrolFontWeight')};
    % Toggle ExpertEdit mode. Value can be 'on' or 'off'
    cfg_defaults.cfg_ui.ExpertEdit = 'off';
catch
    cfg_defaults.cfg_ui = false;
end

% cfg_util
% Parallel execution of independent modules
% Currently, this does not run modules in parallel, but it may reorder
% execution order of modules: all modules without dependencies will be run
% before modules with dependencies will be harvested again. If some modules
% have side effects (e.g. "Change Directory") that are not encoded as
% dependency, this may lead to unwanted results. Disabling parallel
% execution incurs an overhead during job execution because the job
% must be harvested more often.
cfg_defaults.cfg_util.runparallel = false;
% cfg_util('genscript',...) hook to add application specific initialisation
% code to generated scripts. This must be a function handle that takes no
% input arguments and returns two output arguments - the code to be
% inserted as a string array, and a flag indicating whether cfg_util should
% add job execution code (flag == true) or not (flag == false).
% The generated code will be inserted after the for loop which collects the
% input. In the generated code, variables 'jobs' and 'inputs' can be
% referenced. These will hold the jobs and corresponding inputs.
cfg_defaults.cfg_util.genscript_run = [];
% A diary of command window output can be kept for jobs. This is useful for
% debugging various problems related to job execution.
cfg_defaults.cfg_util.run_diary = false;

% Message defaults
cfg_defaults.msgdef.identifier  = 'cfg_defaults:defaultmessage';
cfg_defaults.msgdef.level       = 'info'; % one of 'info', 'warning', 'error'
cfg_defaults.msgdef.destination = 'stdout'; % one of 'none', 'stdout',
                                            % 'stderr', 'syslog'. Errors
                                            % will always be logged to
                                            % the command window, and
                                            % additionally to syslog, if specified
cfg_defaults.msgdef.verbose     = 'off';
cfg_defaults.msgdef.backtrace   = 'off';

cfg_defaults.msgcfg(1)             = cfg_defaults.msgdef;
cfg_defaults.msgcfg(1).identifier  = 'matlabbatch:run:jobfailederr';
cfg_defaults.msgcfg(1).level       = 'error';
cfg_defaults.msgcfg(2)             = cfg_defaults.msgdef;
cfg_defaults.msgcfg(2).identifier  = 'matlabbatch:cfg_util:addapp:done';
cfg_defaults.msgcfg(2).destination = 'none';
cfg_defaults.msgcfg(3)             = cfg_defaults.msgdef;
cfg_defaults.msgcfg(3).identifier  = 'matlabbatch:initialise:invalid';
cfg_defaults.msgcfg(3).level       = 'error';
cfg_defaults.msgcfg(4)             = cfg_defaults.msgdef;
cfg_defaults.msgcfg(4).identifier  = 'matlabbatch:fopen';
cfg_defaults.msgcfg(4).level       = 'error';
cfg_defaults.msgcfg(5)             = cfg_defaults.msgdef;
cfg_defaults.msgcfg(5).identifier  = 'cfg_getfile:notcolumncell';
cfg_defaults.msgcfg(5).level       = 'error';
cfg_defaults.msgcfg(6)             = cfg_defaults.msgdef;
cfg_defaults.msgcfg(6).identifier  = 'matlabbatch:subsref:cfg_dep:multisubs';
cfg_defaults.msgcfg(6).level       = 'warning';
cfg_defaults.msgcfg(6).backtrace   = 'on';

cfg_defaults.msgtpl( 1)             = cfg_defaults.msgdef;
cfg_defaults.msgtpl( 1).identifier  = '^matlabbatch:subsasgn';
cfg_defaults.msgtpl( 1).level       = 'error';
cfg_defaults.msgtpl( 2)             = cfg_defaults.msgdef;
cfg_defaults.msgtpl( 2).identifier  = '^matlabbatch:subsref';
cfg_defaults.msgtpl( 2).level       = 'error';
cfg_defaults.msgtpl( 3)             = cfg_defaults.msgdef;
cfg_defaults.msgtpl( 3).identifier  = '^matlabbatch:constructor';
cfg_defaults.msgtpl( 3).level       = 'error';
cfg_defaults.msgtpl( 4)             = cfg_defaults.msgdef;
cfg_defaults.msgtpl( 4).identifier  = '^matlabbatch:deprecated';
cfg_defaults.msgtpl( 4).destination = 'none';
cfg_defaults.msgtpl( 5)             = cfg_defaults.msgdef;
cfg_defaults.msgtpl( 5).identifier  = '^matlabbatch:usage';
cfg_defaults.msgtpl( 5).level       = 'error';
cfg_defaults.msgtpl( 6)             = cfg_defaults.msgdef;
cfg_defaults.msgtpl( 6).identifier  = '^matlabbatch:setval';
cfg_defaults.msgtpl( 6).destination = 'none';
cfg_defaults.msgtpl( 7)             = cfg_defaults.msgdef;
cfg_defaults.msgtpl( 7).identifier  = '^matlabbatch:run:nomods';
cfg_defaults.msgtpl( 7).level       = 'info';
cfg_defaults.msgtpl( 8)             = cfg_defaults.msgdef;
cfg_defaults.msgtpl( 8).identifier  = '^matlabbatch:cfg_struct2cfg';
cfg_defaults.msgtpl( 8).destination = 'none';
cfg_defaults.msgtpl( 9)             = cfg_defaults.msgdef;
cfg_defaults.msgtpl( 9).identifier  = '^MATLAB:inputdlg';
cfg_defaults.msgtpl( 9).level       = 'error';
cfg_defaults.msgtpl(10)             = cfg_defaults.msgdef;
cfg_defaults.msgtpl(10).identifier  = '^MATLAB:listdlg';
cfg_defaults.msgtpl(10).level       = 'error';
cfg_defaults.msgtpl(11)             = cfg_defaults.msgdef;
cfg_defaults.msgtpl(11).identifier  = '^MATLAB:num2str';
cfg_defaults.msgtpl(11).level       = 'error';
cfg_defaults.msgtpl(12)             = cfg_defaults.msgdef;
cfg_defaults.msgtpl(12).identifier  = '^matlabbatch:ok_subsasgn';
cfg_defaults.msgtpl(12).destination = 'none';
cfg_defaults.msgtpl(13)             = cfg_defaults.msgdef;
cfg_defaults.msgtpl(13).identifier  = 'matlabbatch:checkval:numcheck:transposed';
cfg_defaults.msgtpl(13).destination = 'none';

% value check for cfg_branch/choice/repeat items - set to false after
% configuration has been initialised to speed up job
% initialisation/harvest/run - set this to true if you want to debug some
% configuration or the batch system itself
cfg_defaults.cfg_item.checkval = false;

% verbosity of code generation for cfg_dep objects
% true  - one-line code containing only source information
% false - full code, including source and target specifications
cfg_defaults.cfg_dep.gencode_short = true;


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

% Last Modified by GUIDE v2.5 04-Aug-2010 23:40:57

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

% Choose default command line output for SaveFMFSettings
handles.output = struct;
handles.archstr = computer('arch');
if length(varargin) >= 1,
  handles.previous_values = varargin{1};
else
  handles.previous_values = struct;
end

% Output FPS
if isfield(handles.previous_values,'OutputFPS'),
  handles.output.OutputFPS = handles.previous_values.OutputFPS;
else
  handles.output.OutputFPS = 30;
end
set(handles.edit_OutputFPS,'String',num2str(handles.output.OutputFPS));

% Compression
if length(varargin) >= 2 && ~isempty(varargin{2}),
  handles.Compressions = varargin{2};
else
  switch handles.archstr,
    case 'win32',
      handles.Compressions = {'None','MSVC','RLE','Cinepak','Indeo5'};
    case 'win64',
      handles.Compressions = {'None','MSVC','RLE','IYUV'};
    otherwise
      handles.Compressions = {'None'};
  end
end
if isfield(handles.previous_values,'Compression') && ...
    ismember(handles.previous_values.Compression,handles.Compressions),
  handles.output.Compression = handles.previous_values.Compression;
elseif ismember('None',handles.Compressions'),
  handles.output.Compression = 'None';
else
  handles.output.Compression = 'Uncompressed AVI';
end

set(handles.popupmenu_Compression,'String',handles.Compressions,...
  'Value',find(strcmp(handles.Compressions,handles.output.Compression),1));

% Quality
if isfield(handles.previous_values,'Quality') && ...
    ~strcmp(handles.output.Compression,'None')
  handles.output.Quality = handles.previous_values.Quality;
else
  handles.output.Quality = 100;
end
set(handles.edit_Quality,'String',num2str(handles.output.Quality));
if strcmp(handles.output.Compression,'None'),
  set(handles.edit_Quality,'Enable','off');
end

% Start Frame
if isfield(handles.previous_values,'StartFrame'),
  handles.output.StartFrame = handles.previous_values.StartFrame;
else
  handles.output.StartFrame = 1;
end
set(handles.edit_StartFrame,'String',num2str(handles.output.StartFrame));

% End Frame
if isfield(handles.previous_values,'EndFrame'),
  handles.output.EndFrame = handles.previous_values.EndFrame;
else
  handles.output.EndFrame = inf;
end
set(handles.edit_EndFrame,'String',num2str(handles.output.EndFrame));

% Update handles structure
guidata(hObject, handles);

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

% --- Outputs from this function are returned to the command line.
function varargout = SaveFMFSettings_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;
delete(handles.figure1);

% --- Executes on selection change in popupmenu_Compression.
function popupmenu_Compression_Callback(hObject, eventdata, handles)
% hObject    handle to popupmenu_Compression (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 popupmenu_Compression contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupmenu_Compression
handles.output.Compression = handles.Compressions{get(hObject,'Value')};
if strcmp(handles.output.Compression,'None'),
  handles.output.Quality = 100;
  set(handles.edit_Quality,'Enable','off','String',num2str(handles.output.Quality));
else
  set(handles.edit_Quality,'Enable','on');
end
guidata(hObject,handles);

% --- Executes during object creation, after setting all properties.
function popupmenu_Compression_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupmenu_Compression (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 edit_Quality_Callback(hObject, eventdata, handles)
% hObject    handle to edit_Quality (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 edit_Quality as text
%        str2double(get(hObject,'String')) returns contents of edit_Quality as a double

v = str2double(get(hObject,'String'));
if isnan(v) || v <= 0 || v > 100,
  set(hObject,'String',num2str(handles.output.Quality));
else
  handles.output.Quality = v;
  guidata(hObject,handles);
end

% --- Executes during object creation, after setting all properties.
function edit_Quality_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_Quality (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 button press in pushbutton_Cancel.
function pushbutton_Cancel_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton_Cancel (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

handles.output = struct;
guidata(hObject,handles);
uiresume(handles.figure1);

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

uiresume(handles.figure1);

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

v = str2double(get(hObject,'String'));
if isnan(v) || v <= 0,
  set(hObject,'String',num2str(handles.output.OutputFPS));
else
  handles.output.OutputFPS = v;
  guidata(hObject,handles);
end

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

v = round(str2double(s));
if v <= handles.output.EndFrame && v >= 1,
  handles.output.StartFrame = v;
else
  set(hObject,'String',num2str(handles.output.StartFrame));
end
guidata(hObject,handles);

% --- Executes during object creation, after setting all properties.
function edit_StartFrame_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_StartFrame (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 edit_EndFrame_Callback(hObject, eventdata, handles)
% hObject    handle to edit_EndFrame (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 edit_EndFrame as text
%        str2double(get(hObject,'String')) returns contents of edit_EndFrame as a double
s = strtrim(get(hObject,'String'));
if strcmpi(s,'inf') || strcmpi(s,'infty'),
  handles.output.EndFrame = inf;
  set(hObject,'String','Inf');
else
  v = round(str2double(s));
  if v >= 1 && v >= handles.output.StartFrame,
    handles.output.EndFrame = v;
  else
    set(hObject,'String',num2str(handles.output.EndFrame));
  end
end
guidata(hObject,handles);

% --- Executes during object creation, after setting all properties.
function edit_EndFrame_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_EndFrame (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 when user attempts to close figure1.
function figure1_CloseRequestFcn(hObject, eventdata, handles)
% hObject    handle to figure1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: delete(hObject) closes the figure
handles.output = struct;
guidata(hObject,handles);
uiresume(handles.figure1);


%% This function is used to turn off the server on the robot
% function [ output_args ] = net_turnOffServer( t )
% t: is the TCP/IP connection object
% Copy right, Mohammad SAFEEA, 3rd of May 2017


function neighbours = fixneighbours(neighbours)
% This function converts the old format of the neighbourstructure into the
% new format - although it just works as a wrapper
%
% See also FT_NEIGHBOURSELECTION

neighbours = cellStruct2StructCell(neighbours);

end


function hostip = hlp_hostip()
% Find the host IP address in a platform-independent fashion.

% Copyright (C) Christian Kothe, SCCN, 2010, christian@sccn.ucsd.edu
%
% This program is free software; you can redistribute it and/or modify it under the terms of the GNU
% General Public License as published by the Free Software Foundation; either version 2 of the
% License, or (at your option) any later version.
%
% This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
% even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
% General Public License for more details.
%
% You should have received a copy of the GNU General Public License along with this program; if not,
% write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
% USA

import java.net.InetAddress;
hostip = char(InetAddress.getLocalHost());
hostip = hostip(find(hostip=='/',1)+1:end);


function str = showdetail(item)

% function str = showdetail(item)
% Display details for a cfg_exbranch and all of its options.
%
% 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: showdetail.m 4867 2012-08-30 13:04:51Z volkmar $

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

str = showdetail(item.cfg_branch);
str{end+1} = 'Class  : cfg_exbranch';
str{end+1} = 'Functions associated with this item:';
% Display details about function handles
str{end+1} = sprintf('.prog  : %s', func2str(item.prog));
if ~isempty(item.vout)
    str{end+1} = sprintf('.vout  : %s', func2str(item.vout));
elseif ~isempty(item.vfiles)
    str{end+1} = sprintf('.vfiles: %s', func2str(item.vfiles));
end


function display(tree)
% XMLTREE/DISPLAY Command window display of an XMLTree
% FORMAT display(tree)
%
% tree - XMLTree object
%__________________________________________________________________________
%
% This method is called when the semicolon is not used to terminate a
% statement which returns an XMLTree.
%__________________________________________________________________________
% Copyright (C) 2002-2011  http://www.artefact.tk/

% Guillaume Flandin
% $Id: display.m 4460 2011-09-05 14:52:16Z guillaume $

disp(' ');
disp([inputname(1),' = ']);
disp(' ');
for i=1:numel(tree)
    disp([blanks(length(inputname(1))+3) char(tree(i))]);
end
disp(' ');


% BUZCODE
%
% Files
%   bz_IsEventDatatype - this function checks that the input variable is of the buzcode event
%   compileBuzcode     - this function recompiles all .c scripts to create the apropriate .mex* files on your local machine


function str = showmydoc(item, indent)

% function str = showmydoc(item, indent)
% Display help text for a cfg_choice and all of its options, without
% recursive calls to child nodes.
%
% 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: showmydoc.m 2085 2008-09-12 10:26:59Z volkmar $

rev = '$Rev: 2085 $'; %#ok
str1 = showdoc(item.cfg_item, indent);
citems = subsref(item, substruct('.','values'));
str2{1} = 'One of the following options must be selected:';
% Display short listing of cfg_choice value items first
str3 = cell(1,numel(citems));
for k = 1:numel(citems)
    str3{k} = sprintf('* %s', subsref(citems{k}, substruct('.','name')));
end;
valitem = subsref(item, substruct('.','val'));
if ~isempty(valitem)
    str4 = {'Currently selected option:', ...
            sprintf('* "%s"',subsref(valitem{1}, substruct('.','name')))};
else
    str4 = {};
end;
str = [str1(:); {''}; str2(:); str3(:); str4(:)];


function state = evolutioncomplete(options,state,flag)
% Plays a notification when genetic algorithm finishes. Requires a
% Starcraft installation, in its default directory, typically:
% C:\Program Files\Starcraft
%
% Works with Windows, not tested on other platforms.

if ispc && strcmp(flag,'done') && ~strcmp(options.Display,'off')
    sounddir = [getenv('ProgramFiles') '\Starcraft\Sound\Zerg\Advisor'] ;
    if isdir(sounddir) && exist([sounddir '\ZAdUpd02.wav'],'file')
        [y, Fs, nbits] = audioread([sounddir '\ZAdUpd02.wav']) ;
        obj = audioplayer(y, Fs, nbits);
        playblocking(obj)
    end
end


%--- help for comparison ---
%
%  INTERNAL FUNCTION
%
%


function tf=isNonFailure(obj)
% return whether this test was a non-failure
%
% tf=isSuccess(obj)
%
% Input:
%   obj                     MoxUnitFailedTestOutcome object
%
% Output:
%   tf                      set to false, because a failed test is a
%                           failure
%
% See also: @MoxUnitTestOutcome

    tf=false;


function save_mat(key,outfilename)
% Saves the Key to a mat file.
% Inputs:
%   key: An object of type Key.
%   outfilename: The name for the output mat file.

assert(nargin==2)
assert(isa(key,'Key'))
assert(isa(outfilename,'char'))
assert(key.validate())

warning('off','MATLAB:structOnObject')
key = struct(key);
warning('on','MATLAB:structOnObject')
save(outfilename,'key');


host = 'https://hedtools.ucsd.edu/hed';
%host = 'http://127.0.0.1:5000/';
errorMap = containers.Map('KeyType', 'char', 'ValueType', 'any');
errorMap('testGetServices') = testGetServices(host);
errorMap('testEventServices') = testEventServices(host);
errorMap('testEventSearchServices') = testEventSearchServices(host);
errorMap('testSidecarServices') = testSidecarServices(host);
errorMap('testSpreadsheetServices') = testSpreadsheetServices(host);
errorMap('testStringServices') = testStringServices(host);

%% Output the errors
fprintf('\n\nOverall error report:\n');
keys = errorMap.keys();
for k = 1:length(keys)
    errors = errorMap(keys{k});
    if isempty(errors)
        fprintf('\t%s: no errors\n', keys{k});
    else
        fprintf('\t%s:\n', keys{k});
        for n = 1:length(errors)
           fprintf('\t\t%s\n', keys{k}, errors{n});
        end
    end
end


cur_dir = pwd;
cd(fileparts(mfilename('fullpath')));

fprintf('Downloading Selective Search IJCV code...\n');
urlwrite('http://huppelen.nl/publications/SelectiveSearchCodeIJCV.zip', 'SelectiveSearchCodeIJCV.zip');

fprintf('Unzipping...\n');
unzip('SelectiveSearchCodeIJCV.zip');

fprintf('Done.\n');
system('del SelectiveSearchCodeIJCV.zip');

cd(cur_dir);


% 1) You need to check that your FlightGear installation path is configured correctly below.
% 2) You need to install the 'ExperimentalCarrier' aircraft in %FG_ROOT%/data/Aircraft, e.g. C:\Program Files\FlightGear 3.4.0\data\Aircraft\ExperimentalCarrier

setenv('FG_ROOT', 'C:\Program Files\FlightGear 3.4.0\data');
currPath = pwd;
cd 'C:\Program Files\FlightGear 3.4.0'
system('bin\fgfs --aircraft=ExperimentalCarrier --fdm=network,localhost,5501,5502,5503 --fog-fastest --disable-clouds --start-date-lat=2004:06:01:09:00:00 --disable-sound --in-air --enable-freeze --airport=KSFO --runway=10L --altitude=328 --heading=0 --offset-distance=0 --offset-azimuth=0 &')
cd(currPath);


%==========================================================================
% function channelRead()
%  Reads bytes from from the SocketChannel.
%
% Author: Jude Collins
% Date: 09 March 2012
%
%==========================================================================
function [len buffer] = channelRead(sockChannel, numBytes)
	%
	len = 0;
	buffer = [];

	if nargin > 1 && numBytes < 0
		channelErrMsg('channelRead:negativeBytes','numBytes must be >= 0');
		error('channelRead:negativeBytes','numBytes must be >= 0');
	end

	if ~sockChannel.isConnected
		warning('channelRead:notConnected','sockChannel is not connected');
		return;
	end

	if nargin < 2
		numBytes	= sockChannel.socket.getReceiveBufferSize();
		%TODO: why am I limiting myself to 2Mb?
		numBytes	= min(numBytes, 1024*1024*2);

		array	= zeros(1,numBytes,'int8');
		buffer	= java.nio.ByteBuffer.wrap(array);

		try
			len		= sockChannel.read(buffer);
		catch
			s	= lasterror;
			channelErrMsg('channelRead:badHeapRead','could not read data');
			sockChannel.close();
			rethrow(s);
		end
	else

		totalBytes	= 0;

		array	= zeros(1,numBytes,'int8');
		buffer	= java.nio.ByteBuffer.wrap(array);
		tic
		try
			% NOTE: this is dangerous, you do not really want to do this.
			% I am not sure why I even bothered to put this in here.
			% TODO: remove this or set a timeout to read numBytes.
			while totalBytes < numBytes
				len		= sockChannel.read(buffer);
				if len > 0
					totalBytes	= totalBytes + len;
					%fprintf(1,'Read %.0f bytes @%s (sec) \n', double(len), toc);
				end
			end
		catch
			s	= lasterror;
			channelErrMsg('channelRead:badHeapRead','could not read data');
			sockChannel.close();
			rethrow(s);
		end
	end

	return;
end


classdef MimLocalModelCache < CoreBaseClass

    properties (Access = private)
        Controller
        ModelDictionary
    end

    methods
        function obj = MimLocalModelCache(controller)
            obj.Controller = controller;
            obj.ModelDictionary = containers.Map;
        end

        function entry = getModelCacheEntry(obj, modelName)
            if ~obj.ModelDictionary.isKey(modelName)
                obj.ModelDictionary(modelName) = MimLocalModelCacheEntry([], [], obj.Controller, modelName);
            end
            entry = obj.ModelDictionary(modelName);
        end

        function clear(obj)
            obj.ModelDictionary = containers.Map();
        end
    end
end


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

% Last Modified by GUIDE v2.5 31-Jul-2020 13:47:17

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

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

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

    populateGUI(handles, lvdData);

    % Update handles structure
    guidata(hObject, handles);

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

function populateGUI(handles, lvdData)
    [powerSinkListBoxStr, powerSinks] = lvdData.launchVehicle.getPowerSinksListBoxStr();
    set(handles.sinkListBox,'String',powerSinkListBoxStr);
    set(handles.sinkListBox,'Value',1);

    numPowerSinks = length(powerSinks);
    if(numPowerSinks <= 0)
        handles.removeSinkButton.Enable = 'off';
    end

% --- Outputs from this function are returned to the command line.
function varargout = lvd_EditElectricalPowerSinksGUI_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
        close(handles.lvd_EditElectricalPowerSinksGUI);
    end

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

% --- Executes on selection change in sinkListBox.
function sinkListBox_Callback(hObject, eventdata, handles)
% hObject    handle to sinkListBox (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 sinkListBox contents as cell array
%        contents{get(hObject,'Value')} returns selected item from sinkListBox
    if(strcmpi(get(handles.lvd_EditElectricalPowerSinksGUI,'SelectionType'),'open'))
        lvdData = getappdata(handles.lvd_EditElectricalPowerSinksGUI,'lvdData');
        lv = lvdData.launchVehicle;

        selPowerSink = get(handles.sinkListBox,'Value');
        powerSink = lv.getPowerSinkForInd(selPowerSink);

        stageState = getStageStateForPowerState(powerSink, lvdData);
        oldSinkState = stageState.getStateForPowerSink(powerSink);
        stageState.removePowerSinkStateForPowerState(powerSink);

        powerSink.openEditDialog();

        stageState = getStageStateForPowerState(powerSink, lvdData);
        newPowerSinkState = powerSink.createDefaultInitialState(stageState);

        if(not(isempty(oldSinkState)))
            newPowerSinkState.setActiveState(oldSinkState.getActiveState());
        end
        stageState.addPowerSinkState(newPowerSinkState);

        set(handles.sinkListBox,'String',lvdData.launchVehicle.getPowerSinksListBoxStr());
    end

function stageState = getStageStateForPowerState(powerSink, lvdData)
        stage = powerSink.stage;
        stageStates = lvdData.initStateModel.stageStates;
        stageStateInd = find([stageStates.stage] == stage,1,'first');
        stageState = stageStates(stageStateInd);

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

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

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

    sinkListBoxStr = LaunchVehiclePowerSinkEnum.getListBoxStr();
    [Selection,ok] = listdlgARH('ListString', sinkListBoxStr, ...
                                'SelectionMode','single', ...
                                'Name', 'New Sink Type', ...
                                'PromptString','Select type of new sink:', ...
                                'ListSize',[300,300]);

	if(ok == 1)
        initStage = lvdData.launchVehicle.getStageForInd(1);

        sinkEnum = LaunchVehiclePowerSinkEnum.getEnumForListboxStr(sinkListBoxStr{Selection});
        switch sinkEnum
            case LaunchVehiclePowerSinkEnum.Simple
                powerSink = LaunchVehicleSimplePwrSink(initStage);

            otherwise
                error('Unknown Power Sink Type: %s', class(sinkEnum))
        end

        useTF = powerSink.openEditDialog();

        if(useTF)
            stageStates = lvdData.initStateModel.stageStates;
            stageStateInd = find([stageStates.stage] == powerSink.stage,1,'first');
            stageState = stageStates(stageStateInd);

            newSinkState = powerSink.createDefaultInitialState(stageState);
            stageState.addPowerSinkState(newSinkState);

            set(handles.sinkListBox,'String',lvdData.launchVehicle.getPowerSinksListBoxStr());

            handles.removeSinkButton.Enable = 'on';
        end
	end

% --- Executes on button press in removeSinkButton.
function removeSinkButton_Callback(hObject, eventdata, handles)
% hObject    handle to removeSinkButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    lvdData = getappdata(handles.lvd_EditElectricalPowerSinksGUI,'lvdData');
    lv = lvdData.launchVehicle;

    selPowerSink = get(handles.sinkListBox,'Value');
    powerSink = lv.getPowerSinkForInd(selPowerSink);

    tf = powerSink.isInUse();

    if(tf == false)
        stage = powerSink.getAttachedStage();

        stageStates = lvdData.initStateModel.stageStates;
        stageStateInd = find([stageStates.stage] == stage,1,'first');
        stageState = stageStates(stageStateInd);

        stageState.removePowerSinkStateForPowerState(powerSink);

        stage.removePwrSink(powerSink);

        [listBoxStr, powerSinks] = lvdData.launchVehicle.getPowerSinksListBoxStr();
        set(handles.sinkListBox,'String',listBoxStr);

        numPowerSinks = length(powerSinks);
        if(selPowerSink > numPowerSinks)
            set(handles.sinkListBox,'Value',numPowerSinks);
        end

        if(numPowerSinks <= 0)
            set(handles.sinkListBox,'Value',1);

            handles.removeSinkButton.Enable = 'off';
        end
    else
        warndlg(sprintf('Could not delete the electical power sink "%s" because it is in use as part of an event termination condition, event action, objective function, or constraint.  Remove the dependencies before attempting to delete the electical power sink.', powerSink.getName()),'Cannot Delete Power Sink','modal');
    end

% --------------------------------------------------------------------
function copySinkMenu_Callback(hObject, eventdata, handles)
% hObject    handle to copySinkMenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    lvdData = getappdata(handles.lvd_EditElectricalPowerSinksGUI,'lvdData');
    lv = lvdData.launchVehicle;

    selPowerSink = get(handles.sinkListBox,'Value');
    powerSink = lv.getPowerSinkForInd(selPowerSink);

    newPowerSink = powerSink.copy();
    initStage = newPowerSink.getAttachedStage();

	initStage.addPwrSink(newPowerSink);

    stageStates = lvdData.initStateModel.stageStates;
    stageStateInd = find([stageStates.stage] == initStage,1,'first');
    stageState = stageStates(stageStateInd);

    newSinkState = powerSink.createDefaultInitialState(stageState);
    stageState.addPowerSinkState(newSinkState);

    set(handles.sinkListBox,'String',lvdData.launchVehicle.getPowerSinksListBoxStr());

    handles.removeSinkButton.Enable = 'on';

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

% --- Executes on key press with focus on lvd_EditElectricalPowerSinksGUI or any of its controls.
function lvd_EditElectricalPowerSinksGUI_WindowKeyPressFcn(hObject, eventdata, handles)
% hObject    handle to lvd_EditElectricalPowerSinksGUI (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'
            uiresume(handles.lvd_EditElectricalPowerSinksGUI);
        case 'enter'
            uiresume(handles.lvd_EditElectricalPowerSinksGUI);
        case 'escape'
            uiresume(handles.lvd_EditElectricalPowerSinksGUI);
    end


% OtTableNew Connect to an Omnitrans table.
%
% Usage:
%    htable = OtTableNew()
% or:
%    htable = OtTableNew(<path to .db file>)
%    This form includes a call to OtTableSetName()
%
% To release a table handle, call OtTableFree().

% OtMatlab: Matlab interface to the Omnitrans transport planning software

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

% All rights reserved.

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

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

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

% 2006-02-28 Created (Johan Meijdam, VORtech)

function htable = OtTableNew(dbpath)
   if nargin == 1
      htable = Ot('table', dbpath);
   else
      htable = Ot('table');
   end
end


function data_dir = GetNestedDataDir()
data_dir = 'C:\Janelia2015\datasets';
end


% eeglabexefolder - return the exe folder for EEGLAB. This function is only
%                   relevant for the compiled version of EEGLAB.
%
% Author: Arnaud Delorme, SCCN & CERCO, CNRS, 2008-

% Copyright (C) 15 Feb 2002 Arnaud Delorme, Salk Institute, arno@salk.edu
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

function str = eeglabexefolder;

str = ctfroot;
inds = find(str == filesep);
str = str(1:inds(end)-1);


cur_dir = pwd;
cd(fileparts(mfilename('fullpath')));

try
    fprintf('Downloading model_VGG16...\n');
    urlwrite('https://onedrive.live.com/download?resid=36FEC490FBC32F1A!114&authkey=!AE8uV9B07dREbhM&ithint=file%2czip', ...
        'model_VGG16.zip');

    fprintf('Unzipping...\n');
    unzip('model_VGG16.zip', '..');

    fprintf('Done.\n');
    delete('model_VGG16.zip');
catch
    fprintf('Error in downloading, please try links in README.md https://github.com/ShaoqingRen/faster_rcnn');
end

cd(cur_dir);


% test_this.m is a function-file test case.
function test_this


classdef NoDirectiveChanged < MBeautifier.DirectiveChange
    methods
        function obj = NoDirectiveChanged()
            obj@MBeautifier.DirectiveChange(MBeautifier.DirectiveChangeType.NONE);
        end
    end
end


%--- help for load_data ---
%
%  INTERNAL FUNCTION
%
%
%    Other functions named load_data
%
%       dsge/load_data    generic/load_data
%


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

%% -*- texinfo -*-
%% @defun  python_env_is_cygwin_like (pyexec)
%% Check if Python @var{pyexec} is running in a Cygwin-like POSIX environment,
%% such as Cygwin or MSYS2.  The result is memoized to speed up subsequent
%% calls.
%%
%% @seealso{cygpath}
%% @end defun

function r = python_env_is_cygwin_like (pyexec)
  persistent python_env_is_cygwin_like_memo

  if ~isempty (python_env_is_cygwin_like_memo)
    r = python_env_is_cygwin_like_memo;
    return
  end

  if ispc ()
    if system ('where /q cygpath') ~= 0
      r = false;
      python_env_is_cygwin_like_memo = r;
      return
    end

    [status, out] = system ([pyexec ' -c "import os; print(os.name)"']);
    if status ~= 0
      error ('python_env_is_cygwin_like: %s exited with status %d', ...
             pyexec, status);
    end
    r = ~isempty (regexp (out, 'posix', 'match'));
    python_env_is_cygwin_like_memo = r;
  else
    r = false;
    python_env_is_cygwin_like_memo = r;
  end
end


function result = mergecellstruct(result)

% MERGECELLSTRUCT is a helper function for FT_TEST

if iscell(result)
  if numel(result)>1
    result = appendstruct(result{:});
  else
    result = result{1};
  end
end


function dep = cfg_vout_mkdir(job)

% Define virtual outputs for cfg_run_mkdir. The directory name can either
% be assigned to a cfg_files directory input or to a 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_mkdir.m 1716 2008-05-23 08:18:45Z volkmar $

rev = '$Rev: 1716 $'; %#ok
dep            = cfg_dep;
if isa(job.name, 'cfg_dep')
    dep.sname  = sprintf('Make Directory');
else
    dep.sname  = sprintf('Make Directory ''%s''', job.name);
end;
dep.src_output = substruct('.','dir');
dep.tgt_spec   = cfg_findspec({{'filter','dir', 'strtype','e'}});


%
% Load library from a file,
% as specified in the function defaultps
%
function lib = loadlib()
    ps = defaultps;
    load(ps.libname,'lib');
    assert(isa(lib,'Library'));
end


% CVX: Internal functions and scripts.
%    This directory contains code that is meant for internal use by
%    the CVX system itself. Documentation of the functions in this
%    directory is more sparse and not intended for end users.

% Copyright 2010 Michael C. Grant and Stephen P. Boyd.
% See the file COPYING.txt for full copyright information.
% The command 'cvx_where' will show where this file is located.


function lyrics(varargin)

	query = reshape(transpose([strvcat(varargin{:}),[repmat('+',size(strvcat(varargin{:}),1)-1,1);' ']]),1,[]);

	url = ['''http://search.letssingit.com/cgi-exe/am.cgi?a=search&l=archive&s=',query,''''];

	url(url==' ') = [];

	eval(['web ', url ,' -browser'])

end


function hdrv = hdrvclose(hdrv)
%
%        hdrv = hdrvclose(hdrv)
%
%
%        Input:
%           -hdrv: a HDR video structure
%
%        Output:
%           -hdrv: a HDR video structure
%
%        This function closes a video stream (hdrv) for reading frames
%
%     Copyright (C) 2013-17  Francesco Banterle
%
%     This program is free software: you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation, either version 3 of the License, or
%     (at your option) any later version.
%
%     This program is distributed in the hope that it will be useful,
%     but WITHOUT ANY WARRANTY; without even the implied warranty of
%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%     GNU General Public License for more details.
%
%     You should have received a copy of the GNU General Public License
%     along with this program.  If not, see <http://www.gnu.org/licenses/>.
%

if(hdrv.streamOpen == 1)
    switch hdrv.type
        case 'TYPE_HDR_VIDEO'
            if(hdrv.permission == 'w')
                if(~isempty(hdrv.streamTMO))
                    close(hdrv.streamTMO)
                end

                if(~isempty(hdrv.streamR))
                    close(hdrv.streamR)
                end
            end
    end

    hdrv.streamOpen = 0;
end

end


function out = cfg_run_named_dir(job)

% Return selected dirs as separate output arguments.
%
% 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_run_named_dir.m 1716 2008-05-23 08:18:45Z volkmar $

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

out.dirs = job.dirs;


function varargout = progress(varargin)

% This function is a backward compatibility wrapper. It allows existing
% MATLAB scripts that do not use the new FieldTrip ft_xxx function naming
% scheme to work with recent versions of the FieldTrip toolbox.
%
% Please look in ft_xxx for the help of the function that you are looking
% for, where xxx is the name of the function that you were looking for.

% Copyright (C) 2009, Robert Oostenveld

prefix    = 'ft_';
funname   = mfilename;
warning([upper(mfilename) ' is only a compatibility wrapper, which will soon be removed. Please instead call ' upper(prefix) upper(funname) '.']);
funhandle = str2func([prefix funname]);
[varargout{1:nargout}] = funhandle(varargin{:});


classdef MimPlugin < handle
    % MimPlugin. Base class for a Plugin used by MIM.
    %
    %     Plugins are classes you create to run your own routines from the
    %     MIM toolkit. When you create a plugin, it can automatically
    %     appear as a button in compatible guis, and is available to scripts and other
    %     plugins which use the MIM toolkit. The framework automatically
    %     handles result caching, dependency tracking and preview thumbnail
    %     generation.
    %
    %     To run a plugin from your own code, first create a suitable
    %     MimMain object, usually by using a specific application such as
    %     PTKMain for PTK. Then call CreateDatasetFromInfo() to create a MimDataset for the image files
    %     you wish to run the plugin with. Then call GetResult() on this dataset
    %     interface to run the plugin or fetch a previously cached result.
    %
    %     Example
    %     -------
    %     Replace <image path> and <filenames> with the path and filenames
    %     to your image data, and MyPluginName with the name of the plugin to
    %     run.
    %
    %         image_info = PTKImageInfo( <image path>, <filenames>, [], [], [], []);
    %         ptk = PTKMain();
    %         dataset = ptk.CreateDatasetFromInfo(image_info);
    %         results = dataset.GetResult('MyPluginName');
    %
    %
    %
    %     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.
    %

    % You must set each of these properties in your plugin class
    properties (Abstract = true)
        % Should normally be set to true.
        % Specifies if the results of this plugin can be cached on disk. If you
        % set this to false, the results will never be cached and the plugin
        % will have to be run each time its result is requested. This will save
        % disk space but could substantially increase execution time.
        AllowResultsToBeCached

        % Should normally be set to false.
        % Set to true if you want to force the plugin to be run every time its
        % result is requested, ignoring any results in the disk cache. One
        % reason to set this to true is during plugin development, where you are
        % modifying the code and want to test your changes.
        AlwaysRunPlugin

        % Should normally be set to 'ReplaceOverlay'.
        % This specifies how the plugin result will be displayed to the user
        % when using the gui. Allowable values are:
        % 'ReplaceOverlay' - the result is displayed as an image overlay
        % 'ReplaceImage'   - the result replaces the image. Normally you would
        %                    only do this when creating a new image context
        %                    (i.e. region of interest)
        % 'DoNothing'      - do not display any results. This option is
        %                    appropriate if your plugin displays its results in
        %                    its own window
        PluginType

        % Set to force the plugin to appear in a particular panel name in the gui.
        % If you leave blank, the panel name will be the subdirectory under
        % Plugins where the plugin is found
        Category

        % Should normally be set to false.
        % If true, this plugin will not have a button in the gui window
        HidePluginInDisplay

        % Should normally be set to 6.
        % The width (in units defined by the gui) of the button for this plugin
        ButtonWidth

        % Should normally be set to 2.
        % The height (in units defined by the gui) of the button for this plugin
        ButtonHeight

        % The text to appear in the gui when the user hovers the mouse over the
        % button for this plugin
        ToolTip

        % The text to appear on the button in the gui. Also used in reporting of
        % progress, so the text should make sense when displayed as "Calculating
        % <button text>", e.g. 'Airways by Lobe' will display as "Calculating
        % Airways by Lobe" in the progress dialog. Note that HTML tags are
        % allowed - use <BR> for a newline in the button text
        ButtonText

        % Should normaly be set to true.
        % Specifies in a preview thumnail should be generated from the plugin
        % result after the plugin has been run. This thumbnail will be displaued
        % in the button itself. Set this to false if the plugin does not
        % generate an image.
        GeneratePreview

        % Should normally be set to false.
        % Specifies whether a MIP will be used to generate the preview
        % thumbnail. Set to true for small structures such as airways which are
        % best visualised with the "flatten" plugin.
        FlattenPreviewImage
    end

    % Optional properties
    %   PluginInterfaceVersion - specifies the version of the plugin interface
    %   that your plugin implements

    methods (Abstract, Static)

        % Generates the results for this plugin.
        % The results can be a PTKImage or
        % any kind of Matlab structure. Plugins should generally return an
        % output image as their result, but some plugins (such as PTKAirways)
        % generate information which cannot be stored in a simple image. For
        % these types of plugin, you should return a custom data structure
        % containing your results, and then override the function
        % GenerateImageFromResults below to produce an illustrative output
        % image.
        results = RunPlugin(dataset, context, reporting)

    end

    methods (Static)

        function results = GenerateImageFromResults(results, ~, ~)
            % Generates a results image from the results returned by RunPlugin.
            % If the result is itself an image, there is no need to override this
            % function as this image will be returned. If the result is a data
            % structure, this function should generate an illustrative output image
            % based on the results. For example, the PTKAirways plugin returns a
            % heirarchical data structure describing the airway tree. This functin
            % is then used to turn the structure into an image.
        end

        function result = GetEditedResult(result, edited_result, ~)
            % Modifies a plugin result based on manual editing of the output image.
            % The default behaviour is that the edited result replaces the
            % result, provided they are both of the same type.
            % However, plugins may choose to modify the original result based on
            % an edited result, in which case the plugin must override this
            % method and define its desired behaviour.
            if isempty(result) || strcmp(class(result), class(edited_result))
                result = edited_result;
            end
        end

        function result = GenerateDefaultEditedResultFollowingFailure(dataset, context, reporting)
            % Defines the behaviour if the plugin execution fails with an
            % exception. If this method returns an empty result, then the
            % exception will be rethrown and propagated down to the caller,
            % which is the default behaviour. A plugin may override this
            % method and return a default edited result, in which case the
            % user will be prompted if they wish to accept the edited
            % result.
            %
            result = [];
        end

        function enabled = IsEnabled(mim_gui_app)
            enabled = true;
        end

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


classdef MimSegmentationButton < GemButton
    % MimSegmentationButton. 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.
    %
    %     MimSegmentationButton is used to build a button control representing a plugin,
    %     with a backgroud image preview of the segmentation
    %
    %
    %     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
        RootButtonWidth = 20;
        RootButtonHeight = 20;
    end

    properties (Access = protected)
        LoadManualSegmentationCallback
    end

    methods
        function obj = MimSegmentationButton(parent, name, load_manual_segmentation_callback)
            tooltip_string = ['<HTML>' name];

            button_text = ['<HTML><P ALIGN = RIGHT>', name];
            tag = name;
            obj = obj@GemButton(parent, button_text, tooltip_string, tag, []);
            obj.LoadManualSegmentationCallback = load_manual_segmentation_callback;
            obj.Callback = @obj.ButtonPressed;

            % Calculate the button size, based on plugin properties
            obj.ButtonWidth = 6*obj.RootButtonWidth;
            obj.ButtonHeight = 2*obj.RootButtonHeight;
        end

        function AddPreviewImage(obj, preview_fetcher, window, level)
            if ~isempty(preview_fetcher)
                preview_image = preview_fetcher.GetPluginPreview(obj.Tag);
            else
                preview_image = [];
            end
            if isempty(obj.Position)
                button_size = [obj.ButtonWidth, obj.ButtonHeight];
            else
                button_size = obj.Position(3:4);
            end
            preview_image_raw = MimImageUtilities.GetButtonImage(preview_image, button_size(1), button_size(2), window, level, 1, obj.BackgroundColour, obj.UnSelectedColour);
            obj.ChangeImage(preview_image_raw);
        end

        function height = GetRequestedHeight(obj, width)
            % Returns a value for the height of the object

            height = obj.ButtonHeight;
        end

        function ButtonPressed(obj, name)
            obj.LoadManualSegmentationCallback(name);
        end

    end
end


function str = showdetail(item)

% function str = showdetail(item)
% Display details for a cfg_choice and all of its options.
%
% 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: showdetail.m 4867 2012-08-30 13:04:51Z volkmar $

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

str = showdetail(item.cfg_item);
str{end+1} = 'Class  : cfg_choice';
str{end+1} = ['Set one of the options listed as a struct with a ' ...
              'single field:'];
% Display detailed help for each cfg_choice value item
tags = tagnames(item, true);
for k = 1:numel(tags)
    str{end+1} = sprintf('.%s', tags{k});
end;


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

% Last Modified by GUIDE v2.5 13-Dec-2013 17:48:09

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

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

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

    hRtsMainGUI = varargin{1};
    vesselGUID = varargin{2};
    handles.mainGUI = hRtsMainGUI;
    handles.vesselGUID = vesselGUID;

    rts_initRTSDynPanel(hRtsMainGUI, hObject, handles.clockLabel, handles.connStatusLabel, vesselGUID,...
                        handles.attPointingTextDispLabel, handles.attRatesTextDispLabel, handles.attCmdTextDispLabel, handles.attDispAxes,...
                        handles.actStatusTextDispLabel, handles.rwaInfoUitable, handles.attDerivedTextDispLabel);

    % Update handles structure
    guidata(hObject, handles);

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

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

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

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


function varargout = BrowserGUI(varargin)
%BrowserGUI GUI code for OlyDat Browser
%
%   See also OlyDat.Browser.

% Begin initialization code - DO NOT EDIT
gui_Singleton = 0;
if ismac
    gui_Name = 'BrowserGUI_Mac';
else
    gui_Name = 'BrowserGUI_PC'; % use this for both PC and Unix
end
gui_State = struct('gui_Name',       gui_Name, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @browserGUI_OpeningFcn, ...
                   'gui_OutputFcn',  @browserGUI_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

% browserGUI = BrowserGUI(browserObj)
function browserGUI_OpeningFcn(hObject, eventdata, handles, varargin) %#ok<*INUSL>
handles.output = hObject;
handles.browser = varargin{1};
guidata(hObject, handles);
centerGUI(hObject);

function varargout = browserGUI_OutputFcn(hObject, eventdata, handles)
varargout{1} = handles.output;

function pumAuxVar_Callback(hObject, eventdata, handles) %#ok<*DEFNU>
handles.browser.auxVarChanged();

function lbBStats_Callback(hObject, eventdata, handles)
handles.browser.statChanged();

function pumBStats_Callback(hObject, eventdata, handles)
handles.browser.statChanged();

function lbGroupVars_Callback(hObject, eventdata, handles)
handles.browser.groupOrGroup2SelectionChanged();

function pumGroup_Callback(hObject, eventdata, handles)
handles.browser.groupChanged();

function lbGroupVars2_Callback(hObject, eventdata, handles)
handles.browser.groupOrGroup2SelectionChanged();

function pumGroup2_Callback(hObject, eventdata, handles)
handles.browser.group2Changed();

function pbUseAllGroupVals_Callback(hObject, eventdata, handles)
strs = get(handles.lbGroupVars,'String');
set(handles.lbGroupVars,'Value',1:numel(strs));
handles.browser.groupOrGroup2SelectionChanged();

function pbUseAllGroupVals2_Callback(hObject, eventdata, handles)
strs = get(handles.lbGroupVars2,'String');
set(handles.lbGroupVars2,'Value',1:numel(strs));
handles.browser.groupOrGroup2SelectionChanged();

function pbPlot_Callback(hObject, eventdata, handles)
handles.browser.plot();

function pumPlotType_Callback(hObject, eventdata, handles)
handles.browser.newPlot();

function cbRemoveExp_Callback(hObject, eventdata, handles)
handles.browser.setRemoveExp(get(hObject,'Value'));

function pbCompare_Callback(hObject, eventdata, handles)
handles.browser.addComparePlot();

function figure1_CloseRequestFcn(hObject, eventdata, handles)
handles.browser.browserGUIWantsToClose();

function pbEnterCurationInfo_Callback(hObject, eventdata, handles)
handles.browser.curationOpenCurationInfoEntry();

function pbNextExpDetail_Callback(hObject, eventdata, handles)
handles.browser.nextExpDetail;

function pbPrevExpDetail_Callback(hObject, eventdata, handles)
handles.browser.prevExpDetail;

function pbCreateCustomGroup_Callback(hObject, eventdata, handles)
grpname = inputdlg('Specify a name for the group');
if ~isempty(grpname)
    grpname = grpname{1};
    handles.browser.createCustomGroup(grpname);
end

function pbLineReport_Callback(hObject, eventdata, handles)
handles.browser.openLineReport();

function pbExpDetail_Callback(hObject, eventdata, handles)
handles.browser.openExperimentDetailPlots();

function pbFileSystem_Callback(hObject, eventdata, handles)
handles.browser.openExperimentFileSystem();

% MENU
function mnuCuration_Load_Callback(hObject, eventdata, handles)
handles.browser.curationLoadCurationFile();

function mnuCuration_Append_Callback(hObject, eventdata, handles)
handles.browser.curationAppendCurationDataToFile();

function mnuCuration_Write_Callback(hObject, eventdata, handles)
handles.browser.curationWriteCurationDataToNewFile();

function mnuCuration_OpenCurationManager_Callback(hObject, eventdata, handles)
handles.browser.curationOpenCurationManager();

function pbExport_Callback(hObject, eventdata, handles)
handles.browser.exportPlot();


function y = sdpfun(varargin)
%SDPFUN Obsolete - changed to blackbox

y = blackbox(varargin{:});


function cell2file(file,str,flag)
% write cellstring to file

if nargin == 2, flag = 'w'; end
fid = efopen(file,flag);

write_cell(fid,str);
fclose(fid);


function fn = fieldnames(item)

% function fn = fieldnames(item)
% Return a list of all (inherited and non-inherited) field names.
%
% 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: fieldnames.m 4867 2012-08-30 13:04:51Z volkmar $

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

fn1 = fieldnames(item.cfg_item);
fn2 = mysubs_fields;

fn = [fn1(:); fn2(:)]';