Adding replacement of invalid characters.
Improving error handling.