Tidied up the code and added comments