def bam_best(infile, outfile, failfile=None, tags=['AS+', 'NM-'], quiet=False):
    inbam = pysam.Samfile(infile, "rb")
    outbam = pysam.Samfile('%s.tmp' % outfile, "wb", template=inbam)

    if failfile:
        failbam = pysam.Samfile('%s.tmp' % failfile, "wb", template=inbam)

    for reads in ngsutils.bam.bam_batch_reads(inbam, quiet=quiet):
        best_val = None
        best_reads = []
        failed = []

        for read in reads:
            if not read.is_unmapped:
                tag_val = []
                for tag in tags:
                    val = float(read.opt(tag[:2]))
                    if tag[-1] == '-':
                        val = -val
                    tag_val.append(val)

                if not best_val or tag_val > best_val:
                    if best_reads and failfile:
                        failed.extend(best_reads)

                    best_val = tag_val
                    best_reads = [read]

                elif tag_val == best_val:
                    best_reads.append(read)

                elif failfile:
                    failed.append(read)

        for read in best_reads:
            outbam.write(read)

        if failfile:
            for read in failed:
                failbam.write(read)

    outbam.close()
    os.rename('%s.tmp' % outfile, outfile)

    if failfile:
        failbam.close()
        os.rename('%s.tmp' % failfile, failfile)
dataset/ETHPy150Open ngsutils/ngsutils/ngsutils/bam/best.py/bam_best/original