More refactoring of code from the old branch.