Code cleanup

I've split the changes into a commit for each kind of change so you can review them easily.