Added sub function to calculate minimum distance.