Optimized and refactored