function ed_bt = intrpbt_new(bt_depth, time)
%
% interpolates missing bottom depths for those regions where the bottom
% track was enabled.  bt_depth is set to NAN where bottom tracking was
% not enabled.

% CNF 1/7/99
% Fixed a bug in determining if bt_ng ~= 0, CNF 4/19/99

%save intrpbt
nprfs = length(time);

bt_on = find(bt_depth < 1000);	% when bottom tracking is off, bt_depth ~ 1.0e38
bt_off = find(bt_depth > 1000);
bt_ng = find(bt_depth < 0);	% bad bottom tracks result in bt_depth = -1

if (length(bt_on) == nprfs & length(bt_ng) == 0)
  ed_bt = bt_depth;
  return
end

% set bottom depths to NANs when bottom tracking is off
bt_depth(bt_off) = nan*ones(size(bt_depth(bt_off)));

% Check for periods when bottom tracking was on
length(bt_on) == 0
if (length(bt_on) == 0), return, end

% and check for gaps in the data
df_on = diff(bt_on);
df_on_1 = find(df_on ~= 1);
npiece = length(df_on_1)+1;	% number of intervals when bottom tracking was on
%fprintf('INTRPBT: %d pieces when bottom track was on\n', npiece);
p_start = [bt_on(1) bt_on(df_on_1+1)];
p_end = [bt_on(df_on_1) max(bt_on)];

ed_bt = nan*ones(size(bt_depth));

for i = 1:npiece
  bt = bt_depth(p_start(i):p_end(i));
  igood = find(bt > 0 );
  ngood = length(igood);

  if ngood ~= length(bt)

% Extrapolate the good depths at either end if necessary
    bt(1:igood(1)) = bt(igood(1))*ones(size(bt(1:igood(1))));
    bt(max(igood):length(bt)) = bt(max(igood))*ones(size(bt(max(igood):length(bt))));

% Interpolate across the internal gaps within the pieces if there are any
    if (length(find(diff(igood) ~= 1)) ~= 0)
      df = diff(igood);
      df_1 = find(df ~= 1);
      gap = df(df_1)-1;		% the number of missing data points in each gap
      ngap = length(gap);	% number of gaps in the current piece
%      fprintf('%d bottom depth gaps to be filled by INTRPBT\n', ngap);
      cumgap = cumsum(gap);
      ind0 = igood(1) - 1 + [df_1(1)  [(df_1(2:ngap) + cumgap(1:(ngap-1)))]];
      indn = ind0 + gap + 1;
      bt0 = [];
      i0 = 1;
      for ii = 1:length(gap)
        bt0 = [bt0 bt(i0:ind0(ii))];
        del_bt = (bt(1,indn(ii)) - bt(1,ind0(ii)))/(gap(ii)+1);
        bt0 = [bt0 bt(ind0(ii))+del_bt*[1:gap(ii)]];
        i0 = indn(ii);
      end
      bt = [bt0 bt(i0:length(bt))];
    end

end

    ed_bt(p_start(i):p_end(i)) = bt;
end
