function ind = adp_frac(filename, minmaxp, nparts)
%  function ind = adp_frac(filename, minmaxp, nparts)
%
%    Given an adp file, find the index ranges that split
%    its time series into downcast and upcast, and each of
%    those into nparts sections.  The cast is delimited by
%    pressures minmaxp = [minp maxp], or by the maximum
%    pressure in the cast if maxp is omitted.
%    ind has nparts rows of 4 columns, which are the
%    start and end indices of the downcast and upcast
%    for each part.
%    Index ranges are approximate, and may overlap slightly,
%    or have slight gaps.
%
%    EF 2000/03/17
%

ind = zeros(nparts, 4);
[ts, dd] = adp(filename, 'ts');
p = ts(:, 5);
np = length(p);
clear ts
minp = minmaxp(1);
if length(minmaxp) == 2,
   maxp = min([minmaxp(2), max(p)]);
else
   maxp = max(p);
end
pp = minp + (0:nparts) * (maxp - minp) / nparts;

imax = find(p >= maxp);
idn = 1:imax(1);
iup = imax(end):np;


id = zeros(nparts + 1, 1);
iu = id;
for irow = 1:(nparts + 1)
   id(irow) = max(find(p(idn) < pp(irow)));
   iu(irow) = iup(min(find(p(iup) < pp(irow))));
end
ind(:, 1) = id(1:(end-1));
ind(:, 2) = id(2:end);
ind(:, 3) = iu(2:end);
ind(:, 4) = iu(1:(end-1));

