#!/usr/bin/perl

use Cwd;
use Config;

use Getopt::Std;
#require 'getopts.pl';

$uname="uname";

$nice_value = "0";		# default nice value (=lowest priority)
$is_package = 1;
$SHOW_SKIPPING = 0;

# On Cygwin, specify $cygwin_home in your ~/.ace.perl 
# e.g. $cygwin_home="c:/cygwin";
$cygwin_home = "";


# ====================================
# Defaults ACE
# ====================================

#for each compiler, give the possible OS's
%combinationsfordir = ("master" => ["Solaris", "Linux", "Windows"],
		       "sicstus" => ["Solaris", "Linux", "Windows"],
		       "yap" => ["Solaris", "Linux"],
		       "ilp" => ["Solaris", "Linux", "Windows", "Cygwin", "Alpha", "MacOS"]
		       );
#for each OS, give default compiler
%defaultforos = ("Solaris" => "ilp",
		 "Linux" => "ilp",
		 "Windows" => "ilp",
		 "Cygwin" => "ilp",
		 "Alpha" => "ilp",
		 "MacOS" => "ilp");

$version = "1.0";
$run_preproc = 1;  #either 1 or 0

#defaults for engine and options
$engine{'master'}{'Solaris'} = 'PLeng';
$engine{'master'}{'Linux'} = 'PLeng';
$engine{'master'}{'Windows'} = 'PLeng';
$engine{'sicstus'}{'Solaris'} = '/cw/prolog/sicstus/sicstus-yes.solaris/bin/sicstus';
$engine{'sicstus'}{'Linux'} = '/cw/prolog/sicstus/sicstus-yes.linux/bin/sicstus';
$engine{'sicstus'}{'Windows'} = 'sicstus';
$engine{'ilp'}{'Solaris'} = 'ilProlog';
#$engine{'ilp'}{'Linux'} = 'ilProlog';
$engine{'ilp'}{'Linux'} = 'bin/hipP';
$engine{'ilp'}{'Windows'} = 'hipP';
$engine{'ilp'}{'Cygwin'} = 'ilProlog';
$engine{'ilp'}{'Alpha'} = 'ilProlog';
$engine{'ilp'}{'MacOS'} = 'hipP';
$engine{'yap'}{'Solaris'} = 'yap';
$engine{'yap'}{'Linux'} = 'yap';

$OLDYAP = 1;

$engine_path{'ilp'}{'Solaris'} = '/cw/prolog/ilprolog/ilprolog-yes.solaris';
$engine_path{'ilp'}{'Linux'} = '/cw/prolog/hipp/hipp-yes.linux';
$engine_path{'ilp'}{'Windows'} = '/cygdrive/c/Tools/ilprolog';
$engine_path{'ilp'}{'Cygwin'} = '/cygdrive/i/cache/jan/ilprolog';
$engine_path{'ilp'}{'MacOS'} = '/Users/remko/Documents/work/hipp/src';

$options{'master'}{'Solaris'} = '-Cc+ -Pc+ -Pq+ -Ps+ -THb1m -TBl20m -THl20m -TCl100m -TIe100',
$options{'master'}{'Linux'} = '-Cc+ -Pc+ -Pq+ -Ps+ -THb1m -TBl20m -THl20m -TCl100m -TIe100';
$options{'master'}{'Windows'} = '-Cc+ -Pc+ -Pq+ -Ps+ -THb1m -TBl20m -THl20m -TCl100m -TIe100';
$options{'sicstus'}{'Solaris'} = '';
$options{'sicstus'}{'Linux'} = '';
$options{'sicstus'}{'Windows'} = '';

$options{'ilp'}{'Solaris'} = ' -h4000000 ';
$options{'ilp'}{'Linux'} =   ' -h4000000 ';
$options{'ilp'}{'Windows'} = ' -h4000000 ';
$options{'ilp'}{'Cygwin'} = ' -h4000000 ';
$options{'ilp'}{'Alpha'} = ' -h4000000 ';
$options{'ilp'}{'MacOS'} = ' -h4000000 ';

