Fix a bunch of bugs caught by static analysis

There are more, but I will file a bug with the remaining.