function [deltas,session] = BatchDetectAndSaveDeltaWaves(session, PFCgroups, ~,~,~,~, minutes, HPCgroups, day)

% Call this by StartBatch(@BatchDetectDeltaWaves,'all.batch');
rat = str2num(session(4+max(strfind(session,'/')):6+max(strfind(session,'/'))));
[~,sessionName] = fileparts(session);

global BASEPATH
cd(BASEPATH); cd('data');

% Detect delta waves

try % in case file exists already
    deltas = dlmread(fullfile(BASEPATH, 'data', [sessionName '-deltas-lfp-deltagroups']));
catch
    display(['Rat ' num2str(rat) '; detecting deltas...']);
    SetCurrentSession(session,'verbose','off');
    pfc = GetChannels(PFCgroups(:))';
    try
        pfc = dlmread(fullfile(BASEPATH, 'data', [sessionName '-good-PFC-channels']));
    end
    [deltas, w] = DetectDeltaWaves(session,pfc(:)');
    deltas = [deltas w];
	
	units = GetUnits;
	pfcUnits = units(ismember(units(:,1),PFCgroups),:);
	pfc = GetSpikeTimes(pfcUnits,'output','numbered');
	
	% Delta waves need to be associated with an overall decrease of firing rate
	[h,ht] = PETH(pfc(:,1),deltas(2:end,2));
	h = Smooth(h,[0 3]);
	z = zscore(h,[],2);
	bad = [false; z(:,floor((1+size(z,2))/2))>0];
	deltas(bad,:) = [];
	peaks(bad,:) = [];
	starts(bad,:) = [];
	stops(bad,:) = [];
	
	cd(BASEPATH); cd('data');
	dlmwrite(fullfile(BASEPATH, 'data', [sessionName '-deltas-lfp-deltagroups']),deltas,'precision','%f5');
	dlmwrite(fullfile(BASEPATH, 'data', [sessionName '-deltas-lfp-deltagroups']),peaks,'precision','%f5');
	dlmwrite(fullfile(BASEPATH, 'data', [sessionName '-deltas-lfp-deltagroups']),starts,'precision','%f5');
	dlmwrite(fullfile(BASEPATH, 'data', [sessionName '-deltas-lfp-deltagroups']),stops,'precision','%f5');
end
