function thred=idmodred(th,order,oe)
%IDMODRED  Reduces the order of models.
%       THRED = IDMODRED(TH,ORDER,OE)
%
%       TH: Original model in THETA format.
%       ORDER: Desired order of reduced model.
%          If ORDER=[] (default), a plot is shown, and you are
%	   prompted to select the order.
%       OE: If OE='oe', an output error model is produced,
%           otherwise also the noise model is reduced.
%       THRED: The reduced order model in THETA format.
%
%       The routine is based on (d)balreal and (d)modred in the
%       Control Systems Toolbox.
%	See also BALREAL, DBALREAL, DMODRED, MODRED, THETA.

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

if nargin < 1
   disp('Usage: THRED = IDMODRED(TH)')
   disp('       THRED = IDMODRED(TH,ORDER,OE)')
   disp('       OE is one of ''no_oe'', ''oe''.')
   return
end

if ~exist('dbalreal'),
    error('This routine requires the Control Systems Toolbox!')
end
if nargin<3,oe=[];end
if nargin<2,order=[];end

if strcmp(oe,'oe'), isoe=1;else isoe=0;end
if isthss(th)
     ny=th(1,4);
else
     ny=1;
end
nu=th(1,3);T=gett(th);
[a,b,c,d,k,x0]=th2ss(th);
if isoe,
      bk=b;dd=d;
else 
      bk=[b k];dd=[d,eye(ny)];
end
if T>0
  [ab,bb,cb,g,t]=dbalreal(a,bk,c);
else
  [ab,bb,cb,g,t]=balreal(a,bk,c);
end
ab=real(ab);bb=real(bb);cb=real(cb);g=real(g);t=real(t);
x0=t*x0;
if isempty(order)
   stem(1:length(g),log(g)),xlabel('order'),ylabel('log of weight')
   title('Select order in the Command Window')
   order=input('Type the desired order:   ')
end
if T>0
    [ar,br,cr,dr]=dmodred(ab,bb,cb,dd,[sum(order)+1:length(g)]);
else
    [ar,br,cr,dr]=modred(ab,bb,cb,dd,[sum(order)+1:length(g)]);
end
if isoe
      kr=zeros(sum(order),ny);br
else
      br1=br(:,1:nu);kr=br(:,nu+1:nu+ny);br=br1;dr=dr(:,1:nu);
end
x0=x0(1:sum(order));
if T>0
   cd='d';
else
   cd='c';
end
[dum,dum1,lam]=th2par(th);
thred=ms2th(modstruc(ar,br,cr,dr,kr,x0),cd,[],lam,abs(T));
