#!/usr/bin/perl -w
#
# Trim unnecessary empty pixels in bdf fonts.
# Usage: bdftrim.pl < input.bdf > output.bdf
# In the horizontal direction, changes are only performed on byte boundaries (i.e. no bit shifting)
# No error checking on BDF input is done.
# Author: Serge Winitzki. http://members.tripod.com/winitzki/LS/
# Script is in public domain. Version 1.0

while (<STDIN>) {
	print;
	last if (/^CHARS\s/);
}

while (<STDIN>) {
	if (/^STARTCHAR\s/ or /^ENCODING\s/ or /^SWIDTH\s/ or /^DWIDTH\s/ or /^ENDCHAR/ or /^ENDFONT/) {
		print;
		last if (/^ENDFONT/);
	} elsif (/^BBX\s/) {
		# Don't print the BBX yet, wait until we read the whole bitmap
		($i, $width, $height, $bbx, $bby) = (split);
	} elsif (/^BITMAP/) {
		# Read the bitmap and determine the minimal bounding box. Then modify the width, height, bbx, bby and @bitmap arrays and print them.
		@bitmap = ();
		($last_e, $first_e, $left_e, $right_e) = (-1, -1, $width, $width);
		for ($i=0; $i<$height; ++$i) {
			$line = <STDIN>;
			$line =~ s/\n$//;
			push (@bitmap, $line);
			if ($line =~ /^0+$/) {	# Empty line, modify counters
				$last_e = $i if ($last_e == $i-1);
				$first_e = $i if ($first_e == -1);
			} else {	# Line not empty
				$first_e = -1;
				if ($line =~ /^(0*)([^0].*[^0])(0*)$/) {
#					print STDERR "got $1, $2, $3";	# Debugging
					$left_e = (int(length($1)/2) < $left_e) ? int(length($1)/2) : $left_e;
					$right_e = (int(length($4)/2) < $right_e) ? int(length($3)/2) : $right_e;
				}
			}
		}	# Bitmap is now in @bitmap
		# Now we need to modify @bitmap
		# First check if the bitmap is not empty
		if ($first_e == 0 or $height == 0) {
			$width = 0;
			$height = 0;
			$bbx = 0;
			$bby = 0;
		} else {
			$left_e = 0 if ($left_e == $width);	# special value
			$right_e = 0 if ($right_e == $width);	# special value
			$width = (int(($width+7)/8) - ($left_e + $right_e))*8 if ($left_e + $right_e != 0);
			$bbx += $left_e*8;
			$bby += ($height - $first_e) if ($first_e != -1);
			for ($i=0; $i < $height; ++$i) {
				$bitmap[$i] = substr($bitmap[$i], $left_e*2, length($bitmap[$i]) - ($left_e + $right_e)*2);
			}
			$height = $first_e if ($first_e != -1);
			$height -= $last_e + 1;
		}
		printf "BBX %d %d %d %d\nBITMAP\n", $width, $height, $bbx, $bby;
		for ($i=0; $i < $height; ++$i) {
			print "$bitmap[$i + $last_e + 1]\n";
		}
	}	# BITMAP
}	# ENDFONT

