#!perl

# mk_dep example/out/obj/lib/util/obj/util.dep
# util.o: example/src/util/util.c example/src/inc/util.h
# util.obj util.d: example/src/util/util.c example/src/inc/util.h
# example/out/obj/lib/util/obj/util.obj example/out/obj/lib/util/obj/util.d: example/src/util/util.c example/src/inc/util.h

my $dep_file=$ARGV[0];
my $obj_file=$ARGV[0];
my $d_file=$ARGV[0];

# construct the object file name (replace .d with .obj)
$obj_file =~ s/\.dep\b/.obj/;

# construct the .d file name (replace .dep with .d)
$d_file =~ s/\.dep\b/.d/;


unless (-s $dep_file) {
	unlink $d_file;
	unlink $dep_file;
	die "Abort: Empty dependency file >> $dep_file <<, did the source file parse correctly ?\n"
}

# open the files
open (DEP,$dep_file)||die "can't open file\n";
open (DFILE,">$d_file")||die "can't open file\n";

#parse the dependency file
while ($line=<DEP>) {
	# find object filename (.o) and replace it with new full
	# object and dependency file names (.obj, .d)
	$line =~ s/(\w+\.o)/$obj_file $d_file/;

	# cope with CPP error, it sometimes appends a \ to the filename
	# it even sometimes creates solitary \ characters
	$line =~ s/\\([ \t]+)/$1/g;
    
	# cyclic (henn and egg) dependency between .d files and generated files
	# e.g msconst.cdg/rv_swe.h must be handled by busyb.pl
	# $line =~ s/(\s)(\w+.cdg|[pPmM]_\w+.((h)|(val)))\b/$1$gen_cdginc_dir\/$2/g;
	# $line =~ s/(\s)(rv_swe.h)\b/$1$gen_cfginc_dir\/$2/g;
	# $line =~ s/(\s)(\w+.cfg)\b/$1$gen_cfginc_dir\/$2/g;

	print DFILE $line;
}

close DFILE;
close DEP;

unlink $dep_file;
