%  internal function

%  - Jimmy Shen (jimmy@rotman-baycrest.on.ca)

function [hdr, filetype, fileprefix, machine] = load_nii_hdr(fileprefix)

   if ~exist('fileprefix','var'),
      error('Usage: [hdr, filetype, fileprefix, machine] = load_nii_hdr(filename)');
   end

   machine = 'ieee-le';
   new_ext = 0;

   if findstr('.nii',fileprefix) & strcmp(fileprefix(end-3:end), '.nii')
      new_ext = 1;
      fileprefix(end-3:end)='';
   end

   if findstr('.hdr',fileprefix) & strcmp(fileprefix(end-3:end), '.hdr')
      fileprefix(end-3:end)='';
   end

   if findstr('.img',fileprefix) & strcmp(fileprefix(end-3:end), '.img')
      fileprefix(end-3:end)='';
   end

   if new_ext
      fn = sprintf('%s.nii',fileprefix);

      if ~exist(fn)
         msg = sprintf('Cannot find file "%s.nii".', fileprefix);
         error(msg);
      end
   else
      fn = sprintf('%s.hdr',fileprefix);

      if ~exist(fn)
         msg = sprintf('Cannot find file "%s.hdr".', fileprefix);
         error(msg);
      end
   end

   fid = fopen(fn,'r',machine);

   if fid < 0,
      msg = sprintf('Cannot open file %s.',fn);
      error(msg);
   else
      fseek(fid,0,'bof');

      if fread(fid,1,'int32') == 348
         hdr = read_header(fid);
         fclose(fid);
      else
         fclose(fid);

         %  first try reading the opposite endian to 'machine'
         %
         switch machine,
         case 'ieee-le', machine = 'ieee-be';
         case 'ieee-be', machine = 'ieee-le';
         end

         fid = fopen(fn,'r',machine);

         if fid < 0,
            msg = sprintf('Cannot open file %s.',fn);
            error(msg);
         else
            fseek(fid,0,'bof');

            if fread(fid,1,'int32') ~= 348

               %  Now throw an error
               %
               msg = sprintf('File "%s" is corrupted.',fn);
               error(msg);
            end

            hdr = read_header(fid);
            fclose(fid);
         end
      end
   end

   if strcmp(hdr.hist.magic, 'n+1')
      filetype = 2;
   elseif strcmp(hdr.hist.magic, 'ni1')
      filetype = 1;
   else
      filetype = 0;
   end

   return					% load_nii_hdr

%---------------------------------------------------------------------
function [ dsr ] = read_header(fid)

        %  Original header structures
	%  struct dsr
	%       {
	%       struct header_key hk;            /*   0 +  40       */
	%       struct image_dimension dime;     /*  40 + 108       */
	%       struct data_history hist;        /* 148 + 200       */
	%       };                               /* total= 348 bytes*/

    dsr.hk   = header_key(fid);
    dsr.dime = image_dimension(fid);
    dsr.hist = data_history(fid);

    %  For Analyze data format
    %
    if ~strcmp(dsr.hist.magic, 'n+1') & ~strcmp(dsr.hist.magic, 'ni1')
        dsr.hist.qform_code = 0;
        dsr.hist.sform_code = 0;
    end

    return					% read_header

