function careful_latency_measurement(ddata, presyn_INa_onsets, pulse_duration_presyn, samples_per_ms, stim_indices, remove_entire_stim_artifact, extradeadsamples, trial, number_of_trials,...
    fastemplate, save_that_sht, plot_latency_measures, save_after_each_trial, common_pathname, asky, dub, tbs)
%description: called each trial, removes the end of the stimulus artifact then compares the postsyn trace to a PSC template, storing the criterion following each AP for later analyses
%called by: patchfile analysis
%calls: lsqfit_template_generator, template_based_mini_detector
%notes: it would be faster to pass the template in
%code confirmed date:

pulsamples=pulse_duration_presyn*samples_per_ms;

persistent criteria_for_latency
criteria_for_latency_this_trial=[];

for captain_caveman=1:length(presyn_INa_onsets)
    if remove_entire_stim_artifact   %in some cases (e.g. with gap junctions present) it is necessary to remove the entire timeperiod of the stim artifact to get an accurate criterion
        deadlength=pulsamples+extradeadsamples;
        ddata(stim_indices(captain_caveman,1):stim_indices(captain_caveman,1)+deadlength-1,2)=zeros(length(deadlength),1);
    else
        stepper=[-3:3];deadspace=(pulsamples)+stim_indices(captain_caveman,1)+stepper;  %removing the artifact only from the end of the presyn stim; this is done in almost all cases
        begindead=ddata(deadspace(1),2);enddead=ddata(deadspace(2),2); 
    if begindead==enddead,stepper=repmat(begindead,length(stepper),1);else stepper=[begindead:(enddead-begindead)/length(stepper):enddead-(enddead-begindead)]';end
    end
    postsyn_trace_after_this_AP=ddata(presyn_INa_onsets(captain_caveman)+[0:199],2)';   %using 1 to 199 permits detection of events beginning up to 14.9 ms after the onset of presyn I_Na, assuming 5 ms template
    criterion_this_AP=template_based_mini_detector(postsyn_trace_after_this_AP,fastemplate)';
    criteria_for_latency_this_trial=[criteria_for_latency_this_trial;criterion_this_AP];
    if plot_latency_measures
        figure,plot(postsyn_trace_after_this_AP,'k'),hold on,plot(criterion_this_AP,'r'), plot([1 199],[2 2],'b'), plot([1 199],[1.5 1.5],'g'),drawnow
    end
end
criteria_for_latency=[criteria_for_latency criteria_for_latency_this_trial];
if (trial==number_of_trials & save_that_sht) | (save_after_each_trial & save_that_sht)
    pathname=strcat(common_pathname,'criteria_for_latency');save(pathname,'criteria_for_latency',asky,dub,tbs)
end