Refactor; should be easier to test, too