fixing the algorithm; now works with max distance too. Big change