Added some logging and general tidying up