% EEGLAB functions used for data preprocessing

% load raw dataset
EEG = pop_loadset('filename',loadname,'filepath',[cartella]);

% resample if necessary
if EEG.srate > 250
    EEG = pop_resample( EEG, 250);
end

% hpf 1Hz
EEG = pop_firws(EEG, 'fcutoff', 1, 'ftype', 'highpass', 'wtype', 'hamming', 'forder', 1100, 'minphase', 0, 'usefftfilt', 0, 'plotfresp', 0, 'causal', 0); % onepass-zerophase, order 1100, hamming-windowed sinc FIR cutoff (-6 dB) 1 Hz transition width 0.7 Hz, stopband 0-0.6 Hz, passband 1.4-125 H max. passband deviation 0.0022 (0.22%), stopband attenuation -53 dB
% lpf 47Hz
EEG = pop_firws(EEG, 'fcutoff', 47, 'ftype', 'lowpass', 'wtype', 'blackman', 'forder', 1376, 'minphase', 0, 'usefftfilt', 0, 'plotfresp', 0, 'causal', 0); % onepass-zerophase, order 1376, blackman-windowed sinc FIR cutoff (-6 dB) 47 Hz transition width 1.0 Hz, passband 0-46.5 Hz, stopband 47.5-125 Hz max. passband deviation 0.0002 (0.02%), stopband attenuation -74 dB

% for the 64 electrode cap
% eye channels removal 
EEG = pop_select( EEG, 'nochannel',{'E61','E62','E63','E64','E1001','E65'});

% for the 128 electrode cap
% selection of the 60 channels of interest
EEG = pop_select( EEG, 'channel',{'E1','E3','E4','E6','E9','E11','E13','E16','E19','E22','E23','E24','E27','E28','E29','E30','E32','E33','E34','E36','E37','E41','E44','E45','E46','E47','E51','E52','E57','E58','E60','E62','E64','E67','E70','E72','E75','E77','E83','E85','E87','E92','E95','E96','E97','E98','E100','E102','E103','E104','E105','E108','E111','E112','E114','E116','E117','E122','E123','E124'});

% bad data points and channels removal
EEG = pop_clean_rawdata(EEG, 'FlatlineCriterion',5,'ChannelCriterion',0.8,'LineNoiseCriterion',4,'Highpass','off','BurstCriterion',20,'WindowCriterion',0.25,'BurstRejection','on','Distance','Euclidian','WindowCriterionTolerances',[-Inf 7] );

% bad channels interpolation
EEG = pop_interp(EEG, originalEEG.chanlocs, 'spherical');

% average rereference   
EEG.nbchan = EEG.nbchan+1;
EEG.data(end+1,:) = zeros(1, EEG.pnts);
EEG.chanlocs(1,EEG.nbchan).labels = 'initialReference';
EEG = pop_reref(EEG, []);
EEG = pop_select( EEG,'nochannel',{'initialReference'});

% ICA
r = rank(EEG.data(:,:));
EEG = pop_runica(EEG, 'icatype', 'runica', 'extended',1,'interrupt','on','pca',r);

% identification and removal of artefactual ICs
EEG = pop_iclabel(EEG, 'default');
[ALLEEG EEG] = eeg_store(ALLEEG, EEG, CURRENTSET);
EEG = eeg_checkset( EEG );
EEG = pop_icflag(EEG, [NaN NaN;0.8 1;0.8 1;NaN NaN;NaN NaN;0.8 1;0.8 1]);
EEG = pop_subcomp( EEG, find(EEG.reject.gcompreject == 1), 0);

