#!/usr/bin/perl
#
# nh2ps_opt 2.0
# - nh2ps hangul, hanja font optimizer
#
# CHOI Junho(junker@jazz.snu.ac.kr)
# Narae, CS Dept., SNU
# 
# $Id: nh2ps_opt,v 2.1 1998/10/20 11:19:17 junker Exp $
#
# This program is originally from nhppf Netscape print filter
#

# argument processing
if ($ARGV[0] =~ /^(-h$|-help|--help)/){
    if ($ENV{'LANG'} =~ /^(ko|ko_KR|korean|ko_KR.euc)/){
	print STDERR "nh2ps_opt - nh2psƮ ȭ \n\n";
        print STDERR "  nh2ps-2.x HLaTeXƮ  Բ ؾ մϴ\n";
        print STDERR "  2.1 PSƮ ʹ ȣȯ ʽϴ\n";
	print STDERR "  ) nh2ps aa.txt | nh2ps_opt | lpr\n";
    }else{
	print STDERR "nh2ps_opt - nh2ps hangul font optimizing filter\n\n";
        print STDERR "  It should be used with nh2ps-2.x HLaTeX font mode\n";
	print STDERR "  It is not compatible with PS font mode in nh2ps 2.1 and above\n";
	print STDERR "  e.g) nh2ps aa.txt | nh2ps_opt | lpr\n";
    }
    exit 0;
}

# Phase 1 - get font loading information
#
# clear up font loading list
#
%fontusage_list=(
	"A", 0, "B", 0, "C", 0, "D", 0, "E", 0,
	"F", 0, "G", 0, "H", 0, "I", 0, "J", 0,
	
	"04", 0, "05", 0, "06", 0, "07", 0,
	
	"10", 0, "11", 0, "12", 0, "13", 0, "14", 0,
	"15", 0, "16", 0, "17", 0, "18", 0, "19", 0,
	"20", 0, "21", 0, "22", 0, "23", 0, "24", 0,
	"25", 0, "26", 0, "27", 0, "28", 0, "29", 0
);

while(<>){
    $line=$_;
    # translate chars
    if (/^(nhf)([0-9A-J]+) setfont/){
	#print STDERR "get font - $2\n";
        $fontusage_list{$2}++;
    }

    push(@pass1, $line);
}

# check key usage - only for debugging purpose
#foreach $v (keys(%fontusage_list)){
#	print STDERR "Key[$v] Value[$fontusage_list{$v}]\n";
#}

@pass2=reverse(@pass1);

# pass 2
#
# don't print unnecessary font loading commands
#
$fontdef="";

while($_=pop(@pass2)){
# check font definition and print other things
    if (/^\/(nhf)([0-9A-J]+)/){
	if ($fontusage_list{$2}>0){
          print $fontdef;
          #print STDERR "get definition - $fontdef\n";
          print $_;
        }
    }elsif (/^\/(hangul|hanja|symbol)/){
        $fontdef=$_;
        #print STDERR "fontdef - $fontdef\n";
    }else{  
        print $_;
    }
}
