Merge multiple BibTeX files into a single homogeneously-formatted output,
    using a LaTeX .aux file to know which records are worth paying attention
    to.

    The file identified by `mainpath` will be overwritten with the new .bib
    contents. This function is intended to be used in a version-control
    context.

    Files matching the glob "*.bib" in `extradir` will be read in to
    supplement the information in `mainpath`. Records already in the file in
    `mainpath` always take precedence.

def merge_bibtex_with_aux(auxpath, mainpath, extradir, parse=get_bibtex_dict, allow_missing=False):
    """Merge multiple BibTeX files into a single homogeneously-formatted output,
    using a LaTeX .aux file to know which records are worth paying attention
    to.

    The file identified by `mainpath` will be overwritten with the new .bib
    contents. This function is intended to be used in a version-control
    context.

    Files matching the glob "*.bib" in `extradir` will be read in to
    supplement the information in `mainpath`. Records already in the file in
    `mainpath` always take precedence.

    """
    auxpath = Path(auxpath)
    mainpath = Path(mainpath)
    extradir = Path(extradir)

    with auxpath.open('rt') as aux:
        citednames = sorted(cited_names_from_aux_file(aux))

    main = mainpath.try_open(mode='rt')
    if main is None:
        maindict = {}
    else:
        maindict = parse(main)
        main.close()

    def gen_extra_dicts():
        # If extradir does not exist, Path.glob() will return an empty list,
        # which seems acceptable to me.
        for item in sorted(extradir.glob('*.bib')):
            with item.open('rt') as extra:
                yield parse(extra)

    merged = merge_bibtex_collections(citednames, maindict, gen_extra_dicts(),
                                      allow_missing=allow_missing)

    with mainpath.make_tempfile(want='handle', resolution='overwrite') as newbib:
        write_bibtex_dict(newbib, six.viewvalues(merged))