Added comments and refactored code for better readability