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

require "getopt.pl";

#  ץ
#
#  -C <cc_path>	CѥΥޥ̾
#  -O <cc_opts>	Cѥ/CPPϤץ
#
#  -X		եŪCإåեȸʤ
#
#  -T <target>	åȤΥե̾
#  -D <t_dir>	åȤΥǥ쥯ȥ̾ꤹ
#  -d		åȤΥǥ쥯ȥݻ
#  -s		åȤΥեå ".s" ˤʥǥեȤ ".o"

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

$cc_path = $opt_C;
$cc_opts = $opt_O;

$suffix = $opt_s ? "s" : "o";
if ($opt_T) {
	$target_file = $opt_T;
}
elsif ($opt_D) {
	$target_dir = $opt_D;
}
elsif (!$opt_d) {
	$target_dir = "";
}

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

	if ($target_file) {
		$target = $target_file;
	}
	else {
		$target = $file;
		$target =~ s/(.*)\.(.)/$1.$suffix/;
	}	
	if (defined($target_dir)) {
		$target =~ s/^.*\/([^\/]+)$/$1/;
		if ($target_dir) {
			$target = $target_dir."/".$target;
		}
	}
	print $target, ": ";
	$column = length($target) + 2;
    
	foreach $file (keys(%dependlist)) {
		$len = length($file) + 1;
		if ($column > 8 && $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, $filename);

	$command = "$cc_path -E $cc_opts";
	if ($opt_X) {
		$command .= " -x c-header";
	}
	unless (open(INPUT, "$command $file |")) {
		print STDERR "makedep: can't open $file\n";
		exit(1);
	}
	while ($line = <INPUT>) {
		if ($line =~ /^\#\s*([0-9]+)\s*\"([^\"]+)\"/) {
			$filename = $2;
			$filename =~ s/ /\\ /;
			if ($filename !~ /^\<.*\>$/ && $filename !~ /\/$/) {
				$dependlist{$filename} = 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);
}
