+ unshift @body, "\\begin{pgfonlayer}{$layer}";
+ push @body, "\\end{pgfonlayer}";
+ }
+
+ return @body;
+}
+
+=head2 C<fold>
+
+=cut
+
+sub fold {
+ my ($left, $right, $rev) = @_;
+
+ my (@left, @right);
+
+ if ($my_tc->check($left)) {
+
+ if ($my_tc->check($right)) {
+
+ my ($only_left, $common, $only_right) = $inter->(
+ $left->_mods_cache,
+ $right->_mods_cache,
+ );
+
+ my $has_different_layers;
+ for (@$only_left, @$only_right) {
+ if ($_->type eq 'layer') {
+ $has_different_layers = 1;
+ last;
+ }
+ }
+
+ if (!$has_different_layers and @$common) {
+ my $x = $left->new(
+ mods => $only_left,
+ body => $left->body,
+ );
+ my $y = $left->new(
+ mods => $only_right,
+ body => $right->body,
+ );
+ return $left->new(
+ mods => $common,
+ body => fold($x, $y, $rev),
+ );
+ } else {
+ @right = $right->instantiate;
+ }
+ } else {
+ $body_tc->assert_valid($right);
+ @right = @$right;
+ }
+
+ @left = $left->instantiate;
+ } else {
+ if ($my_tc->check($right)) {
+ return fold($right, $left, 1);
+ } else {
+ $body_tc->assert_valid($_) for $left, $right;
+ @left = @$left;
+ @right = @$right;
+ }