Simplified XS code. max_distance argument added