classdef CoreReporting < CoreReportingInterface
    % CoreReporting. Provides error, message and progress reporting.
    %
    %     CoreReporting. Implementation of CoreReportingInterface, which is used by
    %     CoreMat and other libraries for progress and error/message reporting. This
    %     implementation displays warnings and messages on the command window,
    %     and uses Matlab's error() command to process errors. Logging
    %     information is writen to a log file. An object which implements
    %     the CoreProgressInterface can be passed in for progress reporting.
    %
    %     Usage
    %     -----
    %
    %     You should create a single CoreReporting object and pass it into all the
    %     CoreMat routines you use in order to provide error, warning,
    %     message and progress reporting during execution of routines.
    %
    %     If you are not writing a gui application but would like a standard
    %     pop-up progress dialog to appear while waiting for plugins to execute,
    %     consider creating a CoreReportingDefault object instead. Use CoreReporting
    %     if you want to specify your own progress dialog, or specify a gui
    %     viewing panel, or if you want no progress dialog at all.
    %
    %         reporting = CoreReporting(progress_dialog, viewing_panel);
    %
    %             progress_dialog - a CoreProgressInterface object such as
    %                 a CoreProgressDialog for displaying a progress bar. You can omit this argument
    %                 or replace it with [] if you are writing scripts to run
    %                 in the background and do not want progress dialogs popping
    %                 up. Otherwise, you should create a CoreProgressDialog
    %                 or else implement your own progress class if you want
    %                 custom behaviour.
    %
    %     See CoreReportingIntertface.m for details of the methods this class
    %     implements.
    %
    %
    %     Licence
    %     -------
    %     Part of CoreMat. https://github.com/tomdoel/coremat
    %     Author: Tom Doel, 2013.  www.tomdoel.com
    %     Distributed under the MIT licence. Please see website for details.
    %

    properties (Constant)
        CancelErrorId = 'CoreReporting:UserCancel'
    end

    properties
        ProgressDialog  % Handle to a CoreProgressInterface object
    end

    properties (Access = private)
        LogFileName     % Full path to log file

        % Stack for nested progress reporting
        ProgressStack
        CurrentProgressStackItem
        ParentProgressStackItem
        VerboseMode
    end

    methods
        function obj = CoreReporting(progress_dialog, verbose_mode, log_file_name)
            if nargin > 0
                obj.ProgressDialog = progress_dialog;
            end
            if nargin > 1
                obj.VerboseMode = verbose_mode;
            else
                obj.VerboseMode = false;
            end
            if nargin > 2
                obj.LogFileName = log_file_name;
            else
                obj.LogFileName = fullfile(CoreDiskUtilities.GetUserDirectory, 'corereporting.log');
            end

            obj.ClearProgressStack;
        end

        function Log(obj, message)
            [calling_function, ~] = CoreErrorUtilities.GetCallingFunction(2);

            obj.AppendToLogFile([calling_function ': ' message]);
        end

        function LogVerbose(obj, message)
            if obj.VerboseMode
                [calling_function, ~] = CoreErrorUtilities.GetCallingFunction(2);
                obj.AppendToLogFile([calling_function ': ' message]);
            end
        end

        function ShowMessage(obj, identifier, message)
            [calling_function, ~] = CoreErrorUtilities.GetCallingFunction(2);
            if isempty(calling_function)
                calling_function = 'Command Window';
            end
            disp(message);
            obj.AppendToLogFile([calling_function ': ' identifier ':' message]);
        end

        function ShowMessageFromException(obj, identifier, message, ex)
            [calling_function, ~] = CoreErrorUtilities.GetCallingFunction(2);
            if isempty(calling_function)
                calling_function = 'Command Window';
            end
            message = [calling_function ': ' identifier ':' message '; Exception message:' ex.message ' : ' ex.stack(1).name];
            [summary, stack_text] = obj.GetExceptionSummary(ex);

            obj.AppendToLogFile(message);
            obj.AppendToLogFile(summary);
            obj.AppendToLogFile(stack_text);
            disp(message);
            disp(' ');
            disp('If reporting an error, please include the following information:');
            disp(['  ' summary]);
            disp(['  ' stack_text '\n']);
            disp(' ');
        end

        function ShowWarning(obj, identifier, message, supplementary_info)
            [calling_function, ~] = CoreErrorUtilities.GetCallingFunction(2);

            obj.AppendToLogFile([calling_function ': WARNING: ' identifier ':' message]);
            disp(['WARNING: ' message]);
            if nargin > 3 && ~isempty(supplementary_info)
                disp('Additional information on this warning:');
                disp(supplementary_info);
            end

        end

        function Error(obj, identifier, message)
            [calling_function, stack] = CoreErrorUtilities.GetCallingFunction(2);

            if ischar(calling_function) && length(calling_function) >= 13 && strcmp(calling_function(1:13), 'CoreReporting')
                [calling_function, stack] = CoreErrorUtilities.GetCallingFunction(3);
            end

            msgStruct = [];
            msgStruct.message = ['Error in function ' calling_function ': ' message];
            msgStruct.identifier = identifier;
            msgStruct.stack = stack;
            obj.AppendToLogFile([calling_function ': ERROR: ' identifier ':' message]);
            error(msgStruct);
        end

        function ErrorFromException(obj, identifier, message, ex)
            [calling_function, stack] = CoreErrorUtilities.GetCallingFunction(2);

            msgStruct = [];
            [summary, stack_text] = obj.GetExceptionSummary(ex);
            message_text = ['Error in function ' calling_function ': ' identifier ': ' message ' Exception message:' ex.message ' : ' ex.stack(1).name];
            msgStruct.message = message_text;
            msgStruct.identifier = identifier;
            msgStruct.stack = stack;

            obj.AppendToLogFile(message_text);
            obj.AppendToLogFile(summary);
            obj.AppendToLogFile(stack_text);

            disp(message_text);
            disp(' ');
            disp('If reporting an error, please include the following information');
            disp(['  ' summary]);
            disp(['  ' stack_text]);
            disp(' ');

            error(msgStruct);
        end

        function ShowProgress(obj, text)
            adjusted_text = obj.AdjustProgressText(text);

            if ~isempty(obj.ProgressDialog) && isvalid(obj.ProgressDialog)
                if nargin > 1
                    obj.ProgressDialog.SetProgressText(adjusted_text);
                else
                    obj.ProgressDialog.SetProgressText();
                end
                obj.CurrentProgressStackItem.Visible = true;
            end
        end

        function CompleteProgress(obj)
            if ~isempty(obj.ProgressDialog)
                if isempty(obj.ProgressStack) || ~obj.ParentProgressStackItem.Visible
                    obj.ProgressDialog.Complete;
                    obj.CurrentProgressStackItem.Visible = false;
                end
            end
        end

        function UpdateProgressMessage(obj, text)
            adjusted_text = obj.AdjustProgressText(text);

            if ~isempty(obj.ProgressDialog)
                obj.ProgressDialog.SetProgressText(adjusted_text);
                obj.CurrentProgressStackItem.Visible = true;
            end
        end

        function UpdateProgressValue(obj, progress_value)
            adjusted_value = obj.AdjustProgressValue(progress_value, []);

            if ~isempty(obj.ProgressDialog)
                obj.ProgressDialog.SetProgressValue(adjusted_value);
                obj.CurrentProgressStackItem.Visible = true;
            end
            obj.CheckForCancel;
        end

        function UpdateProgressStage(obj, progress_stage, num_stages)
            progress_value = 100*progress_stage/num_stages;
            value_change = 100/num_stages;
            adjusted_value = obj.AdjustProgressValue(progress_value, value_change);
            if ~isempty(obj.ProgressDialog)
                obj.ProgressDialog.SetProgressValue(adjusted_value);
                obj.CurrentProgressStackItem.Visible = true;
            end
            obj.CheckForCancel;
        end

        function UpdateProgressAndMessage(obj, progress_value, text)
            adjusted_value = obj.AdjustProgressValue(progress_value, []);
            adjusted_text = obj.AdjustProgressText(text);

            if ~isempty(obj.ProgressDialog)
                obj.ProgressDialog.SetProgressAndMessage(adjusted_value, adjusted_text);
                obj.CurrentProgressStackItem.Visible = true;
            end

            obj.CheckForCancel;

        end

        function cancelled = HasBeenCancelled(obj)
            if ~isempty(obj.ProgressDialog)
                cancelled = obj.ProgressDialog.CancelClicked;
            else
                cancelled = false;
            end
        end

        function CheckForCancel(obj)
            if obj.HasBeenCancelled
                obj.Error(CoreReporting.CancelErrorId, 'User cancelled');
            end
        end

        function PushProgress(obj)
            obj.ProgressStack(end + 1) = obj.ParentProgressStackItem;
            obj.ParentProgressStackItem = obj.CurrentProgressStackItem;
            obj.CurrentProgressStackItem = CoreProgressStackItem('', obj.ParentProgressStackItem.MinPosition, obj.ParentProgressStackItem.MaxPosition);
            obj.CurrentProgressStackItem.Visible = obj.ParentProgressStackItem.Visible;

        end

        function PopProgress(obj)
            obj.CurrentProgressStackItem = obj.ParentProgressStackItem;
            if isempty(obj.ProgressStack)
                obj.ParentProgressStackItem = [];
            else
                obj.ParentProgressStackItem = obj.ProgressStack(end);
                obj.ProgressStack(end) = [];
            end
        end

        function ClearProgressStack(obj)
            obj.ProgressStack = CoreProgressStackItem.empty(0);
            obj.CurrentProgressStackItem = CoreProgressStackItem('', 0, 100);
            obj.ParentProgressStackItem = CoreProgressStackItem('', 0, 100);
        end

        function ShowAndClearPendingMessages(obj)
        end

        function OpenPath(obj, file_path, message)
            disp([message, ': ', file_path]);
        end
    end

    methods (Access = private)
        function AppendToLogFile(obj, message)
            file_id = fopen(obj.LogFileName, 'at');
            message = [datestr(now) ': ' message];
            fprintf(file_id, '%s\n', message);
            fclose(file_id);
        end

        function [summary, stack] = GetExceptionSummary(obj, exc)
            stack = 'Stack:';
            for s = exc.stack'
                stack = [stack s.name '(' num2str(s.line) '); '];
            end
            summary = ['Error in ' exc.stack(1).name '(PTK' PTKSoftwareInfo.Version ') : ' exc.message];
        end

        function adjusted_text = AdjustProgressText(obj, text)
            adjusted_text = text;
            obj.CurrentProgressStackItem.ProgressText = text;
        end

        function adjusted_value = AdjustProgressValue(obj, value, value_change)
            if isempty(value_change)
                value_change = value - obj.CurrentProgressStackItem.LastProgressValue;
            end
            obj.CurrentProgressStackItem.LastProgressValue = value;

            scale = (obj.ParentProgressStackItem.MaxPosition - obj.ParentProgressStackItem.MinPosition)/100;
            adjusted_value = obj.ParentProgressStackItem.MinPosition + scale*value;
            obj.CurrentProgressStackItem.MinPosition = adjusted_value;
            if value_change > 0
                obj.CurrentProgressStackItem.MaxPosition = adjusted_value + scale*value_change;
            end
        end

        function SetValueChange(obj, value_change)
            value = obj.CurrentProgressStackItem.LastProgressValue;
            scale = (obj.ParentProgressStackItem.MaxPosition - obj.ParentProgressStackItem.MinPosition)/100;
            adjusted_value = obj.ParentProgressStackItem.MinPosition + scale*value;
            obj.CurrentProgressStackItem.MinPosition = adjusted_value;
            if value_change > 0
                obj.CurrentProgressStackItem.MaxPosition = adjusted_value + scale*value_change;
            end
        end
    end
