modified distance algorithm slightly