Tidy code and add some comments