Refactored and optimized.