function [estimates, model] = fit_g_curve(xdata, ydata)

% Call fminsearch with a random starting point.
start_point(1) = .1; % .9
start_point(2) = 1/10; % 1/500
model = @myfun;

[estimates, fval, exitflag] = fminsearch(model, start_point);

if exitflag==1
    disp('converge');
elseif exitflag==0
    disp('maximum number of iterations reached');
end

% expfun accepts curve parameters as inputs, and outputs sse,
% the sum of squares error for A * exp(-lambda * xdata) - ydata, 
% and the FittedCurve. FMINSEARCH only needs sse, but we want to 
% plot the FittedCurve at the end.
    function [sse, FittedCurve] = myfun(params)
        g = params(1);
        A = params(2);
        FittedCurve = A * (1-g*g)./((1+g*g-2*g*cos(xdata)).^(1.5));
        ErrorVector = FittedCurve - ydata;
        sse = sum(ErrorVector .^ 2);
    end

end