Code fixes

Various code fixes, mostly discovered by MSVC code static analyzer .
I think you're gonna need to explain this one.  It's not obvious to me at all what is supposed to be happening here.