tidied up code and added some comments