def getGenomeSegmentGroups(genomeSegmentIterator, contigsExcludedFromGrouping = None) :
    """
    Iterate segment groups and 'clump' small contigs together

    @param genomeSegmentIterator any object which will iterate through ungrouped genome segments)
    @param contigsExcludedFromGrouping defines a set of contigs which are excluded from grouping
                           (useful when a particular contig, eg. chrM, is called with contig-specific parameters)
    @return yields a series of segment group lists

    Note this function will not reorder segments. This means that grouping will be suboptimal if small segments are
    sparsely distributed among larger ones.
    """

    def isGroupEligible(gseg) :
        if contigsExcludedFromGrouping is None : return True
        return (gseg.chromLabel not in contigsExcludedFromGrouping)

    minSegmentGroupSize=200000
    group = []
    headSize = 0
    isLastSegmentGroupEligible = True
    for gseg in genomeSegmentIterator :
        isSegmentGroupEligible = isGroupEligible(gseg)
        if (isSegmentGroupEligible and isLastSegmentGroupEligible) and (headSize+gseg.size() <= minSegmentGroupSize) :
            group.append(gseg)
            headSize += gseg.size()
        else :
            if len(group) != 0 : yield(group)
            group = [gseg]
            headSize = gseg.size()
        isLastSegmentGroupEligible = isSegmentGroupEligible
    if len(group) != 0 : yield(group)