Refactored and optimized code