function [TH,st]=search(z,th,g,lim)
%SEARCH   Searches for a lower value of the criterion function
%
%	[TH,ST] = search(Z,TH,G,LIM)
%
%	TH : New parameter giving a lower value of the criterion
%	ST=1 : No lower value of the criterion could be found.
%
%	The routine evaluates the prediction error criterion at values
%	along the G-direction, starting at TH. It is primarily intended
%	as a subroutine to MINCRIT. See PEM for an explanation of the
%	arguments.

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

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

th1=th;nu=th(1,3);
Nb=sum(th(1,4:4+nu)); nc=th(1,5+nu); Nd=sum(th(1,4:6+nu));
nf=th(1,7+nu:6+2*nu);
n=sum(th(1,4:6+2*nu));
l=0;,k=1;,V=th(1,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(3,1:n)=th1(3,1:n)+k*g';mc=0;
   if nc>0,c=fstab([1 th(3,Nb+1:Nb+nc)]); th(3,Nb+1:Nb+nc)=c(2:nc+1);
   	else c=1;end
   s=Nd;
   for ku=1:nu, 
      if nf(ku)>0,  f=fstab([1 th(3,s+1:s+nf(ku))]);
      th(3,s+1:s+nf(ku))=f(2:1+nf(ku));end
        s=s+nf(ku);
   end
   
      e=pe(z,th);
      [me,ne]=size(e);
      ll=lim*ones(me,ne);,el=min(e,ll);,el=max(el,-ll);
      V1=e'*el/length(e);
   
   home, disp(int2str(l)) % Give status information to the screen
   k=k/2; if l==8,k=0;end
   l=l+1; if l==10, st=1;end
end

TH=th;,TH(1,1)=V1;if length(e)>1, TH(2,1)=e'*e/length(e);end
