Refactoring some code. Adding a few tests.