#!/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;

# We start by loading the database.

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

my %wknots = %knots;

my $numkeys = keys ( %wknots );
print "We have $numkeys entries in the original database. Looking for files without rconds...\n";

# first, a pass to remove files with rconds from the hash

my $key;

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

    if (defined($wknots{$key}{rcond})) {

	delete $wknots{$key};

    }

}

$numkeys = keys ( %wknots );
print "There seem to be $numkeys knot types in the database without rconds. Generating rconds now.\n";

chdir "./vects" or die "Couldn't change to ./vects: $_";

my $filename;
my $rcond;

foreach $key ( keys %wknots ) {

    if ($key =~ /vect/) { # If the key contains "vect", it is a filename
	$filename = $key;
    } else {
	$filename = $wknots{$key}{filename};
    }

    print "$key ($filename) : rcond -> ";

    $rcond = undef;

    open(RCOND,"rcond $filename | ");
    while (<RCOND>) {
	if ($_ =~ m/Rcond: (\S+)/) { 
	    $rcond = $1;
        }
    }
    close RCOND;

    $knots{$key}{rcond} = $rcond;
    print "$rcond \n";

}

chdir("..") or die("Couldn't change back out of ./vects");

print "Writing updated database...\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;

