refactoring and speedup