#!/usr/bin/env perl
# dmft_monitor - gathers NRG results and starts a new DMFT iteration
# (c) Rok Zitko, rok.zitko@ijs.si, Sep 2007, Jan, Oct 2008

use warnings;
use Term::ANSIColor qw(:constants);

print "dmft_monitor, Rok Zitko, rok.zitko\@ijs.si, 2007-2008\n";

# Cleanup flag files
unlink("CONVERGED");
unlink("ERROR");

# Initialize directory structure and input files
system("./dmft_init");

while (!-e "STOP") {
    my $cas = localtime(); # current time
    my $notdone = completedp(); # list of tasks to be completed
    print BOLD, "$cas", RESET, " [$notdone]\n";
    my $monfn = "DIFFS_C";
    -e $monfn && system "tail $monfn"; # show energy differences
    iterate() unless $notdone; # when done, new iteration!
    sleep(10); # ten second delay
}

# Returns "" if all jobs completed.
sub completedp {
    my $path = ".";
    opendir(DIR, $path);
    my @dirs;
    @dirs = map  { $_->[1] }                # extract pathnames
    sort { $a->[0] <=> $b->[0] }    # sort names numeric
    grep { -d $_->[1] }             # path is a dir
    map  { [ $_, "$path/$_" ] }     # form (name, path)
    grep { /^\d+$/ }                # just numerics
    readdir(DIR);                   # all files
    closedir(DIR);

    my $done = "";
    foreach $task (@dirs) {
	-e "$task/DONE" or $done = "$done $task";
    }
    return $done;
}

sub iterate {
    if (-d "1") { # Previous iteration detected
	# Postprocess the results
	system("./dmft_done");
	($? != -1) or die "Failed to execute dmft_done, stopped";
	if (-e "ERROR") { die "ERROR, stopped" };
	
	# Have we achieved convergence?
	system("./checkconv");
	($? != -1) or die "Failed to execute checkconv, stopped";
	if (-e "CONVERGED") { die "Convergence achieved, stopped" };
    }
    
    # Initiate new iteration
    system("./param.loop");
    -e "1" or die "param.loop failed? stopped";
}