end


classdef (Abstract) Directive < handle

    properties(SetAccess = protected)
        Values
    end

    properties(Abstract, SetAccess = immutable)
        Name
    end

    methods(Abstract, Access = protected)
        [success, toBeGarbadeCollected] = tryToupdateFromValue(obj, value)
    end

    methods(Sealed)
        function [success, toBeGarbadeCollected] = updateFromValue(obj, value)
            [success, toBeGarbadeCollected] = obj.tryToupdateFromValue(value);
            if ~success
                warning('MBeautifier:Directive:InvalidValue', ['The value "', char(value), '" is not a valid directive value for directive "', obj.Name, '".']);
            end
        end
    end
end


%  Footnote
%
%  ::
%
%     document.footnote('option_name',option_value);
%
%  Args:
%
%     varargin: arguments need to come in pairs
%
%        - **text** : footnote text
%
%


function CloseShapefile(fid,format)
%CLOSESHAPEFILE Writes footer to specified shapefile format
%
% //////////////////////////////////////////
% /// CLASSIFICATION: UNCLASSIFIED       ///
% //////////////////////////////////////////
%
% Function writes footer to Socet GRFX .grfx file, RemoteView .rvl file or
% Google Earth .kml file
%
%CLASSIFICATION:
%   Unclassified
%
%INPUTS:
%  fid      - required: File Handle of open Shape File
%  format   - required: 'grfx','rvl' or 'kml'
%
%OUTPUTS:
%
%VERSION:
%   1.0
%     - Tim Cox 20090324
%     - initial version

format = lower(format);

if (strcmp(format,'grfx') == 1)
    fprintf(fid,'</GrGmGraphicList>\n');
	fprintf(fid,'</GmLayer>\n');
	fprintf(fid,'</GmLayerList>\n');
	fprintf(fid,'</GmGraphicsLayout>\n');
	fprintf(fid,'</Graphics>\n');
    fclose(fid);
    return;
elseif (strcmp(format,'rvl') == 1)
    fprintf(fid,']\n');
	fprintf(fid,'>>\n');
	fprintf(fid,'>>\n');
    fclose(fid);
    return;
elseif (strcmp(format,'kml') == 1)
    fprintf(fid,'</Document>\n');
	fprintf(fid,'</kml>\n');
    fclose(fid);
    return;
else
    return;
end

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


function [execError] = getExecutionErrors()
%getExecutionErrors Summary of this function goes here
%   Detailed explanation goes here
    global script_execution_errors;
    execError = script_execution_errors;
end


mex libsvm_classifier_spider.cpp svm.cpp -I..\compiletools ..\compiletools\mexarg.cpp


main_fig = figure(...
'Units','characters',...
'Position',[135 4 198 56],...
'Visible',get(0,'defaultfigureVisible'),...
'Color',get(0,'defaultfigureColor'),...
'IntegerHandle','off',...
'MenuBar','none',...
'Name','CNMF_E',...
'NumberTitle','off',...
'Resize','on',...
'PaperPosition',get(0,'defaultfigurePaperPosition'),...
'ScreenPixelsPerInchMode','manual',...
'ParentMode','manual',...
'HandleVisibility','callback',...
'Tag','figure1' );


function DoHouseKeeping(added_paths, previous_open_figure_handles, bRestoreErrorStatus)

our_fig_hdl = [findall(0, 'Tag', 'a2hbc');findall(0, 'Tag', 'progress_bar')];
close(our_fig_hdl);

on_exit_open_handles = findall(0);
handles2_close = setdiff(on_exit_open_handles, previous_open_figure_handles);
delete(handles2_close);

prwaitbar('off')

if( bRestoreErrorStatus )
    dbclear if caught error
end

rmpath(added_paths);


function out = cfg_run_gunzip_files(job)
% Run gunzip on a list of files.
%
% This code is part of a batch job configuration system for MATLAB. See
%      help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging

% Volkmar Glauche
% $Id: cfg_run_gunzip_files.m 7499 2018-11-28 11:57:34Z guillaume $

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

if isempty(job.outdir) || isempty(job.outdir{1})
    out = gunzip(job.files);
else
    out = gunzip(job.files, job.outdir{1});
end
if ~job.keep
    delete(job.files{:});
end


function result = requestJavaAdapter(object)
%REQUESTJAVAADAPTER Support function for GUIDE

%   Copyright 1984-2006 The MathWorks, Inc.
%   $Revision: 1915 $

