Add max depth checking to avoid stack overflow