#This script is invoked from lib/libaubit4gl/Makefile
#It creates lib/generated/tmperrs.h file used by lib/libaubit4gl/error.c
#WARNIG: errno renamed to a4gl_errno because of the conflict in errno.h
#exitwith renamed to A4GL_exitwith - do we need to change it here?

#Get settings
. ../../etc/aubitrc

#Why not use find here?
#a="*.c ../libsql/odbc/*.c ../libsql/esqlc/*.ec ../libsql/nosql/nosql.c"
#b="../libform/form_xdr/*.c ../libui/ui_gtk/*.c ../libmenu/menu_xdr/*.c ../libmsg/msg_native/*.c"
#c="../libpdf/*.c ../librpc/sun_rpc/*.c ../librpc/xml_rpc/*.c ../libui/ui_console/*.c ../libui/ui_curses/*.c"
#SOURCES="$a $b $c"

if test "$COMSPEC" != ""; then 
	SOURCES_X=`/bin/find ../.. -name "*.c"`
	SOURCES_EC=`/bin/find ../.. -name "*.ec"`
	SORT=/usr/bin/sort
else
	SOURCES_X=`find ../.. -name "*.c"`
	SOURCES_EC=`find ../.. -name "*.ec"`
	SORT=sort 
fi

SOURCES=""

rm -f efile
for a in $SOURCES_X $SOURCES_EC
do
	if [ -r $a ]
	then
		#SOURCES="$SOURCES $a"
		grep "exitwith" $a >> efile
	fi
done

cp mkerrors2.out current_errs

$AWK '
BEGIN {
errcnt=1;
FS="|"
inerrs="current_errs"
while (getline < inerrs) {
if($0=="") break;
a4gl_errno=$1
if (a4gl_errno>errcnt) errcnt=a4gl_errno+1
errmsg=$2
errors[errmsg]=a4gl_errno
}

FS=" "
close(inerrs)
}

/IGNOREEXITWITH/ {next}
/exitwith\(char/ {next}
/exitwith_sql\(char/  {next}
/exitwith_sql_odbc\(char/  {next}
/exitwith_sql_odbc_errm\(char/  {next}
/define exitwith exitwith_sql/  {next}
/define IGNOREEXITWITH/   {next}
/exitwith2/ {next}
/local_exitwith/ {next}
/exitwith/ {
gsub("exitwith\\(","exitwith (")
gsub("exitwith_sql\\(","exitwith_sql (")
gsub("exitwith_sql_odbc_errm\\(","exitwith_sql_odbc_errm (")
if (NF==1) {
	old=$0
	getline
	$0=old $0
}

gsub("\\\\\"","\"")
b=substr($0,index($0,":")-1)
a=substr($0,index($0,"exitwith")+9)
a=substr(a,index(a,"\"")+1)
a=substr(a,1,index(a,"\"")-1)

if (errors[a]=="") {
		if (a=="\"\"") {
			print "INTERNAL ERROR : variable (a) is blank in " FILENAME
			print $0
			exit 
		}
		errcnt++;
		errors[a]=errcnt
}
}
END {
	for (a in errors) {
		printf("%s|%s\n",errors[a],a);
	}
}
' efile  | $SORT -n > mkerrors2.out


