#!/bin/gawk -f
#
# Generates code for reading forms settings and storing them into
# a class's fields.
#

BEGIN {
	# are we generating set-option or get-option code?
	if (ARGC > 2 && ARGV[2] == "set") 
		set = 1;
	ARGV[2] = "";

	for (i = 3; i <= ARGC; i++)
	{
		flags = flags " " ARGV[i];
		ARGV[i] = "";
	}

	subf = "";	# subfield of class that the option variables are in.
	cast = "";	# cast of integer control value to an enum...

	if (ENVIRON["CPP"] != "")
		extcmd = "$CPP -P " flags " " ARGV[1];
	else
		extcmd = "cpp -P " flags " " ARGV[1];
	ARGV[1] = "";

# Read in the fd+ extensions file. This contains menu definitions etc.

	while ((extcmd | getline line) > 0)
	{
		$0 = line;

	flf = "";	# function-specifier
	tail = "";	# tail-sequence, e.g., + 1

	# set option & control names
	optName = $2;
	if ($3 == "") 
		ctrlName = $2;
	else
		ctrlName = $3;

	# parse command in $1

	if ($1 == "m" || $1 == "c")
	{
		current_menu = ctrlName;	# start of a menu
		mn = 0; 
	}

	if ($1 == "subfield")
		subf = $2 ".";

	else if ($1 == "getfunc" && !set)
	{
		doGet = 1;
		print "Void " $2 "()\n{";
	}
	else if ($1 == "setfunc" && set)
	{
		doSet = 1;
		print "Void " $2 "()\n{";
	}

	else if ($1 == "cast")
		cast = "(" $2 ") ";
	else if ($1 == "nocast")
		cast = "";
	
	else if ($1 == "b")
		flf = "button";
	 else if ($1 == "s")
		flf = "slider_value";
	else if ($1 == "c")
		flf = "choice";
	else if ($1 == "cz")
	{
		flf = "choice";
		if (set)
			tail = " + 1";
		else
			tail = " - 1";
	}
	else if ($1 == "i")
		mn++;
	else if ($1 == "ib")
	{
		mn++;
		if (current_menu != "")
		{
			flf = "menu_item_check";
			ctrlName = current_menu ", " mn;
		}
	}
	
	if (flf != "")
		if (doSet)
			printf("    fl_set_%s(%s, %s%s%s);\n", flf, ctrlName,
				subf, optName, tail);
#			print "    fl_set_" flf "(" ctrlName ", " subf $2 tail ");"
		else if (doGet)
		{
			if (cast != "" && tail != "")
				printf("    %s%s = %s(fl_get_%s(%s)%s);\n", subf, optName,
					cast, flf, ctrlName, tail);
			else
				printf("    %s%s = %sfl_get_%s(%s)%s;\n", subf, optName,
					cast, flf, ctrlName, tail);
		}

}
	print "}\n";
}
