Refactor

A variety of code cleanups and refactorings, not affecting behaviour.