Fixed a bunch of bugs found by Coverity