%% pwgaufit.m uses hist to bin the inputted data and then fits
%% a gaussian distribution to determine the mean and distribution.
%%  

function [datmn,datsd,datap,yvout,xvout,histout]=pwgaufit(data,xv)

% data = data to be fitted (matrix or vector).
% xv = bin center vector to be used by hist (if scalar, then number of bins to be used)
% datmn = mean of fitted Gaussian. 
% datsd = standard deviation of fitted Gaussian.
% datap = amplitude of fitted Gaussian.
% yvout = values of Gaussian curve at xvout values
% xvout = vector used by hist (xvo = xv if length(xv)>1, otherwise output from hist)
% histout = vector with number of data points per bin.

%Convert data input to column vector.
data=data(:);

%Use hist to bin the data
if length(xv)==1
 [histout,xvout]=hist(data,xv);
else
 histout=hist(data,xv);
 xvout=xv;
end

%Fit Gaussian function to data to required output paramters
c0=[mean(histout) std(histout) 0.1*length(histout)];
options=optimset('Display','off');
c=fminsearch('pwgaufitb',c0,options,xvout,histout);

%Required output
datmn=c(1);
datsd=c(2);
datap=c(3);
yvout=pwgauss(c(1),c(2),c(3),xvout);