$body{'master'}{'Solaris'} = '$SRC_DIR/ace -';
$body{'master'}{'Linux'} = '$SRC_DIR/ace -';
$body{'master'}{'Windows'} = '$SRC_DIR/ace -';
$body{'sicstus'}{'Solaris'} = '-l $SRC_DIR/ace -a';
$body{'sicstus'}{'Linux'} = '-l $SRC_DIR/ace -a';
$body{'sicstus'}{'Windows'} = '-l $SRC_DIR/ace -a';
$body{'ilp'}{'Solaris'} = '$SRC_DIR/ace -a';
$body{'ilp'}{'Linux'} = '$SRC_DIR/ace -a';
$body{'ilp'}{'Windows'} = '$SRC_DIR/ace -a';
$body{'ilp'}{'Cygwin'} = '$SRC_DIR/ace -a';
$body{'ilp'}{'Alpha'} = '$SRC_DIR/ace -a';
$body{'ilp'}{'MacOS'} = '$SRC_DIR/ace -a';
$body{'yap'}{'Solaris'} = '-l $SRC_DIR/ace ';
$body{'yap'}{'Linux'} = '-l $SRC_DIR/ace ';

$makeoptions{'master'}{'Solaris'} = 'CC=gcc CFLAGS=\'-I$(PL_HOME)/include -I/home/wimv/iODBC/solaris/include -DEII_SOLARIS\'';
$makeoptions{'master'}{'Linux'} = 'CC=gcc CFLAGS=\'-I$(PL_HOME)/include -I/home/wimv/iODBC/linux/include -DEII_LINUX\'';
#$makeoptions{'master'}{'Windows'} = '/I CFLAGS=\'/I$(PL_HOME)/include /DEII\_WINDOWS\'';  #include voor ODBC gekend door Visual C
$makeoptions{'master'}{'Windows'} = '"CFLAGS=/DEII_WINDOWS"';  #include voor ODBC gekend door Visual C

$ld_library_path{'master'}{'Solaris'} = "/home/wimv/ODBC/MySQL/local/mysql/lib/mysql/:/home/wimv/iODBC/solaris/lib";
$ld_library_path{'sicstus'}{'Solaris'} = "/home/wimv/ODBC/MySQL/local/mysql/lib/mysql/:/home/wimv/iODBC/solaris/lib";
$ld_library_path{'master'}{'Linux'} = "/home/wimv/ODBC/MySQL/local/mysql/lib/mysql/:/home/wimv/iODBC/linux/lib";
$ld_library_path{'sicstus'}{'Linux'} = "/home/wimv/ODBC/MySQL/local/mysql/lib/mysql/:/home/wimv/iODBC/linux/lib";

#evaluate user ~/.ace.perl -> you can change default values
eval `cat $ENV{"HOME"}/.ace.perl` if (-e "$ENV{HOME}/.ace.perl");

# ====================================
# PREPARE ACE
# ====================================

$CURRENT_DIR=cwd();

$THIS_PROGRAM=expand_dir($0);
printf("This is $THIS_PROGRAM\n");
$THIS_PROGRAM=~/(.*)\/ACE(\.new|.*)/ || die("can't find directory where executed");
$ACE_DIR=$1;

if ($is_package == 1) {
	$UTIL_DIR = $BASE_DIR . "/util";
} else {
	$UTIL_DIR = $ACE_DIR . "/Util";
}

require "$UTIL_DIR/preproc/preproc.perl";

# Run ACE with ./ACE or ~/.../ACE or /fullpath
sub expand_dir {
    my ($dir) = @_;
    my ($pwd);
    # Unix style full path /...
    if ($dir =~ /^\//) {
    	return $dir;
    }
    # Windows style full path C:\.. or D:\..
    if ($dir =~ /^.\:\\/) {
    	return $dir;
    }
    # Relative path
    $pwd = $dir;
    $pwd =~ s/ACE$//;
    chdir $pwd;
    $pwd = cwd();
    chdir $CURRENT_DIR;
    return "${pwd}/ACE";
}

# ====================================
# Process Options
# ====================================

do getopts('hpgSsvV:o:n:WcRrCPd:D:qm:');

if (defined($opt_h)) {
	&print_usage;
	exit;
    }

if (defined($opt_D)) {
	eval `cat $opt_D` if (-e "$opt_D");
}

if ($opt_p) {
    $run_preproc = $run_preproc ^ 1;  #0->1, 1->0
}

if (defined($opt_o)) {
    $extra_options = $opt_o;
}
else {
    $extra_options = '';
}

if (defined($opt_s)) {
	$is_package = $is_package ^ 1;
}

$nice_value = $opt_n if (defined($opt_n));  # new nice value
$nicecmd = "nice -$nice_value";

if (defined($opt_W)) {
    $writecmd = 1;
}
else {
    $writecmd = 0;
}

if (defined($opt_R)) {
    $makeruntime = 1;
}
else {
    $makeruntime = 0;
}

