Encode according to stream encoding

Here's another stab at #116/#130 -- still missing a test that shows the failure case, but this is working for me in practice, in combination with the other unicode/ascii fix I just merged.