use OLE;

die "Usage: perl norm.pl sysid\n" unless $#ARGV == 0;

$builder = CreateObject OLE 'SP.GroveBuilder';

$root = $builder->parse($ARGV[0]);

&displayMessages($root->Messages) if $root->Messages;
&normalize($root->DocumentElement) if $root->DocumentElement;

sub normalize {
    local($node) = $_[0];
    local($gi) = $node->Gi;
    if ($gi) {
	print "<$gi";
	local ($att) = $node->Attributes->NodeList->First;
	while ($att) {
	    if (!$att->implied) {
		print " ", $att->Name, "=";
		$val = $att->StringValue;
		$val =~ s/\"/&quot;/g;
		print '"', $val, '"';
	    }
	    $att = $att->NextSibling;
	}
	print ">";
	local($nd) = $node->FirstChild;
	while ($nd) {
	    &normalize($nd);
	    $nd = $nd->NextChunkSibling;
	}
	print "</$gi>" unless $node->MustOmitEndTag;
    }
    else {
	$data = $node->charChunk;
	if ($data) {
	    $data =~ s/&/&amp;/g;
	    $data =~ s/</&lt;/g;
	    $data =~ s/>/&gt;/g;
	    $data =~ s/\r/\n/g;
	    print $data;
	}
    }
}

sub displayMessages {
    local($msg) = $_[0]->First;
    while ($msg) {
	$pos = $msg->StoragePos;
	if ($pos) {
	    print STDERR $pos->StorageObjectId, ":", $pos->LineNumber, ": ";
	}
	print STDERR $msg->Text, "\n";
	$msg = $msg->NextSibling;
    }
}
