% compute average waveforms of silent and non-silent deltas

batch = StartBatch(@BatchCheckDeltaWaveform,'all.batch','hide','off');
X = get(batch,'UserData');

write = false; %whether or not to save figures
global BASEPATH

%%

nSessions = size(X,1);
nChannels = cellfun(@max,X(:,2));
channelID = cell2mat(X(:,2));
size1 = @(x) size(x,1);
nDeltas = cellfun(size1,X(:,1))./nChannels;


ht = X{1,4};
all = cell2mat(X(:,1));
z = zscore(all,[],2);
mid = nanmean(z(:,(0:1)+size(z,2)/2),2); % estimate for gamma power at t=0 (mean of bins on the two sides of zero)

add = [0;cumsum(nDeltas)];
ses = repelem((1:nSessions)',nChannels.*nDeltas);
deltaID = CumSum(diff([0;channelID])==0,diff([0;channelID])~=0)+1;
dID = deltaID + add(ses);

%%

[mi,idx] = Accumulate(dID,mid,'mode','max'); % for each delta, find the best channel (the one with the peak lfp signal)

nans = find(isnan(idx));
for i=nans',
    idx(i) = find(dID==i,1);
end

zmi = z(idx,:);

count = cell2mat(X(:,3));

%%

figure;
for i=1:4,
    subplot(2,2,i);
    smooth = i-1;
    cla
    plot(ht,Smooth(nanmean(zmi(count0==0,:)),smooth),'k','linewidth',2);
    hold all
    plot(ht,Smooth(nanmean(zmi(count0>0,:)),smooth),'r','linewidth',2);
    
    semplot(ht,zmi(count0>0,:),'r',smooth);
    semplot(ht,zmi(count0==0,:),'k',smooth);
    
    legend('location','southeast',['silent deltas, n=' num2str(sum(count0==0))],['nonsilent, n=' num2str(sum(count0>0))]);
    title(['z-scored lfp around events, smooth = ' num2str(smooth)]);
end


if write, export_fig(fullfile(BASEPATH,'figures','DeltaWaveforms_zscored.pdf')); end
%%

ami = all(idx,:);

figure;
for i=1:4,
    subplot(2,2,i);
    smooth = i-1;
    cla
    plot(ht,Smooth(nanmean(ami(count0==0,:)),smooth),'k','linewidth',2);
    hold all
    plot(ht,Smooth(nanmean(ami(count0>0,:)),smooth),'r','linewidth',2);
    
    semplot(ht,ami(count0>0,:),'r',smooth);
    semplot(ht,ami(count0==0,:),'k',smooth);
    
    legend('location','southeast',['silent deltas, n=' num2str(sum(count0==0))],['nonsilent, n=' num2str(sum(count0>0))]);
    title(['mean lfp around events, smooth = ' num2str(smooth)]);
end

if write, export_fig(fullfile(BASEPATH,'figures','DeltaWaveforms.pdf')); end
