function [event1, event, event_offset]=event_extractor_coretemp(mem_current,event_aligned_extraction,which_APs,AP_times,crit_peaks,rel_event_times,event_window,baseline_offset_window1,...
    baseline_offset_window2,fit_slope_thresh,plot_sloperemovedextractions,plot_extracted_events)
%description: extracts events; measures and, if above a threshold (i.e., if the event is riding on decaying phasic PSC), removes underlying slope.  
    %if ~event_aligned_extraction, will return membrane current beginning at the AP for those APs that were followed by detected PSCs
%called by: phasic_and_asynchronous_event_extractor
%calls: exp_decay
%notes: if an event is too close to the end (or beginning) of the recording to be fully extracted, a vector of nan is returned for that event
%code confirm date: jan 6, 2013

events=[];
for present_event=1:length(crit_peaks)
    if event_aligned_extraction
        event1=mem_current(crit_peaks(present_event)+event_window);
        event=event1;
        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);
            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;
            if plot_extracted_events
                figure,plot(event,'k'),title(num2str(lin(1))),xlabel(num2str(rel_event_times(present_event)))
            end
        end
    else
        if which_APs(present_event) %in other words, if this event actually followed an AP
            event=mem_current(AP_times(which_APs(present_event))+event_window);
        end
    end
    %events=[events [crit_peaks(present_event);event]];
end