#!/usr/bin/perl

#use strict;

use Font::BDF;
use Getopt::Long;

my $data   = "file.dat";
my $width = 200; # pixels
my $help = 0;
my $output = undef;
my $font = undef;
my $text = undef;
my $fg = 1;
my $bg = 0;
my $v = 1;

my $result = GetOptions("output=s" => \$output,    
			"width=i" => \$width,
			"text=s" => \$text,
			"fg=s" => \$fg,
			"bg=s" => \$bg,
			"v=i" => \$v,
			) or die "perldoc me for usage";

if ($ARGV[0]) {
    if (!defined $output) { $output = "text.pbm"; }
}
else {
    pod2usage(2);
}

if (!defined $text) {
    $text = "Hello, World!";
}

$text =~ s/\\n/\n/g;

my %bitmap = ();

my $f = Font::BDF->new_from_bdf(\*ARGV);

my %p = $f->get_properties;
my $height = $p{FONT_ASCENT} + $p{FONT_DESCENT};

open OUT, ">$output" or die $!;
select(OUT);
my ($hpos, $vpos) = (0,0);
my ($maxx, $maxy) = (0,0);


for my $c (split //, $text) {
    my $enc = ord $c;
    my ($name, $offset) = $f->get_char_info ($enc);
    my ($hoff, $voff) = @$offset;
    my ($pixels) = $f->get_pixels($enc);
    if ($enc == 13 or $enc == 10) {
	$vpos += $height;
	$hpos = 0;
    } 
    else {
	for (keys %$pixels) {
	    my ($x, $y) =  /^(.+),(.+)$/;
	    my ($xp, $yp) = ($x + $hpos, $height - $y + $vpos);
	    $xp > $maxx and $maxx = $xp;
	    $yp > $maxy and $maxy = $yp;
	    $bitmap{$yp}{$xp} = 1;

	}
	$hpos += $hoff;
    }
}

my ($w, $h) = ($maxx + 1, $maxy + 1);
my $xtra = $v == 1 ? "" : "255";
print "P$v $w $h $xtra\n";
for my $j (0..$maxy) {
    my $row = $bitmap{$j};
    for my $i (0..$maxx) {
	print (($row->{$i} ? $fg : $bg), " ");
    }
    print "\n";
}


__END__


=head1 NAME

bdf2pnm

=head1 SYNOPSIS

bdf2pnm [options] font.bdf

 Options:
           --output file        set output file (defaults to 
                                text.pbm)
           --text t             text to render (\n creates newline)          
           --fg grayval         set foreground color
           --fg "r g b"         
           --bg grayval         set background color
           --bg "r g b"         
           -v n                 set PNM format version to n
                                1 = bitmap
                                2 = grayscale
                                3 = color
=head1 DESCRIPTION

B<bdf2sfd> reads in a X11 bitmap font in BDF format, and outputs a PNM
file with text in that font.

=cut

