#! /bin/sh
# sdeltmap - map one element type to another
# USAGE:
#	sdeltmap [-iINPUT] [-oOUTPUT] oldElt newElt <old.sd >new.sd
# AUTHOR:
#	Tom Stockfisch

trap '/bin/rm -f /tmp/awk.$$; exit' 0 1 2 3 15

cat <<\EOF >/tmp/awk.$$
BEGIN {
	initHandy()
	getopt()
	#traceStates=TRUE
	newState("header");
}

state == "header" {
	print >output
	getline	# comment
	print >output
	getline # comment
	print >output
	getline # counts
	nat =	substr( $0, 1, 3 )
	print >output
	newState("coord")
	next
}

state == "coord" && $1 == "$$$$" {
	fatal("missing coordinates")
}

state == "coord" {
	printf( "%s", substr( $0, 1, 31 ) ) >output
	elt =	substr( $0, 32, 2 )
	if (elt == oldElt)
		elt =	newElt
	printf( "%s%s\n", elt, substr( $0, 34 ) ) >output
	if (--nat == 0)
		newState("none")
	next
}

state == "none" && $1 == "$$$$" {
	print >output
	newState("header")
	next
}

state == "none" {print >output}

END {
	if (errorOccurred)
		exit(1)
}

function initHandy()
{
	TRUE =	1
	stderr =	"cat 1>&2"
	FLOATPAT =	"([-+]?[0-9.]+([eEdD][-+]?[0-9]+)?)"
	PI =		3.141592653589793238462643383276
}

function getopt(     progNamePath, i, nInputFile )
{
	argv[0] =	progNamePath[ split( ARGV[1], progNamePath, "/" ) ]
	for ( i = 2; i < ARGC; ++i )
	{
		if (ARGV[i] ~ /^[-][a-zA-Z]/)
		{
			if (ARGV[i] ~ /^[-]i/)
				input = \
				ARGV[i] =	substr(ARGV[i], 3)
			else if (ARGV[i] ~ /^[-]o/)
			{
				output =	substr(ARGV[i], 3)
				ARGV[i] =	""
			} else
				usage("unknown option `"  ARGV[i]  "'")
		} else if (ARGV[i] ~ /[=]/)
			fatal("file name `"  ARGV[i]  "' contains equals sign")
		else
		{
			arg[++narg] =	ARGV[i]
			ARGV[i] =	""
		}
	}
	ARGV[1] =	input ? "" : "-"
	if (narg != 2)
		usage()
	oldElt =	sprintf( "%-2s", arg[1] )
	newElt =	sprintf( "%-2s", arg[2] )
}

function usage(diagnostic)
{
	if (diagnostic)
		print	diagnostic | stderr
	printf( "usage: %s [-iINPUT] [-oOUTPUT] oldElt new <old.sd >new.sd\n",
		argv[0] ) | stderr
	errorOccurred =	TRUE
	exit(1)
}

function warn(s)
{
	printf( "%s: (file `%s', line %d) WARNING: %s\n",
		argv[0], FILENAME, FNR, s ) | stderr
}

function warnOnce( class, s )
{
	if (!warnOnce__class[class])
	{
		warn(s ? s : class)
		warnOnce__class[class] =	TRUE
	}
}

function fatal(s)
{
	printf( "%s: (file `%s', line %d) %s\n",
		argv[0], FILENAME, FNR, s ) | stderr
	errorOccurred =	TRUE
	exit(1)
}

function newState(s)
{
	state =	s
	if (traceStates)
	{
		if (NR > 0)
			print	"new state: ", s, "on `"  $0  "'" | stderr
		else
			print	"new state: ", s | stderr
	}
}

function assert(x)
{
	if (x)
		return	1
	else
		fatal("assertion failed")
}
# (derived from awk.skel14)
EOF

nawk -f /tmp/awk.$$ $0 $@
