Rewrite distance function