CORE-4875: Moved code around to make it easier to test.