Made dist() more robust