def extended_cigar(aligned_template, aligned_query):
    """ Convert mutation annotations to extended cigar format
   
   https://github.com/lh3/minimap2#the-cs-optional-tag
   
   USAGE:
      >>> template = 'CGATCGATAAATAGAGTAG---GAATAGCA'
      >>> query = 'CGATCG---AATAGAGTAGGTCGAATtGCA'
      >>> extended_cigar(template, query) == ':6-ata:10+gtc:4*at:3'
      True
   """
    insertion = []
    deletion = []
    matches = []
    cigar = []
    for r_aa, q_aa in zip(aligned_template.lower(), aligned_query.lower()):
        gap_ref = r_aa == '-'
        gap_que = q_aa == '-'
        match = r_aa == q_aa
        if matches and not match:
            cigar.append(':%s' % len(matches))
            matches = []
        if insertion and not gap_ref:
            cigar.append('+%s' % ''.join(insertion))
            insertion = []
        elif deletion and not gap_que:
            cigar.append('-%s' % ''.join(deletion))
            deletion = []
        if gap_ref:
            if insertion:
                insertion.append(q_aa)
            else:
                insertion = [q_aa]
        elif gap_que:
            if deletion:
                deletion.append(r_aa)
            else:
                deletion = [r_aa]
        elif match:
            if matches:
                matches.append(r_aa)
            else:
                matches = [r_aa]
        else:
            cigar.append('*%s%s' % (r_aa, q_aa))
    if matches:
        cigar.append(':%s' % len(matches))
        del matches
    if insertion:
        cigar.append('+%s' % ''.join(insertion))
        del insertion
    elif deletion:
        cigar.append('-%s' % ''.join(deletion))
        del deletion
    return ''.join(cigar)
