Fix stack overflow bug