Refactored code to DRY it up