function success = testPrepareJAABAData(datatype,rootdir)

success = false;
if nargin < 2,
  rootdir = '/groups/branson/bransonlab/projects/JAABA/sampledata';
end

%% create the JAABA GUI
hfig = PrepareJAABAData;

% get handles
handles = guidata(hfig);

%% parameters

params = struct;
params.datatype = datatype;

switch datatype,

  case 'Ctrax'

    params.inputdir = fullfile(rootdir,'flies','GMR_14C07_AE_01_TrpA_Rig1Plate15BowlA_20120404T141155');
    params.inputmoviefilestr = 'movie.ufmf';
    params.inputmoviefile = fullfile(params.inputdir,params.inputmoviefilestr);
    params.inputfiledict = {'intrxfile','ctrax_results.mat',fullfile(params.inputdir,'ctrax_results.mat')
      'annfile','movie.ufmf.ann',fullfile(params.inputdir,'movie.ufmf.ann')};
    [~,params.experiment_name] = fileparts(params.inputdir);
    params.experiment_name = [params.experiment_name,'__Ctrax'];
    params.outputdir = '../tests/PrepareJAABADataTests';
    params.outputmoviefilestr = params.inputmoviefilestr;
    params.outputtrxfilestr = 'registered_trx.mat';
    params.outputperframedir = 'perframe';

    % sample jab file
    params.jabfile = fullfile(rootdir,'flies','ChaseAR_new_v10p0.jab');

    % options
    params.options = struct;
    params.options.SoftLinkFiles = true;
    params.options.fliplr = false;
    params.options.flipud = false;
    params.options.dotransposeimage = false;
    params.options.fps = 30.344385106161738;
    params.options.pxpermm = 7.888175824175824;
    params.options.OverRideFPS = true;
    params.options.OverRideArena = false;
    params.options.CropFirstFrame = 1;
    params.options.CropEndFrame = inf;
    params.options.ArenaType = 'circle';

    % read arena or fps?
    params.readarena = true;
    params.readfps = true;

  case 'CtraxPlusWings',

    params.inputdir = fullfile(rootdir,'flies','GMR_14C07_AE_01_TrpA_Rig1Plate15BowlA_20120404T141155');
    params.inputmoviefilestr = 'movie.ufmf';
    params.inputmoviefile = fullfile(params.inputdir,params.inputmoviefilestr);
    params.inputfiledict = {'intrxfile','wingtracking_results.mat',fullfile(params.inputdir,'wingtracking_results.mat')
      'annfile','movie.ufmf.ann',fullfile(params.inputdir,'movie.ufmf.ann')
      'inperframedir','perframe',fullfile(params.inputdir,'perframe')};
    [~,params.experiment_name] = fileparts(params.inputdir);
    params.experiment_name = [params.experiment_name,'__CtraxPlusWings'];
    params.outputdir = '../tests/PrepareJAABADataTests';
    params.outputmoviefilestr = params.inputmoviefilestr;
    params.outputtrxfilestr = 'wingtracking_results.mat';
    params.outputperframedir = 'perframe';

    % sample jab file
    params.jabfile = fullfile(rootdir,'flies','WingExtension_AR_v1p0.jab');

    % options
    params.options = struct;
    params.options.SoftLinkFiles = true;
    params.options.fliplr = false;
    params.options.flipud = false;
    params.options.dotransposeimage = false;
    params.options.fps = 30.344385106161738;
    params.options.pxpermm = 7.888175824175824;
    params.options.OverRideFPS = true;
    params.options.OverRideArena = false;
    params.options.CropFirstFrame = 1;
    params.options.CropEndFrame = inf;
    params.options.ArenaType = 'circle';

    % read arena or fps?
    params.readarena = true;
    params.readfps = true;

  case 'SimpleTwoFlies',

    params.inputdir = fullfile(rootdir,'courtship_bowls','FCF_pBDPGAL4U_1500437_TrpA_Rig2Plate17BowlD_20121121T152832');
    params.inputmoviefilestr = 'movie.ufmf';
    params.inputmoviefile = fullfile(params.inputdir,params.inputmoviefilestr);
    params.inputfiledict = {'intrxfile','registered_trx.mat',fullfile(params.inputdir,'registered_trx.mat')
      'inperframedir','perframe',fullfile(params.inputdir,'perframe')};
    [~,params.experiment_name] = fileparts(params.inputdir);
    params.experiment_name = [params.experiment_name,'__SimpleTwoFlies'];
    params.outputdir = '../tests/PrepareJAABADataTests';
    params.outputmoviefilestr = params.inputmoviefilestr;
    params.outputtrxfilestr = 'registered_trx.mat';
    params.outputperframedir = 'perframe';

    % sample jab file
    params.jabfile = fullfile(rootdir,'courtship_bowls','copulation_cb_ARv1p8.jab');

    % options
    params.options = struct;
    params.options.SoftLinkFiles = true;
    params.options.fliplr = false;
    params.options.flipud = false;
    params.options.dotransposeimage = false;
    params.options.OverRideFPS = true;
    params.options.OverRideArena = false;
    params.options.CropFirstFrame = 1;
    params.options.CropEndFrame = inf;
    params.options.ArenaType = 'None';

    % read arena or fps?
    params.readarena = false;
    params.readfps = true;

  case 'LarvaeRiveraAlba'

    params.inputdir = fullfile(rootdir,'larvae','OregonRA');
    params.inputmoviefilestr = 'movie.mov';
    params.inputmoviefile = fullfile(params.inputdir,params.inputmoviefilestr);
    params.inputfiledict = {'intrxfile','trx.mat',fullfile(params.inputdir,'trx.mat')
       'inperframedir','perframe',fullfile(params.inputdir,'perframe')};
    [~,params.experiment_name] = fileparts(params.inputdir);
    params.experiment_name = [params.experiment_name,'__LarvaeRiveraAlba'];
    params.outputdir = '../tests/PrepareJAABADataTests';
    params.outputmoviefilestr = params.inputmoviefilestr;
    params.outputtrxfilestr = 'trx.mat';
    params.outputperframedir = 'perframe';

    % sample jab file
    params.jabfile = fullfile(rootdir,'larvae','TODO.jab');

    % options
    params.options = struct;
    params.options.SoftLinkFiles = true;
    params.options.fliplr = false;
    params.options.flipud = false;
    params.options.dotransposeimage = false;
    params.options.OverRideFPS = false;
    params.options.OverRideArena = false;
    params.options.CropFirstFrame = 1;
    params.options.CropEndFrame = inf;
    params.options.ArenaType = 'circle';

    % read arena or fps?
    params.readarena = false;
    params.readfps = false;

  case 'Qtrax',

    params.inputdir = fullfile(rootdir,'qtrax','EH091202_15A01_p1');
    params.inputmoviefilestr = 'EH091202_15A01_p1.mp4';
    params.inputmoviefile = fullfile(params.inputdir,params.inputmoviefilestr);
    params.inputfiledict = {'featfile','EH091202_15A01_p1_1_feat.mat',fullfile(params.inputdir,'EH091202_15A01_p1_1_feat.mat')
      'roifile','EH091202_15A01_p1_1_roi.mat',fullfile(params.inputdir,'EH091202_15A01_p1_1_roi.mat')};
    [~,params.experiment_name] = fileparts(params.inputdir);
    params.experiment_name = [params.experiment_name,'__Qtrax'];
    params.outputdir = '../tests/PrepareJAABADataTests';
    [~,~,ext] = fileparts(params.inputmoviefilestr);
    params.outputmoviefilestr = ['movie',ext];
    params.outputtrxfilestr = 'trx.mat';
    params.outputperframedir = 'perframe';

    % sample jab file
    params.jabfile = fullfile(rootdir,'qtrax','qtrax_dummy20130819.jab');

    % options
    params.options = struct;
    params.options.SoftLinkFiles = true;
    params.options.fliplr = false;
    params.options.flipud = false;
    params.options.dotransposeimage = false;
    params.options.OverRideFPS = false;
    params.options.OverRideArena = false;
    params.options.CropFirstFrame = 1;
    params.options.CropEndFrame = inf;
    params.options.ArenaType = 'Circle';

    % read arena or fps?
    params.readarena = false;
    params.readfps = false;

  case 'MAGATAnalyzer',

    params.inputdir = fullfile(rootdir,'larvae_samuel','20120206_100300');
    params.inputmoviefilestr = '20120206_100300@FCF_attp2_1500062@UAS_TNT_2_0003@t7@n#n#n#n@30@.mmf';
    params.inputmoviefile = fullfile(params.inputdir,params.inputmoviefilestr);
    params.inputfiledict = {'expfile','expfile.mat',fullfile(params.inputdir,'FCF_attp2_1500062@UAS_TNT_2_0003_experiment_20120206_100300.mat')};
    % experiment name is encoded in movie name
    [~,params.experiment_name,ext] = fileparts(params.inputmoviefile);
    params.experiment_name = [params.experiment_name,'__MAGATAnalyzer'];
    params.outputdir = '../tests/PrepareJAABADataTests';
    params.outputmoviefilestr = ['movie',ext];
    params.outputtrxfilestr = 'trx.mat';
    params.outputperframedir = 'perframe';

    % sample jab file
    params.jabfile = fullfile(rootdir,'larvae_samuel','MAGATAnalyzer_Test.jab');

    % options
    params.options = struct;
    params.options.SoftLinkFiles = true;
    params.options.fliplr = false;
    params.options.flipud = false;
    params.options.dotransposeimage = false;
    params.options.OverRideFPS = false;
    params.options.OverRideArena = false;
    params.options.CropFirstFrame = 1;
    params.options.CropEndFrame = inf;
    params.options.ArenaType = 'None';

    % read arena or fps?
    params.readarena = false;
    params.readfps = false;

  case 'MWT',

    params.inputdir = fullfile(rootdir,'larvae_mwt','MZZ_ppk1d9GAL4_t2_TrpA_20120612_110553');
    params.inputmoviefilestr = '';
    params.inputmoviefile = '';
    tmp = dir(fullfile(params.inputdir,'*.blob*'));
    blobspaths = cellfun(@(x) fullfile(params.inputdir,x),{tmp.name},'UniformOutput',false);
    tmp = dir(fullfile(params.inputdir,'*.dat'));
    datpaths = cellfun(@(x) fullfile(params.inputdir,x),{tmp.name},'UniformOutput',false);
    params.inputfiledict = {'blobsfile','trx.blobs',blobspaths
      'datfiles','chor.dat',datpaths};
    [~,params.experiment_name] = fileparts(params.inputdir);
    params.experiment_name = [params.experiment_name,'__MWT'];
    params.outputdir = '../tests/PrepareJAABADataTests';
    params.outputmoviefilestr = params.inputmoviefilestr;
    params.outputtrxfilestr = 'trx.mat';
    params.outputperframedir = 'perframe';

    % sample jab file
    params.jabfile = fullfile(rootdir,'larvae_mwt','LarvaeMWT_Roll_v18TO.jab');

    % options
    params.options = struct;
    params.options.SoftLinkFiles = true;
    params.options.fliplr = false;
    params.options.flipud = false;
    params.options.dotransposeimage = false;
    params.options.fps = 30.319466231015564;
    params.options.pxpermm = 17.857142387323400;
    params.options.OverRideFPS = false;
    params.options.OverRideArena = false;
    params.options.CropFirstFrame = 1;
    params.options.CropEndFrame = inf;
    params.options.ArenaType = 'None';

    % read arena or fps?
    params.readarena = true;
    params.readfps = false;

  case 'LarvaeReid',

    name1 = 'FCF_attP2_1500062_50';
    name2 = 'o_ethylbutyrate015m8ul_0s1x360s0s#n#n#n@20';
    name3 = '20120427_134403';
    inputdir1 = fullfile(rootdir,'larvae_reid',name1,name2);
    params.inputdir = fullfile(inputdir1,name3);
    params.inputmoviefilestr = '';
    params.inputmoviefile = '';
    tmp = dir(fullfile(params.inputdir,'*.blob*'));
    blobspaths = cellfun(@(x) fullfile(params.inputdir,x),{tmp.name},'UniformOutput',false);
    params.inputfiledict = {'blobsfile','trx.blobs',blobspaths
      'kinmatfile','kinVariables.mat',fullfile(inputdir1,'kinVariables.mat')
      'eventmatfile','eventVariables.mat',fullfile(inputdir1,'eventVariables.mat')};
    params.experiment_name = sprintf('%s__%s__%s__LarvaeReid',name1,name2,name3);
    params.outputdir = '../tests/PrepareJAABADataTests';
    params.outputmoviefilestr = params.inputmoviefilestr;
    params.outputtrxfilestr = 'trx.mat';
    params.outputperframedir = 'perframe';

    % sample jab file
    params.jabfile = fullfile(rootdir,'larvae_reid','LarvaeReid_dummy.jab');

    % options
    params.options = struct;
    params.options.SoftLinkFiles = true;
    params.options.fliplr = false;
    params.options.flipud = false;
    params.options.dotransposeimage = false;
    params.options.fps = 30.319466231015564;
    params.options.pxpermm = 17.857142387323400;
    params.options.OverRideFPS = false;
    params.options.OverRideArena = false;
    params.options.CropFirstFrame = 1;
    params.options.CropEndFrame = inf;
    params.options.ArenaType = 'None';

    % read arena or fps?
    params.readarena = true;
    params.readfps = false;

  case 'LarvaeLouis',

    name1 = 'rawdata';
    name2 = '20111212-120514';
    inputdir1 = fullfile(rootdir,'larvae_louis',name1);
    params.inputdir = fullfile(inputdir1,name2);
    params.inputmoviefilestr = '20111212-120514_video.avi';
    params.inputmoviefile = fullfile(params.inputdir,params.inputmoviefilestr);
    params.inputfiledict = {'indatafile','20111212-120514_data.txt',fullfile(params.inputdir,'20111212-120514_data.txt')
      'inkinmatfile','kinVariables.mat',fullfile(inputdir1,'kinVariables.mat')};
    params.experiment_name = sprintf('%s__LarvaeLouis',name2);
    params.outputdir = '../tests/PrepareJAABADataTests';
    [~,~,ext] = fileparts(params.inputmoviefilestr);
    params.outputmoviefilestr = ['movie',ext];
    params.outputtrxfilestr = 'trx.mat';
    params.outputperframedir = 'perframe';

    % sample jab file
    params.jabfile = fullfile(rootdir,'larvae_louis','LarvaeLouis_dummy.jab');

    % options
    params.options = struct;
    params.options.SoftLinkFiles = true;
    params.options.fliplr = false;
    params.options.flipud = false;
    params.options.dotransposeimage = false;
    params.options.OverRideFPS = false;
    params.options.OverRideArena = false;
    params.options.CropFirstFrame = 1;
    params.options.CropEndFrame = inf;
    params.options.ArenaType = 'None';

    % read arena or fps?
    params.readarena = false;
    params.readfps = false;

