function [ITER,B,T,flg] = ILPRevisedSimplex(A,B,c,T)
%
% This is the Simplex Method using the Revised Simplex Tableau.
% We assume the Tableau T has been initialized on input.
% Written by Ming Gu for Math 170
% March 2007
%
% flg = 0: convergence
% flg = 1: LP unbounded below
% flg = 2: LP degenerate
%
simplex = 1;
ITER    = 0;
[m,n]   = size(A);
x       = zeros(n,1);
x(B)    = T(1:m,1);
flg     = 0;
obj     = c'*x;
ctol    = 1e-13;
while (simplex == 1)
%
% determine the next s and r values.
%
   y        = T(end,2:end)';
   [Y, I]   = sort(c-A'*y);
   mask     = find(Y<-ctol);
%
% check if the iteration has converged.
%
   if (length(mask)<1)
%%%       disp('Simplex Method has converged');
       simplex = 0;
       continue;
   end
   sflg = 1;
   for sk = 1:length(mask)
%
% loop over all possible s choices to reduce
% chance of non-convergence due to degeneracy.
%
       s    = I(sk);
       zmin = Y(sk);
       t    = T(1:end-1,2:end)*A(:,s);
       r    = Revisedgetr(n,s,B,T,t);
       if (r < 1)
          disp('LP has no lower bound');
          simplex = 0;
          flg     = 1;
          continue;
       end
       [Tnew,Bnew,flg] = RevisedSimplexTableau(B,r,s,t,zmin,T);      
       if (flg == 0 & Tnew(end,1)-obj < -ctol)
%
% success. update the revised simplex tableau.
%
           sflg = 0;
           B    = Bnew;
           T    = Tnew;
           obj  = T(end,1);
           ITER = ITER + 1;
           f = ['Iteration ', num2str(ITER), ' Obj ', ...
                num2str(obj), '. c-A^T*y componet = ', ... 
                num2str(zmin), ' at s =', num2str(s), '. Kicked out r = ', ...
                num2str(r)];
%%%           disp(f);
           break;
       end
    end
    if (sflg == 1)
%
%  none of the s choices was good enough to avoid degeneracy. Give up.
%
        disp('LP is degenerate');
        simplex = 0;
        flg     = 2;
%%%        disp(T(1:end-1,1));
        continue;
    end
end




