def pcrdup_mark(inbam, outbam, fragment=False, countfile=None):
    cur_pos = None
    cur_reads = {}

    total = 0
    unique = 0
    duplicates = 0

    dup_list = set()

    def callback(read):
        return '%s, %s, %s - %s' % (total, unique, duplicates, read.qname)

    for read in bam_iter(bamfile, callback=callback):
        if not read.is_paired or read.is_read1:
            total += 1

        if read.is_unmapped:
            __flush_cur_reads(cur_reads, outbam, inbam, countfile)
            if outbam:
                outbam.write(read)
            continue

        start_pos = (read.tid, read.pos)

        if fragment:
            dup_pos = (read.tid, read.pos, '')
        else:
            # isize is the insert length, which if this is the first read, will
            # be the right most part of the second read. If the ends of the reads
            # are trimmed for QC reasons, only the 5' pos of the first read and the 3'
            # pos of the second read will be accurate.
            
            dup_pos = (read.tid, read.pos, read.isize)

        if not cur_pos or start_pos != cur_pos:
            __flush_cur_reads(cur_reads, outbam, inbam, countfile)

            cur_pos = start_pos
            cur_reads = {}
            idx = 0

        if not fragment and (read.mate_is_unmapped or not read.is_paired or not read.is_proper_pair or read.isize < 0):
            # this is a paired file, but the mate isn't paired or proper or mapped
            # just write it out, no flags to set.

            if dup_list in read.qname:
                read.is_duplicate = True
                dup_list.remove(read.qname)

            if outbam:
                outbam.write(read)
        elif dup_pos in cur_reads:
            duplicates += 1
            if not fragment:
                dup_list.add(read.qname)
            cur_reads[dup_pos].append((read.mapq, -idx, read))
        else:
            unique += 1
            cur_reads[dup_pos] = [(read.mapq, -idx, read), ]

        idx += 1

    __flush_cur_reads(cur_reads, outbam, inbam, countfile)

    sys.stdout.write('Total reads:\t%s\n' % total)
    sys.stdout.write('Unique reads:\t%s\n' % unique)
    sys.stdout.write('PCR duplicates:\t%s\n' % duplicates)
dataset/ETHPy150Open ngsutils/ngsutils/ngsutils/bam/pcrdup.py/pcrdup_mark/swapped operands of `in`