##########################################################################
#
#  Perl program to read a hmp file and expand it to a constant record
#
#  Run the script by typing 
#
#    perl fontfile
#
#  where fontfile.hmp is a font file with the mapping of the 
#  characters 32-127 to Hershey symbols.
#
##########################################################################
while ($ARGV[0]=~ /\.hmp/i) {
  $fontName= $ARGV[0];
  $fontName=~ s/\.hmp//i;  # Erase the file extension
  $fontName=~ tr/A-Z/a-z/;
  $fontName=~ s/^(.)$/ $ch=$1, $ch=~tr|a-z|A-Z|, $ch/e;  
  &printHeader;
  open(IN, $ARGV[0]);
  while(<IN>) {
    @charNumbers=split(/\s+/);
    foreach (@charNumbers) {
      if (/(\d+)\-(\d+)/) {
        for $i ($1..$2) {
          if (32 + $numCount > 127) { 
            print STDERR "Warning! Too many entries in HMP file! Truncating...\n"; 
            goto GotEnough; 
          }
          &printNum($i);
          $numCount++;
        }
      }
      else {
        if (32 + $numCount > 127) { 
          print STDERR "Warning! Too many entries in HMP file! Truncating...\n";
          goto GotEnough; 
        }
        &printNum($_);
        $numCount++;
      }
    }
  }

GotEnough:
  close(IN);
  
  # Fill the rest of the table with the zero character 
  if (32 + $numCount <= 127) {
    print STDERR "Not enough entries in HMP file. Filling reminder with zeroes.\n";
  }
  for (32+$numCount..127) { &printNum(0); }
  &printTail;
  print "\n";

  # Now there is just one comma too many at the very, very end. Erase it...
  $*=1;         # Set multiline handling on
  $outString=~ s/,\)/\)/;
  $outString=~ s/,(\n\s*\))/\)/;
  
  # print the new neatlooking character table
  print $outString;

  shift;
}

#######################################################################
# Output routines. They can easily be changed for any programming 
# language. This version is for a constant record in Turbo Pascal.
#######################################################################
sub printHeader {
  $outString= "const\n  Hershey" . $fontName ." : HersheyFont = (\n  ";
}

sub printTail {
  $outString .= ");\n";
}

sub printNum {
  $outString .= sprintf("%4d,", $_[0]);
  if (++$numNumbersOnLine == 16) {
    $numNumbersOnLine = 0;
    $outString .= "\n  ";
  }
}

