import pathlib


def find_timepoint(imagedir: pathlib.Path,
                   tile: str,
                   timepoint: int = 1) -> pathlib.Path:
    """ Find the specified timepoint

    :param Path imagedir:
        Directory containing the image file
    :param str tile:
        Prefix for all images in this directory
    :param int timepoint:
        Time index for which frame to load (1 - first frame, 2 - second, etc)
    :returns:
        The file matching this timestamp
    """
    ct = 0
    for infile in sorted(imagedir.iterdir()):
        if not infile.is_file():
            continue
        if infile.suffix not in ('.png', '.tif', '.jpg'):
            continue
        if not infile.name.startswith(tile):
            continue
        ct += 1
        if ct == timepoint:
            return infile
    raise ValueError(f'No images under {imagedir} match tile {tile} and timepoint {timepoint}')