#!/usr/bin/perl

use strict;

open IN, "encodings.in"
  or die "Can't open in\n";
open out, ">encodings.c"
  or die "Can't open out\n";

my @qwritingSystems = (
    "Any",
    "Latin",
    "Greek",
    "Cyrillic",
    "Armenian",
    "Hebrew",
    "Arabic",
    "Syriac",
    "Thaana",
    "Devanagari",
    "Bengali",
    "Gurmukhi",
    "Gujarati",
    "Oriya",
    "Tamil",
    "Telugu",
    "Kannada",
    "Malayalam",
    "Sinhala",
    "Thai",
    "Lao",
    "Tibetan",
    "Myanmar",
    "Georgian",
    "Khmer",
    "SimplifiedChinese",
    "TraditionalChinese",
    "Japanese",
    "Korean",
    "Vietnamese",
    "Yi",
    "Tagalog",
    "Hanunoo",
    "Buhid",
    "Tagbanwa",
    "Limbu",
    "TaiLe",
    "Braille",
    "Other"
);

my $writingSystemsCount = @qwritingSystems;

my $num = 0;
my @xlfd = ();
my @mib = ();
my @writingSystems = ();

my $i;

while (<IN>) {
  chomp;
  s/#.*//;			
  if ( index( $_, ' ' ) > -1 ) {
    chomp;
    my @line = split( / /, $_ );
    $xlfd[$num] = $line[0];
    $mib[$num] = $line[1];
    $writingSystems[$num] = $line[2];

    $num = $num + 1;
  }

}

print out "#define make_tag( c1, c2, c3, c4 ) \\\n";
print out "    ((((unsigned int)c1)<<24) | (((unsigned int)c2)<<16) | \\\n";
print out "    (((unsigned int)c3)<<8) | ((unsigned int)c4))\n\n";

print out "struct XlfdEncoding {\n    const char *name;\n    int id;\n";
print out "    int mib;\n    unsigned int hash1;\n    unsigned int hash2;\n};\n\n";

print out "static const XlfdEncoding xlfd_encoding[] = {\n";
$i = 0;
while( $i < $num ) {
  my $x = $xlfd[$i];
  my $hash1 = "make_tag('".substr($x,0,1)."','".substr($x,1,1)."','".substr($x,2,1)."','".substr($x,3,1)."')";
  if( index( $x, "*" ) > -1 && index( $x, "*" ) < 4 ) {
    $hash1 = "0";
  }
  my $idx = length( $x ) - 4;
  my $hash2 = "make_tag('".substr($x,$idx,1)."','".substr($x,$idx+1,1)."','".substr($x,$idx+2,1)."','".substr($x,$idx+3,1)."')";
  if( index( $x, "*", $idx ) > -1 ) {
    $hash2 = "0";
  }
  print out "    { \"".$xlfd[$i]."\", ".$i.", ".$mib[$i].
    ", ".$hash1.", ".$hash2." },\n";
  $i = $i + 1;
}
print out "    { 0, 0, 0, 0, 0 }\n};\n\n";

print out "static const char writingSystems_for_xlfd_encoding[".$num."][".$writingSystemsCount.
"] = {    \n";
$i = 0;
while( $i < $num ) {
  my $j = 0;
  my @s = split( /,/, $writingSystems[$i] );
  print out "    // ".$xlfd[$i]."\n";
  print out "    { ";
  while( $j < $writingSystemsCount ) {
    if( grep( /^$qwritingSystems[$j]$/, @s ) ) {
      print out "1";
    } else {
      print out "0";
    }
    $j = $j + 1;
    if ( $j < $writingSystemsCount ) {
      print out ", ";
      if ( !(($j) % 10) ) {
        print out "\n      ";
      }
    }
  }
  $i = $i + 1;
  if ( $i < $num ) {
    print out " },\n";
  } else {
    print out " }\n";
  }
}
print out "\n};\n\n";



close out;
