Try factoring out encode loop.
Miscellaneous cleanup.