function [ a_fac, info ] = spofa ( a, lda, n )

%*****************************************************************************80
%
%% SPOFA factors a real symmetric positive definite matrix.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    31 March 2013
%
%  Author:
%
%    FORTRAN77 version by Cleve Moler.
%    MATLAB version by John Burkardt.
%
%  Parameters:
%
%    Input, real A(LDA,N), the symmetric matrix to be factored.  Only the 
%    diagonal and upper triangle are accessed.
%
%    Input, integer LDA, the leading dimension of the array A.
%    N <= LDA.
%
%    Input, integer N, the order of the matrix.
%
%    Output, real A_FAC(LDA,N), an upper triangular matrix R such that
%    A = R' * R.  If INFO is nonzero, the factorization was not completed.
%
%    Output, integer INFO, error flag.
%    0, no error was detected.
%    K, the leading minor of order K is not positive definite.
%
  a_fac(1:n,1:n) = a(1:n,1:n);
  for i = 2 : n
    for j = 1 : i - 1
      a_fac(i,j) = 0.0;
    end
  end

  info = 0;

  for j = 1 : n
    info = j;
    s = 0.0;
    for k = 1, j - 1
      t = a_fac(k,j) - a_fac(1:k-1,k)' * a_fac(1:k-1,j);
      t = t / a_fac(k,k);
      a_fac(k,j) = t;
      s = s + t * t;
    end
    s = a_fac(j,j) - s;
    if ( s <= 0.0 )
      info = j;
      return
    end
    a_fac(j,j) = sqrt ( s );
  end

  return
end
