refactoring and algorithm tuning