#!/usr/bin/perl

# quick script to generate the seer ExtSym routines from the given
# header files. For development use only. If I can get Seer to work
# with a table of function pointers and a single AddExtSym routine
# this script is going the way of the dodo.

open(OUTFILE, ">bastard_seer.h");
open(HFILE, ">seer.bastard.h");
print HFILE "#include clib\n#include bastard_def\n\n";
print OUTFILE "int InitSeerSymbols(){\n"; 

print HFILE "/* The _t naming is used to differentiate from Seer ";
print HFILE "internal names */\n";
open(INFILE, "bdb.h");
foreach (<INFILE>) {
	if ( ! /^.define/  && ! /^\/\*/ && /^\s*\S+/) { 
		s/long /int /g;
		s/const / /g;
		s/\/\/.+$//g;
		s/\/\*.+$//g;
		if ( /struct +([A-z_]+)/ ){
			print HFILE "struct $1_t {\n";
		} else {
			print HFILE $_; 
		}
	}
}
close(INFILE);

open(INFILE, "api.h");
foreach (<INFILE>) {
	s/^\s*//g;
	if ( /^\S+ (\S+)\(.*\).*/ ) {
		print OUTFILE "\tscAddExtSym($1);\n";
		s/long /int /g;
		s/const / /g;
		s/FILE /int /g;
		s/, *...\)/)/;
		s/\/\/.+$//g;
		s/\/\*.+$//g;
		s/([A-z_]+)\[[0-9]+\]/*$1/g ; #strip array brackets (char buf[43]);
		s/[A-z_]+ ?([,\)])/$1/g; #strip param names; keep types
		s/struct +([A-z_]+)/$1_t/g;
		print HFILE "import $_";
	} elsif ( /^struct (\S+ \*) (\S+)\(.*\).*/ ){
		#redundant, but this is only a quick hack to do structs
		print OUTFILE "\tscAddExtSym($2);\n";
		s/long /int /g;	# change type long to type int
		s/const / /g;		# strip keyword const
		s/FILE /int /g;   # change type FILE to type int
		s/, *...\)/)/; 	# strip var_args
		s/\/\/.+$//g;		# strip C++ comments
		s/\/\*.+$//g;		# strip C comments
		s/[A-z_]+ ?([,\)])/$1/g; #strip param names; keep types
		s/([A-z_]+)\[[0-9]+\]/*$1/g ; #strip array brackets (char buf[43]);
		s/struct +([A-z_]+)/$1_t/g; #turns structs to SeerC types
		if ( /(\S+) (\S+.+)$/ ) {
			print HFILE "import $1 $2\n";
		}
		#print HFILE "import $_";
	}
	
}
close(INFILE);
close (HFILE);

open(INFILE, "seer.clib.h");
print OUTFILE	"\t/* Export C Routines */\n";
foreach (<INFILE>) {
	s/^\s*//g;
	if ( /^import.* (\S+)\(.*\)/ ) {
		print OUTFILE "\tscAddExtSym($1);\n";
	}
}
close(INFILE);

open(INFILE, "seer.b_def.h");
print OUTFILE "\t/* Export Global Data */\n"; 
foreach (<INFILE>) {
	s/^\s*//g;
	if ( /^import\s+\S+\s+(\S+);/ ) {
		print OUTFILE "\tscAddExtSym($1);\n";
	}
}
close(INFILE);

print OUTFILE "return(0);\n}\n";
close(OUTFILE);
	
exit;
