Added comments and tidied up some code