optimization: change recursive-tail call to loop.