Modified distance function. Not optimal though