#!/usr/bin/perl

$fn=shift;

print "#include \"$fn\"\n#include <stdlib.h>\n\n";

open IN, $fn;
$fn=~s/\..*?$//;
$fn=$1 if ($fn=~/\/([^\/]+)$/);
$pre=$fn;
while (<IN>) {
    if (/^JNIEXPORT ([a-z]+) JNICALL ([a-zA-Z0-9_]+)/) {
	$ret=$1; $fn=$2;
	$a=<IN>;
	if ($a=~/\((JNIEnv.*)\)/) {
	    $par=$1;
	    @p=split /,/,$par; $i=0; undef @pc;
	    foreach (@p) { $_.=" par$i"; push @pc, "par$i"; $i++; }
	    $parn=join ',',@p;
	    $parc=join ', ',@pc;
	    $rc = ($ret eq 'void')?'':'return ';
	    print "typedef $ret(*c_${fn}_t)($par);\nc_${fn}_t Call_$fn;\n";
	    print "JNIEXPORT $ret JNICALL $fn\n  ($parn) {\n    $rc Call_$fn($parc);\n  }\n\n";
	    push @fnl, $fn;
	}
    }
}

print "void Setup_$pre(void **ptrs) {\n";
$i=0;
foreach (@fnl) { print "Call_$_ = (c_${_}_t) ptrs[$i];\n"; $i++; }
print "}\n\n";

$i=0;
print "void **GetRef_$pre() {
  void **ptrs = (void**) malloc(sizeof(void*) * ( $#fnl + 2 ) );
";
foreach (@fnl) { print "ptrs[$i] = (void*) Call_$_;\n"; $i++; }
print "ptrs[$i] = (void*) 0;\nreturn ptrs;\n}\n";

