function [ params ] = tapas_BLT_runIntroTrain( params )
% tapas_BLT_runIntroTrain Presents written instructions and logs the event
%
% About:
%   Coded by F.Petzschner 19. April 2017
%	Last change: F.Petzschner 19. April 2017

for i = 1:params.nIntroTrain

    Screen('DrawTexture', params.screen.window, params.text.IntroTrain{i}, [], params.screen.fit, 0);
    Screen('Flip', params.screen.window);
    wait2_escapeOption(params.dur.showIntroScreen, params);
    detecting = 1;

    if i == params.nIntroTrain
        wait2(3000);
        break
    else
        while detecting
            keyCode = 0;
            keyCode = detectkey(params);
            if keyCode == params.keys.two
                    Screen('DrawTexture', params.screen.window, params.text.imgbreak, [], params.screen.fit, 0);
                    Screen('Flip', params.screen.window);
                    wait2(1000);
                    keyCode2 = detectkey(params);
                    if keyCode2 == params.keys.one
                       detecting = 0;
                    end
            elseif keyCode == params.keys.one
                detecting = 0;
            end
        end
    end

    fprintf(['Intro Training Slide...',num2str(i)])
end


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

% Last Modified by GUIDE v2.5 28-May-2014 22:09:41

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

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

% Update handles structure
guidata(hObject, handles);

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

clc;
lrs_load_conf;

set(hObject,'Name','Video editor','NumberTitle','off');

set(handles.edit_input_video,'string',fullfile(lrs_conf.lrs_dir,'dataset','demo.avi'));
set(handles.edit_output_video,'string',fullfile(lrs_conf.lrs_dir,'dataset','demo_out.avi'));

img = imread(fullfile(lrs_conf.lrs_dir,'figs','no-available-image.png'));
imshow(img,'parent',handles.axes_input);

