import glob
import re


def get_file_list(prefix, run_type):
    """get file lists of log files belonging to each executables

    Assume log files have this pattern:
        <prefix>/<run_type>/<run_type>-<executable name>-XXXXXXXXXXX.log

    Args:
        prefix [in]: prefix of the folder holding log files
        run_type [in]: the type of run, i.e., the PBS scipt used

    Return:
        If log files exist, a dictionary. The key in the dictionary is names of
        executable, while the values are lists of log files belonging to each
        executable.

        If log files don't exist or the path is wrong, return None.
    """

    tmpFileList = glob.glob("{0}/{1}/*.log".format(prefix, run_type))

    if len(tmpFileList) == 0:
        return None

    file_list = {}

    for file in tmpFileList:
        match = re.match(
            r"{0}/{1}/{1}-(?P<exe>\S*?)-[0-9-:]*?.log".format(prefix, run_type),
            file)

        if match is None:
            raise IOError("The log file {0} ".format(tmpFileList[0]) +
                          "does not fit filename pattern.")

        exe = match.groupdict()['exe']

        if exe not in file_list:
            file_list[exe] = []

        file_list[exe].append(file)

    return file_list