function THcap=mincrit(z,th,index,maxiter,tol,lim,maxsize,T)
%MINCRIT   Minimizes prediction error criteria
%
%	TH = mincrit(Z,TH,MAXITER,TOL,LIM,MAXSIZE,T)
%
%	This routine minimized robustified quadratic prediction error
%	criteria. It is intended primarily as a subroutine to PEM.
%	See PEM for an explanation of arguments.

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

nu=th(1,3);
NN=th(1,4:6+2*nu);n=sum(NN); [Ncap,nz]=size(z);
if isempty(index),index=1:n;end
g=ones(n,1);, l=0;
e=pe(z,th);


%** Determine limit for robustification of criterion ***

if lim~=0, lim=median(abs(e-median(e)))*lim/0.7;end
if lim==0, lim=1000*th(1,1);end

[me,ne]=size(e);
el=min(e,lim*ones(me,ne)); el=max(el,-lim*ones(me,ne)); th(1,1)=el'*e/length(e);
clear e, l=0; st=0;

%  ** The minimization loop **

while [norm(g)>tol l<maxiter st~=1]
   l=l+1;

%   * Compute the Gauss-Newton direction *

   [g,R,grad]=gn(z,th,lim,maxsize,index);

%    * Search along the g-direction for a lower value of V *

    [th1,st]=search(z,th,g,lim);
    if st==1,
    [th1,st]=search(z,th,grad/trace(R)*length(R),lim);end
%  * Display the current values along with the previous ones *

     t=zeros(n,3); t(:,1)=th1(3,1:n)';t(:,2)=th(3,1:n)';t(:,3)=g;
     home
     disp(['    ITERATION # ' int2str(l)])
     disp(['Current loss: ' num2str(th1(1,1)) '   Previous loss: ' num2str(th(1,1))])
      disp(['Current th  prev. th   gn-dir. '])
      disp(t)
      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
      th=th1;
end

% *** Build up the TH-matrix ***

THcap=th;THcap(1,1)=th(2,1);THcap(1,2)=T;
THcap(2,1)=(1+n/Ncap)/(1-n/Ncap)*THcap(1,1);
THcap(4:n+3,1:n)=zeros(n);
THcap(index+3,index)=THcap(1,1)*inv(R);
ti=fix(clock); ti(1)=ti(1)/100;
THcap(2,2:6)=ti(1:5); THcap(2,7)=5;

