function I = rankfilter_arbitrarySupport(I,Msupport);
%function I = rankfilter_arbitrarySupport(I,Msupport);
%
%support must be a binary matrix.  The centroid of the support will be at
%[floor(size(support,1)/2), floor(size(support,2)/2)]
%The returned value will be the rank of the centroid pixel relative to the support, where rank
%refers to the position within a sorted vector.

sz = size(Msupport);
c = [floor((size(Msupport,1)+1)/2), floor((size(Msupport,2)+1)/2)];
Msupport(c(1),c(2)) = 0;
Msupport = Msupport / sum(Msupport(:));
centroid = floor(sz);
fsupport = find(Msupport);
vsupport = Msupport(fsupport);
Msupport = 0 * Msupport;
Msupport(c(1),c(2)) = 1;
fcenter = find(Msupport);

ndxsupport = NDind2sub(sz,fsupport);
ndxcenter = NDind2sub(sz,fcenter);
nPoints = size(fsupport,1);
ndxsupport = ndxsupport - repmat(centroid, [nPoints,1]);
ndxcenter = ndxcenter - centroid;
padamnt = max(ceil(sz/2));
ndxsupport = ndxsupport + padamnt;
ndxsupport = ndxsupport + padamnt;
ndxcenter = ndxcenter + padamnt;
ndxcenter = ndxcenter + padamnt;
padI = padimage(I,padamnt,'symmetric');
BigMat = zeros(nPoints, prod(size(I)));
sI = size(I);
for i = 1:nPoints
  crop = padI( ndxsupport(i,1) +  (1:sI(1))-1,ndxsupport(i,2) + (1:sI(2)) - 1 );
  BigMat(i,:) = crop(:);
end
crop = padI( ndxcenter(1,1) +  (1:sI(1))-1,ndxcenter(1,2) + (1:sI(2)) - 1 );
MyVal(1,:) = crop(:);
% keyboard;
BigMat = (BigMat - repmat(MyVal,[nPoints,1])) <= 0;
% keyboard;
BigMat = vsupport' * BigMat ; 
% keyboard;

I = reshape(BigMat,sI);
