from pathlib import Path


def path_to_datafile(filename):
    """
    Get absolute path to datafile

    :param filename: pathname of datafile
    :type filename: str
    :raises FileNotFoundError: File does not exist
    :return: Absolute path
    :rtype: str

    If ``filename`` contains no path specification eg. ``map1.mat`` it will
    first attempt to locate the file within the ``roboticstoolbox/data``
    folder and if found, return that absolute path.

    Otherwise, ``~`` is expanded, the path made absolute, resolving symlinks
    and the file's existence is tested.

    Example::

        loadmat('map1.mat')        # read ...roboticstoolbox/data/map1.mat
        loadmat('foo.dat')         # read ./foo.dat
        loadmat('~/data/foo.dat')  # read ~/data/foo.dat
    """

    filename = Path(filename)

    if filename.parent == Path():
        # just a filename, no path, assume it is in roboticstoolbox/data

        p = Path(__file__).resolve().parent.parent / 'data' / filename
        if p.exists():
            return str(p.resolve())

    p = filename.expanduser()
    p = p.resolve()
    if not p.exists():
        raise FileNotFoundError(f"File '{p}' does not exist")
    return str(p)