final version of distance function