def merged_filter_region_generator(filter_region_generator, filter_file,
    filter_function):
    """ Generates merged regions from a given generator that produces
    chromosome regions """
    current_chromosome = None
    current_start = None
    current_end = None
    for chromosome_name, filter_start, filter_end in filter_region_generator(
        filter_file, filter_function):
        if current_chromosome:
            if (chromosome_name == current_chromosome and current_end >=
                filter_start):
                current_end = filter_end
            else:
                yield current_chromosome, current_start, current_end
                current_chromosome = chromosome_name
                current_start = filter_start
                current_end = filter_end
        else:
            current_chromosome = chromosome_name
            current_start = filter_start
            current_end = filter_end
    if current_chromosome:
        yield current_chromosome, current_start, current_end
