% Jon Newman
% Get channel-channel or unit-unit xcorr functions at different time points
% during a clamp recording

% Parameters
fid = 'herbI5374_12-13DIV_CNQX-ChR2-stim_01';
fig_name = [fid '_xcorr_01'];
t_data = 1800;
dt = 0.1;
maxlag = 5;
channels = setdiff(1:64,[1 8 33 57 64]);
r = randperm(length(channels));
channels = channels(r(1:20));

% Load data
s = load(fid);
original_start = min(s.time);
s.time = s.time - original_start;
ss = SqueakySpk(fid,25e3,1,s);

% Generate XCorr function
close all
figure
hold on

% Before clamp
t_centers = 3600*[-2 -1 1 3 6 12 18 23];
col = hsv(numel(t_centers));
XC = cell(numel(t_centers),1);

for i = 1:length(t_centers)
    t_start = t_centers(i) - t_data/2;
    ss.GenerateChannelXCorr([t_start - original_start t_start+t_data- original_start],dt,maxlag,[],1,1);

    XC{i} = ss.chan_xc;
    hline = findobj(gcf, 'type', 'line');
    set(hline(1),'Color',col(i,:));
    drawnow
end

% Figure porperties
xlabel('Lag (sec)')
ylabel('Firing rate (Hz/channel)')
hline = findobj(gcf, 'type', 'line');
set(hline(2),'Color','blue')
set(gca,'TickDir','out')
legend(num2str(t_centers'/3600))

% Export data
xc.t_centers = t_centers;
xc.t_data = t_data;
xc.maxlag = maxlag;
xc.dt = dt;
xc.chan_xc = XC;

% Export figure
save([fid '_xc'],'xc');
saveas(gcf,fig_name)
export_fig('-pdf','-transparent',fig_name,gcf)
