add depth check in the loop