Various codegen improvements

Don't merge yet, for the moment just using this pull request to track the work in this branch.

For a start, resolves #100.