%%
%
% Predict the foreground map...
%
% Mode: 
%     1: prediction
%     2: only morphological clean-up

function fgMap = predFgMap(npx, npy, segMap, blkSiz, PO2, mode)

[m, n] = size(npx);
NUMTH = PO2*m*n;
% we run through morphological operation to get rid of isolated MVs, since
% those MVs will be taken care of by Type-1 outlier removal

% symmetric extension
padMap = wextend('2D','sym',segMap,1);

% morphological closing
diff = zeros(size(segMap));
diff(segMap==1) = 1;
for ii = 1:3
    for jj = 1:3
        diff = diff + abs(segMap-padMap(ii:end-(3-ii),jj:end-(3-jj)));
    end
end

[row, col] = find(diff==0);

fgMap = zeros(size(segMap));

% morphological opening
for jj=-1:1:1
    for ii=-1:1:1

        % find the coordinate
        pR = row+jj;
        pR(pR<1) = 1;
        pR(pR>m) = m;

        pC = col+ii;
        pC(pC<1) = 1;
        pC(pC>n) = n;

        rM = (pC-1).*m+pR;
        fgMap(rM) = 1;
    end
end

% if sum(fgMap(:)) > NUMTH
%     rM = find(fgMap(:)==1);
%     magMV = npx(rM).^2+npy(rM).^2;
%     [B,IX] = sort(magMV, 'descend');
%     IXIN = IX(1:round(NUMTH));
%     fgMap(:) = 0;
%     fgMap(rM(IXIN)) = 1;
% end
% projection for a 3x3 MV matrix

if mode == 1
    [pR, pC] = find(fgMap==1);
    rM = (pC-1).*m+pR;
    fgMap(:) = 0;
    % add MV on it.
    pC = pC - round(npx(rM)./blkSiz);
    pC(pC<1) = 1;
    pC(pC>n) = n;
    pR = pR - round(npy(rM)./blkSiz);
    pR(pR<1) = 1;
    pR(pR>m) = m;

    % get the 
    rM = (pC-1).*m+pR;
    fgMap(rM) = 1;
end

return;

if mode == 1
    for jj=-1:1:1
        for ii=-1:1:1

    %         if sum(fgMap(:)) < NUMTH

                % find the coordinate
                pR = row+jj;
                pR(pR<1) = 1;
                pR(pR>m) = m;

                pC = col+ii;
                pC(pC<1) = 1;
                pC(pC>n) = n;

                rM = (pC-1).*m+pR;

                % add MV on it.
                pC = pC - round(npx(rM)./blkSiz);
                pC(pC<1) = 1;
                pC(pC>n) = n;
                pR = pR - round(npy(rM)./blkSiz);
                pR(pR<1) = 1;
                pR(pR>m) = m;

                % get the 
                rM = (pC-1).*m+pR;
                fgMap(rM) = 1;
    %         end
        end
    end
else
    % no operations
%     for jj=-1:1:1
%         for ii=-1:1:1
% 
%             % find the coordinate
%             pR = row+jj;
%             pR(pR<1) = 1;
%             pR(pR>m) = m;
% 
%             pC = col+ii;
%             pC(pC<1) = 1;
%             pC(pC>n) = n;
% 
%             rM = (pC-1).*m+pR;
%             fgMap(rM) = 1;
%         end
%     end
end
