function [a,b,c,d,e] = elimAV(a,b,c,d,e,EBCscale,EXPLICIT)
% Eliminates algebraic variables (adapted from ISPROPER).
% Numerically superior especially for MatchDC because it
% eliminates most algebraic states in stages 1-2 using 
% only row/column compressions

% Copyright 2023 The MathWorks, Inc.

% Note: For rank tests,
% 1) Scale E by the norm of original E matrix
% 2) Scaled B,C by the norms of the original B,C rather than the norms
%    of Br,Cr which can be zero within rounding errors (g371439)
if any(e,'all')
   [a,b,c,e,rkE] = minreal_inf(a,b,c,e,EBCscale);
else
   % Go straight to elimAV when E=0 (static gain). Helps for dNUM_OrderReduction:FullC
   rkE = 0;
end
if rkE<size(a,1)
   % Eliminate remaining algebraic variables, keeping growth factor in check
   [a,b,c,d,e] = elimAV(a,b,c,d,e,rkE,eps^(1/3));
   EDIAG = true;  % reduced E is diagonal and positive
else
   EDIAG = false;
end

if EXPLICIT && rkE>0 && rkE==size(a,1)
   % Eliminate E when original model is explicit and reduced model is proper
   if EDIAG
      % Exploit diagonal structure of E
      s = 1./sqrt(diag(e));
      a = a .* (s * s');  b = s .* b;  c = c .* s';
   else
      [a,b] = ltipack.utElimE(a,b,e);
   end
   e = [];
end
