switch from recursive to iterative