#!/usr/bin/perl

# Will take the output of gcc -MM -E *.c and massage it so that it 
# can be plugged right in to a Mindy Makefile.in
# (Namely, it adds ${SRCDIR} to the front of each target, while trying to 
# make the line breaks look halfway decent)

# Accesses and destroys the global array @words, which contains target, 
# a colon, and a bunch of dependencies
#
sub print_target {
    local($first_word) = shift @words;
    if ($first_word =~ /:/) {
	print $first_word, " ";
    } else {
	local($colon) = shift @words;
	print $first_word, " : ";
    }
    local($c_file) = $words[0];
    local($count) = 0;
    while (@words) {
	local($this_word) = shift(@words);
	print " \${SRCDIR}/", $this_word;
	$count++;
	if ($count == 3 && @words) {
	    $count = 0;
	    print " \\\n";
	    for ($i=0; $i<length($first_word . " : "); $i++) {
		print " ";
	    }
	}
    }
    print "\n\t\${CC} -c \${CFLAGS} \${SRCDIR}/", $c_file, "\n\n";
}

print "# It's easiest to generate this part by machine.\n";
print "# Try gcc -MM -E *.c ",
    "| perl ../etc/generate-depends\n\n";

while (<>) {
    chop;
    @these_words = split(" ", $_);
    $this_line_escaped = 0;
    if ($these_words[$#these_words] eq "\\") {
	@these_words = @these_words[0..$#these_words - 1];
	$this_line_escaped = 1;
    }
    if ($last_line_escaped) {
	@words = (@words, @these_words);       # Concatenate them
    } else {
	@words = @these_words;
    }
    if (! $this_line_escaped) {
	&print_target;
    }
    $last_line_escaped = $this_line_escaped;
}    
