Fix a bunch of bugs reported by Coverity.