beautified code and added more comments for clarity.