switched from recursive logic to iterative logic