improved error handling (needs a tidy up as there is now redundant code)