Huge refactoring and fixup.