function [a,b,c,d,k,x0]=th2ssaux(th);
%TH2SSAUX	An auxiliary routine to TH2SS
%
%	[a,b,c,d,k,x0]=th2ssaux(th);

%	L. Ljung 10-2-90,10-10-93
%	Copyright (c) 1986-95 by the MathWorks, Inc.
%	$Revision: 1.4 $  $Date: 1995/01/24 00:54:03 $

T=th(1,2);
[ap,bp,cp,dp,fp]=th2poly(th);
nu=th(1,3);
if nu>0
    na=th(1,4);nb=th(1,5:4+nu);nc=th(1,5+nu);nd=th(1,6+nu);
    nf=th(1,7+nu:6+2*nu);nk=th(1,7+2*nu:6+3*nu);nf1=max(nd,max(nf))+1;
else
    na=th(1,4);nc=th(1,5);nd=th(1,6);
    nk=0;nb=0;nf=0;nf1=nd+1;fp=1;
end

if T>0
  fp(nu+1,1:length(dp))=dp;
else
  fp(nu+1,1:nf1)=zeros(1,nf1);fp(nu+1,nf1-nd:nf1)=dp;
end
nf(nu+1)=nd;

for ku=1:nu+1
  if T>0 findx=1:nf(ku)+1;else findx=nf1-nf(ku):nf1;end
  ffp=fp(ku,findx);
  ap=conv(ap,ffp);
  if ku==nu+1
    btemp=cp;
  else
    if T>0,btemp=bp(ku,1:nb(ku)+nk(ku));
    else   btemp=bp(ku,nk(ku)+1:nb(ku)+nk(ku));
    end
  end
  for kku=1:nu+1
    if T>0 findx=1:nf(kku)+1;else findx=nf1-nf(kku):nf1;end
    if kku~=ku,btemp=conv(btemp,fp(kku,findx));end
  end
  bpp(ku,1:length(btemp))=btemp;nbpp(ku)=length(btemp);
end
[dum,maxindb]=size(bpp);nap=length(ap);nab=max(maxindb,nap);
bp=zeros(nu+1,nab);
if T<=0,
if maxindb>nap,error('Pure differentiations of inputs. No state-space model produced.'),end

for ku=1:nu+1,bp(ku,:)=[zeros(1,nab-nbpp(ku)) bpp(ku,1:nbpp(ku))];end

else

bp=[bpp,zeros(nu+1,nab-maxindb)];end
app=zeros(1,nab);app(1:nap)=ap;
d=bp(1:nu,1)';
if bp(nu+1,1)~=1,
   disp('WARNING: Noise model indicates no white noise component.')
   disp('Resulting state-space model has unreliable noise structure.')
end
bp=bp-bp(:,1)*app;
nx=nab-1;
bt=bp(:,2:nab);
at=app(2:nab)';

a=[-at,eye(nx,nx-1)]; % Transform to state-space
b=bt(1:nu,:)';
c=[1 zeros(1,nx-1)];
k=bt(nu+1,:)';
x0=zeros(nx,1);
