<?php

// helpers
function hex($int) 
{
	$h = dechex($int);
	if (strlen($h)%2 != 0) 
	{
		$h = str_pad($h, strlen($h) + 1, '0', STR_PAD_LEFT);
	}
	return strtoupper($h)."h";
}
function ValidateRef($ref)
{
	$ref = str_replace("-", "_", $ref);
	$ref = str_replace("*", "", $ref);
	$ref = str_replace("?", "", $ref);
	$ref = str_replace(".", "", $ref);
	$ref = str_replace("+", "", $ref);
	if (!trim($ref)) $ref = "UNK";
	return $ref;
}
function getNetByPadOfs($pcb, $ofs)
{
	for($i=1; $i<=$pcb->HDR['comp_count_real']['v']; $i++)
	{
		for ($j=1; $j<=$pcb->COMP[$i]['pads_count']['v']; $j++)
		{
			$pad_ofs = $pcb->COMP[$i]['pad'.$j.'_ofs']['v'];
			if ($pad_ofs == $ofs)
			{                    
				return $pcb->COMP[$i]['pad'.$j.'_net']['v'];
			}
		}
	}
}

// include class
include("p/" . $proj[$PROJ_ID]['dir'] . "/Class_OrCad21.php");

// parse
// ------------------------------------------------------------------------------------------------
$pcb = new orcad21("p/" . $proj[$PROJ_ID]['dir'] . "/sprint05.pcb");
echo"file size = [".$pcb->FileSize."]<br>";

if (!$pcb->Parse())
{
	echo"parser error<br>";
	return;
}

// print results
// ------------------------------------------------------------------------------------------------
echo"min_x = ".$pcb->MinPosX.", min_y = ".$pcb->MinPosY."<br>";
echo"max_x = ".$pcb->MaxPosX.", max_y = ".$pcb->MaxPosY."<br>";

// transform all coordinates from "orcad-top-left" to "pcad-bottom-left"
$pcb->ChangePos(0,0, 0,($pcb->MaxPosY + $pcb->MinPosY), 1);

// check ref duplicated
$REF = array();
echo"validate ref...<br>";
for($i=1; $i<=$pcb->HDR['comp_count_real']['v']; $i++)
{
	$ref1 = $pcb->COMP[$i]['name1_str']['v'];
	$ref2 = ValidateRef($pcb->COMP[$i]['name1_str']['v']);
	if ($ref1 != $ref2)
	{
		echo"name [$ref1] change to [$ref2]<br>";
		$pcb->COMP[$i]['name1_str']['v'] = $ref2;
	}

}

echo"check duplicates...<br>";
$found = 0;
for($i=1; $i<=$pcb->HDR['comp_count_real']['v']; $i++)
{
	$ref = $pcb->COMP[$i]['name1_str']['v'];
	$REF[$ref] = $REF[$ref] + 1;
	if ($REF[$ref] > 1)
		$found = 1;
}
if ($found)
{
	echo"duplicate found!<br>";
	foreach ($REF as $ref => $m)
	{
		if ($REF[$ref] > 1)
		{
			echo"[$ref] = ".$REF[$ref]."<br>";
			$id = 1;
			for($i=0; $i<=$pcb->HDR['comp_count_real']['v']; $i++)
			{
				$comp_ref = $pcb->COMP[$i]['name1_str']['v'];
				if ($comp_ref == $ref)
				{
					$pcb->COMP[$i]['name1_str']['v'] = $comp_ref . "_DUP".$id;
					$id++;
				}
			}
		}
	}
}

$REF = array();
echo"check duplicates...<br>";
$found = 0;
for($i=1; $i<=$pcb->HDR['comp_count_real']['v']; $i++)
{
	$ref = $pcb->COMP[$i]['name1_str']['v'];
	$REF[$ref] = $REF[$ref] + 1;
	if ($REF[$ref] > 1)
		$found = 1;
}
if ($found)
	echo"duplicate found!<br>";
else
	echo"no duplicates now<br>";

echo"<br>";

// build ...
