Various cleanups, better error reporting

Some of this code is just hideous, from back when I sucked at this. I
did a bit of cleanup, but not nearly enough.