## This file helps create a valid MetaFont file from piecemeal MF input
## I'm thinking mainly of files that are output by TTF2MF, each of which
## has a different selection of glyphs.
## 

$true=1; $false=0;

## Begin by reading mkr2.etx and extracting from it the valid glyphs
## and their associated positions.

open (ETXIN, "../mkr2.etx") || die "Where the heck is mkr2.etx?";

## Initializations...
$position=0;
foreach $1 (0..255) {$slottochar[$1]="";}

while ($_=<ETXIN>) {
    next unless /\\nextslot|\\setslot/;
    if (/nextslot/) {
	/nextslot\{(\d+)\}/;
	$position=$1;
    }
    if (/setslot\{([a-z]+)\}/) {
	$currglyph=$1;
    }
    $slottochar[$position]=$currglyph;
    $chartoslot{$currglyph}=$position;
    $position++;
}
close ETXIN;

## USAGE: Perl ../mf2mkr.pl mfout mfin1 mfin2 ...
## Run this script from a working directory below the directory which
## contains the script.

die "Gimme more parameters for files and such..."
    unless $#ARGV>0;

open (OUT, ">$ARGV[0]");
foreach $i (1..$#ARGV) {
    open (MAP, "../$ARGV[$i].map") || 
	die "I am missing the map file for $ARGV[$i] ($i)...";
    ## lines in map file are like <slotnum> <charname>
    foreach $i (0..255) {$mapslottochar[$i]="";} # initialize
    while (<MAP>) { # read local map file
	($mapcurrslot, $mapcurrchar)=split /\s/;
	$mapslottochar[$mapcurrslot]=$mapcurrchar;
    };
    close MAP;
    $newchar=$false; $goodchar=$false;
    open (IN, "../$ARGV[$i].mf");
	while (<IN>) {
	    $newchar=$true if /beginchar/;
	    if ($newchar) {
		$newchar=$false;
		/beginchar\((\d+)\,/; 
		$thisslot=$1; 
		$remainder=$';
		$thischar=$mapslottochar[$thisslot];
		if ($thischar ne "") {
		    $goodchar=$true;
		    $mkrslot=$chartoslot{$thischar};
                  $_="beginchar($mkrslot,$remainder";
              }
		chomp;
		$_.=" % $thischar\n";
	    }
	    $_.="\n" if /endchar/;
	    if ($goodchar) {
		print OUT;
		$goodchar=$false if /endchar/;
	    }
	}
	close IN;
}

