Static analysis cleanup

Cleanups based on output from http://gcc-python-plugin.readthedocs.org/en/latest/ fixes a number of ref count errors and some other issues. Though most of these are likely rare corner cases that need to be fixed for correctness, not for actual impact.