Added comments and tidied up code a little.