Bug fixes and code cleanup identified by valgrind and clang.
Merge pull request #780 from sorlok/minor_fixes

Bug fixes and code cleanup identified by valgrind and clang.