Refactor and add distance function.