Improved distance calculation.