import copy


def sort_shell(shell, use_copy=True):
    """
    Sort a basis set shell into a standard order

    The order within a shell is by decreasing value of the exponent.

    If use_copy is True, the input shells are not modified.
    """

    if use_copy:
        shell = copy.deepcopy(shell)

    # Transpose of coefficients
    tmp_c = list(map(list, zip(*shell['coefficients'])))

    # Zip together exponents and coeffs for sorting
    tmp = zip(shell['exponents'], tmp_c)

    # Sort by decreasing value of exponent
    tmp = sorted(tmp, key=lambda x: -float(x[0]))

    # Unpack, and re-transpose the coefficients
    tmp_c = [x[1] for x in tmp]
    shell['exponents'] = [x[0] for x in tmp]
    shell['coefficients'] = list(map(list, zip(*tmp_c)))

    return shell