function th=bj(z,nn,maxiter,tol,lim,maxsize,Tsamp)
%BJ	Computes the prediction error estimate of a Box-Jenkins model.
%
%	TH=bj(Z,NN)
%
%	TH: Returned as the estimated parameters of the Box-Jenkins model
%	y(t) = [B(q)/F(q)] u(t-nk) + [C(q)/D(q)] e(t)
%	along with estimated covariances and structure information. For
%	the exact format of TH, see HELP THETA.
%
%	Z : The output-input data Z=[y u], with y and u being column vectors.
%	This routine only works for single-input systems. Use PEM otherwise.
%
%	NN: Initial value and structure information, given either as 
%	NN=[nb nc nd nf nk], the orders and delay of the above model,
%	or as NN=THI, with THI being a theta matrix of standard format.
%	In the latter case the criterion minimization is initialized at THI.
%
%	Some parameters associated with the algorithm are accessed by
%	TH = bj(Z,NN,maxiter,tol,lim,maxsize,T)
%	See HELP AUXVAR for an explanation of these and their default values.

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

% *** Set up default values ***
[Ncap,nz]=size(z);
maxsdef=idmsize(Ncap);

if nargin<7, Tsamp=[];end
if nargin<6, maxsize=[];end
if nargin<5, lim=[];end
if nargin<4, tol=[];, end
if nargin<3, maxiter=[]; end
Tdef=0;if isempty(Tsamp),Tsamp=1;Tdef=1;end
if isempty(maxsize),maxsize=maxsdef;end
if isempty(lim),lim=1.6;end,if isempty(tol),tol=0.01;end
if isempty(maxiter),maxiter=10;end
if Tsamp<0,Tsamp=1;end, if maxsize<0,maxsize=maxsdef;end, if lim<0,lim=1.6;end
if tol<0,tol=0.01;end,if maxiter<0, maxiter=10;end

% *** Do some consistency tests ***

[nr,cc]=size(nn);  nu=nz-1;
if nz>Ncap, error('The data should be organized in column vectors')
return,end
if nu>1, error('This routine only works for single-input systems. Use PEM instead!')
return,end
if nu==0, error('For time series, use ARMAX instead!'),
return,end

if nr==1 & cc~=5,
       error('Incorrect number of orders specified: nn should be  nn=[nb nc nd nf nk]')
return,end

% *** if nn has more than 1 row, it is a theta matrix
%      and we jump directly to the minimization ***
%
if nr>1, nu=nn(1,3);
   if nu>1, error('This routine only works for single input systems. Use PEM instead')
   return,end
   if nu==0, error('This routine is only meaningful for a SISO system. Use ARMAX instead!'),end
     na=nn(1,4);nb=nn(1,5);nc=nn(1,6);nd=nn(1,7);
   nf=nn(1,8);nk=nn(1,9);
 if na>0,error('na should be zero for this routine!'),
