function [p,q] = dcovar(a,b,c,d,w)
%DCOVAR Covariance response of discrete system to white noise.
%	[P,Q] = DCOVAR(A,B,C,D,W) computes the covariance response of the 
%	discrete state-space system (A,B,C,D) to Gaussian white noise
%	inputs with intensity W,
%
%		E[w(k)w(n)'] = W delta(k,n)
%
%	where delta(k,n) is the kronecker delta.  P and Q are the output
%	and state covariance response:
%
%		P = E[yy'];  Q = E[xx'];
%
%	P = DCOVAR(NUM,DEN,W) computes the output covariance response of
%	the polynomial transfer function system.  W is the intensity of 
%	the input noise.
%
%	See also: COVAR,LYAP and DLYAP.

%	Clay M. Thompson  7-5-90
%       Revised by Wes Wang 8-5-92
%	Copyright (c) 1986-93 by the MathWorks, Inc.

error(nargchk(3,5,nargin));
if ~((nargin==3)|(nargin==5)), error('Wrong number of input arguments.'); end

% --- Determine which syntax is being used ---
if (nargin == 3) % T.F. syntax
  [num,den] = tfchk(a,b);
  w = c;
  [a,b,c,d] = tf2ss(num,den);
end

if (nargin==5), error(abcdchk(a,b,c,d)); end

q = dlyap(a,b*w*b');
p = c*q*c' + d*w*d';

% A valid covariance must be positive semi-definite.
if min(real(eig(q))) < -eps,
  if max(abs(eig(a))) > 1
    disp('Warning: Unstable system. Returning infinity.')
  else
    disp('Warning: Invalid covariance - not positive semi-definite.  Returning infinity.')
  end;
  q = inf*ones(length(q)); p = inf*ones(length(p));
end
