Minor refactoring and adding tests.