tidied up and added comments