Refactor and add tests.