refactoring and speed optimization