#!/bin/sh
#srcs="circ.h"
#structs="brush_s=brush circ_s=circ"
#module="structs"
srcs="$1"
structs="$2"
module="$3"
includes="$4"

# parse source files and concat trees
parse()
{
	for n in $*
	do
		treecc -I../common $n
#		cat $n.TREE
#		rm $n.TREE $n.E
	done
}

struct_extract='
	BEGIN {
		split(names, A, " ")
		for(n in A) {
			struct = A[n]
			name = A[n]
			sub("[=].*$", "", struct)
			sub("^[^=]*[=]", "", name)
			STRUCT[struct]++
			NAME[struct] = name
		}
	}
'

# extract struct fields in text format of all structs named in $1
extract_struct()
{
	scr='
		# calculate indentation level
		{
			level = $0
			sub("[^ ].*$", "", level)
			level = length(level)
		 }

		# we are in the struct
		(struct_level != "") {
			# indentation is back to starting level, struct is closed 
			if (level <= struct_level)
				struct_level = ""
			else if ($1 == "TYPENAME")
				type = $2;
			else if ($1 == "ID") {
				idx = struct SUBSEP name SUBSEP $2
				if (!(idx in SEEN)) {
					print struct " " name " " type " " $2
					SEEN[idx]=1
				}
			}
		}

		# check for our struct and remember indentation level
		/^ *STRUCT/ {
			if ($2 in STRUCT) {
				struct_level = level
				struct = $2
				name = NAME[$2]
			}
			next
		}
	'
	awk -v "names=$1" "$struct_extract $scr"
}

# generate sphash from flattened struct
gen_sphash()
{
	awk '{ print $2 "." $4 }'
}

# generate setter c code from flattened struct
# $1 is structs list, $2 and $3 are c and h names, $4 is module name, $5 is includes
gen_c()
{
	scr='
		BEGIN {
			q = "\""
			print "#include <stdlib.h>" > cf
			print "#include <stdio.h>" > cf
			print includes > cf
			print "#include " q hf q > cf
			for(n in STRUCT)
				parm=parm ", struct " n " *" NAME[n]
			print "int " module "_setfield(char *field, char *value" parm ")" >cf
			print "{" > cf
			print "	" module "_keys_t f;" > cf
			print "	f = structs_sphash(field);" > cf
			print "	switch(f) {" > cf

			print "#include " q module "_sph.h" q > hf
			print "int " module "_setfield(char *field, char *value" parm ");" >hf
			print "" > hf
			print "/* called provided conversion functions: */" > hf
		}
		
		function fillup(s) {
			return sprintf("%-40s", s)
		}
		
		{
			print "		case " fillup(module "_" $2 "_" $4 ":") $2 "->" $4 " = field_conv_" $3 "(field, value, f); break;" > cf
			if (!($3 in CONV)) {
				print $3 " field_conv_" $3 "(char *field, char *value, " module "_keys_t f);" > hf
				CONV[$3]++
			}
		}
		
		END {
			print "		case " fillup(module "_SPHASH_INVALID:") "return -1;" > cf
			print "	}" > cf
			print "}" > cf
		}
	'
	awk -v "names=$1" -v "cf=$2" -v "hf=$3" -v "module=$4" -v "includes=$5" "$struct_extract $scr"
}

parse $srcs | extract_struct "$structs" > A

gen_sphash < A > $module.fields
sphash -p $module -o ${module}_sph < $module.fields

gen_c "$structs" "$module.c" "$module.h" "$module" "$includes" < A
