function eta=arx2th(A,B,ny,nu,lam,Tsamp)
%ARX2TH	constructs the THETA-format for an ARX model
%
%	th=arx2th(A,B,ny,nu)
%
%	A,B: The given matrix polynomials for a (possibly) multivariable
%	ARX-model  
%	y(t) + A1 y(t-1) + .. + An y(t-n) = 
%	= B0 u(t) + ..+ B1 u(t-1) + .. Bm u(t-m)
%	A = [I A1 A2 .. An],  B=[B0 B1 .. Bm]
%	ny, nu : The number of outputs and inputs, respectively
%
%	TH is returned as a model structure (in the THETA-format, see HELP 
%	theta)	where free parameters are consistent with the structure of A 
%	and B, i.e. leading zeros in the rows of B are regarded as fixed 
%	delays, and trailing zeros in the rows of A and B are regarded as a 
%	definition of lower order polynomials. These zeros will thus be 
%	regarded as fixed while all other parameters are free. The nominal 
%	values of these free parameters are set equal to the values in A and B.
%	With th = arx2th(A,B,ny,nu,LAMBDA,Tsamp) also the innovations covarian-
%	ce matrix LAMBDA and the sampling interval Tsamp can be specified.
%
%	See also TH2ARX, and ARX

%        L. Ljung 10-2-90,11-2-91
%        Copyright (c) 1986-90 by the MathWorks, Inc.
%        All Rights Reserved.

if nargin<6, Tsamp=[];end, if nargin<5, lam=[];end
if isempty(Tsamp),Tsamp=1;end, if isempty(lam),lam=eye(ny);end
[ra,ca]=size(A);if isempty(B),rb=ra;nu=0;else [rb,cb]=size(B);end
na=(ca-ny)/ny; if nu>0,nb=(cb-nu)/nu;else nb=0;end
if ra~=ny | rb~=ny, error('The A and the B polynomials must have the same number of rows as the number of outputs!'),end
if floor(na)~=na | floor(nb)~=nb,error('The size of A or B is not consistent with an ARX-model! The number of columns must be a multiple of the number of rows'),end
for outp=1:ny
for kk=1:ny
sl=A(outp,ny+kk:ny:na*ny+ny);
sl=(sl~=0);sl=sl(length(sl):-1:1);
sl=cumsum(sl);ksl=max(find(sl==0));if length(ksl)==0,ksl=0;end

nna(outp,kk)=na-ksl;
end
for kk=1:nu
sl=B(outp,kk:nu:nb*nu+nu);
sl1=(sl~=0);ksl=max(find(cumsum(sl1)==0));
if length(ksl)==0,ksl=0;end
nnk(outp,kk)=ksl;
sl1=sl1(length(sl1):-1:1);sl=cumsum(sl1);
ksl=max(find(sl==0));if length(ksl)==0,ksl=0;end
if ksl==nb+1,nnb(outp,kk)=0;nnk(outp,kk)=0;else
nnb(outp,kk)=nb-ksl-nnk(outp,kk)+1;end
end
end

nn=[nna nnb nnk];
nd=sum(sum(nna)')+sum(sum(nnb)');
eta0=mketaarx(nn,ones(1,nd));
[A1,B1]=th2arx(eta0);[ra,ca]=size(A1);[rb,cb]=size(B1);
A1=A1(:,ny+1:ca);
Am=A(:,ny+1:ca);
B2=B1(:,nu+1:cb);Bm=B(:,nu+1:cb);
C=[A1 B2];
par=[];
for kk=1:ny
if ~isempty(Am),filla=-Am(kk,find(A1(kk,:)==-1));else filla=[];end
if ~isempty(Bm),fillb=Bm(kk,find(B2(kk,:)==1));else fillb=[];end
par=[par filla fillb];
end

for kk=1:ny
if nu>0,par=[par B(kk,find(B1(kk,1:nu)==1))];end
end
eta=mketaarx(nn,par,lam,Tsamp);
eta(2,7)=32;

