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..
Use C++ or Doxygen style comments