#! /usr/bin/perl
$RAWCPP="gcc -E -undef -traditional";
#
# reads CPP output and turns #line things into appropriate Haskell
# pragmas
#
# considered to be GHC-project specific
#
#
# NOTE: this script needs RAWCPP set in order to do something
# useful:
#

$Verbose = 0;
$file = '';
@args = ();

$Cpp = ${RAWCPP};

while (@ARGV) {
    $_ = $ARGV[0];
    /^-v$/  && do { $Verbose = 1; shift(@ARGV); next; };
    /^[^-]/ && $#ARGV == 0 && do { $file = $_; shift(@ARGV); next; };
    push @args, $_;
    shift(@ARGV);
}

die "usage: hscpp [arg...] file" if ($file eq '');

print STDERR "hscpp:CPP invoked: $Cpp @args - <$file\n" if $Verbose;
open(INPIPE, "$Cpp @args - <$file |") 
	|| die "Can't open C pre-processor pipe\n";

while (<INPIPE>) {

    s/^#\s*line\s+(\d+)\s+\"\"$/\{\-# LINE \1 \"$file\" \-\}/;
    s/^#\s*(\d+)\s+\"\".*/\{\-# LINE \1 \"$file\" \-\}/;

# line directives come in flavo[u]rs:

#   s/^#\s*line\s+\d+$/\{\-# LINE \-\}/;   IGNORE THIS ONE FOR NOW
    s/^#\s*line\s+(\d+)\s+(\".+\")$/\{\-# LINE \1 \2 \-\}/;
    s/^#\s*(\d+)\s+(\".*\").*/\{\-# LINE \1 \2 \-\}/;

    print $_;
}

close(INPIPE) || exit(1); # exit is so we reflect any errors.

exit(0);
