Refactor and add some tests.