#!/usr/local/bin/perl

$_ = $mapfile = shift @ARGV || $ENV{"MAPFILE"};
$command = "$0 $_";
$charset = shift @ARGV || $ENV{"CHARSET"} 
|| (/8859-(\d+)/ ? "iso8859-$1" : 
    /ascii/ ? "iso646-irv" :
    /iso-646-(\w+)/ ? "iso646-$1" :
    /iso-ir-(\d+)/ ? "isoir-$1" :
    /cp(\d+)/i ? "microsoft-cp$1" :
    /mac-(\w+)/ ? "macintosh-$1" :
    /(\w+-\w+)/i ? $1 : "iso10646-1");

chop ($date = `date +%Y-%m-%d`);
chop ($user = "$ENV{'USER'}@".`domainname`); $[=1;

dbmopen (%charname, "/usr/doc/unicode/unidata/charname.db", 0644);
$glyphdir = "/usr/doc/unicode/fonts/exploded";

sub insertglyph {

    open (GLYPH, "$glyphdir/U+$character") 
	|| return warn "U+$character: $!";

    $bitmap = ""; $width = 0;

    while (<GLYPH>)
    {
	next unless ($_) = /^\s*([-\#]+)\s*$/;
	$width = length ($_) if $width < length ($_);
	y/-#/01/; $bitmap .= unpack("H*", pack("B*", $_)). "\n";
    }

    $charname = $charname{pack("n",hex($character))};

    push (@chars, "STARTCHAR U+$character $charname
ENCODING $position
SWIDTH 500 0
DWIDTH 8 0
BBX 8 16 0 -2
BITMAP
${bitmap}ENDCHAR");

}


if ($mapfile || $charset !~ /iso10646/)
{
    open (MAP, $mapfile) || die "$mapfile: $!";
    while (<MAP>)
    {
	next if /^#/;
	warn $_, next 
	    unless /^(=|0x)([0-9A-F]{2})\s+(U\+|0x)([0-9A-F]{4})\s+/i;
	$position = hex($2); $character = "\U$4";
	next if $character =~ /^00([0189].|7F)/i;
	&insertglyph;
    }
}
else
{
    for (split (/\n/, `ls $glyphdir`))
    {
	next unless ($character) = /U[+]([0-9A-F]{4})$/;
	$position = hex ($character);
	&insertglyph;
    }

#   for ($position = 0; $position < 0x10000; ++$position)
#   {
#	$character = sprintf ("%04X", $position);
#	&insertglyph if -r "$glyphdir/U+$character";
#    }
}

$"="\n";

print "STARTFONT 2.1
COMMENT $charset charset font
COMMENT generated with $command
COMMENT on $date by $user
FONT -misc-fixed-medium-r-normal--16-160-75-75-c-80-$charset
SIZE 16 75 75
FONTBOUNDINGBOX 8 16 0 -2
STARTPROPERTIES 2
FONT_ASCENT 14
FONT_DESCENT 2
ENDPROPERTIES
CHARS $#chars
@chars
ENDFONT\n"