end

%% set PrepareJAABAData fields to match

%% set data type
handles = guidata(hfig);
handles.InputDataTypeIndex = find(strcmp(params.datatype,handles.InputDataTypeNames));
handles.InputDataType = params.datatype;
handles = PrepareJAABAData('UpdateGUI',handles);
guidata(hfig,handles);

%% set input table entries
handles = guidata(hfig);

% movie
handles.inputmoviefilestr = params.inputmoviefilestr;
handles.InputVideoFile = params.inputmoviefile;

% rest of files
InputDataType = handles.InputDataTypes.(handles.InputDataType);
for i = 1:size(params.inputfiledict,1),
  j = find(strcmp({InputDataType.files.code},params.inputfiledict{i,1}));
  if numel(j) ~= 1,
    error('Could not match input file type %s',params.inputfiledict{i,1});
  end
  handles.inputfilestrs.(handles.InputDataType){j} = params.inputfiledict{i,2};
  handles.InputFiles.(handles.InputDataType){j} = params.inputfiledict{i,3};
end

handles = PrepareJAABAData('UpdateGUI',handles);
guidata(hfig,handles);

%% set output table entries

handles = guidata(hfig);

% experiment directory
handles.ExperimentDirectory = fullfile(params.outputdir,params.experiment_name);

% output file strings
handles.moviefilestr = params.outputmoviefilestr;
handles.trxfilestr = params.outputtrxfilestr;
handles.perframedirstr = params.outputperframedir;

handles = PrepareJAABAData('UpdateGUI',handles);
guidata(hfig,handles);

%% options

handles = guidata(hfig);

fns = fieldnames(params.options);
for i = 1:numel(fns),
  handles.(fns{i}) = params.options.(fns{i});
end

handles = PrepareJAABAData('UpdateGUI',handles);
guidata(hfig,handles);

%% read arena parameters

if params.readarena,

  PrepareJAABAData('pushbutton_ReadArenaParameters_Callback',hfig,[],guidata(hfig));
  handles = guidata(hfig);

end

