Tidied up code and added comments and docblocks