convert recursion to iteration