Refactor and add unit tests.