%---------------------------------------------------------------------
function [ hk ] = header_key(fid)

    fseek(fid,0,'bof');

	%  Original header structures
	%  struct header_key                     /* header key      */
	%       {                                /* off + size      */
	%       int sizeof_hdr                   /*  0 +  4         */
	%       char data_type[10];              /*  4 + 10         */
	%       char db_name[18];                /* 14 + 18         */
	%       int extents;                     /* 32 +  4         */
	%       short int session_error;         /* 36 +  2         */
	%       char regular;                    /* 38 +  1         */
	%       char dim_info;   % char hkey_un0;        /* 39 +  1 */
	%       };                               /* total=40 bytes  */
	%
	% int sizeof_header   Should be 348.
	% char regular        Must be 'r' to indicate that all images and
	%                     volumes are the same size.

    v6 = version;
    if str2num(v6(1))<6
       directchar = '*char';
    else
       directchar = 'uchar=>char';
    end

    hk.sizeof_hdr    = fread(fid, 1,'int32')';	% should be 348!
    hk.data_type     = deblank(fread(fid,10,directchar)');
    hk.db_name       = deblank(fread(fid,18,directchar)');
    hk.extents       = fread(fid, 1,'int32')';
    hk.session_error = fread(fid, 1,'int16')';
    hk.regular       = fread(fid, 1,directchar)';
    hk.dim_info      = fread(fid, 1,'uchar')';

    return					% header_key

%---------------------------------------------------------------------
function [ dime ] = image_dimension(fid)

	%  Original header structures
	%  struct image_dimension
	%       {                                /* off + size      */
	%       short int dim[8];                /* 0 + 16          */
        %       /*
        %           dim[0]      Number of dimensions in database; usually 4.
        %           dim[1]      Image X dimension;  number of *pixels* in an image row.
        %           dim[2]      Image Y dimension;  number of *pixel rows* in slice.
        %           dim[3]      Volume Z dimension; number of *slices* in a volume.
        %           dim[4]      Time points; number of volumes in database
        %       */
	%       float intent_p1;   % char vox_units[4];   /* 16 + 4       */
	%       float intent_p2;   % char cal_units[8];   /* 20 + 4       */
	%       float intent_p3;   % char cal_units[8];   /* 24 + 4       */
	%       short int intent_code;   % short int unused1;   /* 28 + 2 */
	%       short int datatype;              /* 30 + 2          */
	%       short int bitpix;                /* 32 + 2          */
	%       short int slice_start;   % short int dim_un0;   /* 34 + 2 */
	%       float pixdim[8];                 /* 36 + 32         */
	%	/*
	%		pixdim[] specifies the voxel dimensions:
	%		pixdim[1] - voxel width, mm
	%		pixdim[2] - voxel height, mm
	%		pixdim[3] - slice thickness, mm
	%		pixdim[4] - volume timing, in msec
	%					..etc
	%	*/
	%       float vox_offset;                /* 68 + 4          */
	%       float scl_slope;   % float roi_scale;     /* 72 + 4 */
	%       float scl_inter;   % float funused1;      /* 76 + 4 */
	%       short slice_end;   % float funused2;      /* 80 + 2 */
	%       char slice_code;   % float funused2;      /* 82 + 1 */
	%       char xyzt_units;   % float funused2;      /* 83 + 1 */
	%       float cal_max;                   /* 84 + 4          */
	%       float cal_min;                   /* 88 + 4          */
	%       float slice_duration;   % int compressed; /* 92 + 4 */
	%       float toffset;   % int verified;          /* 96 + 4 */
	%       int glmax;                       /* 100 + 4         */
	%       int glmin;                       /* 104 + 4         */
	%       };                               /* total=108 bytes */

    dime.dim        = fread(fid,8,'int16')';
    dime.intent_p1  = fread(fid,1,'float32')';
    dime.intent_p2  = fread(fid,1,'float32')';
    dime.intent_p3  = fread(fid,1,'float32')';
    dime.intent_code = fread(fid,1,'int16')';
    dime.datatype   = fread(fid,1,'int16')';
    dime.bitpix     = fread(fid,1,'int16')';
    dime.slice_start = fread(fid,1,'int16')';
    dime.pixdim     = fread(fid,8,'float32')';
    dime.vox_offset = fread(fid,1,'float32')';
    dime.scl_slope  = fread(fid,1,'float32')';
    dime.scl_inter  = fread(fid,1,'float32')';
    dime.slice_end  = fread(fid,1,'int16')';
    dime.slice_code = fread(fid,1,'uchar')';
    dime.xyzt_units = fread(fid,1,'uchar')';
    dime.cal_max    = fread(fid,1,'float32')';
    dime.cal_min    = fread(fid,1,'float32')';
    dime.slice_duration = fread(fid,1,'float32')';
    dime.toffset    = fread(fid,1,'float32')';
    dime.glmax      = fread(fid,1,'int32')';
    dime.glmin      = fread(fid,1,'int32')';

    return					% image_dimension

%---------------------------------------------------------------------
function [ hist ] = data_history(fid)

	%  Original header structures
	%  struct data_history
	%       {                                /* off + size      */
	%       char descrip[80];                /* 0 + 80          */
	%       char aux_file[24];               /* 80 + 24         */
	%       short int qform_code;            /* 104 + 2         */
	%       short int sform_code;            /* 106 + 2         */
	%       float quatern_b;                 /* 108 + 4         */
	%       float quatern_c;                 /* 112 + 4         */
	%       float quatern_d;                 /* 116 + 4         */
	%       float qoffset_x;                 /* 120 + 4         */
	%       float qoffset_y;                 /* 124 + 4         */
	%       float qoffset_z;                 /* 128 + 4         */
	%       float srow_x[4];                 /* 132 + 16        */
	%       float srow_y[4];                 /* 148 + 16        */
	%       float srow_z[4];                 /* 164 + 16        */
	%       char intent_name[16];            /* 180 + 16        */
	%       char magic[4];   % int smin;     /* 196 + 4         */
	%       };                               /* total=200 bytes */

    v6 = version;
    if str2num(v6(1))<6
       directchar = '*char';
    else
       directchar = 'uchar=>char';
    end

    hist.descrip     = deblank(fread(fid,80,directchar)');
    hist.aux_file    = deblank(fread(fid,24,directchar)');
    hist.qform_code  = fread(fid,1,'int16')';
    hist.sform_code  = fread(fid,1,'int16')';
    hist.quatern_b   = fread(fid,1,'float32')';
    hist.quatern_c   = fread(fid,1,'float32')';
    hist.quatern_d   = fread(fid,1,'float32')';
    hist.qoffset_x   = fread(fid,1,'float32')';
    hist.qoffset_y   = fread(fid,1,'float32')';
    hist.qoffset_z   = fread(fid,1,'float32')';
    hist.srow_x      = fread(fid,4,'float32')';
    hist.srow_y      = fread(fid,4,'float32')';
    hist.srow_z      = fread(fid,4,'float32')';
    hist.intent_name = deblank(fread(fid,16,directchar)');
    hist.magic       = deblank(fread(fid,4,directchar)');

    fseek(fid,253,'bof');
    hist.originator  = fread(fid, 5,'int16')';

    return					% data_history


function s=get_name(a)

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

s=[s ' m=' num2str(a.m)];
if a.n~=30          s=[s ' n='  num2str(a.n)];      end;


%% Example of using KST class for interfacing with KUKA iiwa robots

% Drawing a sequare with a pen using the KUKA iiwa robot

% An example script, it is used to show how to use the different
% functions of the KUKA Sunrise Toolbox

% First start the server on the KUKA iiwa controller
% Then run the following script in Matlab

% be careful when runnning the script, be sure that no human, nor obstacles
% are around the robot

% This example works with Sunrise application version KST_1.7  and higher.
% Copyright Mohammad SAFEEA, 26th-June-2018

close all;clear;clc;
warning('off')
%% Create the robot object
ip='172.31.1.147'; % The IP of the controller
arg1=KST.LBR7R800; % choose the robot iiwa7R800 or iiwa14R820
arg2=KST.Medien_Flansch_elektrisch; % choose the type of flange
Tef_flange=eye(4); % transofrm matrix of EEF with respect to flange
iiwa=KST(ip,arg1,arg2,Tef_flange); % create the object

%% Start a connection with the server
flag=iiwa.net_establishConnection();
if flag==0
    return;
end
pause(1);
disp('Doing some stuff')

%% move to initial position
jPos_init={0,pi*20/180,0,-pi*70/180,0,pi*90/180,0}; % initial confuguration
VEL=0.15; % relative velocity
iiwa.movePTPJointSpace(jPos_init, VEL); % point to point motion in joint space

%% Get position roientation of end effector
disp('Cartesian position')
Pos=iiwa.getEEFPos();
disp(Pos);
z_1=Pos{3}; % save initial hight level
z0=448+3; % go to writing position
VEL=50; % velocity of the end effector, mm/sec

%% Insert the Pen at box level
Pos{3}=z0; %% first point
iiwa.movePTPLineEEF(Pos, VEL);

disp=50*2; % length of the side of the sequare

%% move in x positive direction
Pos{1}=Pos{1}+disp;
iiwa.movePTPLineEEF(Pos, VEL)

%% move in y negative direction
Pos{2}=Pos{2}-disp;
iiwa.movePTPLineEEF(Pos, VEL)

%% move in x negative direction
Pos{1}=Pos{1}-disp;
iiwa.movePTPLineEEF(Pos, VEL)

%% move in y positive direction
Pos{2}=Pos{2}+disp;
iiwa.movePTPLineEEF(Pos, VEL)

%% Go back to initial position
Pos{3}=z_1;
iiwa.movePTPLineEEF(Pos, VEL)

%% turn off the server
iiwa.net_turnOffServer();


function filum_test02 ( )

%*****************************************************************************80
%
%% TEST02 tests FILE_CHAR_COUNT.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    06 June 2007
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST02\n' );
  fprintf ( 1, '  FILE_CHAR_COUNT counts the characters in a file.\n' );

  filename = 'story.txt';

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Examining file:\n' );
  fprintf ( 1, '    "%s".', filename );
  fprintf ( 1, '\n' );

  char_num = file_char_count ( filename );
  fprintf ( 1, '  Number of characters in file: %d\n', char_num );

  return
end


% delete mesh, algorithm, or everything at once
% Danil Kirsanov, 09/2007

function object = geodesic_delete(object)

global geodesic_library;
if ~libisloaded(geodesic_library)       %everything is already cleared
    object = [];
    return;
end

if nargin == 0          % the simplest way to delete everything is to unload the library
   unloadlibrary(geodesic_library);
else
    if libisloaded(geodesic_library)
        if strcmp(object.object_type, 'mesh')
            calllib(geodesic_library, 'delete_mesh', object.id);      % delete mesh and corresponding algorithms
        else
            calllib(geodesic_library, 'delete_algorithm', object.id); % delete a single algorithm
        end
    end
end
object = [];


classdef PrecomputedVariableTest < handle

    properties (Access = protected)
        testName
        variablesToStore
        storedVar
        computedVar
        computation
        computerType
        testResultsName
    end

    methods (Access = public)

        function obj = PrecomputedVariableTest(cParams)
            obj.init(cParams);
            obj.computeVariable(cParams);
            obj.selectComputedVar();
            obj.loadStoredVariable();
        end

        function error = computeError(obj)
            d = numel(obj.variablesToStore);
            err = ones(d,1);
            for ivar = 1:d
                sV = obj.storedVar{ivar};
                cV = obj.computedVar{ivar};
                err(ivar) = norm(sV - cV)/norm(sV);
            end
            error = norm(err);
        end

        function overwriteResults(obj)
            % NOTE: change the variable name "x" to the one in the .mat
            % file so that it works
            variableNames = who('-file', obj.testResultsName);
            d = numel(variableNames);
            for ivar = 1:d
                varName = variableNames{ivar};
                eval([varName ' = obj.computedVar{ivar}' ])
                save(obj.testResultsName, varName, '-append')
            end
        end

        function comp = getComputation(obj)
            comp = obj.computation;
        end
    end

    methods (Access = private)

        function init(obj, cParams)
            obj.testName         = cParams.testName;
            obj.variablesToStore = cParams.variablesToStore;
            obj.computerType     = cParams.computerType;
            obj.testResultsName  = cParams.testName;
            if isfield(cParams, 'testResultsName')
                obj.testResultsName = cParams.testResultsName;
            end
        end

        function computeVariable(obj, s)
            s.testName = obj.testName;
            testComputer = TestComputer.create(obj.computerType, s);
            testComputer.compute();
            obj.computation = testComputer.computation;
        end

        function selectComputedVar(obj)
            toStore = obj.variablesToStore;
            comp = obj.computation;
            if isprop(comp, 'variables')
                vars = obj.computation.variables;
            elseif isprop(comp, 'designVariable')
                vars = struct(obj.computation.designVariable);
                valX = toStore{1};
                [vars.(valX)] = vars.value;
                vars = rmfield(vars, 'value');
            end
            fnms = fieldnames(vars);
            totalComputationVariables = numel(fnms);
            totalStoredVariables = size(toStore,2);
            for i = 1:totalComputationVariables
                calcVar = fnms(i);
                for j = 1:totalStoredVariables
                    storVar = toStore(j);
                    if strcmp(calcVar, storVar)
                        obj.computedVar{j} = vars.(fnms{i});
                        break
                    end
                end
            end
        end

        function loadStoredVariable(obj)
            file2load = obj.testResultsName;
            load(file2load);
            for icell = 1:numel(obj.variablesToStore)
              obj.storedVar{icell} = eval(obj.variablesToStore{icell});
            end
        end

    end

end


function opt=varargin2struct(varargin)
%
% opt=varargin2struct('param1',value1,'param2',value2,...)
%   or
% opt=varargin2struct(...,optstruct,...)
%
% convert a series of input parameters into a structure
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% date: 2012/12/22
%
% input:
%      'param', value: the input parameters should be pairs of a string and a value
%       optstruct: if a parameter is a struct, the fields will be merged to the output struct
%
% output:
%      opt: a struct where opt.param1=value1, opt.param2=value2 ...
%
% license:
%     BSD or GPL version 3, see LICENSE_{BSD,GPLv3}.txt files for details
%
% -- this function is part of jsonlab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%

len=length(varargin);
opt=struct;
if(len==0) return; end
i=1;
while(i<=len)
    if(isstruct(varargin{i}))
        opt=mergestruct(opt,varargin{i});
    elseif(ischar(varargin{i}) && i<len)
        opt=setfield(opt,varargin{i},varargin{i+1});
        i=i+1;
    else
        error('input must be in the form of ...,''name'',value,... pairs or structs');
    end
    i=i+1;
end


function value = p21_i4 ( action, name, value )

%*****************************************************************************80
%
%% P21_I4 sets or gets I4 parameters for problem 21.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    18 March 2007
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string ACTION,
%    'D' to set a parameter to its default value.
%    'S' to set a parameter,
%    'G' to get a parameter,
%    'I' to increment a parameter.
%
%    Input, string NAME, the name of the variable.
%    '#' is the number of calls to the integrand routine.
%
%    Input/output, integer VALUE.
%    * If ACTION = 'I', then VALUE is an input quantity, and is the
%      new value to be added to NAME.
%    * If ACTION = 'S', then VALUE is an input quantity, and is the
%      new value to be assigned to NAME.
%    * If ACTION = 'G', then VALUE is an output quantity, and is the
%      current value of NAME.
%
  persistent calls;

  if ( action == 'D' | action == 'd' )

    if ( name == '#' | name == '*' )
      calls = 0;
    end

  elseif ( action == 'G' | action == 'g' )

    if ( name == '#' )
      value = calls;
    else
      fprintf ( 1, '\n' );
      fprintf ( 1, 'P21_I4 - Fatal error!\n' );
      fprintf ( 1, '  Unrecognized name = "%s".\n', name );
      error ( 'P21_I4 - Fatal error!' );
    end

  elseif ( action == 'I' | action == 'i' )

    if ( name == '#' )
      calls = calls + value;
    else
      fprintf ( 1, '\n' );
      fprintf ( 1, 'P21_I4 - Fatal error!\n' );
      fprintf ( 1, '  Unrecognized name = "%s".\n', name );
      error ( 'P21_I4 - Fatal error!' );
    end

  elseif ( action == 'S' | action == 's' )

    if ( name == '#' )
      calls = value;
    else
      fprintf ( 1, '\n' );
      fprintf ( 1, 'P21_I4 - Fatal error!\n' );
      fprintf ( 1, '  Unrecognized name = "%s".\n', name );
      error ( 'P21_I4 - Fatal error!' );
    end

  else

    fprintf ( 1, '\n' );
    fprintf ( 1, 'P21_I4 - Fatal error!\n' );
    fprintf ( 1, '  Unrecognized action = "%s".\n', action );
    error ( 'P21_I4 - Fatal error!' );

  end

  return
end


% Base class for all estimators in KAFBOX.
%
% This file is part of the Kernel Adaptive Filtering Toolbox for Matlab.
% https://github.com/steven2358/kafbox/

classdef base_estimator < matlab.mixin.Copyable
    methods
        % get parameter names for the estimator
        function names = get_param_names(obj)
            names = fieldnames(obj);
        end

        % get parameters
        function params = get_params(obj)
            params = struct;
            for fn = fieldnames(obj)'
                params.(fn{1}) = obj.(fn{1});
            end
        end

        % set parameters
        function set_params(obj,params)
            if (nargin > 0) % copy valid parameters
                for fn = fieldnames(params)'
                    if ismember(fn{1},fieldnames(obj))
                        values = params.(fn{1});
                        obj.(fn{1}) = values;
                    else
                        warning('Unknown parameter: %s.',fn{1});
                    end
                end
            end
        end
    end
end


function res = chanlabels(this, varargin)
% Method for getting/setting the channel labels
% FORMAT res = chanlabels(this, ind, label)
% _______________________________________________________________________
% Copyright (C) 2008-2012 Wellcome Trust Centre for Neuroimaging

% Vladimir Litvak
% $Id: chanlabels.m 5933 2014-03-28 13:22:28Z vladimir $

if this.montage.Mind == 0
    if nargin == 3
        ind = varargin{1};
        label = varargin{2};

        if iscell(label) && length(label)>1
            if isnumeric(ind) && length(ind)~=length(label)
                error('Indices and values do not match');
            end

            if length(label)>1
                for i = 1:length(label)
                    for j = (i+1):length(label)
                        if strcmp(label{i}, label{j})
                            error('All labels must be different');
                        end
                    end
                end
            end

        end
    end

    res = getset(this, 'channels', 'label', varargin{:});
else
% case with an online montage applied
    if nargin == 3
        ind = varargin{1};
        label = varargin{2};

        if iscell(label) && length(label)>1
            if isnumeric(ind) && length(ind)~=length(label)
                error('Indices and values do not match');
            end

            if length(label)>1
                for i = 1:length(label)
                    for j = (i+1):length(label)
                        if strcmp(label{i}, label{j})
                            error('All labels must be different');
                        end
                    end
                end
            end

        end

        this.montage.M(this.montage.Mind) = getset(this.montage.M(this.montage.Mind), 'channels', 'label', varargin{:});
        res = this;
    else
        res = getset(this.montage.M(this.montage.Mind), 'channels', 'label', varargin{:});
    end

end


function spm_defaults
% Set the defaults which are used by SPM
%__________________________________________________________________________
%
% If you want to customise some defaults for your installation, do not
% modify this file directly, but create a file named spm_my_defaults.m
% instead, accessible from MATLAB search path; e.g., it can be saved in
% MATLAB Startup Folder: userhome/Documents/MATLAB.
%
% Example: create the following file to change the image file extension:
% ----------- file /home/karl/Documents/MATLAB/spm_my_defaults.m -----------
% global defaults
% defaults.images.format = 'img';
%--------------------------------------------------------------------------
%
% spm_defaults should not be called directly in any script or function
% (apart from SPM internals).
% To load the defaults, use spm('Defaults',modality).
% To get/set the defaults, use spm_get_defaults.
%
%                 ** This file should not be edited **
%__________________________________________________________________________
% Copyright (C) 1994-2014 Wellcome Trust Centre for Neuroimaging

% SPM
% $Id: spm_defaults.m 6255 2014-11-05 09:55:02Z christophe $

global defaults

% Command Line Usage default
%==========================================================================
defaults.cmdline  = 0;

% User Interface defaults
%==========================================================================
defaults.ui.monitor = NaN;
defaults.ui.colour  = [0.58 0.77 0.57];
defaults.ui.fs      = 14;  % unused
defaults.ui.print   = 'ps';
defaults.renderer   = 'zbuffer';

% File format specific
%==========================================================================
% Note that defaults.analyze.flip is no longer used.  Specifying the
% left/right handedness of the voxel indices is now done entirely by
% spm_flip_analyze_images.m
defaults.images.format  = 'nii'; % options: 'img', 'nii'
defaults.mat.format     = '-v6'; % options: '-mat', '-v6', '-v7.0', '-v7.3'

% Toolboxes defaults
%==========================================================================
defaults.tbx.dir = { fullfile(spm('Dir'),'toolbox') };

% DICOM Import defaults
%==========================================================================
defaults.dicom.root = 'flat'; % Folder hierarchy

% fMRI design defaults
%==========================================================================
defaults.stats.fmri.t   = 16;
defaults.stats.fmri.t0  = 8;
defaults.stats.fmri.hpf = 128;
defaults.stats.fmri.cvi = 'AR(1)';

% Mask defaults
%==========================================================================
defaults.mask.thresh    = 0.8;

% Stats defaults
%==========================================================================
defaults.stats.maxmem      = 2^26;
defaults.stats.maxres      = 64;
defaults.stats.resmem      = false;
defaults.stats.fmri.ufp    = 0.001;  % Upper tail F-probability
defaults.stats.pet.ufp     = 0.05;
defaults.stats.eeg.ufp     = 0.05;
defaults.stats.topoFDR     = 1;
defaults.stats.rft.nonstat = 0;
defaults.stats.results.volume.distmin =  8;
defaults.stats.results.volume.nbmax   =  3;
defaults.stats.results.svc.distmin    =  4;
defaults.stats.results.svc.nbmax      = 16;
defaults.stats.results.mipmat         = {fullfile(spm('dir'),'MIP.mat')};

% Filename prefix defaults
%==========================================================================
defaults.slicetiming.prefix     = 'a';
defaults.realign.write.prefix   = 'r';
defaults.coreg.write.prefix     = 'r';
defaults.unwarp.write.prefix    = 'u';
defaults.normalise.write.prefix = 'w';
defaults.smooth.prefix          = 's';
defaults.imcalc.prefix          = 'i';

% Realignment defaults
%==========================================================================
defaults.realign.estimate.quality = 0.9;
defaults.realign.estimate.interp  = 2;
defaults.realign.estimate.wrap    = [0 0 0];
defaults.realign.estimate.sep     = 4;
defaults.realign.estimate.fwhm    = 5;
defaults.realign.estimate.rtm     = 1;
defaults.realign.write.mask       = 1;
defaults.realign.write.interp     = 4;
defaults.realign.write.wrap       = [0 0 0];
defaults.realign.write.which      = [2 1];

% Unwarp defaults
%==========================================================================
defaults.unwarp.estimate.rtm      = 0;
defaults.unwarp.estimate.fwhm     = 4;
defaults.unwarp.estimate.basfcn   = [12 12];
defaults.unwarp.estimate.regorder = 1;
defaults.unwarp.estimate.regwgt   = 1e5;
defaults.unwarp.estimate.foe      = [4 5];
defaults.unwarp.estimate.soe      = [];
defaults.unwarp.estimate.rem      = 1;
defaults.unwarp.estimate.jm       = 0;
defaults.unwarp.estimate.noi      = 5;
defaults.unwarp.estimate.expround = 'Average';
%
% Unwarp uses defaults.realign.write defaults for writing.
%

% Coregistration defaults
%==========================================================================
defaults.coreg.estimate.cost_fun = 'nmi';
defaults.coreg.estimate.sep      = [4 2];
defaults.coreg.estimate.tol      = [0.02 0.02 0.02 0.001 0.001 0.001 0.01 0.01 0.01 0.001 0.001 0.001];
defaults.coreg.estimate.fwhm     = [7 7];
defaults.coreg.write.interp      = 4;
defaults.coreg.write.wrap        = [0 0 0];
defaults.coreg.write.mask        = 0;

% Spatial Normalisation defaults
%==========================================================================
defaults.normalise.write.preserve   = 0;
defaults.normalise.write.bb         = [[-78 -112 -70];[78 76 85]];
defaults.normalise.write.vox        = [2 2 2];
defaults.normalise.write.interp     = 4;

% Old Spatial Normalisation defaults
%==========================================================================
defaults.old.normalise.estimate.smosrc  = 8;
defaults.old.normalise.estimate.smoref  = 0;
defaults.old.normalise.estimate.regtype = 'mni';
defaults.old.normalise.estimate.weight  = '';
defaults.old.normalise.estimate.cutoff  = 25;
defaults.old.normalise.estimate.nits    = 16;
defaults.old.normalise.estimate.reg     = 1;
defaults.old.normalise.write.preserve   = 0;
defaults.old.normalise.write.bb         = [[-78 -112 -70];[78 76 85]];
defaults.old.normalise.write.vox        = [2 2 2];
defaults.old.normalise.write.interp     = 1;
defaults.old.normalise.write.wrap       = [0 0 0];
defaults.old.normalise.write.prefix     = 'w';

% VBM Preprocessing defaults
%==========================================================================
defaults.old.preproc.tpm     = cellstr(char(...
    fullfile(spm('Dir'),'toolbox','OldSeg','grey.nii'),...
    fullfile(spm('Dir'),'toolbox','OldSeg','white.nii'),...
    fullfile(spm('Dir'),'toolbox','OldSeg','csf.nii'))); % Prior probability maps
defaults.old.preproc.ngaus          = [2 2 2 4]'; % Gaussians per class
defaults.old.preproc.warpreg        = 1;          % Warping Regularisation
defaults.old.preproc.warpco         = 25;         % Warp Frequency Cutoff
defaults.old.preproc.biasreg        = 0.0001;     % Bias regularisation
defaults.old.preproc.biasfwhm       = 60;         % Bias FWHM
defaults.old.preproc.regtype        = 'mni';      % Affine Regularisation
defaults.old.preproc.fudge          = 5;          % Fudge factor, can not be set in batch GUI
defaults.old.preproc.samp           = 3;          % Sampling distance
defaults.old.preproc.output.GM      = [0 0 1];
defaults.old.preproc.output.WM      = [0 0 1];
defaults.old.preproc.output.CSF     = [0 0 0];
defaults.old.preproc.output.biascor = 1;
defaults.old.preproc.output.cleanup = 0;

% Smooth defaults
%==========================================================================
defaults.smooth.fwhm = [8 8 8];

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%-Prevent users from making direct calls to spm_defaults
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
persistent runOnce
try
    if ~isdeployed && isempty(runOnce)
        d = dbstack;
        if isempty(intersect({'spm','spm_get_defaults'},{d.name}))
            fprintf(['Direct calls to spm_defauts are deprecated.\n' ...
                'Please use spm(''Defaults'',modality) ' ...
                'or spm_get_defaults instead.\n']);
            runOnce = 1;
        end
    end
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%-Execute user-specified defaults files
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
def = defaults;
user_defaults = 'spm_my_defaults.m';
if exist(user_defaults,'file')
    if isdeployed && exist(fullfile(spm('Dir'),user_defaults),'file')
        user_defaults_file = cellstr(fullfile(spm('Dir'),user_defaults));
    else
        user_defaults_file = which(user_defaults,'-ALL');
    end
    for i=1:numel(user_defaults_file)
        try
            spm('run', user_defaults_file{i});
        catch
            lr = lasterror;
            warning(lr.message);
        end
    end
    if spm_check_version('matlab','8.0') >= 0, my_isequaln = @isequaln;
    else my_isequaln = @isequalwithequalnans; end
    if ~my_isequaln(def,defaults)
        fprintf('Defaults settings have been modified by file(s):\n');
        for i=1:numel(user_defaults_file)
            fprintf('  %s\n',user_defaults_file{i});
        end
        fn0 = fieldnames(def);
        mf = fn0(~cellfun(@(x) my_isequaln(def.(x),defaults.(x)),fn0));
        if ~isempty(mf)
            fprintf('Modified fields: ');
            for i=1:numel(mf)
                fprintf('%s ',mf{i});
            end
            fprintf('\n');
        end
    end
end


function model = cgpsimExpandParam(model, params)

% CGPSIMEXPANDPARAM Expand params into model structure.
% FORMAT
% DESC this is just a wrapper for learning three GP models
% simultaneously.
% ARG model : input model from which parameters will be extracted.
% ARG params : parameters to place in the model.
% RETURN model : model filled with the given parameters.
%
% SEEALSO : gpsimExpandParam
%
% COPYRIGHT : Neil D. Lawrence, 2006

% SHEFFIELDML

for i = 1:length(model.comp)
  model.comp{i} = gpsimExpandParam(model.comp{i}, params);
end


function atlasView = atlasInit(view,atlasName,nAtlases,newAtlasNum,atlasDim)
%
%   atlasView = atlasInit(view,atlasName,nAtlases,newAtlasNum,atlasDim)
%
% Author:
% Purpose:
%    We should use initHiddenFlat for this routine. But that function insists
% on recomputing the coords, and the paths to the flat mat are hard-coded
% and not machine independent, so it often breaks.

atlasView.name = atlasName;
atlasView.viewType = 'Flat';
atlasView.subdir = view.subdir;
atlasView.map = [];
atlasView.mapName = '';
atlasView.curDataType = newAtlasNum;
atlasView.coords = view.coords;
atlasView.grayCoords = view.grayCoords;
atlasView.leftPath = view.leftPath;
atlasView.rightPath = view.rightPath;
atlasView.co = cell(1, nAtlases);
atlasView.amp = cell(1, nAtlases);
atlasView.ph = cell(1, nAtlases);
atlasView.ui.imSize = view.ui.imSize;

% Fill up the co amp and ph with NaNs until the atlas is created.
for(ii=1:nAtlases)
    atlasView.co{ii} = repmat(NaN, atlasDim);
    atlasView.amp{ii} = repmat(NaN, atlasDim);
    atlasView.ph{ii} = repmat(NaN, atlasDim);
end

% In this model, there could be an existing atlas for the other hemisphere.
atlasView = loadCorAnal(atlasView);

return;


%% Example of using KST class for interfacing with KUKA iiwa robots
% Controlling KUKA iiwa from V-rep simulation using MATLAB and KST as a
% middle-ware.
% This script works together with V-rep scene: iiwaFromVrep.ttt

%% To run this example do the following:
% 1- Run the Vrep simulation: iiwaFromVrep.ttt
% 2- Run the (MarlabToolboxServer) application on the robot
% 3- Run this script from MATLAB.

% Copyright: Mohammad SAFEEA, 25th of June 2018

%% Initiation part of the code
close all;clear;clc;
warning('off')
disp('Program started');
%% Add path of KST class to work space
cDir = pwd;
cDir=getTheKSTDirectory(cDir);
addpath(cDir);

%% Declare V-rep objects
vrep=remApi('remoteApi');
vrep.simxFinish(-1);
clientID=vrep.simxStart('127.0.0.1',19999,true,true,5000,5);

%% Instantiate the KST object
ip='172.31.1.147'; % The IP of the controller
arg1=KST.LBR7R800; % choose the robot iiwa7R800 or iiwa14R820
arg2=KST.Medien_Flansch_elektrisch; % choose the type of flange
Tef_flange=eye(4); % transofrm matrix of EEF with respect to flange
iiwa=KST(ip,arg1,arg2,Tef_flange); % create the object

if (clientID>-1)
    %% Start a connection with the server
    flag=iiwa.net_establishConnection();
    if flag==0
      return;
    end

    jHandles=zeros(7,1);
    for i=1:7
            s=['LBR_iiwa_7_R800_joint',num2str(i)];
            [res, daHandle]=vrep.simxGetObjectHandle(clientID,s,vrep.simx_opmode_oneshot_wait);
            jHandles(i)=daHandle;
    end
else
    return;
end
jPos={0., pi / 180 * 20., 0., -pi / 180 * 70., 0.,...
                        pi / 180 * 90., 0.};
relVel=0.25;
iiwa.movePTPJointSpace(jPos, relVel);
%% Control loop
iiwa.realTime_startDirectServoJoints();
pause(10);
counter=0;
tic;
totalTimeSecs=60; % 60 seconds of execution time
vrep.simxStartSimulation(clientID,vrep.simx_opmode_oneshot_wait);
for i=1:7
        [res,tempPos]=vrep.simxGetJointPosition(clientID,jHandles(i),...
            vrep.simx_opmode_streaming);
end
vrep.simxWriteStringStream(clientID,'path_velocity','0.07',vrep.simx_opmode_oneshot_wait);
jpos=zeros(7,25000);
t_0=toc;
while(t_0<totalTimeSecs)
    for i=1:7
            [res,tempPos]=vrep.simxGetJointPosition(clientID,jHandles(i),...
                vrep.simx_opmode_buffer);
            jPos{i}=tempPos;
    end

    if(toc-t_0>0.003)
        counter=counter+1;
        iiwa.sendJointsPositionsf(jPos);
        for i=1:7
            jpos(i,counter)=jPos{i};
        end
        t_0=toc;
	end
end
%% Turn off KST server
iiwa.net_turnOffServer();
%% Stop simulation
vrep.simxStopSimulation(clientID,vrep.simx_opmode_oneshot_wait);
%% End simulation
vrep.simxFinish(clientID);
vrep.delete();


subset_map = containers.Map;
[a,b,c] = fileparts(image_list{1});
last_folder_all = a;
folder_names = strsplit(a,'\');
last_folder = [folder_names{end-1} '/' folder_names{end}];
subset_map(last_folder) = [1 0];
for i=2:length(image_list)
    [a,b,c] = fileparts(image_list{i});
    folder_names = strsplit(a,'\');
    if strcmp(last_folder_all, a) == 0
        start_end = subset_map(last_folder);
        subset_map(last_folder) = [start_end(1) i-1];
        last_folder = [folder_names{end-1} '/' folder_names{end}];
        subset_map(last_folder) = [i 0];
    end;
    last_folder_all = a;
end;
start_end = subset_map(last_folder);
subset_map(last_folder) = [start_end(1) length(image_list)];


function event = read_spmeeg_event(filename, varargin)

% read_spmeeg_event() - import evtns from SPM5 and SPM8 meeg datasets
%
% Usage:
%   >> header = read_spmeeg_event(filename);
%
% Inputs:
%   filename - [string] file name
%
% Outputs:
%   event   - FILEIO toolbox event structure
% _______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Vladimir Litvak

if nargin < 1
    help read_spmeeg_event;
    return;
end

header = ft_getopt(varargin, 'header');

if isempty(header)
    header = read_spmeeg_header(filename);
end

D = header.orig;

event = [];

if isfield(D, 'Radc') % SPM5
    for i = 1:D.Nevents
        if isfield(D, 'events') && isfield(D.events, 'code') && length(D.events.code) == D.Nevents
            value = D.events.code(i);
        else
            value = [];
        end

        event = [event struct('type', 'trial', 'sample', (i-1)*header.nSamples + 1,...
            'value', value, 'offset', -header.nSamplesPre, 'duration', header.nSamples)];
    end

    if D.Nevents == 1 && isfield(D, 'events') && isfield(D.events, 'time')
        event = [event struct('type', 'spm5_event', 'sample', num2cell(D.events.time),...
            'value', num2cell(D.events.code), 'offset', -header.nSamplesPre, 'duration', header.nSamples)];
    end

elseif all(isfield(D, {'type', 'Nsamples', 'Fsample', 'timeOnset'})) % SPM8

    for i = 1:numel(D.trials)
        if isfield(D.trials, 'events')
            cevent = D.trials(i).events;
            if ~isempty(cevent)
                for j = 1:numel(cevent)
                    if ~strcmp(cevent(j).type, 'trial')
                        csample = round((cevent(j).time - D.trials(i).onset)*header.Fs + 1);
                        if csample > 0 && csample <= header.nSamples
                            tmp = rmfield(cevent(j), 'time');
                            if strcmp(D.type, 'continuous') && (D.timeOnset ~= 0)
                                tmp.sample  = (cevent(j).time - D.timeOnset)* header.Fs + 1;
                            else
                                tmp.sample = (i-1)*header.nSamples + 1 +(cevent(j).time - D.trials(i).onset)*header.Fs;
                            end
                            tmp.sample = round(tmp.sample);
                            tmp.offset = 0;
                            event = [event tmp];
                        end
                    end
                end
            end
        end
    end

else
    ft_error('Cannot recognize an SPM EEG header format');
end


function opt = mpoption_info_glpk(selector)
%MPOPTION_INFO_GLPK  Returns MATPOWER option info for GLPK.
%
%   DEFAULT_OPTS = MPOPTION_INFO_GLPK('D')
%   VALID_OPTS   = MPOPTION_INFO_GLPK('V')
%   EXCEPTIONS   = MPOPTION_INFO_GLPK('E')
%
%   Returns a structure for GLPK options for MATPOWER containing ...
%   (1) default options,
%   (2) valid options, or
%   (3) NESTED_STRUCT_COPY exceptions for setting options
%   ... depending on the value of the input argument.
%
%   This function is used by MPOPTION to set default options, check validity
%   of option names or modify option setting/copying behavior for this
%   subset of optional MATPOWER options.
%
%   See also MPOPTION.

%   MATPOWER
%   Copyright (c) 2014-2016, Power Systems Engineering Research Center (PSERC)
%   by Ray Zimmerman, PSERC Cornell
%
%   This file is part of MATPOWER.
%   Covered by the 3-clause BSD License (see LICENSE file for details).
%   See https://matpower.org for more info.

if nargin < 1
    selector = 'D';
end
if have_feature('glpk')
    switch upper(selector)
        case {'D', 'V'}     %% default and valid options
            opt = struct(...
                'glpk',           struct(...
                    'opts',            [], ...
                    'opt_fname',       '' ...
                ) ...
            );
        case 'E'            %% exceptions used by nested_struct_copy() for applying
            opt = struct(...
                'name',         { 'glpk.opts' }, ...
                'check',        0 ...
                );
%                 'copy_mode',    { @glpk_options } ...
        otherwise
            error('mpoption_info_glpk: ''%s'' is not a valid input argument', selector);
    end
else
    opt = struct([]);       %% GLPK is not available
end


function fid = writefort15( f15dat, f15out, boudat )
%
if ( strcmp(strtrim(f15out), 'fort.15') )
    disp('Error: an output file name must not be fort.15') ;
    return ;
end

fid = fopen( f15out, 'w' ) ;

fprintf(fid, '%s\n', f15dat.rundes ) ; % RUNDES
fprintf(fid, '%s\n', f15dat.runid  ) ;  % RUNID

% NFOVER
L = length(f15dat.nfover);
dfmt = repmat('%g ',1, L);
fprintf( fid, [dfmt '        \t ! NFOVER \n'], f15dat.nfover ) ;

% NABOUT
fprintf(fid, '%d        \t ! NABOUT \n', f15dat.nabout ) ;

% NSCREEN
fprintf(fid, '%d        \t ! NSCREEN \n', f15dat.nscreen ) ;

% IHOT
fprintf(fid, '%d        \t ! IHOT \n', f15dat.ihot ) ;

% ICS
fprintf(fid, '%d        \t ! ICS \n', f15dat.ics ) ;

% IM
fprintf(fid, '%d        \t ! IM \n', f15dat.im ) ;

% IDEN
if f15dat.im == 20 || f15dat.im == 30
    fprintf( fid, '%d           \t ! IDEN \n', f15dat.iden ) ;
end

% NOLIBF
fprintf(fid, '%d        \t ! NOLIBF \n', f15dat.nolibf ) ;

% NOLIFA
fprintf(fid, '%d        \t ! NOLIFA \n', f15dat.nolifa ) ;

% NOLICA
fprintf(fid, '%d        \t ! NOLICA \n', f15dat.nolica ) ;

% NOLICAT
fprintf(fid, '%d        \t ! NOLICAT \n', f15dat.nolicat ) ;

% NWP
fprintf(fid, '%d        \t ! NWP \n', f15dat.nwp ) ;
if ( f15dat.nwp > 0 )
    for l = 1: f15dat.nwp
        fprintf(fid, '%s\n', f15dat.AttrName(l).name ) ;
    end
end

% NCOR
fprintf(fid, '%d   \t \t ! NCOR \n', f15dat.ncor ) ;

% NTIP
fprintf(fid, '%d   \t \t ! NTIP \n', f15dat.ntip ) ;

% NWS
fprintf(fid, '%d   \t \t ! NWS \n', f15dat.nws ) ;

% NRAMP
fprintf(fid, '%d   \t \t ! NRAMP \n', f15dat.nramp ) ;

% G
fprintf(fid, '%f   \t ! G  \n', f15dat.gravity ) ;

% TAU0
fprintf(fid, '%g   \t \t ! TAU0 \n', f15dat.tau0 ) ;

% Tau0FullDomainMin, Tau0FullDomainMax
if ( abs(f15dat.tau0 + 5.D0) < 1e-10 )
    fprintf(fid, '%f %f   \t ! Tau0FullDomainMin, Tau0FullDomainMax \n', f15dat.tau0minmax ) ;
end

% DTDP
fprintf( fid, '%g  \t \t ! DTDP \n', f15dat.dtdp ) ;

% STATIM
fprintf( fid, '%g  \t \t ! STATIM \n',  f15dat.statim ) ;

% REFTIM
fprintf( fid, '%g  \t \t ! REFTIM \n', f15dat.reftim ) ;

% WTIMINC
if f15dat.nws == 8
  fprintf( fid, '%d %d %d %d %d %g', f15dat.wtimnc ) ;
  fprintf( fid, '  \t ! YYYY MM DD HH24 StormNumber BLAdj \n' ) ;
elseif f15dat.nws >= 19
  fprintf( fid, '%d %d %d %d %d %g %d', f15dat.wtimnc ) ;
  fprintf( fid, '  \t ! YYYY MM DD HH24 StormNumber BLAdj geofactor \n' ) ;
elseif f15dat.nws > 0
  fprintf( fid, '%d  ', f15dat.wtimnc ) ;
  fprintf( fid, '  \t ! WTMINC \n' ) ;
end

% RNDY
fprintf( fid, '%g   \t \t ! RNDY \n', f15dat.rndy ) ;

% DRAMP
L = length(f15dat.dramp);
dfmt = repmat('%g ',1, L);
fprintf( fid, [dfmt ' \t \t ! DRAMP \n'],  f15dat.dramp ) ;

% A00, B00, C00
fprintf( fid, '%g %g %g  \t ! A00, B00, C00 \n', f15dat.a00b00c00 ) ;

% H0
len = length(f15dat.h0) ;
for k = 1: len
  fprintf( fid, '%g ', f15dat.h0(k) ) ;
end
fprintf( fid, '   \t ! H0, 2*dummy, VELMIN \n' ) ;

% SLAM0, SFEA0
fprintf( fid, '%f %f  \t \t ! SLAM0, SFEA0 \n', f15dat.slam ) ;

% CF
if ( f15dat.nolibf <= 2 )
    fprintf( fid, '%f ', f15dat.taucf ) ;
    fprintf( fid, '    \t ! CF \n' ) ;
end

% ESLM, ESLC
if ( f15dat.im <= 2 || f15dat.im == 10 || f15dat.im >= 111111 )
    fprintf( fid, '%f ', f15dat.elsm ) ;
    fprintf( fid, '    \t ! ELSM \n' ) ;
end

% CORI
fprintf( fid, '%f   \t ! CORI \n', f15dat.cori ) ;

% NTIF
fprintf( fid, '%d   \t \t ! NTIF \n', f15dat.ntif ) ;

% Tidal potential
for k = 1: f15dat.ntif
    fprintf( fid, '%s \n',  f15dat.tipotag(k).name ) ;
    fprintf( fid, '%f %16.9e %f %f %f', f15dat.tipotag(k).val ) ;
    fprintf( fid, '   \t !  TPK, AMIGT, ETRF, FFT, FACET \n' ) ;
end

% NBFR
fprintf( fid, '%d   \t \t ! NBFR \n', f15dat.nbfr ) ;
for k = 1: f15dat.nbfr
    fprintf( fid, '%s  \n', f15dat.bountag(k).name ) ;
    fprintf( fid, '%16.9e %f %f \n', f15dat.bountag(k).val ) ;
end

% Open boundary harmonic forcing
for k = 1: f15dat.nbfr
    fprintf(fid, '%s \n', f15dat.opealpha(k).name  ) ;
    fprintf(fid, '%16.9e %16.10g \n', f15dat.opealpha(k).val' ) ;
end

%  ANGINN
fprintf( fid, '%g   \t \t ! ANGINN \n', f15dat.anginn ) ;

% Land boundary
ibtype = [2 12 22 32 52] ;
sm = 0 ;

if ~isempty(boudat)
    for k = 1: length(ibtype)
        sm = sm + sum(~(boudat.ibtype - ibtype(k))) ;
    end
end
if ( sm > 0 )
    fprintf( fid, '%d  \t \t ! NFFR \n', f15dat.nffr ) ;

    nm = 0 ;
    for ib = 1: boudat.nbou
        ibty = boudat.ibtype(ib);

        switch ibty
            case {2,12,22,32,52}
                nm = nm + boudat.nvell(ib) ;
            otherwise
        end
    end

    for k = 1: f15dat.nffr
        fprintf( fid, '%s \n', f15dat.fbountag(k).name ) ;
        fprintf( fid, '%15.8e ', f15dat.fbounspec(k).val ) ;
        fprintf( fid, '\n') ;
    end

    for k = 1: f15dat.nffr
        fprintf( fid, '%s  \n',  f15dat.boualpha(k).name  ) ;

        % val = fscanf(fid, '%f ' ) ; % Must be revisit
        icnt = 0 ;
        for ib = 1: boudat.nbou
            ibty = boudat.ibtype(ib);

            switch ibty
                case {2,12,22,52}
                   for ir = 1: boudat.nvell(ib)
                      icnt = icnt + 1 ;

                      fprintf(fid, '%16.9e  ', f15dat.qnam(k).val(icnt,1:2) ) ;
                      fprintf(fid, ' \n' ) ;
                   end
                case 32
                   for ir = 1: boudat.nvell(ib)
                      icnt = icnt + 1 ;

                      fprintf(fid, '%15.8e ', f15dat.qnam(k).val(icnt,1:5) ) ;
                      fprintf(fid, ' \n' ) ;
                   end
                otherwise
            end
        end
    end
end

% NOUTE, TOUTSE, TOUTFE, NSPOOLE
fprintf( fid, '%d %g %g %d', f15dat.oute ) ;
fprintf( fid, '   \t ! NOUTE, TOUTSE, TOUTFE, NSPOOLE \n' ) ;

% NSTAE
fprintf( fid, '%d  \t \t ! NSTAE \n', f15dat.nstae ) ;

% STAE location
if ( f15dat.nstae > 0 )
    for k = 1: f15dat.nstae
        fprintf(fid, '%f %f %s \n', f15dat.elvstaloc(k,1:2), f15dat.elvstaname{k} ) ;
    end
end

% NOUTV, TOUTV, TOUTFV, NSPOOLV
fprintf( fid, '%d %g %g %d',  f15dat.outv ) ;
fprintf( fid, '  \t ! NOUTV, TOUTV, TOUTFV, NSPOOLV \n') ;

% NSTAV
fprintf( fid, '%d  \t \t ! NSTAV \n', f15dat.nstav ) ;

% STAV location
if ( f15dat.nstav > 0 )
    for k = 1: f15dat.nstav
        fprintf( fid, '%f %f %s \n', f15dat.velstaloc(k,1:2), f15dat.velstaname{k} ) ;
    end
end

% NOUTM, TOUTM, TOUTFM, NSPOOLM
if ( f15dat.nws ~= 0  )
    fprintf(fid, '%d %g %g %d', f15dat.outm ) ;
    fprintf(fid, '  \t ! NOUTM, TOUTM, TOUTFM, NSPOOLM \n') ;

    % NSTAM
    fprintf(fid, '%d   \t \t ! NSTAM \n', f15dat.nstam ) ;

    % STAM location
    if ( f15dat.nstam > 0 )
        for k = 1: f15dat.nstam
            fprintf( fid, '%f %f %s \n', f15dat.metstaloc(k,1:2), f15dat.metstaname{k} ) ;
        end
    end
end

% NOUTGE
fprintf( fid, '%d %g %g %d', f15dat.outge ) ;
fprintf( fid, '  \t ! NOUTGE, ... \n') ;

% NOUTGV
fprintf( fid, '%d %g %g %d', f15dat.outgv ) ;
fprintf( fid, '  \t ! NOUTGV, ... \n') ;

% NOUTGC
if ( f15dat.im == 10 )
    fprintf( fid, '%d %g %g %d', f15dat.outgc ) ;
    fprintf( fid, '  \t ! NOUTGC, ... \n' ) ;
end

% NOUTGM
if ( f15dat.nws ~= 0  )
    fprintf( fid, '%d %g %g %d', f15dat.outgm ) ;
    fprintf( fid, '  \t ! NOUTGM, ... \n' ) ;
end

% NFREQ
fprintf( fid, '%d  \t \t ! NFREQ \n', f15dat.nfreq ) ;
for k = 1: f15dat.nfreq
    fprintf( fid, '%s \n', f15dat.harfreq(k).name ) ;

    fprintf( fid, '%16.9e %f %f \n', f15dat.harfreq(k).val ) ;
end

% THAS, THAF, NHAINC, FMV
fprintf( fid, '%g %g %d %g  \t ! THAS, THAF, NHAINC, FMV \n', f15dat.outhar ) ;

% NHASE, NHASV, NHAGE, NHAGV
fprintf( fid, '%d ', f15dat.outhar_flag ) ;
fprintf( fid, '  \t ! NHASE, NHASV, NHAGE, NHAGV \n' ) ;

% NHSTAR, NHSINC
fprintf( fid, '%d %d  \t ! NHSTAR, NHSINC \n', f15dat.nhstar) ;

% ITITER, ISLDIA, CONVCR, ITMAX
fprintf( fid, '%d %d  %16.9e %d  \t ! ITITER, ISLDIA, CONVCR, ITMAX \n', f15dat.ititer ) ;

% Extra lines including NETCDF & namelist
for k = 1: f15dat.nextraline
    fprintf( fid, '%s\n', f15dat.extraline(k).msg ) ;
end

% If
if find(strcmp(fieldnames(f15dat),'controllist'),1)
for k = 1: length(f15dat.controllist)
    fprintf( fid, '! -- Begin %s Control Namelist -- \n', f15dat.controllist(k).type ) ;
    fprintf( fid, '&%sControl\n', f15dat.controllist(k).type ) ;
    for m = 1:length(f15dat.controllist(k).var)
        val = f15dat.controllist(k).var(m).val;
        if ~ischar(val); val = num2str(val); end
        fprintf( fid, '%s = %s,\n',f15dat.controllist(k).var(m).name,val) ;
    end
    fprintf( fid, '/\n') ;
    fprintf( fid, '! -- End %s Control Namelist -- \n', f15dat.controllist(k).type ) ;
end
end

fclose(fid) ;

end


function [varargout] = acq_makeDataFolder(varargin)
%ACQ_MAKEDATAFOLDER - Create a folder for saving EEG data
%
%Synopsis:
% folder= acq_makeDataFolder;
% folder= acq_makeDataFolder(OPT);
%
%Arguments:
% 'tmp' : creates temporal directory
% OPT: struct or property/value list of optinal properties:
%
%Returns:
% folder: name of the folder in which EEG signals will be saved
%Side effect:
% Set global variables BTB.Tp.Code, BTB.Tp.Dir
%
% XX-XX Benjamin Blankertz
% 06-12 Javier Pascual. Updated. Created new function getSubjectcode

global BTB

%BTB.Tp.Code = [];

%% Get the date
today_vec= clock;
today_str= sprintf('%02d_%02d_%02d', today_vec(1)-2000, today_vec(2:3));

if length(varargin)==1 && isequal(varargin{1},'tmp'),
  BTB.Tp.Dir= [BTB.RawDir 'Temp_' today_str '\'];
  if ~exist(BTB.Tp.Dir, 'dir'),
    mkdir_rec(BTB.Tp.Dir);
  end
  return;
end

if isempty(BTB.Acq.StartLetter),
  BTB.Acq.StartLetter= 'a';
end

props = {'MultipleFolders'	0   'BOOL'
         'Interactive'      1   'BOOL'};

% if nargin==0,
%   varargout{1} = opt_catProps(props, acq_getSubjectCode);
%   return;
% end;

opt= opt_proplistToStruct(varargin{:});
[opt,isdefault] = opt_setDefaults(opt, props);
opt_checkProplist(opt, props);

%% Check whether a directory exists that is to be used
dd= dir([BTB.RawDir 'VP???_' today_str '*']);

FolderList{1}= strcat('Temp_', today_str);
Comment{1}= 'for testing purpose';
NewCode= acq_getSubjectCode;
FolderList{2}= strcat(NewCode, '_', today_str);
Comment{2}= 'to be generated as new folder';
for k= 1:length(dd),
  FolderList{2+k}= dd(k).name;
  de= dir([BTB.RawDir dd(k).name '\*']);
  deeg= dir([BTB.RawDir dd(k).name '\*.eeg']);
  if length(de)<=2,
    Comment{2+k}= 'empty folder';
  elseif isempty(deeg),
    Comment{2+k}= 'folder without *.eeg files';
  else
    Comment{2+k}= 'folder with *.eeg files';
  end
end

if opt.Interactive,
  for k= 1:length(FolderList),
    fprintf('(%d) %s  (%s)\n', k, FolderList{k}, Comment{k});
  end
  choice= 0;
  while choice<1 || choice>length(FolderList),
    msg= sprintf(' -> Input your choice (1-%d): ', length(FolderList));
    choice= input(msg);
    if isempty(choice),
      choice= 1;
    end
  end
else
  choice= 2;
end
BTB.Tp.Dir= fullfile(BTB.RawDir, FolderList{choice});
is= find(FolderList{choice}=='_', 1, 'first');
BTB.Tp.Code= FolderList{choice}(1:is-1);

if ~exist(BTB.Tp.Dir, 'dir'),
  mkdir(BTB.Tp.Dir);
end

fprintf('EEG data will be saved in <%s>.\n', BTB.Tp.Dir);


%% subImage
% Below is a demonstration of the features of the |subImage| function

%%
clear; close all; clc;

%% Syntax
% |[M,linearInd]=subImage(M,nSub);|

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


%% Defines the class interface for the ECGtask derived classes
%
% Description:
% Abstract class for defining ECGtask interface
%
% Arguments: %
%
% Output:
%
% Examples:
%
%
% See also ECGtask_QRS_detection, ECGtask_ECG_delineation
%
% Author: Mariano Llamedo Soria llamedom@electron.frba.utn.edu.ar
% Version: 0.1 beta
% Last update: 14/5/2014
% Birthdate  : 20/3/2012
% Copyright 2008-2015
%
classdef ECGtask < handle

    properties(Abstract = true, GetAccess = public, Constant)
        name
        target_units
        doPayload
        % if user = memory;
        % memory_constant is the fraction respect to user.MaxPossibleArrayBytes
        % which determines the maximum input data size.

    end

    properties(Abstract = true, GetAccess = public, SetAccess = private)
        memory_constant
        started
    end

    properties(Abstract = true)
        progress_handle
        tmp_path
    end

    methods (Abstract)

% ECG_header is the header for this signal
% ECG_annotations are the QRS locations available for this signal
        function Start(obj, ECG_header, ECG_annotations)
        endfunction
% ECG is the ECG signal
% ECG_start_offset is the location of ECG(1,:) within the whole signal
% ECG_sample_start_end_idx are the start and end samples within ECG to
%    generate valid results.
% ECG_header is the header for this signal
% ECG_annotations are the QRS locations available for this signal
% ECG_annotations_start_end_idx are the start and end indexes corresponding
%    to the first and last element of ECG_annotations in the current
%    iteration.
        function payload = Process(ECG, ECG_start_offset, ECG_sample_start_end_idx, ECG_header, ECG_annotations, ECG_annotations_start_end_idx )
        endfunction
% payload is the result of the task, after the final processing done by this method
% ECG_header is the header for this signal
        function payload = Finish(obj, payload, ECG_header)
        endfunction

% plA, plB are two payloads produced by the Process method.
        function payload = Concatenate(plA, plB)
        endfunction

    end

end


function str = gencode_substruct(subs, name)

% GENCODE_SUBSTRUCT  String representation of subscript structure.
% Generate MATLAB code equivalent to subscript structure subs. See help
% on SUBSTRUCT, SUBSASGN and SUBSREF for details how subscript structures
% are used.
%
% str = gencode_substruct(subs, name)
% Input arguments:
%  subs - a subscript structure
%  name - optional: name of variable to be dereferenced
% Output arguments:
%  str  - a one-line cellstr containing a string representation of the
%         subscript structure
% If name is given, it is prepended to the string.
% For '()' and '{}' also pseudo subscripts are allowed: if subs.subs{...}
% is a string, it will be printed literally, even if it is not equal to
% ':'. This way, it is possible create code snippets that contain
% e.g. references to a loop variable by name.
%
% See also GENCODE, GENCODE_RVALUE, GENCODE_SUBSTRUCTCODE.
%
% This code has been developed as part of a batch job configuration
% system for MATLAB. See
%      http://sourceforge.net/projects/matlabbatch
% for details about the original project.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging

% Volkmar Glauche
% $Id: gencode_substruct.m 3355 2009-09-04 09:37:35Z volkmar $

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

ind = 1;
if nargin < 2
    name = '';
end

if ~isstruct(subs) || ~all(isfield(subs, {'type','subs'}))
    if any(exist('cfg_message') == 2:6)
        cfg_message('matlabbatch:usage', 'Item is not a substruct.');
    else
        warning('gencode_substruct:usage', 'Item is not a substruct.');
    end
else
    str = {name};
    for k = 1:numel(subs)
        switch subs(k).type
            case '.',
                str{1} = sprintf('%s.%s', str{1}, subs(k).subs);
            case {'()','{}'},
                str{1} = sprintf('%s%s', str{1}, subs(k).type(1));
                for l = 1:numel(subs(k).subs)
                    if ischar(subs(k).subs{l})
                        substr = subs(k).subs{l};
                    else
                        substr = sprintf('%d ', subs(k).subs{l});
                        if numel(subs(k).subs{l}) > 1
                            substr = sprintf('[%s]', substr(1:end-1));
                        else
                            substr = substr(1:end-1);
                        end
                    end
                    str{1} = sprintf('%s%s, ', str{1}, substr);
                end
                str{1} = str{1}(1:end-2);
                str{1} = sprintf('%s%s', str{1}, subs(k).type(2));
        end
    end
end


function Dataset2XLS(DATA, filename)
%DATASET2XLS - Save Dataset format to EXCEL File
% This function wil help you to save simulation results to Excel files.
% INPUTS:
% DATA - The data to be saved, in DataSet format (Simulink).
% Filename - optional file name to save in. if not supplied, will use
% example_Dataset.xlsx.
% usage:
% 1. Run a Simulink model, and save the result in a Dataset format. The
% defaults filename is 'logsout'.
% 2. Run this function: Dataset2XLS(logsout, 'test.xls');
%

%% Check inputs:
if (nargin < 1 || nargin >3)
    error('Wrong number of arguments. Enter Dataset parameter Name');
end
if nargin < 2
    filename = 'example_Dataset.xlsx';
    warning('### No filename supplied, using example_Dataset.xlsx instead ###');
end
if ~ischar(filename)
    error('Illegal file name');
end
if isempty(DATA)
    error('Illegal Data to save');
end
if ~isa(DATA,'Simulink.SimulationData.Dataset')
    error('Data is not in Simulink.SimulationData.Dataset Format');
end
if ~exist(filename,'file')
    existingFile = 0;
else
    existingFile = 1;
end

%% Write data to file:
disp('### Writing to file ###')
warning('off'); %#ok<*WNOFF>
for i = 1:DATA.numElements
    fprintf('### Writing element #%d ###\n',i);
    locSig = DATA.getElement(i);
    stat = xlswrite(filename, [locSig.Values.Time locSig.Values.Data], locSig.Name);
    if ~stat
        error('Problem writing to file, check if it''s not open');
    end
end
warning('on'); %#ok<*WNON>
fprintf('### Finished writing to file %s ###\n',filename)

%% Delete unwanted excel sheets (If file did not exist beforehand):
if ~existingFile
    disp('### Removing extra sheets ###')
    % Retrieve sheet names
    [~, sheetNames] = xlsfinfo(filename);
    % Open Excel as a COM Automation server
    hExcel = actxserver('Excel.Application');
    % Open Excel workbook
    Workbook = hExcel.Workbooks.Open(fullfile(pwd,filename));
    % Clear the content of the sheets (from the second onwards)
    cellfun(@(x) hExcel.ActiveWorkBook.WorkSheets.Item(x).Delete, sheetNames(1:3));
    % Now save/close/quit/delete
    Workbook.Save;
    hExcel.Workbook.Close;
    hExcel.Quit;
    hExcel.delete;
end


%GETSIZE Return size of a mapping
%
%   SIZE = GETSIZE(W)
%
% This function is identical to SIZE(W).


function run_mimic_imp_annotation
% run_mimic_imp_annotation is designed to annotate the quality and breaths
% of signals in the impedance pneumography signal quality index (SQI) dataset
% (extracted from the MIMIC III database). It was used to evaluate the
% impedance pneumography SQI (using only the breath annotation functionality).
%
%               run_mimic_imp_annotation
%
%	Inputs:
%       mimic_imp_sqi_data.mat - a file containing curated data from the MIMIC database.
%        - Specify the path to this file in the "setup_universal_params" function below.
%
%	Outputs:
%       Matlab files containing the annotations for each subject, called
%          "ImP_SQI#_##_an.mat" (where #_## is the subject number, followed
%          by the initials of the annotator)
%
%   Further Information:
%       This version of the run_mimic_imp_annotation is provided to facilitate
%       replication of the analysis reported in:
%           Charlton P. H. et al., "An impedance pneumography signal
%           quality index for respiratory rate monitoring: design,
%           assessment and application", [under review]
%       Further information on this study can be obtained at:
%           http://peterhcharlton.github.io/RRest/imp_sqi.html
%       In addition, further information on RRest, a toolbox of respiratory
%       algorithms which can be used with this dataset, can be obtained at:
%           http://peterhcharlton.github.io/RRest/index.html
%
%   Comments, Questions, Criticisms, Feedback, Contributions:
%       See: http://peterhcharlton.github.io/RRest/contributions.html
%
%   Version:
%       v.0.1 - accompanying peer review, 6th Aug 2020 by Peter H Charlton
%
%   Source:
%       This script has been adapted from 'MIMICII_data_importer.m', which
%       is one of the scripts in the RRest toolbox, available at:
%           https://github.com/peterhcharlton/RRest
%
%   Licence:
%       This program is available under the GNU public license. This
%       program is free software: you can redistribute it and/or modify
%       it under the terms of the GNU General Public License as published by
%       the Free Software Foundation, either version 3 of the License, or
%       (at your option) any later version. This program is distributed in
%       the hope that it will be useful, but WITHOUT ANY WARRANTY; without
%       even the implied warranty of MERCHANTABILITY or FITNESS FOR A
%       PARTICULAR PURPOSE.  See the GNU General Public License for more
%       details: <http://www.gnu.org/licenses/>.
%

%% Setup
% ~~~ This function needs adjusting by the individual user as it contains paths
% specific to their computer ~~~
up = setup_universal_params;

%% Initialisation

% Load data
load(up.paths.data_file)
subjects = 1:length(data);   % create a list of subjects which are to be analysed.

% mode
up.mode = 2;        % select 1 if annotating high or low quality, 2 if annotating breaths
if up.mode == 1, fprintf('\n *** Mode selected: quality annotation *** '), elseif up.mode == 2, fprintf('\n *** Mode selected: Breath annotation *** '), end

fprintf(['\n\n\n\n\n~~~~~~~  Starting annotations  ~~~~~~~\n' ...
    'Instructions: Use the left mouse key to\n' ...
    'annotate a peak, and use the right mouse\n' ...
    'key to annotate a trough. To delete the\n' ...
    'most recent annotation, hold down SHIFT\n' ...
    'and press a mouse key.\n' ...
    'Please note that any previous annotations\n' ...
    'will be kept as long as the results files\n' ...
    'are in the correct location.\n\n']);

operator=input('(To enter review mode, type  review  )\n\nOtherwise, please type your first and last initial,\nand press enter:\n','s');
%operator = 'PC';
if strcmp(operator, 'review') == 1
    paw_verification_script_checker(subjects, data, up);
    return
end

question=input('\nWould you like to start from the \nfirst subject? (y or n, followed by enter)\n', 's');
%question = 'y';
if strcmp(question, 'n') == 1
    start_subject = str2num(input('\nWhich subject?\n', 's'));
else
    start_subject = 1;
end

%% Cycle through different subjects and periods
start_subject_el = find(subjects == start_subject);
% load data on which windows were high quality if annotating breaths
if up.mode == 2
    load(up.paths.data_file2)
    rel_col = find(strcmp(data_mat.all.response_header, 'subj'));
    data_mat.all.subj = data_mat.all.response_data(:,rel_col);
    rel_col = find(strcmp(data_mat.all.response_header, 'win_no'));
    data_mat.all.win_no = data_mat.all.response_data(:,rel_col);
end
if isempty(start_subject_el)
    fprintf('\nThis subject doesn''t exist. Try all over again.');
else
    subjects = subjects(start_subject_el:end);
    for s = subjects(1:end)

        %% Identify wins deemed to be high qual
        if up.mode == 2 % i.e. identifying RRs
            rel_col1 = find(strcmp(data_mat.all.response_header, 'sqi_novel'));
            rel_els1 = data_mat.all.subj==s;
            rel_els2 = data_mat.all.response_data(:, rel_col1) == 1;
            high_qual_wins = data_mat.all.win_no(rel_els1 & rel_els2);
            if length(high_qual_wins) > 5
                high_qual_wins = high_qual_wins(1:5);
            end
        end

        %% Load Impedance
        imp.fs = data(s).ref.resp_sig.imp.fs;
        imp.v = data(s).ref.resp_sig.imp.v;
        imp.t = [0:(length(imp.v)-1)]/imp.fs;

        %% Process Impedance
        imp = lpf_to_exclude_resp(imp, up);
        imp.v = -1*imp.v;

        %% Set up file for keeping annotations in:
        % see if this subject has already been annotated:
        if up.mode == 1
            qual.t = []; qual.v = [];
            save(up.paths.annotations_file, 'qual', 'up')
        else
            pk_anns.t=[]; pk_anns.v=[];
            save(up.paths.annotations_file, 'pk_anns', 'up')
        end

        %% plot waveforms and annotations (for further annotation)
        duration_of_signal = imp.t(end) - imp.t(1);
        NUMWINS = floor(duration_of_signal / up.win_length); clear duration_of_signal
        edge_time = up.edge_prop*up.win_length;
        for win = 1:NUMWINS
            % skip if annotating breaths and this window was deemed to be
            % low quality
            if up.mode == 2 && ~sum(win==high_qual_wins)
                continue
            end

            % Find window timings
            starttime = imp.t(1)+(win-1)*up.win_length;
            endtime = starttime + up.win_length;

            % Skip if this window has already been annotated
            savename = [up.paths.annotations_folder, 'ImP_SQI' num2str(s), '_' operator '_an.mat'];
            if exist(savename, 'file')
                temp = load(savename);
                rel_els = temp.pk_anns.t>=starttime & temp.pk_anns.t<=endtime;
                min_diff = min(diff(temp.pk_anns.t(rel_els)));
                if min_diff < 1
                    error(['Check window ', num2str(win), ', subj ', num2str(s)])
                end
                if sum(rel_els)>0
                    continue
                end
            end

            % Setup plot
            rel_els = find(imp.t >= starttime & imp.t < endtime);
            grey_els = find(imp.t >= (starttime - edge_time) & imp.t < (endtime + edge_time));
            scrsz = get(0,'ScreenSize');
            load(up.paths.annotations_file)

            % Plot
            h=figure('OuterPosition',[1 1 scrsz(3) scrsz(4)]);
            %save('plot_vars.mat', 'h', 'imp', 'Re', 'grey_paw_els', 'rel_paw_els', 'rel_Re_els', 'grey_Re_els', 'period', 's', 'subjects')
            [axis_h, h2] = annotation_plotter2(up.paths.annotations_file, h, imp, grey_els, rel_els, s, subjects, up, win, NUMWINS,starttime);

            % use pointer to identify breaths
            set(gcf, 'Pointer', 'cross');
            if up.mode == 1
                % Construct a questdlg with three options
                choice = MFquestdlg([0.1,0.1],'High quality?', ...
                    '', ...
                    'Yes','No','No');
                % Handle response
                switch choice
                    case 'Yes'
                        load(up.paths.annotations_file);
                        [qual.t,inds]=unique([qual.t; starttime]);
                        qual.v=[qual.v; 1]; qual.v = qual.v(inds);
                        [qual.t, inds] = sort(qual.t);
                        qual.v = qual.v(inds);
                        save(up.paths.annotations_file, 'qual');
                    case 'No'
                        load(up.paths.annotations_file);
                        [qual.t,inds]=unique([qual.t; starttime]);
                        qual.v=[qual.v; 0]; qual.v = qual.v(inds);
                        [qual.t, inds] = sort(qual.t);
                        qual.v = qual.v(inds);
                        save(up.paths.annotations_file, 'qual');
                end
            else
                set(h2,'ButtonDownFcn',{@Click_CallBack2 gca axis_h h2 up up.paths.annotations_file starttime});
                pause
            end
            close(h);

        end

        if up.DOSAVE
            fprintf(['~~~~~~ Saving subject ' num2str(s) '  ~~~~~~\n']);
            if exist(savename, 'file')
                old_data = load(savename);
            end
            new_data.up = up;
            temp = load(up.paths.annotations_file);
            % If there are annotations in both the old file and the current annotations file
            if exist('old_data', 'var') && sum(strcmp(fieldnames(old_data), 'pk_anns')) && ~isempty(old_data.pk_anns.t) ...
                    && sum(strcmp(fieldnames(temp), 'pk_anns')) && ~isempty(temp.pk_anns.t)
                all_t = [temp.pk_anns.t; old_data.pk_anns.t];
                all_v = [temp.pk_anns.v; old_data.pk_anns.v];
                [~, order] = sort(all_t);
                new_data.pk_anns.t = all_t(order);
                new_data.pk_anns.v = all_v(order);
                clear order all_t all_v
            % If there are annotations in the old file
            elseif exist('old_data', 'var') && sum(strcmp(fieldnames(old_data), 'pk_anns')) && ~isempty(old_data.pk_anns.t)
                new_data.pk_anns = old_data.pk_anns;
            % If there are annotations in the current annotations file
            elseif sum(strcmp(fieldnames(temp), 'pk_anns')) && ~isempty(temp.pk_anns.t)
                new_data.pk_anns = temp.pk_anns;
            else
                [new_data.pk_anns.t, new_data.pk_anns.v] =deal([]);
            end
            if exist('qual', 'var') && ~isempty(qual.t)
                new_data.qual = qual;
            elseif sum(strcmp(fieldnames(temp), 'qual'))  && ~isempty(temp.qual.t)
                new_data.qual = temp.qual;
            elseif exist('old_data', 'var') && sum(strcmp(fieldnames(old_data), 'qual'))  && ~isempty(old_data.qual.t)
                new_data.qual = old_data.qual;
            else
                new_data.qual.t = []; qual.v = [];
            end
            pk_anns = new_data.pk_anns;
            qual = new_data.qual;
            up = new_data.up;
            save(savename, 'pk_anns', 'qual', 'up')
            clear old_data new_data temp pk_anns qual
        end

        clear pk_anns qual NUMWINS pawmean STUDYID

    end

end

end

function up = setup_universal_params

close all

%% folderpaths
up.paths.root_data_folder = '/Users/petercharlton/Documents/Data/ImP_SQI_mimic_dataset_test/';
up.paths.data_file = [up.paths.root_data_folder, 'mimic_imp_sqi_data.mat'];
up.paths.data_file2 = [up.paths.root_data_folder, 'data_mat.mat'];
up.paths.resultspath = [up.paths.root_data_folder, 'SQI_development', filesep];
up.paths.annotations_folder = [up.paths.root_data_folder, '2019_annotations', filesep];
up.paths.annotations_file = [up.paths.root_data_folder, '2019_annotations', filesep, 'temp.mat'];
up.paths.dlg = '/Users/petercharlton/Google Drive/Work/Projects/PhD/Github/phd/Tools/Other Scripts/MFquestdlg/';
addpath(up.paths.dlg)
if ~exist(up.paths.annotations_folder, 'dir')
    mkdir(up.paths.annotations_folder)
end

%% waveform specifications
up.spikefs = 500;     % It is assumed in vortal_spike_conversion that all the spike waveforms are exported at this freq
up.reg = 1;
up.paworig = 2;
up.pawresample = 3;
up.resp = 4;
up.FS = [4, up.spikefs, 50, 62.5];

%% Operational specifications
up.DOSAVE = 1;                  % Save plots of filter characteristics?
up.DOPLOT = 0;
up.viewing_win_length = 32;     % duration of window to be viewed at once (in secs)
up.edge_prop = 0.3;             % proportion of window to show either side of the one currently being viewed.

%% Filtering specifications
up.filt_prop = 2;              % proportion of a second for which to apply the filter. (i.e. this * fs = order)
up.LP_CUTOFF = 60;                 % in rpm
up.time_offset = 1.1;          % The time (secs) by which the resp signal is delayed after the Paw signal.

%% Analysis specifications:
up.win_length = 32;            % window length for analysis in secs
up.true_BR_lims = 2;           % number of bpm either side at which ref BR estimates are considered reasonable.
up.mingap = 5;                 % If there is a gap in data of duration greater than this no. of secs, then this is considered to be a gap (anything less is ignored), for both numerics and waveforms

% duration of Tukey window taper in secs
up.paramSet.tukey_win_duration_taper = 2;

% Eliminate HFs (above resp freqs)
up.paramSet.elim_hf.Fpass = 1.2;  % in Hz
up.paramSet.elim_hf.Fstop = 0.8899;  % in Hz     (1.2 and 0.8899 provide a -3dB cutoff of 1 Hz)
up.paramSet.elim_hf.Dpass = 0.057501127785;
up.paramSet.elim_hf.Dstop = 0.01;

end

function [axis_h, h2] = annotation_plotter2(annotations_filepath, h, imp, grey_els, rel_els, s, subjects, up, win, NUMWINS, starttime)

%% ------------    annotation_plotter  ------------------------------
%
% Created by: Peter Charlton (17/10/2012)
%
% Purpose: To plot the Paw and impedance waveforms, and the annotated
%           breaths.
%
% Context: Some safety nets have been added to make it run ok even if the
% impedance signal isn't recorded.
%
% Inputs:
%
% Outputs:
%
% Files required:
%
% Called by:            Run_paw_verification
%
% ------------------------------------------------------------------------

ftsize = 16; lwidth = 2;
init_time = imp.t(rel_els(1));

load(annotations_filepath)
mean_imp = mean(imp.v(rel_els));
h3 = plot(imp.t(rel_els) - init_time, zeros(1,length(rel_els)), 'k', 'LineWidth', lwidth); hold on    % plot zero line on Paw plot
set(h3, 'HandleVisibility', 'off')
h1 = plot(imp.t(grey_els) - init_time, imp.v(grey_els) - mean_imp, 'Color', [0.5 0.5 0.5], 'LineWidth', lwidth); hold on,    % plot Paw (grey)
set(h1, 'HandleVisibility', 'off')
h2 = plot(imp.t(rel_els) - init_time, imp.v(rel_els) - mean_imp, 'LineWidth', lwidth);    % plot Paw
set(h2, 'HandleVisibility', 'off')
xlim([imp.t(grey_els(1)) - init_time, imp.t(grey_els(end)) - init_time])

%% Calculate and plot mix signal
if up.mode == 2
    % plot annotations which are relevant to this plot:
    %breathels = find(pk_anns.t>=imp.t(grey_els(1)) & pk_anns.t<=imp.t(grey_els(end)));
    %plot(pk_anns.t(breathels) - init_time,pk_anns.v(breathels)-mean_imp, 'ro','LineWidth',4)
    breathels = find(pk_anns.t>=imp.t(rel_els(1)) & pk_anns.t<=imp.t(rel_els(end)));
    plot(pk_anns.t(breathels) - init_time,pk_anns.v(breathels), 'ro','LineWidth',4)

    title(['Please annotate the peaks (red)  -  ' num2str(win) ' of ' num2str(NUMWINS) ' windows for subject ' num2str(s) ' of ' num2str(subjects(end))], 'FontSize', ftsize)
    ylabel('Impedance', 'FontSize', ftsize), xlabel('Time [s]', 'FontSize', ftsize);
    ylabel('Imepdance (above line = inhalation)', 'FontSize', ftsize)
    set(gca,'XTick',((imp.t(rel_els(1)) - init_time):5:ceil((imp.t(rel_els(end)) - init_time))), 'YTick', [])
    set(gca, 'FontSize', ftsize)
else
    title(['Please annotate high quality (left) or low quality (right)  -  ' num2str(win) ' of ' num2str(NUMWINS) ' windows for subject ' num2str(s) ' of ' num2str(subjects(end))], 'FontSize', ftsize)
    ylabel('Impedance', 'FontSize', ftsize), xlabel('Time [s]', 'FontSize', ftsize);
    ylabel('Imepdance (above line = inhalation)', 'FontSize', ftsize)
    set(gca,'XTick',((imp.t(rel_els(1)) - init_time):5:ceil((imp.t(rel_els(end)) - init_time))), 'YTick', [])
    set(gca, 'FontSize', ftsize)
    if find(qual.t == starttime)
        rel_qual = qual.v(qual.t == starttime);
        if rel_qual
            annotation('textbox',[0.75, 0.2, 0.1,0.1],'String','High Quality', 'Color', 'b', 'FontSize', ftsize*3, 'LineStyle', 'None')
        else
            annotation('textbox',[0.75, 0.2, 0.1,0.1],'String','Low Quality', 'Color', 'r', 'FontSize', ftsize*3, 'LineStyle', 'None')
        end
    end
    if exist('pk_anns', 'var')
        % plot annotations which are relevant to this plot:
        breathels = find(pk_anns.t>=imp.t(rel_els(1)) & pk_anns.t<=imp.t(rel_els(end)));
        plot(pk_anns.t(breathels) - init_time,pk_anns.v(breathels), 'ro','LineWidth',4)
    end
end

axis_h = gca;

end

function [pk_anns, TRS]= Click_CallBack2(h,e, a, axis_h, h2, up, annotations_filepath, start_time)

switch get(ancestor(a,'figure'),'SelectionType')

    case 'normal' %left click
        point = get(a,'CurrentPoint');
        load(annotations_filepath);
        [pk_anns.t,inds]=unique([pk_anns.t; point(1,1)+start_time]);
        pk_anns.v=[pk_anns.v; point(1,2)]; pk_anns.v = pk_anns.v(inds);
        [pk_anns.t, inds] = sort(pk_anns.t);
        pk_anns.v = pk_anns.v(inds);
        save(annotations_filepath, 'pk_anns');

    case 'alt'  % right click
        point = get(a,'CurrentPoint');
        load(annotations_filepath);
        [pk_anns.t,inds]=unique([pk_anns.t; point(1,1)]);
        pk_anns.v=[pk_anns.v; point(1,2)]; pk_anns.v = pk_anns.v(inds);
        [pk_anns.t, inds] = sort(pk_anns.t);
        pk_anns.v = pk_anns.v(inds);
        save(annotations_filepath, 'pk_anns');

    case 'extend' % right click whilst holding down shift
        load(annotations_filepath)
        pk_anns.t = pk_anns.t(1:(end-1));
        pk_anns.v = pk_anns.v(1:(end-1));
        save(annotations_filepath, 'pk_anns');

end

cla(axis_h)
plot(pk_anns.t-start_time,pk_anns.v, 'ro','LineWidth',4)

end

function paw_verification_script_checker(subjects, data, up)
% this function is used to check that the results can indeed be plotted
% back on the original waveform:
%% initialisation
fprintf('\n\n\n\n\n~~~~~~~  Reviewing Annotations  ~~~~~~~\n');

%% find out the file details
operator=input('Please type the first and last initial,\nof the operator whose annotations\nyou''d like to review, and press enter:\n','s');
question=input('\nWould you like to start from the \nfirst subject? (y or n, followed by enter)\n', 's');
if strcmp(question, 'n') == 1
    start_subject = input('\nWhich subject?\n', 's');
    start_subject = str2double(start_subject);
else
    start_subject = 1;
end

start_subject_el = find(subjects == start_subject);
if isempty(start_subject_el)
    fprintf('\nThis subject doesn''t exist. Try all over again.');
else
    subjects = subjects(start_subject_el:end);
    for s = subjects(1:end)

        %% Load Impedance
        imp.fs = data(s).ref.resp_sig.imp.fs;
        imp.v = data(s).ref.resp_sig.imp.v;
        imp.t = [0:(length(imp.v)-1)]/imp.fs;

        %% Process Impedance
        imp = lpf_to_exclude_resp(imp, up);
        imp.v = -1*imp.v;

        %% Load annotations
        annotations_filepath = [up.paths.annotations, 'RRLISTEN' num2str(s), '_' operator '-imp_an.mat'];
        up_copy = up;
        load(annotations_filepath);
        up = up_copy; clear up_copy

        %% plot waveforms and annotations
        duration_of_signal = imp.t(end) - imp.t(1);
        NUMWINS = floor(duration_of_signal / up.win_length); clear duration_of_signal
        edge_time = up.edge_prop*up.win_length;
        for win = 1:NUMWINS
            % Setup
            starttime = imp.t(1)+edge_time+(win-1)*up.win_length;
            endtime = starttime + up.win_length;
            rel_els = find(imp.t >= starttime & imp.t < endtime);
            grey_els = find(imp.t >= (starttime - edge_time) & imp.t < (endtime + edge_time));
            scrsz = get(0,'ScreenSize');

            % Plot
            h=figure('OuterPosition',[1 1 scrsz(3) scrsz(4)]);
            [axis_h, h2] = annotation_plotter2(annotations_filepath, h, imp, grey_els, rel_els, s, subjects, up, win, NUMWINS, starttime);

            % close plot after a pause
            pause
            close all
        end
    end
end

end

function imp = lpf_to_exclude_resp(imp, up)

imp.v(isnan(imp.v)) = median(imp.v(~isnan(imp.v)));

%% Window signal to reduce edge effects
duration_of_signal = imp.t(end) - imp.t(1);
prop_of_win_in_outer_regions = 2*up.paramSet.tukey_win_duration_taper/duration_of_signal;
tukey_win = tukeywin(length(imp.v), prop_of_win_in_outer_regions);
d_s_win = imp;    % copy time and fs
d_s_win.v = detrend(imp.v(:)).*tukey_win(:);

%% LPF to remove freqs above resp
respWave.t = d_s_win.t;
respWave.v = lp_filter_signal_to_remove_freqs_above_resp(d_s_win.v, d_s_win.fs, up);
respWave.fs = d_s_win.fs;
imp = respWave;
end

function s_filt = lp_filter_signal_to_remove_freqs_above_resp(s, Fs, up)
%% Filter pre-processed signal to remove freqs above resp

% parameters for the low-pass filter to be used
flag  = 'scale';
Dpass = up.paramSet.elim_hf.Dpass;
Dstop = up.paramSet.elim_hf.Dstop;
Fstop = up.paramSet.elim_hf.Fstop;
Fpass = up.paramSet.elim_hf.Fpass;

% create filter
[N,Wn,BETA,TYPE] = kaiserord([Fstop Fpass]/(Fs/2), [1 0], [Dstop Dpass]);
b  = fir1(N, Wn, TYPE, kaiser(N+1, BETA), flag);
AMfilter = dfilt.dffir(b);

%% Check frequency response
% Gives a -3 dB cutoff at ? Hz, using:
% freqz(AMfilter.Numerator)
% norm_cutoff_freq = 0.3998;    % insert freq here from plot
% cutoff_freq = norm_cutoff_freq*(Fs/2);

% Prepare signal
s_dt=detrend(s);
s_filt = filtfilt(AMfilter.numerator, 1, s_dt);
end


function d = calc(e,d)

if 0
   if isa(d,'cell')
     for i=1:length(d)
       d{i}=feval(e.loss_type,e,d{i});
     end
   else
     d=feval(e.loss_type,e,d);
   end
end


function view_bdepth(lab1, valueMap)
    % view_maxz plots the maxz LTA values calculated
    % with maxzlta.m or other similar values as a color map
    % needs valueMap, gx, gy, stri
    %
    % define size of the plot etc.
    %
%
%          The Z-Value Map Window
%
%               This window displays seismicity rate changes
%               as z-values using a color code. Negative
%               z-values indicate an increase in the seismicity'
%               rate, positive values a decrease.
%               Some of the menu-bar options are
%               described below:
%
%               Threshold: You can set the maximum size that
%                 a volume is allowed to have in order to be
%                 displayed in the map. Therefore, areas with
%                 a low seismicity rate are not displayed.
%                 edit the size (in km) and click the mouse
%                 outside the edit window.
%              FixAx: You can chose the minimum and maximum
%                      values of the color-legend used.
%              Polygon: You can select earthquakes in a
%               polygon either by entering the coordinates or
%               defining the corners with the mouse
%
%              Circle: Select earthquakes in a circular volume:'
%                    Ni, the number of selected earthquakes can'
%                    be edited in the upper right corner of the'
%                    window.
%               Refresh Window: Redraws the figure, erases
%                     selected events.
%
%               zoom: Selecting Axis -> zoom on allows you to
%                     zoom into a region. Click and drag with
%                     the left mouse button. type <help zoom>
%                     for details.
%               Aspect: select one of the aspect ratio options
%               Text: You can select text items by clicking.The'
%                     selected text can be rotated, moved, you
%                     can change the font size etc.
%                     Double click on text allows editing it.

    % turned into function by Celso G Reyes 2017

    ZG=ZmapGlobal.Data; % used by get_zmap_globals

    report_this_filefun();

    % Find out if figure already exists
    %
    bmap=findobj('Name','b-value-depth-ratio-map');

    use_old_win = false;
    % This is the info window text

    % Set up the Seismicity Map window Enviroment
    %
    if isempty(bmap) || ~use_old_win
        bmap = figure_w_normalized_uicontrolunits( ...
            'Name','b-value-depth-ratio-map',...
            'NumberTitle','off', ...
            'NextPlot','new', ...
            'backingstore','on',...
            'Visible','off', ...
            'Position',position_in_current_monitor(ZG.map_len(1), ZG.map_len(2)));
        % make menu bar

        uicontrol('Units','normal',...
            'Position',[.0 .93 .08 .06],'String','Info ',...
            'callback',@callbackfun_001);

        create_my_menu();

        ZG.tresh_km = nan; re4 = valueMap;

        colormap(jet)
        ZG.tresh_km = nan; minpe = nan; Mmin = nan;

    end   % This is the end of the figure setup

    % Now lets plot the color-map of the z-value
    %
    figure(bmap);
    delete(findobj(bmap,'Type','axes'));
    % delete(sizmap);
    reset(gca)
    cla
    set(gca,'NextPlot','replace')
    watchon;
    set(gca,'visible','off','FontSize',ZmapGlobal.Data.fontsz.s,'FontWeight','bold',...
        'FontWeight','bold','LineWidth',1.5,...
        'Box','on','SortMethod','childorder')

    rect = [0.18,  0.10, 0.7, 0.75];
    rect1 = rect;

    % find max and min of data for automatic scaling
    %
    ZG.maxc = max(valueMap(:));
    ZG.maxc = fix(ZG.maxc)+1;
    ZG.minc = min(valueMap(:));
    ZG.minc = fix(ZG.minc)-1;

    % Find percentage above and below 1.0
    disp('HELP!!!!!!');
    under_1 = valueMap < 1.0;
    equal_1 = valueMap == 1.0;
    over_1 = valueMap > 1.0;

    total_num = length(valueMap);
    p_under = under_1/total_num;
    p_equal = equal_1/total_num;
    p_over = over_1/total_num;

    % set values gretaer ZG.tresh_km = nan
    %
    re4 = valueMap;
    re4(r > ZG.tresh_km) = nan;
    re4(Prmap < minpe) = nan;
    re4(old1 <  Mmin) = nan;

    % plot image
    %
    orient landscape
    %set(gcf,'PaperPosition', [0.5 1 9.0 4.0])

    axes('position',rect)
    set(gca,'NextPlot','add')
    pco1 = pcolor(gx,gy,re4);

    axis([ min(gx) max(gx) min(gy) max(gy)])
    axis image
    set(gca,'NextPlot','add')

    shading(ZG.shading_style);

    % make the scaling for the recurrence time map reasonable
    if lab1(1) =='T'
        re = valueMap(~isnan(valueMap));
        caxis([min(re) 5*min(re)]);
    end

    fix_caxis.ApplyIfFrozen(gca);

    title([name ';  '   num2str(t0b) ' to ' num2str(teb) ],'FontSize',ZmapGlobal.Data.fontsz.s,...
        'Color','r','FontWeight','bold')

    xlabel('Longitude [deg]','FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.s)
    ylabel('Latitude [deg]','FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.s)

    % plot overlay
    %
    set(gca,'NextPlot','add')
    zmap_update_displays();
    ploeq = plot(ZG.primeCatalog.Longitude,ZG.primeCatalog.Latitude,'k.');
    set(ploeq,'Tag','eq_plot','MarkerSize',ZG.ms6,'Marker',ty,'Color',ZG.someColor,'Visible','on')

    set(gca,'visible','on','FontSize',ZmapGlobal.Data.fontsz.s,'FontWeight','bold',...
        'FontWeight','bold','LineWidth',1.5,...
        'Box','on','TickDir','out')
    h1 = gca;
    hzma = gca;

    %lab1 = 'b-value-depth-ratio:';

    % Create a colorbar
    %
    h5 = colorbar('horiz');
    set(h5,'Pos',[0.35 0.05 0.4 0.02],...
        'FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.s,'TickDir','out')

    rect = [0.00,  0.0, 1 1];
    axes('position',rect)
    axis('off')
    %  Text Object Creation
    txt1 = text(...
        'Units','normalized',...
        'Position',[ 0.33 0.06 0 ],...
        'HorizontalAlignment','right',...
        'FontSize',ZmapGlobal.Data.fontsz.s,....
        'FontWeight','bold',...
        'String',lab1);
    ni_txt = text('Position', [.39 .12],'String',[num2str(ni_plot),' events per grid node.']);
    bval_txt =  text('Position', [.34 .96],'String',['Overall b-value depth ratio = ' num2str(depth_ratio)]);
    %bval2_txt =  text('Position', [.63 .95],'String',depth_ratio);

    dbrange1 = num2str(top_zonet);
    dbrange2 = num2str(top_zoneb);
    dbrange3 = num2str(bot_zonet);
    dbrange4 = num2str(bot_zoneb);
    mid_txt = text('Position', [.20 .915],'String', ['Top and bottom zones for ratio calculation(km):' dbrange1,' to ',dbrange2 ,' and ' dbrange3,' to ',dbrange4]);
    %mid2_txt = text('Position', [.685 .915],'String', [dbrange1,' to ',dbrange2 ,' and ' dbrange3,' to ',dbrange4]);

    % Make the figure visible
    %
    set(gca,'FontSize',ZmapGlobal.Data.fontsz.s,'FontWeight','bold',...
        'FontWeight','bold','LineWidth',1.5,...
        'Box','on','TickDir','out')
    figure(bmap);
    %sizmap = signatur('ZMAP','',[0.01 0.04]);
    %set(sizmap,'Color','k')
    axes(h1)
    watchoff(bmap)
    %whitebg(gcf,[ 0 0 0 ])

    %% ui functions
    function create_my_menu()
        add_menu_divider();

        add_symbol_menu('eq_plot');
        options = uimenu('Label',' Select ');
        uimenu(options,'Label','Refresh ','MenuSelectedFcn',@callbackfun_002)
        uimenu(options,'Label','Select EQ in Circle',...
            'MenuSelectedFcn',@callbackfun_003)

        op1 = uimenu('Label',' Maps ');

        adjmenu =  uimenu(op1,'Label','Adjust Map Display Parameters');
        uimenu(adjmenu,'Label','Adjust Rmax cut',...
            'MenuSelectedFcn',@callbackfun_004)
        uimenu(adjmenu,'Label','Adjust goodness of fit cut',...
            'MenuSelectedFcn',@callbackfun_005)

        uimenu(op1,'Label','Depth Ratio Map',...
            'MenuSelectedFcn',@callbackfun_013)

        uimenu(op1,'Label','Utsu Probability Map',...
            'MenuSelectedFcn',@callbackfun_014)

        uimenu(op1,'Label','Top Zone b value Map',...
            'MenuSelectedFcn',@callbackfun_015)

        uimenu(op1,'Label','Bottom Zone b value Map',...
            'MenuSelectedFcn',@callbackfun_016)

        uimenu(op1,'Label','% of nodal EQs within top zone',...
            'MenuSelectedFcn',@callbackfun_017)

        uimenu(op1,'Label','% of nodal EQs within bottom zone',...
            'MenuSelectedFcn',@callbackfun_018)

        uimenu(op1,'Label','resolution Map',...
            'MenuSelectedFcn',@callbackfun_019)
        uimenu(op1,'Label','Histogram ','MenuSelectedFcn',@(~,~)zhist())

        add_display_menu(1);
    end

    %% callback functions

    function callbackfun_001(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        web(['file:' hodi '/zmapwww/chp11.htm#996756']) ;
    end

    function callbackfun_002(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        use_old_win = 1;
        view_bdepth(lab1, valueMap);
    end

    function callbackfun_003(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        h1 = gca;
        met = 'rd';
        ZG=ZmapGlobal.Data;
        ZG.hold_state=false;
        cirbva_bdepth2;
        watchoff(bmap);
    end

    function callbackfun_004(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        asel = 'rmax';
        adjub();
        view_bdepth(lab1, valueMap);
    end

    function callbackfun_005(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        asel = 'gofi';
        adjub();
        use_old_win = 1;
        view_bdepth(lab1, valueMap);
    end

    function callbackfun_013(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        lab1='b ratio';
        valueMap = old;
        view_bdepth(lab1, valueMap);
    end

    function callbackfun_014(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        lab1='Probability';
        valueMap = Prmap;
        view_bdepth;
    end

    function callbackfun_015(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        lab1='Top Zone b value';
        valueMap = top_b;
        view_bdepth(lab1, valueMap);
    end

    function callbackfun_016(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        lab1='Bottom Zone b value';
        valueMap = bottom_b;
        view_bdepth(lab1, valueMap);
    end

    function callbackfun_017(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        lab1='% of nodal EQs within top zone';
        valueMap = per_top;
        view_bdepth(lab1, valueMap);
    end

    function callbackfun_018(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        lab1='% of nodal eqs within bottom zone';
        valueMap = per_bot;
        view_bdepth(lab1, valueMap);
    end

    function callbackfun_019(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        lab1='Radius in [km]';
        valueMap = r;
        view_bdepth(lab1, valueMap);
    end

    function adjub()
        report_this_filefun();

        prompt={'Enter the maximum radius cut-off:','Enter the minimum Utsu probability '};
        def={'nan','nan'};
        dlgTitle='Input Map Selection Criteria';
        lineNo=1;
        answer=inputdlg(prompt,dlgTitle,lineNo,def);
        re4 = valueMap;

        ZG.tresh_km = str2double(answer{2,1}) ;
        minpe = str2double(answer{1,1}) ;

        if ZG.tresh_km >= 0
            valueMap(Prmap < ZG.tresh_km) = 1;
        elseif minpe >= 0
            valueMap(r >= minpe) = 1;
        end

        ca = caxis;

        ve = ca(1):(ca(2)-ca(1))/64:ca(2);

        i = find(abs(ve-1) == min(abs(ve-1)) );

        col = jet;
        col(i,:) = [0.8 0.8 0.8] ;
        col(i-1,:) = [0.8 0.8 0.8] ;
        col(i+1,:) = [0.8 0.8 0.8] ;

        colormap(col);
    end
end


function cvx_end

%CVX_END  Completes a cvx specification.
%   CVX_BEGIN marks the end of a new cvx model, and instructs cvx to
%   complete its processing. For standard, complete models, cvx will send
%   a transformed version of the problem to a solver to obtain numeric
%   results, and replace references to cvx variables with numeric values.

try
    evalin( 'caller', 'cvx_verify' );
    evalin( 'caller', 'cvx_finish' );
    evalin( 'caller', 'cvx_pop' );
catch exc
    if ~isequal( exc.identifier, 'CVX:IncompatibleSolver' ),
        evalin( 'caller', 'cvx_pop' );
    end
    rethrow( exc );
end

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