Implement most of the algorithm