More cleanups
These could use a quick glossing over, but should be fine.
There are two minor bugfixes in here, a hidden unused variable, and a leak. But mostly cleaning up hard to grok stuff and trying to leave things in a slightly better state for the next visit.
I really need to look at some clean crisp code now...