import warnings


def reorder(names, faname):
    """Format the string of author names and return a string.

    Adapated from one of the `customization` functions in
    `bibtexparser`.
    INPUT:
    names -- string of names to be formatted. The names from BibTeX are
             formatted in the style "Last, First Middle and Last, First
             Middle and Last, First Middle" and this is the expected
             style here.
    faname -- string of the initialized name of the author to whom
              formatting will be applied
    OUTPUT:
    nameout -- string of formatted names. The current format is
               "F.M. Last, F.M. Last, and F.M. Last".

    """
    # Set the format tag for the website's owner, to highlight where on
    # the author list the website owner is. Default is **
    my_name_format_tag = '**'

    # Convert the input string to a list by splitting the string at the
    # "and " and strip out any remaining whitespace.
    nameslist = [i.strip() for i in names.replace('\n', ' ').split("and ")]

    # Initialize a list to store the names after they've been tidied
    # up.
    tidynames = []

    # Loop through each name in the list.
    for namestring in nameslist:
        # Strip whitespace from the string
        namestring = namestring.strip()

        # If, for some reason, we've gotten a blank name, skip it
        if len(namestring) < 1:
            continue

        # Split the `namestring` at the comma, but only perform the
        # split once.
        namesplit = namestring.rsplit(',', 1)

        if (len(namesplit) == 1):
            namesplit = namestring.rsplit(' ', 1)
            last = namesplit[-1].strip().strip('{}')
            firsts = namesplit[:-1]
        else:
            last = namesplit[0].strip().strip('{}')
            firsts = [i.strip().strip('.') for i in namesplit[1].split()]

        # Now that all the first name edge cases are sorted out, we
        # want to initialize all the first names. Set the variable
        # initials to an empty string to we can add to it. Then loop
        # through each of the items in the list of first names. Take
        # the first element of each item and append a period, but no
        # space.
        initials = ''
        for item in firsts:
            initials += item[0] + '.'

        # Stick all of the parts of the name together in `tidynames`
        tidynames.append(initials + ' ' + last)

    # Find the case of the website author and set the format for that
    # name
    if faname is not None:
        try:
            i = tidynames.index(faname)
            tidynames[i] = my_name_format_tag + tidynames[i] + my_name_format_tag
        except ValueError:
            warnings.warn("Couldn't find {} in the names list. Sorry!".format(faname))

    # Handle the various cases of number of authors and how they should
    # be joined. Convert the elements of `tidynames` to a string.
    if len(tidynames) > 2:
        tidynames[-1] = 'and ' + tidynames[-1]
        nameout = ', '.join(tidynames)
    elif len(tidynames) == 2:
        tidynames[-1] = 'and ' + tidynames[-1]
        nameout = ' '.join(tidynames)
    else:
        # If `tidynames` only has one name, we only need to convert it
        # to a string. The first way that came to mind was to join the
        # list to an empty string.
        nameout = ''.join(tidynames)

    # Return `nameout`, the string of formatted authors
    return nameout