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..
If you are gonna change this line, please use either C++ style comments
```
// Performs ...
```
or the Doxygen style
```
/**
 * Performs...
 */
```