function chi2 = xychisquare(fitmat,xprof,yprof,xscal,yscal)
%
% XYCHISQUARE.M - calculates a chi-squared
%
%    The function XYCHISQUARE calculates a chi-squared fit for the X and Y
%    profile data from the ion source emittance measurements.  The
%    chi-squared fit is calculated in the following way:
%
%        - sum the X-Y profile matrix in both directions to produce 2
%          fitted profiles;
%        - calculate the chi-squared for each of these fitted profiles with
%          respect to the actual X and Y profiles;
%        - add these 2 chi-squared values together.
%
%    XYCHISQUARE requires 5 inputs in the following order:
%
%    [chi2] = xychisquare(fitmat,xprof,yprof,xscal,yscal)
%
%    fitmat - a 2D matrix of size (NxM) containing beam X-Y profile
%             histogram data.
%    xprof - vector of length (M) containing the X-profile to which the fit
%            will be made.
%    yprof - vector of length (N) containing the Y-profile to which the fit
%            will be made.
%    xscal - X-profile scale factor to ensure the fitted histogram values
%            are correct.
%    yscal - Y-profile scale factor to ensure the fitted histogram values
%            are correct.
%

    xsum = sum(fitmat) ; ysum = sum(fitmat') ;
    xsumsc = xsum./xscal ; ysumsc = ysum./yscal ;

    chix = sum( ( xsumsc - xprof ).^2 ) ;
    chiy = sum( ( ysumsc - yprof ).^2 ) ;

    chi2 = chix + chiy ;

    return