%%%%%%%  CAUTION                                           %%%%%%%%
%%%%%%%  This file is duplicated in both uitools and guide %%%%%%%%%
%%%%%%%  %TODO - determine if this functionality can be    %%%%%%%%%
%%%%%%%  broken out or replaced so this file doesn't exist %%%%%%%%%
%%%%%%%  in two places                                     %%%%%%%%%

  len = length(object);
  if len == 1
    if ishandle(object) && ~isjava(object)
      result = java(handle(object));
    else
      error('MATLAB:requestJavaAdapter:InvalidInput', '''requestJavaAdapter'' argument must be a handle list.');
    end
  else
    if ~isempty(object) && all(ishandle(object) & ~isjava(object))
      result = cell(len, 1);
      for i = 1:len
        result{i} = java(handle(object(i)));
      end
    else
      error('MATLAB:requestJavaAdapter:InvalidArgument', '''requestJavaAdapter'' argument must be a handle list.');
    end
  end


function [res, isCancel] = java_dialog( msgType, msg, msgTitle, jParent, varargin )
% JAVA_DIALOG: Display a Java-based dialog.
%
% USAGE:  [res, isCancel] = java_dialog( msgType, msg )
%         [res, isCancel] = java_dialog( msgType, msg, msgTitle )
%         [res, isCancel] = java_dialog( msgType, msg, msgTitle, jParent )
%         [res, isCancel] = java_dialog( msgType, msg, msgTitle, jParent, OPTIONS )
%
% INPUT:
%    - msgType  : String that defines the icon and controls displayed in the dialog box. Possible values:
%                 {'error', 'warning', 'msgbox', 'confirm', 'question', 'input', 'checkbox', 'radio', 'combo', 'hotkey', 'color'}
%    - msg      : Message in the dialog box
%                 (can be a cell array of strings for 'input' message type)
%    - msgTitle : Title of the dialog box
%    - jParent  : Handle to the parent JFrame.
%                 If no parent, or unknown, set to [].
%    - OPTIONS  : Depends on the dialog type
%                  - 'question' : OPTIONS = buttonList
%                                 OPTIONS = buttonList, defaultButton
%                  - 'combo'    : OPTIONS = buttonList
%                                 OPTIONS = buttonList, defaultButton
%                  - 'input'    : OPTIONS = defaultVals
%                  - 'checkbox' : OPTIONS = buttonList
%                                 OPTIONS = buttonList, defaultVals
%                  - 'radio'    : OPTIONS = buttonList
%                                 OPTIONS = buttonList, defaultInd
%                  - 'color'    : No options
% OUTPUT:
%    - res      : Depends on the dialog type
%                  - 'error', 'warning', 'msgbox', 'confirm':
%                        1 if user validated the dialog, 0 else.
%                  - 'question':
%                        'Yes' if user clicked yes button, 'No' for no button,
%                        [] if user closed the dialog.
%                  - 'input':
%                        str or cell array of str corresponding to selected input
%                        [] if dialog canceled
%                  - 'radio':
%                        [] if user closed dialog or cancelled, else index of choice.
%                  - 'combo':
%                        value of choice (empty if user cancelled or closed dialog)
%                  - 'hotkey':
%                        [] if user closed dialog or cancelled, else chosen hotkey
%    - isCancel : 1 if the user pressed the cancel button or closed the
%                 window (0 else). Always 0 for dialog types 'error', 'warning' and 'msgbox'

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

global GlobalData;

% Java imports
import org.brainstorm.dialogs.*;

% Get brainstorm frame
jBstFrame = bst_get('BstFrame');

% Parse inputs
if (nargin < 1)
    error('Invalid call to java_dialog()');
end
if (nargin < 2)
    msg = '';
end
if (nargin < 3)
    msgTitle = '';
end
if (nargin < 4) || isempty(jParent)
    jParent = jBstFrame;
end
isCancel = 1;

% Hide progress bar
isProgress = bst_progress('isvisible');
if isProgress
    bst_progress('hide');
end

% Headless dialog displayed in command line
if bst_get('GuiLevel') < 0
    switch(lower(msgType))
        case 'error'
            disp(['Error: ' msg]);
            isCancel = 0;
            res = 1;
        case 'warning'
            disp(['Warning: ' msg]);
            isCancel = 0;
            res = 1;
        case 'msgbox'
            disp(msg);
            isCancel = 0;
            res = 1;
        case 'confirm'
            response = lower(strtrim(input([msg ' (y/n) '], 's')));
            if ismember(response, {'y', 'yes'})
                isCancel = 0;
                res = 1;
            elseif ismember(response, {'n', 'no'})
                isCancel = 0;
                res = 0;
            else
                isCancel = 1;
                res = 0;
            end
        case 'question'
            if length(varargin) < 1 || isempty(varargin{1})
                answers = {'Yes', 'No'};
            else
                answers = varargin{1};
            end
            nAnswers = length(answers);

            % Display question and possible answers
            disp(msg);
            for iAnswer = 1:nAnswers
                disp([num2str(iAnswer) '. ' answers{iAnswer}]);
            end
            disp(' ');

            % Validate user selection
            response = str2num(input('Select the number of your answer: ', 's'));
            if ~isempty(response) && response >= 1 && response <= nAnswers
                res = answers{response};
                isCancel = 0;
            else
                res = [];
                isCancel = 1;
            end
        otherwise
            error('Unsupported call of java_dialog in headless mode.');
    end
    return;
end

% Get all the modal JDialogs
if ~isempty(jBstFrame)
    jDialogModal = [];
    jDialogAlwaysOnTop = [];
    for i=1:length(GlobalData.Program.GUI.panels)
        panelContainer = get(GlobalData.Program.GUI.panels(i), 'container');
        panelContainer = panelContainer.handle{1};
        if isa(panelContainer, 'javax.swing.JDialog') && panelContainer.isModal()
            % A modal JDialog is found => Set it non non-modal
            jDialogModal = panelContainer;
            jDialogModal.setModal(0);
        end
        if (isa(panelContainer, 'javax.swing.JDialog') || isa(panelContainer, 'javax.swing.JFrame')) && panelContainer.isAlwaysOnTop()
            % An AlwaysOnTop frame is found => Remove always on top attribute
            jDialogAlwaysOnTop = panelContainer;
            jDialogAlwaysOnTop.setAlwaysOnTop(0);
        end
    end
end

% Check that parent frame is visible
if ~isempty(jParent) && ~jParent.isVisible()
    jParent = [];
end

% Show java dialog
switch(lower(msgType))
    case 'error'
        if isempty(msgTitle)
            msgTitle = 'Error';
        end
        java_call('javax.swing.JOptionPane', 'showMessageDialog', 'Ljava.awt.Component;Ljava.lang.Object;Ljava.lang.String;I', jParent, msg, msgTitle, javax.swing.JOptionPane.ERROR_MESSAGE);
        isCancel = 0;
        res = 1;
    case 'errorhelp'
        if isempty(msgTitle)
            msgTitle = 'Error';
        end
        if ~java_call('org.brainstorm.dialogs.MsgServer', 'dlgErrorHelp', 'Ljava.awt.Component;Ljava.lang.String;Ljava.lang.String;[Ljava.lang.String;Ljava.lang.String;', jParent, msg, msgTitle);
            web('https://neuroimage.usc.edu/forums/', '-browser');
        end
        isCancel = 0;
        res = 1;
    case 'warning'
        if isempty(msgTitle)
            msgTitle = 'Warning';
        end
        java_call('javax.swing.JOptionPane', 'showMessageDialog', 'Ljava.awt.Component;Ljava.lang.Object;Ljava.lang.String;I', jParent, msg, msgTitle, javax.swing.JOptionPane.WARNING_MESSAGE);
        isCancel = 0;
        res = 1;
    case 'msgbox'
        if isempty(msgTitle)
            msgTitle = 'Information';
        end
        java_call('javax.swing.JOptionPane', 'showMessageDialog', 'Ljava.awt.Component;Ljava.lang.Object;Ljava.lang.String;I', jParent, msg, msgTitle, javax.swing.JOptionPane.INFORMATION_MESSAGE);
        isCancel = 0;
        res = 1;
    case 'confirm'
        if isempty(msgTitle)
            msgTitle = 'Confirmation';
        end
        reponse = java_call('javax.swing.JOptionPane', 'showConfirmDialog', 'Ljava.awt.Component;Ljava.lang.Object;Ljava.lang.String;I', jParent, msg, msgTitle, javax.swing.JOptionPane.YES_NO_OPTION);
        if reponse == javax.swing.JOptionPane.CLOSED_OPTION
            res = 0;
            isCancel = 1;
        else
            res = (reponse == javax.swing.JOptionPane.OK_OPTION);
            isCancel = 0;
        end
    % OPTIONS: buttonList; buttonDefault
    case 'question'
        % Button list
        if (length(varargin) < 1)
            buttonList = {'Yes','No'};
        elseif iscell(varargin{1})
            buttonList = varargin{1};
        else
            error('Invalid call.');
        end
        % Default button
        if (length(varargin) < 2)
            buttonDefault = buttonList{1};
        elseif ischar(varargin{2})
            buttonDefault = varargin{2};
        else
            error('Invalid call.');
        end
        % Show dialog
        java_res = java_call('org.brainstorm.dialogs.MsgServer', 'dlgQuest', 'Ljava.awt.Component;Ljava.lang.String;Ljava.lang.String;[Ljava.lang.String;Ljava.lang.String;', jParent, msg, msgTitle, buttonList, buttonDefault);
        if isempty(char(java_res))
            res = [];
            isCancel = 1;
        else
            res = char(java_res);
            isCancel = 0;
        end

    % OPTIONS: defaultVals
    case 'input'
        % Default values
        if (length(varargin) < 1)
            if ischar(msg)
                defaultVals = '';
            elseif iscell(msg)
                defaultVals = repmat({''}, 1, length(msg));
            end
        elseif ~((ischar(msg) && ischar(varargin{1})) || (iscell(msg) && iscell(varargin{1}) && (length(varargin{1}) == length(msg))))
            error('First and third argument must have the same type and the same size.');
        else
            defaultVals = varargin{1};
        end
        % === CALL INPUT DIALOG ===
        if iscell(msg)
            java_res = java_call('org.brainstorm.dialogs.MsgServer', 'dlgInput', 'Ljava/awt/Component;[Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;', jParent, msg, msgTitle, defaultVals);
            if ~isempty(java_res)
                isCancel = 0;
            end
        else
            java_res = java_call('org.brainstorm.dialogs.MsgServer', 'dlgInput', 'Ljava/awt/Component;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;', jParent, msg, msgTitle, defaultVals);
            if (isa(java_res, 'java.lang.String') || ischar(java_res)) && ~isequal(char(java_res), '#cancel#')
                isCancel = 0;
            end
        end
        % === GET RESULTS ===
        if isCancel
            res = [];
        elseif isempty(java_res)
            res = '';
        elseif ischar(msg)
            res = char(java_res);
            isCancel = 0;
        elseif iscell(msg)
            nbInputs = numel(java_res);
            res = cell(1, nbInputs);
            for i=1:nbInputs
                res{i} = char(java_res(i));
            end
            isCancel = 0;
        end

    % Options: buttonList, defaultVal
    case 'checkbox'
        % List of options
        if iscell(varargin{1})
            buttonList = varargin{1};
        else
            error('Invalid call.');
        end
        % Default values
        if (length(varargin) >= 2)
            defaultVal = varargin{2};
        else
            defaultVal = [];
        end

        % Create a dialog message
        if ~isempty(buttonList)
            jPanel = gui_river([2,2], [3,3,3,3]);
            jCheck = javaArray('javax.swing.JCheckBox', length(buttonList));
            isLongText = any(cellfun(@length, buttonList) > 20);
            for i = 1:length(buttonList)
                % Create check box
                jCheck(i) = javax.swing.JCheckBox(buttonList{i});
                % Default value
                if ~isempty(defaultVal)
                    jCheck(i).setSelected(defaultVal(i));
                end
                % Add: right after of on the next row ?
                if isLongText
                    jPanel.add('br', jCheck(i));
                else
                    if (mod(i-1, 5) == 0)
                        jPanel.add('tab br', jCheck(i));
                    else
                        jPanel.add('tab', jCheck(i));
                    end
                end
            end
        end
        message = javaArray('java.lang.Object',2);
        message(1) = java.lang.String(msg);
        message(2) = jPanel;
        % Show question
        answer = java_call('javax.swing.JOptionPane', 'showConfirmDialog', 'Ljava.awt.Component;Ljava.lang.Object;Ljava.lang.String;I', jParent, message, msgTitle, javax.swing.JOptionPane.OK_CANCEL_OPTION);
        if (answer ~= javax.swing.JOptionPane.OK_OPTION)
            res = [];
        else
            isCancel = 0;
            % Else look for the selected options
            if isempty(defaultVal)
                res = {};
                for i = 1:length(buttonList)
                    if (jCheck(i).isSelected())
                        res{end+1} = buttonList{i};
                    end
                end
            else
                res = [];
                for i = 1:length(buttonList)
                    res(end+1) = double(jCheck(i).isSelected());
                end
            end
        end

    % Options: buttonList, defaultInd
    case 'radio'
        % List of options
        if iscell(varargin{1})
            buttonList = varargin{1};
        else
            error('Invalid call.');
        end
        % Default values
        if (length(varargin) >= 2)
            defaultInd = varargin{2};
        else
            defaultInd = [];
        end

        % Create a dialog message
        if ~isempty(buttonList)
            jPanel = gui_river([2,2], [3,3,3,3]);
            jRadio = javaArray('javax.swing.JRadioButton', length(buttonList));
            jGroup = javax.swing.ButtonGroup;
            for i = 1:length(buttonList)
                % Create check box
                jRadio(i) = javax.swing.JRadioButton(buttonList{i});
                % Add it to button group
                jGroup.add(jRadio(i));
                % Box size
                isLongText = (length(buttonList{i}) > 10);
                if ~isLongText
                    jRadio(i).setPreferredSize(java_scaled('dimension', 80, 20));
                end
                % Default value
                if ~isempty(defaultInd) && (i == defaultInd)
                    jRadio(i).setSelected(1);
                end
                % Add: right after of on the next row ?
                if (mod(i-1, 5) == 0) || isLongText
                    jPanel.add('br', jRadio(i));
                else
                    jPanel.add(jRadio(i));
                end
            end
        end
        message = javaArray('java.lang.Object',2);
        message(1) = java.lang.String(msg);
        message(2) = jPanel;
        % Show question
        answer = java_call('javax.swing.JOptionPane', 'showConfirmDialog', 'Ljava.awt.Component;Ljava.lang.Object;Ljava.lang.String;I', jParent, message, msgTitle, javax.swing.JOptionPane.OK_CANCEL_OPTION);
        if (answer ~= javax.swing.JOptionPane.OK_OPTION)
            res = [];
        else
            isCancel = 0;
            % Else look for the selected option
            for i = 1:length(jRadio)
                if (jRadio(i).isSelected())
                    res = i;
                    break;
                end
            end
        end

    % OPTIONS: buttonList; buttonDefault
    case 'combo'
        % List of options
        if iscell(varargin{1})
            buttonList = varargin{1};
        else
            error('Invalid call.');
        end
        % Default values
        if (length(varargin) >= 2)
            iSelect = find(strcmpi(varargin{2}, buttonList));
        else
            iSelect = [];
        end

        % Create a dialog message
        jCombo = gui_component('ComboBox', [], [], [], {buttonList}, [], [], []);
        jCombo.setMaximumRowCount(30);
        % Default selection
        if ~isempty(iSelect)
            jCombo.setSelectedIndex(iSelect - 1);
        end
        % Message
        message = javaArray('java.lang.Object',2);
        message(1) = java.lang.String(msg);
        message(2) = jCombo;
        % Show question
        answer = java_call('javax.swing.JOptionPane', 'showConfirmDialog', 'Ljava.awt.Component;Ljava.lang.Object;Ljava.lang.String;I', jParent, message, msgTitle, javax.swing.JOptionPane.OK_CANCEL_OPTION);
        if (answer ~= javax.swing.JOptionPane.OK_OPTION)
            res = [];
        else
            isCancel = 0;
            iSelect = jCombo.getSelectedIndex() + 1;
            res = buttonList{iSelect};
        end

    % Dialog for hotkey input from user
    case 'hotkey'
        % Open up hotkey dialog
        fontSize = round(11 * bst_get('InterfaceScaling') / 100);
        dialog = HotkeyDialog(fontSize);
        % If a valid key was selected, return it. Otherwise, cancel
        if dialog.hasKey()
            res = dialog.getKey();
            isCancel = 0;
        else
            res = [];
            isCancel = 1;
        end

    % Color picker
    case 'color'
        % Create color chooser
        if ~isfield(GlobalData.Program, 'ColorChooser') || isempty(GlobalData.Program.ColorChooser)
            jColorChooser = javax.swing.JColorChooser();
            GlobalData.Program.ColorChooser = javax.swing.JColorChooser();
        else
            jColorChooser = GlobalData.Program.ColorChooser;
        end
        % Show question
        answer = java_call('javax.swing.JOptionPane', 'showConfirmDialog', 'Ljava.awt.Component;Ljava.lang.Object;Ljava.lang.String;I', jParent, jColorChooser, msgTitle, javax.swing.JOptionPane.OK_CANCEL_OPTION, javax.swing.JOptionPane.PLAIN_MESSAGE);
        if (answer ~= javax.swing.JOptionPane.OK_OPTION)
            res = [];
        else
            isCancel = 0;
            color = jColorChooser.getColor();
            res = double([color.getRed(), color.getGreen(), color.getBlue()]) ./ 255;
        end
end

% Restore modal panels
if ~isempty(jBstFrame)
    if ~isempty(jDialogModal)
        jDialogModal.setModal(1);
    end
    if ~isempty(jDialogAlwaysOnTop)
        jDialogAlwaysOnTop.setAlwaysOnTop(1);
    end
end

% Restore progress bar
if isProgress
    bst_progress('show');
end


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

% Last Modified by GUIDE v2.5 03-Dec-2018 16:58:14

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

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

    centerUIFigure(hObject);

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

    populateGUI(handles, action);

    % Update handles structure
    guidata(hObject, handles);

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

function populateGUI(handles, action)

    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_EditActionSetClampStateGUI_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');

        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; %TODO Create this field

        varargout{1} = true;
        close(handles.lvd_EditActionSetClampStateGUI);
    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_EditActionSetClampStateGUI);

