from re import compile, findall


def filterSpilloverFilename(filename):
    """ Remove any unwanted spill-over filename endings (i.e. _NNN or ._NNN) """

    # Create the search pattern
    pattern = compile(r'(\.?\_\d+)')
    found = findall(pattern, filename)
    if found:
        # Make sure that the _NNN substring is at the end of the string
        for f in found:
            if filename.endswith(f):
                # Do not use replace here since it might cut away something from inside the filename and not only at the end
                filename = filename[:-len(f)]

    return filename