%% read fps parameters

if params.readfps,

  PrepareJAABAData('pushbutton_ReadFPS_Callback',hfig,[],guidata(hfig));
  handles = guidata(hfig);

end

%% convert

outexpdir = fullfile(params.outputdir,params.experiment_name);
if exist(outexpdir,'dir'),
  rmdir(outexpdir,'s');
end

PrepareJAABAData('pushbutton_Convert_Callback',hfig,[],guidata(hfig));
handles = guidata(hfig);

%% check that this worked right

filesneeded = {
  fullfile(outexpdir,params.outputtrxfilestr)
  fullfile(outexpdir,params.outputperframedir)
  };
if ~isempty(params.outputmoviefilestr),
  filesneeded{end+1} = fullfile(outexpdir,params.outputmoviefilestr);
end

ismissing = false(size(filesneeded));
for i = 1:numel(filesneeded),
  ismissing(i) = ~exist(filesneeded{i},'file');
  if ismissing(i) && ispc,
    [~,didfind] = GetPCShortcutFileActualPath(filesneeded{i});
    ismissing(i) = didfind == 0;
  end
  fprintf('File %s exists? %d\n',filesneeded{i},~ismissing(i));
end
if any(ismissing),
  error(['Files missing:',sprintf(' %s',filesneeded{ismissing})]);
end

%% close the gui

PrepareJAABAData('figure1_CloseRequestFcn',hfig,[],guidata(hfig));

%% see if we can run JAABADetect on this experiment

JAABADetect(outexpdir,'jabfiles',{params.jabfile},'forcecompute',true);

success = true;


function dtiSpatialNormalize(dt6FileName, templateName, outDirName, useBrainMask, useB0)
%
% dtiSpatialNormalize([dt6FileName=uiget], [templateName='MNI'],
%                     [outDirName=inName_templateName],
%                     [useBrainMaskFlag=false], [useB0Flag=false])
%
% Compute spatial normalization for a single subject and save a
% spatially-normalized copy of the data. Now works with the new
% NIFTI-based dt6 format (should work on old data too).
%
% To normalize a mrDiffusion dataset, try running dtiSpatialNormalize. If
% you don't enter a specific dt6 filename, it will prompt you for a
% dt6 file. It will save a normalized copy of the data in a
% directory with the same name as the one containing the dt6 file,
% but with '_templateName' appended on the end. It will also save a
% png image in there that is a montage showing the normalized PDD
% map overlaid on the MNI t1. This is useful for checking the results.
%
% 2007.10.30 RFD: revamped this script, cleaning up much code in the
% process.
% 2007.11.19 RFD: turned this into a proper function and moved it
% to the xform dir.

if(~exist('dt6FileName','var'))
  dt6FileName = '';
end
if(~exist('useB0','var')||isempty(useB0))
  useB0 = false;
end
if(~exist('useBrainMask','var')||isempty(useBrainMask))
  useBrainMask = false;
end
if(~exist('templateName','var')||isempty(templateName))
  templateName = 'MNI';
end

switch templateName
 case {'MNI','SIRL54'}
  templateDir = fullfile(fileparts(which('mrDiffusion.m')),'templates');
  if(useB0)
	template = fullfile(templateDir, [templateName '_EPI']);
  else
	template = fullfile(templateDir, [templateName '_T1']);
  end
  if(useBrainMask)
	template = [template '_brain'];
  end
  template = [template '.nii.gz'];
 otherwise
  template = templateName;
  [junk,templateName] = fileparts(template);
end

[dt,t1] = dtiLoadDt6(dt6FileName,false);

if(~exist('outDirName','var')||isempty(outDirName))
  outDirName = [fileparts(dt.dataFile) '_' templateName];
end
spm_defaults; global defaults; defaults.analyze.flip = 0;
params = defaults.normalise.estimate;

if(useB0)
    desc = [templateName ' normalized using b0'];
    im = mrAnatHistogramClip(double(dt.b0),0.4,0.98);
    xf = dt.xformToAcpc;
	if(useBrainMask)
	  im(~dt.brainMask) = 0;
	  desc = [desc ' (masked)'];
	end
else
    desc = [templateName ' normalized using T1'];
    im = mrAnatHistogramClip(double(t1.img),0.4,0.98);
    xf = t1.xformToAcpc;
	if(useBrainMask)
	  im(~t1.brainMask) = 0;
	  desc = [desc ' (masked)'];
	end
end

disp(['Normalizing ' dt6FileName ' to ' template '...']);
sn = mrAnatComputeSpmSpatialNorm(im, xf, template, params);

[dt_sn,t1_sn] = dtiSpmDeformer(dt,sn,t1);

t1 = niftiGetStruct(single(t1_sn.img), t1_sn.xformToAcpc, [], desc, 't1');
b0 = niftiGetStruct(single(dt_sn.b0), dt_sn.xformToAcpc, [], desc, 'b=0');
bm = niftiGetStruct(uint8(dt_sn.brainMask), dt_sn.xformToAcpc, [], desc, 'dtBrainMask');
sz = size(dt_sn.dt6);
niftiDt6 = reshape(dt_sn.dt6(:,:,:,[1 4 2 5 6 3]),[sz(1:3),1,sz(4)]);
tensors = niftiGetStruct(niftiDt6, dt_sn.xformToAcpc, [], desc, 'DTI');

% Load the MNI to check the normalization results:
mni = niftiRead(fullfile(templateDir, 'MNI_T1.nii.gz'));
[pddT1,acpcToImXform,mm] = dtiRawCheckTensors(tensors, mni, bm);
sl = 6:2:size(mni.data,3)-2;
imgRgb = makeMontage3(flipdim(permute(pddT1,[2 1 3 4]),1), sl, mni.pixdim(1), 0, [], [], -1);
%figure; image(imgRgb);

% To save the results:
[fullParentDir, dataDir] = fileparts(outDirName);
files.b0 = fullfile(dataDir,'bin','b0.nii.gz');
files.brainMask = fullfile(dataDir,'bin','brainMask.nii.gz');
files.tensors = fullfile(dataDir,'bin','tensors.nii.gz');
files.t1 = fullfile(dataDir,'t1.nii.gz');
mkdir(outDirName);
mkdir(fullfile(outDirName,'bin'));
b0.fname = fullfile(fullParentDir,files.b0);
tensors.fname = fullfile(fullParentDir,files.tensors);
bm.fname = fullfile(fullParentDir,files.brainMask);
t1.fname = fullfile(fullParentDir,files.t1);
writeFileNifti(b0);
writeFileNifti(tensors);
writeFileNifti(bm);
writeFileNifti(t1);
adcUnits = dt_sn.adcUnits;
params.buildDate = datestr(now,'yyyy-mm-dd HH:MM');
l = license('inuse');
params.buildId = sprintf('%s on Matlab R%s (%s)',l(1).user,version('-release'),computer);
params.sourceData = dt_sn.dataFile;
save(fullfile(outDirName,'dt6'),'adcUnits','params','files');
imwrite(imgRgb,fullfile(outDirName,'pddT1.png'));

return;

bd = '/biac3/wandell4/data/reading_longitude/dti_y4/';
inDir = 'dti06_smooth2';

d = dir(fullfile(bd,'*0*'));
n = 0;
for(ii=1:length(d))
  tmp = fullfile(bd,d(ii).name,inDir,'dt6.mat');
  if(exist(tmp,'file'))
	n = n+1;
    sc{n} = d(ii).name;
	fn{n} = tmp;
  end
end

for(ii=1:length(fn))
  disp(['Processing ' sc{ii} '...']);
  dtiRawFixDt6File(fn{ii});
  dtiSpatialNormalize(fn{ii}, 'SIRL54', [], true);
end


%% This file will be used to plot the different result of DL-SINDy
% Coded By: K
% Last Updated: 2019/06/23
%%
clc;clear all; close all;

%% Add path
addpath('.\PDE_Find_Results')

%% Load data
Files=dir('.\PDE_Find_Results\*.mat');

Error=zeros(length(Files),1);
for k=1:length(Files)
   FileNames=Files(k).name;
   load(FileNames)
   Error(k,1)=minVal_Final;
   digits(4)
   Expression
end

%% Plot
close all
g0=[0;0.0001;0.001;0.01;0.1;1];
figure(1)
loglog(g0,Error,'marker','o','linewidth',2.5)
set(gca,'FontSize',18);
set(gcf,'Position',[100 100 600 400]);
set(gcf,'PaperPositionMode','auto');
grid on


