Fix various issues with looping (#1) and distance calculation