function y = intnan(yn, x)
%
% function y = intnan(yn, x)
%
% Given an array yn of variables with NaNs, and an optional
% array, x, of locations of the values in yn, replace the
% NaNs by linear interpolation.  Leading or trailing NaNs
% are left in place; there is no extrapolation. (changed 97/04, EF)
%
% If there is only one argument, yn, assume it is an array
%  of equally spaced points.
%
% Slightly modified (00/06/20) by EF, to eliminate a warning.
%

[nr, nc] = size(yn);
if nargin == 1,
        if nr == 1,
                nx = nc;
        else
                nx = nr;
        end
        x = 1:nx;
end

if nr == 1 % row vector; turn into column temporarily
        row_vector = 1;
        yn = yn(:);
        nc = 1;
else
        row_vector = 0;
end


x = x(:); % make column vector


y = yn;
for ic = 1:nc,
   goodmask = ~isnan(yn(:,ic));
   ig = find(goodmask);
   if length(ig) > 1
      igr = min(ig):max(ig);   % i-good-range
      badmask = isnan(yn(igr,ic));
      ib = find(~goodmask(igr));
      if ~isempty(ib)
         ig = find(goodmask(igr));  % Not the same as ig above.
         tab = [ x(igr(ig)) yn(igr(ig),ic) ];
         y(igr(ib),ic) = table1(tab, x(igr(ib)) );
      end
   end
end

if row_vector == 1,
        y = y.';
end

