Clean up the code and add some comments