function t = scaleR(anorm,bnorm,rnorm)
% Scales 
%    [ anorm  bnorm ]        [  anorm    t*bnorm  ]
%    [              ]  --->  [                    ]
%    [ bnorm  rnorm ]        [ t*bnorm  t^2*rnorm ]
% to minimize the numerical range (ratio between largest and smallest
% nonzero entries).
% 
% This is useful to scale the Riccati pencils
%
%    [ A-s*E   G       B]      [ A-s*E    G      t*B ]
%    [  -Q   -A'-s*E' -S]  ->  [  -Q   -A'-s*E' -t*S ]   (continuous time)
%    [   S'    B'      R]      [  t*S'   t*B'   t^2*R]
%
% or 
% 
%    [ A-z*E   0       B]      [ A-z*E   0       t*B ]
%    [  -Q   E'-z*A'  -S]  ->  [  -Q   E'-z*A'  -t*S ]   (discrete time)
%    [   S'   z*B'     R]      [  t*S'  t*z*B'  t^2*R]
%
% by setting ANORM to the norm of (A,G,Q), BNORM to the norm of (B,S),
% and RNORM to the norm of R.

%   Copyright 1986-2018 The MathWorks, Inc.
   
% NOTE: Placeholder for full/optimal R scaling
if anorm>0 && rnorm>0
   % Minimize cond([anorm t*bnorm;t*bnorm t^2*rnorm])
   t = sqrt(anorm/rnorm);
elseif bnorm>0
   % This is within a factor 2.5 of optimal conditioning (4 for t=Inf)
   t = (anorm+rnorm)/bnorm;
else
   t = 1;
end