First stage refactoring; tests pass.