function [num,den]=th2tf(th,iu)
%TH2TF	Transforms from the THETA-format to transfer functions.
%	[NUM,DEN] = TH2TF(TH,IU)
%
%	TH: The model, defined in the THETA-format (See also THETA).
%
%	IU: The input number (default 1) to be considered. Noise source
%           number ni is counted as input number -ni.
%	NUM: The numerator(s) of the transfer function. For a multivariable
%	     model row k of NUM gives the transfer function from input # IU
%	     to output # k.
%	DEN: The denominator of the transfer function. (Common to all outputs)
%
%	NUM and DEN are given in the standard formats of the Control Systems
%	Toolbox (both for continuous and discrete time models)
%	See also TH2FF, TH2POLY, TH2SS and TH2ZP.

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

if nargin < 1
   disp('Usage: [NUMERATOR(S), DENOMINATOR] = TH2TF(TH)')
   disp('       [NUMERATOR(S), DENOMINATOR] = TH2TF(TH,INPUT_NUMBER)')
   return
end

nu=th(1,3);
if nargin<2,if nu>0,iu=1;else iu=-1;end,end;if iu==0,iu=-1;end
if iu>nu,error('There are not that many inputs in the system'),end
if isthss(th), 
	[a,b,c,d,k]=th2ss(th);	
	[mc,nc] = size(c);dk=eye(mc);
	den = poly(a);
	if iu>0,b = b(:,iu);d=d(:,iu);
	else b=k(:,-iu);d=dk(:,-iu);end
	
	num = ones(mc, nc+1);
	for i=1:mc
		num(i,:) = poly(a-b*c(i,:)) + (d(i) - 1) * den;
		nnd(i)=max(find(abs(num(i,:))>eps));
	end

nd=max(find(abs(den)>eps));ord=max([nd nnd]);
den=den(1:ord);num=num(:,1:ord);

return,end
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

[a,b,c,d,f]=th2poly(th);T=th(1,2);
if iu>0,den=conv(a,f(iu,1:nf(iu)+1));else den=conv(a,d);end
if iu>0,num=b(iu,1:nb(iu)+nk(iu));else num=c;end
ld=length(den);ln=length(num);mn=max(ld,ln);
if T>0,den=[den,zeros(1,mn-ld)];num=[num,zeros(1,mn-ln)];
else den=[zeros(1,mn-ld),den];num=[zeros(1,mn-ln),num];end
