import json


def merge_mip_infos(file_list, output_file=None):
    """Merge multiple mip_info files in json format.

    Mip info files are hierarchically organized into
    {gene: "mips": {mip1: ..}} structure.
    If two files have overlapping gene names, preceeding info file's gene
    will be updated with the following file. If mip names are shared within
    genes, the mips from the latter file will replace the preceeding file's
    mip.

    Save the merged mip info file to specified file, if given.
    """
    info = {}
    for f in file_list:
        with open(f) as infile:
            temp_info = json.load(infile)
        for g in temp_info:
            try:
                info[g]["mips"].update(temp_info[g]["mips"])
            except KeyError:
                info[g] = {"mips": temp_info[g]["mips"]}
    if output_file is not None:
        with open(output_file, "w") as outfile:
            json.dump(info, outfile, indent=1)
    return info