return,end
         n=nf+nb+nc+nd; t=nn(3,1:n)';ni=max([na+nd nd+nb+nk-1 nc+nf]);
         if nc>0, c=[1 t(nb+1:nb+nc)'];else c=1;,end
         if nf>0,f=[1 t(nb+nc+nd+1:n)'];else f=1;,end
         if nb>0,b=[zeros(1,nk) t(na+1:na+nb)'];,else b=0;,end
         if nd>0,d=[1 t(nb+nc+1:nb+nc+nd)'];else d=1;end
         w=filter(b,f,z(:,2));v=z(:,1)-w;e=pefilt(d,c,v,zeros(1,ni));
	 if Tdef,Tsamp=gett(nn);end
end
if nr==1,
%
    nb=nn(1); nc=nn(2); nd=nn(3); nf=nn(4);
    nk=nn(5); n=sum(nn(1:4));ni=max([na+nd nd+nb+nk-1 nc+nf]);
%
%     *** compute initial estimate via LS and IV ***
%
    t=arx(z,[nf nb nk],maxsize,Tsamp,0);
    f=fstab([1 t(1:nf)']);
    t=iv(z,[nf nb nk],f,[zeros(1,nk) t(nf+1:nf+nb)'],maxsize,Tsamp,0);
    f=fstab([1 t(1:nf)']);t(1:nf)=f(2:nf+1)';
%
%  *** Determine the initial C- and D-estimates by first building a
%      high order AR model of the residuals, and then
%      using the LS-method ***
%
     w=pefilt([zeros(1,nk) t(nf+1:nf+nb)'],f,z(:,2),z(1:ni,1));
     v=z(:,1)-w;
     c=1; t2=[];
    if nc>0
        t1=arx(v,n,maxsize,Tsamp,0);
        e=pefilt([1 t1'],1,v);
        t2=arx([v e],[nd nc 1],maxsize,Tsamp,0);
%
%         ** test the stability of the C-estimate **
%
        c=fstab([1 t2(nd+1:nd+nc)']); t2(nd+1:nd+nc)=c(2:nc+1)';
    end
%
    if nc==0
       t2=arx(v,nd,maxsize,Tsamp,0);
    end

if nf>0, tf=t(1:nf);else tf=[];end
if nc>0, tc=t2(nd+1:nd+nc);else tc=[];end
if nd>0, td=t2(1:nd);else td=[];end
t=[t(nf+1:nf+nb);tc;td;tf];

%
if nd==0, d=1; else d=[1 t2(1:nd)'];end
e=pefilt(d,c,v,zeros(1,ni));
end
% *** Display initial estimate ***
%
Vcap=e'*e/(Ncap-ni);
clc, disp(['  INITIAL ESTIMATE'])
disp(['Current loss:' num2str(Vcap)])
disp(['th-vector'])
disp(t)
%
% *** start minimizing ***
%
% ** determine limit for robustification **
 if lim~=0, lim=median(abs(e-median(e)))*lim/0.7;end
 if lim==0, lim=1000*Vcap;end
 [me,ne]=size(e);
 ll=ones(me,ne)*lim;el=max(min(e,ll),-ll); clear ll
 g=ones(n,1); l=0; st=0; nmax=max([nf nb+nk-1 nc nd]);
  h=conv(f,c);
%
% ** the minimization loop **
%
while [norm(g)>tol l<maxiter st~=1]
      l=l+1;
%     * compute gradient *
      wf=filter(-d,h,w); ef=filter(1,c,e);
      vf=filter(-1,c,v); uf=filter(d,h,z(:,2));
  M=floor(maxsize/n);
  R=zeros(n);Fcap=zeros(n,1);
  for k1=nmax:M:Ncap-1
      jj=(k1+1:min(Ncap,k1+M));
      psi=zeros(length(jj),n);
      for k=1:nb, psi(:,k)=uf(jj-k-nk+1);end
      for k=1:nc, psi(:,nb+k)=ef(jj-k);end
      for k=1:nd, psi(:,k+nb+nc)=vf(jj-k);end
      for k=1:nf, psi(:,k+nb+nc+nd)=wf(jj-k);end
      if Ncap>M, R=R+psi'*psi; Fcap=Fcap+psi'*el(jj);end
  end
   if Ncap>M, g=R\Fcap; else g=psi\el(jj);end
%
%     * search along the g-direction *
%

      [t1,e,el,v,w,V1,c,d,h,st]=searchbj(z,t,g,lim,Vcap,nb,nc,nd,nf,nk,ni);
      home
      disp(['      ITERATION # ' int2str(l)])
      disp(['Current loss: ' num2str(V1) '  Previous loss: ' num2str(Vcap)])
      disp(['Current th  prev. th   gn-dir'])
      disp([t1 t g])
      disp(['Norm of gn-vector: '  num2str(norm(g))])
      if st==1
	 disp(['No improvement of the criterion possible along the search direction'])
	 disp(['Iterations therefore terminated']),end
      t=t1; Vcap=V1;
end
th=zeros(3+n,max([9 n]));
Vcap=e'*e/(length(e)-ni);
   th(1,1:9)=[Vcap Tsamp 1 0 nb nc nd nf nk];
th(2,1)=Vcap*(1+n/Ncap)/(1-n/Ncap);
ti=fix(clock); ti(1)=ti(1)/100;
th(2,2:6)=ti(1:5);
th(2,7)=2;
th(3,1:n)=t';
if maxiter==0,th(2,7)=2;return,end
if Ncap>M, PP=inv(R); else PP=inv(psi'*psi);end
th(4:3+n,1:n)=Vcap*PP;

