def sanitizeGenome(infile, outfile, contigs):

    ninput, noutput = 0, 0
    ntruncated_contig, nskipped_contig, nskipped_empty = 0, 0, 0

    for line in infile:
        if line.startswith("track"):
            outfile.write(line)
            continue
        elif line.startswith("variableStep"):
            contig = re.search("chrom=(\S+)", line).groups()[0]
            span = int(re.search("span=(\d+)", line).groups()[0])

            if contig not in contigs:
                nskipped_contig += 1
                skip_contig = True
            else:
                skip_contig = False
                outfile.write(line)
                contig_size = contigs[contig]

            continue

        if skip_contig:
            continue

        start, val = map(int, line[:-1].split("\t"))

        if start + span > contig_size:
            ntruncated_contig += 1
            continue

        outfile.write(line)

    E.info("ninput=%i, noutput=%i, nskipped_contig=%i, ntruncated=%i, nskipped_empty=%i" %
           (ninput, noutput, nskipped_contig, ntruncated_contig, nskipped_empty))
truncate bed intervals that extend beyond contigs.
dataset/ETHPy150Open CGATOxford/cgat/scripts/wig2wig.py/sanitizeGenome