% --- 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_EditActionSetClampStateGUI);

% --- 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_EditActionSetClampStateGUI or any of its controls.
function lvd_EditActionSetClampStateGUI_WindowKeyPressFcn(hObject, eventdata, handles)
% hObject    handle to lvd_EditActionSetClampStateGUI (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_EditActionSetClampStateGUI);
    end


function manageMiji(varargin)
	% Controls starting and stopping of Miji in a way to reduce issues
	% Biafra Ahanonu
	% started: 2019.04.08
	% inputs
		%
	% outputs
		%

	ciapkg.io.manageMiji('passArgs', varargin);
end


%YUVCLOSE	Close a YUV4MPEG file
%
%	yuvclose(yuv)
%
%	Close an open YUV file.

% Copyright (C) 1993-2011, by Peter I. Corke
%
% This file is part of The Machine Vision Toolbox for Matlab (MVTB).
%
% MVTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% MVTB 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 Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with MVTB.  If not, see <http://www.gnu.org/licenses/>.

function yuvclose(yuv)

	fclose(yuv.fp);


classdef BoxPanel < uix.Panel & uix.mixin.Panel
    %uix.BoxPanel  Box panel
    %
    %  p = uix.BoxPanel(p1,v1,p2,v2,...) constructs a box panel and sets
    %  parameter p1 to value v1, etc.
    %
    %  A box panel is a decorated container with a title box, border, and
    %  buttons to dock and undock, minimize, get help, and close.  A box
    %  panel shows one of its contents and hides the others.
    %
    %  See also: uix.Panel, uipanel, uix.CardPanel

    %  Copyright 2009-2016 The MathWorks, Inc.
    %  $Revision: 1599 $ $Date: 2018-04-07 07:15:03 +1000 (Sat, 07 Apr 2018) $

    properties( Dependent )
        TitleColor % title background color [RGB]
        Minimized % minimized [true|false]
        MinimizeFcn % minimize callback
        Docked % docked [true|false]
        DockFcn % dock callback
        HelpFcn % help callback
        CloseRequestFcn % close request callback
    end

    properties( Dependent, SetAccess = private )
        TitleHeight % title panel height [pixels]
    end

    properties( Access = private )
        TitleBox % title bar box
        TitleText % title text label
        EmptyTitle = '' % title when empty, [] otherwise
        TitleAccess = 'public' % 'private' when getting or setting Title, 'public' otherwise
        TitleHeight_ = -1 % cache of title text height (-1 denotes stale cache)
        MinimizeButton % title button
        DockButton % title button
        HelpButton % title button
        CloseButton % title button
        Docked_ = true % backing for Docked
        Minimized_ = false % backing for Minimized
    end

    properties( Constant, Access = private )
        NullTitle = char.empty( [2 0] ) % an obscure empty string, the actual panel Title
        BlankTitle = ' ' % a non-empty blank string, the empty uicontrol String
    end

    properties
        MaximizeTooltipString = 'Expand this panel' % tooltip string
        MinimizeTooltipString = 'Collapse this panel' % tooltip string
        UndockTooltipString = 'Undock this panel' % tooltip string
        DockTooltipString = 'Dock this panel' % tooltip string
        HelpTooltipString = 'Get help on this panel' % tooltip string
        CloseTooltipString = 'Close this panel' % tooltip string
    end

    methods

        function obj = BoxPanel( varargin )
            %uix.BoxPanel  Box panel constructor
            %
            %  p = uix.BoxPanel() constructs a box panel.
            %
            %  p = uix.BoxPanel(p1,v1,p2,v2,...) sets parameter p1 to value
            %  v1, etc.

            % Define default colors
            foregroundColor = [1 1 1];
            backgroundColor = [0.05 0.25 0.5];

            % Set default colors
            obj.ForegroundColor = foregroundColor;

            % Create panels and decorations
            titleBox = uix.HBox( 'Internal', true, 'Parent', obj, ...
                'Units', 'pixels', 'BackgroundColor', backgroundColor );
            titleText = uix.Text( 'Parent', titleBox, ...
                'ForegroundColor', foregroundColor, ...
                'BackgroundColor', backgroundColor, ...
                'String', obj.BlankTitle, 'HorizontalAlignment', 'left' );

            % Create buttons
            minimizeButton = uix.Text( ...
                'ForegroundColor', foregroundColor, ...
                'BackgroundColor', backgroundColor, ...
                'FontWeight', 'bold', 'Enable', 'on' );
            dockButton = uix.Text( ...
                'ForegroundColor', foregroundColor, ...
                'BackgroundColor', backgroundColor, ...
                'FontWeight', 'bold', 'Enable', 'on' );
            helpButton = uix.Text( ...
                'ForegroundColor', foregroundColor, ...
                'BackgroundColor', backgroundColor, ...
                'FontWeight', 'bold', 'String', '?', ...
                'TooltipString', obj.HelpTooltipString, 'Enable', 'on' );
            closeButton = uix.Text( ...
                'ForegroundColor', foregroundColor, ...
                'BackgroundColor', backgroundColor, ...
                'FontWeight', 'bold', 'String', char( 215 ), ...
                'TooltipString', obj.CloseTooltipString, 'Enable', 'on' );

            % Store properties
            obj.Title = obj.NullTitle;
            obj.TitleBox = titleBox;
            obj.TitleText = titleText;
            obj.MinimizeButton = minimizeButton;
            obj.DockButton = dockButton;
            obj.HelpButton = helpButton;
            obj.CloseButton = closeButton;

            % Create listeners
            addlistener( obj, 'BorderWidth', 'PostSet', ...
                @obj.onBorderWidthChanged );
            addlistener( obj, 'BorderType', 'PostSet', ...
                @obj.onBorderTypeChanged );
            addlistener( obj, 'FontAngle', 'PostSet', ...
                @obj.onFontAngleChanged );
            addlistener( obj, 'FontName', 'PostSet', ...
                @obj.onFontNameChanged );
            addlistener( obj, 'FontSize', 'PostSet', ...
                @obj.onFontSizeChanged );
            addlistener( obj, 'FontUnits', 'PostSet', ...
                @obj.onFontUnitsChanged );
            addlistener( obj, 'FontWeight', 'PostSet', ...
                @obj.onFontWeightChanged );
            addlistener( obj, 'ForegroundColor', 'PostSet', ...
                @obj.onForegroundColorChanged );
            addlistener( obj, 'Title', 'PreGet', ...
                @obj.onTitleReturning );
            addlistener( obj, 'Title', 'PostGet', ...
                @obj.onTitleReturned );
            addlistener( obj, 'Title', 'PostSet', ...
                @obj.onTitleChanged );

            % Draw buttons
            obj.redrawButtons()

            % Set properties
            try
                uix.set( obj, varargin{:} )
            catch e
                delete( obj )
                e.throwAsCaller()
            end

        end % constructor

    end % structors

    methods

        function value = get.TitleColor( obj )

            value = obj.TitleBox.BackgroundColor;

        end % get.TitleColor

        function set.TitleColor( obj, value )

            % Set
            obj.TitleBox.BackgroundColor = value;
            obj.TitleText.BackgroundColor = value;
            obj.MinimizeButton.BackgroundColor = value;
            obj.DockButton.BackgroundColor = value;
            obj.HelpButton.BackgroundColor = value;
            obj.CloseButton.BackgroundColor = value;

        end % set.TitleColor

        function value = get.CloseRequestFcn( obj )

            value = obj.CloseButton.Callback;

        end % get.CloseRequestFcn

        function set.CloseRequestFcn( obj, value )

            % Set
            obj.CloseButton.Callback = value;

            % Mark as dirty
            obj.redrawButtons()

        end % set.CloseRequestFcn

        function value = get.DockFcn( obj )

            value = obj.DockButton.Callback;

        end % get.DockFcn

        function set.DockFcn( obj, value )

            % Set
            obj.DockButton.Callback = value;

            % Mark as dirty
            obj.redrawButtons()

        end % set.DockFcn

        function value = get.HelpFcn( obj )

            value = obj.HelpButton.Callback;

        end % get.HelpFcn

        function set.HelpFcn( obj, value )

            % Set
            obj.HelpButton.Callback = value;

            % Mark as dirty
            obj.redrawButtons()

        end % set.HelpFcn

        function value = get.MinimizeFcn( obj )

            value = obj.MinimizeButton.Callback;

        end % get.MinimizeFcn

        function set.MinimizeFcn( obj, value )

            % Set
            obj.MinimizeButton.Callback = value;
            obj.TitleText.Callback = value;
            if isempty( value )
                obj.TitleText.Enable = 'inactive';
            else
                obj.TitleText.Enable = 'on';
            end

            % Mark as dirty
            obj.redrawButtons()

        end % set.MinimizeFcn

        function value = get.Docked( obj )

            value = obj.Docked_;

        end % get.Docked

        function set.Docked( obj, value )

            % Check
            assert( islogical( value ) && isequal( size( value ), [1 1] ), ...
                'uix:InvalidPropertyValue', ...
                'Property ''Docked'' must be true or false.' )

            % Set
            obj.Docked_ = value;

            % Mark as dirty
            obj.redrawButtons()

        end % set.Docked

        function value = get.Minimized( obj )

            value = obj.Minimized_;

        end % get.Minimized

        function set.Minimized( obj, value )

            % Check
            assert( islogical( value ) && isequal( size( value ), [1 1] ), ...
                'uix:InvalidPropertyValue', ...
                'Property ''Minimized'' must be true or false.' )

            % Set
            obj.Minimized_ = value;

            % Show selected child
            obj.showSelection()

            % Mark as dirty
            obj.Dirty = true;

        end % set.Minimized

        function value = get.TitleHeight( obj )

            value = obj.TitleBox.Position(4);

        end % get.TitleHeight

        function set.MaximizeTooltipString( obj, value )

            % Check
            assert( ischar( value ), ...
                'uix:InvalidPropertyValue', ...
                'Property ''MaximizeTooltipString'' must be a string.' )

            % Set
            obj.MaximizeTooltipString = value;

            % Mark as dirty
            obj.redrawButtons()

        end % set.MaximizeTooltipString

        function set.MinimizeTooltipString( obj, value )

            % Check
            assert( ischar( value ), ...
                'uix:InvalidPropertyValue', ...
                'Property ''MinimizeTooltipString'' must be a string.' )

            % Set
            obj.MinimizeTooltipString = value;

            % Mark as dirty
            obj.redrawButtons()

        end % set.MinimizeTooltipString

        function set.UndockTooltipString( obj, value )

            % Check
            assert( ischar( value ), ...
                'uix:InvalidPropertyValue', ...
                'Property ''UndockTooltipString'' must be a string.' )

            % Set
            obj.UndockTooltipString = value;

            % Mark as dirty
            obj.redrawButtons()

        end % set.UndockTooltipString

        function set.DockTooltipString( obj, value )

            % Check
            assert( ischar( value ), ...
                'uix:InvalidPropertyValue', ...
                'Property ''DockTooltipString'' must be a string.' )

            % Set
            obj.DockTooltipString = value;

            % Mark as dirty
            obj.redrawButtons()

        end % set.DockTooltipString

        function set.HelpTooltipString( obj, value )

            % Check
            assert( ischar( value ), ...
                'uix:InvalidPropertyValue', ...
                'Property ''HelpTooltipString'' must be a string.' )

            % Set
            obj.HelpTooltipString = value;

            % Mark as dirty
            obj.redrawButtons()

        end % set.HelpTooltipString

        function set.CloseTooltipString( obj, value )

            % assert that value is a char array
            assert( ischar( value ), ...
                'uix:InvalidPropertyValue', ...
                'Property ''CloseTooltipString'' must be a string.' )

            obj.CloseTooltipString = value;

            % Mark as dirty
            obj.redrawButtons()

        end % set.CloseTooltipString

    end % accessors

    methods( Access = private )

        function onBorderWidthChanged( obj, ~, ~ )

            % Mark as dirty
            obj.Dirty = true;

        end % onBorderWidthChanged

        function onBorderTypeChanged( obj, ~, ~ )

            % Mark as dirty
            obj.Dirty = true;

        end % onBorderTypeChanged

        function onFontAngleChanged( obj, ~, ~ )

            obj.TitleText.FontAngle = obj.FontAngle;

        end % onFontAngleChanged

        function onFontNameChanged( obj, ~, ~ )

            % Set
            obj.TitleText.FontName = obj.FontName;

            % Mark as dirty
            obj.TitleHeight_ = -1;
            obj.Dirty = true;

        end % onFontNameChanged

        function onFontSizeChanged( obj, ~, ~ )

            % Set
            fontSize = obj.FontSize;
            obj.TitleText.FontSize = fontSize;
            obj.HelpButton.FontSize = fontSize;
            obj.CloseButton.FontSize = fontSize;
            obj.DockButton.FontSize = fontSize;
            obj.MinimizeButton.FontSize = fontSize;

            % Mark as dirty
            obj.TitleHeight_ = -1;
            obj.Dirty = true;

        end % onFontSizeChanged

        function onFontUnitsChanged( obj, ~, ~ )

            fontUnits = obj.FontUnits;
            obj.TitleText.FontUnits = fontUnits;
            obj.HelpButton.FontUnits = fontUnits;
            obj.CloseButton.FontUnits = fontUnits;
            obj.DockButton.FontUnits = fontUnits;
            obj.MinimizeButton.FontUnits = fontUnits;

        end % onFontUnitsChanged

        function onFontWeightChanged( obj, ~, ~ )

            obj.TitleText.FontWeight = obj.FontWeight;

        end % onFontWeightChanged

        function onForegroundColorChanged( obj, ~, ~ )

            foregroundColor = obj.ForegroundColor;
            obj.TitleText.ForegroundColor = foregroundColor;
            obj.MinimizeButton.ForegroundColor = foregroundColor;
            obj.DockButton.ForegroundColor = foregroundColor;
            obj.HelpButton.ForegroundColor = foregroundColor;
            obj.CloseButton.ForegroundColor = foregroundColor;

        end % onForegroundColorChanged

        function onTitleReturning( obj, ~, ~ )

            if strcmp( obj.TitleAccess, 'public' )

                obj.TitleAccess = 'private'; % start
                if ischar( obj.EmptyTitle )
                    obj.Title = obj.EmptyTitle;
                else
                    obj.Title = obj.TitleText.String;
                end

            end

        end % onTitleReturning

        function onTitleReturned( obj, ~, ~ )

            obj.Title = obj.NullTitle; % unset Title
            obj.TitleAccess = 'public'; % finish

        end % onTitleReturned

        function onTitleChanged( obj, ~, ~ )

            if strcmp( obj.TitleAccess, 'public' )

                % Set
                obj.TitleAccess = 'private'; % start
                title = obj.Title;
                if isempty( title )
                    obj.EmptyTitle = title; % store
                    obj.TitleText.String = obj.BlankTitle; % set String to blank
                else
                    obj.EmptyTitle = []; % not empty
                    obj.TitleText.String = title; % set String to title
                end
                obj.Title = obj.NullTitle; % unset Title
                obj.TitleAccess = 'public'; % finish

                % Mark as dirty
                obj.TitleHeight_ = -1;
                obj.Dirty = true;

            end

        end % onTitleChanged

    end % property event handlers

    methods( Access = protected )

        function redraw( obj )
            %redraw  Redraw
            %
            %  p.redraw() redraws the panel.
            %
            %  See also: redrawButtons

            % Compute positions
            bounds = hgconvertunits( ancestor( obj, 'figure' ), ...
                [0 0 1 1], 'normalized', 'pixels', obj );
            tX = 1;
            tW = max( bounds(3), 1 );
            tH = obj.TitleHeight_; % title height
            if tH == -1 % cache stale, refresh
                tH = ceil( obj.TitleText.Extent(4) );
                obj.TitleHeight_ = tH; % store
            end
            tY = 1 + bounds(4) - tH;
            p = obj.Padding_;
            cX = 1 + p;
            cW = max( bounds(3) - 2 * p, 1 );
            cH = max( bounds(4) - tH - 2 * p, 1 );
            cY = tY - p - cH;
            contentsPosition = [cX cY cW cH];

            % Redraw contents
            selection = obj.Selection_;
            if selection ~= 0
                uix.setPosition( obj.Contents_(selection), contentsPosition, 'pixels' )
            end
            obj.TitleBox.Position = [tX tY tW tH];
            obj.redrawButtons()

        end % redraw

        function showSelection( obj )
            %showSelection  Show selected child, hide the others
            %
            %  c.showSelection() shows the selected child of the container
            %  c, and hides the others.

            % Call superclass method
            showSelection@uix.mixin.Panel( obj )

            % If minimized, hide selected contents too
            selection = obj.Selection_;
            if selection ~= 0 && obj.Minimized_
                child = obj.Contents_(selection);
                child.Visible = 'off';
                if isa( child, 'matlab.graphics.axis.Axes' )
                    child.ContentsVisible = 'off';
                end
                % As a remedy for g1100294, move off-screen too
                margin = 1000;
                if isa( child, 'matlab.graphics.axis.Axes' ) ...
                        && strcmp(child.ActivePositionProperty, 'outerposition' )
                    child.OuterPosition(1) = -child.OuterPosition(3)-margin;
                else
                    child.Position(1) = -child.Position(3)-margin;
                end
            end

        end % showSelection

    end % template methods

    methods( Access = private )

        function redrawButtons( obj )
            %redrawButtons  Redraw buttons
            %
            %  p.redrawButtons() redraws the titlebar buttons.
            %
            %  Buttons use unicode arrow symbols:
            %  https://en.wikipedia.org/wiki/Arrow_%28symbol%29#Arrows_in_Unicode

            % Retrieve button box and buttons
            box = obj.TitleBox;
            titleText = obj.TitleText;
            minimizeButton = obj.MinimizeButton;
            dockButton = obj.DockButton;
            helpButton = obj.HelpButton;
            closeButton = obj.CloseButton;

            % Detach all buttons
            titleText.Parent = [];
            minimizeButton.Parent = [];
            dockButton.Parent = [];
            helpButton.Parent = [];
            closeButton.Parent = [];

            % Attach active buttons
            titleText.Parent = box;
            minimize = ~isempty( obj.MinimizeFcn );
            if minimize
                minimizeButton.Parent = box;
                box.Widths(end) = minimizeButton.Extent(3);
            end
            dock = ~isempty( obj.DockFcn );
            if dock
                dockButton.Parent = box;
                box.Widths(end) = dockButton.Extent(3);
            end
            help = ~isempty( obj.HelpFcn );
            if help
                helpButton.Parent = box;
                helpButton.TooltipString = obj.HelpTooltipString;
                box.Widths(end) = helpButton.Extent(3);
            end
            close = ~isempty( obj.CloseRequestFcn );
            if close
                closeButton.Parent = box;
                closeButton.TooltipString = obj.CloseTooltipString;
                box.Widths(end) = closeButton.Extent(3);
            end

            % Update icons
            if obj.Minimized_
                minimizeButton.String = char( 9662 );
                minimizeButton.TooltipString = obj.MaximizeTooltipString;
            else
                minimizeButton.String = char( 9652 );
                minimizeButton.TooltipString = obj.MinimizeTooltipString;
            end
            if obj.Docked_
                dockButton.String = char( 8599 );
                dockButton.TooltipString = obj.UndockTooltipString;
            else
                dockButton.String = char( 8600 );
                dockButton.TooltipString = obj.DockTooltipString;
            end

        end % redrawButtons

    end % helper methods

