#!/usr/bin/perl
#	MkDeps *.c
#-----------------------------------------------------------------------------#
# This program takes a list of C source and feeds them to "cc -Em" to get the #
# make dependencies.  It then reduces the (rather large and overly redundant) #
# output  to  a  list  of  1-line  make  dependencies.   It  strips  out  any #
# /usr/include files, strips away initial "./" from names, discards dbg.h and #
# local.h dependencies, and sorts and uniquifies  the  resulting  list.   The #
# result should be a reasonably compact set of make dependencies that you can #
# insert in your makefile.                                                    #
#-----------------------------------------------------------------------------#
$D = $ENV{"DBGMkDep"};
$, = ' ';
open(DP,"cc -Em @ARGV |") || die "Can't run `cc -Em'\n";
if($D){printf "Pipe opened.\n";}
while (<DP>) {
	chop;
	if($D){printf "Line: $_\n";}
	if (/(.+) *: *(.*)/) {
		if($D){printf "Dependency: \"$1\" : \"$2\"\n";}
		$file = $2;
		if ($1 ne $curr) {
			if($D){printf "New file \"$1\"\n";}
			&out() if ($curr);
			$curr = $1;
		} 
		if ($file =~ /^\/usr\/include\//) {
			if($D){printf "Ignored.\n";}
		} elsif ($file =~ /^\.\/(.*)/) {
			if ($1 eq "dbg.h" || $1 eq "local.h") {
				if($D){printf "Ignored \"$file\"\n";}
			} else {
				$hdr{$curr} .= " $1";
				if($D){printf "hdr{$curr}: \"%$hdr{$curr}\"\n";}
			}
		} else {
			$src{$curr} .= " $file";
			if($D){printf "src{$curr}: \"$src{$curr}\"\n";}
		}
	}
}
&out() if ($curr);	# Remember to output the last one!
exit 0;
#-----------------------------------------------------------------------------#
# Whenever a new filename is discovered in column 1, this routine is called to
# output the dependency line for the previous filename.
sub out {
	if($D){printf "------\n";}
	if($D){printf "curr=\"$curr\"\n";}
	if($D){printf " src=\"$src{$curr}\"\n";}
	if($D){printf " hdr=\"$hdr{$curr}\"\n";}
	$list = `say +1 $hdr{$curr}`;
	chop $list;
	if($D){printf "list=\"$list\"\n";}
	@list = split(/ /,$list);
	if($D){printf "list: @list\n";}
	@ordr = sort(@list);
	if($D){printf "ordr: @ordr\n";}
	printf "$curr: $src{$curr} @ordr\n";
	if($D){printf "------\n";}
}
