Tidy code and add comments