#!/usr/bin/perl

my @cmpfiles;

while($ARGV[0] eq "-c") {
	shift(@ARGV);
	push(@cmpfiles, shift(@ARGV));
}

if( $#ARGV < 1) {
	die("Usage: $0 [-c file]... file glyph-code...\n");
}

$fname=shift @ARGV;

# storage for files
my %fontname;
my %fbbox;
my %fblues;
my %fenc;
my %frevenc;
my %fsubrs;
my %fchars;
my @cmnbbox; # common bounding box covering all files

@cmnbbox = (100, 100, 100, 100);

# read all files into memory
for $f (@cmpfiles, $fname) {
	open(FILE, "<$f") or die("no such file $f");
	while(<FILE>) {
		if(/FontBBox\s+\{\s*(.*)\s*}/) {
			@bbox=split(/\s+/, $1);
			push(@{$fbbox{$f}}, @bbox);
			if($bbox[0] < $cmnbbox[0]) {
				$cmnbbox[0] = $bbox[0];
			}
			if($bbox[1] < $cmnbbox[1]) {
				$cmnbbox[1] = $bbox[1];
			}
			if($bbox[2] > $cmnbbox[2]) {
				$cmnbbox[2] = $bbox[2];
			}
			if($bbox[3] > $cmnbbox[3]) {
				$cmnbbox[3] = $bbox[3];
			}
		} elsif( /BlueValues\s+\[\s*(.*)\s*\]/ || /OtherBlues\s+\[\s*(.*)\s*\]/ ) {
			@blues=split(/\s+/, $1);
			push(@{$fblues{$f}}, @blues);
		} elsif( /^dup\s+(\d+)\s+\/(\S+)\s+put/ ) {
			$fenc{$f}{$1} = $2;
			if( ! defined $frevenc{$f}{$2} ) {
				$frevenc{$f}{$2} = $1;
			}
		} elsif( /^dup\s+(\d+)\s+\{\s*$/ ) {
			$key = $1;
			$bf = $_;
			while(<FILE>) {
				$bf .= $_;
				if( /\}\s+NP/ ) {
					last;
				}
			}
			$fsubrs{$f}{$key} = $bf;
		} elsif( /^\/(\S+)\s+\{\s*$/ ) {
			$key = $1;
			$bf = $_;
			while(<FILE>) {
				$bf .= $_;
				if( /endchar/ ) {
					last;
				}
			}
			$fchars{$f}{$key} = $bf;
		} elsif( /^\/FontName\s+(\S+)/ ) {
			$fontname{$f} = $1;
		}
	}
	close(FILE);
}

######################## Prolog ###################################

print("%%!PS-Adobe-1.0
%%DocumentNeededResources: font Courier
%%Pages: (atend)
%%EndComments
%%BeginProlog
/cmpfcolorarray [ 
	[ 1 0.2 0.2 ] % slightly lighter red
	[ 0 0.7 0.7 ] % cyan 
	[ 0.7 0.7 0 ] % brown-yellow
] def
/cmpfcolor { % number -> .
	cmpfcolorarray length mod % get the subarray number
	cmpfcolorarray exch get aload pop setrgbcolor
} bind def
/contourcolor { 0 0 0 setrgbcolor } bind def % black
/bluezonecolor { 0.95 0.95 1 setrgbcolor } bind def % very light blue
/coordcolor { 0 1 0 setrgbcolor } bind def % green
/textcolor { 0 0 0 setrgbcolor } bind def % black
/stemcolor { 1 0 0 setrgbcolor } bind def % red
/mainstemcolor { 0 0 1 setrgbcolor } bind def % blue

% /fnt2pt { 72 5 mul 1000 div } bind def

/linehor { % . font_y -> .
	gsave
	0 72 translate
	72 fnt2pt scale
	newpath
	0 exch moveto
	7 0 rlineto
	stroke
	grestore
} bind def

/linevert { % . font_x -> .
	gsave
	72 0 translate
	fnt2pt 72 scale
	newpath
	0 moveto
	0 7 rlineto
	stroke
	grestore
} bind def

/bluezone { % . font_y_1 font_y_2 -> .
	gsave
	bluezonecolor
	0 72 translate
	72 fnt2pt scale
	newpath
	0 exch moveto
	7 0 rlineto
	7 exch lineto
	-7 0 rlineto
	closepath
	fill
	grestore
} bind def

/drawstem { %  . xwidth ywidth x0 y0 -> .
	gsave
	72 72 translate fnt2pt fnt2pt scale xorg yorg translate
	newpath
	moveto
	dup 0 exch rlineto
	exch 0 rlineto
	neg 0 exch rlineto
	closepath fill
	grestore
} bind def
	
/getlen {
	dup stringwidth pop
} bind def

/compressfont 0.8 def

/label { % . string stringwd y -> .
	dup lasty lt {
		dup lasty fontsz sub le
	} { 
		dup lasty fontsz add ge
	} ifelse {
		/curx 0 store
	} if
	dup /lasty exch store
	0 exch moveto
	compressfont mul dup curx add maxx gt {
		/curx 0 store
	} if
	curx 0 rmoveto
	dup 0 rlineto
	stroke
	gsave
	curx lasty moveto
	curx add /curx exch store
	compressfont 1 scale
	show
	grestore
} bind def
");

@bbox=@cmnbbox;

$nx=$bbox[2]-$bbox[0];
$ny=$bbox[3]-$bbox[1];
$maxsz= ($nx>$ny) ? $nx : $ny;
$fnt2pt= 72*5/$maxsz;
printf("/fnt2pt 72 5 mul %d div def\n", $maxsz);
$xorg= -($bbox[0]-($maxsz-$nx)/2); 
$yorg= -($bbox[1]-($maxsz-$ny)/2);
printf("/xorg %d def /yorg %d def\n", $xorg, $yorg);

print("
%%EndProlog
");

######################## Subroutines ##############################

sub bluezone # from to
{
	my ($a, $b)=@_;
	printf("%d %d bluezone\n",$a+$yorg, $b+$yorg);
	$ycoord{$a+0}=1;
	$ycoord{$b+0}=1;
}

sub linehor # x
{
	my $a=$_[0];
	printf("%d linehor\n",$a+$yorg);
	$ycoord{$a+0}=1;
}

sub linevert # x
{
	my $a=$_[0];
	printf("%d linevert\n",$a+$xorg);
	$xcoord{$a+0}=1;
}

sub hstem # from width
{
	my ($from, $width)=@_;
	$stemhused=1;
	printf("%d %d %d %d drawstem %% %d %d h \n", -$stemwd, $width,
		$bbox[0]-2-$stemhgrp*$stemwd, $from,
		$from, $width);
	printf("%d %d %d %d drawstem %% %d %d h \n", $stemwd, $width,
		$bbox[2]+2+$stemhgrp*$stemwd, $from,
		$from, $width);
}

sub vstem # from width
{
	my ($from, $width)=@_;
	$stemvused=1;
	printf("%d %d %d %d drawstem %% %d %d v \n", $width, -$stemwd,
		$from, $bbox[1]-2-$stemhgrp*$stemwd,
		$from, $width);
	printf("%d %d %d %d drawstem %% %d %d v \n", $width, $stemwd,
		$from, $bbox[3]+2+$stemhgrp*$stemwd,
		$from, $width);
}

sub nextstemgrp
{
	if($stemhused || $stemvused) {
		$stemhgrp++;
		$stemhused=0;
		$stemvgrp++;
		$stemvused=0;
	}
}

sub substems # fname subrlist
{
	my $fname = shift;
	my $i, $cmd, @vals;

	print("\nstemcolor\n");

	for $i (@_) {
		&nextstemgrp();
		for $_ (split(/\n/, $fsubrs{$fname}{$i})) {
			s/^\s+//;
			@vals=split(/\s+/, $_);
			$cmd=$vals[$#vals];
			if($cmd eq "hstem") {
				&hstem($vals[0], $vals[1]);
			} elsif($cmd eq "vstem") {
				&vstem($vals[0], $vals[1]);
			}
		}
	}
	print("\n");
}

sub drawcharwstems # charstring
{
	my($x,$y)=(0,0);
	my @vals, $cmd, $i;

	print("\nmainstemcolor\n");
	&nextstemgrp();
	for $_ (split(/\n/, $_[0])) {
		s/^\s+//;
		@vals=split(/\s+/, $_);
		$cmd=$vals[$#vals];

		if($cmd eq "hsbw") {
			$x=$vals[0]+0;
		} elsif($cmd eq "hstem") {
			&hstem($vals[0], $vals[1]);
		} elsif($cmd eq "hstem3") {
			&hstem($vals[0], $vals[1]);
			&hstem($vals[2], $vals[3]);
			&hstem($vals[4], $vals[5]);
		} elsif($cmd eq "vstem") {
			&vstem($vals[0], $vals[1]);
		} elsif($cmd eq "vstem3") {
			&vstem($vals[0], $vals[1]);
			&vstem($vals[2], $vals[3]);
			&vstem($vals[4], $vals[5]);
		} elsif($cmd eq "rmoveto") {
			# a shortcut
			last;
		}
	}
	&drawchar("drawchar", 1, "contourcolor", $_[0]);
}

sub drawchar #procname wantgrid color charstring
{
	my($procname, $wantgrid, $color, $charstring) = @_;
	my($x,$y)=(0,0);
	my @vals, $cmd, $i;
	my %xv=();
	my %yv=();

	printf("\n/%s {\n",$procname);
	printf("\ngsave 72 72 translate fnt2pt fnt2pt scale %d %d translate\n", $xorg, $yorg);
	printf("%s 1 setlinewidth newpath\n", $color);
	for $_ (split(/\n/, $charstring)) {
		s/^\s+//;
		@vals=split(/\s+/, $_);
		$cmd=$vals[$#vals];

		if($cmd eq "callsubr" && $vals[1] == 4) {
			push(@subrlist, $vals[0]);
		} elsif($cmd eq "amoveto") {
			$x=$vals[0]+0;
			$y=$vals[1]+0;
			$xv{$x+0}=1; $yv{$y+0}=1; 
			printf("%d %d moveto\n", $x, $y);
			printf("%d %d 5 0 360 arc %d %d moveto\n", $x, $y, $x, $y);
		} elsif($cmd eq "rmoveto") {
			$x+=$vals[0];
			$y+=$vals[1];
			$xv{$x+0}=1; $yv{$y+0}=1; 
			printf("%d %d moveto\n", $x, $y);
			printf("%d %d 5 0 360 arc %d %d moveto\n", $x, $y, $x, $y);
		} elsif($cmd eq "hmoveto") {
			$x+=$vals[0];
			$xv{$x+0}=1; $yv{$y+0}=1; 
			printf("%d %d moveto\n", $x, $y);
			printf("%d %d 5 0 360 arc %d %d moveto\n", $x, $y, $x, $y);
		} elsif($cmd eq "vmoveto") {
			$y+=$vals[0];
			$xv{$x+0}=1; $yv{$y+0}=1; 
			printf("%d %d moveto\n", $x, $y);
			printf("%d %d 5 0 360 arc %d %d moveto\n", $x, $y, $x, $y);
		} elsif($cmd eq "alineto") {
			$x=$vals[0]+0;
			$y=$vals[1]+0;
			$xv{$x+0}=1; $yv{$y+0}=1; 
			printf("%d %d lineto\n", $x, $y);
			printf("%d %d 3 0 360 arc %d %d moveto\n", $x, $y, $x, $y);
		} elsif($cmd eq "rlineto") {
			$x+=$vals[0];
			$y+=$vals[1];
			$xv{$x+0}=1; $yv{$y+0}=1; 
			printf("%d %d lineto\n", $x, $y);
			printf("%d %d 3 0 360 arc %d %d moveto\n", $x, $y, $x, $y);
		} elsif($cmd eq "hlineto") {
			$x+=$vals[0];
			$xv{$x+0}=1; $yv{$y+0}=1; 
			printf("%d %d lineto\n", $x, $y);
			printf("%d %d 3 0 360 arc %d %d moveto\n", $x, $y, $x, $y);
		} elsif($cmd eq "vlineto") {
			$y+=$vals[0];
			$xv{$x+0}=1; $yv{$y+0}=1; 
			printf("%d %d lineto\n", $x, $y);
			printf("%d %d 3 0 360 arc %d %d moveto\n", $x, $y, $x, $y);
		} elsif($cmd eq "arcurveto") {
			for $i (0,2,4) {
				$x=$vals[$i]+0;
				$y=$vals[$i+1]+0;
				printf("%d %d ", $x, $y);
			}
			$xv{$x+0}=1; $yv{$y+0}=1; 
			printf("curveto\n");
			printf("%d %d 3 0 360 arc %d %d moveto\n", $x, $y, $x, $y);
		} elsif($cmd eq "rrcurveto") {
			for $i (0,2,4) {
				$x+=$vals[$i];
				$y+=$vals[$i+1];
				printf("%d %d \n", $x, $y);
			}
			$xv{$x+0}=1; $yv{$y+0}=1; 
			printf("curveto\n");
			printf("%d %d 3 0 360 arc %d %d moveto\n", $x, $y, $x, $y);
		} elsif($cmd eq "hvcurveto") {
			$x+=$vals[0];
			printf("%d %d \n", $x, $y);
			$x+=$vals[1];
			$y+=$vals[2];
			printf("%d %d \n", $x, $y);
			$y+=$vals[3];
			printf("%d %d \n", $x, $y);
			$xv{$x+0}=1; $yv{$y+0}=1; 
			printf("curveto\n");
			printf("%d %d 3 0 360 arc %d %d moveto\n", $x, $y, $x, $y);
		} elsif($cmd eq "vhcurveto") {
			$y+=$vals[0];
			printf("%d %d \n", $x, $y);
			$x+=$vals[1];
			$y+=$vals[2];
			printf("%d %d \n", $x, $y);
			$x+=$vals[3];
			printf("%d %d \n", $x, $y);
			$xv{$x+0}=1; $yv{$y+0}=1; 
			printf("curveto\n");
			printf("%d %d 3 0 360 arc %d %d moveto\n", $x, $y, $x, $y);
		} elsif($cmd eq "closepath") {
			printf("closepath stroke newpath\n");
		}
	}

	printf("grestore } bind def\n");
	if($wantgrid) {
		printf("coordcolor\n");
		for $x (keys %xv) {
			&linevert($x);
		}
		for $y (keys %yv) {
			&linehor($y);
		}
	}
}

$pages=0;

for $arg (@ARGV) {
	undef $name, $code;

	if( $arg =~ /^\/(.*)/ ) {
		$name=$1;
	} elsif( $arg =~ /^\.(.)/ ) {
		$code=ord($1);
	} else {
		$code=$arg;
	}

	$pages++;

	$stemhgrp=0;
	$stemhused=0;
	$stemvgrp=0;
	$stemvused=0;
	$stemwd=10;
	undef %xcoord;
	undef %ycoord;

	if( defined $name ) {
		$xname = $name;
		$xcode = $frevenc{$fname}{$name};
		if( $xcode eq "" ) {
			$xcode = "**UNKNOWN**";
		}
	} else {
		$xname = $fenc{$fname}{$code};
		if( $xname eq "" ) {
			$xname = "**UNKNOWN**";
		}
		$xcode = $code;
	} 

	printf("%%%%Page: %d %d\n", $pages, $pages);
	printf("gsave

0 setlinewidth
36 72 translate

gsave
contourcolor
72 72 scale
newpath
0 0 moveto
7 0 rlineto
0 7 rlineto
-7 0 rlineto
closepath
stroke
1 1 translate
newpath
0 0 moveto
5 0 rlineto
0 5 rlineto
-5 0 rlineto
closepath
stroke
grestore

");

	undef @subrlist;


	@bbox=@{$fbbox{$fname}};

	print("coordcolor\n");
	printf("0 linehor %d linehor %d linehor\n", $bbox[1]+$yorg, $bbox[3]+$yorg);
	printf("%d linevert %d linevert\n", $bbox[0]+$xorg, $bbox[2]+$xorg);

	%vals=@{$fblues{$fname}};
	for $i (keys %vals) {
		&bluezone($i, $vals{$i});
	}

	$havechar = 1;
	if( defined $fchars{$fname}{$xname} ) {
		&drawcharwstems($fchars{$fname}{$xname});
	} else {
		$havechar = 0;
		if(defined $name) {
			printf(STDERR "WARNING: %s nas no character with name \"%s\"\n", $fname, $name);
		} else {
			printf(STDERR "WARNING: %s nas no character with code \"%s\"\n", $fname, $code);
		}
	}

	&substems($fname, @subrlist);

	printf(STDERR "glyph name:%s code:%s (%d substituted stem groups)\n", $xname, $xcode, scalar @subrlist);

	$cmpfidx = 0;
	for $cmpf(@cmpfiles) {
		undef $cname, $ccode;

		if( defined $name ) {
			if ( ! defined $fchars{$cmpf}{$name} && defined $fenc{$cmpf}{$xcode}) {
				printf(STDERR "  NOTE: %s nas no glyph with name \"%s\", guessed by code\n", $cmpf, $name);
				$cname = $fenc{$cmpf}{$xcode};
				if( $cname eq "" ) {
					$cname = "**UNKNOWN**";
				}
				$ccode = $xcode;
			} else {
				$cname = $name;
				$ccode = $frevenc{$cmpf}{$name};
				if( $ccode eq "" ) {
					$ccode = "**UNKNOWN**";
				}
			}
		} else {
			$cname = $fenc{$cmpf}{$code};
			if( $cname eq "" ) {
				$cname = "**UNKNOWN**";
			}
			$ccode = $code;
		} 

		if( defined $fchars{$cmpf}{$cname} ) {
			&drawchar("drawcmpchar", 0, sprintf("%d cmpfcolor", $cmpfidx),
				$fchars{$cmpf}{$cname});
			printf("drawcmpchar\n\n");
			printf(STDERR "  in %s glyph name:%s code:%s\n", $cmpf, $cname, $ccode);
		} else {
			if(defined $name) {
				printf(STDERR "  WARNING: %s nas no character with name \"%s\"\n", $cmpf, $name);
			} else {
				printf(STDERR "  WARNING: %s nas no character with code \"%s\"\n", $cmpf, $code);
			}
		}
		$cmpfidx++;
	}

	if($havechar) {
		printf("drawchar\n\n");
	}

	# flush the last group
	&nextstemgrp();

	# the values of coordinates
	printf("/fontsz 8 fnt2pt div def\n");
	printf("/Myfont /Courier findfont fontsz scalefont def\n\n");
	printf("contourcolor Myfont setfont\n");

	for $org (0, $xorg+$bbox[2]+$stemwd*$stemhgrp+72/$fnt2pt) {
		printf("gsave\n");
		printf("/maxx 72 fnt2pt div %d sub def /curx 0 def /lasty -10000 def\n",
				2+$stemhgrp*$stemwd-$xorg-$bbox[0]);
		printf("0 72 translate fnt2pt fnt2pt scale %f yorg translate 1 setlinewidth\n", $org);
		for $y (sort {$a <=> $b} keys %ycoord) {
			printf("(%d) getlen %d label\n", $y, $y);
		}
		printf("grestore\n");
	}

	for $org (0, $yorg+$bbox[3]+$stemwd*$stemvgrp+72/$fnt2pt) {
		printf("gsave\n");
		printf("/maxx 72 fnt2pt div %d sub def /curx 0 def /lasty -10000 def\n",
				2+$stemvgrp*$stemwd-$yorg-$bbox[1]);
		printf("72 0 translate fnt2pt fnt2pt scale xorg %f translate 90 rotate 1 setlinewidth\n", $org);
		for $x (sort {$a <=> $b} keys %xcoord) {
			printf("(%d) getlen %d label\n", $x, -$x);
		}
		printf("grestore\n");
	}

	printf("gsave 0 %d translate\n", 7.5*72 );
	printf("contourcolor /Courier findfont 12 scalefont setfont\n");
	$line = 0;

	$cmpfidx = $#cmpfiles;
	if( $cmpfidx > (2.5*72/15)-4 ) {
		$cmpfidx = (2.5*72/15)-4;
	}
	for(; $cmpfidx>=0; $cmpfidx--) {
		$cmpf = $cmpfiles[$cmpfidx];
		printf("%d cmpfcolor\n", $cmpfidx);
		printf("newpath 20 %d moveto 0 10 rlineto 10 0 rlineto 0 -10 rlineto closepath fill\n", 
			15*$line, $cmpf);
		printf("contourcolor 40 %d moveto (%s %s) show\n", 15*$line, $cmpf, $fontname{$cmpf});
		$line++;
	}
	if( $#cmpfiles >=0 ) {
		printf("0 %d moveto (Comparison files:) show\n", 15*$line++);
	}
	printf("0 %d moveto (code: %d  name: %s) show\n", 15*$line++, $xcode, $xname);
	printf("0 %d moveto (%s) show\n", 15*$line++, $fname);
	printf("0 %d moveto (%s) show\n", 15*$line++, $fontname{$fname});
	printf("grestore\n\n");

	printf("showpage grestore\n\n");
}
printf("%%%%Pages: %d\n", $pages);
