function [A,B,C,D,K,X0]=ssmodx9(th,T,mod)
%SSMODX9 The standard state-space model
%
%	[A,B,C,D,K,X0] = ssmodx9(PARVAL,T,MS)
%
%	This routine is used as the standard model-defining routine
%	inside the THETA-structure for state space models if no user-
%	defined structure is specified. The use of SSMODx9 should be
%	transparent to the user.
%
%	A,B etc: The discrete time state space matrices corresponding to
%	the parameter values PARVAL for a linear model structure
%	defined by MS (obtained from MODSTRUC or CANFORM)

%	L. Ljung 10-2-90,11-25-93
%	Copyright (c) 1986-95 by the MathWorks, Inc.
%	$Revision: 1.2 $  $Date: 1995/01/24 00:54:03 $
	
[dum,nn]=size(mod);nyy=mod(1,nn);nx=mod(2,nn);
ny=abs(nyy);nu=(nn-nx-2*ny-2)/2;
s=1;
if nyy<0,arx=1;else arx=0;end
na=0;
if arx,
as1=mod(1:nx,1:nx);
sumas=sum4vms(as1');
nr=find(sumas==0&~isnan(sumas));
if isempty(nr),na=nx/ny;else na=(nr(1)-1)/ny;end
end
A=mod(1:nx,1:nx);
for kr=1:nx
	for kc=1:nx
	if isnan(A(kr,kc)), A(kr,kc)=th(s);s=s+1;end
	end
end
B=mod(1:nx,nx+1:nx+nu);
for kr=1:nx
	for kc=1:nu
	if isnan(B(kr,kc)),B(kr,kc)=th(s);s=s+1;end
	end
end
if na==0
C=mod(1:nx,nx+nu+1:nx+nu+ny)';
for kr=1:ny
	for kc=1:nx
	if isnan(C(kr,kc)),C(kr,kc)=th(s);s=s+1;end
	end
end
if nu==0, D=[];else D=mod(1:ny,nx+nu+ny+1:nx+2*nu+ny);end
for kr=1:ny
	for kc=1:nu
	if isnan(D(kr,kc)),D(kr,kc)=th(s);s=s+1;end
	end
end
else
C=A(1:ny,1:nx);
if nu>0,D=B(1:ny,:);else D=[];end
end
K=mod(1:nx,nx+2*nu+ny+1:nx+2*nu+2*ny);
for kr=1:nx
	for kc=1:ny
	if isnan(K(kr,kc)),K(kr,kc)=th(s);s=s+1;end
	end
end

X0=mod(1:nx,nx+2*nu+2*ny+1);
for kr=1:nx
	if isnan(X0(kr)),X0(kr)=th(s);s=s+1;end
end
if T>0 % We shall in this case sample the model with sampling interval T
s = expm([[A [B K]]*T; zeros(nu+ny,nx+nu+ny)]);
A = s(1:nx,1:nx);
B = s(1:nx,nx+1:nx+nu);
K = s(1:nx,nx+nu+1:nx+nu+ny);
end

