working iterative version