<?php

$script_mode = TRUE;
include 'wwwroot/inc/init.php';

$netlist = listCells ('ipv4net');
foreach ($netlist as $cell)
	echo $cell['id'] . "\t" . $cell['ip'] . "/" . $cell['mask'] . "\n";

IPNetworkCmp_debug ($netlist[11], $netlist[12]);

$buggy_tree = makeIPTree_debug ($netlist);
displayTree ($buggy_tree);

function displayTree ($tree, $indent = '')
{
	$self = __FUNCTION__;
	foreach ($tree as $item)
	{
		echo $indent . $item['ip'] . '/' . $item['mask'] . "\n";
		$self ($item['kids'], $indent . '  ');
	}
}

function makeIPTree_debug ($netlist)
{
	// treeFromList() requires parent_id to be correct for an item to get onto the tree,
	// so perform necessary pre-processing to calculate parent_id of each item of $netlist.
	$stack = array();
	foreach ($netlist as $net_id => &$net)
	{
		while (! empty ($stack))
		{
			$top_id = $stack[count ($stack) - 1];
			echo "     * net#$top_id is on the top\n";
			if (-2 !== IPNetworkCmp_debug ($netlist[$top_id], $net)) // unless $net is a child of stack top
				array_pop ($stack);
			else
			{
				$net['parent_id'] = $top_id;
				break;
			}
		}
		if (empty ($stack))
			$net['parent_id'] = NULL;
		echo " * * * parent for $net_id is ${net['parent_id']}\n";
		array_push ($stack, $net_id);
	}
	unset ($stack);

	$tree = treeFromList ($netlist); // medium call
	return $tree;
}

function IPNetworkCmp_debug ($netA, $netB)
{
	if (strlen ($netA['ip_bin']) !== strlen ($netB['ip_bin']))
	{
		printf("strlen(a) %d != strlen (b) %d\n", strlen ($netA['ip_bin']), strlen ($netB['ip_bin']));
		return strlen ($netA['ip_bin']) < strlen ($netB['ip_bin']) ? -1 : 1;
	}
	$ret = strcmp ($netA['ip_bin'], $netB['ip_bin']);
	print "strcmp = $ret\n";
	if ($ret == 0)
	{
		$ret = $netA['mask'] < $netB['mask'] ? -1 : ($netA['mask'] > $netB['mask'] ? 1 : 0);
		print "ips are qeual, masks cmp = $ret\n";
	}
	if ($ret == -1 and $netA['ip_bin'] === ($netB['ip_bin'] & $netA['mask_bin']))
		$ret = -2;
	elseif ($ret == -1)
	{
		$first_bin = $netB['ip_bin'] & $netA['mask_bin'];
		$first = ip_format ($first_bin);
		print "first = $first\n";
		if ($netA['ip_bin'] !== $first_bin)
			print "${netA['ip']} != $first\n";
	}
	printf ("%s/%d - %s/%d = %d\n", $netA['ip'], $netA['mask'], $netB['ip'], $netB['mask'], $ret);
	return $ret;
}


