More refactoring, minor bugfixes

@dwightguth review?