Refactor, plus added a bunch of tests.