function ths = ss2th(th,psobs)
%SS2TH  Produces a paramaterized state-space model.
%       THS = SS2TH(TH,ORDERS)
%
%       TH:  Original model in THETA format
%       THS: Model in THETA format, corresponding to a state
%            space representation in a canonical form corresponding
%            th 'pseudobservability indexes' ORDERS. 
%
%	Nominal parameter values are taken from the nominal or fixed values in TH.
%       If K, D and/or X0 is all zero in TH, this will make these matrices fixed 
%       to zero also in THS.
%       If ORDERS is omitted, a default choice is made.
%
%       See also CANFORM, CANSTART and MS2TH

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

if nargin<1
  disp('Usage: THS = SS2TH(TH)')
  disp('       THS = SS2TH(TH,ORDERS)')
  return
end
[a,b,c,d,k,x0]=th2ss(th);
Tsamp=gett(th);
[n,dum]=size(a);
[dum,nu]=size(b);[ny,dum]=size(c);
if nargin<2
   ind1=floor(n/ny);
   for kc=1:ny-1
       psobs(kc)=ind1;
   end
   if ny>1
      psobs(ny)=n-sum(psobs);
   else
      psobs=n;
   end
end
np=sum(psobs);
if any(psobs<0)
   error('The order indices must be non-negative.')
end
if length(psobs)~=ny,
   error('The number of order indices must be equal to the number of outputs.')
end
if np~=n,
   error('The sum of the order indices must equal the model order.')
end

psnz=find(psobs>0);
psz=find(psobs==0);
psmod=psobs(psnz);
if ~isempty(psz),cmod=c(psnz,:);nymod=length(psnz);else cmod=c;nymod=ny;end
r=cumsum(psmod);
o1=zeros(n,n);
rown=[];kc=1;
for ky=1:nymod
  for koi=0:psmod(ky)-1
     rown=[rown,koi*nymod+ky];
     if ky==1,rr=0;else rr=r(ky-1);end
     o1(kc,rr+1+koi)=1;
     kc=kc+1;
  end
end
o2=zeros(n*ny,n);
for jk = 1:ny
    xx = ltitr(a',zeros(n,1),zeros(n,1),c(jk,:)');
    o2(jk:ny:ny*(n-1)+jk,:) = xx;
end
o2=o2(rown,:);
T=inv(o2)*o1;
Ti=inv(o1)*o2;
ac=Ti*a*T;bc=Ti*b;kc=Ti*k;cc=c*T;x0=Ti*x0;
ms=canform(psobs,nu,[1,1,1]);
par=[];
for kl=r
   par=[par,ac(kl,:)];
end
if nu>0
for kl=1:n
   par=[par,bc(kl,:)];
end
end
for kl=psz
   par=[par,cc(kl,:)];
end
if nu>0
for kl=1:ny
   par=[par,d(kl,:)];
end
end
for kl=1:n
   par=[par,kc(kl,:)];
end
for kl=1:n
   par=[par,x0(kl)];
end
ths=ms2th(ms,'d',par);
ths=sett(ths,Tsamp);
if norm(k)==0
   ths=fixpar(ths,'k');
end
if norm(d)==0
   ths=fixpar(ths,'d');
end
if norm(x0)==0
   ths=fixpar(ths,'x0');
end
