More refactoring and speedup