function[ M, LblCounts, SrtLblCounts ] = cComponent(BW, mode ,th)

[m n] = size(BW);

[L,num] = bwlabel(BW,mode);
LblCounts(1:num) = double(1);
display(sprintf(' Number of connected components found: %d', num));

for i= 1:m
    for j = 1:n
        if(L(i,j) > 0 )
            LblCounts(1,L(i,j)) = double(LblCounts(1,L(i,j))+1);
        end

    end
end


% imhist(LblCounts(1,:));


SrtLblCounts = sort(LblCounts , 'descend');

% display(SrtLblCounts(1,:))

counter = 1;


for i = 1:th
    x = SrtLblCounts(i);
    loc = find(LblCounts == x);
    [p q] = size(loc);

    if(p>1)
        for j = 1:p
            locs(counter , 1) = loc(p,1);
            counter = counter + 1;
        end
    else
        locs(counter , 1 ) = loc(p,1);
        counter = counter + 1;
    end

    if(counter > th)
        break;
    end

end

M(m,n) = zeros;

for i = 1:th

    z = locs(i , 1);

    for j = 1:m
        for k =1:n

            if( L(j,k) == z)
                M(j,k) = 1;
           
            end
        end
    end


end

end