Fix stack overflow and add test.