function ft_realtime_headlocalizer(cfg)

% FT_REALTIME_HEADLOCALIZER is a real-time application for online visualization of
% the head position for the CTF275 and the Neuromag/Elekta/Megin systems. This uses the
% continuous head localization (in CTF terminology, i.e. CHL) or position indicator
% (in Neuromag/Elekta/Megin terminology, i.e. cHPI) information.
%
% Repositioning the subject to a previous recording session can be done by specifying
% the previous dataset as cfg.template = 'subject01xxx.ds', or by pointing to a text
% file created during a previous recording; e.g. cfg.template = '29-Apr-2013-xxx.txt'.
% The latter textfile is written automatically to disk with each 'Update' buttonpress.
%
% The online visualization shows the displacement of the head relative to the start
% of the recording. The timepoint (i.e. position) relative to which the displacement
% is shown can be updated can be achieved by marking the HPI at an arbitrary moment
% by clicking the 'Update' button. This allows for repositioning within a recording
% session. Black unfilled markers should appear which indicate the positions of the
% coils at the moment of buttonpress. Distance to these marked positions then become
% colorcoded, i.e. green, orange, or red.
%
% Use as
%   ft_realtime_headlocalizer(cfg)
% with the following configuration options
%   cfg.dataset         = string, name or location of a dataset/buffer (default = 'buffer://odin:1972')
%   cfg.template        = string, name of a template dataset for between-session repositioning (default = [])
%   cfg.bufferdata      = whether to start on the 'first or 'last' data that is available (default = 'last')
%   cfg.xlim            = [min max], range in cm to plot (default = [-15 15])
%   cfg.ylim            = [min max], range in cm to plot (default = [-15 15])
%   cfg.zlim            = [min max], range in cm to plot (default is automatic)
%   cfg.blocksize       = number, size of the blocks/chuncks that are processed (default = 1 second)
%   cfg.accuracy_green  = distance from fiducial coordinate; green when within limits (default = 0.15 cm)
%   cfg.accuracy_orange = orange when within limits, red when out (default = 0.3 cm)
%   cfg.dewar           = filename or mesh, description of the dewar shape (default is automatic)
%   cfg.polhemus        = filename or mesh, description of the head shape recorded with the Polhemus (default is automatic)
%   cfg.headshape       = filename or mesh, description of the head shape recorded with the Structure Sensor
%
% The following options only apply to data from the Neuromag/Elekta/Megin system
%   cfg.headmovement    = string, name or location of the .pos file created by MaxFilter which describes the location of the head relative to the dewar
%   cfg.coilfreq        = single number in Hz or list of numbers (default = [293, 307, 314, 321, 328])
%
% This method is described in Stolk A, Todorovic A, Schoffelen JM, Oostenveld R.
% "Online and offline tools for head movement compensation in MEG."
% Neuroimage. 2013 Mar;68:39-48. doi: 10.1016/j.neuroimage.2012.11.047.

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

agreement = {
  'By using this realtime headlocalizer tool in your research, you agree to citing the publication below.'
  ''
  'Stolk A, Todorovic A, Schoffelen JM, Oostenveld R.'
  '"Online and offline tools for head movement compensation in MEG."'
  'Neuroimage. 2013 Mar;68:39-48.'
  };

if ~strcmp(questdlg(agreement, 'User agreement', 'Yes', 'Cancel', 'Cancel'), 'Yes')
  return
end

% do the general setup of the function
ft_defaults

% set the defaults
cfg.dataset         = ft_getopt(cfg, 'dataset', 'buffer://odin:1972'); % location of the buffer/dataset
cfg.accuracy_green  = ft_getopt(cfg, 'accuracy_green',  .15); % green when within this distance from reference
cfg.accuracy_orange = ft_getopt(cfg, 'accuracy_orange',  .3); % orange when within this distance from reference
cfg.template        = ft_getopt(cfg, 'template',         []); % template dataset containing the references
cfg.blocksize       = ft_getopt(cfg, 'blocksize',         1); % in seconds
cfg.bufferdata      = ft_getopt(cfg, 'bufferdata',   'last'); % first (replay) or last (real-time)
cfg.coilfreq        = ft_getopt(cfg, 'coilfreq',   [293, 307, 314, 321, 328]); % in Hz for Neuromag
cfg.dewar           = ft_getopt(cfg, 'dewar',            []); % mesh of the dewar
cfg.headshape       = ft_getopt(cfg, 'headshape',        []); % mesh of the head with the structure sensor
cfg.polhemus        = ft_getopt(cfg, 'polhemus',         []); % mesh of the head recorded with the polhemus
cfg.headmovement    = ft_getopt(cfg, 'headmovement',     []); % maxfilter created file containing quaternions information for headlocalistation

% ensure pesistent variables are cleared
clear ft_read_header

% start by reading the header from the realtime buffer
cfg = ft_checkconfig(cfg, 'dataset2files', 'yes'); % translate dataset into datafile+headerfile
hdr = ft_read_header(cfg.headerfile, 'cache', true, 'coordsys', 'dewar');

% for backward compatibility, can be removed end 2018
cfg = ft_checkconfig(cfg, 'renamed', {'head', 'headshape'});

% determine the size of blocks to process
blocksize   = round(cfg.blocksize * hdr.Fs);
prevSample  = 0;
count       = 0;

% determine MEG system type
isneuromag = ft_senstype(hdr.grad, 'neuromag');
isctf      = ft_senstype(hdr.grad, 'ctf275');

% this is needed to fit everything in the figure, note that the dewar coordinate systems differ
if isctf
  cfg.xlim            = ft_getopt(cfg, 'xlim', [-15 15]);
  cfg.ylim            = ft_getopt(cfg, 'ylim', [-15 15]);
  cfg.zlim            = ft_getopt(cfg, 'zlim', [-38 -8]);
elseif isneuromag
  cfg.xlim            = ft_getopt(cfg, 'xlim', [-15 15]);
  cfg.ylim            = ft_getopt(cfg, 'ylim', [-15 15]);
  cfg.zlim            = ft_getopt(cfg, 'zlim', [-25 15]);
end

if isempty(cfg.dewar)
  [v, p] = ft_version;
  if isctf
    cfg.dewar = fullfile(p, 'template', 'dewar', 'ctf.mat');
  elseif isneuromag
    cfg.dewar = fullfile(p, 'template', 'dewar', 'elekta.mat');
  end
end

if ischar(cfg.dewar) && exist(cfg.dewar, 'file')
  fprintf('reading dewar from file %s\n', cfg.dewar);
  cfg.dewar = ft_read_headshape(cfg.dewar);
end

if ischar(cfg.headshape) && exist(cfg.headshape, 'file')
  fprintf('reading headshape from file %s\n', cfg.headshape);
  cfg.headshape = ft_read_headshape(cfg.headshape);
end

if ischar(cfg.polhemus) && exist(cfg.polhemus, 'file')
  fprintf('reading polhemus data from file %s\n', cfg.polhemus);
  cfg.polhemus = ft_read_headshape(cfg.polhemus);
elseif isneuromag
  fprintf('reading polhemus data from file %s\n', cfg.dataset);
  % Neuromag/Elekta/Megin dataset will contain head shape
  cfg.polhemus = ft_read_headshape(cfg.dataset);
elseif isctf
  fprintf('reading polhemus data from file %s\n', cfg.dataset);
  % CTF dataset may contain electrode information
  elec = ft_read_sens(cfg.dataset, 'senstype', 'eeg');
  cfg.polhemus.pos  = elec.elecpos;
  cfg.polhemus.unit = elec.unit;
end

if ~isempty(cfg.headshape)
  cfg.headshape = ft_convert_units(cfg.headshape, 'cm');
end

if ~isempty(cfg.polhemus)
  cfg.polhemus = ft_convert_units(cfg.polhemus, 'cm');
end

if ~isempty(cfg.dewar)
  cfg.dewar = ft_convert_units(cfg.dewar, 'cm');
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% read template head position, to reposition to, if template file is specified
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if isctf
  if ~isempty(cfg.template)
    [p, f, x] = fileparts(cfg.template);
    if strcmp(x, '.ds')
      shape = ft_read_headshape(cfg.template, 'coordsys', 'dewar', 'format', 'ctf_ds');
      template(1,:) = [shape.fid.pos(1,1), shape.fid.pos(1,2), shape.fid.pos(1,3)]; % chan X pos
      template(2,:) = [shape.fid.pos(2,1), shape.fid.pos(2,2), shape.fid.pos(2,3)];
      template(3,:) = [shape.fid.pos(3,1), shape.fid.pos(3,2), shape.fid.pos(3,3)];
    elseif strcmp(x, '.txt')
      template = dlmread(cfg.template);
    else
      ft_error('incorrect template file specified');
    end
  else
    template = [];
  end

  % remove CTF REF sensors, for plotting purposes
  chansel = match_str(hdr.grad.chantype, 'meggrad');
  hdr.grad.chanpos  = hdr.grad.chanpos(chansel,:);
  hdr.grad.chanori  = hdr.grad.chanori(chansel,:);
  hdr.grad.chantype = hdr.grad.chantype(chansel,:);
  hdr.grad.label    = hdr.grad.label(chansel,:);
  hdr.grad.tra      = hdr.grad.tra(chansel,:);

elseif isneuromag
  if ~isempty(cfg.template)
    [p, f, x] = fileparts(cfg.template);
    if strcmp(x, '.fif')
      shape = ft_read_headshape(cfg.template, 'coordsys', 'dewar', 'format', 'neuromag_fif');
      template(1,:) = [shape.fid.pos(1,1), shape.fid.pos(1,2), shape.fid.pos(1,3)]; % chan X pos
      template(2,:) = [shape.fid.pos(2,1), shape.fid.pos(2,2), shape.fid.pos(2,3)];
      template(3,:) = [shape.fid.pos(3,1), shape.fid.pos(3,2), shape.fid.pos(3,3)];
    elseif strcmp(x, '.txt')
      template = dlmread(cfg.template);
    end
  else
    template = [];
  end

else
  ft_error('the data does not resemble ctf, nor neuromag')
end % if ctf or neuromag

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% read digitized head position (for dipole fitting)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if isctf
  sens = hdr.grad;
  % not needed for CTF275 systems
  dip  = [];
  vol  = [];
  coilsignal = [];

elseif isneuromag
  shape = ft_read_headshape(cfg.headerfile, 'coordsys', 'dewar', 'format', 'neuromag_fif', 'unit', 'cm');
  for i = 1:min(size(shape.pos,1),length(cfg.coilfreq)) % for as many digitized or specified coils
    if ~isempty(strfind(shape.label{i}, 'hpi'))
      dip(i).pos = shape.pos(i,:); % chan X pos, initial guess for each of the dipole/coil positions
      dip(i).mom = [0 0 0]';
    end
  end
  if ~exist('dip', 'var')
    ft_error('head localization requires digitized positions for Neuromag systems')
  end

  % prepare the forward model and the sensor array for subsequent fitting
  % note that the forward model is a magnetic dipole in an infinite vacuum
  cfg.channel = ft_channelselection('MEGMAG', hdr.label); % old
  [vol, sens] = ft_prepare_vol_sens([], hdr.grad, 'channel', cfg.channel);
  sens = ft_datatype_sens(sens, 'scaling', 'amplitude/distance', 'distance', 'cm'); % ensure SI units
  coilsignal = [];

  % update distances, given that sensor units are m an not cm
  cfg.accuracy_green = cfg.accuracy_green/100;
  cfg.accuracy_orange = cfg.accuracy_orange/100;

else
  ft_error('the data does not resemble ctf, nor neuromag')
end % if ctf or neuromag

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% define a subset of channels for reading
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if isctf
  [dum, chanindx] = match_str('headloc', hdr.chantype);

elseif isneuromag
  % depending on wether movement compensation was done or only head position
  % estimation, the fif file that results from Maxfilter will contain 9 channels that
  % start with QUAT or with CHPI

  if ~isempty(cfg.headmovement)
    % load the head position information from cfg.headmovement
    tmpcfg = [];
    tmpcfg.dataset = cfg.headmovement;
    tmpcfg.channel = 'QUAT*';
    data_movement  = ft_preprocessing(tmpcfg);

    % ensure that it is regularly sampled
    tmpcfg = [];
    tmpcfg.time{1} = (1:data_movement.hdr.nSamples)/data_movement.hdr.Fs;
    data_movement  = ft_resampledata(tmpcfg, data_movement);

  elseif sum(startsWith(hdr.label, 'QUAT'))==9
    % the data only contains the estimated position, but has not been movement corrected
    chanindx = find(startsWith(hdr.label, 'QUAT'));

  elseif sum(startsWith(hdr.label, 'CHPI'))==9
    % this is movement corrected data
    chanindx = find(startsWith(hdr.label, 'CHPI'));

  else
    % select the 102 magnetometers for fitting of the HPI coils
    [dum, chanindx] = match_str('megmag', hdr.chantype);
  end
