function [R, REGS] = remove_small_regions(R, REGS, ind)
if isempty(R)
    return;
end
if isempty(ind)
    return;
end
wbar_handle = waitbar(0, 'Removing small regions, please wait...');
for i=ind
    r = R(:,:,i);
    rd = imdilate(r, ones(5));
    [x, y] = find(rd == 1);
    rd = rd(min(x):max(x),min(y):max(y));
    area = 0;
    m = 0;
    ind2 = setdiff(2:size(R,3), ind);
    for ii=ind2
        r2 = R(min(x):max(x),min(y):max(y),ii);
        aa = sum(sum(r2&rd));
        if aa>area
            area = aa;
            m = ii;
        end
    end
    R(:,:,m) = R(:,:,m) | r;
    REGS{m} = [REGS{m}, REGS{i}];
    waitbar(i/length(ind), wbar_handle);
end
close(wbar_handle);
R(:,:,ind) = [];
REGS(ind) = [];
return;