Fixups potpourri

Fixes many memory leaks and use-after-free bugs.

There are still lifeycle bugs left, the test suite hits them fairly reliably.  I wonder if it isn't less work to simply rewrite from scratch instead of trying to track down bug after bug...