Wrote most of encode().