Refactored to be able to extract methods for testing.