import re


def _sort_nd2_files(files):
    """
    The script used on the Nikon scopes is not handling > 100 file names
    correctly and is generating a pattern like:
        ESN_2021_01_08_00_jsp116_00_P_009.nd2
        ESN_2021_01_08_00_jsp116_00_P_010.nd2
        ESN_2021_01_08_00_jsp116_00_P_0100.nd2
        ESN_2021_01_08_00_jsp116_00_P_011.nd2
    So this function parses the last number and treats it as an int for sorting
    """

    pat = re.compile(r"(.*_)(\d+)(\.nd2)$")
    file_splits = []
    did_split = None
    for file in files:
        g = pat.match(file)
        if g is not None:
            file_splits += [(g.group(1), g.group(2), g.group(3))]
            assert did_split is True or did_split is None
            did_split = True
        else:
            assert did_split is False or did_split is None
            did_split = False
    if did_split:
        numerically_sorted = sorted(file_splits, key=lambda x: int(x[1]))
        return ["".join(i) for i in numerically_sorted]
    else:
        return sorted(files)