Refactored and optimized