Refactored and optimized the code.