Fixes to various non-obvious bugs

I played around with a static analysis tool and found some issues.
This seems wrong to me.