#!/bin/perl
use strict;
use warnings;
use File::Slurp;
use File::Path;
use Data::Dumper;
use Getopt::Long;


print STDERR "addWrite.pl: adds writhing numbers to the KnotDB.pl database.\n";

my $force = '';

GetOptions ( 'force' => \$force );

# 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 writhes...\n";

my $key;

unless ($force) {

  # first, a pass to remove files with writhes from the hash
 
  foreach $key ( sort(keys %wknots) ) {
    
    if (defined($wknots{$key}{writhe})) {
      
      delete $wknots{$key};
      
    }
    
  }
  
  $numkeys = keys ( %wknots );
  print "There seem to be $numkeys knot types in the database without writhes. Generating writhes now.\n";

} else {

  print "Force mode means we will recompute writhes for all ".keys ( %wknots )." files.\n";

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

my $filename;
my $writhe;

foreach $key ( keys %wknots ) {

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

    print "Processing knot type $key, represented by filename $filename.\n";

    $writhe = undef;

    print "Running writhecomp . . .\n";
    open(WRITHE,"kpwrithe --file=$filename | ");
    while (<WRITHE>) {
	if ($_ =~ m/writhe:\s+(\S+)/) { 
	    $writhe = $1;
        }
    }
    close WRITHE;

    $knots{$key}{writhe} = $writhe;
    print "Computed writhe = $writhe.\n\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;

