Refactoring nearest point in line and distance calculation