More refactoring, and bug fixes.