Fixed infinite looping in new iterative version