fixes #3: avoid stack overflows by tracking and limiting stack depth