% Jon Newman
% Create time series summary figure

%% Load SS
SS1 = load('J:/newmonster/2012_02_16_Lollipop_Long-Term-optoBB/cl-long-bb_01_2012-02-16_chr2_lollipop_10803.SS','-mat');

sort_bound = [0 3600]; % The time to sort unit firing rate over

% First zoom parameters
dt = 300;
r1 = 0.5;
r2 = 10;
r3 = 20;

% xcorr parameters
tau = 0.01; % sec
maxlag = 1; % sec
nunit = 10; % number of units to base xcorr on


%% First Raster zoom in
close all
figure('units','centimeter','outerposition',[1 1 19 10]); % fill A4 paper width
rb = [[3600*r1 - 0.5*dt 3600*r1 + 0.5*dt];
    [3600*r2 - 0.5*dt 3600*r2 + 0.5*dt];
    [3600*r3 - 0.5*dt 3600*r3 + 0.5*dt]];
for i = 1:size(rb,1)
    
    subplot(4,3,i)
    hold on
    
    %% No drug
    l = ceil(maxlag/tau);
    t = 0:tau:dt;
    XC =  zeros(1,2*l+1);
    MaxUnit=max(SS1.SS.unit);
    r =  randperm(MaxUnit);
    u = 1:MaxUnit;
    combos = nchoosek(u(1:nunit),2);
    XC =  zeros(length(combos),2*l+1);
    for j=1:length(combos)
        b1 = SS1.SS.time > rb(i,1) & SS1.SS.time <= rb(i,2) & SS1.SS.unit == combos(j,1);
        b2 = SS1.SS.time > rb(i,1) & SS1.SS.time <= rb(i,2) & SS1.SS.unit == combos(j,2);
        S1t = hist(SS1.SS.time(b1)-rb(i,1),t);
        S2t = hist(SS1.SS.time(b2)-rb(i,1),t);
        if sum(S1t) > 0 && sum(S2t) > 0
            [XC(j,:) lags] = xcorr(S1t,S2t,l);
            XC(j,:) = XC(j,:)/(sqrt(var(S1t)*var(S2t)));
        end
    end
    
    uXC = mean(XC);
    plot(tau*lags,tau*uXC);
    ylim([-10 100])
    
    

    
    ip = get(gca, 'Position');
    op = get(gca, 'OuterPosition');
    set(gca, 'Position', [op(1) ip(2) op(3) ip(4)]);
    if i == 1
        w = op(3);
        h = ip(4);
    else
        set(gca, 'Position', [op(1) ip(2) w h]);
    end
end
%%
% export_fig '2012-01-12_lollipop-10803_DW-MEStim-combined_pearsons_xcorr_FINAL' -pdf -transparent









