#!/usr/bin/perl
# fort77 (compiler driver) script for f2c
# For use with gcc under Linux
# This code is in the public domain; use at your own risk.
# Parse options

while ($_ = $ARGV[0], /^-/) {
    shift;

# First, the f2c options.

    if (/^-[CUuaEhPRrz]$/ || /^-I[24]$/ || /^-onetrip$/ || /^-![clPR]$/ ||
    	/^-ext$/ || /^-!bs$/ || /^-W[1-9][0-9]*$/ || /^-w8$/ || /^-w66$/ ) {
	push (@fopts, $_);
    }

# These are common to both f2c and gcc
    elsif (/^-w$/) {
	push(@fopts, $_);
	push(@copts, $_);
    }

# This is for the linker, too...
   elsif (/^-g$/) {
	push(@fopts, $_);
	push(@copts, $_);
	push(@lopts, $_);
   }

# gcc only options

# too many -f and -W options to list them all...

   elsif (/^-[fWDUA]/ || /^-[SEvx]$/ || /^-pipe$/ ) {
	push(@copts, $_);
   }
   elsif (/^-[oIVb]$/) {
	(@ARGV > 0) || die "Missing argument to \"$_\"\n";
	$output = shift;
   }
   elsif (/^-[oIVb]/) {
	$output = (/^-.(.*)/)[0];
   }

# Options for both C compiler and linker

    elsif (/^-[Og]/ || /^-p$/ || /^-pg$/) {
	push(@copts, $_);
	push(@lopts, $_);
    }

# Linker options

    elsif (/^-[lL]$/) {
	push(@lopts, $_);
	(@ARGV > 0) || die "Missing argument to \"$_\"\n";
	$_ = shift;
	push(@lopts, $_);
    }
    elsif (/^-[lL]./ || /^-nostartfiles$/ || /^-static$/ || /^-shared$/ ||
		/^-symbolic$/) {
	push(@lopts, $_);
    }
    elsif (/^-c$/) {
	$compile_only = $_;
    }
    else {
	die "Illegal option: $_\n";
    }
}

foreach (@ARGV) {
    $ffile = undef;
    $cfile = undef;
    $lfile = undef;

    if (/^-[lL]$/) {
        push(@lopts, $_);
        (@ARGV > 0) || die "Missing argument to \"$_\"\n";
        shift;
        push(@lopts, $_);
	next;
    }
    elsif (/^-[lL]./) {
	push(@lopts, $_);
	next;
    }
    elsif (/\.[fF]$/) {
	$ffile = $_;
    }
    elsif (/\.[cCisSm]$/ || /\.cc$/ || /\.cxx$/) {
	$cfile = $_;
    }
    else {
	push(@lfiles, $_);
    }
    if ($ffile) {
	$cfile = ($ffile =~ /(.*\.).$/)[0] . "c";
        $retcode = system("f2c", @fopts, $ffile)/256;
	if ($retcode) {
	    unlink $cfile;
	    die "$0: aborting compilation\n";
	}
    }
    if ($cfile) {
	if ($compile_only && $output) {
	    $lfile = $output;
	}
	else {
	    $lfile = ($cfile =~ /(.*\.).*$/)[0] . "o";
	}
	$retcode = system("cc", "-c", @copts, "-o", $lfile, $cfile)/256;
	if ($retcode) {
	    die "$0: aborting compilation\n";
	}
	unlink $cfile;
	push (@gener_lfiles, $lfile);
    }
    push (@lfiles, $lfile) if $lfile;
}


die "No input files specified\n" unless @ffiles + @cfiles + @lfiles;

exit if $compile_only;

push (@output, "-o", $output) if $output;
$retcode = system("cc", @output, @lfiles, @ldflags, "-lf2c", "-lm" );
unlink (@gener_lfiles);
exit $retcode;
