function kt_events=find_multiple_peaks(datatrace, input_parameters)
%description: event detection, using the method published by kudoh and taguchi (Biosensors and Bioelectronics 17 (2002) 773-782), tip from j. castro
%calls: no custom functions
%called by: command line, simulated_psc_in_noise
%notes: all times in samples, all amplitudes in pA; expects negative-going synaptic currents
%code confirmed date: november 5, 2012

step=input_parameters(1); %roughly corresponds to rise time
binwidth=input_parameters(2); %for local averaging
peak_time_range=input_parameters(3); %the window after the detected onset time within which search for peak happens
thresh=input_parameters(4); %a negative value; initial detection threshold, also used as a threshold to check that an event peak is legit
noise=input_parameters(5); %a negative value; noise analog, sets a sort of significance threshold for various parameters, see code

bin_dec=binwidth-1;
kt_events=[];
i=binwidth; %have to skip these first samples due to backward portion of peak search 
while i<length(datatrace)-(step+peak_time_range+bin_dec-1)
    if datatrace(i+step)<datatrace(i)+thresh     %finding the temp onset point
        onset_time=i;
        for j=1:step  %looking for true onset point, take first point where <j+bin> is closer to negative infinity than (original algorithm uses <=) the onset point + (negative-going) noise
            if mean(datatrace(i+j+[0:bin_dec]))<datatrace(i)+1.5*noise   %original algorithm uses noise, not 1.5*noise
               onset_time=i+j;
               break
            end
        end
        onset_amplitude=datatrace(onset_time);
                
        temp_peak_time=onset_time+step;
        for k=1:peak_time_range  %finding the temp peak point (i.e., the forward search portion)
            if mean(datatrace(onset_time+k+[0:bin_dec]))>=datatrace(onset_time+k)-noise
                temp_peak_time=onset_time+k;
                break
            end
        end
        
        true_peak_time=temp_peak_time;
        for m=temp_peak_time:-1:onset_time  %the backward search portion
            if mean(datatrace((m-bin_dec):m))>=datatrace(temp_peak_time)-noise  %addition of the noise term here differs from original algorithm, appears to improve accuracy
                true_peak_time=m;
                break
            end
        end
        peak_amplitude=datatrace(true_peak_time);
        corrected_peak_amplitude=peak_amplitude-onset_amplitude;
         
        if corrected_peak_amplitude<=thresh           
            kt_events=[kt_events; [onset_time;onset_amplitude;true_peak_time;peak_amplitude;corrected_peak_amplitude]];
            i=true_peak_time;
        end
    end
    i=i+1;
end