function t = TGflat(f,K)
%
% TGflat: returns a likelihood that a pixel is in a flat area
% Computes root median square average value 
% On input:
%    f:  2D image function
%    K:  window size for median computation
% On output:
%    t:  root median square average value at pixel for KxK window 
% Calling sequence:
%    t = TGflat(f,K)

[m,n] = size(f);
t = zeros(m,n); Karray = ones(K,K);
Wradius = (K-1)/2; Ksquared = K*K;
rmin = (K+1)/2;   cmin = rmin;
rmax = m-rmin+1; cmax = n-cmin+1;

for r = rmin:rmax
  for c = cmin:cmax
    W = f(r-Wradius:r+Wradius,c-Wradius:c+Wradius);
	Wmedian = median(W(1:Ksquared));
	dif = W-Wmedian*Karray; dif2 = dif.*dif;
	Wrms = sqrt(sum(dif2(1:Ksquared)))/Ksquared;
    t(r,c) = Wrms;
    end
  end
end
%t = 1-t/max(max(t));
