def select_query(x, read_seq, read_qual):
    """Selects query.

    If multiple matches are found, select the one with the smallest levenshtein
    distance. If multiple matches having the same smallest levenshtein
    distance, select the one with lowest sequencing quality sum at the
    mismatched nucleotides. If there's still a tie, select the first one.

    Parameters
    ----------
    x : dict
        A dictionary of fuzzy searching result. Keys are levenshtein distance.
        Values are list of matched barcodes.
    read_seq : str
        A DNA string (not whole read).
    read_qual : str
        A sequencing quality string (not whole read).

    Returns
    -------
    str
        Matched reference barcode.
    int
        Levenshtein distance.
    """

    # for i in sorted(x.keys()):
    for i in x:
        if x[i]:
            if len(x[i]) == 1:
                return x[i][0], i
            else:
                s = [sum([ord(read_qual[idx]) - 33
                          for idx, val in enumerate(read_seq)
                          if ii[idx] != val]) for ii in x[i]]

                s = [idx for idx, val in enumerate(s) if val == min(s)][0]

                return x[i][s], i