#!/usr/bin/perl -w
use strict;

foreach my $file(@ARGV)
{
    unless (-e $file)
    {
	print "$file not found\n";
	next;
    }
    my @emb = ();
    my @fonts = `pdffonts $file`;
    print "\n*** Looking at $file:\n\n", @fonts, "\n";
    shift(@fonts); shift(@fonts);
    foreach my $font(@fonts)
    {
	chomp($font); $font =~ s/\s\s+/,/g;
	while ($font =~ s/([\s,])yes /$1yes,/){}
	my @columns = split(/,/, $font);
	if ($columns[1] ne 'Type 1')
	{
	    print STDERR '*'x50, "\n\n";
	    print STDERR "* Font $columns[0] is $columns[1] in $file.\n";
	    print STDERR '*'x50, "\n\n";
	}
	if ($columns[2] ne 'yes')
	{
	    print STDERR "      *** Font $columns[0] is not embedded in $file.\n";
	    push(@emb, $columns[0]);
	}
    }
    if (@emb)
    {
	my $destination = $file;
	$destination =~ s/\.pdf$/\-emb\.pdf/;
	print STDERR "      *** Attempting to embed ".join(', ', @emb)." in $destination\n\n";
	my @conversion = `gs -dSAFER -dNOPLATFONTS -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sPAPERSIZE=letter -dCompatibilityLevel=1.4 -dPDFSETTINGS=/printer -dCompatibilityLevel=1.4 -dMaxSubsetPct=100 -dSubsetFonts=true -dEmbedAllFonts=true -sOutputFile=$destination -f $file`;
	print @conversion, "\n";
    }
    else
    {
	print STDERR "      *** All fonts are already embedded in $file.\n";
    }
}
print STDERR "Done.\n";
