Made separate distance calculation function