Refactor

Various cleanup and refactoring, with some added tests.