Refactoring and adding minDistance