Replacing manual search with an efficient kd search