<?php
class Stats {
    private $timing = array();
    private $type;
    
    function __construct($type) {
        $this->type = $type;
        $this->process_stats = (isset($_GET['get_stats']))? $_GET['get_stats'] :  'F';
    }
        
	private function microtime_float() {
        list($usec, $sec) = explode(" ", microtime());
        return ((float)$usec + (float)$sec);
    }
    
    public function tstart($name) {
        if (!$this->process_stats) return;
        
        if (!isset($this->timing[$name])) {
            $this->timing[$name] = array("seconds"=>0,"no"=>0);//,"id"=>$id, "parent"=>$parent);
        }
        $this->timing[$name]['starttime'] = $this->microtime_float();
    }

    public function tend($name) {
        if (!$this->process_stats) return;

        $end = $this->microtime_float();
        if (!isset($this->timing[$name]['starttime'])) $this->timing[$name]['starttime'] = $end;
        $elapsed = $end - $this->timing[$name]['starttime'];
        $this->timing[$name]['seconds'] += $elapsed;
        $this->timing[$name]['no'] += 1;
        unset($this->timing[$name]['starttime']);
    }
    
    public function asXML() {
        if (!$this->process_stats) return;
        
        $s = '<!-- STATS['.'<stats tm="'.time().'" type="'.$this->type.'">';
        foreach ($this->timing as $name=>$stat) {
            $s .= '<s t="'.$stat['seconds'].'" f="'.$name.'" n="'.$stat['no'].'"/>';
        }
        $s .= '</stats>'.'] -->';
        return $s;
    }
    
}