- my ($walk, $ordersub) = @_;
-
- my %seen;
- my @visited;
- while ($walk) {
- push @visited, $walk;
-
- # spot/break loops
- $seen{$walk} = 1;
-
- my $child = $walk->{child};
- if ($child && $seen{$child}) {
- $walk->{child} = $child = undef;
- }
-
- my $next = $walk->{next};
- if ($next && $seen{$next}) {
- $walk->{next} = $next = undef;
- }
-
- # go down, or across
- $next = $child if $child;
-
- # no next? look up
- if (!$next) {
- my $up = $walk;
- while ($up && !$next) {
- $up = $up->{parent};
- $next = $up->{next} if $up;
- }
- }
- $walk = $next;
- }
- foreach my $cont (@visited) {
- my $children = $cont->children;
- next if @$children < 2;
- $children = $ordersub->($children);
- $cont = $cont->{child} = shift @$children;
- do {
- $cont = $cont->{next} = shift @$children;
- } while ($cont);
+ my ($cur, $ordersub, $ctx) = @_;
+
+ my %seen = ($cur => 1); # self-referential loop prevention
+ my @q = ($cur);
+ my $ibx = $ctx->{-inbox};
+ while (defined($cur = shift @q)) {
+ my $c = $cur->{children}; # The hashref here...
+
+ $c = [ grep { !$seen{$_}++ && visible($_, $ibx) } values %$c ];
+ $c = $ordersub->($c) if scalar @$c > 1;
+ $cur->{children} = $c; # ...becomes an arrayref
+ push @q, @$c;