function [num,den,NeedsPadding] = utFormatNumDen(num,den,RightFlag)
% Equalizes the length of numerator and denominator vectors and
% trims extra leading/trailing zeros.
%
% When RIGHTFLAG=FALSE (z,q variables), this function
%   * Removes extra leading zeros in NUM and DEN
%   * Left-pads NUM or DEN with zeros to equalize their length.
%
% When RIGHTFLAG=TRUE (z^-1,q^-1 variables), this function
%   * Removes extra leading and trailing zeros in NUM and DEN
%   * Right-pads NUM or DEN with zeros to equalize their length.
%
% On exit, NUM(1) or DEN(1) is always nonzero.
%
% STATIC METHOD.

%   Author: P. Gahinet, 5-1-96
%   Copyright 1986-2012 The MathWorks, Inc.
NeedsPadding = false;
if RightFlag
   for k = 1:numel(num)
      nk = num{k};
      dk = den{k};
      % Pad zeros to the right to make num/den of equal length
      lgap = length(dk) - length(nk);
      if lgap~=0
         nk = [nk , zeros(1,lgap)]; %#ok<*AGROW>
         dk = [dk , zeros(1,-lgap)];
      end
      % Remove leading and trailing zeros appearing in both num and den
      % (delete leading zeros to ensure that num(1) or den(1) is always nonzero)
      ind = find(nk~=0 | dk~=0);
      num{k} = nk(ind(1):ind(end));
      den{k} = dk(ind(1):ind(end));
   end
else
   for k = 1:numel(num)
      nk = num{k};
      dk = den{k};
      % Pad zeros to the left to make num/den of equal length
      lgap = length(dk) - length(nk);
      if lgap~=0
         NeedsPadding = true;
         nk = [zeros(1,lgap) , nk];
         dk = [zeros(1,-lgap) , dk];
      end
      % Remove leading zeros appearing in both num and den
      if nk(1)==0 && dk(1)==0
         ld = length(dk);
         ind = find(nk~=0 | dk~=0);
         nk = nk(ind(1):ld);
         dk = dk(ind(1):ld);
      end
      num{k} = nk;
      den{k} = dk;
   end
end
