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?

Also, there is one real bugfix here, unfortunately a bit buried on other changes:

freopen("/proc/kmsg", "a", stderr) => EBADF
...but...
freopen("/proc/kmsg", "w", stderr) => a valid FILE *

I'm guessing that this fails in the append case because the underlying lseek call fails because /proc/kmsg is of length zero, or otherwise because it is not an on-disk file.

Best wishes, Matt