updated code with more robust zero distance test
