
use Treedemo;
use strict;

sub layout_tree {
    my($tree) = @_;

    # Get the representation of the root node
    my $node_lines = $tree->text;

    # Get the children of the node
    my @children = $tree->children;
    my $child_count = scalar(@children);

    # If no children, return the existing lines
    return @$node_lines unless($child_count);

    # Get the layout for each sub tree.
    my @child_lines;
    foreach my $child (@children) {
        my @lines = layout_tree($child);
#        push @lines, "";
        push(@child_lines, \@lines);
    }


    # Combine the children with the current node
    my $node_height = scalar(@$node_lines);

    # find the index of the line nearest the middle  of the array
    my $middle = int(($node_height-1)/2);

    # Determine the width of the current node and create a string of
    # spaces to pad lines in the subtrees with.
    my $node_width = length($node_lines->[0]);
    my $node_pad = " " x $node_width;

    # Printing children to the right of the parent.
    # So prepend the lines to the child lines. Need to prepend spaces
    # to the other lines.
    # If there is only one child join with ---
    # multiple children are joined with -+- for the first and +- for subseuqent

    my $yoff = $middle;
    for my $i (0..$child_count-1) {
        my $c_lines = $child_lines[$i];
        my $c_height = scalar(@$c_lines);

        # now need to combine node_lines and c_lines
        for my $j (0..$c_height-1) {
            my $ypos = $yoff + $j;
            my $separator = "   ";

            if ($j == 0) {
              if ($child_count == 1) {
                $separator = " --";
              } else {
                $separator = " +-";
              }
            } elsif ($i < $child_count - 1) {
              $separator = " | ";
            }
            substr($separator, 0, 1) = "-" if $ypos == $middle;

            # Prepend the lines of the current node to the children lines
            if($ypos < $node_height) {
                $node_lines->[$ypos] = $node_lines->[$ypos] . $separator . $c_lines->[$j];
            } else {
                $node_lines->[$ypos] = $node_pad . $separator .  $c_lines->[$j];
            }
        }
        $yoff += $c_height;
    }

    return @$node_lines;
}


