
function [Epi_Events]= Detect_itd (ripplech)
%% detect ID Spike
targetFile = dir('*.hippocampalLayers.channelinfo.mat'); % uncomment later load(targetFile(1).name); 
ripplech = 21 % uncomment later hippocampalLayers.bestShankLayers.pyramidal;

[Epi]= findRipples(ripplech,'thresholds',[1.5 3.5],'passband',[60 80],...
    'EMGThresh',1,'durations',[100 500], 'saveMat',false,'restrict',[],'frequency',1250);

figure; subplot(1,2,1); hist(Epi.peakNormedPower,100);
 h = figure;
        hist(Epi.peakNormedPower,100);
        title('Select threshold with the mouse and press right click...');
        [cutpoint,thr] = ginput(1);
        hold on
        line(cutpoint*[1 1],ylim,'Color','r');
        pause(1);
        close(h);
validEvents = find(Epi.peakNormedPower>=cutpoint);
Epi_Events.timestamps = Epi.timestamps(validEvents,:);
try 
   Epi_Events.peaks = Epi.peaks(validEvents,:);
   Epi_Events.peakNormedPower = Epi.peakNormedPower(validEvents,:);
end


%Epi_Events = removeArtifactsFromEventsEPI(Epi, 'stdThreshold',0.5); %3.2 2.5 Naz1 or 2 for az10 AZ11 4 lower == lower cutpoint
figure; subplot(1,2,1); hist(Epi.peakNormedPower,100);
hold on; subplot(1,2,2); hist(Epi_Events.peakNormedPower,100);


saveas(gcf,'Analysis\IED\thresholdIED.jpeg');  

targetFile = dir('*MergePoints*.mat'); load(targetFile(1).name);
% Pre maze 
start=MergePoints.timestamps(1,1);
stop=MergePoints.timestamps(1,2);
[f ind]= find(Epi_Events.timestamps(:,2)>start & Epi_Events.timestamps(:,2)<stop);
Epi_Events.pre.rate= length(ind)/(stop-start);
Epi_Events.pre.count= length(ind);

%Post Maze 
start=MergePoints.timestamps(end,1);
stop=MergePoints.timestamps(end,2);
[f ind]= find(Epi_Events.timestamps(:,2)>start & Epi_Events.timestamps(:,2)<stop);
Epi_Events.post.rate= length(ind)/(stop-start);
Epi_Events.post.count= length(ind);

start=MergePoints.timestamps(1,1);
stop=MergePoints.timestamps(1,2);
Epi_Events.total.count= length(Epi_Events.timestamps);
Epi_Events.total.rate= length(Epi_Events.timestamps)/(MergePoints.timestamps(end,2)-MergePoints.timestamps(1,1));

mkdir('SummaryFigures')
filename = split(pwd,filesep); filename = filename{end};
save([filename '.IED.mat'],'Epi_Events');


% Plots
if Epi_Events.total.count >=1
lfp = getLFP(ripplech); %59
[wavAvg, lfpAvg] = bz_eventWavelet(lfp, Epi_Events.peaks(randperm(Epi_Events.total.count),1),'twin',[.8 .8], 'frange',[10 50], 'whitening',false);
caxis([1000 20000]);
xlabel('Time(ms)')
ylabel('Frequency(HZ)')
xt = get(gca, 'XTick');
set(gca, 'XTick',xt, 'XTickLabel',xt/10)
title('IED');
colorbar
saveas(gcf,'Analysis\IED\IED.fig');  
saveas(gcf,'Analysis\IED\IED.jpeg');  
end 

% Neuroscope visualize
events1.time=Epi_Events.peaks; 
for i=1:size(Epi_Events.peaks,1);
events1.description{i,1} = ['IED peak'];
end 
SaveEvents([filename '.IED.evt'],events1);

%%  Firing of cells

