#!/usr/local/sbin/perl -w
use strict;

sub usage () {
    die << "EOM";
Usage: $0 <fortran source file> <dir> <dir> ...
Read the given source file.  Print an equivalent source to stdout,
with all include statements replaced by whatever they included.  Use
the -I<dir> argument to find the included files.  You must have at
least one directory on the include path, otherwise there's no point.

We're doing this because g77 generates wrong line numbers when you
have nested include files, which makes debugging difficult.
EOM
}

use FileHandle;

sub readFile ($$) {
    my ($filename, $includepath) = @_;
    my $fh = new FileHandle $filename, "r";
    if (!defined ($fh)) {
	die "Can't read $filename: $!";
    }
    print "C fixinclude is starting to read from $filename\n";
    my $lineNumber = 0;
    for (;;) {
	my $line = <$fh>;
	last unless defined $line;
	$lineNumber++;
	if ($line =~ m!^\s*include\s*'(.*)'\s*$!i) {
	    my $foundfile = "";
	    my $dir;
	    foreach $dir (@$includepath) {
		if (-r "$dir/$1") {
		    $foundfile = "$dir/$1";
		}
	    }
	    if ($foundfile) {
		readFile ($foundfile, $includepath);
	    } else {
		die "Can't find $1 in the path @$includepath";
	    }
	    print "C fixinclude is resuming reading from $filename line $lineNumber\n";
	} else {
	    print $line;
	}
    }
}

sub main () {
    usage () unless @ARGV;
    my $filename = shift (@ARGV);
    if (! -r $filename) {
	die "Can't read $filename: $!";
    }
    my @path = @ARGV;
    my $dir;
    foreach $dir (@path) {
	if (! -d $dir) {
	    die "$dir is not a directory";
	}
    }
    readFile ($filename, \@path);
}

main ();