% THIS SOFTWARE AND ANY ACCOMPANYING DOCUMENTATION IS RELEASED "AS IS."  THE U.S. GOVERNMENT MAKES NO WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, CONCERNING THIS SOFTWARE AND ANY ACCOMPANYING DOCUMENTATION, INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.  IN NO EVENT WILL THE U.S. GOVERNMENT BE LIABLE FOR ANY DAMAGES, INCLUDING ANY LOST PROFITS, LOST SAVINGS OR OTHER INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE, OR INABILITY TO USE, THIS SOFTWARE OR ANY ACCOMPANYING DOCUMENTATION, EVEN IF INFORMED IN ADVANCE OF THE POSSIBILITY OF SUCH DAMAGES.
%
% file: poisspdf_of_lambda.m
% Used when you want to integrate a poisson pdf with
% respect to lambda.
%
% 022300 tdr created
% 030400 tdr replaced global variable approach to getting x and n to binopdf.
% 031600 tdr converted from binopdf_of_p.m to poisson dist.
% 032200 tdr replaced for loop with vector argument.

function y = poisspdf_of_lambda(lambda, x)

if nargin ~= 2,
    error('Requires two input arguments (lambda,x)');
end

y = poisspdf_0ok(x,lambda);


function [ varargout ] = readLeCroyWaveJetWfm( varargin )
%readLeCroyWaveJetWfm - Read binary waveform (.wfm) files as saved by
% LeCroy WaveJet oscilloscopes.
%
% readLeCroyWaveJetWfm( filename )
%
%   Loads the specified file, shows some information about the file,
%   and displays the waveform(s).
%
% [ data ] = readLeCroyWaveJetWfm( filename )
% [ data nfo ] = readLeCroyWaveJetWfm( filename )
%
%   Load the specified file and returns its data.
%   data - Array with loaded waveform(s). If only one channel was recorded
%          this is a single column with the waveform. If more than one
%          channel was recorded this is a 2D array where each column
%          corresponds with a channel. If a lower number channel is not
%          recorded it will contain a column with NaN's. If a higher number
%          channel is not recorded, it's column is removed from the data
%          array. E.g. ch1: x, ch2: 0, ch3: x, ch4: 0 will result in a 2D
%          array with 3 column, where the second column contains NaN's.
%   nfo - structure with time axis information and text header
%         nfo.x0    - time of first sample (trigger will be at t = 0)
%         nfo.dx    - sampling time, i.e. time between two consecutive samples
%         nfo.notes - text field with complete oscilloscope setup.
%

% Copyright (c) 2008-2010, Paul Wagenaars
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are
% met:
%
%     * Redistributions of source code must retain the above copyright
%       notice, this list of conditions and the following disclaimer.
%     * Redistributions in binary form must reproduce the above copyright
%       notice, this list of conditions and the following disclaimer in
%       the documentation and/or other materials provided with the distribution
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
% POSSIBILITY OF SUCH DAMAGE.
%
% Changelog:
% v0.1 (2008-06-29)
%   - initial release
%
% v0.2 (2008-08-??)
%   - in averaging mode the binary WFM waveform seems to have a half a
%     sample offset compared to the ASCII CSV file. The binary waveform is
%     now shifted half sample downwards.
%   - if averaging mode is turned on the data of inactive channels was
%     skipped incorrectly. This has been fixed.
%
% v0.3 (2010-03-02)
%   - made function compatible with GNU Octave.
%   - fixed waveforms with multiple waveform modes, e.g. when averaging and
%     equivalent sampling are specified at the same time.
%

% Define some constants
global RLWJW_XWAV_DEF_INF_NOACQ RLWJW_XWAV_DEF_INF_NORM RLWJW_XWAV_DEF_INF_PEAK
global RLWJW_XWAV_DEF_INF_EQU   RLWJW_XWAV_DEF_INF_AVG  RLWJW_XWAV_DEF_INF_ROLL
global RLWJW_XWAV_DEF_INF_ILV
RLWJW_XWAV_DEF_INF_NOACQ = uint16(0);  % 0x0000 /* Not acquired */
RLWJW_XWAV_DEF_INF_NORM = uint16(1);   % 0x0001 /* Normal wave */
RLWJW_XWAV_DEF_INF_PEAK = uint16(2);   % 0x0002 /* Peak wave */
RLWJW_XWAV_DEF_INF_EQU = uint16(4);    % 0x0004 /* Equ wave */
RLWJW_XWAV_DEF_INF_AVG = uint16(8);    % 0x0008 /* Average wave */
RLWJW_XWAV_DEF_INF_ROLL = uint16(16);  % 0x0010 /* Roll wave */
RLWJW_XWAV_DEF_INF_ILV = uint16(32);   % 0x0020 /* Interleave wave */

% Maximum memory enum
global MAX_MEM_ENUM
MAX_MEM_ENUM = 1024 * [0 0.5 ; 1 1 ; 2 10 ; 3 100 ; 4 500];

% V/div enum
global RLWJW_VDIV_ENUM
RLWJW_VDIV_ENUM = [10 5 2 1 500e-3 200e-3 100e-3 50e-3 20e-3 10e-3 5e-3 2e-3];

% time/div enum
global RLWJW_TDIV_ENUM
RLWJW_TDIV_ENUM = [50     20     10     5     2     1     500e-3  200e-3  100e-3 ...
             50e-3  20e-3  10e-3  5e-3  2e-3  1e-3  500e-6  200e-6  100e-6 ...
             50e-6  20e-6  10e-6  5e-6  2e-6  1e-6  500e-9  200e-9  100e-9 ...
             50e-9  20e-9  10e-9  5e-9  2e-9  1e-9  500e-12 200e-12 100e-12 ...
             50e-12 20e-12 10e-12 5e-12 2e-12 1e-12 500e-15 200e-15 100e-15];

% Display informatie about waveform(s)
infomode = (nargout == 0);

if nargin < 1
    error('No filename specified.');
else
    filename = varargin{1};
end

if infomode
    fprintf('Loading %s\n', filename);
end

% Open file
[fid, msg] = fopen(filename, 'r', 'b');
if fid == -1
    error('Unable to open %s: %s', filename, msg);
end

% Skip text header
fullheader = '';
while true
    line = fgetl(fid);
    fullheader = sprintf('%s%s\n', fullheader, line);
    if ~ischar(line)
        fclose(fid);
        error('Unable to find end of setup information. Is this a correct LeCroy WaveJet .wfm file?');
    elseif strcmp(line, '[END OF SETUP]');
        % The 'fgetl' function seems to consume one byte too much.
        % So, here we check the byte and rewind in necessary.
        fseek(fid, -1, 'cof');
        data = fread(fid, 1, 'uint8');
        if (data ~= 10) && (data ~= 13)
            fseek(fid, -1, 'cof');
        end
        break;
    end
end

% Read the XWAV_TDE_WAVEINF structure
wavinf = load_XWAV_TDE_WAVEINF(fid);

% Read waveform data
data = nan(wavinf.timebase.memoryLength + 1, 4);
dataStart = wavinf.timebase.validWfmStart;
memLen = wavinf.timebase.memoryLength;
bankSize = wavinf.timebase.bankSize;
validChannels = nan(1,4);
if bitand(wavinf.timebase.wfmMode, RLWJW_XWAV_DEF_INF_AVG)
    bytesPerSample = 2;
else
    bytesPerSample = 1;
end
sampleType = sprintf('int%d', 8 * bytesPerSample);
maxValue = 2^(8 * bytesPerSample);
for j = 1:4
    if wavinf.channels(j).isValid
        validChannels(j) = 1;
        singleChannel = fread(fid, bankSize, sampleType);
        if bitand(wavinf.timebase.wfmMode, RLWJW_XWAV_DEF_INF_AVG)
            % In average mode there is a half a sample offset compared to
            % the csv file. Here we correct that.
            singleChannel = singleChannel - 127;
        end
        singleChannel = singleChannel * 8 * wavinf.channels(j).vdiv / maxValue;
        singleChannel = singleChannel - wavinf.channels(j).offset;
        data(:, j) = singleChannel((5 + dataStart):(memLen + dataStart + 5));
    else
        validChannels(j) = 0;
        fseek(fid, bankSize * bytesPerSample, 'cof');
    end
end
fclose(fid);
clear singleChannel;

% Select only the "good" channels
if sum(validChannels) == 1
    data = data(:, validChannels == 1);
elseif sum(validChannels) < 4
    maxIndex = find(validChannels == 1, 1, 'last');
    data = data(:, 1:maxIndex);
end

