Refactored the code and added the comments.