function base = monotoneMinimim(slider, saturate)
% baseline = monotoneMinimum(smoothSpectrum, saturationEnd)
%
% This function estimates the baseline of a smooth spectrum as a monotone
% minimum. It starts at the maximum level reached during the saturation
% period. Everything before this maximum is reached is removed from the
% spectrum. Everything after this is computed as a decreasing function
% that always takes on the minimum value seen so far. The baseline curve
% is returned.

% Copyright (c) 2003, 2004 UT M.D. Anderson Cancer Center. All rights reserved.
% See the accompanying file "license.txt" for details.

if nargin < 2,
   saturate = length(slider);
end
if saturate < 1,
   saturate = 1;
end
if saturate > length(slider),
   saturate =length(slider);
end


m = max(slider(1:saturate));
d = [diff(slider) 0];
base = repmat(m, size(slider));
%pointer = min(saturate, max(find(slider==m)));
pointer = saturate;
base(1:pointer) = slider(1:pointer);
while pointer < length(slider),
   if d(pointer) <= 0,
%      'dn'
      click = min(find(d(pointer:end) >= 0))- 1;
      base(pointer:pointer+click) = slider(pointer:pointer+click);
   else
%      'up'
      click = min(find(slider(pointer:end) < base(pointer))) - 1;
      base(pointer:end) = slider(pointer);
   end
   pointer = pointer+click;
end