if (defined($opt_W)) {
    $writecmd = 1;
}
else {
    $writecmd = 0;
}

#$opt_c used later
#$opt_r used later
#$opt_C used later

# ====================================
# GET info OS
# ====================================

#$OS=`$uname -s`;
#$os = $OSNAME;
$OS = $Config{osname};

if ($OS =~/Linux/i) {  #i : case insensitive matching
    $aceos = "Linux";  #index of oslist
    chop($hw = `$uname -m`);
}
elsif ($OS =~ /SunOS|Solaris/i) {
    $aceos = "Solaris";
    chop($hw = `$uname -m`);
}
elsif ($OS =~/WIN_NT|MSWin/i) {
    $aceos = "Windows";
    unless (chop($hw = `$uname -m`)) {$hw = 'unknown'};  #at MS-DOS prompt uname does not exist
    $nicecmd = '';  #no nice command in Windows!
}
elsif ($OS =~/cygwin/i) {
    $aceos = "Windows";
    chop($hw = `uname -m`);
}
elsif ($OS =~/dec_osf/i) {
    $aceos = "Alpha";
    chop($hw = `uname -m`);
}
elsif ($OS =~ /darwin/i) {
	$aceos = "MacOS";
	chop($hw = `uname -m`);
}
else {
    printf "Unknown OS: $OS \n";
    die("Can't run ACE");
}

if ($opt_d) {
	system("$UTIL_DIR/preproc/c/bin/$aceos/PPreproc showdefs \"$ACE_DIR/V-$version/src/ace.pch\" \"$opt_d\"");
	exit(0);
}

#$hostname = `$uname -n`;

$smallos = lc($aceos);

use Sys::Hostname qw(hostname);  #works also for Windows
$hostname = hostname();

# ====================================
# Make use of Condor?
# ====================================

$condor = 0;
if (defined($opt_c)) {
	$condor = 1;
}

# ====================================
# GET info Compiler
# ====================================

if ($ENV{"COMPILER"}) {
    $compiler = $ENV{"COMPILER"};
} else {
    $compiler = $defaultforos{$aceos};
}

unless (defined($engine{$compiler}{$aceos})) {
    die("no engine defined for $compiler on $aceos");
}

if (defined($opt_m)) {
	$options{$compiler}{$aceos} = $options{$compiler}{$aceos} . " -m$opt_m";
}

# ====================================
# RUN runtime if specified
# ====================================

if (defined($opt_r)) {
	if ($compiler =~ /master/) {  #need to compile all C files - currently only OdbcLow.c
		if (defined($ld_library_path{$compiler}{$aceos})) {
			$ENV{"LD_LIBRARY_PATH"}= "$ld_library_path{$compiler}{$aceos}:$ENV{LD_LIBRARY_PATH}";
		}
		$ENV{ACE_DIR}="$ACE_DIR/RT-$version/$compiler";
		$ENV{LD_LIBRARY_PATH}=$ENV{ACE_DIR}."/lib/so:".$ENV{LD_LIBRARY_PATH};
		&run_command("/bin/sh $ENV{ACE_DIR}/bin/acert @ARGV");
		exit;
	}
	if ($compiler =~ /ilp/) {
		$ENV{ACE_ILP_ROOT}="$ACE_DIR/RT-$version/ACE-ilProlog/$smallos";
		print "Running ACE-ilProlog runtime $ENV{ACE_ILP_ROOT}\n";
		$ENV{LD_LIBRARY_PATH}=$ENV{ACE_ILP_ROOT}."/lib/so:".$ENV{LD_LIBRARY_PATH};
		&run_command("$ENV{ACE_ILP_ROOT}/bin/ace @ARGV");
		exit;
	}
}

# ====================================
# Clean-up if specified
# ====================================

if (defined($opt_C)) {
	print "Cleaning up ACE source tree\n";
	foreach $keycompiler (keys %combinationsfordir) {
		system("rm -rf \"$ACE_DIR/V-$version/src.$keycompiler/\"");
	}
	exit;
}

sub main_cleanup_dir {
    my ($parent) = @_;
    rec_to($parent, $parent, 0, "cleanup_remove");
}

sub cleanup_remove {
    my ($dir) = @_;
    cleanup(dir);
    rmdir(dir);
}

