function dirSynch( root1, root2, showOnly, flag, ignDate )
% Synchronize two directory trees (or show differences between them).
%
% If a file or directory 'name' is found in both tree1 and tree2:
%  1) if 'name' is a file in both the pair is considered the same if they
%     have identical size and identical datestamp (or if ignDate=1).
%  2) if 'name' is a directory in both the dirs are searched recursively.
%  3) if 'name' is a dir in root1 and a file in root2 (or vice-versa)
%     synchronization cannot proceed (an error is thrown).
% If 'name' is found only in root1 or root2 it's a difference between them.
%
% The parameter flag controls how synchronization occurs:
%  flag==0: neither tree1 nor tree2 has preference (newer file is kept)
%  flag==1: tree2 is altered to reflect tree1 (tree1 is unchanged)
%  flag==2: tree1 is altered to reflect tree2 (tree2 is unchanged)
% Run with showOnly=1 and different values of flag to see its effect.
%
% By default showOnly==1. If showOnly, displays a list of actions that need
% to be performed in order to synchronize the two directory trees, but does
% not actually perform the actions. It is highly recommended to run
% dirSynch first with showOnly=1 before running it with showOnly=0.
%
% USAGE
%  dirSynch( root1, root2, [showOnly], [flag], [ignDate] )
%
% INPUTS
%  root1    - root directory of tree1
%  root2    - root directory of tree2
%  showOnly - [1] show but do NOT perform actions
%  flag     - [0] 0: synchronize; 1: set root2=root1; 2: set root1==root2
%  ignDate  - [0] if true considers two files same even if have diff dates
%
% OUTPUTS
%  dirSynch( 'c:\toolbox', 'c:\toolbox-old', 1 )
%
% EXAMPLE
%
% See also
%
% Piotr's Image&Video Toolbox      Version 2.10
% Copyright 2012 Piotr Dollar.  [pdollar-at-caltech.edu]
% Please email me if you find bugs, or have suggestions or questions!
% Licensed under the Simplified BSD License [see external/bsd.txt]

if(nargin<3 || isempty(showOnly)), showOnly=1; end;
if(nargin<4 || isempty(flag)), flag=0; end;
if(nargin<5 || isempty(ignDate)), ignDate=0; end;
% get differences between root1/root2 and loop over them
D = dirDiff( root1, root2, ignDate );
roots={root1,root2}; ticId = ticStatus;
for i=1:length(D)
  % get action
  if( flag==1 )
    if( D(i).in1 ), act=1; src1=1; else act=0; src1=2; end
  elseif( flag==2 )
    if( D(i).in2 ), act=1; src1=2; else act=0; src1=1; end
  else
    act=1;
    if(D(i).in1 && D(i).in2)
      if( D(i).new1 ), src1=1; else src1=2; end
    else
      if( D(i).in1 ), src1=1; else src1=2; end
    end
  end
  src2=mod(src1,2)+1;
  % perform action
  if( act==1 )
    if( showOnly )
      disp(['COPY ' int2str(src1) '->' int2str(src2) ': ' D(i).name]);
    else
      copyfile( [roots{src1} D(i).name],  [roots{src2} D(i).name], 'f' );
    end;
  else
    if( showOnly )
      disp(['DEL in  ' int2str(src1) ': ' D(i).name]);
    else
      fName = [roots{src1} D(i).name];
      if(D(i).isdir), rmdir(fName,'s'); else delete(fName); end
    end
  end
  if(~showOnly), tocStatus( ticId, i/length(D) ); end;
end
end

function D = dirDiff( root1, root2, ignDate )
% get differences from root1 to root2
D1 = dirDiff1( root1, root2, ignDate, '/' );
% get differences from root2 to root1
D2 = dirDiff1( root2, root1, ignDate, '/' );
% remove duplicates (arbitrarily from D2)
D2=D2(~([D2.in1] & [D2.in2]));
% swap 1 and 2 in D2
for i=1:length(D2),
  D2(i).in1=0; D2(i).in2=1; D2(i).new1=~D2(i).new1;
end
% merge
D = [D1 D2];
end

function D = dirDiff1( root1, root2, ignDate, subdir )
if(root1(end)~='/'), root1(end+1)='/'; end
if(root2(end)~='/'), root2(end+1)='/'; end
if(subdir(end)~='/'), subdir(end+1)='/'; end
fs1=dir([root1 subdir]); fs2=dir([root2 subdir]);
D=struct('name',0,'isdir',0,'in1',0,'in2',0,'new1',0);
D=repmat(D,[1 length(fs1)]); n=0; names2={fs2.name}; Dsub=[];
for i1=1:length( fs1 )
  name=fs1(i1).name; isdir=fs1(i1).isdir;
  if( any(strcmp(name,{'.','..'})) ), continue; end;
  i2 = find(strcmp(name,names2));
  if(~isempty(i2) && isdir)
    % cannot handle this condition
    if(~fs2(i2).isdir), disp([root1 subdir name]); assert(false); end;
    % recurse and record possible differences
    Dsub=[Dsub dirDiff1(root1,root2,ignDate,[subdir name])]; %#ok<AGROW>
  elseif( ~isempty(i2) && fs1(i1).bytes==fs2(i2).bytes && ...
      (ignDate || fs1(i1).datenum==fs2(i2).datenum))
    % nothing to do - files are same
    continue;
  else
    % record differences
    n=n+1;
    D(n).name=[subdir name]; D(n).isdir=isdir;
    D(n).in1=1; D(n).in2=~isempty(i2);
    D(n).new1 = ~D(n).in2 || (fs1(i1).datenum>fs2(i2).datenum);
  end
end
D = [D(1:n) Dsub];
end


function string=getProgressStr(obj,verbosity)
% give description of text outcome
%
% Inputs:
%   obj             MOxUnitTestOutcome instance.
%   verbosity       integer in range 0 to 2
%
% Output:
%   string          String containing a line (if verbosity==2); or a single
%                   character ('.','F','E','s'; if verbosity==1); or the
%                   empty string

    outcome=getOutcomeStr(obj, verbosity);

    if verbosity>=2
        test_node=getTest(obj);
        string=sprintf('%10s in % 7.2f s: %s\n', ...
                            outcome, getDuration(obj), ...
                            str(test_node));
    elseif verbosity>=1
        string=outcome;
    else
        string='';
    end


function [rd, boardName] = hdlcoder_ref_design_customization
% Reference design plugin registration file
% 1. The registration file with this name inside of a board plugin folder
%    will be picked up
% 2. Any registration file with this name on MATLAB path will also be picked up
% 3. The registration file returns a cell array pointing to the location of
%    the reference design plugins
% 4. The registration file also returns its associated board name
% 5. Reference design plugin must be a package folder accessible from
%    MATLAB path, and contains a reference design definition file

%   Copyright 2013-2014 The MathWorks, Inc.

rd = {...
    'AnalogDevices.fmcomms5.zc706.plugin_rd_rx', ...
    'AnalogDevices.fmcomms5.zc706.plugin_rd_tx', ...
    'AnalogDevices.fmcomms5.zc706.plugin_rd_rxtx', ...
    };

boardName = 'AnalogDevices FMCOMMS5 ZC706';

end


classdef MimTemplateCallback < CoreBaseClass
    % MimTemplateCallback. Used by plugins to fetch empty template images
    %
    %     Template images are empty images with metadata matching the current
    %     image. They are used to create images that will be compatible with
    %     other images from the same dataset. The metadata image size and origin
    %     depends on the chosen context.
    %
    %
    %     Licence
    %     -------
    %     Part of the TD MIM Toolkit. https://github.com/tomdoel
    %     Author: Tom Doel, Copyright Tom Doel 2014.  www.tomdoel.com
    %     Distributed under the MIT licence. Please see website for details.
    %

    properties (Access = private)
        LinkedDatasetChooser  % Sends the API calls to the correct dataset
        DatasetStack       % Handle to the current call stack for the primary dataset
        Reporting
    end

    methods
        function obj = MimTemplateCallback(linked_dataset_chooser, dataset_call_stack, reporting)
            obj.DatasetStack = dataset_call_stack;
            obj.LinkedDatasetChooser = linked_dataset_chooser;
            obj.Reporting = reporting;
        end

        % Returns an image template for the requested context
        function template = GetTemplateImage(obj, context, dataset_name)
            if nargin < 2
                context = [];
            end
            if nargin < 3
                dataset_name = [];
            end
            template = obj.LinkedDatasetChooser.GetDataset(obj.Reporting, dataset_name).GetTemplateImage(context, obj.DatasetStack, obj.Reporting);
        end
    end
end


function eps2pdf(source, dest, crop, append, gray, quality, gs_options)
%EPS2PDF  Convert an eps file to pdf format using ghostscript
%
% Examples:
%   eps2pdf source dest
%   eps2pdf(source, dest, crop)
%   eps2pdf(source, dest, crop, append)
%   eps2pdf(source, dest, crop, append, gray)
%   eps2pdf(source, dest, crop, append, gray, quality)
%   eps2pdf(source, dest, crop, append, gray, quality, gs_options)
%
% This function converts an eps file to pdf format. The output can be
% optionally cropped and also converted to grayscale. If the output pdf
% file already exists then the eps file can optionally be appended as a new
% page on the end of the eps file. The level of bitmap compression can also
% optionally be set.
%
% This function requires that you have ghostscript installed on your
% system. Ghostscript can be downloaded from: http://www.ghostscript.com
%
% Inputs:
%   source  - filename of the source eps file to convert. The filename is
%             assumed to already have the extension ".eps".
%   dest    - filename of the destination pdf file. The filename is assumed
%             to already have the extension ".pdf".
%   crop    - boolean indicating whether to crop the borders off the pdf.
%             Default: true.
%   append  - boolean indicating whether the eps should be appended to the
%             end of the pdf as a new page (if the pdf exists already).
%             Default: false.
%   gray    - boolean indicating whether the output pdf should be grayscale
%             or not. Default: false.
%   quality - scalar indicating the level of image bitmap quality to
%             output. A larger value gives a higher quality. quality > 100
%             gives lossless output. Default: ghostscript prepress default.
%   gs_options - optional ghostscript options (e.g.: '-dNoOutputFonts'). If
%                multiple options are needed, enclose in call array: {'-a','-b'}

