Make Python 3 compatible, pass 2

Fix encoding issues.

It would probably be good if the boundaries between text and bytes were
better defined. As it is now, there are various checks for bytes vs
text which ISTM shouldn’t be necessary (and which also seems quite
brittle).