First pass at the refactoring, manual and automatic tests passing.