clc
clear all
loadpath='***';
savepath='***';
if (exist(savepath)==0); mkdir (savepath); end;
tmp = dir(loadpath);
n_set = 0;
for n=3:numel(tmp)
    if strcmp(tmp(n).name(end-2:end),'set')
        n_set = n_set+1;
        filenames{n_set} = tmp(n).name;
    end
end
for k=1:n_set
    EEG = pop_loadset([loadpath,'\',filenames{k}]);
    n_epoch=size(EEG.data,3);
    bad_epoch=[];nt=[];
    for i=1:n_epoch
        n_max=length(find(max(abs(EEG.data(:,:,i)')>80)));
        n_mdm=length(find(max(EEG.data(:,:,i)')-min(EEG.data(:,:,i)')>100));
        nt(i)=max([n_max n_mdm]);
        if nt(i)>=20
            bad_epoch=[bad_epoch i];
        end
    end
    be(k)=length(bad_epoch);
    EEG = pop_rejepoch( EEG, bad_epoch,0);
    [EEG,badepoch,n_zero_epoch(k),chnl_band_epoch]=reconstruction_epoch(EEG);
    [EEG,c_NAN(k)]=reconstruction_epoch_ch(EEG,0);
    pop_saveset( EEG,'filename', filenames{k},'filepath', savepath, 'savemode','onefile', 'check','on');
end
be
n_zero_epoch

