function ibad_amp = flagamp(amp, amp_threshold);

% This function is called by init to check the echo amplitude
% for bottom problems, as signalled by kinks (an increase in
% amplitude with depth) that exceed the AMP_THRESHOLD criterion.

%editglob
global NPRFS NBINS

ibad_amp = [];
da = [-ones(1,NPRFS); diff(amp)];

ipos = find(da > 0);
if isempty(ipos)
  clear da ipos
  return
end

poseq = da >= 0;
dposeq = diff(poseq);
dposeq = [dposeq; -1 * (sum(dposeq) > 0)]; % so each startkink has endkink

startkink = find(dposeq > 0);  % change from decreasing to nondecreasing
endkink = find(dposeq < 0);  % change from nondecreasing to decreasing

ibad = find(abs(amp(startkink) - amp(endkink)) > amp_threshold);
if ~isempty(ibad)
  z = -ones(size(amp));
  z(endkink(ibad)) = amp(endkink(ibad));
  [max_amp ibin] = max(z);
  ibad = find(max_amp > -1);

  ibinprf = [ibin(ibad)' ibad'];
  ibad_amp = (ibinprf(:,2)-1) * NBINS + ibinprf(:,1); % vectorize

end

