Cleaning up the code and adding comments