Added comments, refactored code and improved readability.