# Sync the XPath2Lexer.lex debug (TokenName[]) with the autogenerated Parser tokens file

open (LEXFILE, "$ARGV[0]") or die "Cannot open requested file: $ARGV[0]";

my $outputFile = "$ARGV[0]" . ".out";
open (OUTFILE, ">$outputFile") or die "Cannot open output file: $outputFile";

# Find %%

my $copyLines = 1;
my $foundPP = 0;

while (defined($_ = <LEXFILE>)) {

  if ($_ =~ /^%%/  && !$foundPP) {

    $copyLines = 0;
    $foundPP = 1;

    print OUTFILE "%%\n\n";

    open(TOKENDEFS, "../parser/XPath2Parser.hpp") or die "Cannot open XPath2Parser.hpp";

    # extract TOKEN_NAMES and create return rules

    while (defined($_ = <TOKENDEFS>)) {

      if(/\#define\s(.*?)\s/) {
        print OUTFILE "{" . $1 . "}  return " . $1 . ";\n";
      }
    }

    close(TOKENDEFS);
    print OUTFILE "\n";

    # Print out special rules
    print OUTFILE $specialLexerRules;

  }

  elsif (/^%%/) {
    print OUTFILE;
    last;
  }

  elsif (/TOKEN_COLON_COLON/) {
    print OUTFILE;
    $copyLines = 1;
  }
  
  elsif($copyLines) {
    print OUTFILE;
  }
}


# Find #ifdef XPATHLEXERCES_CPP_NAMESPACE_QUALIFIER EBUG

my $foundIFDEF = 0;
my $inIFDEF = 0;

while (defined($_ = <LEXFILE>)) {

  if ($_ =~ /\#ifdef\ XPATHLEXERCES_CPP_NAMESPACE_QUALIFIER EBUG/x && !$foundIFDEF) {

    $foundIFDEF = 1;
    $inIFDEF = 1;

    print OUTFILE;
    print OUTFILE "char *TokenName[] = {\n";

    open(TOKENDEFS, "../parser/XPath2Parser.hpp") or die "Cannot open XPath2Parser.hpp";

    # extract TOKEN_NAMES and print in lexer debug array

    my $firstLine = 1;

    while (defined($_ = <TOKENDEFS>)) {

      if(/\#define\s(.*?)\s/) {

        if (!$firstLine) {
          print OUTFILE ",\n";
        }
        print OUTFILE "  \"${1}\"";
        $firstLine = 0;
      }
    }

    close(TOKENDEFS);
    print OUTFILE ",\n  \"Unknown\"\n};\n#endif\n";
  }

  if($inIFDEF == 1) {
    if(/#endif/) {
      $inIFDEF = 0;
    }
  }
  else {
    print OUTFILE;
  }
}

close(LEXFILE);
close(OUTFILE);

# if there have been changes, replace the .lex file

$diffRet = system("diff --brief $ARGV[0] $outputFile > /dev/null");

if($diffRet) {

  unlink(LEXFILE);
  rename($outputFile, $ARGV[0]);
}
