Fix bug in distance field calculation


and other changes for perf.