function [chi2] = chisquare(RC,sigma,tzero,A)
%
% CHISQUARE.M - calculates a chi-squared
%
%    The function CHISQUARE.M calculates a chi-squared fit for the
%    short pulse data taken with the X-band BPM, stored in
%    V:\NLCTA\FONT\phaselockdata (using the data file in the .MAT
%    file 'phaselockdata.mat' - particularly the array 'ydat_12').
%
%    The function to which the data is fitted is a Gaussian distribution
%    skewed by a low pass filter i.e. with an added tail. For an example,
%    see the function GAUSSFILT.M.
%
%    CHISQUARE.M requires 4 inputs in the following order:
%
%    function [chi2] = chisquare(RC,sigma,tzero,A)
%
%    RC - RC time constant (a.k.a. tau) for the response of the filter. Default
%         is 2.
%    sigma - standard deviation of Gaussian distribution. Default is 1.
%    tzero - approximate time at which peak of function occurs; corresponds
%            to mean position of Gaussian distribution. Default is 25.
%    A - amplitude scaling factor for distribution peak (peak height depends
%        upon A and sigma). Default is 0.45.
%

    load V:\NLCTA\FONT\phaselockdata\phaselockdata.mat ;

    time = ydat_12(:,1)*1e9 ; bpm = ydat_12(:,2) ;

    for i = 1:length(time)

        filtarr(i) = ( A * ( sqrt(pi/2) ) * sigma * exp( -0.5*( 2*time(i)*RC - 2*tzero*RC - sigma^2 ) / RC^2 ) ) * ...
            ( ( erf( (sqrt(2) * ( time(i)*RC - tzero*RC - sigma^2 ) ) / (2 * sigma * RC) ) ) + ...
            ( erf( (sqrt(2) * ( 30*RC + tzero*RC + sigma^2 ) ) / (2 * sigma * RC) ) ) ) ;

    end

    chi2 = sum( ( bpm - filtarr' ).^2 ) ;

    return