% Create nfo structure
totalTime = 10.0 * wavinf.timebase.tdiv;
nfo.dx = totalTime / (wavinf.timebase.memoryLength);
nfo.x0 = -0.5 * totalTime - wavinf.timebase.delay + nfo.dx;
nfo.notes = fullheader;

if infomode
    showInfo(wavinf, nfo, data);
end

% Set the output arguments
if nargout >= 1
    varargout{1} = data;
end
if nargout >= 2
    varargout{2} = nfo;
end

end  % End of main function

%%
%% SUBFUNCTIONS
%%

%% load_XWAV_TDE_WAVEINF
% Loads a wave information structure from file.
% The structure (C code):
% typedef struct
% {
%   XWAV_TDE_WAVEINF_TBASE  TbaseInfo;  /* Time Base Info. */
%   XWAV_TDE_WAVEINF_CH     ChInfo[4];  /* Ch Info. */
% } XWAV_TDE_WAVEINF;
function [waveinfo] = load_XWAV_TDE_WAVEINF(fid)
    waveinfo.timebase = load_XWAV_TDE_WAVEINF_TBASE(fid);
    waveinfo.channels = load_XWAV_TDE_WAVEINF_CH(fid);
end

%% load_XWAV_TDE_WAVEINF_TBASE
% Loads a time base information structure from file.
% The structure (C code):
% typedef struct
% {
%   SVMNG_TDE_TRGDLY delay;        /* Trigger delay time?i-500s..750s?j*/
%   XWAV_TDE_TSTAMP  Tstamp;       /* Time stamp */
%   IWDP_TDE_BANKS   bankNr;       /* Current bank size setting in enum */
%   Uint             mleng;        /* Memory length */
%   Uint             BankSize;     /* Actual bank size (512..512*1024) */
%   Uint             TrgSkew;      /* Trigger skew(TDC): WDP internal value */
%   Uint             WavValidAdr;  /* Start address for valid waveform data */
%   Ushort           wvinf;        /* Bitfielf of waveform mode */
%   Ushort           AvgTimes;     /* Number of average (0,1?`256) */
%   char             tim;          /* time/div in enum */
%   char             spclk;        /* sampling clock in enum */
%   Uchar            RdmInitVal;   /* Random seed: WDP internal value */
%   Uchar            WavSkew;      /* Fraction of delay and trigger skew in a
%                                     sampling clock. 0..99 for normalwaveform,
%                                     0..49 for interleaved waveform,
%                                     (0..100)/(equivalent sampling) for EQU. */
%   Uchar            maxmem;       /* MAX MEMORY LENGTH	0:0.5k, 1:1k, 2:10k,
%                                     3:100k, 4:500k */
%   Ushort           MaskBank;     /* Mask for bank number */
% } XWAV_TDE_WAVEINF_TBASE;
%
% Sizes of the differnet bank numbers (bankNr):
% IWDP_ENM_BANKS = [8 16 32 64 128 256 512 1024 2*1024 4*1024 8*1024 ...
%      16*1024 32*1024 64*1024 128*1024 256*1024 512*1024 1048576 ...
%      2*1048576 4*1048576 Inf];
function [tbase] = load_XWAV_TDE_WAVEINF_TBASE(fid)
    global MAX_MEM_ENUM RLWJW_TDIV_ENUM
    tbase.delay = load_SVMNG_TDE_TRGDLY(fid);
    tbase.timeStamp = load_XWAV_TDE_TSTAMP(fid);
    tbase.bankNr = fread(fid, 1, 'uint32');
    tbase.memoryLength = fread(fid, 1, 'uint32');
    tbase.bankSize = fread(fid, 1, 'uint32');
    tbase.triggerSkew = fread(fid, 1, 'uint32');
    tbase.validWfmStart = fread(fid, 1, 'uint32');
    tbase.wfmMode = fread(fid, 1, 'uint16');
    tbase.nrAvgs = fread(fid, 1, 'uint16');
    tbase.tdivEnum = fread(fid, 1, 'uint8');
    tbase.tdiv = RLWJW_TDIV_ENUM(1 + tbase.tdivEnum);
    tbase.samplingClockEnum = fread(fid, 1, 'uint8');
    tbase.rndInit = fread(fid, 1, 'uint8');
    tbase.wavSkew = fread(fid, 1, 'uint8');
    tbase.maxMemory = MAX_MEM_ENUM(1 + fread(fid, 1, 'uint8'), :);
    tbase.bankMask = fread(fid, 1, 'uint16');
    fread(fid, 1, 'uint8');
end

%% load_SVMNG_TDE_TRGDLY
% // Trigger delay structure
% typedef struct {
%  Uint sgn;  // -1:-/0:+
%  Uint sec;  // 0?`750s     (1s?`750s)
%  Uint us;   // 0?`999999us (1us?`999ms)
%  Uint ps;   // 0?`999999ps (1ps?`999ns)
% } SVMNG_TDE_TRGDLY;
function [delay] = load_SVMNG_TDE_TRGDLY(fid)
    sgn = fread(fid, 1, 'uint32');
    sec = fread(fid, 1, 'uint32');
    us = fread(fid, 1, 'uint32');
    ps = fread(fid, 1, 'uint32');
    if sgn == 0
        delay = 1.0;
    else
        delay = -1.0;
    end
    delay = delay * (sec + 1e-6 * us + 1e-12 * ps);
end

%% load_XWAV_TDE_TSTAMP
% Load time stamp information.
%
% // Date structure
% typedef struct {
%   Ushort  year;
%   Uchar   month;
%   Uchar   day;
% } SVMNG_TDE_DATE;
%
% // Time structure
% typedef struct {
%   Uchar   hour;
%   Uchar   min;
%   Uchar   sec;
% } SVMNG_TDE_TIME;
%
% typedef struct {
%   SVMNG_TDE_DATE  date;   // DATE year:2000..2099, month:1..12, day:1..31
%   SVMNG_TDE_TIME  time;   // TIME hour:0..23, min:0..59, sec:0..59
%   Uchar           msec;   // 100ms
% } XWAV_TDE_TSTAMP;
function [tstamp] = load_XWAV_TDE_TSTAMP(fid)
    year = fread(fid, 1, 'uint16');
    month = fread(fid, 1, 'uint8');
    day = fread(fid, 1, 'uint8');
    hour = fread(fid, 1, 'uint8');
    min = fread(fid, 1, 'uint8');
    sec = fread(fid, 1, 'uint8');
    msec = 100 * fread(fid, 1, 'uint8');
    tstamp = [year month day hour min sec msec];
end

%% load_XWAV_TDE_WAVEINF_CH
% Load channel information for a single channel.
function [chs] = load_XWAV_TDE_WAVEINF_CH(fid)
    global RLWJW_VDIV_ENUM
    chs = struct('offset', {NaN NaN NaN NaN}, ...
        'vdivEnum', {NaN NaN NaN NaN}, ...
        'isValid', {false false false false});
    for i = 1:4
        chs(i).offset = fread(fid, 1, 'int32');
        chs(i).vdivEnum = fread(fid, 1, 'uint8');
        chs(i).vdiv = RLWJW_VDIV_ENUM(1 + chs(i).vdivEnum);
        chs(i).offset = chs(i).offset / 3200 * chs(i).vdiv;
        chs(i).isValid = (fread(fid, 1, 'uint8') > 0);
        chs(i).unknown = fread(fid, 1, 'uint16');
    end
end

