#!/bin/perl

# This program searches the KnotDB database for knot types without Cr/Comp/Ind data
# then adds the corresponding data by parsing the filename. 

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

require 'tightknot_common.pl';

print STDERR "addCrCompInd.pl: adds Cr/Comp/Index data 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 Cr/Comp/Ind...\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}{cr}) && defined($wknots{$key}{comp}) && defined($wknots{$key}{index})) {
      
      delete $wknots{$key};
      
    }
    
  }
  
  $numkeys = keys ( %wknots );
  print "There seem to be $numkeys knot types in the database without Cr/Comp/Index data.\n";
  print "Generating data now.\n";

} else {

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

}
  
my $filename;

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";

    my %fname_stuff;

    %fname_stuff = parsefilename( $filename );

    $knots{$key}{cr} = $fname_stuff{cr};
    $knots{$key}{comp} = $fname_stuff{comp};
    $knots{$key}{index} = $fname_stuff{index};

    print "Computed cr/comp/index = $knots{$key}{cr}/$knots{$key}{comp}/$knots{$key}{index}.\n\n";

}

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;

