function F = lyngby_cdf_chi2(x, r)

% lyngby_cdf_chi2      - X^2 cumulated distribution function
%
%       function F = lyngby_cdf_chi2(x, r)
%
%	Input:  x   Value where the chi2 distribution is to be
%                   evaluated
%		r   Degrees of freedom
%
%	Output: F   Distribution value
%
%       The lower tail area of the chi squared distribution evaluated
%       by the incomplete gamma function.
%
%       See also LYNGBY, LYNGBY_CDF_BETA, LYNGBY_CDF_F,
%                LYNGBY_CDF_FISHERSG, LYNGBY_CDF_GAUSS, LYNGBY_CDF_T,
%                LYNGBY_CDF_WILRANK. 
%
% $Id: lyngby_cdf_chi2.m,v 1.2 2003/02/16 23:23:38 fnielsen Exp $



    if 1

      F = gammainc(x/2, r/2); 
      
    else
      %	Ref: Lennart Raade, Beta 17.4, page 385, 1990.
      
      A = (x/r).^(1/3) + 2/(9*r) - 1;
      B = sqrt(2/(9*r));
      
      y = A / B;
      
      if y < 0
	if r > 30
	  % Gaussian approximation to chi^2 distribution:
	  F = lyngby_cdf_gauss(sqrt(2*x), sqrt(2*r-1));
	  
	else
	  F = 0;
	  disp(sprintf(['Sorry, lyngby_cdf_chi2 will not ' ...
		'work with these parameters\ndof: %d, x: %f'], r, x));
	end
      end
    
      F = 1/(1 + exp(-(y*(1.5976 + 0.070566*y.^2))));
    end
      




