import re
import glob


def iter_temporal_find(direct):
    """
    Function to recursively find all log files that are temporally related

    Args:
        direct (str): initial log directory to start off search

    Returns:
        chron (list): sorted list of temporally related log directories
    """
    directLong = "./pickles/" + direct
    dat_type = re.sub(r".*_(.*)$", "\g<1>", direct)
    prefix = re.sub(r"(.*_)(.*)$", "\g<1>", direct)
    # get all files present
    logs = glob.glob("./pickles/*" + dat_type)
    logs.remove(directLong)
    # start recursive process
    chron = [directLong]
    found = True
    while found:
        found = False
        for log in logs:
            if prefix in re.sub(r"(.*R(C)?GAN_).*", "\g<1>", log):
                found = True
                chron.append(log)
                prefix = re.sub(r"(.*_R(C)?GAN_)(.*)(_.*)$", "\g<2>", log)
                logs.remove(log)
                break
    return chron