Improve encoding of strings. Addresses #231 and #253