tidied code
added comments, and some code tidyup