Fix for Trac #343 (handling of 'strange' file names)

This PR includes a fix for Trac #343 and #333 and an improved fix for #246, as well as some smaller cleanup.

Since it's a fairly intrusive fix, it would be great if others could give it a spin before I merge this.