Add closestCommonParentFold function for fold management.

This returns the fold that is a parent for two other folds and
is also common to both of them. If the two folds are equal,
it returns that fold.
Fix up various corner cases in folding, including child fold handling.