Lots of improved error handling and logging and a bunch of bug fixes