#!/usr/bin/perl -w

my @fontsC00 = ();
my @fontsC10 = ();
my @fontsC40 = ();
sub add_char {
  my ($fonts, $char, $uval) = @_;
  my ($f, $c) = (int($char / 256), $char % 256);
  $fonts->[$f] = [] unless defined $fonts->[$f];
  $fonts->[$f]->[$c] = $uval;

}
while(<>) {
  if(/\\uc\@dclc\{(\d+)\}/) {
    my $u = $1 + 0;
    if(/\{cjkbg5\}\{\\u\@cjk\@Bgv(\d{2})([\dA-F]{2})\}/) {
      my $c = $1 * 256 + hex($2);
      add_char \@fontsC00, $c, $u;
    }
    if(/\{cjkgb\}\{\\u\@cjk\@GB(\d{2})([\dA-F]{2})\}/) {
      my $c = $1 * 256 + hex($2);
      add_char \@fontsC10, $c, $u;
    }
    if(/\{cjkjis\}\{\\jischar\{([\dA-F]{2})([\dA-F]{2})\}\}/) {
      my $c = hex($1) * 94 + hex($2) - 0xB3F;
      add_char \@fontsC40, $c, $u;
    }
  }
}
sub out_font {
  my ($enc, $fonts) = @_;
  my $nf = scalar(@$fonts);
  for(my $i = 0; $i < $nf; $i++) {
    my $f = $fonts->[$i];
    next unless defined $f;
    open E, sprintf(">uni%s%2.2d.enc", $enc, $i);
    printf E "/LaTeX%s%2.2dEncoding [", $enc, $i;
    for(my $j = 0; $j < 256; $j++) {
      print E "\n " if $j % 8 == 0;
      my $c = $f->[$j];
      $c = defined($c) ? sprintf("/uni%4.4X", $c) : "/.notdef";
      print E " ", $c;
    }
    print E "\n] def\n";
    close E;
  }
}
out_font "C00", \@fontsC00;
out_font "C10", \@fontsC10;
out_font "C40", \@fontsC40;
