Changed distance calculation to treat space as a torus