files = [{'DT2_rPPC_rCCG_3324um_650um_20160216_160216_132620'},...
         {'DT2_rPPC_rCCG_3324um_1000um_20160217_160217_103121'},...
         {'DT2_rPPC_rCCG_3396um_1180um_20160220_160220_141839'},...
         {'DT2_rPPC_rCCG_3396um_1180um_20160221_160221_135947'},...
         {'DT2_rPPC_rCCG_3468um_1216um_20160222_160222_120902'},...
         {'DT2_rPPC_rCCG_3468um_1216um_20160223_160223_121321'},...
         {'DT2_rPPC_rCCG_3468um_1216um_20160225_160225_130701'},...
         {'DT2_rPPC_rCCG_3468um_1252um_20160226_160226_124132'},...
         {'DT2_rPPC_rCCG_3540um_1288um_20160227_160227_121226'},...
         {'DT2_rPPC_rCCG_3540um_1288um_20160228_160228_135001'},...
         {'DT2_rPPC_rCCG_3612um_1360um_20160305_160305_141507'},...
         ];
     
     
for i=1:length(files)
    cd(files{i})
    SetCurrentSessionclose 
    units=GetUnits();
    for j=1:length(units)
        spikes{j}=GetSpikeTimes(units(j,:));
    end
    lfp = GetLFP([23]);
    [b a] = butter(3,[130/625 190/625],'bandpass');
    power = zscore(fastrms(filtfilt(b,a,lfp(:,2)),20)); 
    q = prctile(power,linspace(0,100,6));
    dis = discretize(power,q);
    bins = unique(dis);
    for bin = 1:length(bins)
        f = find(dis==bins(bin));
        for c = 1:length(units)
           sp{bin}{c} = []; 
        end
    end
    parfor bin = 1:length(bins)
        f = find(dis==bins(bin));
        for c = 1:length(units)
%             for s = 1:length(spikes{c})
%                 tic
%                 [a b]=min(abs(lfp(f,1)-spikes{c}(s)));
%                if a < .001
%                   sp{bin}{c} = [sp{bin}{c};spikes{c}(s)]; 
%                end
%                 t(s) = toc;
%                 tic;
              temp = ismember(ceil(10000*spikes{c})/10000,lfp(f,1));
                   sp{bin}{c} = [spikes{c}(temp)]; 
%                tt(s) = toc;
%                plot(t);hold on; plot(tt); hold off; pause(.01)
%             end
        end; bin
    end
    spp{i}=sp;
    units_all{i} = units;
    clear sp
    
    files{i}
    cd ..
end

 for i=1:length(files)
    for j=1:length(bins)
    [times groups blah] = spikes2sorted(spp{i}{j});
    [ccg{i}{j},time] = CCG(times,groups,'binSize',.001);
    for shank = 1:5
       f = find(units_all{i}(:,1)==shank);
       ff = find(ismember(units_all{i}(:,1),shank+1:6));
       temp = [];
       if size( ccg{i}{j},2)>1
       for k=1:length(f)
           for l = 1:length(ff)
                temp = [temp,ccg{i}{j}(:,f(k),ff(l))];
           end
       end
       end
       ccg_ordered{i}{j}{shank}=temp;
    end
    end
 end 

for i=1:11
for j=1:length(bins)
for k=1:5
if ~isempty(ccg_ordered{i}{j}{k})
cc(i,j,k,:)=zscore(squeeze(mean(ccg_ordered{i}{j}{k},2)));
else
cc(i,j,k,:)=zeros(2001,1);
end
end
end
end






