Added some event handling and general tidying up