Better handling of invalid characters.

fixes #2, #3, #4