Refactored to make testing easier.