#!/bin/perl

# This program searches the KnotDB database for knot types, then checks that their mugshots
# exist and correspond to the current correct filename.

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. Checking mugshots...\n";
chdir "./mugshots" or die("Couldn't get to ./mugshots:$_\n");

my $key;

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

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

	delete $wknots{$key};

    } elsif (!defined($wknots{$key}{mugshot})) {

	delete $wknots{$key};

    } elsif (defined($wknots{$key}{bestside})) {

	delete $wknots{$key};

    }

}

my $numsides = keys ( %wknots );

print "A best side has not been picked for $numsides entries in the database.\n";
print "User will pick best sides now. Input 1 for left, 2 for middle, 3 for right hand image.\n";

foreach $key ( keys ( %wknots )) {

    

    } else {

	my $filebase;

	$filebase = $wknots{$key}{filename};
	$filebase =~ s/.vect//;

	if ($wknots{$key}{mugshot}[0] ne $filebase.".a0.jpg") { # doesn't match file

	    print("The mugshot file $wknots{$key}{mugshot}[0] doesn't match the filename $wknots{$key}{filename}. Deleting the record.\n");
	    
	    delete $knots{$key}{mugshot};

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

		delete $knots{$key}{bestside};

	    }

	}

    }

}

print "Updated knots database. Writing ProposedKnotDB.pl.\n\n";

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