Refactoring and adding some tests.