#!/sw/bin/perl

# Checks the KnotDB.pl database against the list of knot files, and runs spreadvect if needed.

use strict;
use warnings;
use Lingua::EN::Numbers qw(num2en num2en_ordinal);
use File::Slurp;
use Data::Dumper;
use POSIX;

my $DBFILE = read_file('KnotDB.pl');
my %knots;

eval($DBFILE);

my $numkeys = keys ( %knots );
print "Loaded KnotDB. Scanning $numkeys entries for files with no upperbound.\n";

my $key;
my $upperbound;
my $num;

foreach $key ( keys ( %knots ) ) {

    if ($key =~ /.vect/ and !defined($knots{$key}{upperbound})) { $num++; }

}

print "Found $num such entries. Now running roundout_rl on these entries.\n";

#Now we check for entries that have no upperbound.



foreach $key ( sort(keys %knots) ) {

    if ($key =~ /.vect/) {

	if (!defined($knots{$key}{upperbound})) {

	    print "Running roundout_rl on ".$key."\n";
	    open(ROUNDOUT,"/usr/local/bin/roundout_rl -a 0.001 2>/dev/null vects/'$key' |");
	    while (<ROUNDOUT>) {
		if (/e\^2-Upper Bound: (\d\S+)/) { # Depending on the radius one being second
		    $upperbound = $1;
		}
	    };

	    defined($upperbound) or die("roundout_rl failed on '$key'");

	    print "Epsilon\^2 upperbound of ".$upperbound."\n";

	    $knots{$key}{upperbound} = $upperbound;

	    # Now we have to update the knot entry with the new upperbound.

	    my @parts;
	    die "Couldn't parse filename '$key'" unless 
		@parts = ($key =~ /kl_(\d+_\d+(?:_\d+)?)_([A-Za-z1-9_.]+).vect/i) or
		@parts = ($key =~ /kl_(g[\d.g-]+g)_([A-Za-z1-9_.]+).vect/i);
	    my $crossings;
	    if ($parts[0] =~ /^\d/) {
		($crossings) = ($parts[0] =~ /^(\d+)/);
	    } else {
		my @crossings = sort { $a <=> $b } 
		map { abs($_) } grep { $_ } split(/[.g]+/,$parts[0]);
		$crossings = $crossings[-1];
	    }

	    # Go ahead and update the database.

	    unless (defined($knots{$parts[0]}{upperbound})) {

		$knots{$parts[0]}{upperbound} = 50000;

	    }
	    
	    unless (defined($knots{$parts[0]}) and 
		    (!defined($knots{$parts[0]}{upperbound}) or $knots{$parts[0]}{upperbound} <= $upperbound) and $parts[0] !~ /open/) {
			print "Updating DB with new values.\n";

			$knots{$parts[0]} = {
			    filename => $key,
			    edges => $knots{$key}{edges},
			    edgelength => $knots{$key}{edgelength},
			    ropelength => $knots{$key}{ropelength},
			    upperbound => $knots{$key}{upperbound}
			} 
			
			
		    } else {

			print "DB upperbound of '$knots{$parts[0]}{upperbound}' better.\n";

		    }
	    
	    
	}
	
	
    }

}

# Write out the new database
open(KNOTDB,'>ProposedKnotDB.pl') or die "Unable to create Knot database.";
print KNOTDB Data::Dumper->Dump([\%knots],['*knots']),"\n";
close KNOTDB;
