add comments and tidy code