Refactoring nearest line calculation