Changed from recursive to iterative