Do not generate invalid filenames. Fixes #814.

Turn invalid characters into underscores, remove leading dots and enforce
a maximum length. Should be fine on main file systems used by Windows, Mac OS
and Linux.
Thanks to @Avaris for helping to clean my code.