function events=mini_waveform_extractor(raw_trace,criterion_trace,criterion_threshold,event_jitter,event_window,baseline_offset_window1,baseline_offset_window2,...
    fit_slope_thresh,plot_sloperemovedextractions)
%description: Works on a single trial at a time, extracting each raw waveform beginning at the point when the criterion trace exceeds a threshold.
%Measures and, if above another threshold, removes underlying slope (e.g., if the event is riding on decaying phasic PSC).  Uses the criterion matrix 
%previously established by template_based_mini_detector and spontaneous_event_finder.
%called by: cluster_asynch_based_on_phasic, temporary_asynch_analyzer(deprecated), analyze_waveforms_clusters_mixtures_using_database(deprecated)
%calls: find_peaks_within_threshold_crossing_regions, exp_decay
%notes: the raw_trace is longer than the criterion_trace by enough to ensure that any event detected in the criterion trace can be fully
% (as determined by event_window) extracted from the raw trace
%code confirm date: sep 19, 2009

events=[];
event_peaks=find_peaks_within_threshold_crossing_regions(criterion_threshold,event_jitter,criterion_trace);
for present_peak=1:length(event_peaks)
    event=raw_trace(event_peaks(present_peak)-event_window(1)+event_window)';
    if ~isempty(baseline_offset_window1) || ~isempty(baseline_offset_window2)
        lin=polyfit([baseline_offset_window1 baseline_offset_window2],event([baseline_offset_window1 baseline_offset_window2]),1);%first need linear fit to check the slope
        if lin(1)<fit_slope_thresh,
            event_offset=lin(2);
        else    %if a linear fit gives a slope above the threshold, likely this event is riding on the decay phase of a larger event, so the 'undertow' has to be fitted and removed
            meanwin1=mean(event(baseline_offset_window1));meanwin2=mean(event(baseline_offset_window2));
            wingap=meanwin2-meanwin1;len=baseline_offset_window2(1)-baseline_offset_window1(end);steppe=wingap/len;
            riser=[steppe:steppe:steppe*(len-1)]+meanwin1;
            undertow=event;undertow(baseline_offset_window1(end)+1:baseline_offset_window2(1)-1)=riser;
            undertow_amptau=lsqcurvefit(@exp_decay,[10 20],[1:length(event)],undertow);
            event_offset=exp_decay(undertow_amptau,[1:length(event)]);
            if plot_sloperemovedextractions,figure,hold on,plot(event,'k'),plot(event_offset,'g'),plot(event-event_offset,'b'),plot(undertow,'r');end
        end
        event=event-event_offset;
        %figure,plot(event,'k'),title(num2str(lin(1)))
    end
    events=[events;event];
end