tidy up and some better error handling