Refactoring to allow better tests; WIP
Finished refactor, passing tests, added comments.