function [A,errflag] = ge_naive(A)
%
% Performs naive Gaussian elimination on a square matrix A. 
%
% Input: 
%     A  = square matrix
%
% Outputs: 
%       A  = matrix with the upper triangular factor of A in the 
%            upper triangular part and the multipliers in strict lower 
%            triangular part. 
% errflag = error flag: 
%           0 => elimination completed with no error
%           k>0 => elimination stopped with zero pivot at step k
%

n = size(A,1);
if n ~= size(A,2), error('\n The matrix must be square.\n'); end

maxA = max(max(abs(A)));

errflag = 0;

% Elimination loop. 
for k = 1:n-1,
% Check for zero pivot. 
maxA\abs(A(k,k))
  if maxA\abs(A(k,k)) < 100*eps,
      fprintf('\n Elimination stopped with dangerously small pivot at step %d.\n', k);
      errflag = k;
      break;
  end
% Form the kth column of multipliers. 
  A(k+1:n,k) = -A(k,k)\A(k+1:n,k);
% Perform the kth elimination step. 
  A(k+1:n,k+1:n) = A(k+1:n,k+1:n) + A(k+1:n,k)*A(k,k+1:n);
end

if maxA\abs(A(n,n)) < 100*eps, 
     fprintf('\n Elimination completed but near-singularity indicated at step %d.\n', n);
     errflag = n;
end
