def cleanup(read,orig,RG):

    if read.is_unmapped and read.is_reverse:
        read.is_reverse = False
        qual = read.qual
        read.seq  = rc(read.seq)
        read.qual = qual[::-1]
    if read.mate_is_unmapped and read.mate_is_reverse:
        read.mate_is_reverse = False
        # mate seq/qual should be caught by the above logic

    if RG:
        hasRG = False
        if read.tags is not None:
            for tag in read.tags:
                if tag[0] == 'RG':
                    hasRG = True

        # use RG from original read if it exists
        if orig is not None:
            if not hasRG and orig.tags is not None:
                for tag in orig.tags:
                    if tag[0] == 'RG':
                        read.tags = read.tags + [tag] 
                        hasRG = True

        if not hasRG:
            # give up and add random read group from list in header (e.g. for simulated reads)
            newRG = RG[random.randint(0,len(RG)-1)]
            read.tags = read.tags + [("RG",newRG)]
    return read
fixes unmapped reads that are marked as 'reverse'
dataset/ETHPy150Open adamewing/bamsurgeon/bamsurgeon/replacereads.py/cleanup