clc
clear all
%% readme
% Before using this script, you must make a new folder and put all set
% files of all subjects you are going to preprocess into it.
% And make sure that none subfolder is in it.
% Note that the EEGLab version should be 13.3.2 or newer
% This script includes the following 3 preprocessing steps:
% 1. Remove bad (select good) channels
% 2. Resample % 250Hz proposed
% 3. Filter (bandpass and bandstop) % The orders of fileters are
%    automatically determined according to the sample rate of 250Hz)
%    select one filter for EEG or ERP data before using this file
%%
FilePath='E:\Functions\EEG_ToolBox_JCFan\Data to test this toolbox\resting EEG';% The path of original setfiles converted from rawfiles of EGI machine
SavePath = 'E:\Functions\EEG_ToolBox_JCFan\Data to test this toolbox\resting EEG 1';% The folder name of the new preprocessed files
if (exist(SavePath)==0)
    mkdir(SavePath);
end
FileList=dir(FilePath);
nFile=0;FileName=[];
for i=3:numel(FileList)
    if strcmp(FileList(i).name(end-2:end),'set')
        nFile=nFile+1;
        FileName{nFile}=FileList(i).name;
    end
end
%% Preprocessing
for i=1:nFile
    disp(FileName{i}(1:end-4))
    EEG = pop_loadset([FilePath,'\',FileName{i}]);
    %% 1.Reomve bad channels (EGI marginal channels)
    BadChannels=[127 126 17 128 125 48 119 43 49 56 63 68 73 81 88 94 99 107 113 120];% for EGI-128 cap
    % BadChannels=[];% (If you don't want to remove any channel, remove the first '%' in this line)
    if length(BadChannels)>=1
        EEG = pop_select(EEG,'nochannel',BadChannels);
    end
    %% 2.Resample
    EEG = pop_resample(EEG, 250);% Must be 250, or the following filter orders will be not very appropriate
    %% 3.Filter
    % High pass (Low pass is not necessary) choose one of the following two
    % steps before using: first one is for ERP data, and the second on is
    % for EEG data
    % EEG = pop_eegfiltnew(EEG, [], 0.1, 8250, true, [], 0);% This is for ERP data
    EEG = pop_eegfiltnew(EEG, [], 0.5, 1650, true, [], 0);% This is for EEG data
    
    % Notch (for both of EEG and ERP)
    EEG = pop_eegfiltnew(EEG, 48, 52, 414, 1, [], 0);
    EEG = pop_eegfiltnew(EEG, 98, 102, 414, 1, [], 0);
    %% Save the results
    pop_saveset(EEG,'filename', [FileName{i}(1:end-3),'set'],'filepath', SavePath, 'savemode','onefile', 'check','on');
end % end of n_cnt

%