#!/usr/bin/perl
#
# t1embed: Embed Type 1 font in a PostScript file that calls for 
# non-standard fonts but does not supply them.
#
# IMPORTANT NOTE: This script relies on the use of special comments which 
# are only embedded by type1inst.  This is NOT a general font embedding
# script!
#

@standard_fonts = ("Times-Roman", "Helvetica");

# Start of script proper

$numargs = @ARGV;

if ($numargs < 1) {
    die("Usage : $0 PSfile1 [PSfile2 PSfile3 ....]\n");
}

foreach $filename (@ARGV) {
    print "file : $filename\n";
    open(IN, $filename) || die("Can't open \"$filename\"\n");
    @toembed = ();
    while (<IN>) {
	if (/^%\s+t1embed\s+:\s+(\S+)\s+(\S+)\s*$/) {
	    @suppliedfonts = (@suppliedfonts, "/$2");
	    @toembed = (@toembed, $1);
	}
    }
    close(IN);
    
    $numtoembed = @toembed;
    
    if ($numtoembed == 0) {
	print "No fonts to embed\n";
	next;
    }
    
    foreach $i (@toembed) {
	print "Embed $i\n";
    }
    
    open(OUT, ">foo") || die("Can't open temporary file \"foo\"\n");
    open(IN, $filename) || die("Can't open $filename\n");
    while (<IN>) {
	if (/%%EndComments/) {
	    print OUT "%%DocumentSuppliedResources font @suppliedfonts\n";
	    print OUT;
	    foreach $fname (@toembed) {
		print "$fname\n";
		$fontname = shift(@suppliedfonts);
		print OUT "%%BeginResource: font $fontname\n";
		if ($fname =~ /\.pfb$/) {
		    open(F, "pfbtops $fname |") || die("Can't run pfbtops on $fname\n");
		} else {
		    open(F, $fname) || die("Can't open $fname\n");
		}
		while (<F>) {
		    print OUT;
		}
		close(F);
		print OUT "%%EndResource\n";
	    }
	} else {
	    print OUT;
	}
    }
    close(IN);
    close(OUT);
    
    system("mv foo $filename");
}
