Various cleanups and refactorings, done as part of code review, see #1.