Updated for faster algorithm.