Commented and tidied up code