add comments and tidy up code
Several modifications (Philip?)