function [A,h,k,fit] = fit_parabola_vertex(x,data,A_guess,h_guess,k_guess,tolerance,showplot)

options=optimset('Display','off', 'Tolx', tolerance, 'TolFun',tolerance, 'MaxIter', 2000);
 
params(1) = A_guess;
params(2) = h_guess;
params(3) = k_guess;
 
% Call fminsearch function
[paramsout,~,~,output]=fminsearch(@calcdiff,params,options,x,data);

%fprintf(' -- Fit completed after %d iterations--\n',output.iterations);
%fprintf(' Started with: width=%g, center=%g, magnitude=%g',width_guess,center_guess,1);

A  =  paramsout(1);
h  = paramsout(2);
k = paramsout(3);
x2=linspace(min(x),max(x),100);
fit=A*(x2-h).^2+k;

fprintf(' Finished with: A =%g, x offset =%g, y offset = %g\n',A,h,k);

if (showplot==1)
    figure1=figure()
    plot(x,data,'b-',x2,fit,'r--');
    legend('data','fit')
    
end


function err = calcdiff(params,x,data)
  
A = params(1);
h = params(2);
k = params(3);
fit=A*(x-h).^2+k;
err=sqrt(sum((data-fit).^2));
