#!/usr/local/bin/perl
#----------------------------------------------------------
# Configurable part: Please change global variables at your own needs.
$HOME = $ENV{'HOME'};
$ENV{'SmallEiffel'} = "/usr/local/SmallEiffel/";
$ENV{'PATH'} = "/usr/local/SmallEiffel/bin:/usr/local/bin:/bin:/usr/bin:$HOME/bin/command";
$e_flags  = "-require_ceck";
$dbg_flags = "-g";
$c_flags  = "-ansi -D_HPUX_SOURCE -IC -I/usr/local/include";
$ld_flags = "-z /usr/local/lib/libgc.a";
# Configurable part end
#----------------------------------------------------------
mkdir("B",0755); #prepare orginal source dir
mkdir("C",0755); #prepare converted source dir
$debug = 1;
$target = shift(@ARGV);
if($ARGV[0] !~ /^-/) {
    $root = $target;
} else {
    $root   = shift(@ARGV);
}
if($ARGV[0] !~ /^-/) {
    $make = "make";
} else {
    $make   = shift(@ARGV);
}

if(!$target) {
    $help++;
} else {
    if(@ARGV) {
	$e_flags = "";
	while($fl = shift(@ARGV)) {
	    if($fl =~ /^-?h/) {$help++;}
	    if($fl =~ /^-?d/) {$e_flags = "-debug_check";}
	    if($fl =~ /^-?a/) {$e_flags = "-all_check";}
	    if($fl =~ /^-?l/) {$e_flags = "-loop_check";}
	    if($fl =~ /^-?i/) {$e_flags = "-invariant_check";}
	    if($fl =~ /^-?e/) {$e_flags = "-ensure_check";}
	    if($fl =~ /^-?r/) {$e_flags = "-require_check";}
	    if($fl =~ /^-?n/) {$e_flags = "-no_check";}
	    if($fl =~ /^-?b/) {$e_flags = "-boost";}
	    if($fl =~ /^-?O/) {$e_flags = "-boost";$dbg_flags = "-g -O3";}
	    if($fl =~ /^-?v/) {$e_flags .= " -verbose";}
	}
    }
}

if($help) {
    print "Usage: se-comp target [root [make]] [-daliernbO] [-v]\n";
    exit;
}

if(-f $target) {
    $target_age = -M $target;
} else {
    $target_age = 10000000;
}

chomp($cwd = `pwd`);
opendir(DIR,$cwd);
@sources = grep(/.e$/,readdir(DIR));
@new_sources = grep {(-M $_) < $target_age} @sources;
closedir(DIR);

if(@new_sources) {
    
    do_command("compile_to_c $e_flags -o $target $root $make");
    opendir(DIR,$cwd);
    @cfiles = grep {(-M $_) < $target_age} grep(/^$root\d*.[ch]$/,readdir(DIR));
    closedir(DIR);
    if(!@cfiles) { exit; }
    if($e_flags ne "-boost") {
	do_command("add_line_directive @cfiles");
    } else {
	do_command("move-if-changed @cfiles C");
	unlink @cfiles;
    }
    chdir "C";
    @new_cfiles = grep(/^$root\d+.c$/,@cfiles);
    @new = ();
    foreach $s (@new_cfiles) {
	$o = $s;
	$o =~ s/\.c$/.o/;
	if(!-f $o || (-M $o) > (-M $s)) {
	    push(@new,$s);
	}
    }
    $ret = 0;
    if(@new) {
	$ret += do_command("$CC $dbg_flags $c_flags -c @new");
    }

    if(!$ret) {
	@objects = grep{s/(.*)\.c$/$1.o/} @cfiles;
	do_command("$CC -o ../$target $dbg_flags @objects $ld_flags");
    }

}

sub do_command {
    my($com) = @_;
    print "$com\n" if $debug;
    system($com);
}
