added comments, tidied some code