end % classdef


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

% Last Modified by GUIDE v2.5 16-Jul-2010 19:34:10

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

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

% Update handles structure
guidata(hObject, handles);

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

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

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

% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
programma
% hObject    handle to pushbutton1 (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 pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
dtmf_story
% hObject    handle to pushbutton2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

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

% Hint: place code in OpeningFcn to populate axes1

% --- Executes during object creation, after setting all properties.
function axes2_CreateFcn(hObject, eventdata, handles)
imshow(imread('logo-sun.jpg'))
% hObject    handle to axes2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: place code in OpeningFcn to populate axes2


function ds = setinterpreter(ds,funchandle)
   %SETINTERPRETER changes the associated interpreter function
   % datasource = setinterpreter(datasource,function_handle)

   if ~isa(funchandle,'function_handle')
      error('Trying to set a function handle to a %s',class(funchandle));
   end
   ds.interpreter = funchandle;
   % ds = datasource(funchandle,ds.file_string,ds.file_args{:});
end


 function tdir = test_dir(tdir)
%function tdir = test_dir(tdir)
%
% Return path to test directory.
% Users can/should customize this file.

persistent pdir
if ~isvar('pdir') || isempty(pdir)
	try
		pdir.name = getenv('USER');
	catch
		pdir.name = 'user';
	end
	pdir.name = ['test,'  pdir.name];
	pdir.top = '/tmp/';
	pdir.path = [pdir.top pdir.name '/']; % trailing '/' is essential!
end

if nargin
	pdir.path = tdir;
end

if ~exist(pdir.path, 'dir')
	printf('Directory "%s" not found, so it will be created', pdir.path)
%	printf('run the following command!:')
%	'!mkdir /tmp/test'
	try
		mkdir(pdir.top, pdir.name) % compat with matlab 6.x
	catch
		try
			mkdir(pdir.path) % matlab 7.x accepts full path
		catch
			error 'give up'
		end
	end
end

tdir = pdir.path;


function mne_license

% MNE_LICENSE prints the license only once upon the first call to
% this function. If the user does a "clear all", the license will
% again be shown.  This function should be included in every openmeeg
% function to ensure that the license is displayed at least once.

% Copyright (C) 2009-2011, Robert Oostenveld

persistent status

if isempty(status)
  % this is for the first time
  status = false;
end

if ~status
  % show the license
  try
    tmp = which('mne_license');
  catch
    tmp = mfilename;
  end
  [p, f] = fileparts(tmp);
  clc
  fprintf('==============================================================================\n');
  type(fullfile(p, 'LICENSE.txt'));
  fprintf('==============================================================================\n');
  % remember that it has been shown
  status = true;
  pause(3)
end


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

% Copyright 2006 The MathWorks, Inc.

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

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


function uninstall
% AnalogDevices.uninstall removes AnalogDevices HDL BSPs

% Copyright 2015 MathWorks, Inc. All Rights Reserved.

    AnalogDevices.install(1);
end


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 = AnalogDevices.fmcomms5.common.plugin_board('ZC706');


function hfssSetSolveInside(fid, Object, solveInsideFlag)

fprintf(fid, 'oEditor.ChangeProperty _\n');
fprintf(fid, '\tArray("NAME:AllTabs",  _\n');
fprintf(fid, '\t\tArray("NAME:Geometry3DAttributeTab", _\n');
fprintf(fid, '\t\t\tArray("NAME:PropServers",  "%s"), _\n', Object);
fprintf(fid, '\t\t\tArray("NAME:ChangedProps", _\n');
if (solveInsideFlag)
	fprintf(fid, '\t\t\t\tArray("NAME:Solve Inside", "Value:=", true) _\n');
else
	fprintf(fid, '\t\t\t\tArray("NAME:Solve Inside", "Value:=", false) _\n');
end
fprintf(fid, '\t\t\t\t) _\n');
fprintf(fid, '\t\t\t) _\n');
fprintf(fid, '\t\t) \n');


function [output,extras] = urlread2(urlChar,method,body,headersIn,varargin)
%urlread2  Makes HTTP requests and processes response
%
%   [output,extras] = urlread2(urlChar, *method, *body, *headersIn, varargin)
%
%   * indicates optional inputs that must be entered in place
%
%   UNDOCUMENTED MATLAB VERSION
%
%   EXAMPLE CALLING FORMS
%   ... = urlread2(urlChar)
%   ... = urlread2(urlChar,'GET','',[],prop1,value1,prop2,value2,etc)
%   ... = urlread2(urlChar,'POST',body,headers)
%
%   FEATURES
%   =======================================================================
%   1) Allows specification of any HTTP method
%   2) Allows specification of any header. Very little is hard-coded
%      in for header handling.
%   3) Returns response status and headers
%   4) Should handle unicode properly ...
%
%   OUTPUTS
%   =======================================================================
%   output : body of the response, either text or binary depending upon
%            CAST_OUTPUT property
%   extras : (structure)
%       .allHeaders  - stucture, fields have cellstr values, HTTP headers may
%           may be repeated but will have a single field entry, with each
%           repeat's value another being another entry in the cellstr, for
%           example:
%               .Set_Cookie = {'first_value' 'second_value'}
%       .firstHeaders - (structure), variable fields, contains the first
%                      string entry for each field in allHeaders, this
%                      structure can be used to avoid dereferencing a cell
%                      for fields you expect not to be repeated ...
%                   EXAMPLE:
%                   .Response       : 'HTTP/1.1 200 OK'}
%                   .Server         : 'nginx'
%                   .Date           : 'Tue, 29 Nov 2011 02:23:16 GMT'
%                   .Content_Type   : 'text/html; charset=UTF-8'
%                   .Content_Length : '109155'
%                   .Connection     : 'keep-alive'
%                   .Vary           : 'Accept-Encoding, User-Agent'
%                   .Cache_Control  : 'max-age=60, private'
%                   .Set_Cookie     : 'first_value'
%       .status     - (structure)
%               .value  : numeric value of status, ex. 200
%               .msg    : message that goes along with status, ex. 'OK'
%       .url        - eventual url that led to output, this can change from
%                     the input with redirects, see FOLLOW_REDIRECTS
%       .isGood     - (logical) I believe this is an indicator of the presence of 400
%                      or 500 status codes (see status.value) but more
%                      testing is needed. In other words, true if status.value < 400.
%                      In code, set true if the response was obtainable without
%                      resorting to checking the error stream.
%
%   INPUTS
%   =======================================================================
%   urlChar   : The full url, must include scheme (http, https)
%   method    : examples: 'GET' 'POST' etc
%   body      : (vector)(char, uint8 or int8) body to write, generally used
%               with POST or PUT, use of uint8 or int8 ensures that the
%               body input is not manipulated before sending, char is sent
%               via unicode2native function with ENCODING input (see below)
%   headersIn : (structure array), use empty [] or '' if no headers are needed
%                   but varargin property/value pairs are, multiple headers
%                   may be passed in as a structure array
%       .name    - (string), name of the header, a name property is used
%                   instead of a field because the name must match a valid
%                   header
%       .value   - (string), value to use
%
%   OPTIONAL INPUTS (varargin, property/value pairs)
%   =======================================================================
%   CAST_OUTPUT      : (default true) output is uint8, useful if the body
%                       of the response is not text
%   ENCODING         : (default ''), ENCODING input to function unicode2native
%   FOLLOW_REDIRECTS : (default true), if false 3xx status codes will
%                       be returned and need to be handled by the user,
%                       note this does not handle javascript or meta tag
%                       redirects, just server based ones
%   READ_TIMEOUT     : (default 0), 0 means no timeout, value is in
%                       milliseconds
%
%   EXAMPLES
%   =======================================================================
%   GET:
%   --------------------------------------------
%   url    = 'http://www.mathworks.com/matlabcentral/fileexchange/';
%   query  = 'urlread2';
%   params = {'term' query};
%   queryString = http_paramsToString(params,1);
%   url = [url '?' queryString];
%   [output,extras] = urlread2(url);
%
%   POST:
%   --------------------------------------------
%   url    = 'http://posttestserver.com/post.php';
%   params = {'testChars' char([2500 30000]) 'new code' '?'};
%   [paramString,header] = http_paramsToString(params,1);
%   [output,extras] = urlread2(url,'POST',paramString,header);
%
%   From behind a firewall, use the Preferences to set your proxy server.
%
%   See Also:
%       http_paramsToString
%       unicode2native
%       native2unicode
%
%   Subfunctions:
%   fixHeaderCasing - small subfunction to fix case errors encountered in real
%       world, requires updating when casing doesn't match expected form, like
%       if someone sent the header content-Encoding instead of
%       Content-Encoding
%
%   Based on original urlread code by Matthew J. Simoneau
%
%   VERSION = 1.1

