function optcert = findbest(d, e, dtol, prtlevel);  
%
%  Consider the values in d from right to left, and return 
%  the first one (furthest to the right) that is less than corresponding
%  entry in dtol, along with the corresponding entries in d and e.  
%  Since the values of e are strictly increasing from right to left, 
%  this is the same as finding the smallest entry in e subject to the 
%  constraint that the corresponding entry in d is < corresponding dtol.  
%  Combine the two into a struct called optcert with fields dnorm and samprad.  
%  If none of the entries in d are less than corresponding entry in dtol, 
%  return the rightmost values of d, e.
%  Written by M. Overton (overton@cs.nyu.edu), last revised November 2003

[val,ind] = sort(-e);
val = -val;
if val ~= e    % shouldn't be needed (but might be in other contexts)
   if prtlevel > 1
      disp('sorting e, since values in e must be in descending order')
   end
   e = e(ind);
   d = d(ind);
end

if min(d - dtol ) > 0
   if prtlevel > 1
      disp('all d values are > dtol')
   end
   optcert.dnorm = d(length(d));
   optcert.samprad = e(length(d));
   return
end

j = length(d);
dbest = d(j);
ebest = e(j);
while dbest > dtol(j)
   j = j - 1;
   dbest = d(j);
   ebest = e(j);
end
optcert.dnorm = dbest;
optcert.samprad = ebest;
