%_______________________________________________________________________________
%
%   split
%
%   This function implements recursive splitting of image blobs into their
%   disjoint, constiuent parts.  Example: Say two person blobs get
%   connected through artificial means, say shadows. This function will
%   remove the connectivitity of them to each other and make 2 or more 
%   independent image blobs.
%   
%   Input: imageBlob - an imfeatures structure containing Area,
%   BoundingBox, and Image. minArea - the minimum area to define a human.
%   threshold - the minimum height to define a human.
%`  Output: List of imfeature structs meeting requirements of a human.
%
%   Author:         Isaac Gerg
%   Version:        0.02
%   Revision Date:  3.15.2005
%
%   0.02 3.15.2005  idg - Cleaned up code.
%   0.01 3.8.2005   Isaac Gerg(idg) - Initial release.
%_______________________________________________________________________________
function list = split(imageBlob, minArea, threshold)
    % Intialization
    square = strel('square', 2);
    list = [];
    imageBlob.Image = double(imageBlob.Image);
    tmp = sum(imageBlob.Image);
    % Determine columns meeting minimum threshold.
    tmp = tmp > threshold;
    if (tmp == ones(1, size(imageBlob.Image, 2) ))
        list{length(list)+1} = imageBlob;
        return
    end
    % Filter columns less than threshold.
    for y=1:size(imageBlob.Image, 2)
        if (tmp(y) == 0)
            imageBlob.Image(:, y) = zeros(size(imageBlob.Image, 1), 1);
        end
    end
    if (imageBlob.Image == zeros(size(imageBlob.Image, 1), size(imageBlob.Image, 2)))
        return
    end    
    
    % Dilate this 'processed' image now and redo the connected component
    % analysis.  Go and perform split() recursively on any remaining blobs.
    % Store the segmented humans in list{} and return when done.
    tmp = imdilate(imageBlob.Image, square);
    [cc, n] = bwlabel(tmp, 8);
    tmp = imerode(imageBlob.Image, square);
    bb = imfeature(cc, 'Image', 'BoundingBox', 'Area', 8);
    for i=1:length(bb)
        if (bb(i).Area < minArea)
            continue;
        end
        bb(i).BoundingBox(1:2) = bb(i).BoundingBox(1:2) + imageBlob.BoundingBox(1:2);
        tmp = split(bb(i), minArea, threshold);
        if (iscell(tmp) == 1)
            tmp = cell2mat(tmp);
        end
        list{length(list)+1} = tmp;
    end
return