Tidied up, added comments etc.