package xm::pfe::mkexportlist;
use strict;
use xm::o;
use xm::sub;
use xm::pfe::nameguess;

sub DESC {"
  scan the given p4 xm files for fcode-exports
  in the wordset-table and makes a decent table 
  from it along with its canonic names.
"}

sub from_filehash
{
    my $file = shift; # a reference to the filehash
    my $ext = shift;

    my ($f,$n,$t);
    my $list = { }; # manual-name -> hash of values
    

    for $f (sort keys %$file)
    {
	$t = $$file{$f};
	$t =~ s{ 
	    (<CSTRWORDREF(?:\s[^<>]*)?>) 
		((?:.(?!</?CSTRWORDREF[\s>]))*.)
		    (</CSTRWORDREF(?:\s[^<>]*)?>)
	    ((?:.(?!</?ITEMWORDREF[\s>]))*.?)
	    (<LINKWORDREF(?:\s[^<>]*)?>) 
		((?:.(?!</?LINKWORDREF[\s>]))*.)
		    (</LINKWORDREF(?:\s[^<>]*)?>)
		    }
	{
	    if(defined $ext) { $f =~ s/\.$ext$//; }
	    $n = xm::pfe::nameguess::of(xm::sub::un_quote($2));
	    if (not exists $$list{$n}) 
	    { 
		$$list{$n}{"file"} = $f;
		$$list{$n}{"CSTRWORDREF"} = $2;
		$$list{$n}{"LINKWORDREF"} = $6;
	    }else{
		my $i = 2;
		while (exists $$list{"$n,$i"}) { ++$i; }
		$$list{"$n,$i"}{"file"} = $f;
		$$list{"$n,$i"}{"CSTRWORDREF"} = $2;
		$$list{"$n,$i"}{"LINKWORDREF"} = $6;
	    };
	    
	    $&
	    }gsex;
    }
    return $list;
}

sub DO { 
    my $list = from_filehash(@_); 
    my $n;
    my @notunique;
    my $T = "";

    for $n (sort keys %$list)
    {
	push @notunique, $n if $n =~ /,/;
	
	$T .= "<ITEMEXPORT>\n"
	    ."  <FILE>".$$list{$n}{file}."</FILE>\n"
		."  <CSTRWORDREF>".$$list{$n}{CSTRWORDREF}."</CSTRWORDREF>\n"
                ."  <LINKWORDREF>".$$list{$n}{LINKWORDREF}."</LINKWORDREF>\n"
		    ."<NAMEEXPORT>".$n}."</NAMEEXPORT>\n"
			."</ITEMEXPORT>\n";
    }

    if (not exists $o{q} and not exists $o{quiet})
    {
	for $n (@notunique)
	{
	    print STDERR "not-unique:\t", $n,"\n";
	}
    }
}

sub ARGS { return    xm::o::args_filehash(@_,DESC); }
sub main { return DO(xm::o::args_filehash(@_,DESC)); }

1;