function [yout,x,n] = dinitial(a,b,c,d,x0,n)
%DINITIAL Initial condition response of discrete-time linear systems.
%	DINITIAL(A,B,C,D,X0) plots the time response of the discrete
%	system:
%		x[n+1] = Ax[n] + Bu[n]
%		y[n]   = Cx[n] + Du[n]
%
%	due to an initial condition on the states.  The number of sample
%	points is automatically determined based on the system poles and
%	zeros.  
%
%	DINITIAL(A,B,C,D,X0,N) uses the user-supplied number of points, N.
%	When invoked with left hand arguments:
%		[Y,X] = DINITIAL(A,B,C,D,X0,...)
%	returns the output and state responses (Y and X).  No plot is 
%	drawn on the screen.  The matrix Y has as many columns as outputs
%	and X has as many columns as there are states.
%	
%	See also: DIMPULSE,DSTEP,DLSIM, and INITIAL.

%	Clay M. Thompson  7-6-90
%	Revised ACWG 6-21-92
%	Copyright (c) 1986-93 by the MathWorks, Inc.

if nargin==0, eval('exresp(''dinitial'',1)'), return, end

error(nargchk(4,6,nargin));
error(abcdchk(a,b,c,d));

[ny,nu] = size(d);
if (nu*ny==0)|isempty(a),
	x = []; n = []; if nargout~=0, yout=[]; end, return,
end

[nx,na] = size(a);
if nargin==4,		% No x0 specified, use random initial condition.
	x0 = randn(nx,1);

else
	x0 = x0(:);		% Make sure x0 is a column vector
	if length(x0)~=nx,
		error('The length of X0 must be equal to the number of states.');
	end
end

if (nargin==4)|(nargin==5)  % Workout time vector if not supplied.
	% The next line controls the number of samples in the plot if N not specified
	st=0.005; % Set settling time bound  = 0.5%
	n=dtimvec(a,b,c,x0,st);
end


% --- Simulation ---
[nx,nu] = size(b);
[y,x] = dlsim(a,b,c,d,zeros(n,nu),x0(:));

% Plot Graph
if nargout==0
	status = ishold;
	stairs([0:n-1],y)
	hold on
	plot([0,n-1],[0;0],':')
	xlabel('Sample Number'), ylabel('Amplitude')

	if ~status, hold off, end	% Return hold to previous status
	return % Suppress output
end
yout = y; 
