

fils  = getAllExtFiles(pwd,'rip',1);

ripples = LoadEvents(fils{1});

rip_on =  ripples.time(cellfun(@(a) any(regexp(a,'Ripple start')), ...
    ripples.description));

rip_off =  ripples.time(cellfun(@(a) any(regexp(a,'Ripple stop')), ...
    ripples.description));


binSize = .0004; %4ms
duration = .2; %200ms


conv_w = .010/binSize;
SetCurrentSession
spikes = GetSpikeTimes(units,'output','full');
[~,~,cellID] = unique(spikes(:,2:3),'rows');
spikesIDs = [spikes(:,2:3) cellID];
[spiketimes,b] = sort(spikes(:,1));
spikesIDs  = spikesIDs(b,:);


mono_res = MonoSynConvClick3 (spikesIDs,spiketimes(:,1),'plot',false,'sorted',true);

connected = mono_res.sig_con;
idconnected = NWB.spikes.ID(connected);

connected = connected(idconnected(:,1)==1 & idconnected(:,2)>1,:);

fils  = getAllExtFiles(pwd,'ait',1);
stims = LoadEvents(fils{1});

for j = 1:4
    
    sti{j} = unique([stims.time(cellfun(@(a) any(regexp(a,'on')) & ...
        any(regexp(a,num2str(j))),stims.description)) ...
        stims.time(cellfun(@(a) any(regexp(a,'off')) & ...
        any(regexp(a,num2str(j))),stims.description))],'rows');
    
end



[status] = InIntervals(spiketimes,sortrows(cell2mat(sti')));
spiketimes = spiketimes(~status,:);
spikesIDs = spikesIDs(~status,:);
%%
bins  =1:100:15631-500;
idx=1;
trans = nan(length(bins),51);
for i = bins
mono_res = MonoTransCalc (spikesIDs,spiketimes(:,1),connected,'plot',false,'sorted',true,'epoch',[0 500]+i);

for i = 1:51
trans(idx,i) = sum(mono_res.prob(253:256,connected(i,1),connected(i,2)));
end
idx= idx+1

end

%%

[a,b,c]  = pca(zscore(trans'));


%%
close all

SWS = bwconncomp(states==1);
wake = bwconncomp(states==1);
b_SWS = (cellfun(@(a) b1(a,1)  ,SWS.PixelIdxList,'uni',0)');
b_wake = b1(states==1)';
sleepTime = (cellfun(@(a) (a-a(1))/length(a),SWS.PixelIdxList,'uni',0)');
%[~,sleepTime] = histc(sleepTime,0:.25:1);

wakeTime = cell2mat(cellfun(@(a) (a-a(1)),wake.PixelIdxList,'uni',0)');
%[~,wakeTime] = histc(wakeTime,0:.25:1);

for i = 1:length(b_SWS)
    
   plot(sleepTime{i}, b_SWS{i})
   hold on
   
    
end
%%
figure
plot(accumarray(sleepTime,b_SWS,[],@nanmedian,nan))
hold on
plot(accumarray(wakeTime,b_wake,[],@nanmedian,nan))


%%
for i = 1:51
    
    
 temp =   accumarray(states(states>0)',b1(states>0,i),[],@nanmean,nan);
    
 st(i,:) = temp([1 3 5])';
end
 