function [array_2d_new, num_iterations] = fill_gaps_2d(array_2d, lim_iter)
% FILL_GAPS_2D: Replaces NaNs in ARRAY_2D with means of near neighbours
%   [array_2d_new, num_iterations] = fill_gaps_2d(array_2d, lim_iter)
% For a 2-d array (ARRAY_2D) a new version (ARRAY_2D_NEW) is found with NaNs
% replaced by the means of near neighbours. An iterative technique is applied
% that will converge provided that there is at least one non NaN in the
% array. LIM_ITER is the maximum number of iterations to be tried - its
% default value is 50.
  
% $Id: template $
% Copyright J. V. Mansbridge, CSIRO, Wed Apr 26 13:17:37 EST 2000

if nargin == 1
  lim_iter = 50;
elseif nargin ~= 2
  error('fill_gaps_2d should have either 1 or 2 input arguments')
end

% Check that there are some non NaNs in the array

index_pts = find(isnan(array_2d));
[m, n] = size(array_2d);
if length(index_pts) == m*n
  error('the array is entirely composed of NaNs')
end

% Loop through calls to find_mean_neighbours.

num_it = 0;
while (~isempty(index_pts)) & (num_it < lim_iter)
  new_vals = find_mean_neighbours(index_pts, array_2d);
  array_2d(index_pts) = new_vals;
  index_pts = find(isnan(array_2d));
  num_it = num_it + 1;
end
array_2d_new = array_2d;
if nargout >= 2
  num_iterations = num_it;
end
