More refactoring and bug fixing.