#!/bin/perl

# This program searches the KnotDB database for knot types without a mugshot
# then generates corresponding povray views of them in the /mugshots directory.

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


# We start by loading the database.

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

# Now we load the Eric data.

open PBOUND, "<knot_prevbound.dat";

my $cr;
my $num;
my $key;
my %numhash;

foreach (1..50) { 

  my $numword;
  $numword = num2en($_);
  $numword =~ s/\-//g;
  $numword =~ s/^(\w)(\w*)/uc($1).lc($2)/ge;

  $numhash{$numword} = $_; 

}

my $bound;

while (<PBOUND>) {

  if ($_ =~ m/\\newcommand\{\\([A-Z].+?)([A-Z].+?)Prev\}\{(.+)\}/) {

    $cr = $numhash{$1};
    $num = $numhash{$2};
    
    $bound = $3;
    
    $key = $cr."_".$num;
    $knots{$key}{prevbound} = $bound;
    $knots{$key}{prevcite} = "MR2034393";

    print "Found a previous bound of $bound for $key.\n";
    
  }

}

$knots{'3_1'}{prevcite} = "baranska";
$knots{'4_1'}{prevcite} = "mglob";

close PBOUND;

print "Filled in previous bounds from mglob, can computers, and baranska, parsing gilbert.\n";

my @gilglob;
@gilglob = <./vects/*_gilbert.vect>;

my $grepout;
my $claimrop;

foreach (@gilglob) {

  $grepout = `grep \"Claimed Ropelength\" $_`;
  $grepout=~ m/\# Claimed Ropelength: (.+)/;
  $claimrop = $1;

  $_ =~ m/kl_([0-9_]+)_/;
  $key = $1;

  if ($key =~ m/\d+_\d+_\d+/) { $claimrop *= 2; }
  $knots{$key}{gilbertclaim} = $claimrop;

  my $gilfile;
  $gilfile = "kl_".$key."_gilbert.vect";
  
  if (!defined $knots{$key}{prevbound} || $knots{$key}{prevbound} > $knots{$gilfile}{upperbound}) {

    if (defined $knots{$key}{prevbound}) {

      print "Replaced $key bound of $knots{$1}{prevbound} with verified Gilbert bound of $knots{$gilfile}{upperbound}.\n";

    } else {

      print "Added $key verified Gilbert bound of $knots{$gilfile}{upperbound}.\n";

    }

    $knots{$key}{prevbound} = $knots{$gilfile}{upperbound};
    $knots{$key}{prevcite} = "gilbert";

  }

}

print "Updated with Gilbert bounds.\n";	   
print "Writing updated database to KnotDB.pl ...\n";
rename "KnotDB.pl","KnotDB.bak.pl" or die("Couldn't rename the old knot database.\n");

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

