tidied up the code and added some inline doc