#!/usr/bin/perl -w

#- This file is part of the "JNI for Coin" project.
#- Copyright (C) 2002-2005 Systems in Motion. All rights reserved
#-
#- This program is free software; you can redistribute it and/or modify
#- it under the terms of the GNU General Public License as published by
#- the Free Software Foundation; either version 2, or (at your option)
#- any later version.
#-
#- This program is distributed in the hope that it will be useful,
#- but WITHOUT ANY WARRANTY; without even the implied warranty of
#- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#- GNU General Public License for more details.
#-
#- You should have received a copy of the GNU General Public License
#- along with this program; if not, write to the Free Software
#- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

##################
#
# prep.pl
# Preprocess C++ header files
#
# 2002-05-21 Morten Vold
#
##################

my $strip = 0;
my $striptarget = "";
my $destdir = "prep";
my $self = __FILE__;
my @names;

my $preprocessor = "cpp"; # use gcc

# Check arguments
for (@ARGV) {
    /^--strip=(.*)$/ && do { $strip=1; $striptarget=$1; next };
    /^--cpp=(.*)$/ && do { $preprocessor=$1; next };
    /^--destdir=(.*)$/ && do { $destdir=$1; next };
    /^--help/ && do { usage(); exit 0 };
    # Other arguments are considered names of files to preprocess
    push @names, $_;
}

$compiler = $preprocessor;
$compiler =~ s/ -E//;
$compiler =~ s/ \/E//;
$compiler =~ s/ -C//;
$compiler =~ s/ \/C//;

if ( $preprocessor =~ /^[^ ]*wrapmsvc/ ) {
  $preprocessor .= " /C";
  $chop = 1;
} else {
  $preprocessor .= " -C";
  $chop = 0;
}

sub preprocess
{
    my $infile = shift;

    if (! -f $infile) {
	print STDERR "prep.pl: No such file '$infile'\n";
	return;
    }
    my $outfile = "$destdir/$infile";
    my $dir = "";
    my @elements = split(/\//, $outfile);
    $#elements--;
    foreach (@elements) {
	$dir .= "$_/";
	mkdir($dir);
    }
    `$preprocessor -I. -DCOIN_DLL -D__cplusplus $infile | $self --strip=$infile --cpp="$preprocessor" > $outfile`;
}

sub usage
{
    print STDERR "prep.pl
Copyright (C) 2002-2005 Systems in Motion AS.
This is free software and may be redistributed under the terms of the GNU GPL.

Preprocess header files as part of the \"JNI for Coin\" project.

usage:
  prep.pl [OPTION]... [FILE]...

  Where [FILE]... are the files to preprocess.

options:
  --help                - print this help message.
  --cpp=<preprocessor>  - set preprocessor command.
  --destdir=<dir>       - specifies where to put the output files.
                          The default is \"prep\" in the current
                          working directory.
  --strip=<file>        - expect cpp output on stdin, and strip 
                          everything but the parts belonging to 
                          <file>.

If no options are given, prep.pl expects the list of files to 
preprocess on the standard input (each filename separated by 
a newline).
";

}

# If we are not stripping, preprocess
if (!$strip) {
    print STDERR "prep.pl: Outputting files to $destdir/\n";
    if ($#names == -1) {
	# Take names of files to preprocess from stdin
	while (<STDIN>) {
	    chomp;
	    preprocess($_);
	}
    } else {
	# Take names of files to preprocess from command line
	for (@names) {
	    preprocess($_);
	}
    }
} 
else { 
    my $match = 0;
    # Strip everything but the target file from the preprocessor output
    while (<STDIN>) {
	if (/^\#(line)? [0-9]+ "(.*)"/ ) {
	    my $sourcefile = $2;
	    $sourcefile =~ s%\\\\%/%g;
	    $sourcefile =~ s%^\./%%g;
	    # print STDERR "file: $sourcefile && $striptarget\n";
            my $oldmatch = $match;
            # $sourcefile =~ s,^\.\\\\,,;
	    $match = ($sourcefile eq $striptarget);
            if ( $oldmatch && !$match ) {
              print "#include <$sourcefile>\n";
            }
	} elsif ($match) {
            if ( $chop ) {
              chop;
            }
            chop;
            $_ =~ s/;(.)/;\n$1/g;
            $_ =~ s/^[ ]*(public|protected|private):(.)/$1:\n$2/g;
            # cxxwrap doesn't grok declspec
            $_ =~ s/\s__declspec\(.*\)\s/ /g;
            my $line = $_;

            if ( $_ =~ m/=.* ([A-Za-z0-9_]+::[A-Z][A-Z0-9_]*)/ ) {
                my $token = $1;
                # must compile test executable to find real value instead
                # of symbolic reference because the reference doesn't
                # translate into Java... (hard to do it any other way)
                my $value = 1;
                open( FILE, ">enumdump.cpp" )
                    || die "error creating dummy file\n";
		print FILE "#include <stdio.h>\n";
		print FILE "#include <" . $striptarget . ">\n";
		print FILE "\n";
		print FILE "int main(int argc, char ** argv) {\n";
		print FILE "  printf(\"%i\", " . $token . ");\n";
		print FILE "  return 0;\n";
		print FILE "}\n";
                close( FILE );
                # FIXME: make this portable
                my $command =
                    "$compiler -I. -DCOIN_DLL -o enumdump.exe " .
                    "enumdump.cpp >enumdump.txt 2>&1";
                # print STDERR $command . "\n";
                system($command);
                open(EXE, "./enumdump.exe |")
                    || die "error executing dummy program";
                $value = <EXE>;
                close(EXE);
                system("rm enumdump.*");

                print STDERR "> symbolic enum value conversion: " .
                             $token . " => " . $value . "\n";
                $line =~ s/$token/$value/g;
            }
	    print $line . "\n";
	}
    }
}
