filename = 'sub02-visual.xdf';

[data, event] = xdf2fieldtrip(filename);

%%

% normalize the EEG channel names
for i=1:24
  data.label{i} = strrep(data.label{i},'EEG_','');
end

%%

for i=1:150
  event(i).sample = (event(i).timestamp - data.hdr.FirstTimeStamp) / data.hdr.TimeStampPerSample;
  event(i).sample = round(event(i).sample);
end

%%

disp({event.value}');

%%

sample = [event.sample];
time = sample / 250;
trigger = nan(1,150);

for i=1:150
  if event(i).value == 's'
    trigger(i) = 1;
  elseif event(i).value == 'd'
    trigger(i) = 2;
  end
end

plot(time, trigger, 'x')
ylim([0.8 2.2]);

%%

cfg = [];
cfg.event = event;
cfg.hdr = data.hdr;
cfg.trialdef.eventtype = 'EEG';
cfg.trialdef.eventvalue = {'s', 'd'};
cfg.trialdef.prestim = 0.2;
cfg.trialdef.poststim = 0.6;
cfg = ft_definetrial(cfg);

trl = cfg.trl;

%%

cfg = [];
cfg.reref = 'yes';
cfg.refchannel = {'M1', 'M2'};
cfg.lpfilter = 'yes';
cfg.lpfreq = 30;
cfg.hpfilter = 'yes';
cfg.hpfreq = 0.5;

data_preproc = ft_preprocessing(cfg, data);

%%

cfg = [];
cfg.trl = trl;
data_segmented = ft_redefinetrial(cfg, data_preproc);

%%

cfg = [];
cfg.continuous = 'yes';
cfg.blocksize = 10;
cfg.ylim = [-50 50];
% cfg.preproc.demean = 'yes';
ft_databrowser(cfg, data_segmented)

cfg = [];
cfg.demean = 'yes';
data_segmented = ft_preprocessing(cfg, data_segmented);

%%

cfg = []; 
cfg.method = 'summary';
cfg.metric = 'std';
data_clean = ft_rejectvisual(cfg, data_segmented);

%%

cfg = [];
cfg.metric = 'std';
cfg.threshold = 15;

[cfg, artifact] = ft_badsegment(cfg, data_segmented);
data_clean = ft_rejectartifact(cfg, data_segmented);

%%

data_segmented = data_clean;

%%

cfg = [];
erp_all = ft_timelockanalysis(cfg, data_segmented);

%%

cfg = [];
cfg.layout = 'elec1010';
cfg.ylim = [-8 8];
ft_multiplotER(cfg, erp_all)

%%

cfg = [];

cfg.trials = strcmp(data_segmented.trialinfo.eventvalue, 's');
fprintf('selected %d trials\n', sum(cfg.trials));
erp_standard = ft_timelockanalysis(cfg, data_segmented);

cfg.trials = strcmp(data_segmented.trialinfo.eventvalue, 'd');
fprintf('selected %d trials\n', sum(cfg.trials));
erp_deviant = ft_timelockanalysis(cfg, data_segmented);

%%

cfg = [];
cfg.layout = 'elec1010';
ft_multiplotER(cfg, erp_standard, erp_deviant)

%%

figure
plot(erp_deviant.time, erp_deviant.avg, 'r');
hold on
plot(erp_standard.time, erp_standard.avg, 'b');

%%

cfg = [];
cfg.parameter = 'avg';
cfg.operation = 'x1 - x2';
erp_difference = ft_math(cfg, erp_deviant, erp_standard);

%%

cfg = [];
cfg.layout = 'elec1010';
ft_multiplotER(cfg, erp_difference)

%%

cfg = [];
cfg.layout = 'elec1010';
cfg.xlim = [0.14 0.16];
cfg.zlim = [-8 8];
cfg.colormap = '-RdBu';
ft_topoplotER(cfg, erp_difference)