in.CAST_OUTPUT      = true;
in.FOLLOW_REDIRECTS = true;
in.READ_TIMEOUT     = 0;
in.ENCODING         = '';

%Input handling
%---------------------------------------
if ~isempty(varargin)
    for i = 1:2:numel(varargin)
        prop  = upper(varargin{i});
        value = varargin{i+1};
        if isfield(in,prop)
            in.(prop) = value;
        else
           error('Unrecognized input to function: %s',prop)
        end
    end
end

if ~exist('method','var') || isempty(method), method = 'GET'; end
if ~exist('body','var'), body = ''; end
if ~exist('headersIn','var'), headersIn = []; end

assert(usejava('jvm'),'Function requires Java')

import com.mathworks.mlwidgets.io.InterruptibleStreamCopier;
com.mathworks.mlwidgets.html.HTMLPrefs.setProxySettings %Proxy settings need to be set

%Create a urlConnection.
%-----------------------------------
urlConnection = getURLConnection(urlChar);
%For HTTP uses sun.net.www.protocol.http.HttpURLConnection
%Might use ice.net.HttpURLConnection but this has more overhead

%SETTING PROPERTIES
%-------------------------------------------------------
urlConnection.setRequestMethod(upper(method));
urlConnection.setFollowRedirects(in.FOLLOW_REDIRECTS);
urlConnection.setReadTimeout(in.READ_TIMEOUT);

