# This file is part of Mailfromd.
# Copyright (C) 2007-2025 Sergey Poznyakoff
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

BEGIN {
	header[nh++] = "-*- buffer-read-only: t -*- vi: set ro:"
	header[nh++] = "THIS FILE IS GENERATED AUTOMATICALLY.  PLEASE DO NOT EDIT."
}

function pline(f,n)
{
	print "#line " n " \"" f "\""
}

function iterate(array, var, expr,      x, s)
{
	for (x in array) {
		if (array[x] != "NULL") {
                   s = gensub(("%" var), array[x], "g", expr);
		   print s
		}
	}
}

state == 0 && /^[ \t]*#/ { next }
state == 0 && /^TEMPLATE/ {
	START = NR-1
	state = 1; 
	if (NF > 1) {
		if (NF == 2) {
			for (i = 0; i < nh; i++)
				print $2 " " header[i]
		} else {
			for (i = 0; i < nh; i++)
				print $2 " " header[i] " " $3
		}
	}
	pline(ARGV[2], 2)
	next 
}
	
state == 0 && NF >= 1 {
	line[opcode+0] = NR
	opname[opcode++] = $1
	if (NF > 2) {
		opdump[$1] = $2;
		if (NF >= 3) 
			nwords[$1] = $3
	}
	next
}

state == 1 {
	if (match($0, "%{(.*)%}", a)) {
		for (i = 0; i < opcode; i++) {
			s = gensub("%NAME", opname[i], "g", a[1]);
			s = gensub("%CODE", i, "g", s)
			s = gensub("%DUMP",
				   opdump[opname[i]] ? opdump[opname[i]] \
				                       : "NULL",
				   "g", s)
			s = gensub("%name",
				   tolower(opname[i]),
				   "g", s)
			s = gensub("%NWORDS",
				   nwords[opname[i]] ? nwords[opname[i]] \
				                       : "0",
				   "g", s)
			pline(ARGV[1], line[i+0])
			print s 
		}
		pline(ARGV[2], NR-START+1)
	} else if (match($0, "%\\[([a-zA-Z][a-zA-Z]*)\\]\\[([a-zA-Z][a-zA-Z]*)\\]{(.*)%}", a)) {
		if (a[1] == "DUMP")
		   iterate(opdump, a[2], a[3])
		else if (a[1] == "NAME")
		   iterate(opname, a[2], a[3])
		else {
		   print NR ": unknown iterator " a[1] > "/dev/stderr";
		   exit 1
		}
	} else
		print
}
	
