function B = fillNaNs(A,n)

% Returns B where NaNs in A are replaced
% by median of +/- n nearest neighbor values.

B = A;
kk = length(B);

% NaNs in the first n points
ii = find(isnan(B));
ll = ii(ii<n);
if ~isempty(ll)
    for jj=1:length(ll)
        B(ll(jj)) = nanmedian1(B(1:n));
    end;
end;

% NaNs in the last n points
ii = find(isnan(B));
ll = ii(ii>kk-n);
if ~isempty(ll)
    for jj=1:length(ll)
        B(ll(jj)) = nanmedian1(B(ll-n:ll));
    end;
end;

% all the rest
ii = find(isnan(B));
ll = ii(ii>n & ii<kk-n);
if ~isempty(ll)
    for jj=1:length(ll)
        B(ll(jj)) = nanmedian1(B(ll(jj)-n:ll(jj)+n));
    end;
end;
