wrote distance function