%% Show information about the waveform(s)
function showInfo(wavinf, nfo, data)
    global RLWJW_XWAV_DEF_INF_NOACQ RLWJW_XWAV_DEF_INF_NORM
    global RLWJW_XWAV_DEF_INF_PEAK  RLWJW_XWAV_DEF_INF_EQU
    global RLWJW_XWAV_DEF_INF_AVG   RLWJW_XWAV_DEF_INF_ROLL
    global RLWJW_XWAV_DEF_INF_ILV
    fprintf('Time stamp: %04d-%02d-%02d %02d:%02d:%02d.%03d\n', ...
        wavinf.timebase.timeStamp);
    fprintf('Memory length: %d (max.mem %dk)\n', wavinf.timebase.memoryLength, ...
        wavinf.timebase.maxMemory(2)/1024);
    fprintf('Bank size: %d\n', wavinf.timebase.bankSize);
    fprintf('Waveform mode:');
    if wavinf.timebase.wfmMode == RLWJW_XWAV_DEF_INF_NOACQ
        fprintf(' not_acquired');
    else
        if bitand(wavinf.timebase.wfmMode, RLWJW_XWAV_DEF_INF_NORM)
            fprintf(' normal');
        end
        if bitand(wavinf.timebase.wfmMode, RLWJW_XWAV_DEF_INF_PEAK)
            fprintf(' peak');
        end
        if bitand(wavinf.timebase.wfmMode, RLWJW_XWAV_DEF_INF_EQU)
            fprintf(' equivalent_sampling');
        end
        if bitand(wavinf.timebase.wfmMode, RLWJW_XWAV_DEF_INF_AVG)
            fprintf(' averaged(%dx)', wavinf.timebase.nrAvgs);
        end
        if bitand(wavinf.timebase.wfmMode, RLWJW_XWAV_DEF_INF_ROLL)
            fprintf(' roll');
        end
        if bitand(wavinf.timebase.wfmMode, RLWJW_XWAV_DEF_INF_ILV)
            fprintf(' interleaved');
        end
    end
    fprintf('\n');
    fprintf('Hor. resolution: %g s/div (%d)\n', wavinf.timebase.tdiv, ...
        wavinf.timebase.tdivEnum);
    fprintf('Trigger delay: %g s\n', wavinf.timebase.delay);
    fprintf('Valid wfm start: %d\n', wavinf.timebase.validWfmStart);

    fprintf('                    Channel 1  Channel 2  Channel 3  Channel 4 \n');
    fprintf('offset         (V)  %9g  %9g  %9g  %9g\n', wavinf.channels.offset);
    fprintf('resolution (V/div)  %9g  %9g  %9g  %9g\n', wavinf.channels.vdiv);
    fprintf('channel on or off?  %9g  %9g  %9g  %9g\n', wavinf.channels.isValid);
    fprintf('unknown             %9d  %9d  %9d  %9d\n', wavinf.channels.unknown);

    xf = (wavinf.timebase.memoryLength) * nfo.dx + nfo.x0;
    t = linspace(nfo.x0, xf, wavinf.timebase.memoryLength + 1);
    figure;
    plot(t, data);
    grid on;
    xlabel('Time (s)');
end  % end of showInfo function


function testbed_stationplot(Q, varargin)

options = struct(...
    'stations', 1:size(Q.W,1), ...
    'linespec', 'x');

% Check arguments
[options, errmsg, remopts] = argparse(options, varargin{:});
error(errmsg);

mapplot(Q.options.user_data.coordinates(options.stations,1:2)', options.linespec, ...
        remopts{:});


% Choose a png file from the internet that represents something from your
% home country, your life or just something you generally like, and plot
% its polyline silhouette.


function [vol, ext, endian] = er_ldtvolume(stem,ext)
% [vol ext endian] = er_ldtvolume(stem,<ext>)
%
% Loads a volume in tSeries format and returns a 4D structure
% of dimension Nslices X Nrows X Ncols X Ndepth (where Ndepth = # of
% temporal frames).
%
% stem should be the path where a bunch of tSeries are stored. E.g.:
% stem = 'X:\mri\mySession\Inplane\Original\tSeries\Scan1'. Within this
% directory the code looks for files named 'tSeries[#].mat', the default
% format for mrLoadRet.
%
% 'ext' is currently a dummy param, but since some older tSeries are saved
% as .dat files, maybe I'll make it work.
%
% '$Id: er_ldtvolume.m,v 1.1 2004/03/11 01:29:55 sayres Exp $'
%
% 06/18/03 ras: created from fmri_ldbvolume in an attempt to integrate
% fsfast into mrLoadRet.

vol = [];
ext = 'tSeries';
endian = 0;

if(nargin ~= 1 & nargin ~= 2)
  fprintf(2,'USAGE: er_ldtvolume(stem,<ext>)\n');
  qoe; error; return;
end

% First, check whether tSeries are in stem path %
test = filterdir('tSeries',stem);
if isempty(test)
    fprintf(2,'Couldn''t find any tSeries in specified path!!!');
    qoe; error; return;
end

% count slices
nslices = size(test);

% fprintf('er_ldtvolume: found %d slices\n',nslices);

% concatenate into volume
for slice = 1:nslices
  % fprintf('Loading Slice %3d\n',slice);
  fname = fullfile(stem,['tSeries' num2str(slice) '.mat']);

  if ~exist(fname,'file')
      warning(['Could not find file ', fname]);
  end

  z = er_ldtfile(fname);
  if(size(z,1) == 1 & size(z,3) == 1)
    vol(slice,:,:)  = z;
  else
    vol(slice,:,:,:) = z;
  end
end

return;


function [val] = filetype_check_extension(filename, ext)

% FILETYPE_CHECK_EXTENSION helper function to determine the file type
% by performing a case insensitive string comparison of the extension.

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

% these are for speeding up subsequent calls with the same input arguments
persistent previous_argin previous_argout

current_argin = {filename, ext};
if isequal(current_argin, previous_argin)
  % don't do the detection again, but return the previous value from cache
  val = previous_argout;
  return
end

if iscell(filename)
  % compare the extension of multiple files
  val = zeros(size(filename));
  for i=1:length(filename)
    val(i) = filetype_check_extension(filename{i}, ext);
  end
elseif iscell(ext)
  val = zeros(size(ext));
  for i=1:length(ext)
    val(i) = filetype_check_extension(filename, ext{i});
  end
else
  % compare the extension of a single file
  if numel(filename)<numel(ext)
    val = false;
  else
    val = strcmpi(filename((end-length(ext)+1):end), ext);
  end
end

% remember the current input and output arguments, so that they can be
% reused on a subsequent call in case the same input argument is given
current_argout  = val;
previous_argin  = current_argin;
previous_argout = current_argout;

return % main()


function L = ge(p1,p2)
%PREAL/GE Overloaded GE (>=) operator for class preal.

global useUnitsFlag

if ~(useUnitsFlag) % If physunits is disabled...
    L=ge(double(p1),double(p2)); % ... treat as double.
    return
end

p1=preal(p1);
p2=preal(p2);
tol=0.001;
if isscalar(p1)
    p1=preal(p1.value*ones(size(p2)),p1.units);
elseif isscalar(p2)
    p2=preal(p2.value*ones(size(p1)),p2.units);
elseif ndims(p1)==ndims(p2)&size(p1)==size(p2)
    % do nothing
else
    error('Array dimensions must agree')
end

L=false(size(p1));
for k=1:numel(L)
    if any(abs(p1(k).units-p2(k).units)>tol)
        error('Attempt to compare dimensionally inconsistent preals')
    end
    L(k)=ge(p1(k).value,p2(k).value);
end


%Run only this main program. No need to run the other functions separately
clear; clc;
DEPSK_mrc(1);  %performance of DEPSK by 1 Rx antenna
hold on;
clear; clc;
DEPSK_mrc(2);  %performance of DEPSK by 2 Rx antenna
hold on;
clear; clc;
BPSK_mrc(1);  %performance of BPSK by 1 Rx antenna
hold on;
clear; clc;
BPSK_mrc(2);  %performance of BPSK by 2 Rx antenna


function model = changelssvm(model,option, value)
% Change a field of the object oriented representation of the LS-SVM
%
%
% The different options of the fields are given in following table:
%
%     1. General options representing the kind of model:
%
%           type: 'classifier' ,'function estimation'
% implementation: 'CMEX' ,'CFILE' ,'MATLAB'
%         status: Status of this model ('trained'  or 'changed' )
%          alpha: Support values of the trained LS-SVM model
%              b: Bias term of the trained LS-SVM model
%       duration: Number of seconds the training lasts
%         latent: Returning latent variables ('no' ,'yes' )
%       x_delays: Number of delays of eXogeneous variables (by default 0 )
%       y_delays: Number of delays of responses (by default 0 )
%          steps: Number of steps to predict (by default 1 )
%            gam: Regularisation parameter
%    kernel_type: Kernel function
%    kernel_pars: Extra parameters of the kernel function
%
%
%     2. Fields used to specify the used training data:
%
%    x_dim: Dimension of input space
%    y_dim: Dimension of responses
%  nb_data: Number of training data
%   xtrain: (preprocessed) inputs of training data
%   ytrain: (preprocessed,coded) outputs of training data
% selector: Indexes of training data effectively used during training
%
%
%     3. Options used in the Conjugate Gradient (CG) algorithm:
%
%     cga_max_itr: Maximum number of iterations in CG
%         cga_eps: Stopcriterium of CG, largest allowed error
%    cga_fi_bound: Stopcriterium of CG, smallest allowed improvement
%        cga_show: Show the results of the CG algorithm (1 or 0)
% cga_startvalues: Starting values of the CG algorithm
%
%
%     4. Fields with the information for pre- and post-processing (only given if appropriate):
%
%  preprocess: 'preprocess'  or 'original'
%     schemed: Status of the preprocessing
%               ('coded' ,'original'  or 'schemed' )
% pre_xscheme: Scheme used for preprocessing the input data
% pre_yscheme: Scheme used for preprocessing the output data
%   pre_xmean: Mean of the input data
%    pre_xstd: Standard deviation of the input data
%   pre_ymean: Mean of the responses
%    pre_ystd: Standard deviation of the reponses
%
%
%     5. The specifications of the used encoding (only given if appropriate):
%
%          code: Status of the coding
%                 ('original' ,'changed'  or 'encoded')
%      codetype: Used function for constructing the encoding
%                  for multiclass classification (by default 'none')
% codetype_args: Arguments of the codetype function
%  codedist_fct: Function used to calculate to which class a
%                coded result belongs
% codedist_args: Arguments of the codedist function
%     codebook2: Codebook of the new coding
%     codebook1: Codebook of the original coding
%
% Full syntax
%
% >> model = changelssvm(model, field, value)
%
%       Outputs
%         model(*) : Obtained object oriented representation of the LS-SVM model
%       Inputs
%         model    : Original object oriented representation of the LS-SVM model
%         field    : Field of the model one wants to change (e.g. 'preprocess')
%         value    : New value of the field of the model one wants to change
%
% See also:
%   trainlssvm, initlssvm, simlssvm, plotlssvm.

