Added some logging and further tidying up the code.