Correcly handle folds that end where other folds begin

Fixes #2247