More refactoring, needs testing