Normalized and relative file paths

Sometimes one needs to convert a file path into a form that is relative to an arbitrary base (not necessarily the current directory). That's what the function relpath does. Example:
path=a/b/c  base=../x/y
pwd                   # Output: /usr/joe
relpath $base $path   # Output: ../../joe/a/b/c
The problem is not quite trivial, as the function should also work in cases like this:
relpath  ../x/./y   ./a/../a/b/c
To relate the paths to each other, they must first be normalized, i.e. freed of any .. and . components. Also, file names with embedded blanks (a common pitfall in shell programming) should be handled correctly.

The function may be called with one or two parameters:

relpath path prints the path path in an absolute and normalized form.

relpath base path prints the path path relative to directory base. Both may be given in absolute or relative form and need not exist physically. The result may start with one or several .. components and is normalized otherwise.

Created 2011-08-11 by mopcoge