Better error checking and fix a bunch of static analyzer warnings