<?php
/* treematk.php for Treematk 0.3
 * by Yushin Washio
 *
 * licensed under GNU LGPL
 */
class tree{
  var $treearr =array();

  function add_branch($name='',$at=array(),&$tree=-1){
    // $at is a list of parents
    // e. g. [a,c] for x in {a:{b:{},c:{d:{},x}},e:{}}
    if($tree==-1){
      $tree =&$this->treearr;
    };
    if($at==NULL){
      $tree[$name] =array();
    }else{
      $this->add_branch($name,array_slice($at,1),$tree[$at[0]]);
    };
  }

  function generator($stree){
    $result =&$this->treearr;
    if(is_string($stree)){
      for($i=0,$name='',$addat=array();$i<strlen($stree);$i++){
        if($stree[$i]=='\\'){
          $i++;
          $name .=$stree[$i]; //just add the next character
        }elseif($stree[$i]=='.'){
          if(($name=='')and(NULL<$addat)){
            array_splice($addat,-1);
          }else{
            $this->add_branch($name,$addat);
            $name ='';
          };
        }elseif($stree[$i]==','){
          $this->add_branch($name,$addat);
          $addat[] =$name;
          $name ='';
        }else{
          $name .=$stree[$i];
        };
      };
      if($name!=''){
        $this->add_branch($name,$addat);
      };
    };
    return($result);
  }

  function child_html($childtree,$name='',$listlen=1){
    $result ='';
    if($childtree!=array()){
      foreach($childtree as $nam=>$chi){
        $result .=$this->child_html($chi,$nam,count($childtree));
      };
      if($result != ''){
        $result = '<ul>'.$result.'</ul>';
      };
    };
    return('
  <li style="width:'.(95/$listlen -5).'%">'.$name.$result.'</li>');
  }

  function tree_html(){
    $result='';
    foreach($this->treearr as $nam=>$chi){
      $result .=$this->child_html($chi,$nam,count($this->treearr));
    };
    return("<div class=\"tree\">\n<ul>$result\n</ul>\n</div>");
  }
}
?>