end

if isempty(chanindx)
  ft_error('the data does not seem to have head localization channels');
end

% this information is passed between the GUI callback functions
info                    = [];
info.hdr                = hdr;
info.blocksize          = blocksize;
info.isctf              = isctf;
info.isneuromag         = isneuromag;
info.cfg                = cfg;
info.template           = template;
info.sens               = sens;
info.vol                = vol;
info.dip                = dip;
info.continue           = true;
clear hdr blocksize isctf isneuromag cfg template sens vol dip

% initiate main figure
hMainFig = figure;

% attach the info in the figure
guidata(hMainFig, info);

% initiate gui controls
uicontrol_sub(hMainFig);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% this is the general BCI loop where realtime incoming data is handled
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
while ishandle(hMainFig) && info.continue % while the flag is one, the loop continues

  % get the potentially updated information from the main window
  info = guidata(hMainFig);

  % determine number of samples available in buffer
  info.hdr = ft_read_header(info.cfg.headerfile, 'cache', true, 'coordsys', 'dewar');

  % see whether new samples are available
  newsamples = (info.hdr.nSamples*info.hdr.nTrials-prevSample);

  if newsamples>=info.blocksize

    if strcmp(info.cfg.bufferdata, 'last')
      begsample  = info.hdr.nSamples*info.hdr.nTrials - info.blocksize + 1;
      endsample  = info.hdr.nSamples*info.hdr.nTrials;
    elseif strcmp(info.cfg.bufferdata, 'first')
      begsample  = prevSample + 1;
      endsample  = prevSample + info.blocksize;
    else
      ft_error('unsupported value for cfg.bufferdata');
    end

    % remember up to where the data was read
    prevSample  = endsample;
    count       = count + 1;
    fprintf('processing segment %d from sample %d to %d\n', count, begsample, endsample);

    % read data segment from buffer
    dat = ft_read_data(info.cfg.datafile, 'header', info.hdr, 'begsample', begsample, 'endsample', endsample, 'chanindx', chanindx, 'checkboundary', false);

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % from here onward it is specific to the head localization
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

    % put the data in a fieldtrip-like raw structure
    data.trial{1} = double(dat);
    data.time{1}  = offset2time(begsample, info.hdr.Fs, endsample-begsample+1);
    data.label    = info.hdr.label(chanindx);
    data.hdr      = info.hdr;
    data.fsample  = info.hdr.Fs;

    if ~isempty(info.cfg.headmovement) && info.isneuromag
      if ~all(startsWith(data.label, 'QUAT')) || ~all(startsWith(data.label, 'CHPI'))
        data.trial{1} = data_movement.trial{1}(1:size(data_movement.trial{1}),begsample:endsample);
        data.label    = data_movement.label;
      else
        fprintf('Channels for head localisation already in the .fif file, will use data form the .fif file')
      end
    end

    if info.isneuromag && size(coilsignal,2)~=info.blocksize
      % construct the reference signal for each of the coils
      % this needs to be updated if the blocksize changes
      ncoil = length(info.cfg.coilfreq);
      if ncoil==0
        ft_error('no coil frequencies were specified');
      else
        time = (1:info.blocksize)./info.hdr.Fs;
        coilsignal = zeros(ncoil, info.blocksize);
        for i=1:ncoil
          coilsignal(i,:) = exp(time*info.cfg.coilfreq(i)*1i*2*pi);
          coilsignal(i,:) = coilsignal(i,:) / norm(coilsignal(i,:));
        end
      end
    end

    % compute the HPI coil positions, this takes some time
    [hpi, info.dip] = data2hpi(data, info.dip, info.vol, info.sens, coilsignal, info.isctf, info.isneuromag); % for neuromag datasets this is relatively slow

    guidata(hMainFig, info);

    if ~ishandle(hMainFig)
      % the figure has been closed
      break
    end

    % get the potentially updated information from the main window
    info = guidata(hMainFig);
    % update the info
    info.hpi = hpi;

    % store the updated gui variables
    guidata(hMainFig, info);

    % DRAW LEFT PANEL - TOP VIEW
    a = subplot(1,2,1);
    h = get(a, 'children');
    hold on;

    if ~isempty(h)
      % done on every iteration
      delete(h);
    end

    % draw the color-coded head and distances from the templates
    draw_sub(hMainFig);

    % show current timesample
    title(sprintf('top view, runtime = %d s\n', round(mean(data.time{1}))));

    % not needed any more
    clear data;

    % viewing angle
    if info.isctf
      view(-45, 90)
    elseif info.isneuromag
      view(0, 90)
    end

    % DRAW RIGHT PANEL - FRONT/REAR VIEW
    b = subplot(1,2,2);
    i = get(b, 'children');
    hold on;

    if ~isempty(i)
      % done on every iteration
      delete(i);
    end

    % draw the color-coded head and distances from the templates
    draw_sub(hMainFig);

    % viewing angle
    if get(info.hViewMirrorButton, 'Value') == 1
      if info.isctf
        set(gca, 'Ydir', 'reverse')
        view(45, 0)
      elseif info.isneuromag
        set(gca, 'Ydir', 'reverse')
        view(0, 0)
      end
      title(sprintf('Mirror view, clock time %s', datestr(now))); % show current data & time
    else
      if info.isctf
        set(gca, 'Ydir', 'normal')
        view(135, 0)
      elseif info.isneuromag
        set(gca, 'Ydir', 'normal')
        view(180, 0)
      end
      title(sprintf('Normal view, clock time %s', datestr(now))); % show current data & time
    end

    % force Matlab to update the figure
    drawnow

  end % if enough new samples
end % while true

close(hMainFig); % close the figure

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION that initiates the figure
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function uicontrol_sub(handle, eventdata)

% get the info
info = guidata(handle);

% initiate figure
set(handle, 'KeyPressFcn', {@key_sub});

hUpdateButton = uicontrol(...
  'Parent', handle,...
  'Style', 'pushbutton',...
  'String', 'Update',...
  'Units', 'normalized',...
  'Position', [.65 .0875 .15 .075],...
  'FontSize', 12,...
  'Callback', {@update_ButtonDownFcn});

hQuitButton = uicontrol(...
  'Parent', handle,...
  'Style', 'pushbutton',...
  'String', 'Quit',...
  'Units', 'normalized',...
  'Position', [.8 .0875 .15 .075],...
  'FontSize', 12,...
  'Callback', {@quit_ButtonDownFcn});

hSphereCheckBox = uicontrol(...
  'Parent', handle,...
  'Style', 'checkbox',...
  'String', 'Sphere',...
  'Units', 'normalized',...
  'Position', [.05 .1 .075 .05],...
  'FontSize', 8,...
  'BackgroundColor', [.8 .8 .8],...
  'Value', 1,...
  'Callback', {@sphere_CheckBox});

hHeadCheckBox = uicontrol(...
  'Parent', handle,...
  'Style', 'checkbox',...
  'String', 'Head',...
  'Units', 'normalized',...
  'Position', [.125 .1 .1 .05],...
  'FontSize', 8,...
  'BackgroundColor', [.8 .8 .8],...
  'Value', 0,... % by default switched on
  'Callback', {@head_CheckBox});

hPolhemusCheckBox = uicontrol(...
  'Parent', handle,...
  'Style', 'checkbox',...
  'String', 'Polhemus',...
  'Units', 'normalized',...
  'Position', [.2 .1 .075 .05],...
  'FontSize', 8,...
  'BackgroundColor', [.8 .8 .8],...
  'Value', 0,...
  'Callback', {@Polhemus_CheckBox});

hDewarCheckBox = uicontrol(...
  'Parent', handle,...
  'Style', 'checkbox',...
  'String', 'Dewar',...
  'Units', 'normalized',...
  'Position', [.275 .1 .075 .05],...
  'FontSize', 8,...
  'BackgroundColor', [.8 .8 .8],...
  'Value', 0,...
  'Callback', {@Dewar_CheckBox});

hCoilCheckBox = uicontrol(...
  'Parent', handle,...
  'Style', 'checkbox',...
  'String', 'Coils',...
  'Units', 'normalized',...
  'Position', [.35 .1 .075 .05],...
  'FontSize', 8,...
  'BackgroundColor', [.8 .8 .8],...
  'Value', 1,...
  'Callback', {@coil_CheckBox});

hSensorCheckBox = uicontrol(...
  'Parent', handle,...
  'Style', 'checkbox',...
  'String', 'Sensors',...
  'Units', 'normalized',...
  'Position', [.425 .1 .075 .05],...
  'FontSize', 8,...
  'BackgroundColor', [.8 .8 .8],...
  'Value', 0,...
  'Callback', {@sensor_CheckBox});

hAxisCheckBox = uicontrol(...
  'Parent', handle,...
  'Style', 'checkbox',...
  'String', 'Axis',...
  'Units', 'normalized',...
  'Position', [.5 .1 .075 .05],...
  'FontSize', 8,...
  'BackgroundColor', [.8 .8 .8],...
  'Value', 0,...
  'Callback', {@axis_CheckBox});

hBlocksizeMenu = uicontrol(...
  'Parent', handle,...
  'Style', 'popupmenu',...
  'String', {'.1 second', '.2 second', '.5 second', '1 second', '1.5 second', '2 seconds', '5 seconds', '10 seconds', '30 seconds'},...
  'Units', 'normalized',...
  'Position', [.6 .1925 .1 .05],...
  'FontSize', 8,...
  'BackgroundColor', [.8 .8 .8],...
  'Value', 1,... % default
  'Callback', {@blocksize_Menu});

hViewMirrorButton = uicontrol(...
  'Parent', handle,...
  'Style', 'checkbox',...
  'String', 'Mirror View',...
  'Units', 'normalized',...
  'Position', [.8 .1925 .1 .05],...
  'FontSize', 8,...
  'BackgroundColor', [.8 .8 .8],...
  'Value', 1,... % by default switched on
  'Callback', {@mirror_CheckBox});

info.hQuitButton        = hQuitButton;
info.hCoilCheckBox      = hCoilCheckBox;
info.hSphereCheckBox    = hSphereCheckBox;
info.hDewarCheckBox     = hDewarCheckBox;
info.hSensorCheckBox    = hSensorCheckBox;
info.hViewMirrorButton  = hViewMirrorButton;
info.hBlocksizeMenu     = hBlocksizeMenu;
info.hRealistic         = hHeadCheckBox;
info.hPolhemusCheckBox  = hPolhemusCheckBox;
info.hAxisCheckBox      = hAxisCheckBox;

% put the info back
guidata(handle, info);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION that computes the HPI coil positions
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [hpi, dip] = data2hpi(data, dip, vol, sens, coilsignal, isctf, isneuromag)

% The CTF275 system localizes the HPI coil positions online, and writes them
% to the dataset. For the Neuromag systems the signals evoked by the HPI coils
% are superimposed on the other signals. This requires additional online
% dipolefitting of those HPI coils.

if isctf
  % assign the channels to the resp. coil coordinates
  [dum, x1] = match_str('HLC0011', data.label);
  [dum, y1] = match_str('HLC0012', data.label);
  [dum, z1] = match_str('HLC0013', data.label);
  [dum, x2] = match_str('HLC0021', data.label);
  [dum, y2] = match_str('HLC0022', data.label);
  [dum, z2] = match_str('HLC0023', data.label);
  [dum, x3] = match_str('HLC0031', data.label);
  [dum, y3] = match_str('HLC0032', data.label);
  [dum, z3] = match_str('HLC0033', data.label);

  % convert from meter to cm and assign to the resp. coil
  hpi{1} = data.trial{1}([x1 y1 z1],end) * 100;
  hpi{2} = data.trial{1}([x2 y2 z2],end) * 100;
  hpi{3} = data.trial{1}([x3 y3 z3],end) * 100;

