#!/usr/bin/perl

# Modified by Michael Banck <mbanck@debian.org> to run
# during the mpqc-build process

# If this is set to run, then runs involving the largest
# basis sets will be skipped.
$small = 1;

# This is the number of jobs that will be run concurrently.
$maxjobs = 2;

# The path to the MPQC executable
$mpqc = "../../../../../../debian/tmp/usr/bin/mpqc";

# So that MPQC finds its basis files
$ENV{SCLIBDIR} = "../../../../../../debian/tmp/usr/share/mpqc";

######################################################################

# autoflush output
$| = 1;

if ($ARGV[0] eq "-readdir") {
    opendir(DIR,".");
    @files = sort(readdir(DIR));
    closedir(DIR);
}
else {
    @files = sort(@ARGV);
}

$n = 0;
foreach $j (@files) {
    if (!($j =~ /\.in$/)) { next; }
    $out = "$j";
    $out =~ s/\.[^.]*$/.out/;
    printf "%s ", $out;
    $issmall = (!($j =~ /ccpc?v[tq5]z/));
    $can_run_concurrent = ! ($j =~ /^ckpt_[0-9]/);
    if ($small && $issmall != 1) {
        printf "skipping possibly big job\n";
    }
    elsif ( -f $out && ( -M $out < -M $j && -M $out < -M "$mpqc") ) {
        printf "skipping file that is up-to-date\n";
    }
    else {
        if (! $can_run_concurrent || $maxjobs == 1) {
            printf "starting in foreground\n";
            $pid = fork();
            if ($pid == 0) {
                exec("$mpqc -o $out $j");
            }
            waitpid($pid,'');
        }
        else {
            if (fork() == 0) {
                exec("$mpqc -o $out $j");
            }
            printf "started\n";
            $n = $n + 1;
        }
    }
    while ($n >= $maxjobs) {
        wait();
        $n = $n - 1;
    }
}

foreach $i (1..$n) { wait(); }
