def merge_aux(subperm, perm_list):
    """
    Auxiliary function for merging subpermutations.

    Args:
        subperm (tuple):
        perm_list (list)

    Returns:
        (tuple) list with subpermutation merged (if successful) and a flag
        that is set to True if merge was successful and False otherwise.
    """
    
    # Copy list of subpermutations.
    perm_list_aux = perm_list.copy()

    # Go over subpermutations and try to merge.
    for idx in range(len(perm_list_aux)):

        if subperm[-1] == perm_list_aux[idx][0]:
            # If end of subpermutation matches beginning of next.
            res = subperm + perm_list_aux[idx][1:]
            del(perm_list_aux[idx])
            perm_list_aux.append(res)
            return perm_list_aux, True
        if subperm[0] == perm_list_aux[idx][-1]:
            # If end of the subpermutation matches end of next.
            res = perm_list_aux[idx][:-1] + subperm
            del(perm_list_aux[idx])
            perm_list_aux.append(res)
            return perm_list_aux, True

    # If match unsuccessful, set flag to False.
    return perm_list, False