Fix various bugs found by Coverity scanner.