Tidies up and comments some of the code