Optimized and refactored code