#!/usr/bin/perl
# -*-Perl-*-
#
# bdfmerge: merge two or more BDFs into one file,
#           sorting the characters by encodings.
#
#           it requires more memory than the old bdfmerge,
#           but is more flexible, since it allows to merge two or
#           more files in arbitrary order.
#
#   USAGE: bdfmerge bdf1 bdf2 ... > out_bdf
#
#   NOTICE: The header of the 1st BDF file is used 
#           (from the beginning of file ... ENDPROPERTIES).
#           Other headers are simply ignored.
#
#   2002/5/14, by 1@2ch
#   * public domain*
#

$inheader = 1;
while(<>) {
    if (/^startchar\b/i) {
	$inchar = 1; 
	$char1 = '';
    }
    if ($inchar && /^encoding\s+([-0-9]+)\b/i) {
	$enc = $1;
    }
    if ($inchar) {
	$char1 .= $_;
    } elsif ($inheader) {
	# skip CHARS
	print $_ unless (/^chars\b/i)
    }
    if (/^endchar/i) {
	$inchar = 0;
	$chars{$enc} = $char1 if (0 < $enc);
    }
    $inheader = 0 if (/^endproperties\b/i);
}

# CHARS tag immediately follows ENDPROPERTIES
print "CHARS ", 0+keys(%chars), "\n";

# flush buffers
foreach $i (sort {$a<=>$b} keys(%chars)) {
    print $chars{$i};
}

# ENDFONT
print "ENDFONT\n";
