added some comments and tidied up the message handeling