Refactored the code to be more DRY.