function peaks=find_threshold_cross_peak_vals_and_times(data_that_crosses_threshold,threshold,event_jitter)
%description:  finds segments of a vector that exceed a threshold, finds the positivemost element within each segment (the peak),
    %removes peaks that occur within event_jitter of the previous peak, returns peak indices and values
%called by: phasic_and_asynchronous_event_extractor_core  
%calls: [no custom functions]
%notes:
%code confirmed date: feb 2, 2013

%find suprathreshold segments
above_threshold=data_that_crosses_threshold>threshold; 
beginnings_iftrue=~above_threshold(1:end-1)&above_threshold(2:end);
endings_iftrue=above_threshold(1:end-1)&~above_threshold(2:end);
event_start_indices=1+find(beginnings_iftrue);
event_end_indices=find(endings_iftrue);

%remove suprathreshold segments not fully captured in the recording
if length(event_start_indices)>length(event_end_indices),event_start_indices=event_start_indices(1:end-1);  %when data_that_crosses_threshold ends "high," the last event has a beginning but no ending
elseif length(event_end_indices)>length(event_start_indices),event_end_indices=event_end_indices(2:end);      %when d_t_c_t ends "low," the first event has an ending but no beinning
end

%find the index of the max value within each suprathreshold segment
peak_times=[];
for ttt=1:length(event_start_indices)
    suprathresh_max=find(data_that_crosses_threshold(event_start_indices(ttt):event_end_indices(ttt))==max(data_that_crosses_threshold(event_start_indices(ttt):event_end_indices(ttt))));
    peak_times(ttt)=suprathresh_max(1)+event_start_indices(ttt)-1;
end

%remove any peaks within event_jitter of a previous peak
z=length(peak_times);
if length(peak_times)>1
	for bleb=2:length(peak_times)
        if peak_times(z)-peak_times(z-1)<event_jitter
            peak_times(z)=[];
        end
        z=z-1;
    end
end

peak_vals=data_that_crosses_threshold(peak_times);
peaks=[peak_times;peak_vals];