More refractoring, many changes. Will need testing.