Fix stack overflow error by converting to iterative based approach.

Fixes #130.