% --- Outputs from this function are returned to the command line.
function varargout = main_edit_video_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 edit_input_video_Callback(hObject, eventdata, handles)
% hObject    handle to edit_input_video (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_input_video as text
%        str2double(get(hObject,'String')) returns contents of edit_input_video as a double

% --- Executes during object creation, after setting all properties.
function edit_input_video_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_input_video (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_show_input_video.
function pushbutton_show_input_video_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton_show_input_video (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global runningFlag;
if(runningFlag == false)
    inputVideoHandle = handles.edit_input_video;
    axesInputHandle = handles.axes_input;
    textLogMessageHandle = handles.text_log_message;
    gui_show_video(inputVideoHandle,axesInputHandle,textLogMessageHandle);
else
    disp('Stop video first!');
end

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

% --- Executes on button press in pushbutton_select_input.
function pushbutton_select_input_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton_select_input (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
lrs_load_conf;
[filename, pathname] = uigetfile({'*.avi';'*.mpg';'*.mp4';'*.*'},'File Selector',fullfile(lrs_conf.lrs_dir,'dataset'));
if(~isequal(filename,0) && ~isequal(pathname,0))
  inputVideoHandle = handles.edit_input_video;
  fullpath = fullfile(pathname, filename);
  set(inputVideoHandle,'String',fullpath);
end

% --- Executes on button press in pushbutton_stop.
function pushbutton_stop_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton_stop (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global stopFlag;
stopFlag = true;

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

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

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

% --- Executes during object creation, after setting all properties.
function edit_resize_factor_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_resize_factor (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 checkbox_resize.
function checkbox_resize_Callback(hObject, eventdata, handles)
% hObject    handle to checkbox_resize (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 checkbox_resize

% --- Executes on button press in checkbox_crop.
function checkbox_crop_Callback(hObject, eventdata, handles)
% hObject    handle to checkbox_crop (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 checkbox_crop

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

inputVideoHandle = handles.edit_input_video;
inputFileName = get(inputVideoHandle,'String');
disp(['Input video: ' inputFileName]);

outputVideoHandle = handles.edit_output_video;
outputFileName = get(outputVideoHandle,'String');
disp(['Output video: ' outputFileName]);

if exist(inputFileName, 'file')
  displog('Loading video...');
  video_struct = load_video_file(inputFileName);
  video = convert_video_to_4d(video_struct); % show_4dvideo(video);
  video_aux = video;

  checkboxCropHandle = handles.checkbox_crop;
  if (get(checkboxCropHandle,'Value') == get(checkboxCropHandle,'Max'))
    displog('Cropping video...');

    r = str2double(get(handles.edit_crop_begin,'String'));
    s = str2double(get(handles.edit_crop_end,'String'));

    disp(['Begin: ', num2str(r)]);
    disp(['End: ', num2str(s)]);

    [video_aux] = crop_4dvideo(video,r,s);
  end

  checkboxResizeHandle = handles.checkbox_resize;
  if (get(checkboxResizeHandle,'Value') == get(checkboxResizeHandle,'Max'))
    displog('Resizing video...');

    f = str2double(get(handles.edit_resize_factor,'String'));

    disp(['Factor: ', num2str(f)]);

    [video_aux] = resize_4dvideo(video_aux,f);
  end

  displog('Saving video...');
  convert_video4d_to_avi(video_aux,outputFileName);
  displog('OK');
else
  % File does not exist.
  warningMessage = sprintf('Warning: file does not exist:\n%s', inputFileName);
  uiwait(msgbox(warningMessage));
end

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

% --- Executes during object creation, after setting all properties.
function edit_output_video_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_output_video (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_show_output_video.
function pushbutton_show_output_video_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton_show_output_video (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global runningFlag;
if(runningFlag == false)
    gui_show_video(handles.edit_output_video,handles.axes_input,handles.text_log_message);
else
    disp('Stop video first!');
end


function el = export_structure_set_ROI_sequence(args)
%"export_structure_set_ROI_sequence"
%   Subfunction to handle structure_set_ROI sequences within the
%   structure_set module.  Uses the same layout and principle as the parent
%   function.
%
%   This function takes a CERR structure element and the index of that
%   element within the planC.structures array.
%
%JRA 06/23/06
%NAV 07/19/16 updated to dcm4che3
%   replaced ml2dcm_Element to data2dcmElement
%
%Usage:
%   @export_structure_set_ROI_sequence(args)
%
% 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/>.

%Init output element to empty.
el = [];

%Unpack input data.
tag         = args.tag;
structS     = args.data{1};
index       = args.data{2};
template    = args.template;

switch tag
    case 805699618  %3006,0020  ROI Number
        data = uint32(index);
       % el = template.get(tag);
        el = data2dcmElement(data, tag);

    case 805699620  %3006,0024  Referenced Frame of Reference UID
        UID = structS.Frame_Of_Reference_UID;
        el = data2dcmElement(UID, tag);

    case 805699622  %3006,0026  ROI Name
        data = structS.structureName;
        el = data2dcmElement(data, tag);

    case 805699624  %3006,0028  ROI Description
        %Currently unsupported.

    case 805699628  %3006,002C  ROI Volume
        %Currently unsupported.

    case 805699638  %3006,0036  ROI Generation Algorithm
       % el = template.get(tag);
        %el = org.dcm4che3.data.Attributes;
        %el.setString(tag, template.getVR(tag), template.getString(tag));
        data = structS.roiGenerationAlgorithm;
        el = data2dcmElement(data, tag);

    case 805699640  %3006,0038  ROI Generation Description
        data = structS.roiGenerationDescription;
        el = data2dcmElement(data, tag);

    otherwise
        warning(['No methods exist to populate DICOM structure_set module''s structure_set_ROI sequence field: ' dec2hex(tag,8) '.']);
end


function cmdString = tapas_physio_create_spm_toolbox_link(pathPhysIO)
% Creates a symbolik link of PhysIO/code folder to subfolder SPM/toolbox/PhysIO
% to make toolbox visible to SPM Batch editor
%
%   tapas_physio_create_spm_toolbox_link()
%
% IN
%
% OUT
%   cmdString   string of executed command
%
% EXAMPLE
%   tapas_physio_create_spm_toolbox_link
%
%   See also

% Author: Lars Kasper
% Created: 2018-02-17
% Copyright (C) 2018 TNU, Institute for Biomedical Engineering,
%                    University of Zurich and ETH Zurich.
%
% This file is part of the TAPAS PhysIO Toolbox, which is released under the terms of the GNU General Public
% License (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL
% (either version 3 or, at your option, any later version). For further details, see the file
% COPYING or <http://www.gnu.org/licenses/>.
%
cmdString = '';

if nargin < 1
    % 2x fileparts, because parent folder
    pathPhysIO = fileparts(fileparts(mfilename('fullpath')));
end

pathSpm = fileparts(which('spm'));

if isempty(pathSpm)
    warning('SPM folder not found. Could not create symbolic link to PhysIO Toolbox');
else
    pathLinkPhysIOSPM = fullfile(pathSpm, 'toolbox', 'PhysIO');
    if ~exist(pathLinkPhysIOSPM, 'dir')
        % Create Link or hard-copy folder, OS dependent
        if ispc
            % unfortunately, system link does not work for SPM, has to be
            % hard copy
            fprintf('Copying %s to %s, because symlink not sufficient on Windows...\n', pathPhysIO, pathLinkPhysIOSPM);
            cmdString = sprintf('copyfile(''%s'', ''%s'');',pathPhysIO, pathLinkPhysIOSPM);
            eval(cmdString);
            % linking indeed the other way around than in Linux/Mac
            % cmdString = sprintf('mklink /D %s %s', pathLinkPhysIOSPM, pathPhysIO);
        else %unix/Mac
            cmdString = sprintf('ln -s ''%s'' ''%s''', pathPhysIO, pathLinkPhysIOSPM);
            system(cmdString);
        end
    else
        warning('Destination spm/toolbox folder %s already found. Will not overwrite or re-link', pathLinkPhysIOSPM);
    end
end


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

% Last Modified by GUIDE v2.5 06-Aug-2020 15:23:10

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

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

    centerUIFigure(hObject);

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

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

    populateGUI(handles, action, lv);

    % Update handles structure
    guidata(hObject, handles);

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

function populateGUI(handles, action, lv)
    [powerSinkListStr, powerSinks] = lv.getPowerSinksListBoxStr();
    set(handles.refPwrCompCombo,'String',powerSinkListStr);

    if(not(isempty(action.sink)))
        ind = find(powerSinks == action.sink,1,'first');
    else
        ind = [];
    end

    if(not(isempty(ind)))
        set(handles.refPwrCompCombo,'Value',ind);
    end

    if(action.activeStateToSet)
        set(handles.stateCombo,'Value',1);
    else
        set(handles.stateCombo,'Value',2);
    end

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

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

        [~, powerSinks] = lv.getPowerSinksListBoxStr();
        ind = get(handles.refPwrCompCombo,'Value');
        action.sink = powerSinks(ind);

        contents = cellstr(get(handles.stateCombo,'String'));
        stateStr = contents{get(handles.stateCombo,'Value')};

        switch stateStr
            case 'Active'
                state = true;
            case 'Inactive'
                state = false;
            otherwise
                error('Invalid state string: %s', stateStr);
        end

        action.activeStateToSet = state;

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

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

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

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

% --- Executes during object creation, after setting all properties.
function refPwrCompCombo_CreateFcn(hObject, eventdata, handles)
% hObject    handle to refPwrCompCombo (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 selection change in stateCombo.
function stateCombo_Callback(hObject, eventdata, handles)
% hObject    handle to stateCombo (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 stateCombo contents as cell array
%        contents{get(hObject,'Value')} returns selected item from stateCombo

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

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

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


function varargout = ma_MissionNotesGUI(varargin)
% MA_MISSIONNOTESGUI MATLAB code for ma_MissionNotesGUI.fig
%      MA_MISSIONNOTESGUI, by itself, creates a new MA_MISSIONNOTESGUI or raises the existing
%      singleton*.
%
%      H = MA_MISSIONNOTESGUI returns the handle to a new MA_MISSIONNOTESGUI or the handle to
%      the existing singleton*.
%
%      MA_MISSIONNOTESGUI('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in MA_MISSIONNOTESGUI.M with the given input arguments.
%
%      MA_MISSIONNOTESGUI('Property','Value',...) creates a new MA_MISSIONNOTESGUI or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before ma_MissionNotesGUI_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to ma_MissionNotesGUI_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

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

% Last Modified by GUIDE v2.5 18-Jul-2015 20:44:51

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @ma_MissionNotesGUI_OpeningFcn, ...
                   'gui_OutputFcn',  @ma_MissionNotesGUI_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before ma_MissionNotesGUI is made visible.
function ma_MissionNotesGUI_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to ma_MissionNotesGUI (see VARARGIN)

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

% Update handles structure
guidata(hObject, handles);
handles.ma_MainGUI = varargin{1};
guidata(hObject, handles);

setupGui(handles);

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

function setupGui(handles)
    maData = getappdata(handles.ma_MainGUI,'ma_data');
    set(handles.missionNotesText,'String',maData.notes);

% --- Outputs from this function are returned to the command line.
function varargout = ma_MissionNotesGUI_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 missionNotesText_Callback(hObject, eventdata, handles)
% hObject    handle to missionNotesText (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 missionNotesText as text
%        str2double(get(hObject,'String')) returns contents of missionNotesText as a double

% --- Executes during object creation, after setting all properties.
function missionNotesText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to missionNotesText (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 saveCloseButton.
function saveCloseButton_Callback(hObject, eventdata, handles)
% hObject    handle to saveCloseButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    maData = getappdata(handles.ma_MainGUI,'ma_data');
    maData.notes = get(handles.missionNotesText,'String');
    setappdata(handles.ma_MainGUI,'ma_data',maData);

    close(handles.ma_MissionNotesGUI);


% PLUGIN_ASKINSTALL - install EEGLAB plugin from a GUI or command line
%                       call.
% Usage:
%  plugin_askinstall(pluginName, pluginFunc, force);
%
% Inputs:
%  pluginName - [string] name of the plugin
%  pluginFunc - [string] function belonging to the plugin
%  force       - [boolean] force install (even if already installed)
%
% Example:
%   Force install BVA-IO
%   plugin_askinstall('bva-io', [], true);

% Copyright (C) 2012- Arnaud Delorme
%
% This file is part of EEGLAB, see http://www.eeglab.org
% for the documentation and details.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are met:
%
% 1. Redistributions of source code must retain the above copyright notice,
% this list of conditions and the following disclaimer.
%
% 2. 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.
%
% 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 HOLDER 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.

function installRes = plugin_askinstall(pluginName, pluginFunc, forceInstall)

if nargin < 3, forceInstall = false; end

if nargin < 2 || ~exist(char(pluginFunc))

    if ~forceInstall
        db = dbstack;
        if length(db) > 2 && ~strcmpi(db(end).file, 'checkouteeglab.m')
            error([ 'Cannot find ' pluginName ' extension, use EEGLAB Extension Manager to install it' ]);
        end

        installRes = 0;

        % check is deactivated
        try, PLUGINLIST = evalin('base', 'PLUGINLIST'); catch, PLUGINLIST = []; end
        if ~isempty(PLUGINLIST) && isfield(PLUGINLIST, 'plugin')
            indPlugin = strmatch(lower(pluginName), lower({ PLUGINLIST.plugin }), 'exact');
            if ~isempty(indPlugin) && strcmpi(PLUGINLIST(indPlugin(1)).status, 'deactivated')
                res = questdlg2( [ pluginName ' extension is de-activated. Do you want to reactivate it now?' ], [ pluginName ' extension installation' ], 'No', 'Yes', 'Yes' );
                if strcmpi(res, 'no'), return, end
                plugin_reactivate(PLUGINLIST(indPlugin(1)).foldername);
                evalin('base', 'eeglab rebuild');
                installRes = 1;
                return;
            end
        end

        % check for installing
        res = questdlg2( [ pluginName ' extension is not installed. Do you want to download it now?' ], [ pluginName ' extension installation' ], 'No', 'Yes', 'Yes' );
    else
        res = 'yes';
    end

    if strcmpi(res, 'no'), return, end
    try
        plugins = plugin_getweb('plugin_install', []);
    catch
        error('Issue with retrieving statistics for extensions, maybe check your connection');
    end
    if isempty(plugins)
        error('Cannot download the extension. Please check your internet connection');
    end
    indPlugin = strmatch(lower(pluginName), lower({ plugins.name }), 'exact');
    if isempty(indPlugin)
        error([ pluginName ' extension not found' ]);
    end
    result = plugin_install(plugins(indPlugin(1)).zip, plugins(indPlugin(1)).name, plugins(indPlugin(1)).version, forceInstall);
    if result == 1, installRes = 1; end

    evalin('base', 'eeglab rebuild');
else
    installRes = 1;
end


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

% Last Modified by GUIDE v2.5 06-Feb-2008 22:52:28

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

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

% Update handles structure
guidata(hObject, handles);

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

% --- Outputs from this function are returned to the command line.
function varargout = HELP_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 full = fullpath(pth)
%
% full = fullpath(pth);
%
% Given a string specifying a path which may be an absolute path,
% or a path relative to the current directory, always return
% an absolute, full path string. Platform-independent.
%
% Ex: if the current directory is '/usr/me' and the pth string is
% 'Inplane/Original', will return '/usr/me/Inplane/Original'. But if the
% pth string is '/usr/someone_else', will return '/usr/someone_else'.
%
% ras, 11/2005.
% ras, 10/30/2006: deals w/ empty paths now.
if isempty(pth), full = pwd; return; end

if isunix
    % Check for the root file separator '/' for absolute paths
    if isequal(pth(1), filesep)
        full = pth;
    else
        full = fullfile(pwd, pth);
    end
elseif ispc
    % check if the drive colon is specified as 2nd char: e.g., 'C:\'
    if isequal(pth(2), ':')
        full = pth;
    else
        full = fullfile(pwd, pth);
    end
else
    % not unix-y (incl. mac) or pc -- ?
    msg = 'This computer not identified as PC, Mac OS X or Unix. ';
    msg = [msg 'Sorry, fullpath can''t work for this platform. '];
    msg = [msg 'Returning un-modified input path.'];
    warning(msg);
    full = pth;
end

return


function [cmds, errs, msgs] = gitSetBranch(repo, branch, preview, quiet)
cmds = {};

if ~exist('repo','var') || isempty(repo)
    repo = [pwd, '/'];
end
if ~exist('branch','var') || isempty(branch)
    branch = 'development';
end
if ~exist('preview','var')
    preview = false;
end
if ~exist('quiet','var') || isempty(quiet)
    quiet = 1;
end

currdir = pwd;

repoFull = filesepStandard_startup(repo,'full');
ii = 1;

cmds{ii,1} = sprintf('cd %s', repoFull); ii = ii+1;
cmds{ii,1} = sprintf('git checkout %s', branch); ii = ii+1;
cmds{ii,1} = sprintf('git pull'); ii = ii+1;

[errs, msgs] = exeShellCmds(cmds, preview, quiet);

% If requested branch was not checkout it was because it doesn't exist
% so we create it
branchnew = gitGetBranch(repo);
if ~strcmp(branchnew, branch)
    cmds{ii,1} = sprintf('git checkout -b %s', branch);
    [errs, msgs] = exeShellCmds(cmds, preview, quiet);
end

cd(currdir);


function log(logger,level,message,varargin)
% Writes a message to all log files (and possibly standard out and
% standard error).
% Inputs:
%   level: The logging level.  See the constants defined in the
%     class header.  Several constants can be combined by bit oring
%     them.

assert(logger.validate())

for ii=1:length(logger.fidlist)
    if bitand(logger.fidlevels(ii),level)
	fprintf(logger.fidlist(ii),message,varargin{:});
    end
end
for ii=1:length(logger.filenamefids)
    if bitand(logger.filenamelevels(ii),level)
	fprintf(logger.filenamefids(ii),message,varargin{:});
    end
end
end


function dispDoneGibbonCode

disp(['--- Done --- ',datestr(now)]);

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


function new_plugin = MimParseGuiPluginClass(plugin_name, plugin_class, suggested_category, default_category, default_mode, reporting)
    % MimParseGuiPluginClass. Part of the internal framework of the TD MIM Toolkit.
    %
    %     You should not use this class within your own code. It is intended to
    %     be used internally within the framework of the TD MIM Toolkit.
    %
    %     Fetches information about any GUI plugins for the TD MIM Toolkit which
    %     are available.
    %
    %     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.
    %

    new_plugin = [];
    new_plugin.PluginName = plugin_name;

    new_plugin.ToolTip = plugin_class.ToolTip;
    new_plugin.ButtonText = plugin_class.ButtonText;
    if ~isempty(plugin_class.Category)
        new_plugin.Category = plugin_class.Category;
    else
        if ~isempty(suggested_category)
            new_plugin.Category = suggested_category;
        else
            new_plugin.Category = default_category;
        end
    end
    new_plugin.HidePluginInDisplay = plugin_class.HidePluginInDisplay;
    new_plugin.ButtonWidth = plugin_class.ButtonWidth;
    new_plugin.ButtonHeight = plugin_class.ButtonHeight;
    new_plugin.AlwaysRunPlugin = false; % Ensures plugin name is not in italics

    property_list = properties(plugin_class);

    if ismember('PluginInterfaceVersion', property_list)
        new_plugin.PluginInterfaceVersion = plugin_class.PluginInterfaceVersion;
    elseif ismember('PTKVersion', property_list)
        new_plugin.PluginInterfaceVersion = plugin_class.PTKVersion;
    else
        new_plugin.PluginInterfaceVersion = 1;
    end

    if ismember('Visibility', property_list)
        new_plugin.Visibility = plugin_class.Visibility;
    end

    if ismember('Mode', property_list) && ~isempty(plugin_class.Mode)
        new_plugin.Mode = plugin_class.Mode;
    else
        new_plugin.Mode = default_mode;
    end

    if ismember('SubMode', property_list)
        new_plugin.SubMode = plugin_class.SubMode;
    else
        new_plugin.SubMode = [];
    end

    if ismember('Location', property_list)
        new_plugin.Location = plugin_class.Location;
    else
        new_plugin.Location = 100;
    end
end


%
% DEPRECATED
%

h = findobj('Tag','EEGLAB');
i = get(h,'Children');
k = get(i,'Tag');
tags = regexpi(k,'\w*win\w*','match');
tags = [tags{:}];
for a=1:length(tags)
      hh = findobj('Tag',tags{a});
      set(hh,'backgroundcolor','g')
end
hm = findobj('Tag', 'Frame1');
set(hm,'backgroundcolor','g')
hm = findobj('Tag', 'EEGLAB');
set(hm,'Color','g')


import matlab.unittest.plugins.DiagnosticsRecordingPlugin
import matlab.unittest.plugins.TestReportPlugin

runner = matlab.unittest.TestRunner.withNoPlugins;
runner.addPlugin(DiagnosticsRecordingPlugin);
runner.addPlugin(TestReportPlugin.producingPDF('Report.pdf',...
    'IncludingPassingDiagnostics',true,'IncludingCommandWindowText',true));
runner.ArtifactsRootFolder = pwd;

suite = testsuite('HardwarePerformanceTests');

if ~exist('logs', 'dir')
    mkdir('logs')
end

results = runner.run(suite);
t = table(results);
disp(t);

exit(any([results.Failed]));


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

    properties
        MockResults
        SavedMockResults
    end

    methods

        function obj = MockPluginDependencyTracker()
            obj.MockResults = containers.Map;
            obj.SavedMockResults = containers.Map;
        end

        function AddMockResult(obj, name, context, dataset_uid, result_to_add, cache_info, has_been_run)
            result = [];
            result.Result = result_to_add;
            result.CacheInfo = cache_info;
            result.HasBeenRun = has_been_run;
            obj.MockResults([name '.' char(context) '.' dataset_uid]) = result;
        end

        function cache_info = GetCacheInfo(obj, plugin_name)
        end

        function [result, plugin_has_been_run, cache_info] = GetResult(obj, plugin_name, context, linked_dataset_chooser, plugin_info, plugin_class, dataset_uid, dataset_stack, memory_cache_policy, disk_cache_policy, reporting)

            key_name = [plugin_name '.' char(context) '.' dataset_uid];

            result_from_cache = obj.MockResults(key_name);
            result = result_from_cache.Result;
            cache_info = result_from_cache.CacheInfo;
            plugin_has_been_run = result_from_cache.HasBeenRun;

        end

        function SaveEditedResult(obj, plugin_name, context, result, dataset_uid, reporting)
            obj.SavedMockResults([plugin_name '.' char(context) '.' dataset_uid]) = result;
        end

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

end


function varargout = cfg_util_persistent(varargin)
%CFG_UTIL_PERSISTENT - store persistent variables for cfg_util
%
% 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_util_persistent.m 5750 2013-11-15 15:02:24Z volkmar $

rev = '$Rev: 5750 $';

persistent c0;
persistent jobs;
if nargin == 2 && nargout == 0
    c0   = varargin{1};
    jobs = varargin{2};
elseif nargin == 0 && nargout == 2
    varargout{1} = c0;
    varargout{2} = jobs;
else
    cfg_message('matlabbatch:usage', '%s: Usage error.', mfilename);
end


function fileStr = file2string(fname)

fileStr = '';
fid = fopen(fname,'r');
tline = fgetl(fid);
while ischar(tline)
    fileStr = [fileStr ' ' tline];
    tline = fgetl(fid);
end
fclose(fid);


function complainif_notenoughargs(fnargin,limit,callfun)

if nargin<3
    callfun = mfilename;
end

if fnargin<limit
   error('%s: Not enough input arguments.',upper(callfun));
end


function s=get_name(a)
s=[get_name(a.algorithm)];
eval_name


function str = showdetail(item)

% function str = showdetail(item)
% Generic showdetail function for cfg_item classes. It displays the
% name, tag, class and default function call for this item..
%
% 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{1,1} = sprintf('Name   : %s', item.name);
str{2,1} = sprintf('Tag    : %s', gettag(item));
if ~isempty(item.def)
    str{3} = sprintf('Default: %s', func2str(item.def));
end


function str = showmydoc(item, indent)

% function str = showmydoc(item, indent)
% Display help text for a cfg_repeat 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'));
if isfinite(item.num(2))
    str2{1} = sprintf('Between %d and %d options must be selected from:', ...
                         item.num(1), item.num(2));
else
    str2{1} = sprintf('%d or more options must be selected from:', ...
                         item.num(1));
end;
% Display short listing of cfg_repeat 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 = cell(1,numel(valitem)+1);
    str4{1} = sprintf('Currently selected options:');
    for k = 1:numel(valitem)
        str4{k+1} = sprintf('* "%s"', subsref(valitem{k}, substruct('.','name')));
    end;
else
    str4 = {};
end;
str = [str1(:); {''}; str2(:); str3(:); str4(:)];


function nWritten = export_GSPS_IOD(planC, filenameRoot, filenumber)
%"export_GSPS_IOD"
%   Writes to disk all scans contained in planC by constructing the modules
%   specified in part A.3.3 of PS 3.3 of the 2006 DICOM standard.  The
%   planC MUST have first been run through the function:
%
%   generate_DICOM_UID_Relationships.m.
%
%   filenameRoot is the the base path + filename to have file numbers
%   appended to, ie, "C:\tmp\DCM".  filenumber is the starting filenumber
%   to append, with results such as "C:\tmp\DCM00000", "C:\tmp\DCM00001"
%   etc.
%
% APA, 7/12/2019
%
%Usage:
%   nWritten = export_GSPS_IOD(planC, filenameRoot, filenumber);
%
% 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/>.

indexS  = planC{end};

%Init number of files written to zero.
nWritten = 0;

    scanNum = 1;
    if length(planC{indexS.scan}) > 1
        destDirPath = fullfile(filenameRoot,['Scan_',num2str(scanNum)]);
        if ~exist(destDirPath,'dir')
            mkdir(destDirPath)
        end
    else
        destDirPath = filenameRoot;
    end

    % Get the associated scanNum
    %scanNum = getStructureAssociatedScan(structNum,planC);

    %Get the scan we are currently working with
    scanS   = planC{indexS.scan}(scanNum);

    if isempty(planC{indexS.GSPS})
        return;
    end

    gspsObjS = planC{indexS.GSPS}(1);

    %Build patient module.
    patientattr      = export_module('patient', 'gsps', gspsObjS);

    %Build general study module.
    studyattr        = export_module('general_study', gspsObjS);

    %Build general series module.
    %seriesattr       = export_module('general_series', gspsObjS);
    seriesattr       = export_module('rt_series', 'gsps', gspsObjS);

    %Build a frame of reference module.
    frameattr        = export_module('frame_of_reference', gspsObjS);

    %Build a general equipment module.
    equipattr        = export_module('general_equipment', 'gsps', gspsObjS);

    %Build a content module
    contentattr        = export_module('content_identification', gspsObjS);

    %Build Graphic Layer module
    %graphicLayerAttr        = export_module('graphic_layer');

    %For slice-specific modules iterate over scaninfo.
    %for i=1:length(planC{indexS.GSPS}) % in future, loop over GSPS objects
    %belonging to a particular scanNum. Currently, we assume all GSPS objects belong
    %only to a single scan.

        gspsS = planC{indexS.GSPS};

        %Create a attr to hold a single slice.
        %CHANGE to dcm4che 3attribute
        attr = javaObject('org.dcm4che3.data.Attributes');

        %Get info for the slice we are handling.
        %scanInfoS = scanS.scanInfo(slcNum);
        %contourS = planC{indexS.structures}(structNum).contour(slc);

        % Build GSPS module from this structure
        gspsattr    =  export_module('gsps', gspsS, scanS);

        SOPattr     = export_module('SOP_common', 'gsps', gspsObjS);

        %Combine all modules into a single attribute.
        attr.addAll(patientattr);
        attr.addAll(studyattr);
        attr.addAll(seriesattr);
        attr.addAll(frameattr);
        attr.addAll(equipattr);
        attr.addAll(contentattr);
        attr.addAll(gspsattr);
        attr.addAll(SOPattr);

        %clear imgattr imgplaneattr imgpixelattr ctimageattr SOPattr

        fileNum  = num2str(filenumber + nWritten);
        filename = fullfile(destDirPath,['GSPS_', repmat('0', [1 5-length(fileNum)]), fileNum]);

        writefile_mldcm(attr, filename);

        nWritten = nWritten + 1;

        clear attr;
    %end

    clear patientattr studyattr seriesattr frameattr equipattr

end


function out=testDependencyStructure()
out=0;

which('initCobraToolbox.m')
global CBTDIR

%excluded folders and subfolders
exclusionFolderList={'external'};

exclusion_list

function Build_Dependency_Map(root_dir, exclusion_list);


function hP = plugin_board()
% Zynq Platform PCore
% Use Plugin API to create board plugin object

%   Copyright 2015 The MathWorks, Inc.

% Call the common board definition function
hP = AnalogDevicesAGCDemo.adrv9361z7035.common.plugin_board('fmc lvds agc', 'Rx');


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

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

mrGlobals;

switch param

    case 'tseries'
        vw.tSeries = val;
    case 'tseriesslice'
        vw.tSeriesSlice = val;
    case 'tseriesscan'
        vw.tSeriesScan = val;

    otherwise
        error('Unknown view parameter %s.', param);

end %switch

return


classdef testTopOptDensityPrinting < testTopOptPrinting

    properties (Access = protected)
        fileOutputName = 'testTopOptDensityPrinting';
        printMode = 'DesignVariable';
    end

end


% (this is just an interface)
function varargout = mydatehelp (varargin)
    [varargout{1:nargout}] = mydatestd_aux (varargin{:});
end

%!test
%! % just check whether it runs:
%! mydatehelp(1);


%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Save and close the Simulink model through Matlab command line.
% It also closes the associate static GUI

%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
disp('[closeModel]: closing the Simulink model...')

% save and close the Simulink model
save_system('jointsControl.mdl');
close_system('jointsControl.mdl');

% close all figures
close all

% remove paths (optional)
rmpath('../../library/matlab-gui');
rmpath('./src-static-gui');

disp('[closeModel]: done.')


classdef FreeFemFileIdenticalPrinter < FreeFemFilePrinter

    methods (Access = protected)

       function printingLines(obj)
            nlines = numel(obj.linesToPrint);
            for iline = 1:nlines
                line = obj.linesToPrint{iline};
                fprintf(obj.fileID,'%s\r\n',line);
            end
        end

    end

end


function disp(obj)
% display MoxUnitTestSuite object
%
% disp(obj)
%
% Inputs:
%   obj             MoxUnitTestSuite object
%
% NNO 2015

    disp(str(obj));


function gotostart(H)
%GOTOSTART Go to start of movie in movie player

feval(H.fcns.goto_start,[],[],H.hfig);


function [gid, fid] = HDF5_GroupOpen(fileobj, location)

% Find data location
if ischar(fileobj)
    fid = H5F.open(fileobj);
else
    fid = fileobj;
end
try
    gid = H5G.open(fid, location);
catch
    gid.double = -1;
end


classdef (Sealed) PTKUtils < handle
    % PTKUtils. A script to update the PTK codebase via git
    %
    %
    %
    %     Licence
    %     -------
    %     Part of the TD Pulmonary Toolkit. https://github.com/tomdoel/pulmonarytoolkit
    %     Author: Tom Doel, 2015.  www.tomdoel.com
    %     Distributed under the GNU GPL v3 licence. Please see website for details.
    %

    methods (Static)
        function RunScript(script_name, varargin)
            % Runs a PTKScript from the Scripts folder

            m = PTKMain();
            m.RunScript(script_name, varargin{:});
        end

        function Recompile()
            % Forces recompilation of mex files

            m = PTKMain();
            m.Recompile();
        end

        function RebuildDatabase()
            % Forces a rebuild of the image database

            m = PTKMain();
            m.RebuildDatabase();
        end

        function ClearMemory()
            % Clears out memory caches

            close all;
            clear all classes;
            path(pathdef);
        end

        function ClearDisk()
            % Clears out disk and memory caches for temporary files

            m = PTKMain();
            m.DeleteCacheForAllDatasets();
        end

        function ReloadPlugins()
            % Forces reload of plugin information. Useful if you have modified properties of the plugin

            m = PTKMain();
            m.ReloadPlugins();
        end

        function Clear()
            PTKUtils.ClearMemory();
            PTKAddPaths;
        end

    end

    methods (Access = private)
        function obj = PTKUtils()
            disp('PTKUtils contains method to help maintain your PTK');
            disp('PTKUtils.RunScript(script_name, parameters) will run a PTKScript with the specified parameters');
            disp('PTKUtils.RebuildDatabase() will reimport your imaging files and correct problems with the database');
            disp('PTKUtils.ReloadPlugins() will reload plugins to fetch property changes');
            disp('PTKUtils.Recompile() will recompile your mex files');
            disp('PTKUtils.ClearMemory() will clear all the memory caches');
            disp('PTKUtils.ClearDisk() will clear the disk caches to retrieve disk space');
            ClearDisk
        end
    end

end


function hRD = plugin_rd_tx
% Reference design definition

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


function filename = fetch_url(filename)

% FETCH_URL checks the filename and downloads the file to a local copy in
% case it is specified as an Universal Resource Locator. It returns the
% name of the temporary file on the local filesystem.
%
% Use as
%   filename = fetch_url(filename)
%
% In case the filename does not specify an URL, it just returns the original
% filename.

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

if filetype_check_uri(filename, 'sftp')
  [user, host, filename] = filetype_check_uri(filename);
  [p, f, x] = fileparts(filename);
  p = tempdir;
  try
    mkdir(p);
    cmd = sprintf('sftp %s@%s:%s %s', user, host, filename, fullfile(p, [f x]));
    system(cmd);
    filename = fullfile(p, [f x]);
  end
  % elseif filetype_check_uri(filename, 'http')
  % FIXME the http scheme should be supported using default MATLAB
  % elseif filetype_check_uri(filename, 'ftp')
  % FIXME the http scheme should be supported using default MATLAB
  % elseif filetype_check_uri(filename, 'smb')
  % FIXME the smb scheme can be supported using smbclient
end


classdef SettingsConstitutiveTensorFromVademecum < AbstractSettings

    properties (Access = protected)
        defaultParamsName = 'paramsConstitutiveTensorFromVademecum'
    end

    properties (Access = public)
        fileName
    end

    methods (Access = public)
        function obj = SettingsConstitutiveTensorFromVademecum(varargin)
            switch nargin
                case 1
                    obj.loadParams(varargin{1});
            end
        end
    end

end


function varargout = mygui(varargin)
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @mygui_OpeningFcn, ...
                   'gui_OutputFcn',  @mygui_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

function mygui_OpeningFcn(hObject, eventdata, handles, varargin)
handles.output = hObject;
guidata(hObject, handles);
% changeIcon
jFrame=get(handles.figure1,'javaframe');
jIcon=javax.swing.ImageIcon('icon.gif');
jFrame.setFigureIcon(jIcon);
% changeUserData
set(handles.pushbutton_run,'UserData',0);

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

function pushbutton_run_Callback(hObject, eventdata, handles)
if get(handles.pushbutton_run,'UserData')==1, return; end
set(handles.pushbutton_run,'UserData',1);
for n=1:40
    if get(handles.pushbutton_run,'UserData')==0, break; end
    cla; text(0.5,0.5,num2str(n)); pause(0.25);
end

function pushbutton_stop_Callback(hObject, eventdata, handles)
set(handles.pushbutton_run,'UserData',0);


function v = getfield(s,field)
%GETFIELD Get mutable structure field contents.
% f = getfield(s,'field') returns the contents of the specified field.
% This is equivalent to the syntax f = s.field.
%
% See also SETFIELD, RMFIELD, ISFIELD, FIELDNAMES.

% Written by Tom Minka
% (c) Microsoft Corporation. All rights reserved.

v = s.obj.get(field);
if isempty(v)
  error(sprintf('Reference to non-existent field ''%s''.',field));
end
v = fromJava(v);


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

% Last Modified by GUIDE v2.5 06-Aug-2020 15:26:37

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

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

    centerUIFigure(hObject);

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

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

    populateGUI(handles, action, lv);

    % Update handles structure
    guidata(hObject, handles);

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

function populateGUI(handles, action, lv)
    [powerSrcListStr, powerSrcs] = lv.getPowerSrcsListBoxStr();
    set(handles.refPwrCompCombo,'String',powerSrcListStr);

    if(not(isempty(action.src)))
        ind = find(powerSrcs == action.src,1,'first');
    else
        ind = [];
    end

    if(not(isempty(ind)))
        set(handles.refPwrCompCombo,'Value',ind);
    end

    if(action.activeStateToSet)
        set(handles.stateCombo,'Value',1);
    else
        set(handles.stateCombo,'Value',2);
    end

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

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

        [~, powerSrcs] = lv.getPowerSrcsListBoxStr();
        ind = get(handles.refPwrCompCombo,'Value');
        action.src = powerSrcs(ind);

        contents = cellstr(get(handles.stateCombo,'String'));
        stateStr = contents{get(handles.stateCombo,'Value')};

        switch stateStr
            case 'Active'
                state = true;
            case 'Inactive'
                state = false;
            otherwise
                error('Invalid state string: %s', stateStr);
        end

        action.activeStateToSet = state;

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

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

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

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

% --- Executes during object creation, after setting all properties.
function refPwrCompCombo_CreateFcn(hObject, eventdata, handles)
% hObject    handle to refPwrCompCombo (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 selection change in stateCombo.
function stateCombo_Callback(hObject, eventdata, handles)
% hObject    handle to stateCombo (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 stateCombo contents as cell array
%        contents{get(hObject,'Value')} returns selected item from stateCombo

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

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

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


function my_diary_flush()

tmp_status=get(0,'Diary');
if strcmp(tmp_status, 'on')
    diary off
    diary on
end

end


function [] = closematlabpool
   poolobj = gcp('nocreate');
   delete(poolobj);
end


mex -lopencv_core -lopencv_imgproc -L/usr/local/lib -I/usr/local/include/ mexResize.cpp MxArray.cpp
mex gradientMex.cpp


function [success] = resetMiji(varargin)
	% This clears Miji from Java's dynamic path and then re-initializes. Use if Miji is not loading normally.
	% Biafra Ahanonu
	% started: 2019.01.28 [14:34:14]
	% inputs
		%
	% outputs
		%
	% usage
		% % Run the following commands one at a time in the command window.
		% resetMiji
		% % An instance of Miji should appear.
		% currP=pwd;Miji;cd(currP);
		% MIJ.exit

	% changelog
		% 2019.09.09 [18:04:10] - Updated to add fallback to modelAddOutsideDependencies to ask for path to Fiji/Miji in case it is not properly in the path or has been moved.
		% 2019.10.15 [12:29:30] - Added flag to prevent recursive loop between resetMiji and modelAddOutsideDependencies.
		% 2021.08.08 [19:30:20] - Updated to handle CIAtah v4.0 switch to all functions inside ciapkg package.
        % 2021.12.19 [10:34:00] - Update to use manageMiji to setup Miji, avoid certain issues. Also search for imagej instead of Fiji path.
	% TODO
		%

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

	%========================
	% DESCRIPTION
	options.nRounds = 1;
	% get options
	options = getOptions(options,varargin);
	% display(options)
	% unpack options into current workspace
	% fn=fieldnames(options);
	% for i=1:length(fn)
	% 	eval([fn{i} '=options.' fn{i} ';']);
	% end
	%========================

	% try
	success = 0;

	for i = 1:options.nRounds
		try
			clear MIJ miji Miji mij;
			javaDyna = javaclasspath('-dynamic');
			% matchIdx = ~cellfun(@isempty,regexpi(javaDyna,'Fiji'));
            matchIdx = ~cellfun(@isempty,regexpi(javaDyna,'imagej'));
			% cellfun(@(x) javarmpath(x),javaDyna(matchIdx));
			javaDynaPathStr = join(javaDyna(matchIdx),''',''');
			if ~isempty(javaDynaPathStr)
				eval(sprintf('javarmpath(''%s'');',javaDynaPathStr{1}))
			else
				disp('Empty Java dynamic path!')
			end
			clear MIJ miji Miji mij;
			% Load Miji so paths added to javaclasspath('-dynamic')
			currP = pwd;
			% Miji;
			% Miji(false);
            ciapkg.io.manageMiji('startStop','setupImageJ');
            MIJ.start;
			cd(currP);
			MIJ.exit;
			% pause(1);
			% java.lang.Runtime.getRuntime().gc;
			% Miji;
			% MIJ.exit;
		catch err
			disp(repmat('@',1,7))
			disp(getReport(err,'extended','hyperlinks','on'));
			disp(repmat('@',1,7))

			try
				modelAddOutsideDependencies('miji','recursionExit',1);
			catch err
				disp(repmat('@',1,7))
				disp(getReport(err,'extended','hyperlinks','on'));
				disp(repmat('@',1,7))
			end
		end
	end

	success = 1;
	% catch err
	% 	success = 0;
	% 	display(repmat('@',1,7))
	% 	disp(getReport(err,'extended','hyperlinks','on'));
	% 	display(repmat('@',1,7))
	% end
end


% SERVER.GETREPLY gets a reply structure stored by the slave with given index.
function result = getReply(server, slaveIdx)

  if (slaveIdx > server.slaveCount)
    error('Slave index is out of bounds.');
  end

  if (server.options.emulate)
    % emulate the following:
    % 1.  deserialization of data by slave
    % 2.  processing of request by slave
    % 3.  serialization of reply by slave.
    % 4.  de-serialization of reply by server.

    % Deserialize request
    reply = emulateSlaveProcessRequest(server, slaveIdx);
  else
    if (slaveIdx > length(server.slave_sock))
      error('No socket for slave');
    end
    sock=server.slave_sock{slaveIdx};

    % this blocks until slave creates output stream
    is=java.io.ObjectInputStream(sock.getInputStream());
    % block until we get a new message;  convert to MATLAB
    reply = java2matlab(is.readObject());
  end

  result=reply.result;
  if (isfield(reply, 'error'))
    rethrow(reply.error);
  end

  % wrap any slaveRef objects in a serverRef...
  result = serverRef.wrapSlaveRefs(result, server, slaveIdx);


function b = isdir_private(dirname)
%
% isdir_private() is a backward compatible version of matlab's isdir()
% function.
%
% isdir() is a new matlab function that is an improvment over exist() to
% tell if a pathname is a directory or not. But it didn't exist prior to R2017.
% Therefore we use try/catch to still be able to use isdir when it exists

try
    b = isdir(dirname);
catch
    b = (exist(dirname,'dir') == 7);
end


classdef DMDicomLibraryInterface < CoreBaseClass
    % DMDicomLibraryInterface Interface for a class that parses Dicom
    % files.
    %
    % This interface allows you to use your own Dicom parsing libraries
    % with DicoMat functions, by wrapping them up in a class that
    % implements this interface.
    %
    %
    %     Licence
    %     -------
    %     Part of DicoMat. https://github.com/tomdoel/dicomat
    %     Author: Tom Doel, 2015.  www.tomdoel.com
    %     Distributed under the BSD 3-Clause license. Please see the file LICENSE for details.
    %

    methods (Abstract)

        % Tests whether a file is in DICOM format
        isDicom = isdicom(obj, fileName)

        % Reads the metaheader data from a Dicom file
        metaheader = dicominfo(obj, varargin)

        % Reads the image data from a Dicom file
        imageData = dicomread(obj, fileName_or_metaHeader)

    end
end


function obj = removeConcurrentAnalysisFiles(obj)
	% DESCRIPTION
	% Biafra Ahanonu
	% started: 2014.07.31 - branch from calciumImagingAnalysis 2020.05.07 [15:47:29]
	% inputs
		%
	% outputs
		%

	% changelog
		% 2021.08.10 [09:57:36] - Updated to handle CIAtah v4.0 switch to all functions inside ciapkg package.
	% TODO
		%

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

	obj.foldersToAnalyze
	if obj.guiEnabled==1
		if isempty(obj.foldersToAnalyze)
			scnsize = get(0,'ScreenSize');
			[fileIdxArray, ~] = listdlg('ListString',obj.fileIDNameArray,'ListSize',[scnsize(3)*0.2 scnsize(4)*0.25],'Name','which folders to analyze?');
		else
			fileIdxArray = obj.foldersToAnalyze;
		end
	else
		if isempty(obj.foldersToAnalyze)
			fileIdxArray = 1:length(obj.fileIDNameArray);
		else
			fileIdxArray = obj.foldersToAnalyze;
		end
	end

	% Find all concurrent analysis files and delete them
	nFolders = length(fileIdxArray);
	nFoldersTotal = length(obj.inputFolders);
	for folderNo = 1:nFolders
		i = fileIdxArray(folderNo);
		try
			% disp([num2str(i) ' | ' obj.inputFolders{i}])
			fileList = getFileList(obj.inputFolders{i},obj.concurrentAnalysisFilename);
			if ~isempty(fileList)
				fprintf('%d/%d (%d/%d) will delete analysis file: %s\n',i,nFoldersTotal,folderNo,nFolders,fileList{1})
			end
		catch err
			disp(repmat('@',1,7))
			disp(getReport(err,'extended','hyperlinks','on'));
			disp(repmat('@',1,7))
		end
	end
	userInput = input('Continue (1 = yes, 0 = no)? ');
	if userInput==1
		for folderNo = 1:nFolders
			i = fileIdxArray(folderNo);
			try
				% disp([num2str(i) ' | ' obj.inputFolders{i}])
				fprintf('%d/%d (%d/%d): %s\n',i,nFoldersTotal,folderNo,nFolders,obj.inputFolders{i})
				fileList = getFileList(obj.inputFolders{i},obj.concurrentAnalysisFilename);
				if ~isempty(fileList)
					fprintf('Deleting analysis file: %s\n',fileList{1})
					delete(fileList{1});
				end
			catch err
				disp(repmat('@',1,7))
				disp(getReport(err,'extended','hyperlinks','on'));
				disp(repmat('@',1,7))
			end
		end
	end
end


%
% 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: copyright_cfg.m 3944 2010-06-23 08:53:40Z volkmar $

rev = '$Rev: 3944 $';


function sitem = cfg2struct(item)

% function sitem = cfg2struct(item)
% Return a struct containing all fields of item plus a field type. This is
% the method suitable for entry classes.
%
% 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: cfg2struct.m 1716 2008-05-23 08:18:45Z volkmar $

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

% Get parent struct, re-classify as field 'type'
sitem = cfg2struct(item.cfg_item);
sitem.type = class(item);

% Need to cycle through added fields
fn = mysubs_fields;
for k = 1:numel(fn)
    sitem.(fn{k}) = item.(fn{k});
end;


% SLAVEHOOK installs a 'hook' into the slave structure which overrides
% function calls made to the named hook.
%
% slave.hook(hookName, func, userData, noDeref) inserts a hook into the
% slave structure which will be called whenever the slave receives a request
% to call the function with name hookName.  func is the function handle to
% be called and userData is an optional argument whose value is passed as
% the first argument of func, followed by the arguments from the server.
%
% This can be used to override matlab functions or other functions that
% might be called by the server and replace them with more RPC-friendly
% semantics, etc.  For instance, by default, all slaves include an 'exit'
% hook that allows the server to call the 'exit' function as usual, but
% which cleanly destroys the slave state before closing (whereas calling
% MATLAB's exit() directly would quit the slave without cleaning up).
% if
%
function hook(slave, hookName, func, userData, noDeref)

  slave.hooks.(hookName).func = func;

  if ((nargin > 3) & (~isempty(userData)))
    slave.hooks.(hookName).userData = userData;
  end

  if (nargin < 5)
    noDeref = 0;
  end
  slave.hooks.(hookName).noDereference = noDeref;


function varargout = permute(varargin)
% Can not be permuted.
% _______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging

%
% $Id$

error('file_array objects can not be permuted.');


function varargout = cfg_message(varargin)

% function cfg_message(msgid, msgfmt, varargin)
% Display a message. The message identifier msgid will be looked up in a
% message database to decide how to treat this message. This database is
% a struct array with fields:
% .identifier  - message id
% .level       - message severity level. One of
%                'info'    - print message
%                'warning' - print message, raise a warning
%                'error'   - print message, throw an error
% .destination - output destination. One of
%                'none'    - silently ignore this message
%                'stdout'  - standard output
%                'stderr'  - standard error output
%                'syslog'  - (UNIX) syslog
%                Warnings and errors will always be logged to the command
%                window and to syslog, if destination == 'syslog'. All
%                other messages will only be logged to the specified location.
% .verbose
% .backtrace   - control verbosity and backtrace, one of 'on' or 'off'
%
% function [oldsts msgids] = cfg_message('on'|'off', 'verbose'|'backtrace', msgidregexp)
% Set verbosity and backtrace display for all messages where msgid
% matches msgidregexp. To match a message id exactly, use the regexp
% '^msgid$'.
%
% function [olddest msgids] = cfg_message('none'|'stdout'|'stderr'|'syslog', 'destination', msgidregexp)
% Set destination for all messages matching msgidregexp.
%
% function [oldlvl msgids] = cfg_message('info'|'warning'|'error', 'level', msgidregexp)
% Set severity level for all messages matching msgidregexp.
%
% For all matching message ids and message templates, the old value and
% the id are returned as cell strings. These can be used to restore
% previous settings one-by-one.
%
% 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_message.m 5678 2013-10-11 14:58:04Z volkmar $

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

if nargin < 1 || isempty(varargin{1})
    return;
end

% Get message settings
msgcfg = cfg_get_defaults('msgcfg');
msgtpl = cfg_get_defaults('msgtpl');
msgdef = cfg_get_defaults('msgdef');
% Input checks
if ~(ischar(varargin{1}) && size(varargin{1},1) == 1) && ...
        ~(isstruct(varargin{1}) && numel(varargin{1}) == 1 && ...
          all(isfield(varargin{1}, {'message', 'identifier'})))
    cfg_message('matlabbatch:cfg_message', ...
          'First argument must be a one-line character string or an errorstruct.');
    return;
end
if any(strcmpi(varargin{1}, {'on', 'off', 'none', 'stdout', 'stderr', ...
                        'syslog', 'info', 'warning', 'error'}))
    % Set message properties
    if nargin ~= 3
        cfg_message('matlabbatch:cfg_message', ...
              'Must specify status, property and msgidregexp.');
        return;
    end
    if any(strcmpi(varargin{1}, {'on', 'off'})) && ~any(strcmpi(varargin{2}, ...
                    {'verbose', 'backtrace'}))
        cfg_message('matlabbatch:cfg_message', ...
              ['Message property must be one of ''verbose'' or ' ...
               '''backtrace''.']);
        return;
    elseif any(strcmpi(varargin{1}, {'none', 'stdout', 'stderr', 'syslog'})) && ...
            ~strcmpi(varargin{2}, 'destination')
        cfg_message('matlabbatch:cfg_message', ...
              'Message property must be ''destination''.');
        return;
    elseif any(strcmpi(varargin{1}, {'info', 'warning', 'error'})) && ...
            ~strcmpi(varargin{2}, 'level')
        cfg_message('matlabbatch:cfg_message', ...
              'Message property must be ''level''.');
        return;
    end
    if ~ischar(varargin{3}) || size(varargin{3},1) ~= 1
        cfg_message('matlabbatch:cfg_message', ...
              'Third argument must be a one-line character string.');
        return;
    end
    msgstate  = lower(varargin{1});
    msgprop   = lower(varargin{2});
    msgregexp = varargin{3};
    sel = findcfg(msgcfg, msgregexp);
    % Save properties and matching ids
    oldmsgprops = {msgcfg(sel).(msgprop)};
    mchmsgids   = {msgcfg(sel).identifier};
    if any(sel)
        % Set property on all matching messages
        [msgcfg(sel).(msgprop)] = deal(msgstate);
        cfg_get_defaults('msgcfg',msgcfg);
    elseif ismsgid(msgregexp)
        % Add new rule, if msgregexp is a valid id
        msgcfg(end+1)          = msgdef;
        msgcfg(end).identifier = msgregexp;
        msgcfg(end).(msgprop)  = msgstate;
        cfg_get_defaults('msgcfg',msgcfg);
    end
    if ~ismsgid(msgregexp)
        % Update templates
        sel = strcmp(msgregexp, {msgtpl.identifier});
        % Save properties and matching ids
        oldtplprops = {msgtpl(sel).(msgprop)};
        mchtplids   = {msgtpl(sel).identifier};
        if any(sel)
            % Update literally matching regexps
            [msgtpl(sel).(msgprop)] = deal(msgstate);
        else
            % Add new template rule
            msgtpl(end+1)          = msgdef;
            msgtpl(end).identifier = msgregexp;
            msgtpl(end).(msgprop)  = msgstate;
        end
        cfg_get_defaults('msgtpl',msgtpl);
    else
        oldtplprops = {};
        mchtplids   = {};
    end
    varargout{1} = [oldmsgprops(:); oldtplprops(:)]';
    varargout{2} = [mchmsgids(:); mchtplids(:)]';
else
    % Issue message
    if isstruct(varargin{1})
        msgid  = varargin{1}.identifier;
        msgfmt = varargin{1}.message;
        extras = {};
        if isfield(varargin{1},'stack')
            stack = varargin{1}.stack;
        else
            stack = dbstack(2);
        end
        % discard other fields
    else
        if nargin < 2
            cfg_message('matlabbatch:cfg_message', ...
                  'Must specify msgid and message.');
        end
        if ~ischar(varargin{2}) || size(varargin{2},1) ~= 1
            cfg_message('matlabbatch:cfg_message', ...
                  'Second argument must be a one-line character string.');
        end
        msgid  = varargin{1};
        msgfmt = varargin{2};
        extras = varargin(3:end);
        stack = dbstack(2);
    end
    % find msgcfg entry for msgid
    sel = strcmp(msgid, {msgcfg.identifier});
    if any(sel)
        cmsgcfg = msgcfg;
    else
        % no identity match found, match against regexp templates
        sel = ~cellfun(@isempty, regexp(msgid, {msgtpl.identifier}));
        cmsgcfg = msgtpl;
        [cmsgcfg(sel).identifier] = deal(msgid);
    end
    switch nnz(sel)
        case 0
            % no matching id (or invalid msgid), use default setting
            cmsgcfg = msgdef;
            cmsgcfg.identifier = msgid;
            issuemsg(cmsgcfg, msgfmt, extras, stack);
        case 1
            % exact match
            issuemsg(cmsgcfg(sel), msgfmt, extras, stack);
        otherwise
            % multiple matches, use last match (i.e. least recently added rule)
            is = find(sel);
            issuemsg(cmsgcfg(is(end)), msgfmt, extras, stack);
    end
end

function issuemsg(msgcfg, msgfmt, extras, stack)
if strcmp(msgcfg.level,'error') || ~strcmp(msgcfg.destination, 'none')
    switch msgcfg.destination
        case 'none'
            fid = -1;
        case 'stdout'
            fid = 1;
        case 'stderr'
            fid = 2;
        case 'syslog'
            if isunix
                fid = '/usr/bin/logger';
            else
                fid = -1;
            end
    end
    msg = sprintf(msgfmt, extras{:});
    switch msgcfg.level
        case 'info'
            if ischar(fid)
                unix(sprintf('%s -t [MATLAB] %s: %s', fid, msgcfg.identifier, ...
                             msg));
            elseif ~ischar(fid) && fid > 0
                % only display, if destination is neither syslog nor none
                fprintf(fid, '%s\n', msg);
                if strcmp(msgcfg.backtrace, 'on')
                    dbstack(2) % This will ignore fid
                end
                if strcmp(msgcfg.verbose, 'on')
                    fprintf(fid, 'To turn off this message, type %s(''none'', ''destination'', ''%s'').\n',...
                            mfilename, msgcfg.identifier);
                end
            end
        case 'warning'
            if ischar(fid)
                unix(sprintf('%s -t [MATLAB] %s: %s', fid, msgcfg.identifier, ...
                             msg));
            elseif ~ischar(fid) && fid > 0
                % only display, if destination is neither syslog nor none
                bsts = warning('query','backtrace');
                vsts = warning('query','verbose');
                warning('off', 'backtrace');
                warning('off', 'verbose');
                warning(msgcfg.identifier, msg);
                if strcmp(msgcfg.backtrace, 'on')
                    dbstack(2)
                end
                if strcmp(msgcfg.verbose, 'on')
                    fprintf('To turn off this message, type %s(''none'', ''destination'', ''%s'').\n',...
                            mfilename, msgcfg.identifier);
                end
                warning(bsts);
                warning(vsts);
            end
        case 'error'
            if ischar(fid)
                unix(sprintf('%s -t [MATLAB] %s: %s', fid, msgcfg.identifier, ...
                             msg));
            end
            le.identifier = msgcfg.identifier;
            le.message    = msg;
            le.stack      = stack;
            error(le);
    end
end
% Helper functions
function sts = ismsgid(msgidstr)
sts = ~isempty(regexp(msgidstr,'^([a-zA-Z]\w*:)+[a-zA-Z]\w*$','once'));
function cfg = findcfg(msgcfg, msgregexp)
cfg = ~cellfun(@isempty,regexp({msgcfg.identifier},msgregexp,'once'));


import client.EEGLABChat;
import client.VisualToolbar;
import java.awt.*;
import javax.swing.*;

tb = VisualToolbar();
F = gcf;
tb.setPreferredSize(Dimension(0, 75));

javacomponent(tb,'South',F);

refresh(F);


function biosigpathfirst

str2doublepath = fileparts( which('str2double') );
sopenpath      = fileparts( which('sopen') );
if ~strcmp(str2doublepath,sopenpath)
    rmpath(sopenpath);
    addpath(sopenpath,'-begin');
end