#!/usr/local/bin/perl -w
# BEGIN { push(@INC, qw(../../../lib ../../lib ../lib lib)) }

die "Must be executed from Tk/pTk distribution directory\n" unless -f "Lang.h";
open(STDOUT, ">../Tk/English.auto") || die "open failed: $!";
print <<'EOH';
package Tk::English;

require Exporter;
@ISA = (Exporter);

# This file is generated automatically by pTk/makeenglish from Tk distribution.

EOH

%found = ();

@ARGV = "../Tk/English.pm";

while (<>)
 {
  if (/sub\s+([A-Z][A-Z0-9]*)\s+{\s*"-(.*)"\s*}/)
   {
    $old{$1} = $2;
   }
  while (/\*([A-Z]+)\s*=\s*\\\&([A-Z]+)/g)
   {
    $alias{$2} = $1;
   }
 }

die unless (%old);
die unless (%alias);

@ARGV = <*.c>;
while (<>) 
 {
  if (/"-([a-z][a-z0-9]+)"/)
   {my $key = $1;
    my $name = "\U$key";
    if (!defined $found{$name}) 
     {
      $found{$name} = $key;
#     print qq(sub $name { "-$key" }\n);
     }
   }
}

foreach (sort keys %old)
 {
  print STDERR "Was $_ = $old{$_}\n" unless (defined $found{$_});
 }

foreach (sort keys %alias)
 {
  if (defined $found{$alias{$_}})
   {
    print STDERR "Direct $alias{$_} exists for alias\n";
    delete $alias{$_};
   }
  else
   {
    unless (defined $found{$_})
     {
      print STDERR "No $_ for alias\n";
      delete $alias{$_};
     }
   }
 }

print "\n\@EXPORT = qw(\n";
$line = "";
foreach (sort keys %found, values %alias) 
 {
  if (length($line)+length($_)+2 > 76)
   {
    print "    $line\n";
    $line = ""; 
   }
  else
   {
    $line .= ' ' if (length $line);
   }
  $line .= "&$_";
 }
print "    $line\n" if (length $line);
print ");\n";

foreach $name (sort keys %found) {
    my $key = $found{$name};
    print qq(sub $name { "-$key" }\n);
}

foreach $name (sort keys %alias) {
    my $key = $alias{$name};
    print "*$key = \\&$name;\n";
}

print "\n1;\n";

