Misc fix

Bugs found by STACK:

    https://github.com/xiw/stack

and some misc enhancements.