major refactoring of closest neighbour calculation