refactor distance calculation