Refactored code to remove duplication