#! /usr/bin/perl
#
#  TOPPERS/JSP Kernel
#      Toyohashi Open Platform for Embedded Real-Time Systems/
#      Just Standard Profile Kernel
# 
#  Copyright (C) 2000 by Embedded and Real-Time Systems Laboratory
#                              Toyohashi Univ. of Technology, JAPAN
# 
#  嵭ԤϡFree Software Foundation ˤäƸɽƤ 
#  GNU General Public License  Version 2 ˵ҤƤ狼
#  ξΤ줫˸¤ꡤܥեȥܥեȥ
#  ѤΤޤࡥʲƱˤѡʣѡۡʰʲ
#  ѤȸƤ֡ˤ뤳Ȥ̵ǵ롥
#  (1) ܥեȥ򥽡ɤηѤˤϡ嵭
#      ɽѾ浪Ӳ̵ݾڵ꤬Τޤޤηǥ
#      ˴ޤޤƤ뤳ȡ
#  (2) ܥեȥѲǽʥХʥꥳɡʥ֥륪
#      ȥե饤֥ʤɡˤηѤˤϡ
#      ȼɥȡѼԥޥ˥奢ʤɡˤˡ嵭ɽ
#      Ѿ浪Ӳ̵ݾڵǺܤ뤳ȡ
#  (3) ܥեȥԲǽʥХʥꥳɤηޤϵ
#      ߹ѤˤϡΤ줫ξȡ
#    (a) ѤȼɥȡѼԥޥ˥奢ʤɡˤˡ嵭
#        ɽѾ浪Ӳ̵ݾڵǺܤ뤳ȡ
#    (b) Ѥη֤̤ˡˤäơ嵭Ԥ𤹤
#        ȡ
#  (4) ܥեȥѤˤľŪޤϴŪ뤤ʤ»
#      ⡤嵭Ԥդ뤳ȡ
# 
#  ܥեȥϡ̵ݾڤ󶡤ƤΤǤ롥嵭Ԥϡ
#  ܥեȥ˴ؤơŬѲǽޤơʤݾڤԤ
#  ʤޤܥեȥѤˤľŪޤϴŪ
#  ʤ»˴ؤƤ⡤Ǥʤ
# 
#  @(#) $Id: makedep,v 1.3 2001/09/26 02:47:28 hiro Exp $
# 

require "getopt.pl";

#  ץ
#
#  -C <cc_path>	 CѥΥޥ̾
#  -O <cc_opts>	 Cѥ/CPPϤץ
#  -S <paths>	 ե򥵡ѥ":" Ƕڤ
#
#  -P <cpp_path> CPPΥޥ̾
#  -T <target>   åȤΥե̾
#  -s		 åȤΥեå ".s" ˤʥǥեȤ ".o"

#
#  ץν
#
do Getopt("PCOST");

$cc_path = $opt_C;
$cc_opts = $opt_O;
@src_paths = split(/:/, $opt_S);

$suffix = $opt_s ? "s" : "o";
$cpp_path = $opt_P;
$target_file = $opt_T;

#
#  $dependlist ˺줿¸طϤ
#
sub output_dependlist {
	local($file) = @_;
	local($column, $len);

	if ($target_file) {
		print $target_file;
		$column = length($target_file);
	}
	else {
		$file =~ s/(.*)\.(.)/$1.$suffix/;
		print $file;
		$column = length($file);
	}	
	print ": ";
	$column += 2;
    
	foreach $file (keys(%dependlist)) {
		$len = length($file) + 1;
		if ($column + $len >= 70) {
			print "\\\n\t";
			$column = 8;
		}
		$column += $len;
		print "$file ";
	}
	print "\n";
}

#
#  $file ΰ¸ط %dependlist ˺
#
sub makedepend_one {
	local($file) = @_;
	local($command, $input, $dir, $fullpath);

	foreach $dir (".", @src_paths) {
		if (-e $dir."/".$file) {
			$fullpath = $dir."/".$file;
			last;
		}
	}
	unless ($fullpath) {
		print STDERR "makedep: can't find $file\n";
		exit(1);
	}

	if ($cpp_path) {
		$command = "$cpp_path $cc_opts";
	}
	else {
		$command = "$cc_path -E $cc_opts";
	}
	unless (open(INPUT, "$command $fullpath |")) {
		print STDERR "makedep: can't open $fullpath\n";
		exit(1);
	}
	while ($line = <INPUT>) {
		if ($line =~ /^\#\s*([0-9]+)\s*\"([^\"]+)\"/) {
			$dependlist{$2} = 1;
		}
	}
	unless (close(INPUT)) {
		print STDERR "makedep: can't execute $command\n";
		exit(1);
	}
}

#
#  ᥤ롼
#
foreach $file (@ARGV) {
	%dependlist = ();
	do makedepend_one($file);
	do output_dependlist($file) if (%dependlist);
}
