clc;
clear;
close all;

typesOfEvents   = {'FF','UF','RO'};
noTypesOfEvents = length(typesOfEvents);

% Choose a type of event
idEvent          = 1;  % 'FF','UF',or 'RO'

% Choose a subject of interest
idSubject        = 1; %1-15

%IR: 1,5,4,7,9
%APNEA: 2,11,12,13,14  
%HEALTHY: 3,6,8,10,15
%% Manually check the positions of all electrodes
% load('16elec_realigned.mat','elec_realigned'); % electrode configuration aligned 
% to the MNI coordinate system load('16Channels_head_bemcp_model.mat'); % Realistic 
% head model cfg = []; cfg.method = 'interactive'; cfg.elec = elec_realigned; 
% cfg.headshape = headmodel.bnd(3); % 3: Scalp, 2: Skull, 1: Brain temp = ft_electroderealign(cfg); 
%% Load a target data file
%%
eventInterest = typesOfEvents{idEvent};
targetDataFolder = 'U:\BestResearch\Early Diagnostic Tool for AD\Matlab\FortheTeam\DataFiles\RubiDataFolderLatestParadigm\All Dat Files\';
dataFiles = dir(strcat(targetDataFolder,'Subject*',eventInterest,'.mat'));
ftDataFileName  = dataFiles(idSubject).name; 
load(ftDataFileName,'dataFT');
%% Obtain the channel-by-channel averaged ERPs
% cfg = []; cfg.channel = {'all'}; erpAvg = ft_timelockanalysis(cfg,dataFT);
% 
% load('16Channels_layout.mat'); % Layout to plot 16 channels in one figure 
% cfg = []; cfg.layout = layout; cfg.showlabels = 'yes'; cfg.fontsize = 6; figure; 
% ft_multiplotER(cfg,erpAvg);
%% Scalp current density analysis
%%
load('16elec_realigned.mat','elec_realigned'); % electrode configuration aligned to the MNI coordinate system
cfg                 = [];
cfg.method          = 'finite';
cfg.elec            = elec_realigned;
cfg.trials          = 'all';
cfg.feedback        = 'text';
cfg.conductivity    = 1/3;
cfg.lambda          = 1e-05;
cfg.order           = 4;
cfg.degree          = 9;         % value 9 for 32 or less channels
erpAvgSCD           = ft_scalpcurrentdensity(cfg,erpAvg);

% for ct = 1:8
%     cfg                 = [];
%     cfg.layout          = layout;
%     cfg.xlim            = [(ct-1) ct]*0.1;
%     cfg.colorbar        = 'yes';
%     cfg.marker          = 'labels';    
%     figure;
%     ft_topoplotER(cfg,erpAvgSCD);
% end

% For Caroline
cfg                 = [];
cfg.layout          = layout;
cfg.xlim            = [0.2 0.4]; % Adjust this time-window to see what works the best
cfg.colorbar        = 'yes';
cfg.marker          = 'labels';    
figure;
ft_topoplotER(cfg,erpAvgSCD);