#!/usr/bin/env perl
use strict;
use warnings;
use English;
use Carp;
use FindBin;
use Getopt::Std;

#use Data::Dumper;
use XML::LibXML;

sub usage {
  my $message = shift || '';
  $message = "Error: $message\n" if $message;
  die <<EOU;
$message
Usage:
  $FindBin::Script

  Merge a bunch of gamexml files, optionally adding prefixes to the
  displayed names of things that come from each file.

  Options:

  -p pre,pre,pre,...

     comma-separated list of prefixes for identifiers from each file.
     If specified, there must be as many prefixes here as files.

EOU
}

our %opt;
getopts('p:',\%opt) or usage();

my @files = @ARGV;
my @prefixes = do {
  if($opt{p}) {
    split /,/,$opt{p};
  }
  else {
    map {''} @files;
  }
};
@prefixes == @files
  or usage('must have same number of prefixes as files');

my $parser = XML::LibXML->new();
my $doc = $parser->parse_file(shift @files);
rename_stuff($doc,shift @prefixes);

my $ins_point = $doc->documentElement; #should be the <game> element

foreach my $file (@files) {
  my $doc2 = $parser->parse_file($file);
  my $node = $doc2->documentElement;

  rename_stuff($doc2,shift @prefixes);

  foreach my $child_node ($node->childNodes) {
    # Do not copy the <seq focus=true> element multiple times
    next if ( $child_node->nodeName() eq 'seq'
	      and $child_node->getAttributeNode("focus")
	      and $child_node->getAttributeNode("focus")->textContent eq 'true'
	    );
    #	print "appending node ".$child_node->nodeName."\n";
	
    $ins_point->appendChild($child_node);
  }
  #      $doc2->dispose();
}

print $doc->toString;


sub rename_stuff {
  my ($doc,$prefix) = @_;

  return unless $prefix;

  #find all the id attributes and name elements, add the prefix to
  #their contents

  my $rootnode = $doc->documentElement;

  my @textnodes = $rootnode->findnodes('//name/text()');
#  warn "got text nodes @textnodes\n";
  foreach my $textnode (@textnodes) {
    my $namenode = $textnode->parentNode;
#    warn "got name node $namenode\n";
    my $t = $prefix.'-'.$textnode->textContent;
#    warn "made new text content $t\n";
    my $newtext = $doc->createTextNode($t);
#    warn "made new text $newtext\n";
    $namenode->removeChild($textnode);
    $namenode->appendChild($newtext);
  }
}




