#!/bin/perl

use strict;
use warnings;
use File::Slurp;
use File::Path;
use Data::Dumper;

# We start by loading the database.

my $key;

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

my %wknots = %knots;

#foreach $key ( %knots ) {

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

#	delete $wknots{$key};

#    }

#}

my $numkeys = keys ( %wknots );
print "We have $numkeys knot and link types in the original database. Looking for knot types without mrlocs...\n";

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

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

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

	delete $wknots{$key};

    }

}

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

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

my $filename;
my $mrlocs;

foreach $key ( keys %wknots ) {

    if ($key =~ /vect/) {

	$filename = $key;

    } else {

	$filename = $wknots{$key}{filename};

    }

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

    $mrlocs = undef;

    open(MRLOCS,"mrlocs $filename -r 0.5 --nofile | ");
    while (<MRLOCS>) {
	if ($_ =~ m/mrlocs: (\S+) mrlocs found\./) { 
	    $mrlocs = $1;
        }
    }
    close MRLOCS;

    $knots{$key}{mrlocs} = $mrlocs;
    print "$mrlocs \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;

