Added comments and refactored code slightly