Refactoring

Stage 1 of #188. This needs testing to make sure I didn't accidentally break anything, then I'll continue with the next stage.