Merged and tidied up (added comments)