Added distance checks to fix #787