for iHeader = 1:length(headersIn)
    curHeader = headersIn(iHeader);
    urlConnection.setRequestProperty(curHeader.name,curHeader.value);
end

if ~isempty(body)
    %Ensure vector?
    if size(body,1) > 1
        if size(body,2) > 1
            error('Input parameter to function: body, must be a vector')
        else
            body = body';
        end
    end

    if ischar(body)
        %NOTE: '' defaults to Matlab's default encoding scheme
        body = unicode2native(body,in.ENCODING);
    elseif ~(strcmp(class(body),'uint8') || strcmp(class(body),'int8'))
        error('Function input: body, should be of class char, uint8, or int8, detected: %s',class(body))
    end

    urlConnection.setRequestProperty('Content-Length',int2str(length(body)));
    urlConnection.setDoOutput(true);
    outputStream = urlConnection.getOutputStream;
    outputStream.write(body);
    outputStream.close;
else
    urlConnection.setRequestProperty('Content-Length','0');
end

%==========================================================================
%                   Read the data from the connection.
%==========================================================================
%This should be done first because it tells us if things are ok or not
%NOTE: If there is an error, functions below using urlConnection, notably
%getResponseCode, will fail as well
try
    inputStream = urlConnection.getInputStream;
    isGood = true;
catch ME
    isGood = false;
%NOTE: HTTP error codes will throw an error here, we'll allow those for now
%We might also get another error in which case the inputStream will be
%undefined, those we will throw here
    inputStream = urlConnection.getErrorStream;

    if isempty(inputStream)
        msg = ME.message;
        I = strfind(msg,char([13 10 9])); %see example by setting timeout to 1
        %Should remove the barf of the stack, at ... at ... at ... etc
        %Likely that this could be improved ... (generate link with full msg)
        if ~isempty(I)
            msg = msg(1:I(1)-1);
        end
        fprintf(2,'Response stream is undefined\n below is a Java Error dump (truncated):\n');
        error(msg)
    end
end

%POPULATING HEADERS
%--------------------------------------------------------------------------
allHeaders = struct;
allHeaders.Response = {char(urlConnection.getHeaderField(0))};
done = false;
headerIndex = 0;

while ~done
    headerIndex = headerIndex + 1;
    headerValue = char(urlConnection.getHeaderField(headerIndex));
    if ~isempty(headerValue)
        headerName = char(urlConnection.getHeaderFieldKey(headerIndex));
        headerName = fixHeaderCasing(headerName); %NOT YET FINISHED

        %Important, for name safety all hyphens are replace with underscores
        headerName(headerName == '-') = '_';
        if isfield(allHeaders,headerName)
            allHeaders.(headerName) = [allHeaders.(headerName) headerValue];
        else
            allHeaders.(headerName) = {headerValue};
        end
    else
        done = true;
    end
end

firstHeaders = struct;
fn = fieldnames(allHeaders);
for iHeader = 1:length(fn)
   curField = fn{iHeader};
   firstHeaders.(curField) = allHeaders.(curField){1};
end

status = struct(...
    'value',    urlConnection.getResponseCode(),...
    'msg',      char(urlConnection.getResponseMessage));

%PROCESSING OF OUTPUT
%----------------------------------------------------------
byteArrayOutputStream = java.io.ByteArrayOutputStream;
% This StreamCopier is unsupported and may change at any time. OH GREAT :/
isc = InterruptibleStreamCopier.getInterruptibleStreamCopier;
isc.copyStream(inputStream,byteArrayOutputStream);
inputStream.close;
byteArrayOutputStream.close;

