import glob


def file_dict(filetempl, filetype, mem, stmon):
    """
    Returns a dictionary of filepaths keyed by initialization year,
    for a given experiment, field, ensemble member, and initialization month

    Parameters
    ----------
    filetempl : str
        file template
    filetype : str
        file ending
    mem : int
        ensemble member
    stmon : int
        month

    Returns
    -------
    filepaths : dict
        dictionary containing filepaths keyed by initialization year
    """

    memstr = '{0:03d}'.format(mem)
    monstr = '{0:02d}'.format(stmon)
    filepaths = {}

    filetemp = filetempl.replace('MM', monstr).replace('EEE', memstr)

    # find all the relevant files
    files = sorted(glob.glob(filetemp))

    for file in files:
        # isolate initialization year from the file name
        ystr = file.split(filetype)[0]
        y0 = int(ystr[-11:-7])
        filepaths[y0] = file

    return filepaths