refactoring: distance function "exported", C style for loops replaced by while loops