function varargout = gdare(H,J,n,varargin)
%GDARE  Generalized solver for discrete algebraic Riccati equations.
%
%   GDARE is obsolete, please use IDARE instead.
%
%   See also IDARE.

% Old help:
%GDARE  Generalized solver for discrete algebraic Riccati equations.
%
%   [X,L] = GDARE(H,J,NS) computes the unique stabilizing solution 
%   X of the discrete-time algebraic Riccati equation associated  
%   with Symplectic pencils of the form
% 
%                    [  A   0   B  ]       [ E   0   0 ]
%        H - t J  =  [ -Q   E' -S  ]  - t  [ 0   A'  0 ]
%                    [  S'  0   R  ]       [ 0  -B'  0 ]
% 
%   The third input NS is the row size of the A matrix. The output
%   L is the vector of closed-loop eigenvalues.
%
%   [X,L,REPORT] = GDARE(H,J,NS) suppresses errors when X fails
%   to exist. The diagnosis REPORT is set to:
%     * -1 when the Symplectic pencil has eigenvalues on the unit circle
%     * -2 when there is no finite stabilizing solution X
%     * 0 when a finite stabilizing solution X exists.
%
%   [X1,X2,D,L] = GDARE(H,J,NS,'factor') returns two matrices X1, X2 
%   and a diagonal scaling matrix D such that X = D*(X2/X1)*D.
%   The vector L contains the closed-loop eigenvalues.  All outputs 
%   are empty when the Symplectic pencil has eigenvalues on the 
%   unit circle.
%
%   [...] = GDARE(H,...,'nobalance') disables automatic scaling of 
%   the data.
%
%   See also DARE, GCARE.

%   Author(s): Pascal Gahinet
%   Copyright 1986-2009 The MathWorks, Inc.

% Flags
% String support: strcmp does not support cells for strings
FactorFlag = any(cellfun(@(x) strcmp(x,'factor'),varargin));
if any(cellfun(@(x) strcmp(x,'nobalance'),varargin))
   NewFlags = {'noscaling'};
else
   NewFlags = {};
end

n2 = 2*n;
m = size(H,1)-n2;
if ~isequal(size(H),size(J))
   error(message('Control:foundation:ARE25','gdare'))
elseif m<0
   error(message('Control:foundation:ARE28','gdare'))
end

% Extract matrices
A = H(1:n,1:n);
E = J(1:n,1:n);
Q = -H(n+1:n2,1:n);
B = H(1:n,n2+1:n2+m);
S = -H(n+1:n2,n2+1:n2+m);
R = H(n2+1:n2+m,n2+1:n2+m);

% Call IDARE
try
   [X,~,L,INFO] = idare(A,B,Q,R,S,E,NewFlags{:});
catch ME
   throw(ME)
end

% Set REPORT flag
switch INFO.Report
   case 3
      Report = -1;  % Hamiltonian pencil has jw-axis eigenvalues
   case 2
      Report = -2;  % there is no finite stabilizing solution X
   otherwise
      Report = 0;
end
   
% Process results and build outputs
if FactorFlag
   % Factored form
   X1 = INFO.U;
   X2 = INFO.V;
   if isempty(X1)
      D = [];
   else
      Sx = INFO.Sx;
      D = diag(Sx);
      if ~isempty(E)
         Z = orth([Sx .* E * (Sx .\ X1); X2]);
         X1 = Z(1:n,:);   X2 = Z(n+1:n2,:);
      end
   end
   varargout = {X1 X2 D L Report};
else
   if nargout<3
      switch Report
         case -1
            error(message('Control:foundation:ARE22'))
         case -2
            error(message('Control:foundation:ARE20'))
      end
   end
   varargout = {X L Report};
end
