def alignment_to_MD_string(ref_aligned, read_aligned):
    """ Produce an MD string from an alignment. """
    MD_list = []
    current_match_length = 0
    for ref_char, read_char in zip(ref_aligned, read_aligned):
        if ref_char == read_char:
            current_match_length += 1
        elif ref_char != '-':
            if current_match_length > 0:
                MD_list.append(current_match_length)
                current_match_length = 0
            if read_char == '-':
                MD_list.append(0)
            else:
                MD_list.append(ref_char)
    if current_match_length > 0:
        MD_list.append(current_match_length)
    reduced_MD_list = []
    for i in range(len(MD_list)):
        if isinstance(MD_list[i], int):
            if MD_list[i] > 0:
                reduced_MD_list.append(MD_list[i])
            elif 0 < i < len(MD_list) - 1:
                if isinstance(MD_list[i - 1], str) and isinstance(MD_list[i +
                    1], str) and MD_list[i - 1][0] == '^' and MD_list[i + 1][0
                    ] != '^':
                    reduced_MD_list.append(MD_list[i])
        else:
            reduced_MD_list.append(MD_list[i])
    collapsed_MD_list = [reduced_MD_list[0]]
    for i in range(1, len(reduced_MD_list)):
        if isinstance(collapsed_MD_list[-1], str) and collapsed_MD_list[-1][0
            ] == '^' and isinstance(reduced_MD_list[i], str
            ) and reduced_MD_list[i][0] == '^':
            collapsed_MD_list[-1] += reduced_MD_list[i][1]
        else:
            collapsed_MD_list.append(reduced_MD_list[i])
    if isinstance(collapsed_MD_list[0], str):
        collapsed_MD_list.insert(0, 0)
    if isinstance(collapsed_MD_list[-1], str):
        collapsed_MD_list.append(0)
    MD_string = ''.join(map(str, collapsed_MD_list))
    return MD_string
