Work on bug #27, some cleanups and refactorings.