Refactored code with comments