function Af = mf(A,fsize,method);
%% To median filter a 2-D array with options for method.
%%  	Assumes that no data is stored as NaN
%%  USAGE: Af = mf(A,fsize,method);
%%	fsize is filter 2-D window size
%%	if method is 1: NaNs do not enter median calculation; 
%%		NaN edges are not eroded 
%%	if method is 2: NaNs enter median calculation; 
%%		NaN edges are eroded 
%%	if method is 3: The NaNs are filled with surrounding data

Af = A; [R C] = size(A); buffer = floor(fsize/2);

for r = 1+buffer:R-buffer;
 for c = 1+buffer:C-buffer;
  %% Extract data block
  a = A([r-buffer:r+buffer],[c-buffer:c+buffer]); a=a(:); 

  %% Remove NaN if method 1 or method 3
  if method == 1 | method ==3; a(isnan(a))=[]; end

  %% Vectorize
  a=a(:);

  %% Method 1: do not fill where NaN
  if method==1; if ~isnan(A(r,c)) & ~isempty(a); Af(r,c)=median(a(:)); end; end

  %% Method 2: NaNs are retained for erosion
  if method==2; Af(r,c)=median(a(:)); end

  %% Method 3: NaNs are filled where data allows
  if method==3; if ~isempty(a); Af(r,c)=median(a(:)); end; end

 end
end
 
