#!/usr/bin/perl -w
use strict;

use lib qw(.);
use ExampleTree;

my $tree = ExampleTree->new( "top",
 ["1",["1.1"],["1.2",["1.2.1"]]],
 ["2",["2.1",["2.1.1",["2.1.1.1",["2.1.1.1.1"]]]]],
 ["3",["3.1"],["3.2"],["3.3",["3.3.1"]]],
 ["4"],
 ["5",["5.1"],["5.2",["5.2.1"]],["5.3"],["5.4"]]
);

print join("\n",layout_tree($tree)),"\n";

##### NOW THE FUN BEGINS #####

# Only written a one interpretation.
# Depth reads left to right, siblings appear below each other.

sub layout_tree {
 my $tree = shift;        # the current tree object
 my $hash = shift;        # hash settings

 my $layout = $tree->text();      # the current node
 my @children = $tree->children();    # the children (if any)
 my @extended = ();        # the extended layout
 my $pad = '';         # text padding string
 my $ht = scalar(@$layout)-1;     # height of text node
 my $half = int $ht/2;       # halfway point in text

 # deal with the hash settings first
 if(defined $hash) {
  if(defined $hash->{prepad}) {    # create the padding
   $pad = ' ' x $hash->{prepad};   #  string if required
  }

  # if current node is a child, prepend links to parent node
  if(defined $hash->{ischild}) {
   foreach my $inx (0..$ht) {
    if($inx == $half) {     # add link at halway point
     if($hash->{ischild} == 1) {  # only child
      $layout->[$half] = $pad . '--' . $layout->[$half];
     } elsif($hash->{ischild} > 1) { # has siblings
      $layout->[$half] = $pad . '+-' . $layout->[$half];
     }
    } else {
     $layout->[$inx] = $pad . '  ' . $layout->[$inx];
    }
   }
  }
 }

 # if no children, just return the leaf node layout
 return @$layout unless(@children);

 foreach my $inx (0..$ht) {      # append link lines
  $layout->[$inx] .= ($inx == $half ? '-' : ' ');
 }

 # child hash settings
 my %next = (
  ischild => scalar(@children),    # parent child count
  prepad => length($layout->[0]),    # current padding value
 );

 # add each child layout to the extended layout
 foreach my $child (@children) {
  push @extended, layout_tree($child,\%next);
 }

 # insert the parent into the extended layout
 for my $inx (0..$ht) {
  substr($extended[$inx],0,$next{prepad},$layout->[$inx]);
 }

 # if more than one child, link the children together
 if($next{ischild} > 1) {
  my $count = 0;
  foreach (@extended) {
   # found a link node
   $count++ if(m/^(.{$next{prepad}})\+/);

   # if between nodes, link them
   $_ =~ s/^(.{$next{prepad}}) /$1|/
    if($count > 0 && $count < $next{ischild});
  }
 }

 return @extended;        # return extended layout
}



