Clean up code and add some explanation in comments