Additional error checking and other cleanups

Hi, I've added quite a lot of additional error checking and diagnostics, and various other cleanups.
Would you like to pull these, or perhaps cherry-pick them?
Best wishes, Matt