function array_new = lin_interp_1d(array, down_column)
% LIN_INTERP_1D interpolates for NaNs in a matrix.
%    function array_new = lin_interp_1d(array, down_column)
% ARRAY is a vector or matrix possibly containing NaNs. ARRAY_NEW is the same
% matrix but with the NaNs replaced by values found from linear
% interolation. If DOWN_COLUMN is true (non- zero) then the linear
% interpolation is done down each column; in this case the first and last
% rows must be completely free of NaNs. If DOWN_COLUMN is false then the
% interpolation is done across rows and the first and last columns must be
% entirely free of NaNs.
  
% $Id: lin_interp_1d.m,v 1.1 2000/05/08 07:12:01 mansbrid Exp $
% Copyright J. V. Mansbridge, CSIRO, Mon May  8 16:49:05 EST 2000
  
if nargin ~= 2
  help lin_interp_1d
  error('wrong number of input arguments')
end

if ndims(array) > 2
  error('code only written to handle matrices and vectors')
end

if ~down_column
  array = array';
end
[m, n] = size(array);

if any(isnan([array(1, :) array(m, :)]))
  error('doesn''t work with NaNs on the edges')
end

array_new = array(:);
ff_nan = find(isnan(array_new));
ff_not_nan = find(~isnan(array_new));
if ~isempty(ff_nan)
  x_full = 1:m*n;
  x = x_full(ff_not_nan );
  y = array_new(ff_not_nan );
  xi = x_full(ff_nan );
  yi = interp1(x, y, xi);
  array_new(ff_nan ) = yi;
end
array_new = reshape(array_new, m, n);

if ~down_column
  array_new = array_new';
end 
