Fix read_string heuristics for decoding input

The previous implementation was vulnerable to invalid characters
that could result from latin1 encoded characters read on a handle
opened with the ":utf8" layer.

This commit refactors conversion to characters into a separate
method, attempts to fix invalid character strings, and double
decoding data that was already decoded into characters.
Make the write method create UTF-8 encoded files

Adds a "write_utf8_string" method and has "write" use that instead of
"write_string".  This preserves the existing (if suboptimal) behavior of
"write_string", but ensures generated files are correct.