function par_fit = fitGauss(data)
% This function will do a least squares fitting of a Gaussian distribution
% to the data k,N.  These data are assumed to come from a histogram, the
% variable k is the list of histogram bin values (the number of counts in a
% given time interval) and N is the a list of bin populations (the number
% of times a particular count occured).  The fit parameter vector par_fit
% contains the mean value of the distribution as par_fit(1), and the
% standard deviation of the distribution as par_fit(2).
k = data(:,1);
n = data(:,2);

pdf = n/sum(n);

 mu_est = sum(pdf.*k);          % Make an initial estimate of the mean.
sig_est = sqrt(sum(pdf.*k.^2)); % Make an initial estimate of the standard deviation.
par_est  = [mu_est,sig_est];    % Put the estimated values in a vector.

par_fit = fminsearch(@compSSE,par_est);
 mu_fit = par_fit(1);
sig_fit = par_fit(2);

figure(1)
plot(k,pdf,'o',k,gauss(k,mu_fit,sig_fit));
title(sprintf('Fit with $\\mu = %0.2f$ and $\\sigma=%0.2f$',mu_fit,sig_fit),'interpreter','latex')

% define the function that computes the sum of the squared errors
    function sse = compSSE(par)
        sse = sum((pdf-gauss(k,par(1),par(2))).^2);
    end


end

function pdf = gauss(k,mu,sig)
    pdf = (1/(sqrt(2*pi)*sig))*exp(-0.5*((k-mu)/sig).^2);
end