Initial implementation of the iteration algorithm, needs some cleaning up.