% Copyright (C) Oliver Woodford 2009-2014, Yair Altman 2015-

% Suggestion of appending pdf files provided by Matt C at:
% http://www.mathworks.com/matlabcentral/fileexchange/23629

% Thank you to Fabio Viola for pointing out compression artifacts, leading
% to the quality setting.
% Thank you to Scott for pointing out the subsampling of very small images,
% which was fixed for lossless compression settings.

% 9/12/2011 Pass font path to ghostscript.
% 26/02/15: If temp dir is not writable, use the dest folder for temp
%           destination files (Javier Paredes)
% 28/02/15: Enable users to specify optional ghostscript options (issue #36)
% 01/03/15: Upon GS error, retry without the -sFONTPATH= option (this might solve
%           some /findfont errors according to James Rankin, FEX Comment 23/01/15)
% 23/06/15: Added extra debug info in case of ghostscript error; code indentation
% 04/10/15: Suggest a workaround for issue #41 (missing font path; thanks Mariia Fedotenkova)
% 22/02/16: Bug fix from latest release of this file (workaround for issue #41)
% 20/03/17: Added informational message in case of GS croak (issue #186)

    % Intialise the options string for ghostscript
    options = ['-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile="' dest '"'];
    % Set crop option
    if nargin < 3 || crop
        options = [options ' -dEPSCrop'];
    end
    % Set the font path
    fp = font_path();
    if ~isempty(fp)
        options = [options ' -sFONTPATH="' fp '"'];
    end
    % Set the grayscale option
    if nargin > 4 && gray
        options = [options ' -sColorConversionStrategy=Gray -dProcessColorModel=/DeviceGray'];
    end
    % Set the bitmap quality
    if nargin > 5 && ~isempty(quality)
        options = [options ' -dAutoFilterColorImages=false -dAutoFilterGrayImages=false'];
        if quality > 100
            options = [options ' -dColorImageFilter=/FlateEncode -dGrayImageFilter=/FlateEncode -c ".setpdfwrite << /ColorImageDownsampleThreshold 10 /GrayImageDownsampleThreshold 10 >> setdistillerparams"'];
        else
            options = [options ' -dColorImageFilter=/DCTEncode -dGrayImageFilter=/DCTEncode'];
            v = 1 + (quality < 80);
            quality = 1 - quality / 100;
            s = sprintf('<< /QFactor %.2f /Blend 1 /HSample [%d 1 1 %d] /VSample [%d 1 1 %d] >>', quality, v, v, v, v);
            options = sprintf('%s -c ".setpdfwrite << /ColorImageDict %s /GrayImageDict %s >> setdistillerparams"', options, s, s);
        end
    end
    % Enable users to specify optional ghostscript options (issue #36)
    if nargin > 6 && ~isempty(gs_options)
        if iscell(gs_options)
            gs_options = sprintf(' %s',gs_options{:});
        elseif ~ischar(gs_options)
            error('gs_options input argument must be a string or cell-array of strings');
        else
            gs_options = [' ' gs_options];
        end
        options = [options gs_options];
    end
    % Check if the output file exists
    if nargin > 3 && append && exist(dest, 'file') == 2
        % File exists - append current figure to the end
        tmp_nam = tempname;
        try
            % Ensure that the temp dir is writable (Javier Paredes 26/2/15)
            fid = fopen(tmp_nam,'w');
            fwrite(fid,1);
            fclose(fid);
            delete(tmp_nam);
        catch
            % Temp dir is not writable, so use the dest folder
            [dummy,fname,fext] = fileparts(tmp_nam); %#ok<ASGLU>
            fpath = fileparts(dest);
            tmp_nam = fullfile(fpath,[fname fext]);
        end
        % Copy the file
        copyfile(dest, tmp_nam);
        % Add the output file names
        options = [options ' -f "' tmp_nam '" "' source '"'];
        try
            % Convert to pdf using ghostscript
            [status, message] = ghostscript(options);
        catch me
            % Delete the intermediate file
            delete(tmp_nam);
            rethrow(me);
        end
        % Delete the intermediate file
        delete(tmp_nam);
    else
        % File doesn't exist or should be over-written
        % Add the output file names
        options = [options ' -f "' source '"'];
        % Convert to pdf using ghostscript
        [status, message] = ghostscript(options);
    end
    % Check for error
    if status
        % Retry without the -sFONTPATH= option (this might solve some GS
        % /findfont errors according to James Rankin, FEX Comment 23/01/15)
        orig_options = options;
        if ~isempty(fp)
            options = regexprep(options, ' -sFONTPATH=[^ ]+ ',' ');
            status = ghostscript(options);
            if ~status, return; end  % hurray! (no error)
        end
        % Report error
        if isempty(message)
            error('Unable to generate pdf. Check destination directory is writable.');
        elseif ~isempty(strfind(message,'/typecheck in /findfont'))
            % Suggest a workaround for issue #41 (missing font path)
            font_name = strtrim(regexprep(message,'.*Operand stack:\s*(.*)\s*Execution.*','$1'));
            fprintf(2, 'Ghostscript error: could not find the following font(s): %s\n', font_name);
            fpath = fileparts(mfilename('fullpath'));
            gs_fonts_file = fullfile(fpath, '.ignore', 'gs_font_path.txt');
            fprintf(2, '  try to add the font''s folder to your %s file\n\n', gs_fonts_file);
            error('export_fig error');
        else
            fprintf(2, '\nGhostscript error: perhaps %s is open by another application\n', dest);
            if ~isempty(gs_options)
                fprintf(2, '  or maybe the%s option(s) are not accepted by your GS version\n', gs_options);
            end
            fprintf(2, '  or maybe you have another gs executable in your system''s path\n');
            fprintf(2, 'Ghostscript options: %s\n\n', orig_options);
            error(message);
        end
    end
end

% Function to return (and create, where necessary) the font path
function fp = font_path()
    fp = user_string('gs_font_path');
    if ~isempty(fp)
        return
    end
    % Create the path
    % Start with the default path
    fp = getenv('GS_FONTPATH');
    % Add on the typical directories for a given OS
    if ispc
        if ~isempty(fp)
            fp = [fp ';'];
        end
        fp = [fp getenv('WINDIR') filesep 'Fonts'];
    else
        if ~isempty(fp)
            fp = [fp ':'];
        end
        fp = [fp '/usr/share/fonts:/usr/local/share/fonts:/usr/share/fonts/X11:/usr/local/share/fonts/X11:/usr/share/fonts/truetype:/usr/local/share/fonts/truetype'];
    end
    user_string('gs_font_path', fp);
end


%scf - Set current figure, without making it visible.
%
%  This function is useful in batches where figures must remain invisible. It
%  is equivalent to figure(h) but does not make h visible.
%
%  USAGE
%
%    scf(h)
%
%    h              figure handle
%
%  SEE ALSO
%
%    See also Hide, sca, StartBatch.
%

% Copyright (C) 2013 by Michaël Zugaro
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 3 of the License, or
% (at your option) any later version.

function scf(h)

% Check number of parameters
if nargin < 1,
  error('Incorrect number of parameters (type ''help scf'' for details).');
end

% Check parameters
if ~ishandle(h) || ~strcmp(get(h,'type'),'figure'),
  error('Incorrect figure handle (type ''help scf'' for details).');
end

set(0,'CurrentFigure',h);


function varargout = source2sparse(varargin)

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

% Copyright (C) 2009, Robert Oostenveld

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


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

% Last Modified by GUIDE v2.5 23-Apr-2012 21:40:28

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

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

% Update handles structure
guidata(hObject, handles);

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

% --- Outputs from this function are returned to the command line.
function varargout = Biodata_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 during object creation, after setting all properties.
function axes8_CreateFcn(hObject, eventdata, handles)
% hObject    handle to axes8 (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 axes8
axes (hObject)
imshow ('Biodata.jpg')


function drag(varargin)
%DRAG   Move around on a 2-D or 3-D plot.
%   DRAG with no arguments toggles the plot dragging state.
%   DRAG ON turns plot dragging on for the current figure.
%   DRAG XON, YON, or ZON turns plot dragging on for the x, y, or z axis only.
%   DRAG OFF turns plot dragging off in the current figure.
%   DRAG RESET resets the restore point to the current axis settings.
%
%   When plot dragging is on, you can click and drag the axes around while
%   maintaining the current level of zoom.  If DRAG RESET has not been
%   called the restore point is the original non-explored plot.  If DRAG
%   RESET has been called the restore point is the retore point that existed
%   when it was called.  Double clicking retores the axes to the current
%   restore point - the point at which plot dragging was first turned on for
%   this figure (or to the state to which the restore point was set by DRAG
%   RESET).
%
%   In a figure with multiple subplots, pressing and holding the left mouse
%   button drags around the currently active subplot, while pressing and
%   holding the right mouse button drags around all subplots simultaneously.
%   Double clicking with the left mouse button restores the currently active
%   plot to its restore point, while double clicking with the right mouse
%   button restores all subplots to their defined restore point.
%
%   DRAG(FIG,OPTION) applies the drag command to the figure specified by
%   FIG. OPTION can be any of the above arguments.
%
%   Example:
%   x = 0:0.1:5; y = exp(x);
%   figure; subplot(211); plot(x,y,'r.'); subplot(212); plot(y,x,'g.');
%   drag xon;
%
%   Ryan M. Eustice 08-15-2003
%   Woods Hole Oceanographic Institution, MS 7
%   Woods Hole, MA 02543
%   508.289.3269   ryan@whoi.edu

% History
% DATE          WHO                      WHAT
%----------    ------------------        ------------------------------
%2003-07-23    Ryan Eustice              Created & written.
%2003-08-15    Boyko Stoimenov           Modified the private function
%                                        dragreset to correctly count the
%                                        number of axes.  Also, switched
%                                        short-circuit && to & for matlab
%                                        backwards compatability.
%2004-01-29    Ryan Eustice              Fixed bug in private function
%                                        dragreset to properly count
%                                        number of axes and not count
%                                        legend or colorbar objects.

%   Note: drag uses the figure buttondown and buttonmotion functions

%
% PARSE ARGS - set fig and drag command
%
fignum = get(0,'CurrentFigure');
if isempty(fignum)
  return; % no figure
end

switch nargin
case 0 % no arg in
 switch get(fignum,'Tag')
 case 'dragon'  % toggle state
  dragoff(fignum);
 otherwise  % turn on
  figstate.motion = 'all';
  set(fignum,'UserData',figstate);
  dragon(fignum);
 end % switch get(fignum,'Tag')
case 1 % one arg in
 switch lower(varargin{1})
 case 'on'
  figstate.motion = 'all';
  set(fignum,'UserData',figstate);
  dragon(fignum);
 case 'off'
  dragoff(fignum);
 case 'reset'
  dragreset(fignum);
 case 'xon'
  figstate.motion = 'xon';
  set(fignum,'UserData',figstate);
  dragon(fignum);
 case 'yon'
  figstate.motion = 'yon';
  set(fignum,'UserData',figstate);
  dragon(fignum);
 case 'zon'
  figstate.motion = 'zon';
  set(fignum,'UserData',figstate);
  dragon(fignum);
 otherwise
  error(sprintf('Unrecognized argument ''%s''',varargin{1}));
 end % switch varargin{1}
case 2 % two args in
 fignum = varargin{1};
 switch lower(varargin{2})
 case 'on'
  figstate.motion = 'all';
  set(fignum,'UserData',figstate);
  dragon(fignum);
 case 'off'
  dragoff(fignum);
 case 'reset'
  dragreset(fignum);
 case 'xon'
  figstate.motion = 'xon';
  set(fignum,'UserData',figstate);
  dragon(fignum);
 case 'yon'
  figstate.motion = 'yon';
  set(fignum,'UserData',figstate);
  dragon(fignum);
 case 'zon'
  figstate.motion = 'zon';
  set(fignum,'UserData',figstate);
  dragon(fignum);
 otherwise
  error(sprintf('Unrecognized argument ''%s''',varargin{1}));
 end % switch varargin{2}
otherwise % too many args
 error(nargchk(0,2,nargin));
end % switch nargin

%====================================================================
% drag: private
%====================================================================
function dragon(fignum)
figstate = get(fignum,'UserData');
dragreset(fignum);
set(fignum,'Interruptible','on');
set(fignum,'DoubleBuffer','on');
set(fignum,'Tag','dragon');
set(fignum,'WindowButtonDownFcn',@startexploring);
set(fignum,'WindowButtonUpFcn',@stopexploring);

function dragoff(fignum)
set(fignum,'DoubleBuffer','off');
set(fignum,'Tag','');
set(fignum,'WindowButtonDownFcn','');
set(fignum,'WindowButtonUpFcn','');

function dragreset(fignum)
figstate = get(fignum,'UserData');
kids = get(fignum,'Children');
cc = 1;
for ii=1:length(kids)
  % check for regular axes handles by keying off the Tag field which should be
  % empty.  note that objects like legend and colorbar fill in the Tag field.
  if strcmp(get(kids(ii),'Type'),'axes') & strcmp(get(kids(ii),'Tag'),'')
    figstate.axishandle(cc) = kids(ii);
    figstate.origlimits(cc,:) = axis(kids(ii));
    cc = cc+1;
  end
end
figstate.numaxes = length(figstate.axishandle);
set(fignum,'UserData',figstate);

%====================================================================
% callbacks
%====================================================================
function startexploring(obj,eventdata)
fignum = gcbf;
figstate = get(fignum,'UserData');
switch get(fignum,'SelectionType')
case 'normal' %mouse left single-click
 figstate.whichaxes = 'current'; % only drag current axis
 axishandle = gca;
 initaxis(axishandle);
case 'open'   %mouse left or right double-click
 axishandle = gca;
 for ii=1:figstate.numaxes
   if strcmp(figstate.whichaxes,'current') & figstate.axishandle(ii) == axishandle
     % restore currently active axis limits to orig state
     axis(axishandle,figstate.origlimits(ii,:));
     break;
   elseif strcmp(figstate.whichaxes,'all')
     % restore other subplot axis limits to orig state
     axis(figstate.axishandle(ii),figstate.origlimits(ii,:));
   end
 end
case 'alt'    %mouse right single-click
 figstate.whichaxes = 'all'; % drag all axes simultaneously
 for ii=1:figstate.numaxes
   axishandle = figstate.axishandle(ii);
   initaxis(axishandle);
 end
otherwise
  error('Mouse SelectionType unknown');
end
set(fignum,'WindowButtonMotionFcn',@setnewview);
set(fignum,'Pointer','Fleur');
set(fignum,'UserData',figstate); % store figure state

function setnewview(obj,eventdata)
persistent cc;
fignum = gcbf;
figstate = get(fignum,'UserData');
switch figstate.whichaxes
case 'current'
 axishandle = gca;
 updateaxes(axishandle,figstate.motion);
case 'all'
 for ii=1:figstate.numaxes
   axishandle = figstate.axishandle(ii);
   updateaxes(axishandle,figstate.motion);
 end
otherwise
 %do nothing
end % switch figstate.whichaxes
cc = cc+1;
if mod(cc,2)
  drawnow; % force screen update every other motion cycle (lowers cpu usage)
end

function stopexploring(obj,eventdata)
fignum = gcbf;
set(fignum,'WindowButtonMotionFcn','');
set(fignum,'Pointer','arrow');

%====================================================================
% callbacks: private
%====================================================================
function pos = getcurrentposition(axishandle)
pos = get(axishandle,'CurrentPoint');
pos = mean(pos);
pos = round(pos*1000)/1000;

function initaxis(axishandle)
state.currentaxislimits = axis(axishandle);
state.startpoint = getcurrentposition(axishandle);
set(axishandle,'UserData',state); % store axis state

function updateaxes(axishandle,motion)
state = get(axishandle,'UserData');
state.endpoint = getcurrentposition(axishandle);
motionvector = state.startpoint - state.endpoint;

if length(state.currentaxislimits) == 4 % 2D plot
  switch motion
  case 'all'
   state.currentaxislimits = ...
       [state.currentaxislimits(1:2) + motionvector(1), ...
	state.currentaxislimits(3:4) + motionvector(2)];
  case 'xon'
   state.currentaxislimits = ...
       [state.currentaxislimits(1:2) + motionvector(1), ...
	state.currentaxislimits(3:4)];
  case 'yon'
   state.currentaxislimits = ...
       [state.currentaxislimits(1:2), ...
	state.currentaxislimits(3:4) + motionvector(2)];
  otherwise %do nothing
  end % switch motion
elseif length(state.currentaxislimits) == 6 % 3D plot
  switch motion
  case 'all'
   state.currentaxislimits = ...
       [state.currentaxislimits(1:2) + motionvector(1), ...
	state.currentaxislimits(3:4) + motionvector(2), ...
	state.currentaxislimits(5:6) + motionvector(3)];
  case 'xon'
   state.currentaxislimits = ...
       [state.currentaxislimits(1:2) + motionvector(1), ...
	state.currentaxislimits(3:4), ...
	state.currentaxislimits(5:6)];
  case 'yon'
   state.currentaxislimits = ...
       [state.currentaxislimits(1:2), ...
	state.currentaxislimits(3:4) + motionvector(2), ...
	state.currentaxislimits(5:6)];
  case 'zon'
   state.currentaxislimits = ...
       [state.currentaxislimits(1:2), ...
	state.currentaxislimits(3:4), ...
	state.currentaxislimits(5:6) + motionvector(3)];
  otherwise %do nothing
  end % switch motion
end
axis(axishandle,state.currentaxislimits);
set(axishandle,'UserData',state);


function isargdir(varargin)
%ISARGDIR throws an error if not a directory
%
%   Usage: isargdirectory(arg1,arg2,...)
%
%   Input parameters:
%       args        - variable number of args
%
%   See also: isargfile

%*****************************************************************************
% The MIT License (MIT)                                                      *
%                                                                            *
% Copyright (c) 2010-2019 SFS Toolbox Developers                             *
%                                                                            *
% Permission is hereby granted,  free of charge,  to any person  obtaining a *
% copy of this software and associated documentation files (the "Software"), *
% to deal in the Software without  restriction, including without limitation *
% the rights  to use, copy, modify, merge,  publish, distribute, sublicense, *
% and/or  sell copies of  the Software,  and to permit  persons to whom  the *
% Software is furnished to do so, subject to the following conditions:       *
%                                                                            *
% The above copyright notice and this permission notice shall be included in *
% all copies or substantial portions of the Software.                        *
%                                                                            *
% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
% IMPLIED, INCLUDING BUT  NOT LIMITED TO THE  WARRANTIES OF MERCHANTABILITY, *
% FITNESS  FOR A PARTICULAR  PURPOSE AND  NONINFRINGEMENT. IN NO EVENT SHALL *
% THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
% LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT, TORT  OR OTHERWISE, ARISING *
% FROM,  OUT OF  OR IN  CONNECTION  WITH THE  SOFTWARE OR  THE USE  OR OTHER *
% DEALINGS IN THE SOFTWARE.                                                  *
%                                                                            *
% The SFS Toolbox  allows to simulate and  investigate sound field synthesis *
% methods like wave field synthesis or higher order ambisonics.              *
%                                                                            *
% https://sfs.readthedocs.io                            sfstoolbox@gmail.com *
%*****************************************************************************

%% ===== Checking for directory ==========================================
for ii = 1:nargin
    if ~ischar(varargin{ii}) || ~exist(varargin{ii},'dir')
        error('%s need to be a directory.',inputname(ii));
    end
end


function opt= opt_overwriteVoids(opt, fld, default_value);

if ~isfield(opt, fld),
  return;
end

for k= 1:length(opt),
  if isempty(opt(k).(fld)),
    opt(k).(fld)= default_value;
  end
end


% This is used to set the path to visible images
%
% Please change the path in line 16 to your own path before running
%
% Author:Xingchen Zhang, Ping Ye, Gang Xiao
% Contact: xingchen.zhang@imperial.ac.uk
%
% If you use this code, please site the following paper:
%
% X. Zhang, P. Ye, G. Xiao. VIFB:A Visible and Infrared Benchmark. In
% Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern
% Recognition Workshops, 2020.

function imgs=configImgsIR

    path = 'Your own path\VIFB\input\';

    img_IR = {struct('name','carLight','path',strcat(path,'IR\'),'ext','jpg'),...
    struct('name','carShadow','path',strcat(path,'IR\'),'ext','jpg'),...
    struct('name','carWhite','path',strcat(path,'IR\'),'ext','jpg'),...
    struct('name','elecbike','path',strcat(path,'IR\'),'ext','jpg'),...
    struct('name','fight','path',strcat(path,'IR\'),'ext','jpg'),...
    struct('name','kettle','path',strcat(path,'IR\'),'ext','jpg'),...
    struct('name','labMan','path',strcat(path,'IR\'),'ext','jpg'),...
    struct('name','man','path',strcat(path,'IR\'),'ext','jpg'),...
     struct('name','manCall','path',strcat(path,'IR\'),'ext','jpg'),...
    struct('name','manCar','path',strcat(path,'IR\'),'ext','jpg'),...
    struct('name','manlight','path',strcat(path,'IR\'),'ext','jpg'),...
    struct('name','manWalking','path',strcat(path,'IR\'),'ext','jpg'),...
    struct('name','manwithbag','path',strcat(path,'IR\'),'ext','jpg'),...
    struct('name','nightCar','path',strcat(path,'IR\'),'ext','jpg'),...
    struct('name','peopleshadow','path',strcat(path,'IR\'),'ext','jpg'),...
    struct('name','running','path',strcat(path,'IR\'),'ext','jpg'),...
    struct('name','snow','path',strcat(path,'IR\'),'ext','jpg'),...
    struct('name','tricycle','path',strcat(path,'IR\'),'ext','jpg'),...
    struct('name','walking','path',strcat(path,'IR\'),'ext','jpg'),...
    struct('name','walking2','path',strcat(path,'IR\'),'ext','jpg'),...
    struct('name','walkingnight','path',strcat(path,'IR\'),'ext','jpg'),...
    };

imgs=[img_IR];


% Converts a MatLab array into a java.util.ArrayList.
%
% Input arguments:
% array:
%    a MatLab row or column vector (with elements of any type)
%
% Output arguments:
% list:
%    a java.util.ArrayList instance
%
% See also: javaArray

% Copyright 2010 Levente Hunyadi
function list = javaArrayList(array)
list = java.util.ArrayList;
if ~isempty(array)
    assert(isvector(array), 'javaArrayList:DimensionMismatch', ...
        'Row or column vector expected.');
    if iscell(array)  % convert cell array into ArrayList
        for k = 1 : numel(array)
            list.add(array{k});
        end
    else  % convert (numeric) array into ArrayList
        for k = 1 : numel(array)
            list.add(array(k));
        end
    end
end


function varargout=wfdbexec(varargin)
%
% [output]=wfdbexec(commandName,inputArguments,logLevel)
% [nativeCommands]=wfdbexec()
%
% Executes a WFDB native command ('commandName'), with input arguments
% given by 'inputArguments', and outputs everything into a cell array
% called 'output'. The execution is done through a system call outside of
% MATLAB. If no input arguments are provided to the function, the
% output is an array list of all available native WFDB commands in this OS.
% Substantial, non-trivial text parsing maybe required for processing the
% output into a useful MATLAB numerical variable.
%
% WFDBEXEC is useful in cases where a specific command, or feature for a
% command, is not yet in implemented in the MATLAB wrapper. This function
% may be useful for those wishing to do some debugging or performance comparisons.
%
% The user should be very carefull when using this command. The user should
% be familiar with the input and output arguments of the native command
% that he/she is using. In some cases, information about the command can be
% obtained by running the command by itself, of with either '-h',
% '-help','--help' as input arguments in order to access the command help
% information. Offcourse, you can also look at the man page or source code
% for the command at http://www.physionet.org/.
%
%
%
%Required Parameters:
%
% commandName
%       String specifying the command to be called. To ge a list of
%       available WFDB commands that may be runnable by system calls run
%       this function by itself:
%               [nativeCommands]=wfdbexec();
%
%inputArguments
%       Cell array of strings specifying the inputArguments to the command.
%       Each command flag is an element on the cell array. Command flags
%       that require additional parameters should be followed by another
%       String element with the requied parameter(s). In cases you are
%       usign a command that is already implemente in a MATLAB wrapper, it
%       maybe helpful to look at that command's MATLAB code.
%
%Optional Parameters:
%
%       logLevel
%       1x1 integer that specifies the logleve (verbosity) of the execution process.
%       Options are:
%                     0 OFF (Default)
%                     1 SEVERE
%                     2 WARNING
%                     3 INFO
%                     4 FINEST
%                     5 ALL
%
%Output:
%
%output
%       Nx1 Cell array list of Strings.
%
%
% Written by Ikaro Silva, 2013
% Last Modified: January 7, 2014
% Version 0.0.1
% Since 0.9.5
%
% %Get a  list of all WFDB native executables
% nativeComands=wfdbexec()
%
% %Get help on RDSAMP
% out=wfdbexec('rdsamp',{'-h'})
%
% %Read the first five samples of a record
% %Note: This will be very inefficient because we are not buffering
% %and we are returning a list of Strings (instead of doubles and ints).
% %This is provided just as an example on how WFDBEXEC works.
% out=wfdbexec('rdsamp',{'-r','mitdb/100','-t','s5'})
%
% See also WFDB

%endOfHelp
logLevel=[];

[~,config]=wfdbloadlib;

if(nargin==0)
    %With no arguments passed in, we provide the user a list of native
    %commands available for this OS.
    del=findstr(' ',config.WFDB_NATIVE_BIN);
    if(~isempty(del) && del(1)==1)
        config.WFDB_NATIVE_BIN(1)=[];
    end
    commandList={};
    if(ispc)
        [~,message,~] = fileattrib([config.WFDB_NATIVE_BIN '/bin/*.exec']);
        commandList=cell(length(message),1);
        for n=1:length(message)
            str=message(n).Name;
            st=strfind(str,filesep);
            if(~isempty(st))
                str=str(st(end)+1:end);
            end
            commandList(n)={str};
        end
    else
        [~,message,~] = fileattrib([config.WFDB_NATIVE_BIN '/bin/*']);
        for n=1:length(message)
            if(~message(n).directory && message(n).UserExecute)
                str=message(n).Name;
                st=strfind(str,filesep);
                if(~isempty(st))
                    str=str(st(end)+1:end);
                end
                if(isempty(strfind(str,'lib')))
                    commandList(end+1)={str};
                end
            end
        end
    end
    varargout{1}=commandList(:);
else
    if(nargin>2)
        logLevel=varargin{3};
    end
    if(~wfdbloadlib)
        %Add classes to dynamic path
        wfdbloadlib;
    end
    javaWfdbExec=org.physionet.wfdb.Wfdbexec(varargin(1),strcmp(config.customArchFlag,'true'));
    if(~isempty(logLevel))
        javaWfdbExec.setLogLevel(logLevel);
    end
    try
        %System call
        varargout{1}=cell(javaWfdbExec.execToStringList(varargin{2}).toArray);
        clear javaWfdbExec; %Clean-up to avoid leaked Java classes
    catch exception
        clear javaWfdbExec %Clean-up to avoid leaked Java classes
        rethrow(exception)
    end

end


% Converts a MatLab array into a java.util.ArrayList.
%
% Input arguments:
% array:
%    a MatLab row or column vector (with elements of any type)
%
% Output arguments:
% list:
%    a java.util.ArrayList instance
%
% See also: javaArray

% Copyright 2010 Levente Hunyadi
function list = javaArrayList(array)

assert(isvector(array), 'javaArrayList:DimensionMismatch', ...
	'Row or column vector expected.');
list = java.util.ArrayList;
if iscell(array)  % convert cell array into ArrayList
	for k = 1 : numel(array)
		list.add(array{k});
	end
else  % convert (numeric) array into ArrayList
	for k = 1 : numel(array)
		list.add(array(k));
	end
end


classdef SettingsHomogenizedVarComputerFactory < handle

    methods (Access = public, Static)

        function obj = create(cParams)
            switch cParams.type
                case 'ByInterpolation'
                    obj = SettingsHomogenizedVarComputerFromInterpolation(cParams);
                case 'ByVademecum'
                    obj = SettingsHomogenizedVarComputerFromVademecum(cParams);
                otherwise
                    error('Invalid HomogenizerVarComputer type.');
            end
        end

    end

end


classdef GrandlyUnifyView < handle
  properties
    model  % a ref for the model
    controller % a ref for the controller
      % this is necessary b/c we create buttons on-the-fly, and need
      % callbacks for them
    fig  % the figure handle
    projectFileLabelText
    projectFileText
    chooseProjectFileButton
    scoreFeatureLabelText
    scoreFeatureMatTexts=zeros(0,1)
    scoreFeatureJabTexts=zeros(0,1)
    chooseScoreFeatureJabButtons=zeros(0,1)
    classifierFileLabelText
    classifierFileText
    chooseClassifierFileButton
    gtExpDirsLabelText
    gtExpDirsListbox
    gtExpDirsAddButton
    gtExpDirsRemoveButton
    %quitButton
    convertButton
    spinDepth=0  % how many times spin() has been called, minus how many
                 % times unspin() has been called
  end
  methods
    function self=GrandlyUnifyView(model,controller)
      self.model=model;
      self.controller=controller;

      % Create the figure, make it invisible for now
      self.fig= ...
        figure('units','points', ...
               'resize','off', ...
               'numbertitle','off', ...
               'menubar','none', ...
               'name','Grandly Unify', ...
               'windowstyle','normal', ...
               'visible','off', ...
               'closeRequestFcn',@(g,e)(controller.quit()));

      % make the labels
      self.projectFileLabelText= ...
        uicontrol('parent',self.fig, ...
                  'units','points', ...
                  'style','text', ...
                  'backgroundcolor',get(self.fig,'color'), ...
                  'string','Project File ', ...
                  'HorizontalAlignment','right',...
                  'fontsize',12);

      self.classifierFileLabelText= ...
        uicontrol('parent',self.fig, ...
                  'units','points', ...
                  'style','text', ...
                  'backgroundcolor',get(self.fig,'color'), ...
                  'string','Classifier File ', ...
                  'HorizontalAlignment','right',...
                  'fontsize',12);

      self.gtExpDirsLabelText= ...
        uicontrol('parent',self.fig, ...
                  'units','points', ...
                  'style','text', ...
                  'backgroundcolor',get(self.fig,'color'), ...
                  'string',{'Ground-truth ', ...
                            'Experiment ', ...
                            'Directory Names '}, ...
                  'HorizontalAlignment','right',...
                  'fontsize',12);

      % Create the non-label controls
      self.projectFileText= ...
        uicontrol('parent',self.fig, ...
                  'style','text', ...
                  'backgroundcolor','w', ...
                  'HorizontalAlignment','left',...
                  'fontsize',12, ...
                  'units','points');
      self.classifierFileText= ...
        uicontrol('parent',self.fig, ...
                  'style','text', ...
                  'backgroundcolor','w', ...
                  'HorizontalAlignment','left',...
                  'fontsize',12, ...
                  'units','points');
      self.gtExpDirsListbox=...
        uicontrol('parent',self.fig, ...
                  'style','listbox', ...
                  'fontsize',12, ...
                  'units','points');
      self.chooseProjectFileButton= ...
        uicontrol('parent',self.fig, ...
                  'style','pushbutton', ...
                  'string','Choose', ...
                  'fontsize',12, ...
                  'units','points', ...
                  'callback',@(g,e)(controller.chooseProjectFileButtonPressed()));
      self.chooseClassifierFileButton= ...
        uicontrol('parent',self.fig, ...
                  'style','pushbutton', ...
                  'string','Choose', ...
                  'fontsize',12, ...
                  'units','points', ...
                  'callback',@(g,e)(controller.chooseClassifierFileButtonPressed()));
      self.gtExpDirsAddButton= ...
        uicontrol('parent',self.fig, ...
                  'style','pushbutton', ...
                  'string','Add', ...
                  'fontsize',12, ...
                  'units','points', ...
                  'callback',@(g,e)(controller.gtExpDirsAddButtonPressed()));
      self.gtExpDirsRemoveButton= ...
        uicontrol('parent',self.fig, ...
                  'style','pushbutton', ...
                  'string','Remove', ...
                  'fontsize',12, ...
                  'units','points', ...
                  'callback',@(g,e)(controller.gtExpDirsRemoveButtonPressed()));
      self.convertButton= ...
        uicontrol('parent',self.fig, ...
                  'style','pushbutton', ...
                  'string','Convert', ...
                  'fontsize',12, ...
                  'units','points', ...
                  'callback',@(g,e)(controller.convertButtonPressed()));

      % sync the view with the model
      self.update();

      % Get the screen dimensions
      savedUnits=get(0,'units');
      set(0,'units','points');
      screenPosition=get(0,'screensize');
      set(0,'units',savedUnits);

      % Figure the placement of the figure, want it centered relative to
      % primary screen
      pos=get(self.fig,'position');
      figureWidth=pos(3);
      figureHeight=pos(4);
      figureXOffset=screenPosition(1)+(screenPosition(3)-figureWidth )/2;
      figureYOffset=screenPosition(2)+(screenPosition(4)-figureHeight)/2;

      % Position the figure
      set(self.fig, ...
          'position',[figureXOffset figureYOffset figureWidth figureHeight]);

      % make it visible
      set(self.fig,'visible','on');
    end  % constructor method

    % ---------------------------------------------------------------------
    function spin(self)
      % Change the cursor to the watch cursor
      self.spinDepth=self.spinDepth+1;
      set(self.fig,'pointer','watch');
      drawnow('update');
    end

    % ---------------------------------------------------------------------
    function unspin(self)
      % Change the cursor back to normal, unless spin() has been called
      % multiple times without a corresponding unspin() calls.
      if self.spinDepth>0 ,
        self.spinDepth=self.spinDepth-1;
        drawnow('update');  % make sure the figure is as it should be before
                            % switching to the normal cursor
        set(self.fig,'pointer','arrow');
        drawnow('update');
      end
    end

    % ---------------------------------------------------------------------
    function update(self)
      % Update the view to match the model

      %
      % Do the layout
      %

      % Set figure layout parameters
      figureWidth=730+50;
      %figureHeightApprox=272;

      sideButtonWidth=80;  % choose buttons, add/remove buttons
      sideButtonHeight=26;
      sideButtonOffsetWidth=20;  % side buttons are this far to the right of
                                 % the center column
      smallSideButtonWidth=70;
      smallSideButtonHeight=24;
        % The 'Choose' buttons for the score feature jab file names are
        % small side buttons
      addRemoveInterButtonHeight=10;

      bottomButtonWidth=100;  % Convert and Quit are the bottom buttons
      bottomButtonHeight=30;
      %interBottomButtonWidth=20;

      centerColumnWidth=470+50;
      %fileNameTextHeight=20;
      gtExpDirsListboxHeight=100;

      labelOffsetWidth=20;  % Labels are this far to the left of the
                            % text/listbox that they label
      scoreFeatureJabIndentWidth=20;  % the names of the jab file names
                                      % are indented this much relative
                                      % to the score feature mat file names

      topPadHeight=22;
      underProjectPadHeight=10;
      interScoreFeaturePadHeight=5;
      belowScoreFeaturePadHeight=5;
      overClassifierPadHeight=10;
      classifierToGTPadHeight=21;
      bottomAreaHeight=70;
        % The "bottom area" is the rectangular area below the listbox.  It
        % is as wide as the figure, and it's bottom edge is aligned with
        % with bottom edge of the figure.  The row of bottom buttons is
        % centered within this area.

      % Want the top edge of the figure to stay fixed
      % The width of the figure is constant
      pos=get(self.fig,'position');
      figureTopYOffset=pos(2)+pos(4);
      figureXOffset=pos(1);

      % Get text extents
      extent=get(self.projectFileLabelText,'extent');
      extentSize=extent(3:4);
      projectFileLabelTextSize=extentSize;
      fileNameTextHeight=extentSize(2);  % height of a single line of text

      extent=get(self.classifierFileLabelText,'extent');
      extentSize=extent(3:4);
      %classifierFileLabelTextSize=extentSize+4;  % pad a little
      classifierFileLabelTextSize=extentSize;

      extent=get(self.gtExpDirsLabelText,'extent');
      extentSize=extent(3:4);
      %gtExpDirsLabelTextSize=extentSize+4;  % pad a little
      gtExpDirsLabelTextSize=extentSize;

      % Calculate overall figure height
      nScoreFeatures=length(self.model.scoreFeatureMatFileNames);
      scoreFeatureAreaHeight= ...
        2*nScoreFeatures*fileNameTextHeight + ...
        max(nScoreFeatures-1,0)*interScoreFeaturePadHeight + ...
        (nScoreFeatures>0)*belowScoreFeaturePadHeight;
      figureHeight=topPadHeight + ...
                   fileNameTextHeight + ...
                   underProjectPadHeight + ...
                   scoreFeatureAreaHeight + ...
                   overClassifierPadHeight + ...
                   fileNameTextHeight + ...
                   classifierToGTPadHeight + ...
                   gtExpDirsListboxHeight + ...
                   bottomAreaHeight;
      figureYOffset=figureTopYOffset-figureHeight;

      % Calculate positions
      projectCenterLineYOffset=figureHeight-topPadHeight-fileNameTextHeight/2;
      scoreFeatureAreaTopYOffset= ...
        projectCenterLineYOffset-fileNameTextHeight/2-underProjectPadHeight;
      classifierCenterLineYOffset= ...
        scoreFeatureAreaTopYOffset ...
          -scoreFeatureAreaHeight ...
          -overClassifierPadHeight ...
          -fileNameTextHeight/2;
      gtTopLineYOffset= ...
        classifierCenterLineYOffset ...
          -fileNameTextHeight/2 ...
          -classifierToGTPadHeight;

      centerColumnXOffset=(figureWidth-centerColumnWidth)/2;
      projectFileTextXOffset=centerColumnXOffset;
      classifierFileTextXOffset=centerColumnXOffset;
      gtExpDirsListboxXOffset=centerColumnXOffset;

      sideButtonXOffset=centerColumnXOffset+centerColumnWidth+sideButtonOffsetWidth;
      chooseProjectFileButtonXOffset=sideButtonXOffset;
      chooseClassifierFileButtonXOffset=sideButtonXOffset;
      gtExpDirsAddButtonXOffset=sideButtonXOffset;
      gtExpDirsRemoveButtonXOffset=sideButtonXOffset;

      convertButtonXOffset=(figureWidth-bottomButtonWidth)/2;
      projectFileLabelTextXOffset=centerColumnXOffset-labelOffsetWidth-projectFileLabelTextSize(1);
      classifierFileLabelTextXOffset=centerColumnXOffset-labelOffsetWidth-classifierFileLabelTextSize(1);
      gtExpDirsLabelTextXOffset=centerColumnXOffset-labelOffsetWidth-gtExpDirsLabelTextSize(1);

      projectFileLabelTextYOffset=projectCenterLineYOffset-projectFileLabelTextSize(2)/2;
      classifierFileLabelTextYOffset=classifierCenterLineYOffset-classifierFileLabelTextSize(2)/2;
      gtExpDirsLabelTextYOffset=gtTopLineYOffset-gtExpDirsLabelTextSize(2);

      projectFileTextYOffset=projectCenterLineYOffset-fileNameTextHeight/2;
      classifierFileTextYOffset=classifierCenterLineYOffset-fileNameTextHeight/2;
      gtExpDirsListboxYOffset=gtTopLineYOffset-gtExpDirsListboxHeight;

      chooseProjectFileButtonYOffset=projectCenterLineYOffset-sideButtonHeight/2;
      chooseClassifierFileButtonYOffset=classifierCenterLineYOffset-sideButtonHeight/2;
      gtExpDirsAddButtonYOffset=gtTopLineYOffset-sideButtonHeight;
      gtExpDirsRemoveButtonYOffset=gtTopLineYOffset-sideButtonHeight-addRemoveInterButtonHeight-sideButtonHeight;

      bottomButtonYOffset=(bottomAreaHeight-bottomButtonHeight)/2;
        % for both Quit and Convert buttons

      projectFileTextWidth=centerColumnWidth;
      classifierFileTextWidth=centerColumnWidth;
      gtExpDirsListboxWidth=centerColumnWidth;

      projectFileTextHeight=fileNameTextHeight;
      classifierFileTextHeight=fileNameTextHeight;

      % Position the figure
      set(self.fig, ...
          'position',[figureXOffset figureYOffset figureWidth figureHeight]);

      % Position the labels
      set(self.projectFileLabelText, ...
          'position',[projectFileLabelTextXOffset projectFileLabelTextYOffset projectFileLabelTextSize]);
      set(self.classifierFileLabelText, ...
          'position',[classifierFileLabelTextXOffset classifierFileLabelTextYOffset classifierFileLabelTextSize]);
      set(self.gtExpDirsLabelText, ...
          'position',[gtExpDirsLabelTextXOffset gtExpDirsLabelTextYOffset gtExpDirsLabelTextSize]);

      % Position everything else
      set(self.projectFileText, ...
          'position',[projectFileTextXOffset ...
                      projectFileTextYOffset ...
                      projectFileTextWidth ...
                      projectFileTextHeight]);
      set(self.classifierFileText , ...
          'position',[classifierFileTextXOffset ...
                      classifierFileTextYOffset ...
                      classifierFileTextWidth ...
                      classifierFileTextHeight]);
      set(self.gtExpDirsListbox, ...
          'position',[gtExpDirsListboxXOffset ...
                      gtExpDirsListboxYOffset ...
                      gtExpDirsListboxWidth ...
                      gtExpDirsListboxHeight]);
      set(self.chooseProjectFileButton, ...
          'position',[chooseProjectFileButtonXOffset ...
                      chooseProjectFileButtonYOffset ...
                      sideButtonWidth ...
                      sideButtonHeight]);
      set(self.chooseClassifierFileButton, ...
          'position',[chooseClassifierFileButtonXOffset ...
                      chooseClassifierFileButtonYOffset ...
                      sideButtonWidth ...
                      sideButtonHeight]);
      set(self.gtExpDirsAddButton, ...
          'position',[gtExpDirsAddButtonXOffset ...
                      gtExpDirsAddButtonYOffset ...
                      sideButtonWidth ...
                      sideButtonHeight]);
      set(self.gtExpDirsRemoveButton, ...
          'position',[gtExpDirsRemoveButtonXOffset ...
                      gtExpDirsRemoveButtonYOffset ...
                      sideButtonWidth ...
                      sideButtonHeight]);
      set(self.convertButton, ...
          'position',[convertButtonXOffset ...
                      bottomButtonYOffset ...
                      bottomButtonWidth ...
                      bottomButtonHeight]);

      %
      % Update the score feature controls
      %
      delete(self.scoreFeatureLabelText(ishandle(self.scoreFeatureLabelText)));
      delete(self.scoreFeatureMatTexts(ishandle(self.scoreFeatureMatTexts)));
      delete(self.scoreFeatureJabTexts(ishandle(self.scoreFeatureJabTexts)));
      delete(self.chooseScoreFeatureJabButtons(ishandle(self.chooseScoreFeatureJabButtons)));
      self.scoreFeatureLabelText=nan;
      self.scoreFeatureMatTexts=nan(nScoreFeatures,1);
      self.scoreFeatureJabTexts=nan(nScoreFeatures,1);
      self.chooseScoreFeatureJabButtons=nan(nScoreFeatures,1);
      if nScoreFeatures>0
        self.scoreFeatureLabelText= ...
          uicontrol('parent',self.fig, ...
                    'units','points', ...
                    'style','text', ...
                    'backgroundcolor',get(self.fig,'color'), ...
                    'string',{'Score Feature ', ...
                              'File Names '}, ...
                    'HorizontalAlignment','right',...
                    'fontsize',12, ...
                    'visible','off');
        extent=get(self.scoreFeatureLabelText,'extent');
        extentSize=extent(3:4);
        scoreFeatureLabelTextSize=extentSize;
        scoreFeatureLabelTextXOffset=centerColumnXOffset-labelOffsetWidth-scoreFeatureLabelTextSize(1);
        scoreFeatureLabelTextYOffset=scoreFeatureAreaTopYOffset-scoreFeatureLabelTextSize(2);
        set(self.scoreFeatureLabelText, ...
            'position',[scoreFeatureLabelTextXOffset scoreFeatureLabelTextYOffset scoreFeatureLabelTextSize], ...
            'visible','on');
      end
      for i=1:nScoreFeatures
        % Create the mat file name text object for this one
        xOffset=centerColumnXOffset;
        yOffset=scoreFeatureAreaTopYOffset-(i-1)*2*fileNameTextHeight-fileNameTextHeight;
        width=centerColumnWidth;
        height=fileNameTextHeight;
        self.scoreFeatureMatTexts(i)= ...
          uicontrol('parent',self.fig, ...
                    'units','points', ...
                    'style','text', ...
                    'backgroundcolor',get(self.fig,'color'), ...
                    'string',sprintf('%s:',self.model.scoreFeatureMatFileNames{i}), ...
                    'HorizontalAlignment','left',...
                    'fontsize',12, ...
                    'position',[xOffset yOffset width height]);
        % Create the jab file name text object for this one
        xOffset=centerColumnXOffset+scoreFeatureJabIndentWidth;
        yOffset=yOffset-fileNameTextHeight;
        width=centerColumnWidth-scoreFeatureJabIndentWidth;
        height=fileNameTextHeight;
        self.scoreFeatureJabTexts(i)= ...
          uicontrol('parent',self.fig, ...
                    'units','points', ...
                    'style','text', ...
                    'backgroundcolor',get(self.fig,'color'), ...
                    'HorizontalAlignment','right',...
                    'fontsize',12, ...
                    'position',[xOffset yOffset width height]);
        % Create the 'Choose' button for this one
        xOffset=centerColumnXOffset+centerColumnWidth+sideButtonOffsetWidth+(sideButtonWidth-smallSideButtonWidth)/2;
        yOffset=yOffset+fileNameTextHeight-sideButtonHeight/2+(sideButtonHeight-smallSideButtonHeight)/2;
        width=smallSideButtonWidth;
        height=smallSideButtonHeight;
        self.chooseScoreFeatureJabButtons(i)= ...
          uicontrol('parent',self.fig, ...
                    'style','pushbutton', ...
                    'string','Choose', ...
                    'fontsize',12, ...
                    'units','points', ...
                    'callback',@(g,e)(self.controller.chooseScoreFeatureJabFileButtonPressed(self.model.scoreFeatureMatFileNames{i})), ...
                    'position',[xOffset yOffset width height]);
      end

      %
      % Update the contents of UI elements
      %

      % Update the project file text object
      if self.model.isProjectFileSpecified() ,
        set(self.projectFileText, ...
            'String',self.model.projectFileName, ...
            'FontAngle','normal');
      else
        set(self.projectFileText, ...
            'String','Not specified', ...
            'FontAngle','italic');
      end

      % Update the score feature jab file text object(s)
      for i=1:nScoreFeatures
        if self.model.isScoreFeatureJabFileSpecified(i) ,
          set(self.scoreFeatureJabTexts(i), ...
              'String',[self.model.scoreFeatureJabFileNames{i} ' '], ...
              'FontAngle','normal');
        else
          set(self.scoreFeatureJabTexts(i), ...
              'String','Not specified ', ...
              'FontAngle','italic');
        end
      end

      % Update the classifier file text object
      if self.model.isClassifierFileSpecified() ,
        set(self.classifierFileText, ...
            'String',self.model.classifierFileName, ...
            'FontAngle','normal');
      else
        set(self.classifierFileText, ...
            'String','Not specified', ...
            'FontAngle','italic');
      end

      % Update the GT experiment listbox
      set(self.gtExpDirsListbox,'String',self.model.gtExpDirNames);
      set(self.gtExpDirsListbox,'Value',self.model.iCurrentGTExpDir);

      % Update enablement of Remove button
      set(self.gtExpDirsRemoveButton,'enable',offIff(isempty(self.model.gtExpDirNames)));

      % Update enablement of convert button
      set(self.convertButton,'enable',onIff(self.model.isProjectFileSpecified()));
    end  % method

    % ---------------------------------------------------------------------
    function close(self)
      if ishandle(self.fig)
        delete(self.fig);
        self.fig=[];
      end
    end  % method

  end
end


function outcome=getOutcomeStr(obj, verbosity)
% give string indicating the outcome of the test
%
% outcome=getOutcomeStr(obj, verbosity)
%
% Inputs:
%   obj                 MOxUnitTestOutcome object
%   verbosity           Integer in the range [0,1,2]
%
% Returns:
%   outcome:            Depending on the value of verbosity
%                       0: ''
%                       1: 's'
%                       2: 'skipped'
%

    outcome_cell={'','s','skipped'};
    outcome=outcome_cell{verbosity+1};


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

% Last Modified by GUIDE v2.5 13-Apr-2012 20:57:39

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
    'gui_Singleton',  gui_Singleton, ...
    'gui_OpeningFcn', @gui_reviewresults_OpeningFcn, ...
    'gui_OutputFcn',  @gui_reviewresults_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 gui_reviewresults is made visible.
function gui_reviewresults_OpeningFcn(hObject, eventdata, handles, varargin)
% get data and options
data = varargin{1};
% set up default options for utl_summarize_structarray
opts = hlp_varargin2struct(varargin(2:end),'leftindent',[0 15],'rightindent',[0 15], ...
    'rewrite_fields',{'kld','KL divergence','nll','Negative log-likelihood', ...
                      'mcr','Error rate', 'mae','Mean abs error', 'mse','Mean square error',...
                      'max','Max absolut error','rms','Root mean square error','bias','Mean bias',...
                      'medse','Median square error','auc','Neg. area under ROC', ...
                      'cond_entropy','Conditional entropy','cross_entropy','Cross-Entropy', ...
                      'f_measure','Negative F-score','classes','Target classes','class_ratio','Class ratio', ...
                      'per_class','Per-class error','TP','True positive rate','TN','True negative rate',...
                      'FP','False positive rate','FN','False negative rate','measure','Measure',...
                      'targ','Targets','pred','Predictions','time','Runtime','target','Targets',...
                      'prediction','Predictions','expression','Reproducing expression','value','Value'});

% pick out the correct part of the array
if isscalar(data)
    sub_arrays = {};
    % check if some of the sub-fields are a struct arrays...
    for f=fieldnames(data)'
        field = data.(f{1});
        if isstruct(field) && ~isscalar(field)
            sub_arrays{end+1} = field; end
    end
    if length(sub_arrays) == 1
        % exactly one sub-array: take this as the data to summarize...
        data = sub_arrays{1};
    end
end

if isfield(data,'timestamp')
    data = rmfield(data,'timestamp'); end

% set the summary text
[text,handles.data] = summarize_structarray(data,opts);
set(handles.edit1,'String',[{''} text]);
set(handles.edit1,'Position',[0 0 1 1],'Units','normalized');

% create uitable and popuate with data
conts = handles.data.conts;
fullconts = handles.data.fullconts;
fnames = handles.data.fnames;
% no column is editable
columneditable = false(1,length(fnames));
% by default all columns are of type 'char'
columnformat = repmat({'char'},1,length(fnames));
for c=1:length(fullconts)
    col = fullconts{c};
    % check if all fields of a column are numeric or logical
    if all(cellfun(@isnumeric,conts{c}))
        columnformat{c} = 'numeric';
        for r=1:length(col)
            if isempty(col{r}) || ~isnumeric(col{r})
                col{r} = NaN; end
        end
    elseif all(cellfun(@islogical,conts{c}))
        columnformat{c} = 'logical';
    else
        % otherwise we convert to char what is not yet char
        for r=find(~cellfun('isclass',col,'char'))
            col{r} = hlp_tostring(col{r}); end
    end
    % ... and put it into the table data
    tabledata(:,c) = col;
end
handles.tabledata = tabledata;
handles.table1 = uitable('Data',tabledata,'ColumnName',fnames,'Parent',handles.uipanel2, ...
    'Units','normalized','Position',[0 0 1 1],'ColumnEditable',columneditable,'ColumnFormat',columnformat);
set(handles.table1,'Units','pixels')
wh = get(handles.table1,'Position');
colwidth = (wh(3)-35) / length(fnames);
set(handles.table1,'Units','normalized')
set(handles.table1,'ColumnWidth',repmat({round(colwidth)},1,length(fnames)));

% Choose default command line output for gui_reviewresults
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes gui_reviewresults wait for user response (see UIRESUME)
uiwait(handles.figure1);

% --- Outputs from this function are returned to the command line.
function varargout = gui_reviewresults_OutputFcn(hObject, eventdata, handles)
try
    varargout{1} = handles.output;
    close(handles.figure1);
catch
end

% help button
function pushbutton5_Callback(hObject, eventdata, handles)
disp('coming soon...');

% ok button
function pushbutton1_Callback(hObject, eventdata, handles)
uiresume(handles.figure1);

function figure1_KeyPressFcn(hObject, eventdata, handles)
if strcmp(eventdata.Key,'return') || strcmp(eventdata.Key,'escape')
    pushbutton1_Callback(handles.pushbutton1, eventdata, handles); end

% Explore button
function pushbutton4_Callback(hObject, eventdata, handles)
function pushbutton2_Callback(hObject, eventdata, handles)
function pushbutton3_Callback(hObject, eventdata, handles)
function figure1_CreateFcn(hObject, eventdata, handles)
function uipanel1_CreateFcn(hObject, eventdata, handles)
function edit1_Callback(hObject, eventdata, handles)
function edit1_CreateFcn(hObject, eventdata, handles)
function pushbutton6_Callback(hObject, eventdata, handles)
io_mkdirs('home:/.bcilab/results/');
[FileName,PathName] = uiputfile('*.csv','Save table',env_translatepath('home:/.bcilab/results/untitled.csv'));
if FileName
    csvwrite([PathName,FileName],handles.tabledata);  end

function pushbutton6_ButtonDownFcn(hObject, eventdata, handles)

function [text,results] = summarize_structarray(data,varargin)
% Summarize a struct array's fields in text form.
% Text = summarize_structarray(Data,Options...)
%
% This function takes a struct array and calculates summary statistics for each of its numeric
% fields, and outputs a textual report of the results. This is for the review results GUI.
%
% In:
%   Data : A struct array for which a summary report shall be generated.
%
%   Options... : additional name-value pairs; possible names are:
%
%                 --- content control ---
%                 'retain_items' : cell array of checker functions (as in cellfun) that all retained
%                                  data items must satisfy (default: {@isvector,@isnumeric,@isfinite})
%
%                 'retain_fields' : cell array of checker functions (as in cellfun) that all
%                                   retained fields must satisfy (default: {@isvector})
%
%                 'rewrite_fields' : cell array of rewrite rules for field names
%                                   (e.g.{'mcr','Mis-classification rate','auc','Area under Curve'})
%
%                 --- formatting control ---
%
%                 'lhs' : format of the left-hand side of each line (default: '%s')
%
%                 'sep' : separator string between left-hand side and right-hand side (default: ' : ')
%
%                 'rhs' : expression for the right-hand side of each line (in terms of X, the data)
%                         (default: 'sprintf(''%.3f +/- $.3f (N=%d)'',mean(X),std(X),length(X))')
%
%                 'leftspacing' : number of characters to reserve on the left-hand-side;
%                                minimum marging to first character, and minimum spacing to separator
%                                (default: [5 30])
%
%                 'rightspacing': number of characters to reserve on the right-hand-side;
%                                minimum marging from last character, and minimum spacing from
%                                separator (default: [5 15])
%
% Out:
%   Text : a textual summary, akin to what disp(data(1)) produces, but with means and std. devs
%
%                                Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
%                                2010-11-08

% get the options
hlp_varargin2struct(varargin, 'retain_items', {@(x)isscalar(x),@(x)~isempty(x),@isnumeric,@isfinite}, 'retain_fields',{@(x)~isempty(x)}, ...
    'rewrite_fields',{}, 'lhs','%s', 'sep',' : ', 'rhs','sprintf(''%.3f +/- %.3f (N=%d)'',mean(X),std(X),length(X))', ...
    'leftspacing',[5 0], 'rightspacing', [5 0]);

% get the field names
fnames = fieldnames(data)';
% get the raw contents
raw = struct2cell(data(:));
% reformat the contents
for r=1:size(raw,1)
   conts{r} = {raw{r,:}}; end

% reduce the data items
for r=1:length(conts)
    retain{r} = 1:length(conts{r}); end
for checker = retain_items
    for r=1:length(conts)
        retain{r} = retain{r}(cellfun(checker{1},conts{r}(retain{r}))); end
end
% reduce conts
for r=1:length(conts)
    fullconts{r} = cell(1,length(conts{r}));
    conts{r} = conts{r}(retain{r});
    fullconts{r}(retain{r}) = conts{r};
end

% reduce the fields
mask = 1:length(fnames);
for checker = retain_fields
    mask = mask(cellfun(checker{1},conts(mask))); end
fnames = fnames(mask);
fullconts = fullconts(mask);
conts = conts(mask);

% rewrite field names
for f=1:length(fnames)
    fnames{f} = hlp_rewrite(fnames{f},rewrite_fields{:}); end %#ok<USENS>

% create the text
text = cell(1,length(conts));
for r=1:length(conts)
    X = [conts{r}{:}]; %#ok<NASGU>
    left{r} = sprintf(lhs,fnames{r});
    right{r} = eval(rhs);
end

leftspacing = max(leftspacing(2),leftspacing(1)+max(cellfun('length',left))); %#ok<NODEF>
rightspacing = max(rightspacing(2),rightspacing(1)+max(cellfun('length',right))); %#ok<NODEF>
for r=1:length(conts)
    left{r} = [repmat(' ',1,leftspacing - length(left{r})) left{r}];
    right{r} = [right{r} repmat(' ',1,rightspacing - length(right{r})) ];
    text{r} = [left{r} sep right{r}];
end

if nargout == 0
    fprintf('\n');
    % print the text to the console
    for r=1:length(text)
        fprintf([text{r} '\n']); end
    fprintf('\n');
else
    % create results structure
    results.text = text;
    results.fnames = fnames;
    results.conts = conts;
    results.fullconts = fullconts;
end


function bbci_log_write(fid, format, varargin)
%BBCI_LOG_WRITE - Print information to screen or file
%
%Synopsis:
%  bbci_log_write(FID, FORMAT, PARAM1, ...)
%  bbci_log_write(DATA, FORMAT, PARAM1, ...)
%
%Arguments:
%  FID    - Vector of file identifier, e.g. [1 file_id] for printing log
%           log information to the screen and to the file of ID file_id.
%  DATA   - DATA struct as in bbci_calibate and bbci_apply. The FID of
%           the log file is in the subfield DATA.log.fid.
%  FORMAT - As for fprintf.
%  PARAMx - Parameters passed to fprintf.

if isstruct(fid),  % First input argument is given as DATA
  fid= fid.log.fid;
end

for k= 1:length(fid),
  fprintf(fid(k), [format '\n'], varargin{:});
end


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

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

% Last Modified by GUIDE v2.5 09-Sep-2014 18:16:51

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

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

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

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

%%% REPLACE THIS WITH A CALL TO GET CEL BODY DATA FROM MAIN KSPTOT GUI %%%
celBodyData = varargin{1};
setappdata(handles.rtsMainGUI,'CelBodyData',celBodyData);
setappdata(handles.rtsMainGUI,'ChildGUIs',{});

rtsHost = varargin{2};
setappdata(handles.rtsMainGUI,'RHost',rtsHost);

mainGUIFig = varargin{3};
setappdata(handles.rtsMainGUI,'mainGUIFig',mainGUIFig);

rtsOpts = struct();
rtsOpts.tmTransRate = '1';
rtsOpts.procExecMode = 'fixedRate';
rtsOpts.processFreq = '0.5';
setappdata(handles.rtsMainGUI,'RTSOptions',rtsOpts);

% Initialize RTS Main Panel
initRTSMainPanel(handles.rtsMainGUI);

% Update handles structure
if(ishandle(hObject))
    guidata(hObject, handles);
end

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

function initRTSMainPanel(hRtsMainGUI)
    rts_StartTMStream(hRtsMainGUI);
end

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

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

% --- Executes on button press in rts_OrbOpsPageButton.
function rts_OrbOpsPageButton_Callback(hObject, eventdata, handles)
% hObject    handle to rts_OrbOpsPageButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA).
    vesselGUID = getappdata(handles.rtsMainGUI,'VesselGUID');
    h = rts_OrbOpsConsole(handles.rtsMainGUI, vesselGUID);
    ChildGUIs = getappdata(handles.rtsMainGUI,'ChildGUIs');
    ChildGUIs{end+1} = h;
    setappdata(handles.rtsMainGUI,'ChildGUIs',ChildGUIs);
end

% --- Executes on button press in rts_SCDynPageButton.
function rts_SCDynPageButton_Callback(hObject, eventdata, handles)
% hObject    handle to rts_SCDynPageButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    vesselGUID = getappdata(handles.rtsMainGUI,'VesselGUID');
    h = rts_DynConsole(handles.rtsMainGUI, vesselGUID);
    ChildGUIs = getappdata(handles.rtsMainGUI,'ChildGUIs');
    ChildGUIs{end+1} = h;
    setappdata(handles.rtsMainGUI,'ChildGUIs',ChildGUIs);
end

% --- Executes on button press in rts_PwrThrmlPageButton.
function rts_PwrThrmlPageButton_Callback(hObject, eventdata, handles)
% hObject    handle to rts_PwrThrmlPageButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    vesselGUID = getappdata(handles.rtsMainGUI,'VesselGUID');
    h = rts_PwrThermConsole(handles.rtsMainGUI, vesselGUID);
    ChildGUIs = getappdata(handles.rtsMainGUI,'ChildGUIs');
    ChildGUIs{end+1} = h;
    setappdata(handles.rtsMainGUI,'ChildGUIs',ChildGUIs);
end

% --- Executes on button press in rts_PropPageButton.
function rts_PropPageButton_Callback(hObject, eventdata, handles)
% hObject    handle to rts_PropPageButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    vesselGUID = getappdata(handles.rtsMainGUI,'VesselGUID');
    h = rts_PropConsole(handles.rtsMainGUI, vesselGUID);
    ChildGUIs = getappdata(handles.rtsMainGUI,'ChildGUIs');
    ChildGUIs{end+1} = h;
    setappdata(handles.rtsMainGUI,'ChildGUIs',ChildGUIs);
end

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

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

% Hint: delete(hObject) closes the figure
    rts_EndTMStream(handles.rtsMainGUI, true, false, false);
    ChildGUIs = getappdata(handles.rtsMainGUI,'ChildGUIs');
    for(i=1:length(ChildGUIs))
        if(ishandle(ChildGUIs{i}))
            delete(ChildGUIs{i});
        end
    end
    delete(hObject);
end

% --------------------------------------------------------------------
function connect2KSPTOTConnect_Callback(hObject, eventdata, handles)
% hObject    handle to connect2KSPTOTConnect (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    rts_StartTMStream(handles.rtsMainGUI);
end

% --------------------------------------------------------------------
function disconnectFromKSPTOTConnect_Callback(hObject, eventdata, handles)
% hObject    handle to disconnectFromKSPTOTConnect (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    rts_EndTMStream(handles.rtsMainGUI, false, false, false);
end

% --- Executes on button press in rts_TMMonUtilButton.
function rts_TMMonUtilButton_Callback(hObject, eventdata, handles)
% hObject    handle to rts_TMMonUtilButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    vesselGUID = getappdata(handles.rtsMainGUI,'VesselGUID');
    h = rts_TmMonitorConsole(handles.rtsMainGUI, vesselGUID);
    ChildGUIs = getappdata(handles.rtsMainGUI,'ChildGUIs');
    ChildGUIs{end+1} = h;
    setappdata(handles.rtsMainGUI,'ChildGUIs',ChildGUIs);
end

% --------------------------------------------------------------------
function exitGUI_Callback(hObject, eventdata, handles)
% hObject    handle to exitGUI (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    ChildGUIs = getappdata(handles.rtsMainGUI,'ChildGUIs');
    for(i=1:length(ChildGUIs))
        if(ishandle(ChildGUIs{i}))
            close(ChildGUIs{i});
        end
    end
    close(handles.rtsMainGUI);
end

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

% --------------------------------------------------------------------
function connect2NewVessel_Callback(hObject, eventdata, handles)
% hObject    handle to connect2NewVessel (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    rts_EndTMStream(handles.rtsMainGUI, true, false, true);
    rts_StartTMStream(handles.rtsMainGUI);
end

% --------------------------------------------------------------------
function rtsOptions_Callback(hObject, eventdata, handles)
% hObject    handle to rtsOptions (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    rts_kspTotConnectOptions(handles.rtsMainGUI);
end

% --------------------------------------------------------------------
function terminateTMStream_Callback(hObject, eventdata, handles)
% hObject    handle to terminateTMStream (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    rts_EndTMStream(handles.rtsMainGUI, true, false, true);
end


classdef spatiotemporal_datasource
   %UNTITLED2 Summary of this class goes here
   %   Detailed explanation goes here

   properties
   end

   methods
      function data = retrieve(obj, where_, from_ , until_)
         error('unimplemented base datasource class');
      end

   end

end


% check whether a variable is in GPU or not
function output = IsInGPU(x)
if strcmpi(class(x), 'gpuArray')
    output = 1;
else
    output = 0;
end
end