Kind of refactor `codegen`.

It still doesn't look very good (and I accidentally made it bigger), but hey, comments!

Fixes #1