function [a,b,c,d,f,lam]=th2poly(th)
%TH2POLY computes the polynomials associated with a given model
%
%	[A,B,C,D,F,LAM]=th2poly(TH)
%
%	TH is the model with format described by HELP THETA.
%
%	A,B,C,D, and F are returned as the corresponding polynomials
% 	in the general input-output model. A, C and D are then row
%	vectors, while B and F have as many rows as there are inputs.
%	LAM is the variance of the noise source.

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


if isthss(th),error('TH2POLY does not work for state-space models and Multivariable ARX-models. Use TH2TF or TH2ARX instead!'),end
T=gett(th);
nu=th(1,3);
na=th(1,4);,if nu>0,nb=th(1,5:4+nu);,end,nc=th(1,5+nu);,nd=th(1,6+nu);, if nu>0,nf=th(1,7+nu:6+2*nu);,nk=th(1,7+2*nu:6+3*nu);,end
Nacum=na;,Nbcum=Nacum+sum(nb);,Nccum=Nbcum+nc;,Ndcum=Nccum+nd;
Nfcum=Ndcum+sum(nf);
a=[1 th(3,1:Nacum)];
c=[1 th(3,Nbcum+1:Nccum)];
d=[1 th(3,Nccum+1:Ndcum)];
if nu==0, b=0;,f=1;,end
b=zeros(nu,max(nb+nk));nf1=max(nf)+1;f=zeros(nu,nf1);
s=1;,s1=1;
for k=1:nu
      if nb(k)>0,
      b(k,nk(k)+1:nk(k)+nb(k))=th(3,na+s:na+s+nb(k)-1);
      end
      if T>0,if nf(k)>0,
      f(k,1:nf(k)+1)=[1 th(3,Ndcum+s1:Ndcum+nf(k)+s1-1)];
      else f(k,1)=1;end
      else, if nf(k)>0
      f(k,nf1-nf(k):nf1)=[1 th(3,Ndcum+s1:Ndcum+nf(k)+s1-1)];
      else f(k,nf1)=1;end
      end
      s=s+nb(k);,s1=s1+nf(k);
end
