#
# To fully function, this script needs the following variables
# set:
#
#   INSTALLING
#   DEFAULT_TMPDIR
#   TOP_PWD
#   libdir
#   libexecdir
#   ProjectVersionInt
#   HSP_IMPORTS

if ( $ENV{'TMPDIR'} ) { # where to make tmp file names
    $tmp = $ENV{'TMPDIR'} . "/$$.eht";
} else {
    $tmp ="${DEFAULT_TMPDIR}/$$.eht";
    $ENV{'TMPDIR'} = ${DEFAULT_TMPDIR}; # set the env var as well
}

$TopPwd         = "${TOP_PWD}"; # *Only* needed when using it in-situ (i.e., INSTALLING=0).
$InstLibDirGhc  = "${libdir}";
$InstLibExecDirGhc  = "${libexecdir}";

$Unlit = ( $INSTALLING ? 
           "${InstLibExecDirGhc}/unlit" : 
	   "${TopPwd}/ghc/utils/unlit/unlit" );
# but this is re-set to "cat" (after options) if -cpp not seen
$HsCpp = ( $INSTALLING ? 
	   "${InstLibDirGhc}/hscpp" : 
	   "${TopPwd}/ghc/utils/hscpp/hscpp" );
$HsP   = ( $INSTALLING ? 
	   "${InstLibExecDirGhc}/hsp" : 
	   "${TopPwd}/ghc/compiler/hsp" );
$HsTagsHelp = 
	 ( $INSTALLING ? 
	   "${InstLibExecDirGhc}/hstags-help" : 
	   "${TopPwd}/ghc/utils/hstags/hstags-help" );

$Verbose = 0;
$Append = '>';
$DoCpp = 0;
$Cpp_opts = '';
$HsP_opts = '';
@Files = ();

while ($ARGV[0] =~ /^-./) {
    $_ = shift(@ARGV);
    /^--/		&& last;
    /^-v/		&& ($Verbose  =  1, next);
    /^-a$/		&& ($Append   = '>>', next);
    /^-fglasgow-exts/	&& ($HsP_opts .= ' -N', next);
    /^-optP(.*)/	&& ($Cpp_opts .= " $1", next);
    /^-[UDI]/		&& ($Cpp_opts .= " $_", next);
    /^-cpp/		&& ($DoCpp = 1, next);
    /^-/		&& next; # ignore the rest
    push(@Files, $_);
}

$DoHsCpp = ( ! $DoCpp ) ? 'cat'
			: "$HsCpp -D__HASKELL1__=2 -D__GLASGOW_HASKELL__=$ProjectVersionInt $Cpp_opts";

# to find Prelude.hi and friends.
$HsP_opts .= ( $INSTALLING  ? 
	       "-J${InstLibDirGhc}/imports" : 
	       ( '-J' . join(' -J',split(/:/,${HSP_IMPORTS})) ));

open(STDOUT, "$Append TAGS") || die "can't create TAGS";

foreach $f ( @ARGV ) {
    # if file is in a dir && we are CPPing, then we add its dir to the -I list.
    if ( $DoCpp && $f =~ /(.+)\/[^\/]+$/ ) {
	$Idir = "-I$1";
    } else {
	$Idir = '';
    }

    if ( $f =~ /\.lhs$/ ) {
	$ToDo = "$Unlit $f - | $DoHsCpp $Idir | $HsP -E $HsP_opts | $HsTagsHelp $f > $tmp";
    } else {
	$ToDo = "$DoHsCpp $Idir < $f | $HsP -E  $HsP_opts | $HsTagsHelp $f > $tmp";
    }
    print STDERR "$ToDo\n" if $Verbose;
    system($ToDo);
    $return_val = $?;
    die "Fatal error $return_val\n" if $return_val != 0;

    ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
     $atime,$mtime, $ctime,$blksize,$blocks) = stat("$tmp");
  
    print STDOUT "\f\n$f,${size}\n";
    print STDOUT `cat $tmp`;
}

unlink $tmp;
