Completed the code and added comments