% Copyright (c) 2010,  KULeuven-ESAT-SCD, License & help @ http://www.esat.kuleuven.ac.be/sista/lssvmlab

%
% alias sigma^2
%
if (strcmpi(option,'sig2')) option = 'kernel_pars'; end

%
% selector -> nb_data
% nb_data -> selector
%
if strcmp(option,'selector'),
  model.nb_data = length(value);
end
if strcmp(option,'nb_data'),
  model.selector = 1:value;
end

%
% xtrain
%
if strcmp(option,'xtrain'),
  [nb,model.x_dim] = size(value);
  model.nb_data = nb;%min(nb,model.nb_data);
  model.selector = 1:model.nb_data;
  if length(model.gam)>model.y_dim & length(model.gam)~=size(value,1),
    warning('Discarting  different gamma''s...');
    model.gam = max(model.gam);
  end
    eval('value=prelssvm(model,value);',...
       'warning(''new trainings inputdata not comform with used preprocessing'');');
end

%
% ytrain
%
if strcmp(option,'ytrain'),
  if size(value,2)~=size(model.ytrain,2),
    model.y_dim = size(value,2);
  end
  eval('value = codelssvm(model,[],value);',...
       'warning(''new trainings outputdata not comform with used encoding;'');');
  eval('[ff,value] = prelssvm(model,[],value);',...
       'warning(''new trainings outputdata not comform with used preprocessing;'');');
  [nb,model.y_dim] = size(value);
  model.nb_data = min(nb,model.nb_data);
  model.selector = 1:model.nb_data;
end

%
% switch between preprocessing - original data
% model.prestatus = {'changed','ok'}
%
if (strcmpi(option,'preprocess')) & model.preprocess(1)~=value(1),
  model.prestatus = 'changed';
end

%
% change coding
%
if strcmpi(option,'codetype') | strcmpi(option,'codebook2') | ...
      strcmpi(option, 'codeargs') | strcmpi(option, 'codedistfct'),
  model.code = 'changed';
elseif  strcmpi(option,'codebook1'),
  warning('change original format of the classifier; the toolbox will be unable to return results in the original format');
end

%
% final change
%
eval(['old_value = model.' lower(option) ';'],'old_value=[];');
eval(['model.' lower(option) '=value;']);

if (isempty(value) | isempty(old_value)),
  different = 1;
else
  eval('different = any(old_value~=value);','different=1;');
end

if different & ~strcmpi(option,'implementation'),
  model.status = 'changed';
end


% DEMO_MATLAB: Examples of MATLAB-Python integration.
%
% FUNCTIONS:
%    - demo_matlab.py : Original Python example
%    - demo_matlab.m  : Call demo_matlab.py from Matlab
%    - demo_matlab.m  : Reproduce demo_matlab.py with Matlab calls
%
% REFERENCES
%    - Installation: https://neuroimage.usc.edu/brainstorm/MnePython
%    - Dataset: https://neuroimage.usc.edu/brainstorm/Tutorials/MedianNerveCtf
%
% AUTHORS:
%    - Python version: Mainak Jas <mainak.jas@telecom-paristech.fr>
%    - Matlab version: Francois Tadel, 2018-2020

% Initialize Brainstorm-Python
bst_python_init('Initialize', 1);

% Get test dataset
try
    data_path = py.mne.datasets.brainstorm.bst_raw.data_path();
catch
    disp([10 'MATLAB does not support the use of Python function input().' 10 ...
        'You must download the dataset manually from a Python terminal:' 10 ...
        '>>> import mne' 10 ...
        '>>> mne.datasets.brainstorm.bst_raw.data_path()' 10 10]);
end

% Read CTF dataset
raw_fname = fullfile(char(data_path), 'MEG', 'bst_raw', 'subj001_somatosensory_20111109_01_AUX-f.ds');
raw = py.mne.io.read_raw_ctf(raw_fname, pyargs('preload', true));
% Plot raw data
pyFig = raw.plot();
% Change the color of the first axes of the figure
pyAxes = pyFig.get_axes();
pyAxes{1}.set_facecolor({0,1,0});

% Set EOG channel
raw.set_channel_types(py.dict(pyargs('EEG058', 'eog')));
% Alternative syntax using the automatic conversion struct<=>dict
raw.set_channel_types(struct('EEG058', 'eog'));

% Show power line interference
raw.plot_psd();
% Notch filter: 60Hz
% raw.notch_filter(py.numpy.arange(60, 181, 60));

% Read events
events = py.mne.find_events(raw, pyargs('stim_channel', 'UPPT001'));
event_id = uint8(2);    % Right-hand somato

% Pick MEG channels
picks = py.mne.pick_types(raw.info, pyargs('meg', true, 'eeg', false, 'stim', false, 'eog', true, 'exclude', 'bads'));

% Compute epochs: [-100, +300]ms
epochs = py.mne.Epochs(raw, events, event_id, -0.1, 0.3, pyargs(...
    'picks',     picks, ...
    'baseline',  py.tuple({py.None, 0}), ...
    'reject',    py.dict(pyargs('mag', 4e-12, 'eog', 250e-6)), ...
    'preload',   false));

% Compute evoked
evoked = epochs.average();

% Fix stim artifact
py.mne.preprocessing.fix_stim_artifact(evoked);

% Correct delays due to hardware (stim artifact is at 4 ms)
evoked.shift_time(-0.004);

% Plot the result
evoked.plot();
evoked.plot_topomap(pyargs('times', py.numpy.array({0.016, 0.030, 0.060, 0.070})));


% POP_RMDAT - Keep or remove continuous data around specific events
%
% Usage:
%   >> OUTEEG = pop_rmdat( EEG); % pop-up a data entry window
%   >> OUTEEG = pop_rmdat( EEG, typerange, timelimits, invertselection);
%
% Graphic interface:
%   "Time-locking event type(s)" - [edit box] Select 'Edit > Event values'
%                to see a list of event.type values; else use the push button.
%                To use event types containing spaces, enter in single-quotes.
%   "..."      - [push button] scroll event types.
%   "Time limits" - [edit box] epoch latency range [start, end] in seconds relative
%                to the event type latency.
%
% Inputs:
%   EEG        - Input dataset. Data may already be epoched; in this case,
%                extract (shorter) subepochs time locked to epoch events.
%   typerange  - Cell array of event types to time lock to.
%                (Note: An event field called 'type' must be defined in
%                the 'EEG.event' structure).
%   timelimits - Epoch latency limits [start end] in seconds relative to the time-locking event
%                {default: [-1 2]}%
%   invertselection - [0|1] Invert selection. 0 is to keep data around events
%                and 1 is to remove them {default:1 to remove them}
%
% Outputs:
%   OUTEEG     - output dataset
%
% Authors: Arnaud Delorme, SCCN, INC, UCSD, 2009-

% Copyright (C) 2001 Arnaud Delorme, Salk Institute, arno@salk.edu
%
% This file is part of EEGLAB, see http://www.eeglab.org
% for the documentation and details.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are met:
%
% 1. Redistributions of source code must retain the above copyright notice,
% this list of conditions and the following disclaimer.
%
% 2. Redistributions in binary form must reproduce the above copyright notice,
% this list of conditions and the following disclaimer in the documentation
% and/or other materials provided with the distribution.
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
% THE POSSIBILITY OF SUCH DAMAGE.

