#!/usr/bin/perl
# 
#  Copyright (c) 1998
#   Sergey A. Babkin.  All rights reserved.
# 
#  Redistribution and use in source and binary forms, with or without
#  modification, are permitted provided that the following conditions
#  are met:
#  1. Redistributions of source code must retain the above copyright
#     notice, this list of conditions and the following disclaimer.
#  2. Redistributions in binary form must reproduce the above copyright
#     notice, this list of conditions and the following disclaimer in the
#     documentation and/or other materials provided with the distribution.
# 
#  THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
#  WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
#  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
# 
#  Sergey A. Babkin (sab123@hotmail.com, babkin@bellatlantic.net)
# 

#
# Script to transcode the Type1 disassembled font to other encoding
#

if($#ARGV != 1) {
	printf(STDERR "Use: trans src-table dst-table <src-font >dst-font\n");
	exit 1;
}

# tables are formatted in two columns, one row per character
# name decimal-code

# Read the destination table

open(FILE,"<".$ARGV[1])
	or die "Unable to read $ARGV[2]\n";
while(<FILE>) {
	@sl=split(/\s+/);
	$dst{$sl[0]}=$sl[1];
}
close(FILE);

#read the destination table and build the translation table

open(FILE,"<".$ARGV[0])
	or die "Unable to read $ARGV[0]\n";
while(<FILE>) {
	@sl=split(/\s+/);
	$trans{$sl[1]}=$dst{$sl[0]};
}
close(FILE);

# now read the font file, skip everything upto the encoding table
# we suppose that the file was autogenerated by ttf2pt1 with my patches

while(<STDIN>) {
	print $_;
	if(/^\/Encoding/) {
		last;
	}
}

# read the old encoding table and build the new encoding table

while($row=<STDIN>) {
	if( $row !~  /^dup/) {
		last;
	}

	@sl=split(/\s+/,$row);

	$new=$trans{$sl[1]};
	if($new eq "") {
		$new=$sl[1];
		if($enc{$new} eq "") {
			$enc{$new}=$sl[2];
		}
	} else {
		$enc{$new}=$sl[2];
	}
}

# print new encoding table

for $i (0..255) {
	if($enc{$i}) {
		printf("dup %d %s put\n",$i,$enc{$i});
	} else {
		printf("dup %d /.notdef put\n",$i);
	}
}

print $row;

# now copy the rest of file

while(<STDIN>) {
	print;
}
