package xm::pfe::mkitemslist;
use strict;
use xm::o;
use xm::sub;

sub DESC {"
  scan the given p4 xm files for cdcl-items
  in the source-text 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 $dir = shift;

    my ($f,$n,$t);
    my $list = { }; # manual-name -> hash of values
    
    if (defined $dir and not -d $dir) { mkdir $dir, 077; }

    for $f (sort keys %$file)
    {
        my $id = "000";
	$t = $$file{$f};
        $f =~ s/\.$ext// if defined $ext;

	$t =~ s{ 
	    ( <(ITEMXDOC(?:\s[^<>]*)?)> 
		((?:.(?!</?ITEMXDOC[\s>]))*.)
		   <(/ITEMXDOC(?:\s[^<>]*)?)>
	    )|(
	      <(ITEMCDEF(?:\s[^<>]*)?)> 
		((?:.(?!</?ITEMCDEF[\s>]))*.)
		  <(/ITEMCDEF(?:\s[^<>]*)?)>
            )
	}
	{
 	    my $k;

	    if (defined $2)
	    {
		++$id;
		$k = "<$2 id=$id>$3<$4 id=$id>";
		$$list{"$f:$id"}{file} = $f;
		$$list{"$f:$id"}{n} = $id;
		$$list{"$f:$id"}{text} = $k;
	    }

	    if (defined $6)
	    {
		++$id;
		$k = "<$6 id=$id>$7<$8 id=$id>";
		$$list{"$f:$id"}{file} = $f;
		$$list{"$f:$id"}{n} = $id;
		$$list{"$f:$id"}{text} = $k;
	    }
   
	    $k
	}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"
	    ."  <TEXT>".$$list{$n}{text}."</TEXT>\n"
		."  <FILE>".$$list{$n}{file}."</FILE>\n"
		    ."<INDEX>".$$list{$n}{n}."</INDEX>\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;