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 (See also)
%	MODSTRUC or CANFORM)
%
%	CD: CD='c' means a continuous-time model. CD='d' denotes a discrete 
%	time model (default CD='d'). For continuous time models there are 
%	two options: CD='czoh' (default) assumes the input to be piecewise
%	constant between the samples (u(t)=u(kT) for kT<=t<kT+T)) while
%	CD='cfoh' assumes the input to be piecewise linear between the
%	samples (u(t) obtained by linear interpolation of the sampled values)
%	(Note that, unlike 'foh' in c2dm in the CSTB, no extra delay is
%	introduced in this case.)
%
%	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 ARX2TH, MF2TH, PEM and THETA.

%	L. Ljung 10-2-1990,10-10-93
%	Copyright (c) 1986-95 by the MathWorks, Inc.
%	$Revision: 1.5 $  $Date: 1995/05/16 09:01:05 $

if nargin < 1
   disp('Usage: TH = MS2TH(MS)')
   disp('       TH = MS2TH(MS,CD,PARAMETERS,LAMBDA,T)')
   disp('       CD is one of ''d'', ''c'', ''czoh'', ''cfoh''.')
   return
end

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=lower(cd);
if cd(1)~='c' & cd(1)~='d', 
  error('CD must start with either ''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(1)=='c',theta(1,2)=-abs(T);else theta(1,2)=abs(T);end
if cd(1)=='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(1)=='c', 
   if strcmp(cd,'cfoh')
      theta(2,8)=11;
   else
      theta(2,8)=1;
   end
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;

