#!/usr/bin/perl -w
#
# Convert bdf fonts to raw console fonts (only works well for fixed fonts!)
# Usage: bdf2fon.pl [-verbose] < input.bdf > output.fnt
# Limitations: may produce unusable console fonts if char bitmap bounding box is not 8x16 or 8x14 or whatever the console can accept
# Author: Serge Winitzki. http://www.linuxstart.com/~winitzki/
# Script is in public domain. Version 1.0

$verbose = ("@ARGV" =~ /-verbose/i) ? 1 : 0;

while (<STDIN>) {
	if (/^FONTBOUNDINGBOX\s/) {
		($i, $fwidth, $fheight, $i, $fbby) = (split);
		if ($fwidth == 9 or $fwidth == 8) {
			$fwidth = 8;
		} else {
			print STDERR "Error: font width is not 8 or 9, stop.\n";
			exit 1;
		}
	}
	if (/^CHARS\s(.*)$/) {
		$totalchars = $1;
		last;
	}
}

print STDERR "$totalchars chars in font\n" if ($verbose);

# Prepare an empty line and fill the char array with empty chars

$emptyline = "\x00" x int($fwidth/8);
@chars = ();
for ($i=0; $i<256; ++$i) {
	$chars[$i] = $emptyline x $fheight;
}

while (<STDIN>) {
	if (/^ENCODING\s([0-9]*)$/) {
		$charcode = $1;
		$chars[$charcode] = "";	# This char is present in font
	} elsif (/^ENDCHAR/) {
	} elsif (/^DWIDTH\s([0-9]*)\s/) {
	} elsif (/^BBX\s/) {
		# Don't print the BBX yet, wait until we read the whole bitmap
		($i, $i, $height, $i, $bby) = (split);
		# Print a number of empty lines if necessary
		$skip = ($fbby + $fheight) - ($bby + $height);
		if ($skip>0) {
			$chars[$charcode] .= $emptyline x $skip;
		}
	} elsif (/^BITMAP/) {
		# Read the bitmap and print the packed bytes
		for ($i=0; $i<$height; ++$i) {
			$line = <STDIN>;
			$line =~ s/$([0-9A-Fa-f][0-9A-Fa-f])/$1/;	# Want only first 2 digits
			$chars[$charcode] .= pack("H2", $line);
		}
		# Print some empty lines
		$skip = $bby - $fbby;
		if ($skip>0) {
			$chars[$charcode] .= $emptyline x $skip;
		}
		#End of bitmap handling
	} elsif (/^ENDFONT/) {
		last;
	}
}

# Now print the output file

for ($i=0; $i<256; ++$i) {
	print $chars[$i];
}