sub cleanup {
    my ($dir) = @_;
    if ($writecmd) {
	print "rm $dir/*  - using unlink in Perl\n";
    } else {
	unlink <$dir/*>;
	unlink <$dir/.*>;
    }
}

# ====================================
# Load and compile all packages
# ====================================

if (defined($opt_P)) {
	print "Creating allpackages.{s,kb}\n";
	unless (mkdir "/tmp/allpackages", 0777) {
		print "Error creating directory /tmp/allpackages\n";
		exit;
	}
	# Generate .kb file
	open(PackageKB, ">/tmp/allpackages/allpackages.kb");
	close(PackageKB);
	# Generate .s file
	open(PackageS, ">/tmp/allpackages/allpackages.s");
	printf PackageS "load(key).\npredict(allpackages(+,-)).\n\n";
	# Insert use_package's
	open(PackageList,"$ACE_DIR/package_list");
	if (open(PackageList,"$ACE_DIR/package_list")) {
		while($subdir=<PackageList>) {
			chop $subdir;
			if (!($subdir =~ /%/)) {
				printf PackageS "load_package($subdir).\n";
			}
		}
        	close(PackageList);
	}
	close(PackageS);
	chdir("/tmp/allpackages");
	$CURRENT_DIR = "/tmp/allpackages";
}

# ===========================================================
# RUN preproc (generate prolog source files from .gen files)
# ===========================================================

if ($run_preproc) {
	select_compiler($compiler);
	preproc_all($ACE_DIR);
	# Used for debugging template package - preproc main source code of ACE
	if (defined($ENV{ACE_MAIN_SRC}) && ($is_package == 1)) {
		$MAIN_SRC = $ENV{ACE_MAIN_SRC};
		preproc_all($MAIN_SRC);
	}
	chdir("$CURRENT_DIR/.");
	terminate_preproc();
}

sub preproc_all {
	my ($acedir) = @_;
	ensuremkdir("$acedir/V-$version/src.$compiler/$aceos/so");
	run_preproc($acedir, $version, "");
	if (open(PackageList,"$acedir/package_list")) {
	    while($dir=<PackageList>) {
	        chop $dir;
	        if (!($dir =~ /%/) && (-d "$acedir/V-$version/src/$dir")) {
	        	preproc_directory($dir, $acedir);
	    	}
    	    }
            close(PackageList);
	}
}

sub preproc_directory {
	my ($subdir, $acedir) = @_;
	ensuremkdir("$acedir/V-$version/src.$compiler/$aceos/$subdir");
	run_preproc($acedir, $version, $subdir);
}

# ====================================
# Copy source files to OS directories
# ====================================

sub ensuremkdir {
	my ($mydir) = @_;
	$mydir =~ s/\s//g;
	if (!(-d $mydir)) {
		if (mkdir $mydir, 0777) {
			print "Creating directory [$mydir]\n";
			return;
		} else {
			my ($subdir) = $mydir;
			$subdir =~ s/\/[A-Z,a-z,0-9]+$//;
			if ($subdir =~ /^\/[A-Z,a-z,0-9]+/) {
				ensuremkdir($subdir);
				if (mkdir $mydir, 0777) {
					print "Creating directory [$mydir]\n";
					return;
				}
			}
		}
		die ("Error creating dir: $mydir\n");
	}
}

sub get_subdirs {
	my ($dir) = @_;
	if (opendir(DIR, $dir)) {
		@dirs = grep {/^[^\.]/ && -d "$dir/$_" && !/CVS/} readdir(DIR);
		closedir DIR;
	} else {
		@dirs = ();
	}
	return @dirs;
}

sub rec_from_to {
	my (@dirs, $dir);
	my ($from, $to, $curr, $call) = @_;
	eval "$call(\"$from/$curr\", \"$to/$curr\")";
	@dirs = &get_subdirs("$from/$curr");
	foreach $dir (@dirs) {
		&rec_from_to($from, $to, "$curr/$dir", $call);
	}
}

sub rec_to {
	my (@dirs, $dir);
	my ($cdir, $curr, $arg, $call) = @_;
	@dirs = get_subdirs("$cdir");
	foreach $dir (@dirs) {
		rec_to("$cdir/$dir", "$curr/$dir", $arg, $call);
	}
	eval "$call(\"$curr\", \"$arg\")";
}

sub copy_if_older {
    my ($from, $to) = @_;
    @stat1 = stat "$from";
    @stat2 = stat "$to";
    if ($stat1[9] > $stat2[9]) {
	print "cp $to\n";
	system("cp $from $to");
    }
}

sub remove_last_path_level {
    my ($path) = @_;
    if ($path =~ /\//) {
	@pathlist = split(/\//, $path);
	pop(@pathlist);
	return join('/', @pathlist);
    }
    if ($path =~ /\\/) {
	@pathlist = split(/\\/, $path);
	pop(@pathlist);
	return join('\\', @pathlist);
    }
    return $path;
}

# ====================================
# Prepare ACE environment
# ====================================

sub unix_to_win {
    my ($cnv) = @_;
    if ($cnv =~ /cygdrive/) {
        $cnv =~ s/\/cygdrive\/(\w+)/$1:/;
    } else {
        $cnv =~ s/\/home\/jan/C:\\cygwin\\home\\jan/;
    }
    $cnv =~ s/\//\\/g;
    print "CNV: '$cnv'\n";
    return $cnv;
}

sub cond_unix_to_win {
    my ($cnv) = @_;
    if ($aceos eq "Windows") {
        return unix_to_win($cnv);
    } else {
        return $cnv;
    }
}

$ENV{"OS"} = $aceos;
$ENV{"EII_SRC_DIR"} = "$ENV{SRC_DIR}";
unless (defined($ENV{"EII_ODBC_DIR"})) {
    $ENV{"EII_ODBC_DIR"} = "/home/wimv/iODBC/solaris/";
}

$crdirenv = $CURRENT_DIR;
$crdirenv =~ s/\/cygdrive\/(\w+)\//$1:\//;
if ($cygwin_home ne "") {
	$crdirenv = $cygwin_home . $crdirenv;
	print "Dir: $crdirenv\n";
}
$ENV{"CURRENT_DIR"} = $crdirenv;
$ENV{"HARDWARE"} = "$hostname: $hw running $OS";

if ($writecmd) {
    print "###\n";
    print "SRC_DIR=\"$ENV{SRC_DIR}\"\n";
    print "EII_SRC_DIR=\"$ENV{EII_SRC_DIR}\"\n";
    print "EII_ODBC_DIR=\"$ENV{EII_ODBC_DIR}\"\n";
    print "CURRENT_DIR=\"$ENV{CURRENT_DIR}\"\n";
    print "HARDWARE=\"$ENV{HARDWARE}\"\n";
    print "export SRC_DIR EII_SRC_DIR EII_ODBC_DIR CURRENT_DIR HARDWARE\n";
}

if (defined($ld_library_path{$compiler}{$aceos})) {
    $ENV{"LD_LIBRARY_PATH"}= "$ld_library_path{$compiler}{$aceos}:$ENV{LD_LIBRARY_PATH}";
    if ($writecmd) {
	print "LD_LIBRARY_PATH=$ENV{LD_LIBRARY_PATH}\n";
	print "export LD_LIBRARY_PATH\n";
    }
}

$GAPIC_COMPILER = $ENV{GAPIC_COMPILER};
if ($aceos eq "Windows") {
    $GAPIC_COMPILER = "perl $UTIL_DIR/aceexe/gapic_compile.cygwin";
} elsif ($GAPIC_COMPILER eq "") {
	$GAPIC_COMPILER = "g++";
}
if (defined($opt_S)) {
	$GAPIC_COMPILER = $GAPIC_COMPILER . " -DSAFECODE";
}
$ENV{GAPIC_COMPILER} = $GAPIC_COMPILER;

if ($is_package == 1) {
	if ($compiler =~ /ilp/) {
		if (defined($ENV{ACE_MAIN_SRC})) {
			$MAIN_SRC = $ENV{ACE_MAIN_SRC};
			print "Using ACE source distribution: $MAIN_SRC\n";
			$ENV{LD_LIBRARY_PATH}="$MAIN_SRC/V-$version/src.$compiler/$aceos/so:".$ENV{LD_LIBRARY_PATH};
			$ENV{SO_DIR} = "$MAIN_SRC/V-$version/src.$compiler/$aceos/so";
			$ENV{SRC_DIR} = "$MAIN_SRC/V-$version/src.$compiler/$aceos";
		} else {
    			$ACE_ILP_ROOT = remove_last_path_level($ENV{ACE_ILP_ROOT});
		    	$ACE_ILP_ROOT = "$ACE_ILP_ROOT/$smallos";		
			if ($smallos =~ /windows/) {
				$ENV{SO_DIR} = cond_unix_to_win("$ACE_ILP_ROOT/bin");
				$ENV{SRC_DIR} = cond_unix_to_win("$ACE_ILP_ROOT/lib");
				$ENV{ILP_HOME} = cond_unix_to_win("$ACE_ILP_ROOT/bin");
				$ENV{PROLOG_INC} = cond_unix_to_win("$ACE_ILP_ROOT/lib/gapic");
				$ENV{PROLOG_LIB} = cond_unix_to_win("$ACE_ILP_ROOT/bin");
    				$engine{$compiler}{$aceos} = "$ACE_ILP_ROOT/bin/$engine{ilp}{Linux}";
			} else {
				$ENV{ACE_ILP_ROOT} = $ACE_ILP_ROOT;			
				$ENV{LD_LIBRARY_PATH}="$ACE_ILP_ROOT/lib/so:".$ENV{LD_LIBRARY_PATH};
				$ENV{SO_DIR} = "$ACE_ILP_ROOT/lib/so";
				$ENV{SRC_DIR} = "$ACE_ILP_ROOT/lib";
				$ENV{ILP_HOME} = "$ACE_ILP_ROOT/lib/";
				$ENV{PROLOG_INC} = "$ACE_ILP_ROOT/lib/gapic";
				$ENV{PROLOG_LIB} = "$ACE_ILP_ROOT/lib";
    				$engine{$compiler}{$aceos} = "$ACE_ILP_ROOT/lib/$engine{ilp}{Linux}";
		    		$extra_options = "$extra_options --s";
			}
        	}
	} else {
		print "Run stable only supported for ilProlog\n";
	}
} else {
	$ENV{"SRC_DIR"} = cond_unix_to_win("$ACE_DIR/V-$version/src.$compiler/$aceos");
	$ENV{LD_LIBRARY_PATH}="$ACE_DIR/V-$version/src.$compiler/$aceos/so:".$ENV{LD_LIBRARY_PATH};
	$ENV{PROLOG_INC} = cond_unix_to_win($engine_path{$compiler}{$aceos}."/include/hipp");
	$ENV{PROLOG_LIB} = cond_unix_to_win("$ACE_DIR/Util/aceexe");
	$ENV{SO_DIR} = cond_unix_to_win("$ACE_DIR/V-$version/src.$compiler/$aceos/so");
}

# ====================================
# Prepare Prolog-C interface
# ====================================
# problems with the interface? -> contact wimv!

if ($compiler =~ /master/) {  #need to compile all C files - currently only OdbcLow.c
    opendir FROMDIR, "$ACE_DIR/V-$version/src.$compiler/$aceos";
    @allfiles = grep {/\.c$/}  readdir FROMDIR;
    closedir FROMDIR;

    if (defined($makeoptions{$compiler}{$aceos})) {
	chdir("$ACE_DIR/V-$version/src.$compiler/$aceos");
	if ($aceos =~ /Windows/) {
	    foreach (@allfiles) {
		s/\.c/\.obj/;
	    }
	    $command = "nmake $makeoptions{$compiler}{$aceos} @allfiles";
	}
	else {
	    foreach (@allfiles) {
		s/\.c/\.o/;
	    }
	    $command = "make $makeoptions{$compiler}{$aceos} @allfiles";
	}
	&run_command($command);
	chdir("$CURRENT_DIR/.");
    }
}
elsif ($compiler =~ /sicstus/) { #currently only OdbcLow
    			         #for simplicity: only compile if not exists
    				 #checking whether older than sources takes to much code :)
    chdir("$ACE_DIR/V-$version/src.$compiler/$aceos");
    if ($aceos =~ /Windows/) {
	if (! -e "odbclow.dll") {
	    $command = "splfr --cflag=/DEII_WINDOWS --resource=odbclow OdbcLow.pl OdbcLow.c";
	    &run_command($command);
	}
    }
    else {
	if (! -e "odbclow.so") {
	    $command = "/cw/prolog/sicstus/sicstus-yes."."\L$aceos"."/bin/splfr --cflag=-DEII_"."\U$aceos".",-I/home/wimv/iODBC/"."\L$aceos"."/include --resource=odbclow OdbcLow.pl OdbcLow.c /home/wimv/iODBC/"."\L$aceos"."/lib/libodbc.so";
	    &run_command($command);
	}
    }
    chdir("$CURRENT_DIR/.");
}

sub exists_file_type {
	my($dir, $type) = @_;
	@files = <$dir/*.$type>;
	return $#files;
}


if (0) {
	print "export CURRENT_DIR = $ENV{CURRENT_DIR}\n";
	print "export SRC_DIR = $ENV{SRC_DIR}\n";
	print "export ILP_HOME = $ENV{ILP_HOME}\n";
	print "export OS = $ENV{OS}\n";
	print "export HARDWARE = $ENV{HARDWARE}\n";
	print "export LD_LIBRARY_PATH = $ENV{LD_LIBRARY_PATH}\n";
	print "export PROLOG_INC = $ENV{PROLOG_INC}\n";
	print "export SO_DIR = $ENV{SO_DIR}\n";
}

# ====================================
# LAUNCH ACE
# ====================================

if ($makeruntime == 1) {
    chdir("$ENV{SRC_DIR}");
    if ($compiler =~ /master/) {
	    &run_command("PLcomp -y- -c+ -w+ acert.pro");
#	    $ENV{"LD_LIBRARY_PATH"}= '';   #met geeft fout bij linken, zonder bij uitvoeren runtime
	    &run_command("PLlink -ic -vh ACE_RT_DIR -pr -HACEData -po -HACERun - $options{$compiler}{$aceos} -Los/FileSys -Lprolog/ordset -Lprolog/lists -Los/Time -Lprolog/random -Los/ask OdbcLow.pro acert.pro");
	    &run_command("mv ACEData ACERun* $ACE_DIR/RT-$version/$compiler/sys.$aceos");
	    chdir("$CURRENT_DIR/.");
	    exit;
    }
    if ($compiler =~ /ilp/) {
	    $RT_DIR = get_runtime_dir();
	    print "\nCleaning up runtime directory $RT_DIR/$smallos/lib\n";
	    main_cleanup_dir("$RT_DIR/$smallos/lib");
	    copy_ilprolog($engine_path{$compiler}{$aceos}, "$RT_DIR/$smallos/lib", "$RT_DIR/$smallos/bin");
	    copy_ace("$ACE_DIR/V-$version/src.$compiler/$aceos", "$RT_DIR/$smallos");
	    copy_util("$ACE_DIR/Util", "$RT_DIR/util");
	    copy_examples("$ACE_DIR", "$RT_DIR/examples");
	    strip_binaries("$RT_DIR/");
	    make_tar($RT_DIR, "ilProlog");
    }
    if ($compiler =~ /sicstus/) {
	    $RT_DIR = get_runtime_dir();
	    print "\nCleaning up runtime directory $RT_DIR/$smallos/lib\n";
	    main_cleanup_dir("$RT_DIR/$smallos/lib");
	    copy_ace("$ACE_DIR/V-$version/src.$compiler/$aceos", "$RT_DIR/$smallos");
	    make_tar($RT_DIR, "sicstus");
    }
    print "Sorry, no runtime for $compiler\n";
} else {
	if ($#ARGV == -1) {
	    $aceargs = `ls *.s 2>/dev/null`;
	    chop($aceargs);
	} else {
	    $aceargs = "@ARGV";
	}
	if ($condor == 1) {
		$appname = $aceargs;
		$appname =~ s/\.s//;
		$jobname = "job-$appname";
		ensuremkdir("$CURRENT_DIR/tilde");
		ensuremkdir("$CURRENT_DIR/warmr3");
		ensuremkdir("$CURRENT_DIR/condor");
		$ENV{"GAPIC_STATIC"} = 1;
		open(OUT, ">$CURRENT_DIR/condor/$jobname.job");
		print OUT "environment = \"GAPIC_STATIC=1 CURRENT_DIR=$ENV{CURRENT_DIR} SRC_DIR=$ENV{SRC_DIR} ILP_HOME=$ENV{ILP_HOME} OS=Linux HARDWARE=condor PROLOG_INC=$ENV{PROLOG_INC} SO_DIR=$ENV{SO_DIR} HOME=$ENV{HOME} USER=$ENV{USER}\"\n";
		print OUT "executable = $ACE_DIR/V-$version/src.$compiler/$aceos/ACE\n";
		print OUT "arguments = \"$options{$compiler}{$aceos} $extra_options $ENV{SRC_DIR}/ace -a $aceargs\"\n";
		print OUT "output = $CURRENT_DIR/condor/$jobname.out\n";
		print OUT "error = $CURRENT_DIR/condor/$jobname.err\n";
		print OUT "log = $CURRENT_DIR/condor/$jobname.log\n";
		print OUT "requirements = memory >= 1000\n";
		print OUT "rank = (machine == \"shampoo.cs.kuleuven.be\") || (machine == \"daneel.cs.kuleuven.be\")\n";
		print OUT "universe = standard\n";
		print OUT "queue\n";
		close(OUT);
		system("rm -f *_ct .$appname.keycode*");
		system("rm -f $CURRENT_DIR/condor/$jobname.out $CURRENT_DIR/condor/$jobname.err $CURRENT_DIR/condor/$jobname.log 2>/dev/null");
		system("touch $CURRENT_DIR/condor/$jobname.out $CURRENT_DIR/condor/$jobname.err $CURRENT_DIR/condor/$jobname.log");
		system("chgrp condorg $CURRENT_DIR $CURRENT_DIR/*.{w,ew,kbi,kbj} 2>/dev/null");
		system("chmod g+w $CURRENT_DIR $CURRENT_DIR/*.{w,ew,kbi,kbj} 2>/dev/null");		
		system("chgrp -R condorg $CURRENT_DIR/tilde $CURRENT_DIR/warmr3 $CURRENT_DIR/condor 2>/dev/null");
		system("chmod -R g+w $CURRENT_DIR/tilde $CURRENT_DIR/warmr3 $CURRENT_DIR/condor 2>/dev/null");
		system("/home/condor/condor_current/bin/condor_submit $CURRENT_DIR/condor/$jobname.job");
		exit(0);	
	}
	if (($compiler eq "yap") && ($OLDYAP == 1)) {
		# The stable version of YAP does not support "-l"
		open(OUTPUT, ">INPUT");
		$srcdir = $ENV{"SRC_DIR"};
		print OUTPUT "['$srcdir/ace'].\n";
		close(OUTPUT);
		print "['$srcdir/ace'].\n";
		$command = "$nicecmd $engine{$compiler}{$aceos} $options{$compiler}{$aceos} $extra_options $aceargs";
	} else {
		if (defined($opt_g)) {
			open(OUTPUT, ">COMMANDS.gdb");
			print OUTPUT "set args $options{$compiler}{$aceos} $extra_options $body{$compiler}{$aceos} $aceargs\n";
			print OUTPUT "run\n";
			close(OUTPUT);
			$ENV{"GAPIC_DEBUG"} = "on";
			$ENV{"GAPIC_STATIC"} = 1;			
			$exepro = "$engine_path{$compiler}{$aceos}/$engine{$compiler}{$aceos}";			
			$exepro = "$ACE_DIR/V-$version/src.$compiler/$aceos/ACE";			
			$command = "gdb --command COMMANDS.gdb $exepro";
		} else {
			if (defined($opt_v)) {
				$command = "valgrind --leak-resolution=high --num-callers=15 --leak-check=yes -v $engine{$compiler}{$aceos} $options{$compiler}{$aceos} $extra_options $body{$compiler}{$aceos} $aceargs";
			} else {
#				$ENV{"GAPIC_STATIC"} = 1;
#				$exepro = "$ACE_DIR/V-$version/src.$compiler/$aceos/ACE";
				$exepro = "$engine_path{$compiler}{$aceos}/$engine{$compiler}{$aceos}";
				print "Running: '$exepro'\n";
				$command = "$nicecmd $exepro $options{$compiler}{$aceos} $extra_options $body{$compiler}{$aceos} $aceargs";
			}
		}
	}
	run_command($command);
}

# ========================================
# Cleanup for load & compile all packages
# ========================================

if (defined($opt_P)) {
	chdir($ACE_DIR);
	cleanup("/tmp/allpackages");
	rmdir("/tmp/allpackages");
}

sub run_command {
    my ($command) = @_;
    if ($writecmd) {
    	print $command."\n"
	}
    else {
    	print $command."\n";
    	system($command);
    }
}


# ----------------------------------------------------------------------
sub print_usage {
    print <<"END_OF_USAGE";

Usage: ACE -h
       ACE [-n nicevalue] [-c compiler] [-o extraoptions] [-D file] [-p]
           [-g] [-S] [-d] [-C] [-W] [-V aceversion] [-P] [-R] [-r] [-s]

Options:
    -h print this help message
    -n nice value (default = $nice_value)
    -c submit a Condor job running ACE
    -m maximum heap size for hipP in MB
    -o set extra options for Prolog engine (as a string!)
    -g use gdb to debug GAPIC code
    -S define SAFECODE when compiling GAPIC code
    -d [match] show class definitions
    -d "depend" show class dependencies  
    -D override defaults of the ACE scripts with this file
    -p toggle \$run_preproc (currently $run_preproc)
    -C clean-up the "src.compiler" directories
    -W write commands
    -V update version number
    -P load & compile all packages
    -R make runtime (currently only for ilProlog and sicstus)
    -r run runtime (currently only for ilProlog and sicstus)
    -s run stable version (using ACE_ILP_ROOT)

Note: use ~/.ace.perl to change defaults in this ACE script.

END_OF_USAGE
}

if ($is_package == 1) {
	return 1;
}
