function Ab = gebueler(Ab)
% GEBUELER  Gaussian Elimination implemented as a function on augmented matrices.
% Only pivots when unavoidable exact zero is on diagonal.
% (Does not do partial pivoting, so it is NOT for serious use.)
%
% Example:
%   >> Ab = [3 2 -1 4; -1 1 1 -1; 2 0 2 5]  % enter system of equations
%   >> Uc = gebueler(Ab)                    % generate transformed augmented
%                                           %   matrix with upper triangular shape
%   >> Ab(:,1:3) \ Ab(:,4)                  % check answer using backslash: these
%   >> Uc(:,1:3) \ Uc(:,4)                  %   two uses of \ should give same
%
% See also:  draft_ge.m shows early version described in class.
% Note: Implementation of back-substitution is still needed to solve systems.

n = size(Ab,1);             % number of rows = number of equations
if size(Ab,2) < n           % check on reasonable shape of augmented matrix
  error('augmented matrix Ab should have at least as many columns as rows')
end
printf('  gauss elimination (row reduction) of system of n = %d equations\n',n)

for i = 1:n-1               % go through cols in which to make zeros
  p = i;
  while Ab(i,p) == 0        % here is where partial pivoting would look different
    if p == n, error('no soln'), end
    p = p+1;
  end
  if p > i
    tmp = Ab(i,:);
    Ab(i,:) = Ab(p,:);
    Ab(p,:) = tmp;
  end
  for j = i+1:n             % go through rows below diagonal (pivot) position
    m = Ab(j,i) / Ab(i,i);  % multiplier
    Ab(j,:) = Ab(j,:) - m * Ab(i,:);  % operation:   E_j <- E_j - # E_i
  end
end 
if Ab(n,n) == 0, error('no soln'), end
printf('  system has unique solution\n')

