improved handling of invalid characters