Added comments and refactored the code