function [Vn,TH,st,elambda]=sess(V,z,th,sspm,T,modarg,sqrlam,g,lim,M,display)
%SEARCH   Searches for a lower value of the criterion function
%
%        [Vn,TH,ST,ELAMBDA] = sess(V,Z,TH,SSPM,T,MODARG,SQRLAM,..
%	                      G,LIM,M,DISPLAY)
%
%	 Vn: New value of the criterion
%        TH : New parameter giving a lower value of the criterion
%        ST=1 : No lower value of the criterion could be found.
%	 ELAMBA: Estimated value of the covariance matrix
%
%        The routine evaluates the prediction error criterion at values
%        along the G-direction, starting at TH. It is primarily intended
%        as a subroutine to PEMSS. See PEMSS for an explanation of the
%        arguments.

%        L. Ljung 10-1-88,9-25-93
%        Copyright (c) 1986-95 by the MathWorks, Inc.
%        $Revision: 1.5 $  $Date: 1995/05/11 14:07:19 $

% *** Set up the model orders ***

th1=th;
[Ncap,nz]=size(z);
l=0;,k=1;,V1=V+1;st=0;

% *** Looping, attempting to find a lower value of V along
%     the G-direction ***

while [V1 > V l<10],
   th=th1+k*g.';
   [A,B,C,D,K,X0]=feval(sspm,th,T,modarg);[ny,nx]=size(C);
   ei=eig(A-K*C);
     if max(abs(ei))<=1
      for kc=1:M:Ncap-1
          jj=(kc:min(Ncap,kc-1+M));
          if jj(length(jj))<Ncap,jjz=[jj,jj(length(jj))+1];else jjz=jj;end
          xh=ltitr(A-K*C,[K B-K*D],z(jjz,:),X0);
          yh(jj,:)=(C*xh(1:length(jj),:).'+[zeros(ny,ny) D]*z(jj,:).').';
          [nxhr,nxhc]=size(xh);X0=xh(nxhr,:).';
      end
     e=z(:,1:ny)-yh;
     ll=ones(Ncap,1)*lim;
      if lim==0,el=e;else la=abs(e)+eps*ll;el=e.*(min(la,ll)./la);end
     V1=real(det(e'*el/length(e)));
    end
   if display  % Give information to the screen
      %home
      disp(int2str(l))
   end 
   k=k/2; if l==8,k=0;end
   l=l+1; if l==10, st=1;end
end

TH=th;,Vn=V1;
elambda=e'*e/length(e);
