
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(@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

    for my $i (0..$child_count-1) {
        my $linkage = "---";
        my $link_pad = "   ";

        my $c_lines = $child_lines[$i];
        my $c_height = scalar(@$c_lines);

        my $index = 0;

        if($i > 0) {
            $index = scalar(@$node_lines);
            # To not put the blank line like in sample output
            # look at height of previous child, if greater than
            # node height don't put in extra line.
            if(scalar(@{$child_lines[$i-1]}) <= $node_height) {
                $node_lines->[$index] = $node_pad . " | ";
                $index++;
            }
        }

        # now need to combine node_lines and c_lines
        for my $j (0..$c_height-1) {
            my $seperator = $link_pad;
            # determine how to link the nodes together
            if($j == $middle) {
                if($child_count == 1) {
                    $seperator = $linkage;
                } else {
                    if($i == 0) {
                        $seperator = "-+-";
                    } else {
                        $seperator = " +-";
                    }
                }
            } elsif($j < $middle && $i > 0) {
                $seperator = " | ";
            } elsif($j > $middle  && ($i + 1) < $child_count ) {
                $seperator = " | ";
            }

            # Prepend the lines of the current node to the children lines
            if($j < $node_height && $i == 0) {
                $node_lines->[$index] = $node_lines->[$index] . $seperator . $c_lines->[$j];
            } else {
                $node_lines->[$index] = $node_pad . $seperator .  $c_lines->[$j];
            }
            $index++;
        }
    }

    return @$node_lines;
}


