function template=iterative_curve_fit(trace)%fitted_values=iterative_curve_fit(trace)

seed_vals=[10 5 45 200 0 22];   %amplitude_scaler,tau_rise,tau_decay1,tau_decay2,y_offset,latency -- time values are in *samples* here
lower_bounds=[4 3 6 20 -3 3];
latency_limit=101;
upper_bounds=[50 100 100 500 3 latency_limit];
fittingz_this_trial=[];
optionz=optimset('display','off');
[best_fitted_vals,best_resnorm,best_residual]=lsqcurvefit(@lsqfit_template_generator,seed_vals,[1:length(trace)],trace',lower_bounds,upper_bounds,optionz);

for latency_value=1:1:latency_limit     %going in larger steps is faster but yields considerably worse results
    [fitted_vals,resnorm,residual]=lsqcurvefit(@lsqfit_template_generator,[seed_vals(1:5) latency_value],[1:length(trace)],trace',[lower_bounds(1:5) latency_value-1],[upper_bounds(1:5) latency_value+1],optionz);
    if resnorm<best_resnorm,best_fitted_vals=fitted_vals;best_residual=residual;best_resnorm=resnorm;end
end
template=lsqfit_template_generator([best_fitted_vals],[1:length(trace)]);
%     figure,plot(trace,'k','linewidth',3),hold on, plot(template,'r','linewidth',3),plot(abs(best_residual),'o','markersize',10,'markerfacecolor','m','markeredgecolor','m')
fitted_PSC=min(template)-best_fitted_vals(5);
fitted_charge=sum(template-best_fitted_vals(5));
[minval minind]=min(template);      %lines 19-22 added july 17, 2006
fitted_riseduration=minind-best_fitted_vals(6);
greaterz=find(template(minind:end)>(minval/2));
if greaterz,fitted_halfdecayduration=greaterz(1)-1;else fitted_halfdecayduration=nan;end
fitted_values=[best_fitted_vals';fitted_PSC;fitted_charge;best_resnorm;fitted_riseduration;fitted_halfdecayduration];
template=[template fitted_values'];