Changed logic algorithm