function [ filtered ] = disk_majority_filter(seg, W)
%DISK_MAJORITY_FILTER Majority filtering with a disk shaped kernel
%   Convolves a disk shaped majority kernel on the binary or 
%   labeled image. Pixels are assigned to the most frequent label 
%   (or 0/1 for binary images) inside the kernel.
%
% citation: S. Arslan, E. Ozyurek, and C. Gunduz-Demir, "A color and shape 
% based algorithm for segmentation of white blood cells in peripheral blood 
% and bone marrow images, Cytometry Part A, vol. 85, no. 6, pp. 480-490, 
% 2014. 
%
% author: Salim Arslan (name.surname@imperial.ac.uk)
% last updated: 22.06.2014
%
% input:
%   seg: Binary image or labeled connected components
%   W: Radius of the disk
%
% output:
%   filtered: Majority filtered output image. Binary or labeled depending 
%             on the input 
%
convert = 0;

if islogical(seg)
    seg = bwlabeln(seg);
    convert = 1;
end

domain = fspecial('disk', W) > 0;
filtered = zeros(size(seg));
cnt = 1;
for i = 1 : max(max(seg))
    A = seg == i;
    B = ordfilt2(A,round(0.5*numel(find(domain))),domain);
    CC = bwconncomp(B == 1);
    if CC.NumObjects > 1
        BW = false(CC.ImageSize);
        numPixels = cellfun(@numel,CC.PixelIdxList);
        [~,idx] = max(numPixels);
        BW(CC.PixelIdxList{idx}) = 1;
    else
        BW = B == 1;
    end

    filled = imfill(BW, 'holes') ;
    filtered(filled == 1) = cnt;
    cnt = cnt + 1; 
end

if convert == 1
    filtered = logical(filtered);
end