#!/bin/perl

#
# This program searches the KnotDB database for knot types, then checks for the corresponding files.
#

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

my @vectlist;
@vectlist = </home/us/TKWorking/vects/*.vect>;

print scalar @vectlist. " vect files found by globbing in ./vects \n";

# Now we need to group these by knot type;

my %types;

foreach (@vectlist) {

    my $ktype;
    my $tag;

    $_ =~ /\/home\/us\/TKWorking\/vects\/(.+)\_(.+)\.vect/;

    $ktype = $1;
    $tag = $2;

    push @{ $types{$ktype} }, $tag;

}

print scalar keys(%types) . " knot types found.\n";

my @typesA = keys(%types);
#print $typesA[1];

print "Examples of tags associated to a knot type.\n";

print "type = kl_3_1\n";
print "@{$types{'kl_3_1'}}\n\n";

print "type = kl_3_1_#_9_32\n";
print "@{$types{'kl_3_1_#_9_32'}}\n\n";

print "type = kl_3_1_#_9_32_r\n";
print "@{$types{'kl_3_1_#_9_32_r'}}\n\n";

print "type = kl_3_1_#_9_32_m\n";
print "@{$types{'kl_3_1_#_9_32_m'}}\n\n";

print "type = kl_3_1_#_3_1_#_3_1\n";
print "@{$types{'kl_3_1_#_3_1_#_3_1'}}\n\n";

print "Now assembling vect files by knot types into .tar.gz files.\n";

foreach (@typesA) {

    my $dirname;
    my @files;
    my @locfiles;
    my $ktype;
    my $tag;

    $dirname = $_;
    $ktype = $_;

    foreach $tag (@{$types{$ktype}}) {

	push @files, "${ktype}_${tag}.vect";
	push @locfiles, "./vects/${ktype}_${tag}.vect";
    }

    `mkdir ./vects/$ktype`;
    `cp @locfiles ./vects/$ktype/`;
    `cd ./vects; tar -czf ${ktype}.tar.gz ./${ktype}/; cd ..`;

}

print "Created .tar.gz files of knot types.\n";
