Bugs found by coverity

Fixes from the coverity report. @mr-c, is there any way for me to run this tool on my own?