<?php
/*
* Copyright (c) 2009-2010 Atmail. All rights reserved
* See http://atmail.com/license.php for license agreement
* Author : Atmail
*/

$total = 0;
$startTime = 0;
$updateTime = 0;
$updateCount = 0;

function resetStats($shm_key = null)
{
	global $startTime;
	$startTime = 0;
	
	if($shm_key != null)
	{
		$stats_shm_id = shmop_open($shm_key, "w", 0644, 100);
		shmop_write($stats_shm_id, str_to_nts($startTime), 16);
		shmop_write($stats_shm_id, str_to_nts($startTime), 32);
		shmop_write($stats_shm_id, str_to_nts($startTime), 48);	
		shmop_close($stats_shm_id);
	}
}

function microtime_float()
{
	list($usec, $sec) = explode(" ", microtime());
	return ((float)$usec + (float)$sec);
}

function displayElaped($msg, $then, $displayType)
{
	$now = microtime_float();
	if($displayType == "human")
	{
		$diff = $now - $then;
		$time = floor($diff / 60) . "m" . ($diff) % 60 . "s";
		fwrite(STDOUT, "\n" . $msg . " : " . $time . "\n");		
	}
	else
	{
		fwrite(STDOUT, "\n" . $msg . " : " . (($now - $then) * 100.0) . " ms\n");
	}
}

function displayStats($count, $total, $shm_key = null)
{
	if($shm_key != null)
	{
		$stats_shm_id = shmop_open($shm_key, "w", 0644, 100);
		$startTime = (float)str_from_mem(shmop_read($stats_shm_id, 16, 16));
		$updateTime = (float)str_from_mem(shmop_read($stats_shm_id, 32, 16));
		$updateCount = (float)str_from_mem(shmop_read($stats_shm_id, 48, 16));
	}
	else
	{
		global $startTime;
		global $updateTime;
		global $updateCount;		
	}
	
	if($startTime == 0)
	{
		$startTime = microtime_float();	
	}
		
	$now = microtime_float();
	if($now > $updateTime + 1 || $count == $total - 1)
	{
		$diff = $now - $startTime;
		if($diff != 0)
		{
			$averagePerSec = ($count / $diff);
		}
		
		if($averagePerSec < 0)
			$averagePerSec = 0;
			
		if($averagePerSec != 0)
		{
			$timeLeft = $total / $averagePerSec;
			$timeLeft = $timeLeft - $diff;
			if($timeLeft < 0)
				$timeLeft = 0;
			$averageTimeLeft = floor($timeLeft / 60) . "m" . ($timeLeft) % 60 . "s";
		}
		else
		{
			$averageTimeLeft = "∞";
		}
		$timeTaken = floor($diff / 60) . "m" . ($diff) % 60 . "s";
		$averagePerSecNow = ($count - $updateCount) / ($now - $updateTime);
		if($averagePerSecNow < 0)
			$averagePerSecNow = 0;
		fwrite(STDOUT, "\r                                                                                     ");
		fwrite(STDOUT, "\r" . ($count + 1) . "/" . $total . " " . $timeTaken . " elasped " . $averageTimeLeft . " remaining. (now " . floor($averagePerSecNow) . " avg " . floor($averagePerSec) . " items/sec)");
		$updateTime = microtime_float();
		$updateCount=$count;
	}
	
	if($shm_key != null)
	{
		shmop_write($stats_shm_id, str_to_nts($startTime), 16);
		shmop_write($stats_shm_id, str_to_nts($updateTime), 32);
		shmop_write($stats_shm_id, str_to_nts($updateCount), 48);
		shmop_close($stats_shm_id);
	}
}
