Clean up code

Lots of changes, presented as individual commits. Except when they are not. Some changes proved too hard to back-rev into single commits.