filename1 = 'sub02-eyesopen.xdf';
filename2 = 'sub02-eyesclosed.xdf';

eyesopen = xdf2fieldtrip(filename1);
eyesclosed = xdf2fieldtrip(filename2);

%%

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

% normalize the time axes
eyesopen.time{1}   = (1:numel(eyesopen.time{1}))   * 0.004 - 0.004;
eyesclosed.time{1} = (1:numel(eyesclosed.time{1})) * 0.004 - 0.004;

%%

cfg = [];
cfg.ylim = [-50 50];
cfg.blocksize = 10;
cfg.preproc.demean = 'yes';
cfg.preproc.lpfilter = 'yes';
cfg.preproc.lpfreq = 48;
ft_databrowser(cfg, eyesopen);

%%

ft_databrowser(cfg, eyesclosed);

%%

cfg = [];
cfg.demean = 'yes';
% cfg.reref = 'yes';
% cfg.refchannel = {'T7', 'T8'};
cfg.lpfilter = 'yes';
cfg.lpfreq = 48;

eyesopen_preproc = ft_preprocessing(cfg, eyesopen);
eyesclosed_preproc = ft_preprocessing(cfg, eyesclosed);

%%

cfg = [];
cfg.length = 1;
cfg.overlap = 0.5;
eyesopen_segmented = ft_redefinetrial(cfg, eyesopen_preproc);
eyesclosed_segmented = ft_redefinetrial(cfg, eyesclosed_preproc);

%%

cfg = [];
cfg.method = 'summary';
cfg.metric = 'std';
eyesopen_clean = ft_rejectvisual(cfg, eyesopen_segmented);
eyesclosed_clean = ft_rejectvisual(cfg, eyesclosed_segmented);

%%

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

[cfg, artifact] = ft_badsegment(cfg, eyesopen_segmented);
eyesopen_clean = ft_rejectartifact(cfg, eyesopen_segmented);

[cfg, artifact] = ft_badsegment(cfg, eyesclosed_segmented);
eyesclosed_clean = ft_rejectartifact(cfg, eyesclosed_segmented);

%%

eyesopen_segmented = eyesopen_clean;
eyesclosed_segmented = eyesclosed_clean;

%%

cfg = [];
cfg.method = 'mtmfft';
cfg.taper = 'hanning';
eyesopen_freq = ft_freqanalysis(cfg, eyesopen_segmented);
eyesclosed_freq = ft_freqanalysis(cfg, eyesclosed_segmented);

%%

cfg = [];
cfg.layout = 'elec1010';
cfg.xlim = [0 30];
ft_multiplotER(cfg, eyesopen_freq, eyesclosed_freq)

%%

cfg = [];
cfg.parameter = 'powspctrm';
cfg.operation = 'eps + 10*log10(x1)';
eyesopen_freq_db = ft_math(cfg, eyesopen_freq);
eyesclosed_freq_db = ft_math(cfg, eyesclosed_freq);

%%

figure

cfg = [];
cfg.layout = 'elec1010';
cfg.xlim = [8 12];
cfg.zlim = [-8 8];

cfg.figure = subplot(1,2,1);
cfg.title = 'eyes open';
ft_topoplotER(cfg, eyesopen_freq_db)

cfg.figure = subplot(1,2,2);
cfg.title = 'eyes closed';
ft_topoplotER(cfg, eyesclosed_freq_db)
