Improved error checking and general tidy up
Improved error checking, general tidy up