function theta=ms2th(ms,cd,parval,lambda,T)
%MS2TH  Packages standard state-space parameterizations into the THETA format
%
%	THETA = ms2th(MS,CD,PARVAL,LAMBDA,T)
%
%	THETA: The resulting matrix in the THETA format (See help theta)
%
%	MS: The model structure. Specifies which state space matrix coeff-
% 	icients that are free and which are fixed (Generated by MODSTRUC or 
%	CANFORM)
%
%	CD: CD='c' means a continuous-time model. CD='d' denotes a discrete 
%	time model (default CD='d')
%
%	PARVAL: The values of the free parameters (Default zeros)
%	LAMBDA: The covariance matrix of the innovations (Default Identity)
%	T: The sampling interval (Default 1). For continuous time models this
%	is the sampling interval of the data to be used for the fit in pem.
%	See also MF2TH, ARX2TH

%	L. Ljung 10-2-1990,4-7-92
%	Copyright (c) 1990 by the MathWorks, Inc.
%	All Rights Reserved.

if nargin<5, T=[];end
if nargin<4, lambda=[];end
if nargin<3, parval=[];end 
if nargin<2, cd=[];end
if isempty(T),T=1;end
d1=sum(sum(isnan(ms))');
if isempty(parval),parval=zeros(1,d1);end
if isempty(cd), cd='d';end, cd=cd(1);
if cd~='c' & cd~='d', 
  error('CD must be one of ''c''(ontinuous) or ''d''(iscrete)')
end
[nx,nn]=size(ms);nyy=ms(1,nn);
if nyy<0,arx=1;else arx=0;end
d=length(parval);
if d~=d1 & ~arx, 
  error('Incorrect number of parameter values  have been specified; must be equal to the number of ''NaN'':s in the model structure!')
end

if T<0,
  error('The sampling interval T must be a positive number. Use ''c'' in the second argument to indicate continuous time model!')
end

[rarg,carg]=size(ms);
if cd=='c',theta(1,2)=-abs(T);else theta(1,2)=abs(T);end
if cd=='d',Tmod=-1;else Tmod=abs(T);end
theta(1,6:7)=[rarg,carg];

[a,b,c,Dd,k,x0]=ssmodx9(parval,Tmod,ms);

if ms(1,carg)>0,
   if max(abs(eig(a-k*c)))>1,disp('WARNING: Predictor unstable!'),end
end
[ny,nx]=size(c);[nx,nu]=size(b);
if isempty(lambda),lambda=eye(ny);end
theta(1,1)=det(lambda);
ti=fix(clock);
ti(1)=ti(1)/100;
theta(1,3:5)=[nu ny d];theta(2,1)=theta(1,1);
theta(2,2:6)=ti(1:5);
theta(2,7)=21;
if cd=='c', theta(2,8)=1;else theta(2,8)=2;end
if d>0,
	theta(3,1:d)=parval;
end
theta(4+d:3+d+rarg,1:carg)=ms;
theta(4+d+rarg:3+ny+d+rarg,1:ny)=lambda;

