Refactor to support tests, and write tests