Refactored code to reduce redundancy