Recursion replaced by a while loop.

This avoids a 'stack level too deep' #328