Code Cleanup

Lots of code analysis fixed, plus one bugfix.

See commits for details.

When writing future code, try to not introduce any more code analysis warnings.