More refactor. Needs testing.