function fitted_waveform_and_parameters=iterative_curve_fit_postpreratio(measuredvals, return_pareddown_template, plotdatafitresiduals)

%description: 
%calls: oneoverxdecay
%notes: 
%code confirmed date: 

datalen=length(datatrace);

seed_vals=[1 1 1];   %x_offset, y_offset, exponent

lower_bounds=[.1 .1 .001];
upper_bounds=[5 5 5];
optionz=optimset('display','off');

[best_fitted_vals,best_resnorm,best_residual]=lsqcurvefit(@oneoverxdecay,seed_vals,[1:datalen],datatrace,lower_bounds,upper_bounds,optionz);

for latency_value=1:1:latency_limit
    [fitted_vals,resnorm,residual]=lsqcurvefit(@monoexprisedecay_template_generator,[seed_vals(1:4) latency_value],[1:datalen],datatrace,[lower_bounds(1:4) latency_value-1],[upper_bounds(1:4) latency_value+1],optionz);
    if resnorm<best_resnorm,best_fitted_vals=fitted_vals;best_residual=residual;best_resnorm=resnorm;end
end

if return_pareddown_template
    puretemplate=monoexprisedecay_template_generator([best_fitted_vals(1:3) 0 0],[1:datalen]);
    [minval,minind]=min(puretemplate);
    fitted_PSC=minval;
    rise_time=minind;
    returntemplate=[0 puretemplate rise_time fitted_PSC];
else
    puretemplate=monoexprisedecay_template_generator(best_fitted_vals,[1:datalen]);
    [minval,minind]=min(puretemplate);
    fitted_PSC=minval-best_fitted_vals(4);
    rise_time=minind-best_fitted_vals(5);
    fitted_charge=sum(puretemplate-best_fitted_vals(4));
    fitted_values=[best_fitted_vals rise_time fitted_PSC fitted_charge best_resnorm];
    returntemplate=[puretemplate fitted_values];
end
if plotdatafitresiduals,figure,plot(datatrace,'k','linewidth',3),hold on, plot(puretemplate,'r','linewidth',3),plot(abs(best_residual),'o',...
        'markersize',10,'markerfacecolor','m','markeredgecolor','m'),title(num2str(rise_time)),end
