#!/opt/gnu/bin/perl

# CDEPEND -- Compute dependencies for mafefile
#
# Usage: cdepend [flags] [files]
# Run with same options as cc, except no -xM1 flag

$cmdline = join (' ', @ARGV);
$includes = '-I../../include -I/usr/stsci/stsdasx/lib -I/usr/local/ostdb/ostdb1_8/include';

open (INPUT, "cc -xM1 $includes $cmdline |") || 
    die "Can't run cc\n";

# Create a hashed array of the function dependencies

while (<INPUT>) {
    chop;
    tr/ //d;
    ($name, $value) = split (/:/);

    next if $name eq 'main.o';
    next if $value =~ m%^/%;

    $value =~ s%//%/%g;

    $pattern = $value;
    $pattern =~ s/(\W)/\\\1/g;
    next if $depend{$name} =~ /$pattern/;

    if ($depend{$name}) {
	$depend{$name} .= " $value";
    } else {
	$depend{$name} = $value;
    }
}

close (INPUT);

# print the dependencies
    
@names = sort (keys (%depend));

print ".PRECIOUS : \$(LIB)\n\n";
print "\$(LIB) : ", join (" \\\n\t", map ("\$(LIB)($_)", @names)), "\n";
print "\tranlib \$\@\n\n"; 

foreach $obj (@names) {
    ($src = $obj) =~ s/\.o$/\.c/;
    @lines = &breakline ($depend{$obj}, 65);
    print "\$LIB($obj) : ", join (" \\\n\t", @lines), "\n";
    print "\t\$(CC) \$(CFLAGS) -c $src\n";
    print "\tar -rv \$(LIB) $obj\n\trm $obj\n";
}

sub breakline {
    local ($line, $maxlen) = @_;
    local ($lastbrk, $lastsp, $nextsp);
 
    $nextsp = 0;
    $lastbrk = $lastsp = $nextsp - 1;
    while (($nextsp = index ($line, ' ',  $nextsp)) >= 0) {
        if ($nextsp - $lastbrk > $maxlen && $lastsp >= 0) {
            substr ($line, $lastsp, 1) = "\n";
            $lastbrk = $lastsp;
        }
 
        $lastsp = $nextsp ++;
    }
 
    substr ($line, $lastsp, 1) = "\n" if length ($line) - $lastbrk > $maxlen &&
	$lastsp > 0;

    split (/\n/, $line);
}