elseif isneuromag
  if all(startsWith(data.label, 'QUAT'))
    q1 = data.trial{1}(strcmp(data.label, 'QUAT001'),:);
    q2 = data.trial{1}(strcmp(data.label, 'QUAT002'),:);
    q3 = data.trial{1}(strcmp(data.label, 'QUAT003'),:);
    q4 = -data.trial{1}(strcmp(data.label, 'QUAT004'),:);
    q5 = -data.trial{1}(strcmp(data.label, 'QUAT005'),:);
    q6 = -data.trial{1}(strcmp(data.label, 'QUAT006'),:);
    q = [q1(1) q2(1) q3(1) q4(1) q5(1) q6(1)];

    % compute the anatomical landmark location in cm
    hpi{1} = ft_warp_apply(q(end,:), data.hdr.orig.dig(1).r' , 'quaternion')'*100;
    hpi{2} = ft_warp_apply(q(end,:), data.hdr.orig.dig(2).r' , 'quaternion')'*100;
    hpi{3} = ft_warp_apply(q(end,:), data.hdr.orig.dig(3).r' , 'quaternion')'*100;

  elseif all(startsWith(data.label, 'CHPI'))
    q1 = data.trial{1}(strcmp(data.label, 'CHPI001'),:);
    q2 = data.trial{1}(strcmp(data.label, 'CHPI002'),:);
    q3 = data.trial{1}(strcmp(data.label, 'CHPI003'),:);
    q4 = -data.trial{1}(strcmp(data.label, 'CHPI004'),:);
    q5 = -data.trial{1}(strcmp(data.label, 'CHPI005'),:);
    q6 = -data.trial{1}(strcmp(data.label, 'CHPI006'),:);
    q = [q1(1) q2(1) q3(1) q4(1) q5(1) q6(1)];

    % compute the anatomical landmark location in cm
    hpi{1} = ft_warp_apply(q(end,:), data.hdr.orig.dig(1).r' , 'quaternion')'*100;
    hpi{2} = ft_warp_apply(q(end,:), data.hdr.orig.dig(2).r' , 'quaternion')'*100;
    hpi{3} = ft_warp_apply(q(end,:), data.hdr.orig.dig(3).r' , 'quaternion')'*100;

  else
    % estimate the complex-valued MEG topography for each coil
    % this implements a discrete Fourier transform (DFT)
    topo = [];
    %[x, ut] = svdfft( data.trial{1} );
    %data.trial{1} = x;
    topo = ft_preproc_detrend(data.trial{1}) * ctranspose(coilsignal);

    % ignore the out-of-phase spectral component in the topography
    topo = real(topo); % THIS SEEMS TO BE CRUCIAL

    % fit a magnetic dipole to each of the topographies
    constr.sequential = true; % for BTI systems this would be 'false' as all coils have the same frequency
    constr.rigidbody = true;

    % fit the coils together
    dipall = [];
    ncoil = numel(dip);
    for i=1:ncoil
      dipall.pos(i,:) = dip(i).pos;
    end
    dipall = ft_inverse_dipolefit(dipall, sens, vol, topo, 'constr', constr, 'display', 'off');
    for i=1:ncoil
      sel = (1:3) + 3*(i-1);
      dip(i).pos = dipall.pos(i,:);
      dip(i).mom = real(dipall.mom(sel,i)); % ignore the complex phase information
      hpi{i} = dip(i).pos;
    end
  end
else
  ft_error('the data does not resemble ctf, nor neuromag')
end % if ctf or neuromag

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION that does the timing
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [time] = offset2time(offset, fsample, nsamples)

offset   = double(offset);
nsamples = double(nsamples);
time = (offset + (0:(nsamples-1)))/fsample;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION which computes the circumcenter(x,y,z) of the 3D triangle (3 coils)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [cc] = circumcenter(hpi)

% use coordinates relative to point `a' of the triangle
xba = hpi{2}(1) - hpi{1}(1);
yba = hpi{2}(2) - hpi{1}(2);
zba = hpi{2}(3) - hpi{1}(3);
xca = hpi{3}(1) - hpi{1}(1);
yca = hpi{3}(2) - hpi{1}(2);
zca = hpi{3}(3) - hpi{1}(3);

% squares of lengths of the edges incident to `a'
balength = xba * xba + yba * yba + zba * zba;
calength = xca * xca + yca * yca + zca * zca;

% cross product of these edges
xcrossbc = yba * zca - yca * zba;
ycrossbc = zba * xca - zca * xba;
zcrossbc = xba * yca - xca * yba;

% calculate the denominator of the formulae
denominator = 0.5 / (xcrossbc * xcrossbc + ycrossbc * ycrossbc + zcrossbc * zcrossbc);

% calculate offset (from `a') of circumcenter
xcirca = ((balength * yca - calength * yba) * zcrossbc - (balength * zca - calength * zba) * ycrossbc) * denominator;
ycirca = ((balength * zca - calength * zba) * xcrossbc - (balength * xca - calength * xba) * zcrossbc) * denominator;
zcirca = ((balength * xca - calength * xba) * ycrossbc - (balength * yca - calength * yba) * xcrossbc) * denominator;

cc(1) = xcirca + hpi{1}(1);
cc(2) = ycirca + hpi{1}(2);
cc(3) = zcirca + hpi{1}(3);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION which draws the color-coded head and distances to the template
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function draw_sub(handle)

% get the info
info = guidata(handle);

% compute transformation
if info.isctf
  M          = ft_headcoordinates([info.hpi{1}(1),info.hpi{1}(2),info.hpi{1}(3)], [info.hpi{2}(1),info.hpi{2}(2),info.hpi{2}(3)], [info.hpi{3}(1),info.hpi{3}(2),info.hpi{3}(3)], 'ctf');
elseif info.isneuromag
  M          = ft_headcoordinates([info.hpi{2}(1),info.hpi{2}(2),info.hpi{2}(3)], [info.hpi{1}(1),info.hpi{1}(2),info.hpi{1}(3)], [info.hpi{3}(1),info.hpi{3}(2),info.hpi{3}(3)], 'neuromag');
end
M(1:3,1:3) = inv(M(1:3,1:3));
M(1:3,4)   = (-M(1:3,4)'/M(1:3,1:3))';

% plot the HPI mismatch
if get(info.hCoilCheckBox, 'Value')
  if info.isctf
    % draw nasion position
    if ~isempty(info.template)
      if abs(info.template(1,1))-info.cfg.accuracy_green < abs(info.hpi{1}(1)) && abs(info.hpi{1}(1)) < abs(info.template(1,1))+info.cfg.accuracy_green ...
          && abs(info.template(1,2))-info.cfg.accuracy_green < abs(info.hpi{1}(2)) && abs(info.hpi{1}(2)) < abs(info.template(1,2))+info.cfg.accuracy_green ...
          && abs(info.template(1,3))-info.cfg.accuracy_green < abs(info.hpi{1}(3)) && abs(info.hpi{1}(3)) < abs(info.template(1,3))+info.cfg.accuracy_green
        plot3(info.hpi{1}(1),info.hpi{1}(2),info.hpi{1}(3), 'g^', 'MarkerFaceColor', [.5 1 .5], 'MarkerSize',25)
        head1 = true;
      elseif abs(info.template(1,1))-info.cfg.accuracy_orange < abs(info.hpi{1}(1)) && abs(info.hpi{1}(1)) < abs(info.template(1,1))+info.cfg.accuracy_orange ...
          && abs(info.template(1,2))-info.cfg.accuracy_orange < abs(info.hpi{1}(2)) && abs(info.hpi{1}(2)) < abs(info.template(1,2))+info.cfg.accuracy_orange ...
          && abs(info.template(1,3))-info.cfg.accuracy_orange < abs(info.hpi{1}(3)) && abs(info.hpi{1}(3)) < abs(info.template(1,3))+info.cfg.accuracy_orange
        plot3(info.hpi{1}(1),info.hpi{1}(2),info.hpi{1}(3), 'y^', 'MarkerFaceColor', [1 .5 0], 'MarkerEdgeColor', [1 .5 0], 'MarkerSize', 25)
        head1 = false;
      else % when not in correct position
        plot3(info.hpi{1}(1),info.hpi{1}(2), info.hpi{1}(3), 'r^', 'MarkerFaceColor', [1 0 0], 'MarkerSize', 25)
        head1 = false;
      end
    else
      plot3(info.hpi{1}(1),info.hpi{1}(2), info.hpi{1}(3), 'r^', 'MarkerFaceColor', [1 0 0], 'MarkerSize', 25)
      head1 = false;
    end

    % draw left ear position
    if ~isempty(info.template)
      if abs(info.template(2,1))-info.cfg.accuracy_green < abs(info.hpi{2}(1)) && abs(info.hpi{2}(1)) < abs(info.template(2,1))+info.cfg.accuracy_green ...
          && abs(info.template(2,2))-info.cfg.accuracy_green < abs(info.hpi{2}(2)) && abs(info.hpi{2}(2)) < abs(info.template(2,2))+info.cfg.accuracy_green ...
          && abs(info.template(2,3))-info.cfg.accuracy_green < abs(info.hpi{2}(3)) && abs(info.hpi{2}(3)) < abs(info.template(2,3))+info.cfg.accuracy_green
        plot3(info.hpi{2}(1),info.hpi{2}(2),info.hpi{2}(3), 'go', 'MarkerFaceColor', [.5 1 .5], 'MarkerSize',25)
        head2 = true;
      elseif abs(info.template(2,1))-info.cfg.accuracy_orange < abs(info.hpi{2}(1)) && abs(info.hpi{2}(1)) < abs(info.template(2,1))+info.cfg.accuracy_orange ...
          && abs(info.template(2,2))-info.cfg.accuracy_orange < abs(info.hpi{2}(2)) && abs(info.hpi{2}(2)) < abs(info.template(2,2))+info.cfg.accuracy_orange ...
          && abs(info.template(2,3))-info.cfg.accuracy_orange < abs(info.hpi{2}(3)) && abs(info.hpi{2}(3)) < abs(info.template(2,3))+info.cfg.accuracy_orange
        plot3(info.hpi{2}(1),info.hpi{2}(2),info.hpi{2}(3), 'yo', 'MarkerFaceColor', [1 .5 0], 'MarkerEdgeColor', [1 .5 0], 'MarkerSize',25)
        head2 = false;
      else % when not in correct position
        plot3(info.hpi{2}(1),info.hpi{2}(2), info.hpi{2}(3), 'ro', 'MarkerFaceColor', [1 0 0], 'MarkerSize', 25)
        head2 = false;
      end
    else
      plot3(info.hpi{2}(1),info.hpi{2}(2), info.hpi{2}(3), 'ro', 'MarkerFaceColor', [1 0 0], 'MarkerSize', 25)
      head2 = false;
    end

    % draw right ear position
    if ~isempty(info.template)
      if abs(info.template(3,1))-info.cfg.accuracy_green < abs(info.hpi{3}(1)) && abs(info.hpi{3}(1)) < abs(info.template(3,1))+info.cfg.accuracy_green  ...
          && abs(info.template(3,2))-info.cfg.accuracy_green  < abs(info.hpi{3}(2)) && abs(info.hpi{3}(2)) < abs(info.template(3,2))+info.cfg.accuracy_green  ...
          && abs(info.template(3,3))-info.cfg.accuracy_green  < abs(info.hpi{3}(3)) && abs(info.hpi{3}(3)) < abs(info.template(3,3))+info.cfg.accuracy_green
        plot3(info.hpi{3}(1),info.hpi{3}(2),info.hpi{3}(3), 'go', 'MarkerFaceColor', [.5 1 .5], 'MarkerSize',25)
        head3 = true;
      elseif abs(info.template(3,1))-info.cfg.accuracy_orange < abs(info.hpi{3}(1)) && abs(info.hpi{3}(1)) < abs(info.template(3,1))+info.cfg.accuracy_orange ...
          && abs(info.template(3,2))-info.cfg.accuracy_orange < abs(info.hpi{3}(2)) && abs(info.hpi{3}(2)) < abs(info.template(3,2))+info.cfg.accuracy_orange ...
          && abs(info.template(3,3))-info.cfg.accuracy_orange < abs(info.hpi{3}(3)) && abs(info.hpi{3}(3)) < abs(info.template(3,3))+info.cfg.accuracy_orange
        plot3(info.hpi{3}(1),info.hpi{3}(2),info.hpi{3}(3), 'yo', 'MarkerFaceColor', [1 .5 0], 'MarkerEdgeColor', [1 .5 0], 'MarkerSize',25)
        head3 = false;
      else % when not in correct position
        plot3(info.hpi{3}(1),info.hpi{3}(2), info.hpi{3}(3), 'ro', 'MarkerFaceColor', [1 0 0], 'MarkerSize', 25)
        head3 = false;
      end
    else
      plot3(info.hpi{3}(1),info.hpi{3}(2), info.hpi{3}(3), 'ro', 'MarkerFaceColor', [1 0 0], 'MarkerSize', 25)
      head3 = false;
    end
  elseif info.isneuromag
    % draw nasion position
    if ~isempty(info.template)
      if abs(info.template(1,1))-info.cfg.accuracy_green < abs(info.hpi{1}(1)) && abs(info.hpi{1}(1)) < abs(info.template(1,1))+info.cfg.accuracy_green ...
          && abs(info.template(1,2))-info.cfg.accuracy_green < abs(info.hpi{1}(2)) && abs(info.hpi{1}(2)) < abs(info.template(1,2))+info.cfg.accuracy_green ...
          && abs(info.template(1,3))-info.cfg.accuracy_green < abs(info.hpi{1}(3)) && abs(info.hpi{1}(3)) < abs(info.template(1,3))+info.cfg.accuracy_green
        plot3(info.hpi{1}(1),info.hpi{1}(2),info.hpi{1}(3), 'go', 'MarkerFaceColor', [.5 1 .5], 'MarkerSize',25)
        head1 = true;
      elseif abs(info.template(1,1))-info.cfg.accuracy_orange < abs(info.hpi{1}(1)) && abs(info.hpi{1}(1)) < abs(info.template(1,1))+info.cfg.accuracy_orange ...
          && abs(info.template(1,2))-info.cfg.accuracy_orange < abs(info.hpi{1}(2)) && abs(info.hpi{1}(2)) < abs(info.template(1,2))+info.cfg.accuracy_orange ...
          && abs(info.template(1,3))-info.cfg.accuracy_orange < abs(info.hpi{1}(3)) && abs(info.hpi{1}(3)) < abs(info.template(1,3))+info.cfg.accuracy_orange
        plot3(info.hpi{1}(1),info.hpi{1}(2),info.hpi{1}(3), 'yo', 'MarkerFaceColor', [1 .5 0], 'MarkerEdgeColor', [1 .5 0], 'MarkerSize',25)
        head1 = false;
      else % when not in correct position
        plot3(info.hpi{1}(1),info.hpi{1}(2), info.hpi{1}(3), 'ro', 'MarkerFaceColor', [1 0 0], 'MarkerSize', 25)
        head1 = false;
      end
    else
      plot3(info.hpi{1}(1),info.hpi{1}(2), info.hpi{1}(3), 'ro', 'MarkerFaceColor', [1 0 0], 'MarkerSize', 25)
      head1 = false;
    end

    % draw left ear position
    if ~isempty(info.template)
      if abs(info.template(2,1))-info.cfg.accuracy_green < abs(info.hpi{2}(1)) && abs(info.hpi{2}(1)) < abs(info.template(2,1))+info.cfg.accuracy_green ...
          && abs(info.template(2,2))-info.cfg.accuracy_green < abs(info.hpi{2}(2)) && abs(info.hpi{2}(2)) < abs(info.template(2,2))+info.cfg.accuracy_green ...
          && abs(info.template(2,3))-info.cfg.accuracy_green < abs(info.hpi{2}(3)) && abs(info.hpi{2}(3)) < abs(info.template(2,3))+info.cfg.accuracy_green
        plot3(info.hpi{2}(1),info.hpi{2}(2),info.hpi{2}(3), 'g^', 'MarkerFaceColor', [.5 1 .5], 'MarkerSize', 25)
        head2 = true;
      elseif abs(info.template(2,1))-info.cfg.accuracy_orange < abs(info.hpi{2}(1)) && abs(info.hpi{2}(1)) < abs(info.template(2,1))+info.cfg.accuracy_orange ...
          && abs(info.template(2,2))-info.cfg.accuracy_orange < abs(info.hpi{2}(2)) && abs(info.hpi{2}(2)) < abs(info.template(2,2))+info.cfg.accuracy_orange ...
          && abs(info.template(2,3))-info.cfg.accuracy_orange < abs(info.hpi{2}(3)) && abs(info.hpi{2}(3)) < abs(info.template(2,3))+info.cfg.accuracy_orange
        plot3(info.hpi{2}(1),info.hpi{2}(2),info.hpi{2}(3), 'y^', 'MarkerFaceColor', [1 .5 0], 'MarkerEdgeColor', [1 .5 0], 'MarkerSize', 25)
        head2 = false;
      else % when not in correct position
        plot3(info.hpi{2}(1),info.hpi{2}(2), info.hpi{2}(3), 'r^', 'MarkerFaceColor', [1 0 0], 'MarkerSize', 25)
        head2 = false;
      end
    else
      plot3(info.hpi{2}(1),info.hpi{2}(2), info.hpi{2}(3), 'r^', 'MarkerFaceColor', [1 0 0], 'MarkerSize', 25)
      head2 = false;
    end

    % draw right ear position
    if ~isempty(info.template)
      if abs(info.template(3,1))-info.cfg.accuracy_green < abs(info.hpi{3}(1)) && abs(info.hpi{3}(1)) < abs(info.template(3,1))+info.cfg.accuracy_green  ...
          && abs(info.template(3,2))-info.cfg.accuracy_green  < abs(info.hpi{3}(2)) && abs(info.hpi{3}(2)) < abs(info.template(3,2))+info.cfg.accuracy_green  ...
          && abs(info.template(3,3))-info.cfg.accuracy_green  < abs(info.hpi{3}(3)) && abs(info.hpi{3}(3)) < abs(info.template(3,3))+info.cfg.accuracy_green
        plot3(info.hpi{3}(1),info.hpi{3}(2),info.hpi{3}(3), 'go', 'MarkerFaceColor', [.5 1 .5], 'MarkerSize', 25)
        head3 = true;
      elseif abs(info.template(3,1))-info.cfg.accuracy_orange < abs(info.hpi{3}(1)) && abs(info.hpi{3}(1)) < abs(info.template(3,1))+info.cfg.accuracy_orange ...
          && abs(info.template(3,2))-info.cfg.accuracy_orange < abs(info.hpi{3}(2)) && abs(info.hpi{3}(2)) < abs(info.template(3,2))+info.cfg.accuracy_orange ...
          && abs(info.template(3,3))-info.cfg.accuracy_orange < abs(info.hpi{3}(3)) && abs(info.hpi{3}(3)) < abs(info.template(3,3))+info.cfg.accuracy_orange
        plot3(info.hpi{3}(1),info.hpi{3}(2),info.hpi{3}(3), 'yo', 'MarkerFaceColor', [1 .5 0], 'MarkerEdgeColor', [1 .5 0], 'MarkerSize', 25)
        head3 = false;
      else % when not in correct position
        plot3(info.hpi{3}(1),info.hpi{3}(2), info.hpi{3}(3), 'ro', 'MarkerFaceColor', [1 0 0], 'MarkerSize', 25)
        head3 = false;
      end
    else
      plot3(info.hpi{3}(1),info.hpi{3}(2), info.hpi{3}(3), 'ro', 'MarkerFaceColor', [1 0 0], 'MarkerSize', 25)
      head3 = false;
    end
  end
end

% plot the template fiducial positions
if ~isempty(info.template)
  if info.isctf
    plot3(info.template(1,1), info.template(1,2), info.template(1,3), 'k^', 'MarkerSize', 27, 'LineWidth', 2); % chan X pos
    plot3(info.template(2,1), info.template(2,2), info.template(2,3), 'ko', 'MarkerSize', 27, 'LineWidth', 2);
    plot3(info.template(3,1), info.template(3,2), info.template(3,3), 'ko', 'MarkerSize', 27, 'LineWidth', 2);

    text(-8,8, info.template(2,3), 'Left', 'FontSize', 15);
    text(6,-6, info.template(3,3), 'Right', 'FontSize', 15);
  elseif info.isneuromag
    plot3(info.template(1,1), info.template(1,2), info.template(1,3), 'ko', 'MarkerSize', 27, 'LineWidth', 2); % chan X pos
    plot3(info.template(2,1), info.template(2,2), info.template(2,3), 'k^', 'MarkerSize', 27, 'LineWidth', 2);
    plot3(info.template(3,1), info.template(3,2), info.template(3,3), 'ko', 'MarkerSize', 27, 'LineWidth', 2);
  end
end

% plot sphere model
if get(info.hSphereCheckBox, 'Value')
  cc = circumcenter(info.hpi);
  x_radius = sqrt((info.hpi{2}(1) - cc(1))^2 + (info.hpi{2}(2) - cc(2))^2);
  y_radius = sqrt((info.hpi{3}(1) - cc(1))^2 + (info.hpi{3}(2) - cc(2))^2);
  [xe, ye, ze] = ellipsoid(cc(1),cc(2),cc(3),x_radius,y_radius,11);
  hh = surfl(xe, ye, ze);
  shading interp
  if get(info.hCoilCheckBox, 'Value') % this only works if 'coils' are updated
    if head1 == true && head2 == true && head3 == true
      colormap cool
    else
      colormap hot
    end
  end
  alpha(.15)
end

% plot realistic head mdoel
if get(info.hRealistic, 'Value') && ~isempty(info.cfg.headshape)
  ft_plot_mesh(ft_transform_geometry(M, info.cfg.headshape))
end

% plot sensors
if get(info.hSensorCheckBox, 'Value') && ~isempty(info.sens)
  % plot the sensors
  ft_plot_sens(info.hdr.grad, 'style', 'k.');
end

% plot the HPI coil positions
for j = 1:numel(info.hpi)
  plot3(info.hpi{j}(1), info.hpi{j}(2), info.hpi{j}(3), 'ko', 'LineWidth', 1, 'MarkerSize', 5)
end

% plot the dewar
if get(info.hDewarCheckBox, 'Value') && ~isempty(info.cfg.dewar)
  ft_plot_mesh(info.cfg.dewar, 'facecolor', [0.5 0.5 0.5], 'facealpha', 0.6, 'edgecolor', 'none');
end

% plot Polhemus
if get(info.hPolhemusCheckBox, 'Value')
  if ~isempty(info.cfg.polhemus)
    ft_plot_mesh(ft_transform_geometry(M,info.cfg.polhemus), 'vertexmarker', '.')
  end
end

% plot Axis
if get(info.hAxisCheckBox, 'Value')
  if info.isctf
    ft_plot_axes([], 'coordsys', 'ctf', 'unit', 'cm');
  elseif info.isneuromag
    ft_plot_axes([], 'coordsys', 'neuromag', 'unit', 'cm');
  end
end

grid on
axis on
xlabel('x (cm)');
ylabel('y (cm)');
zlabel('z (cm)');

% place ticks at 2cm distance
set(gca, 'xtick', info.cfg.xlim(1):2:info.cfg.xlim(2))
set(gca, 'ytick', info.cfg.ylim(1):2:info.cfg.ylim(2))
set(gca, 'ztick', info.cfg.zlim(1):2:info.cfg.zlim(2))

% fix axis to avoid rescaling
axis([info.cfg.xlim info.cfg.ylim info.cfg.zlim])
axis square

% put the info back
guidata(handle, info);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION which handles hot keys in the current plot
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function key_sub(handle, eventdata)

% get the info
info = guidata(handle);

switch eventdata.Key
  case 'u'
    % update the template positions
    fprintf('updating template coordinates \n')
    for j = 1:numel(info.hpi)
      info.template(j,:) = info.hpi{j}(:); % chan X pos
    end

    % write template position to text file for later re-positioning
    template_time = [date datestr(now, '-HH-MM-SS')];
    fprintf('writing to %s.txt \n', template_time);
    dlmwrite([template_time '.txt'], info.template, ' ');

  case 'q'
    % stop the application
    fprintf('stopping the application \n')
    info.continue = false;
  case 'c'
    % display the sensors/dewar
    if get(info.hCoilCheckBox, 'Value') == 0
      fprintf('displaying coils \n')
      set(info.hCoilCheckBox, 'Value', 1); % toggle on
    elseif get(info.hCoilCheckBox, 'Value') == 1
      set(info.hCoilCheckBox, 'Value', 0); % toggle off
    end
  case 'h'
    % display the sensors/dewar
    if get(info.hHeadCheckBox, 'Value') == 0
      fprintf('displaying head \n')
      set(info.hHeadCheckBox, 'Value', 1); % toggle on
    elseif get(info.hHeadCheckBox, 'Value') == 1
      set(info.hHeadCheckBox, 'Value', 0); % toggle off
    end
  case 's'
    % display the sensors/dewar
    if get(info.hSensorCheckBox, 'Value') == 0
      fprintf('displaying sensors/dewar \n')
      set(info.hSensorCheckBox, 'Value', 1); % toggle on
    elseif get(info.hSensorCheckBox, 'Value') == 1
      set(info.hSensorCheckBox, 'Value', 0); % toggle off
    end
  otherwise
    fprintf('no command executed \n')
end

% put the info back
guidata(handle, info);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTIONs which handle button presses
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function update_ButtonDownFcn(handle, eventdata)

% get the info
info = guidata(handle);

% update the template positions
fprintf('updating template coordinates \n')
for j = 1:numel(info.hpi)
  info.template(j,:) = info.hpi{j}(:); % chan X pos
end

% write template position to text file for later re-positioning
template_time = [date datestr(now, '-HH-MM-SS')];
fprintf('writing to %s.txt \n', template_time);
dlmwrite([template_time '.txt'], info.template, ' ');

% put the info back
guidata(handle, info);

function quit_ButtonDownFcn(handle, eventdata)

% get the info
info = guidata(handle);

% stop the application
fprintf('stopping the application \n')
info.continue = false;

% put the info back
guidata(handle, info);

function coil_CheckBox(hObject, eventdata)
% toggle coils display

function sphere_CheckBox(hObject, eventdata)
% toggle head display

function sensor_CheckBox(hObject, eventdata)
% toggle sensors display

function head_CheckBox(hObject, eventdata)
% toggle head display

function Dewar_CheckBox(hObject, eventdata)
% toggle dewar display

function axis_CheckBox(hObject, eventdata)
% toggle axis display

function Polhemus_CheckBox(hObject, eventdata)
% toggle axis display

function mirror_CheckBox(handle, eventdata)
% toggle mirror display

function blocksize_Menu(handle, eventdata)

% get the info
info = guidata(handle);

val = get(info.hBlocksizeMenu, 'Value');
switch val
  case 1
    info.blocksize = round(0.1 * info.hdr.Fs); % 0.1 s
  case 2
    info.blocksize = round(0.2 * info.hdr.Fs);
  case 3
    info.blocksize = round(0.5 * info.hdr.Fs);
  case 4
    info.blocksize = round(1 * info.hdr.Fs);
  case 5
    info.blocksize = round(1.5 * info.hdr.Fs);
  case 6
    info.blocksize = round(2 * info.hdr.Fs);
  case 7
    info.blocksize = round(5 * info.hdr.Fs);
  case 8
    info.blocksize = round(10 * info.hdr.Fs);
  case 9
    info.blocksize = round(30 * info.hdr.Fs);
end
fprintf('changing blocksize to %d samples\n', info.blocksize);

% put the info back
guidata(handle, info);


function dosefilenames = find_pinnacle_dose_filenames(dosedim,planPath)
%
%	dosefilenames = find_pinnacle_dose_filenames(dosedim)
%
%
% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.
%
% This file is part of The Computational Environment for Radiotherapy Research (CERR).
%
% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.
%
% CERR has been financially supported by the US National Institutes of Health under multiple grants.
%
% CERR is distributed under the terms of the Lesser GNU Public License.
%
%     This version of CERR is free software: you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation, either version 3 of the License, or
%     (at your option) any later version.
%
% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
% See the GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with CERR.  If not, see <http://www.gnu.org/licenses/>.

%APA
% planPath = 'C:\Projects\PinnacleReader\PinnacleWholePatientPlanExample\Plan_2\plan.Trial.binary.*';
files = dir(planPath);
%files = dir('plan.Trial.binary.*');
N = length(files);

dosefilenames = cell(0);

for k = 1:N
	if files(k).bytes == prod(dosedim)*4
		if isempty(dosefilenames)
			dosefilenames{1} = files(k).name;
		else
			dosefilenames{end+1,1} = files(k).name;
		end
	end
end

% The number of binary dose files should be equal to 2 * number of beams


classdef World < handle

% Copyright (C) 2013, Georgia Tech Research Corporation
% see the LICENSE file included with this software

    properties
        robots
        obstacles
        parent
        apps
        root_path
    end

    methods
        function obj = World(parent)
            obj.parent = parent;
            obj.robots = simiam.containers.ArrayList(10);
            obj.obstacles = mcodekit.list.dl_list();
            obj.apps = simiam.containers.ArrayList(10);
            obj.root_path = '';
        end

        function build_from_file(obj, root, file, origin)

            % Read in XML file
            blueprint = xmlread(file);
            obj.root_path = root;

            % Parse XML file for robot configurations
            app_list = blueprint.getElementsByTagName('app').item(0);
            app = char(app_list.getAttribute('type'));

            r = str2func(strcat('simiam.app.', app));
            obj.apps.appendElement(r(root));

            if(strcmp(origin, 'launcher') || strcmp(origin, 'testing') || strcmp(origin, 'hardware'))

                robot_list = blueprint.getElementsByTagName('robot');

                for k = 0:(robot_list.getLength-1)
                   robot = robot_list.item(k);

                   type = char(robot.getAttribute('type'));

                   s = robot.getElementsByTagName('supervisor').item(0);
                   spv = char(s.getAttribute('type'));

                   pose = robot.getElementsByTagName('pose').item(0);
                   x = str2double(pose.getAttribute('x'));
                   y = str2double(pose.getAttribute('y'));
                   theta = str2double(pose.getAttribute('theta'));

                   r = obj.add_robot(type, spv, x, y, theta);

                   driver = robot.getElementsByTagName('driver').item(0);
                   if(~isempty(driver) && strcmp(origin, 'hardware'))
                       hostname = char(driver.getAttribute('ip'));
                       port = str2double(driver.getAttribute('port'));
                       r.add_hardware_link(hostname,port);
                       r.open_hardware_link();
                   end
                end
            end

            % Parse XML file for obstacle configurations
            obstacle_list = blueprint.getElementsByTagName('obstacle');

            for i = 0:(obstacle_list.getLength-1)
               obstacle = obstacle_list.item(i);

               pose = obstacle.getElementsByTagName('pose').item(0);
               x = str2double(pose.getAttribute('x'));
               y = str2double(pose.getAttribute('y'));
               theta = str2double(pose.getAttribute('theta'));

               geo = obstacle.getElementsByTagName('geometry').item(0);
               point_list = geo.getElementsByTagName('point');

               obstacle_geometry = zeros(point_list.getLength, 2);
               for j=0:(point_list.getLength-1)
                  point = point_list.item(j);
                  obstacle_geometry(j+1,1) = str2double(point.getAttribute('x'));
                  obstacle_geometry(j+1,2) = str2double(point.getAttribute('y'));
               end

               obj.add_obstacle(x, y, theta, obstacle_geometry);
            end
        end

        function aRobot = add_robot(obj, type, spv, x, y, theta)
            pose = simiam.ui.Pose2D(x, y, theta);

            r = str2func(strcat('simiam.robot.', type));
            robot = r(obj.parent, pose);

            r = str2func(strcat('simiam.controller.', spv));
            supervisor = r();

            supervisor.attach_robot(robot, pose);

            %            parameter_file = fullfile(obj.root_path, 'parameters.xml');
            %            [file, path, extension] = uigetfile(parameter_file, 'Pick a XML file with the parameters for the PID regulator.');
            %
            %            parameter_file = fullfile(path, file);
            %            supervisor.configure_from_file(parameter_file);

            s = struct('robot', robot, 'supervisor', supervisor, 'pose', pose);
            %            obj.robots.append_key(s);

            obj.robots.appendElement(s);
            anApp = obj.apps.elementAt(1);
            anApp.supervisors.appendElement(supervisor);

            aRobot = s.robot;
        end

        function add_obstacle(obj, x, y, theta, geometry)
           pose = simiam.ui.Pose2D(x, y, theta);
           obj.obstacles.append_key(struct('obstacle', simiam.simulator.Obstacle(obj.parent, pose, geometry), 'pose', pose));
        end

    end

end


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

% An example script, it is used to show how to use the
% non-blocking moiton functions of the KST

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

% Note you have 60 seconds to connect to server after starting the
% application (MatlabToolboxServer) from the smart pad on the robot controller.

% 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')

%% Non blocking motion in Cartesian space
for i=1:3
% Go to some initial position
relVel=0.35; % over ride relative joint velocities
jPos={0, -pi / 180 * 10, 0, -pi / 180 * 100, pi / 180 * 90,pi / 180 * 90, 0};   % initial cofiguration
iiwa.movePTPJointSpace(jPos, relVel);

% Get current position of EEF
[ Pos ] = iiwa.getEEFPos(  );
distPos=Pos;
distPos{3}=distPos{3}-100;

% Move non-blocking
vel=25; %25 mm/sec
iiwa.nonBlocking_movePTPLineEEF(distPos, vel);
flag=true;
while ~iiwa.nonBlocking_isGoalReached()
    disp('Cartesian non-blocking motion in progress');
    pause(0.2);
    if(flag)
        iiwa.setBlueOn(  );
        flag=false;
    else
        iiwa.setBlueOff(  );
        flag=true;
    end
end
iiwa.setBlueOff(  );
end
%% Non blocking motion in Cartesian space
for i=1:3
% Go to some initial position
relVel=0.35; % over ride relative joint velocities
jPos={0, -pi / 180 * 10, 0, -pi / 180 * 100, pi / 180 * 90,pi / 180 * 90, 0};   % initial cofiguration
iiwa.movePTPJointSpace(jPos, relVel);

% Distination angular position
distPos=jPos;
distPos{3}=distPos{3}-pi/3;

% Move non-blocking
relVel=0.25;
iiwa.nonBlocking_movePTPJointSpace(distPos, relVel);
flag=true;
while ~iiwa.nonBlocking_isGoalReached()
    disp('Joints non-blocking motion in progress');
    pause(0.2);
    if(flag)
        iiwa.setBlueOn(  );
        flag=false;
    else
        iiwa.setBlueOff(  );
        flag=true;
    end
end
iiwa.setBlueOff(  );
end
%% Turn off server
disp('Distination reached');
disp('Turning off server');
iiwa.net_turnOffServer(  );


function [hdr] = read_biosig_header(filename)

% READ_BIOSIG_HEADER reads header from EEG file using the BIOSIG
% toolbox and returns it in the FCDC framework standard format
%
% Use as
%  [hdr] = read_biosig_header(filename)
%
% The following data formats are supported: EDF, BKR, CNT, BDF, GDF,
% see for full documentation http://biosig.sourceforge.net/
%
% See also READ_BIOSIG_DATA

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

% open the file, read the header and close it again
biosig = sopen(filename,'r');
sclose(biosig);

% the BIOSIG header is defined in full detail below
% the FCDC header should at least contain the following fields
%   hdr.Fs           sampling frequency
%   hdr.nChans       number of channels
%   hdr.nSamples     number of samples per trial
%   hdr.nSamplesPre  number of pre-trigger samples in each trial
%   hdr.nTrials      number of trials
%   hdr.label        cell-array with labels of each channel

if length(biosig.SampleRate)>1 & any(diff(biosig.SampleRate))
  error('channels with different sampling rates are not supported');
else
  hdr.Fs          = biosig.SampleRate(1);
end

if length(biosig.SPR)>1 & any(diff(biosig.SPR))
  error('channels with different number of samples are not supported');
else
  hdr.nSamples  = biosig.SPR(1);
end

hdr.nChans      = biosig.NS;
hdr.nTrials     = biosig.NRec;
hdr.nSamplesPre = 0;      % this one is not in the biosig header
hdr.label       = {};     % start with empty labels and fill them below

if isfield(biosig, 'Label')
  hdr.label = biosig.Label;
end

if length(hdr.label)~=hdr.nChans
  % make default channel labels
  hdr.label = {};
  for i=1:hdr.nChans
    hdr.label{i} = sprintf('%d', i);
  end
end

% I prefer to have them as column vector
hdr.label = hdr.label(:);

% also remember the biosig header details
hdr.orig = biosig;
return;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% the BIOSIG header always contains these elements
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% HDR.TYPE                string          type of data format
% HDR.VERSION             string          (depends on data format)
% HDR.T0                  float[1..6]     [yyyy mm dd hh MM ss.cc] see HELP CLOCK
% HDR.NS                  integer         number of channels
% HDR.SampleRate          integer         sampling frequency in [Hz]
% HDR.NRec                integer         number of records or blocks; 1 for continous data
% HDR.SPR                 integer         samples per record
% HDR.Dur                 float           Duration (in [s]) of minimal block length
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% the BIOSIG header optinally contains the following elements
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% HDR.Filter.LowPass      float           [Hz]
% HDR.Filter.HighPass     float           [Hz]
% HDR.Filter.Notch        int8            0=Off, 1=ON
% HDR.PreFilt             string          filter setting
% HDR.Label               char-array      z.B. '+C3a - C3p  '
% HDR.PhysDim             string          physical dimension e.g. 'uV'
% HDR.PhysMax             float           physical maximum
% HDR.DigMax              integer         digital maximum
% HDR.PhysMin             float           physical minimum
% HDR.DigMin              integer         digital minimum
% HDR.FLAG.TRIGGERED      int             0=no, 1=yes
% HDR.FLAG.REFERENCE      string          COM, CAR: common average reference; LOC,LAR local average ref; LAP Laplacian derivation, WGT weighted average
% HDR.Classlabel          int             0: left, 1: right, etc.
% HDR.ID.Doctor                           Identification of doctor
% HDR.ID.Hospital                         Identification of Hospital
% HDR.Patient.Name                        Name of Patient
% HDR.Patient.Age                         Age of Patient
% HDR.Patient.Sex                         Patient Gender
% HDR.Patient.Handedness                  Patient Handedness
% HDR.Patient.Medication                  Medication
% HDR.Patient.Classification              Classification of Patient


% Author : FUAT COGUN
% Date   : 16.07.2009
%
%
% Gets the dimensions of the screen.
%
%
% Inputs  :
% ======
%
% Outputs : -Width of the screen                                (Integer)
% =======   -Height of the screen                               (Integer)

function [screenWidth screenHeight] = getScreenSize()

    screenSize = get(0,'ScreenSize');
    screenWidth = screenSize(3);
    screenHeight = screenSize(4);


%COPYFIG Create a copy of a figure, without changing the figure
%
% Examples:
%   fh_new = copyfig(fh_old)
%
% This function will create a copy of a figure, but not change the figure,
% as copyobj sometimes does, e.g. by changing legends.
%
% IN:
%    fh_old - The handle of the figure to be copied. Default: gcf.
%
% OUT:
%    fh_new - The handle of the created figure.

% Copyright (C) Oliver Woodford 2012

% 26/02/15: If temp dir is not writable, use the dest folder for temp
%           destination files (Javier Paredes)

function fh = copyfig(fh)
% Set the default
if nargin == 0
    fh = gcf;
end
% Is there a legend?
if isempty(findall(fh, 'Type', 'axes', 'Tag', 'legend'))
    % Safe to copy using copyobj
    fh = copyobj(fh, 0);
else
    % copyobj will change the figure, so save and then load it instead
    tmp_nam = [tempname '.fig'];
    try
        % Ensure that the temp dir is writable (Javier Paredes 26/2/15)
        fid = fopen(tmp_nam,'w');
        fwrite(fid,1);
        fclose(fid);
        delete(tmp_nam);  % cleanup
    catch
        % Temp dir is not writable, so use the current folder
        [dummy,fname,fext] = fileparts(tmp_nam); %#ok<ASGLU>
        fpath = pwd;
        tmp_nam = fullfile(fpath,[fname fext]);
    end
    hgsave(fh, tmp_nam);
    fh = hgload(tmp_nam);
    delete(tmp_nam);
end
end


function varargout=lpcifilt(varargin)
%
% For calling details please see v_lpcifilt.m
%
% This dummy routine is included for backward compatibility only
% and will be removed in a future release of voicebox. Please use
% v_lpcifilt.m in future and/or update with v_voicebox_update.m
%
%      Copyright (C) Mike Brookes 2018
%      Version: $Id: lpcifilt.m 10863 2018-09-21 15:39:23Z dmb $
%
if nargout
    varargout=cell(1,nargout);
    [varargout{:}]=v_lpcifilt(varargin{:});
else
    v_lpcifilt(varargin{:});
end


function [tests,pass,perf]=test_sumann(varargin)

inputs={'verbose'};
verbose=0;
for n=1:nargin
    if(~isempty(varargin{n}))
        eval([inputs{n} '=varargin{n};']);
    end
end

%Test the examples
test_string={'report=sumann(''mitdb/100'',''atr'');'};
clean_up={};
[tests,pass,perf]=test_wrapper(test_string,clean_up,verbose);


any(cellfun(@exist,{'arraydeal', 'chopdeal', 'cummax'})==3)


%   CLASS Reflectometry
% =========================================================================
%
% DESCRIPTION
%   Class to manage reflectometry functions
%
% EXAMPLE
%   rfx = Reflectometry();
%
% CONSTRUCTOR SYNTAX
%   rfx = Reflectometry();
%
% FOR A LIST OF CONSTANTs and METHODS use doc Reflectometry
%
% COMMENTS
% The class stores arrays of time, not just a single element,
% it has been designed this way because MATLAB works best on arrays
%

%--- * --. --- --. .--. ... * ---------------------------------------------
%               ___ ___ ___
%     __ _ ___ / __| _ | __|
%    / _` / _ \ (_ |  _|__ \
%    \__, \___/\___|_| |___/
%    |___/                    v 1.0RC1
%
%--------------------------------------------------------------------------
%  Copyright (C) 2021 Geomatics Research & Development srl (GReD)
%  Written by:        Andrea Gatti
%  Contributors:      Andrea Gatti, ...
%  A list of all the historical goGPS contributors is in CREDITS.nfo
%--------------------------------------------------------------------------
%
%   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/>.
%
%--------------------------------------------------------------------------
% 01100111 01101111 01000111 01010000 01010011
%--------------------------------------------------------------------------

classdef Reflectometry < handle

    properties (Constant, GetAccess = public)
    end

    properties (SetAccess = public, GetAccess = public) % set permission have been changed from private to public (Giulio)
    end

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

    methods
        function this = Reflectometry()
            % Constructor
            %
            % SYNTAX
            %   t = Coordinates();
        end
    end

    % =========================================================================
    %    TESTS
    % =========================================================================

    methods (Static, Access = 'public')
        function getAvgNyquist(rec, el_lim)
            % Show fresnel zones for a receiver
            %
            % INPUT
            %   rec     receiver
            %   el_lim  elevation limits [deg] (e.g. [5 15])
            %
            % SYNTAX
            %   Reflectometry.getAvgNyquist(rec, getAvgNyquist)
            log = Core.getLogger();
            cc = Core.getConstellationCollector;

            diff_el_crit = abs(diff(el_lim)) - 2;
            for r = 1 : numel(rec)
                work = rec(r).work;
                log.addMessage('Displaying fresnel zones for the receiver rec %s', rec(r).getMarkerName);
                [snr, id_snr] =  = work.getSNR();
                id_snr = find(id_snr);
                [az, el] = work.getAzEl(work.go_id(id_snr));
                azi = 0;
                [lat, lon, h_ellips] = work.getMedianPosGeodetic();
                freq_list = freq_list = unique(work.obs_code(id_snr,2));
                for f = 1 : numel(freq_list)
                    id_f = find(work.obs_code(id_snr,2) == freq_list(f));
                    for s = 1 : numel(id_f)
                        sat_name = cc.getSatName(work.go_id(id_snr(id_f(s))));
                        % find data within 20 degrees of azimuth and using elevation angle limits
                        id_ok = el(:,id_f(s)) >= el_lim(1) & el(:,id_f(s)) >= el_lim(2);
                        % sin of elevation
                        sin_el = sind(el(id_ok, id_f(s)));
                        % elevation limits
                        diff_el = max(el(id_ok, id_f(s))) - min(el(id_ok, id_f(s)));
                        diff_t = 2 * (max(sin_el) - min(sin_el)) / work.wl(id_snr(id_f(s)));
                        if diff_el > diff_el_crit
                            fprintf(1,'%s Azim. %6.2f  Nyquist %7.2f (m) %s ElevAngles: %3.0f %3.0f \n', ...
              sat_name, azi, avg_nyq, riseORset(riseset), minElevAngle, maxElevAngle);
                            avg_nyq = sum(id_ok) / (2 * diff_t);
                        end
                    end
                end
            end
        end
    end

end


function dict_dist = find_dups

%% generate splits
[image_ids, class_ids, super_class_ids, path_list] = ...
    textread('/cvgl/group/Ebay_Dataset/Ebay_info.txt', '%d %d %d %s', ...
    'headerlines', 1);

% 1. Do one scan and find out how many classes each super class has
dict_dist = containers.Map;

for i = 1:length(image_ids)
    if mod(i,1000)==0
        fprintf('%d/%d\n', i, length(image_ids));
    end
    this_filename = path_list{i};
    this_image_idx  = image_ids(i);
    this_class_idx = class_ids(i);
    this_super_class_idx = super_class_ids(i);

    C = strsplit(this_filename, '/');
    this_name = C{2};

    if isKey(dict_dist, this_name)
        fprintf('[dup] %s %s\n', this_filename, dict_dist(this_name));
    else
        dict_dist(this_name) = this_filename;
    end
end

% train_images = {};
% val_images = {};
% dict = containers.Map('keytype', 'double', 'valuetype', 'any');
%
% for i = 1:length(image_ids)
%     this_filename = path_list{i};
%     this_image_idx  = image_ids{i};
%     this_class_idx = class_ids{i};
%     this_super_class_idx = super_class_ids{i};
%
%     fprintf('%d/%d, classid=%d, filename= %s\n', i, length(image_ids), ...
%         this_class_idx, this_filename);
%
%
%


function aboxes_out = post_process_candidate_detections_all_imgs(...
    aboxes_in, varargin)
% post_process_candidate_detections_all_imgs performs the post-processing
% step of non-maximum-suppression and optionally of box voting on the
% candidate bounding box detections of a set of images.
%
% INPUTS:
% 1) aboxes_in: contains the candidate bounding box detections of each image.
% It can be of two forms:
%   a) (the flag is_per_class must being set to false) a NI x 1 cell array
%   where NI is the number of images. The aboxes_in{i} element contains
%   the candidate bounding box detection of the i-th image in the form of a
%   NB_i x (4 + C) array where C is the number of categories and NB_i
%   is the number of candidate detection boxes of the i-th image. The first
%   4 columns of this array contain the bounding box coordinates in the
%   form of [x0,y0,x1,y1] (where the (x0,y0) and (x1,y1) are the top-left
%   and bottom-right corners) and the rest C columns contain the confidence
%   score of the bounding boxes for each of the C categories.
%   b) (the flag is_per_class must being set to true) a C x 1 cell array
%   where C is the number of categories. The aboxes_in{j} element in this case
%   is NI x 1 cell array, where NI is the number of images, with the candidate
%   bounding box detections of the j-th category for each image. The
%   element aboxes_in{j}{i} is a NB_{i,j} x 5 array, where NB_{i,j} is the
%   number candidate bounding box detections of the i-th image for the j-th
%   category. The first 4 columns of this array are the bounding box
%   coordinates in the form of [x0,y0,x1,y1] (where the (x0,y0) and (x1,y1)
%   are the top-left and bottom-right corners) and the 5-th column contains
%   the confidence score of each bounding box with respect to the j-th category.
% 2) The rest input arguments are given in the form of Name,Value pair
% arguments and are:
% 'threshold': is a C x 1 array, where C is the number of categories.
% It must contains the threshold per category that will be used for
% removing candidate boxes with low confidence prior to applying the
% non-max-suppression step.
% 'nms_iou_thrs': scalar value with the IoU threshold that will be used
% during the non-max-suppression step.
% 'is_per_class': boolean value that if set to false, then the 1.a) form
% of the aboxes_in input parameter will be expected; otherwise, if set to
% true then the 1.b) form of the aboxes_in input parameter will be expected
% 'max_per_image': scalar value with the maximum number of detection per
% image and per category. Default value: 200.
% 'do_bbox_voting': boolean value that if is set to True then the box voting
% step is applied. Default value: false
% 'box_ave_iou_thresh': scalar value with the minimum IoU threshold that
% is used in order to define the neighbors of bounding box during the box
% voting step. Default value: 0.5
% 'add_val': scalar value that is added to the confidence score of bounding
% boxes in order to compute the box weight during the box voting step.
% Default value: 1.5
% 'use_not_static_thr': boolean value that if set to true, then the threshold
% (param threshold) that is applied on the candidate bounding box
% detections will be modified (decreased from its input value) such that
% the average number of detections per image and per category to be
% ave_per_image. Default value: true
% 'ave_per_image': scalar value with the desired average number of
% detections per image and per category. Used only when the use_not_static_thr
% input parameter is set to true. default value: 5
%
% OUTPUT:
% 1) aboxes_out: is a C x 1 array where C is the number of
% categories. The aboxes_out{j} element is a NI x 1 cell array, where NI is
% the number of images, with the bounding box detections of the j-th
% category for each image. The element aboxes_out{j}{i} is a ND_{i,j} x 5 array,
% where ND_{i,j} is the number bounding box detections for the i-th image
% and the j-th category. The first 4 columns of this array contain the
% bounding box coordinates in the form of [x0,y0,x1,y1] (where the (x0,y0)
% and (x1,y1) are the top-left and bottom-right corners) and the 5-th
% column contains the confidence score of each bounding box with respect to
% the j-th category.
%
% This file is part of the code that implements the following ICCV2015 accepted paper:
% title: "Object detection via a multi-region & semantic segmentation-aware CNN model"
% authors: Spyros Gidaris, Nikos Komodakis
% institution: Universite Paris Est, Ecole des Ponts ParisTech
% Technical report: http://arxiv.org/abs/1505.01749
% code: https://github.com/gidariss/mrcnn-object-detection
%
% Part of the code in this file comes from the R-CNN code:
% https://github.com/rbgirshick/rcnn
%
% AUTORIGHTS
% --------------------------------------------------------
% Copyright (c) 2015 Spyros Gidaris
%
% "Object detection via a multi-region & semantic segmentation-aware CNN model"
% Technical report: http://arxiv.org/abs/1505.01749
% Licensed under The MIT License [see LICENSE for details]
% ---------------------------------------------------------
% Copyright (c) 2014, Ross Girshick
%
% This file is part of the R-CNN code and is available
% under the terms of the Simplified BSD License provided in
% LICENSE. Please retain this notice and LICENSE if you use
% this file (or any portion of it) in your project.
% ---------------------------------------------------------

ip = inputParser;
ip.addParamValue('is_per_class',      false, @islogical);
ip.addParamValue('do_bbox_voting',    false, @islogical);
ip.addParamValue('box_ave_iou_thresh',  0.5, @isnumeric);
ip.addParamValue('use_not_static_thr', true, @islogical);
ip.addParamValue('ave_per_image',         5, @isnumeric);
ip.addParamValue('max_per_image',       200, @isnumeric);
ip.addParamValue('add_val',             1.5, @isnumeric);
ip.addParamValue('use_gpu',           false, @islogical);
ip.addParamValue('nms_iou_thrs',        0.3, @isnumeric);
ip.addParamValue('threshold',            -4, @isnumeric);

ip.parse(varargin{:});
opts = ip.Results;

nms_iou_thrs       = opts.nms_iou_thrs;
threshold         = opts.threshold;
is_per_class       = opts.is_per_class;
do_bbox_voting     = opts.do_bbox_voting;
box_ave_iou_thresh = opts.box_ave_iou_thresh;
use_not_static_thr = opts.use_not_static_thr;
max_per_image      = opts.max_per_image;
ave_per_image      = opts.ave_per_image;
add_val            = opts.add_val;
use_gpu            = opts.use_gpu;

if ~is_per_class
    num_imgs    = length(aboxes_in);
    num_classes = size(aboxes_in{1},2) - 4;
else
    num_classes = length(aboxes_in);
    num_imgs    = length(aboxes_in{1});
end

max_per_set   = ceil(ave_per_image * num_imgs);
aboxes_out    = cell(num_classes, 1);
for i = 1:num_classes, aboxes_out{i} = cell(num_imgs, 1); end

thresh_val_all = ones(num_classes,1,'single') * threshold;

for i = 1:num_imgs
    % get the candidate bounding box detection of one image
    if ~is_per_class
        assert(size(aboxes_in{i},2) == (4 + num_classes));
        bbox_cand_dets = aboxes_in{i};
    else
        bbox_cand_dets = cell(num_classes,1);
        for j = 1:num_classes
            assert(size(aboxes_in{j}{i},2) == 5);
            bbox_cand_dets{j} = aboxes_in{j}{i};
        end
    end

    % post-process the candidate bounding box detection of one image
    bbox_detections_per_class = post_process_candidate_detections(bbox_cand_dets, ...
        'thresholds',thresh_val_all, 'nms_iou_thrs',nms_iou_thrs,...
        'max_per_image',max_per_image,'do_bbox_voting',do_bbox_voting,...
        'box_ave_iou_thresh',box_ave_iou_thresh,'add_val',add_val, ...
        'use_gpu',use_gpu);

    for j = 1:num_classes, aboxes_out{j}{i} = bbox_detections_per_class{j}; end

    if (mod(i, 1000) == 0) && use_not_static_thr
        for j = 1:num_classes
            [aboxes_out{j}, thresh_val_all(j)] = keep_top_k(aboxes_out{j}, i, max_per_set, thresh_val_all(j));
        end
    end
end

if use_not_static_thr
    disp(thresh_val_all(:)');
    for i = 1:num_classes
        % go back through and prune out detections below the found threshold
        aboxes_out{i} = prune_detections(aboxes_out{i}, thresh_val_all(i));
    end
end

total_num_bboxes = zeros(num_classes, 1);
for j = 1:num_classes
    total_num_bboxes(j) = sum(cellfun(@(x) size(x,1), aboxes_out{j}, 'UniformOutput', true));
end

fprintf('Average number of bounding boxes per class\n');
disp(total_num_bboxes(:)' / num_imgs);
fprintf('Average number of bounding boxes in total\n');
disp(sum(total_num_bboxes) / num_imgs);
end

function [boxes, thresh] = keep_top_k(boxes, end_at, top_k, thresh)
% keep top K detections
X = cat(1, boxes{1:end_at});
if isempty(X), return; end

scores = sort(X(:,end), 'descend');
thresh = scores(min(length(scores), top_k));
for image_index = 1:end_at
    bbox = boxes{image_index};
    keep = find(bbox(:,end) >= thresh);
    boxes{image_index} = bbox(keep,:);
end

end

function bbox_dets = prune_detections(bbox_dets, thresh)
for j = 1:length(bbox_dets)
    if ~isempty(bbox_dets{j})
        bbox_dets{j}(bbox_dets{j}(:,end) < thresh ,:) = [];
    end
end
end


function meanF1 = MAMUDA_enterFunc(inputPath,ite1,ite2,itermediateD,reducedD,sharedD)
    load(inputPath);
    [result,F1,meanF1,R,Rt,Q]=MAMUDA(testfea,testlabel,trainFea,trainLabel,unlabelFea,unlabelLabel,ite1,ite2,0.0,itermediateD,reducedD,sharedD,2);
end


function [cfg, artifact] = ft_artifact_eog(cfg, data)

% FT_ARTIFACT_EOG reads the data segments of interest from file and identifies EOG
% artifacts.
%
% Use as
%   [cfg, artifact] = ft_artifact_eog(cfg)
% with the configuration options
%   cfg.dataset     = string with the filename
% or
%   cfg.headerfile  = string with the filename
%   cfg.datafile    = string with the filename
% and optionally
%   cfg.headerformat
%   cfg.dataformat
%
% Alternatively you can use it as
%   [cfg, artifact] = ft_artifact_eog(cfg, data)
% where the input data is a structure as obtained from FT_PREPROCESSING.
%
% In both cases the configuration should also contain
%   cfg.trl        = structure that defines the data segments of interest. See FT_DEFINETRIAL
%   cfg.continuous = 'yes' or 'no' whether the file contains continuous data
%
% The data is preprocessed (again) with the following configuration parameters,
% which are optimal for identifying EOG artifacts.
%   cfg.artfctdef.eog.bpfilter   = 'yes'
%   cfg.artfctdef.eog.bpfilttype = 'but'
%   cfg.artfctdef.eog.bpfreq     = [1 15]
%   cfg.artfctdef.eog.bpfiltord  = 4
%   cfg.artfctdef.eog.hilbert    = 'yes'
%
% Artifacts are identified by means of thresholding the z-transformed value
% of the preprocessed data.
%   cfg.artfctdef.eog.channel      = Nx1 cell-array with selection of channels, see FT_CHANNELSELECTION for details
%   cfg.artfctdef.eog.cutoff       = z-value at which to threshold (default = 4)
%   cfg.artfctdef.eog.trlpadding   = 0.5
%   cfg.artfctdef.eog.fltpadding   = 0.1
%   cfg.artfctdef.eog.artpadding   = 0.1
%
% The output argument "artifact" is a Nx2 matrix comparable to the
% "trl" matrix of FT_DEFINETRIAL. The first column of which specifying the
% beginsamples of an artifact period, the second column contains the
% endsamples of the artifactperiods.
%
% To facilitate data-handling and distributed computing you can use
%   cfg.inputfile   =  ...
% If you specify this option the input data will be read from a *.mat
% file on disk. This mat files should contain only a single variable named 'data',
% corresponding to the input structure.
%
% See also FT_REJECTARTIFACT, FT_ARTIFACT_CLIP, FT_ARTIFACT_ECG, FT_ARTIFACT_EOG,
% FT_ARTIFACT_JUMP, FT_ARTIFACT_MUSCLE, FT_ARTIFACT_THRESHOLD, FT_ARTIFACT_ZVALUE

% Undocumented local options
% cfg.method

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

% these are used by the ft_preamble/ft_postamble function and scripts
ft_revision = '$Id$';
ft_nargin   = nargin;
ft_nargout  = nargout;

% do the general setup of the function
ft_defaults
ft_preamble init

% ft_preamble provenance is not needed because just a call to ft_artifact_zvalue
% ft_preamble loadvar data is not needed because ft_artifact_zvalue will do this

% the ft_abort variable is set to true or false in ft_preamble_init
if ft_abort
  return
end

% check if the input cfg is valid for this function
cfg = ft_checkconfig(cfg, 'renamed',    {'datatype', 'continuous'});
cfg = ft_checkconfig(cfg, 'renamedval', {'continuous', 'continuous', 'yes'});

% set default rejection parameters
cfg.artfctdef            = ft_getopt(cfg,               'artfctdef', []);
cfg.artfctdef.eog        = ft_getopt(cfg.artfctdef,     'eog',       []);
cfg.artfctdef.eog.method = ft_getopt(cfg.artfctdef.eog, 'method',    'zvalue');

if isfield(cfg.artfctdef.eog, 'artifact')
  fprintf('eog artifact detection has already been done, retaining artifacts\n');
  artifact = cfg.artfctdef.eog.artifact;
  return
end

if ~strcmp(cfg.artfctdef.eog.method, 'zvalue')
  ft_error('EOG artifact detection only works with cfg.method=''zvalue''');
end

% for backward compatibility
cfg.artfctdef.eog = ft_checkconfig(cfg.artfctdef.eog, 'renamed', {'sgn',     'channel'});
cfg.artfctdef.eog = ft_checkconfig(cfg.artfctdef.eog, 'renamed', {'passbnd', 'bpfreq'});
cfg.artfctdef.eog = ft_checkconfig(cfg.artfctdef.eog, 'renamed', {'padding', 'trlpadding'});
artpadding_oldstyle  = max(ft_getopt(cfg.artfctdef.eog, 'pretim', 0), ft_getopt(cfg.artfctdef.eog, 'psttim', 0));

% settings for preprocessing
cfg.artfctdef.eog.bpfilter    = ft_getopt(cfg.artfctdef.eog, 'bpfilter',   'yes');
cfg.artfctdef.eog.bpfreq      = ft_getopt(cfg.artfctdef.eog, 'bpfreq',     [1 15]);
cfg.artfctdef.eog.bpfiltord   = ft_getopt(cfg.artfctdef.eog, 'bpfiltor',   4);
cfg.artfctdef.eog.bpfilttype  = ft_getopt(cfg.artfctdef.eog, 'bpfilttype', 'but');
cfg.artfctdef.eog.hilbert     = ft_getopt(cfg.artfctdef.eog, 'hilbert',    'yes');

% settings for the zvalue subfunction
cfg.artfctdef.eog.channel    = ft_getopt(cfg.artfctdef.eog, 'channel',    'EOG');
cfg.artfctdef.eog.trlpadding = ft_getopt(cfg.artfctdef.eog, 'trlpadding', 0.5);
cfg.artfctdef.eog.fltpadding = ft_getopt(cfg.artfctdef.eog, 'fltpadding', 0.1);
cfg.artfctdef.eog.artpadding = max(ft_getopt(cfg.artfctdef.eog, 'artpadding', 0.1), artpadding_oldstyle);
cfg.artfctdef.eog.cutoff     = ft_getopt(cfg.artfctdef.eog, 'cutoff',     4);

% construct a temporary configuration that can be passed onto artifact_zvalue
tmpcfg                  = cfg;
tmpcfg.artfctdef.zvalue = cfg.artfctdef.eog;
tmpcfg.artfctdef        = rmfield(tmpcfg.artfctdef, 'eog');

% call the zvalue artifact detection function, where the data is either passed
% into the function by the user or read from file with cfg.inputfile
hasdata = exist('data', 'var');
if ~hasdata
  tmpcfg             = ft_checkconfig(tmpcfg, 'dataset2files', 'yes');
  tmpcfg             = ft_checkconfig(tmpcfg, 'required', {'headerfile', 'datafile'});
  [tmpcfg, artifact] = ft_artifact_zvalue(tmpcfg);
else
  tmpcfg.artfctdef.zvalue.trlpadding = 0;
  tmpcfg.artfctdef.zvalue.fltpadding = 0;
  ft_warning('trlpadding and fltpadding are set to zero to avoid filter problems with NaN, see bug3193 for details');
  [tmpcfg, artifact] = ft_artifact_zvalue(tmpcfg, data);
end
cfg.artfctdef.eog  = tmpcfg.artfctdef.zvalue;


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

function r = uniop_bool_helper(x, scalar_fcn, opt, varargin)
% SCALAR_FCN can either be the name of a function or a lambda
% definition of a new function.  It can be multiline cell array
% defining a a new function called "sf".
%
% Many SymPy commands return True/False/None (or S.true/S.false/None),
% where None is used for "don't know" or "can't tell".
% The string OPT describes what to do about this.
%   'bool': the default, always return Octave bool (logical) array,
%           maps None to false.
%   'sym': always return symbolic array, which might contain True,
%          False, None.
%   'symIfAnyNone': if the result has any None, return a symbolic
%                   array, otherwise return a bool array.
%
% If you'd like to raise an error on None, do so in SCALAR_FCN.
% See isprime.m for example.
%
% Any additional arguments after OPT are passed to SCALAR_FCN as-is.

  if (iscell(scalar_fcn))
    cmd = scalar_fcn;
  else
    cmd = {['sf = ' scalar_fcn]};
  end

  if ((nargin < 3) || isempty(opt))
    opt = 'bool';
  end

  switch opt
    case 'bool'
      cmd = [ cmd
              'x = _ins[0]'
              'pp = _ins[1:]'
              'if x is not None and x.is_Matrix:'
              '    # bool will map None to False'
              '    return [bool(sf(a, *pp)) for a in x.T],'
              'return bool(sf(x, *pp))' ];

      r = pycall_sympy__ (cmd, x, varargin{:});

      if (~isscalar(x))
        r = reshape(cell2mat(r), size(x));
      end

    case 'sym'
      warning('FIXME: not working for scalars')

      cmd = [ cmd
              'x = _ins[0]'
              'pp = _ins[1:]'
              'if x if not None and x.is_Matrix:'
              '    return x.applyfunc(sf, *pp)'
              'return sf(x, *pp)' ];

      r = pycall_sympy__ (cmd, x, varargin{:});

    case 'symIfAnyNone'
      error('FIXME: not implemented')

    otherwise
      error('uniop_bool_helper: option "%s" not implemented', opt)

  end
end


function xyzl_header_print ( point_num, line_num, line_data_num )

%*****************************************************************************80
%
%% XYZL_HEADER_PRINT prints the header of an XYZL file.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    07 January 2009
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer POINT_NUM, the number of points.
%
%    Input, integer LINE_NUM, the number of lines.
%
%    Input, integer LINE_DATA_NUM, the number of line items.
%
  fprintf ( 1, ' \n');
  fprintf ( 1, '  Number of points =     %d\n', point_num );
  fprintf ( 1, '  Number of lines =      %d\n', line_num );
  fprintf ( 1, '  Number of line items = %d\n', line_data_num );

  return
end


function option_num = p14_option_num ( )

%*****************************************************************************80
%
%% P14_OPTION_NUM returns the number of options for problem 14.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    03 September 2008
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, integer OPTION_NUM, the number of options.
%
  option_num = 1;

  return
end


function make_frames ( frame_total )

%*****************************************************************************80
%
%% MAKE_FRAMES makes the frames of an animation.
%
%  Discussion:
%
%    This program makes FRAME_TOTAL + 1 JPEG files, which constitute
%    individual frames of an animation.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    20 November 2010
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer FRAME_TOTAL, the total number of frames.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'MAKE_FRAMES:\n' );
  fprintf ( 1, '  Make a (potential) animation by creating a sequence\n' );
  fprintf ( 1, '  of JPG files, each containing one frame.\n' );

  if ( nargin < 1 )
    fprintf ( 1, '\n' );
    frame_total = input ( 'Enter the number of frames to create:  ' );
  end

  fprintf ( 1, '\n' );
  fprintf ( 1, '  This program has been asked to create\n' );
  fprintf ( 1, '  frames 0 through %d.\n', frame_total );
  fprintf ( 1, '  The first frame will be stored in "%s",\n', ...
    sprintf ( 'frame%04d.jpg', 0 ) );
  fprintf ( 1, '  The last frame will be stored in "%s".\n', ...
    sprintf ( 'frame%04d.jpg', frame_total ) );

  for frame_id = 0 : frame_total
    make_frame ( frame_id, frame_total );
  end

  fprintf ( 1, '\n' );
  fprintf ( 1, 'MAKE_FRAMES:\n' );
  fprintf ( 1, '  Normal end of execution.\n' );

  return
end


%run_computeScores_localModel applies the local model to the bounding-box proposals to compute their scores

% SETUP THESE PATHS TO RUN THE CODE
dataPath = 'data/HollywoodHeads';
resultPath = 'results/HollywoodHeads';

% network to evaluate
netFile = fullfile( 'models', 'local.mat' );

% file to store the scores
resultFile = fullfile( resultPath, 'local', 'localModel-scores-test.mat' );

% Choose subset of data to compute the scores.
%   To run the evaluation of the local model you need the test test (3).
%   To run the training of the pairwise model you need all the subsets ([1,2,3]). It might be a good idea to do this in batches on multiple GPUs.
scoreSubset = 3; % 1 - train subset, 2 - validation, 3 - test; can do [1,2,3] to compute scores on all the subsets

%% setup paths
filePath = fileparts( mfilename('fullpath') );
run( fullfile( fileparts( filePath ), 'setup.m' ) );

%% parameters
opts_cnn = struct;
opts_cnn.dataPath = dataPath;
opts_cnn.dataset.trainingSetFile = fullfile('Splits', 'train.txt');
opts_cnn.dataset.validationSetFile = fullfile('Splits', 'val.txt');
opts_cnn.dataset.testSetFile = fullfile('Splits', 'test.txt');
opts_cnn.dataset.groundTruthLocalPrefix = 'Annotations';
opts_cnn.dataset.imageLocalPrefix = 'JPEGImages';
opts_cnn.dataset.candidateLocalPrefix = 'Candidates';

opts_cnn.expDir =  resultPath;
opts_cnn.maxGpuImagesEvaluation = 3000;
opts_cnn.gpuBatchSize = 128;
opts_cnn.scoreMode = 'beforeSoftMax'; % 'beforeSoftMax' or 'afterSoftMax' or 'scoreDifference';

opts_cnn.evaluation.iouThreshold = 0.5;
opts_cnn.evaluation.nmsMaxCandidateNumber = inf;
opts_cnn.evaluation.useDifficultImages = false;

%% load dataset
opts_cnn.imdbPath = fullfile(opts_cnn.expDir, 'imdb.mat');
if exist(opts_cnn.imdbPath, 'file')
    fprintf('Reading imdb file %s\n', opts_cnn.imdbPath);
    imdb = load(opts_cnn.imdbPath);
    if isfield(imdb, 'opts') && isequal( imdb.opts, opts_cnn.dataset )
        fprintf('imdb.opts is compatible with the opt_cnn.dataset\n')
    else
        warning('opts_cnn.dataset parameters are not compatible with the provided imdb file. Be careful!');
    end
else
    warning('imdb file is not found. Making it will take some time.');
    fprintf('Generating imdb file %s\n', opts_cnn.imdbPath);
    imdb = cnn_prepareData_localModel( opts_cnn.dataset, 'dataPath', opts_cnn.dataPath );
    imdb.opts = opts_cnn.dataset;
    mkdir(opts_cnn.expDir);
    save(opts_cnn.imdbPath, '-struct', 'imdb', '-v7.3') ;
end

%% load network
net = load( netFile, '-mat');
if ~isfield(net, 'layers') && isfield(net, 'net')
    net = net.net;
end
if ~isfield(net, 'layers')
    error('Could not load the network!');
end
net = vl_simplenn_move(net, 'gpu');

%% select the set of images to run evaluation
imageSetToDoPr = false( numel( imdb.images.set ), 1 );
for iSubset = 1 : numel( scoreSubset )
    imageSetToDoPr = imageSetToDoPr | ( imdb.images.set(:) == scoreSubset( iSubset ) );
end
imageSetToDoPr = find( imageSetToDoPr );

%% start the evaluation
opts_cnn.getBatchEvaluation = struct;
opts_cnn.getBatchEvaluation.cropMode = 'warp';
opts_cnn.getBatchEvaluation.cropPad = [18, 18, 18, 18];
opts_cnn.getBatchEvaluation.meanImage = net.normalization.averageImage;
opts_cnn.getBatchEvaluation.numPatchesPerImage = inf;
opts_cnn.getBatchEvaluation.maxPositives = inf;
opts_cnn.getBatchEvaluation.maxGpuImages = opts_cnn.maxGpuImagesEvaluation;
opts_cnn.getBatchEvaluation.iouPositiveThreshold = opts_cnn.evaluation.iouThreshold;
opts_cnn.getBatchEvaluation.iouNegativeThreshold = opts_cnn.evaluation.iouThreshold;
opts_cnn.getBatchEvaluation.dataPath = opts_cnn.dataPath;
opts_cnn.getBatchEvaluation.jitterStd = 0;

batchWrapperEvaluation = @(imdb, batch) cnn_getBatch_localModel(imdb, batch, ...
    opts_cnn.getBatchEvaluation) ;

[scores, candidateIds] = cnn_computeScores_localModel( net, imdb, batchWrapperEvaluation, ...
    'imageSet', imageSetToDoPr, ...
    'gpuBatchSize', opts_cnn.gpuBatchSize, ...
    'scoreMode', opts_cnn.scoreMode );

if exist(resultFile, 'file')
    warning('The results file already exists. Overwriting!');
end
if ~exist(fileparts(resultFile), 'dir')
    mkdir(fileparts(resultFile));
end
save( resultFile, 'scores', 'candidateIds', '-v7.3' );

%% save detections to files
detSavePath = fullfile( resultPath, 'local', 'dets');
if ~exist(detSavePath, 'dir')
    mkdir(detSavePath)
end
detSaveFormat = fullfile(detSavePath, '%s.mat');
disp('Saving detection files');
for i=1:length(imageSetToDoPr)
    imgIdx = imageSetToDoPr(i);
    cand_path = fullfile(dataPath, imdb.candidateFiles{imgIdx});
    load(cand_path);
    %load candidate
    BB = [convertBb_X1Y1X2Y2_to_X1Y1WH(boxes(candidateIds{imgIdx},[2 1 4 3])) scores{imgIdx}];
    [~, im_name, ~] = fileparts(imdb.imageFiles{imgIdx});
    savePath = sprintf(detSaveFormat, im_name);
    save(savePath, 'BB');
end


function skelVargplvmModify(handle, yVal, chan, skel, padding, zeroIndices)

% SKELMODIFY Update visualisation of skeleton data.
% FORMAT
% DESC updates a skeleton representation in a 3-D plot.
% ARG handle : a vector of handles to the structure to be updated.
% ARG channels : the channels to update the skeleton with.
% ARG skel : the skeleton structure.
%
% SEEALSO : skelVisualise
%
% COPYRIGHT : Neil D. Lawrence, 2005, 2006
% MODIFICATIONS: Andreas C. Damianou, 2014

% SHEFFIELDML

if nargin<5
  padding = 0;
end
channels = demCmu35VargplvmLoadChannels(yVal,skel);
channels = [channels zeros(1, padding)];
vals = skel2xyz(skel, channels);
connect = skelConnectionMatrix(skel);

indices = find(connect);
[I, J] = ind2sub(size(connect), indices);

set(handle(1), 'Xdata', vals(:, 1), 'Ydata', vals(:, 3), 'Zdata', ...
                 vals(:, 2));
%/~
%set(handle(1), 'visible', 'on')
%~/

for i = 1:length(indices)
  set(handle(i+1), 'Xdata', [vals(I(i), 1) vals(J(i), 1)], ...
            'Ydata', [vals(I(i), 3) vals(J(i), 3)], ...
            'Zdata', [vals(I(i), 2) vals(J(i), 2)]);
end

function [vals, connect] = wrapAround(vals, lim, connect);

quot = lim(2) - lim(1);
vals = rem(vals, quot)+lim(1);
nVals = floor(vals/quot);
for i = 1:size(connect, 1)
  for j = find(connect(i, :))
    if nVals(i) ~= nVals(j)
      connect(i, j) = 0;
    end
  end
end


function varargout=lpcpf2cc(varargin)
%
% For calling details please see v_lpcpf2cc.m
%
% This dummy routine is included for backward compatibility only
% and will be removed in a future release of voicebox. Please use
% v_lpcpf2cc.m in future and/or update with v_voicebox_update.m
%
%      Copyright (C) Mike Brookes 2018
%      Version: $Id: lpcpf2cc.m 10863 2018-09-21 15:39:23Z dmb $
%
if nargout
    varargout=cell(1,nargout);
    [varargout{:}]=v_lpcpf2cc(varargin{:});
else
    v_lpcpf2cc(varargin{:});
end


 function argpair = fatrix2_construct_args(ob, varargin)
%function argpair = fatrix2_construct_args(ob, options)
%|
%| Given a fatrix2_block object, return a cell array of name, value pairs
%| such that the object could be re-constructed by
%|	ob = fatrix2(argpair{:})
%| This is useful for constructing variations of the object.
%|
%| out
%|	argpair {2n}	{name1, value1, ...}
%|
%| Copyright 2010-12-02, Jeff Fessler, University of Michigan

if nargin < 1, ir_usage, end

% user-definable properties
name_user = {'arg', 'dim', 'caller', 'odim', 'mask', 'meth'};

% private/internal properties
name_priv = {'dim', 'is_transpose', 'nblock', 'iblock'}

% handles
name_hand = {'back', 'forw', 'power', 'abs', 'free', 'gram', ...
	'mtimes_block', 'block_setup', 'blockify_data'};

argpair = {};

for ii=1:numel(name_user)
	name = name_user{ii};
	argpair{end+[1:2]} = {name, ob.(name)};
end

for ii=1:numel(name_priv)
	name = name_priv{ii};
	argpair{end+[1:2]} = {name, ob.(name)};
end

for ii=1:numel(name_hand)
	name = name_hand{ii};
	argpair{end+[1:2]} = {name, ob.(['handle_' name])};
end