Refactor roughly finished, still needs some polish. All tests pass.