if in.CAST_OUTPUT
    charset = '';

    %Extraction of character set from Content-Type header if possible
    if isfield(firstHeaders,'Content_Type')
        text = firstHeaders.Content_Type;
        %Always open to regexp improvements
        charset = regexp(text,'(?<=charset=)[^\s]*','match','once');
    end

    if ~isempty(charset)
        output = native2unicode(typecast(byteArrayOutputStream.toByteArray','uint8'),charset);
    else
        output = char(typecast(byteArrayOutputStream.toByteArray','uint8'));
    end
else
    %uint8 is more useful for later charecter conversions
    %uint8 or int8 is somewhat arbitary at this point
    output = typecast(byteArrayOutputStream.toByteArray','uint8');
end

extras              = struct;
extras.allHeaders   = allHeaders;
extras.firstHeaders = firstHeaders;
extras.status       = status;
%Gets eventual url even with redirection
extras.url          = char(urlConnection.getURL);
extras.isGood       = isGood;

end

function headerNameOut = fixHeaderCasing(headerName)
%fixHeaderCasing Forces standard casing of headers
%
%   headerNameOut = fixHeaderCasing(headerName)
%
%   This is important for field access in a structure which
%   is case sensitive
%
%   Not yet finished.
%   I've been adding to this function as problems come along

    switch lower(headerName)
        case 'location'
            headerNameOut = 'Location';
        case 'content_type'
            headerNameOut = 'Content_Type';
        otherwise
            headerNameOut = headerName;
    end
end

%==========================================================================
%==========================================================================
%==========================================================================

function urlConnection = getURLConnection(urlChar)
%getURLConnection
%
%   urlConnection = getURLConnection(urlChar)

% Determine the protocol (before the ":").
protocol = urlChar(1:find(urlChar==':',1)-1);

% Try to use the native handler, not the ice.* classes.
try
    switch protocol
        case 'http'
            %http://www.docjar.com/docs/api/sun/net/www/protocol/http/HttpURLConnection.html
            handler = sun.net.www.protocol.http.Handler;
        case 'https'
            handler = sun.net.www.protocol.https.Handler;
    end
catch ME
    handler = [];
end

% Create the URL object.
try
    if isempty(handler)
        url = java.net.URL(urlChar);
    else
        url = java.net.URL([],urlChar,handler);
    end
catch ME
    error('Failure to parse URL or protocol not supported for:\nURL: %s',urlChar);
end

% Get the proxy information using MathWorks facilities for unified proxy
% preference settings.
mwtcp = com.mathworks.net.transport.MWTransportClientPropertiesFactory.create();
proxy = mwtcp.getProxy();

% Open a connection to the URL.
if isempty(proxy)
    urlConnection = url.openConnection;
else
    urlConnection = url.openConnection(proxy);
end

end


load  data1


function gc = getGraphClass(obj)
if isHG2
    gc = lower(obj.Type);
else
    gc = lower(handle(obj).classhandle.name);
end
end


classdef ( Hidden, Sealed ) FigureObserver < handle
    %uix.FigureObserver  Figure observer
    %
    %  A figure observer raises an event FigureChanged when the figure
    %  ancestor of a subject changes.

    %  Copyright 2014-2015 The MathWorks, Inc.
    %  $Revision: 1435 $ $Date: 2016-11-17 17:50:34 +0000 (Thu, 17 Nov 2016) $

    properties( SetAccess = private )
        Subject % subject
        Figure % figure ancestor
    end

    properties( Access = private )
        PreSetListeners % listeners to Parent PreGet
        PostSetListeners % listeners to Parent PreGet
        OldFigure = gobjects( 0 ) % previous figure ancestor
    end

    events( NotifyAccess = private )
        FigureChanged
    end

    methods

        function obj = FigureObserver( subject )
            %uix.FigureObserver  Create figure observer
            %
            %  o = uix.FigureObserver(s) creates a figure observer for the
            %  subject s.

            % Check
            validateattributes( subject, {'matlab.graphics.Graphics'}, ...
                {'scalar'}, '', 'subject' )

            % Store subject
            obj.Subject = subject;

            % Set up object
            obj.update()

        end % constructor

    end % structors

    methods( Access = private )

        function update( obj )
            %update  Update listeners and Figure property

            % Create fresh listeners
            obj.PreSetListeners = event.proplistener.empty( [1 0] ); % clear
            obj.PostSetListeners = event.proplistener.empty( [1 0] ); % clear
            o = obj.Subject;
            while ~isempty( o ) && ~isa( o, 'matlab.ui.Figure' )
                obj.PreSetListeners(end+1) = event.proplistener( o, ...
                    findprop( o, 'Parent' ), 'PreSet', @obj.onParentPreSet );
                obj.PostSetListeners(end+1) = event.proplistener( o, ...
                    findprop( o, 'Parent' ), 'PostSet', @obj.onParentPostSet );
                o = o.Parent;
            end

            % Store figure
            obj.Figure = o;

        end % update

        function onParentPreSet( obj, ~, ~ )
            %onParentPreSet  Event handler

            % Store old figure
            obj.OldFigure = obj.Figure;

        end % onParentPreSet

        function onParentPostSet( obj, ~, ~ )
            %onParentPostSet  Event handler

            % Update object
            obj.update()

            % Raise event
            oldFigure = obj.OldFigure;
            newFigure = obj.Figure;
            if ~isequal( oldFigure, newFigure )
                notify( obj, 'FigureChanged', ...
                    uix.FigureData( oldFigure, newFigure ) )
            end

            % Clear old figure
            obj.OldFigure = gobjects( 0 );

        end % onParentPostSet

    end % private methods

end % classdef


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

try
    fprintf('Downloading region proposals...\n');
    urlwrite('https://onedrive.live.com/download?resid=F371D9563727B96F!91965&authkey=!AErVqYD6NhjxAfw', ...
        'proposals.zip');

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

    fprintf('Done.\n');
    delete('proposals.zip');
catch
    fprintf('Error in downloading, please try links in README.md https://github.com/daijifeng001/R-FCN');
end

cd(cur_dir);


% THIS SOFTWARE AND ANY ACCOMPANYING DOCUMENTATION IS RELEASED "AS IS."  THE U.S. GOVERNMENT MAKES NO WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, CONCERNING THIS SOFTWARE AND ANY ACCOMPANYING DOCUMENTATION, INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.  IN NO EVENT WILL THE U.S. GOVERNMENT BE LIABLE FOR ANY DAMAGES, INCLUDING ANY LOST PROFITS, LOST SAVINGS OR OTHER INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE, OR INABILITY TO USE, THIS SOFTWARE OR ANY ACCOMPANYING DOCUMENTATION, EVEN IF INFORMED IN ADVANCE OF THE POSSIBILITY OF SUCH DAMAGES.
%
% change log:
%   040204 smw stub file
%
% file: get_r_ci_tl.m
%
function varargout = get_r_ci_tl(varargin)
  error('get_r_ci_tl is not part of current release.');
return;


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

% Last Modified by GUIDE v2.5 30-May-2011 10:59:28

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

% loginGUI(fcnHandle)
% fcnHandle has signature fcnHandle(username) and is executed when the
% Login button is pressed. If the window is killed, fcnHandle is not
% called.
function LoginGUI_OpeningFcn(hObject, eventdata, handles, varargin)
assert(numel(varargin)==1,'Expected exactly one input argument.');
handles.output = hObject;
handles.loginFcn = varargin{1};
guidata(hObject, handles);
centerfig(hObject);
set(handles.figure1,'WindowStyle','modal')

function varargout = LoginGUI_OutputFcn(hObject, eventdata, handles) %#ok<*INUSL>

% putting these two lines here rather than in OpeningFcn gets the GUI to
% open with the focus in etUsername
uicontrol(handles.etUsername);
uiwait(handles.figure1);

varargout{1} = [];

function etUsername_Callback(hObject, eventdata, handles) %#ok<*INUSD,*DEFNU>
% If user enters a username and hits return, move focus to pbLogin
c = get(handles.figure1,'CurrentCharacter');
if strcmp(c,sprintf('\r'))
    uicontrol(handles.pbLogin);
end

function edit2_Callback(hObject, eventdata, handles)

function pbLogin_Callback(hObject, eventdata, handles)
username = get(handles.etUsername,'String');
username = strtrim(username);
if isempty(username)
    errordlg('Please enter a username.','Missing Username','modal');
    return;
end
delete(handles.figure1);
handles.loginFcn(username);

function figure1_KeyPressFcn(hObject, eventdata, handles)
switch eventdata.Key
    case 'escape'
        delete(handles.figure1);
end

function pbLogin_KeyPressFcn(hObject, eventdata, handles)
switch eventdata.Key
    case 'return'
        pbLogin_Callback(hObject,[],handles);
    case 'escape'
        % this is not working
        set(handles.figure1,'CurrentObject',handles.figure1);
end


%--- help for recreate_parameters ---
%
%  INTERNAL FUNCTION
%
%


function FatalInitError(str)
%
% function FatalInitError(str)
%
% str: error string
%
% queries user, then blasts the entire thing, deleting mrSESSION and any
% tSeries files
% have been extracted.
%
% djh, 9/26/2001
global HOMEDIR
deleteFlag = questdlg([str,' Start from scratch?'],...
    'Fatal mrInitRet error','Yes','No','Yes');

if strcmp(deleteFlag,'Yes')
    % Delete everything
    sessionFile = fullfile(HOMEDIR,'mrSESSION.mat');
    if exist(sessionFile,'file');
        delete(sessionFile);
    end
    datadir = fullfile(HOMEDIR,'Inplane');
    % Delete anat, if it exists
    delete(fullfile(datadir,'*.mat'));
    % Delete tSeries (if there are any)
    [nscans,scanDirList] = countDirs(fullfile(datadir,'Original','TSeries','Scan*'));
    for s=1:nscans
        delete(fullfile(datadir,'TSeries',scanDirList{s},'*.mat'));
    end
end
clear all
close all


%  INTERNAL FUNCTION: Creates a handle to an m-file not on the matlab search path
%
%  ::
%
%    hdl = func2fhandle(full_path/func)
%    hdl = func2fhandle(relative_path/func)
%    [hdl1,hdl2,...,hdln] = func2fhandle(p1,p2,...,pn)
%    [hdl1,hdl2,...,hdln] = func2fhandle({p1,p2,...,pn})
%
%  Args:
%
%     - **pth** [char|cellstr] : path names to create handles for. The path
%       could be relative to the current directory or absolute
%
%  Returns:
%     :
%
%     - **hdl** [function_handle] : function handle(s)
%
%


function libdir = opti_GetLibPath()
% Return architecture dependent general library path

switch(computer)
    case 'PCWIN'
        libdir = 'lib\win32\ ';
    case 'PCWIN64'
        libdir = 'lib\win64\ ';
    otherwise
        error('This function is only setup for Windows PCs');
end

end


function fnamefullpath = findfile(rootdirexamples, fname)

fnamefullpath = [rootdirexamples, fname];
if ~exist(fnamefullpath, 'file')
    msg = sprintf('%s does not exist. You first have to generate it by running demo_snirf\n', fnamefullpath);
    MenuBox(msg, 'OK');
    fnamefullpath = '';
    return;
end


function val = h5read_safe(fname, name, val)

try
    val = h5read(fname, name);
catch
    switch(class(val))
        case 'char'
            val = '';
        case 'cell'
            val = {};
        otherwise
            val = [];
    end
end


function varargout = ft_error(varargin)

% FT_ERROR prints an error message on screen, just like the standard ERROR function.
%
% Use as
%   ft_error(...)
% with arguments similar to fprintf, or
%   ft_error(msgId, ...)
% with arguments similar to error.
%
% See also FT_ERROR, FT_WARNING, FT_NOTICE, FT_INFO, FT_DEBUG, ERROR, WARNING

% Copyright (C) 2017, 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 nargout
  varargout{:} = ft_notification(varargin{:});
elseif isequal(varargin, {'last'})
  % return an answer anyway
  varargout{1} = ft_notification(varargin{:});
else
  ft_notification(varargin{:});
end


function fnames = subs_fields(item)

% function fnames = subs_fields(item)
% This function works as a "class-based switch" to return the value of
% the private mysubs_fields function for the appropriate class.
% This function is identical for all classes derived from cfg_item, but
% it has to be in the class directory to access the proper private
% function mysubs_fields.
%
% 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: subs_fields.m 4867 2012-08-30 13:04:51Z volkmar $

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

fnames = mysubs_fields;


function m = gpuDistribute(m)
%  m = gpuDistribute(m)
%---------------------------------------------------------------------
% Distibutes the fields of the model <m> onto the GPU card.
%---------------------------------------------------------------------
% DES


function createHdf5File(filename, datasetName, inputData, varargin)
	% Creates an HDF5 file at filename under given datasetName hierarchy and saves inputData.
	% Biafra Ahanonu
	% started: 2014.01.07
	% inputs
		%
	% outputs
		%

	ciapkg.hdf5.createHdf5File(filename, datasetName, inputData,'passArgs', varargin);
end


function str = showdoc(item, indent)

% function str = showdoc(item, indent)
% Display help text for a cfg_menu and all of its options.
%
% This code is part of a batch job configuration system for MATLAB. See
%      help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging

% Volkmar Glauche
% $Id: showdoc.m 1716 2008-05-23 08:18:45Z volkmar $

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

str = showdoc(item.cfg_item, indent);
str{end+1} = sprintf('One of the following options must be selected:');
% Display cfg_menu labels
for k = 1:numel(item.labels)
    str{end+1} = sprintf('* %s', item.labels{k});
end;