function [EEG, com] = pop_rmdat( EEG, events, timelims, invertsel )

if nargin < 1
   help pop_rmdat;
	return;
end
com = '';
if nargin < 4
    invertsel = 1;
    warning('This function behavior has been fixed and data is removed by default')
end
if isempty(EEG(1).event)
    error( [ 'No event. This function removes data' 10 'based on event latencies' ]);
end
if isempty(EEG(1).trials)
    error( [ 'This function only works with continuous data' ]);
end
if ~isfield(EEG(1).event, 'latency')
    error( 'Absent latency field in event array/structure: must name one of the fields ''latency''');
end

if nargin < 3
	% popup window parameters
	% -----------------------
   promptstr    = { strvcat('Time-locking event type(s) ([]=all):', ...
                    'Select ''Edit > Event values'' to see type values.'), ...
                    'Epoch limits [start, end] in seconds:', ...
                    'Name for the new dataset:', ...
					'Out-of-bounds EEG rejection limits ([min max], []=none):'  };

   cbevent = ['tmpEEG = get(gcbf, ''userdata'');' ...
           'if ~isfield(tmpEEG.event, ''type'')' ...
				   '   errordlg2(''No type field'');' ...
				   'else' ...
                   '   tmpevent = tmpEEG.event;' ...
                   '   if isnumeric(tmpEEG.event(1).type),' ...
				   '        [tmps,tmpstr] = pop_chansel(unique([ tmpevent.type ]));' ...
				   '   else,' ...
                   '        [tmps,tmpstr] = pop_chansel(unique({ tmpevent.type }));' ...
                   '   end;' ...
				   '   if ~isempty(tmps)' ...
				   '       set(findobj(''parent'', gcbf, ''tag'', ''events''), ''string'', tmpstr);' ...
				   '   end;' ...
				   'end;' ...
				   'clear tmpEEG tmps tmpv tmpstr tmpevent tmpfieldnames;' ];

   geometry = { [2 1 1.2] [2 1 1.2] };
   uilist = { { 'style' 'text'       'string' 'Event type(s) ([]=all)' } ...
              { 'style' 'edit'       'string' '' 'tag' 'events' } ...
              { 'style' 'pushbutton' 'string' '...' 'callback' cbevent } ...
              { 'style' 'text'       'string' 'Time limits [start, end] in sec.' } ...
              { 'style' 'edit'       'string' '-1 1' } ...
              { 'style' 'popupmenu'  'string' 'Keep selected|Remove selected' } };

   result = inputgui( 'geometry', geometry, 'uilist', uilist, 'helpcom', 'pophelp(''pop_rmdat'')', 'title', 'Remove data portions around events - pop_rmdat()', 'userdata', EEG);
   if isempty(result) return; end

   if strcmpi(result{1}, '[]'), result{1} = ''; end
   if ~isempty(result{1})
       if strcmpi(result{1}(1),'''')   % If event type appears to be in single-quotes, use comma
                                       % and single-quote as delimiter between event types. toby 2.24.2006
                                       % fixed Arnaud May 2006
            events = eval( [ '{' result{1} '}' ] );
       else events = parsetxt( result{1});
       end
   else events = {};
   end
   timelims = eval( [ '[' result{2} ']' ] );
   invertsel = result{3}-1;

end

% process multiple datasets
% -------------------------
if length(EEG) > 1
    if nargin < 3
        [ EEG, com ] = eeg_eval( 'pop_rmdat', EEG, 'warning', 'on', 'params', { events, timelims, invertsel } );
    else
        [ EEG, com ] = eeg_eval( 'pop_rmdat', EEG, 'params', { events, timelims, invertsel } );
    end
    return;
end

tmpevent = EEG.event;

% Checking for numeric values in fieldnames and changing them to string
 for i = 1: length(tmpevent)
     checknum(i) = isnumeric(tmpevent(i).type);
 end
  if sum(checknum)~=0
       tmpindx = find(checknum == 1);
       for i = 1: length(tmpindx)
           tmpevent(tmpindx(i)).type = num2str(tmpevent(tmpindx(i)).type);
       end
  end

% compute event indices
% ---------------------
allinds = [];
for index = 1:length(events)
    inds = strmatch(events{index},{ tmpevent.type }, 'exact');
    allinds = [allinds(:); inds(:) ]';
end
allinds = sort(allinds);
if isempty(allinds)
    disp('No event found');
    return;
end

% compute time limits
% -------------------
array = [];
bnd = strmatch('boundary', lower({tmpevent.type }));
bndlat = [ tmpevent(bnd).latency ];
for bind = 1:length(allinds)
    evtlat = EEG.event(allinds(bind)).latency;
    evtbeg = evtlat+EEG.srate*timelims(1);
    evtend = evtlat+EEG.srate*timelims(2);
    if any(bndlat > evtbeg & bndlat < evtend)
        % find the closer upper and lower boundaries
        bndlattmp = bndlat(bndlat > evtbeg & bndlat < evtend);
        diffbound = bndlattmp-evtlat;
        allneginds = find(diffbound < 0);
        allposinds = find(diffbound > 0);
        if ~isempty(allneginds), evtbeg = bndlattmp(allneginds(1)); end
        if ~isempty(allposinds), evtend = bndlattmp(allposinds(1)); end;
        fprintf('Boundary found: time limits for event %d reduced from %3.2f to %3.2f\n', allinds(bind), ...
            (evtbeg-evtlat)/EEG.srate, (evtend-evtlat)/EEG.srate);
    end
    if ~isempty(array) && evtbeg < array(end)
        array(end) = evtend;
    else
        array = [ array; evtbeg  evtend];
    end
end

if ~isempty(array) && array(1) < 1, array(1) = 1; end
if ~isempty(array) && array(end) > EEG.pnts, array(end) = EEG.pnts; end
if isempty(array)
    disp('No event found');
    return;
end

if invertsel
    EEG = pop_select(EEG, 'notime', (array-1)/EEG.srate);
else
    EEG = pop_select(EEG, 'time', (array-1)/EEG.srate);
end

% generate output command
% -----------------------
com = sprintf('EEG = pop_rmdat( EEG, %s);', vararg2str( { events timelims invertsel } ));


%DELLABLIST Delete a label list from dataset
%
%	B = DELLABLIST(A,LABLISTNAME)
%	B = DELLABLIST(A,LABLISTNUMBER)
%
% INPUT
%   A              - Dataset
%   LABLISTNAME    - String to identify the label list to be deleted
%   LABLISTNUMBER  - Number to identify the label list to be deleted
%
% OUTPUT
%   B              - Dataset
%
% DESCRIPTION
% In the multi-label system for datasets, additional labellings can be
% added by ADDLABELS. This is stored in the LABLIST and NLAB fields of
% the dataset. By this command, DELLABLIST such a labeling can be removed.
%
% SEE ALSO (PRTools Guide)
% DATASETS, MULTI_LABELING, ADDLABELS, ADDLABLIST, CHANGELABLIST, CURLABLIST


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

%%
clear; close all; clc;

%% Syntax
% |hf=gtitle(textString,);|

%% Description
% The |gtitle| function can be used to create a title at the top of a
% figure window. The title is tied to the figure rather than any axes and
% can therefore be combined with figures with multiple subplots.

%% Examples

%%
% Settings
titleString='Title on top'; %The title string
fontSize=25; %The desired font size

%%
% Visualize something with a title
hf=cFigure;

hText=gtitle(titleString,fontSize,hf); %Create the title

surf(peaks(25));
colormap(gjet(250));
axisGeom;
camlight headlight;
drawnow;

%%
%
% <<gibbVerySmall.gif>>
%
% _*GIBBON*_
% <www.gibboncode.org>
%
% _Kevin Mattheus Moerman_, <gibbon.toolbox@gmail.com>

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


%  pageify -- turn databases into one db with one observation and many pages
%
%  ::
%
%
%    db=pageify(pivot_date,varargin)
%
%  Args:
%
%     - **pivot_date** [char|serial date] : reference date, typically end of
%     history.
%
%     - **varargin** [struct|ts] : databases in time series format or in struct
%
%     format
%
%  Returns:
%     :
%
%     - **db** [ts] : time series with one observation and many pages
%
%  Note:
%
%     - This routine is useful for preparing data for conditional forecasting
%
%  Example:
%
%     See also:
%