function eta=mf2th(model,cd,parval,aux,lambda,T)
%MF2TH  Packages user defined model structures into the THETA model format
%
%	TH = mf2th(MODEL,CD,PARVAL,AUX,LAMBDA,T)
%
%	TH: The resulting model matrix
%
%	MODEL: The model structure specified as	the name of a user-written 
%	m-file, which should have the format
%
%		[a,b,c,d,k,x0]=username(parameters,T,AUX)
%
%	Then MODEL='username'. See HELP SSMODEL for the format.
%	CD: CD='c' if 'username' provides a continuous time model when called
%	with a negative value of T. Else CD = 'd'.
%	PARVAL: The values of the free parameters
%	AUX:   The values of auxiliary parameters in the user-written m-file 
%	above.
%	LAMBDA: The covariance matrix of the innovations
%	T: The sampling interval of the data (always a positive number)
%	Default values: AUX=[]; T=1; LAMBDA=identity

%	L. Ljung 10-2-1990
%	Copyrigth (c) 1990 by the MathWorks, Inc.
%	All Rights Reserved.

if nargin<3,error('File name, cont/discrete, and parameters must be specified!'),end

if nargin<6, T=[];end
if nargin<5, lambda=[];end
if nargin<4, aux=[];end
if isempty(T),T=1;end
if isempty(aux),aux=0;end % This is due to a bug in feval (destroys results if
	                  % one argument is [])
[prd,pcd]=size(parval);if prd>pcd,parval=parval';end;d=length(parval);
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(aux);
if ~isstr(cd),error('The argument cd must be a string'),end
if cd=='c',eta(1,2)=-T;else eta(1,2)=T;end

eta(1,6:7)=[rarg,carg];
eta(1,8:7+length(model))=model;
[a,b,c,Dd,k,x0]=feval(model,parval,T,aux);
[nx,nx1]=size(a);[nx2,nu]=size(b);[ny,nx3]=size(c);[ny1,nu2]=size(Dd);
[nx4,ny2]=size(k);[nx5,ett]=size(x0);
if nu==0,nx2=nx;ny1=ny;end,
if nx~=nx1,error('A-matrix in m-file must be square!'),end
if nx~=nx2,error('The B-matrix in m-file must have the same number of rows as A'),end
if nx~=nx3,error('The C-matrix in m-file must have the same number of columns as A!'),end
if nx~=nx4,error('The K-matrix in m-file must have the same number of rows as A!');end
if nx~=nx5,error('Incorrect size of initial value vector!'),end
if ett~=1,error('X0 must be column vector!'),end
if nu~=nu2,error('D-matrix in m-file must have same number of columns as B!'),end
if ny~=ny1,error('D-matrix in m-file must have same number of rows as C!'),end
if ny~=ny2,error('K-matrix in m-file must have same number of columns as C has rows!'),end

if max(abs(eig(a-k*c)))>1+10*eps,disp('WARNING: Predictor unstable!'),end
if isempty(lambda),lambda=eye(ny);end
eta(1,1)=det(lambda);eta(1,[3:5])=[nu ny d];

ti=fix(clock);
ti(1)=ti(1)/100;
eta(2,1)=d;
eta(2,2:6)=ti(1:5);
eta(2,7)=22;
if cd=='c',eta(2,8)=5;else eta(2,8)=4;end
eta(3,1:d)=parval;
%eta(4:3+d,1:d)=zeros(d,d);
eta(4+d:3+d+rarg,1:carg)=aux;
eta(4+d+rarg:3+ny+d+rarg,1:ny)=lambda;


