Refactor to remove some code duplication.