Squash static analyzer warnings.

Adresses #3829. Removes unused variables and checks for null pointers. Sorry, there is also a bit of whitespace fixes in there..