Refactor for easier unit testing, add some tests.