General tidy up and adding some error handling