Fixes for various bugs noticed by Coverity static analysis tool.
Merge remote-tracking branch 'origin/bugfixes' into 3.1