Another hefty batch of refactoring, this time it actually compiles.