# This program applies a whitten operation to all the files in a tar and replaces their filenames with a canonical form.
#

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

my $line;
my %Reversible;
my %NoSymmetry;
my %FullSymmetry;
my %PlusAmphichiral;
my %MinusAmphichiral;

my $input_tar = '';
my $whitten_op = '';
my $new_name = '';

my $cwd;

$cwd = getcwd;

GetOptions ( 'newname=s' => \$new_name, 'inputtar=s' => \$input_tar, 'whittenop=s' => \$whitten_op);

unless (defined $input_tar && defined $whitten_op && defined $new_name) {

  die("usage (example): mkCanonical --newname=\"3_1_#_4_1\" --inputtar=\"kl_3_1_r_#_4_1_r.tar.gz\" --whittenop=\"(1,-1,e)\" \nwill apply whittenop to each file in inputtar, changing each knot type to newname.\n");

}

unless (-f "${cwd}/vects/$input_tar") {

  die("Couldn't find ${cwd}/vects/$input_tar.\n");

}

chdir("${cwd}/vects") or die ("Couldn't chdir to ${cwd}/vects");

print "Untarring ${cwd}/vects/$input_tar...\n";
print `tar -xvzf ${cwd}/vects/$input_tar`;

my $tardir = $input_tar;
$tardir =~ s/\.tar\.gz//g;

unless (-d "${cwd}/vects/$tardir") {

  die("Couldn't unpack ${cwd}/vects/$input_tar to ${cwd}/vects/$tardir.\n");

}

chdir("${cwd}/vects/$tardir") or die("Couldn't chdir to ${cwd}/vects/$tardir\n");

my @vects;
@vects = <*.vect>;

print "Found ".scalar @vects." vect files to salvage in ${cwd}/vects/$tardir. Will apply $whitten_op and rename to knot type $new_name.\n";

my $file;
my $tag;

foreach $file (@vects) {

  $file =~ /kl_.+_(.+)\.vect/;
  $tag = $1;
  $tag = $tag."saved";

  `whittenvect -o \"$whitten_op\" --output=${cwd}/vects/kl_${new_name}_${tag}.vect $file`;
  
  if (-f "${cwd}/vects/kl_${new_name}_${tag}.vect") {

    print "$file -> ${cwd}/vects/kl_${new_name}_${tag}.vect\n";

  } else { 

    die("Run of whittenvect -o \"$whitten_op\" --output=${cwd}/vects/kl_${new_name}_${tag}.vect $file seems to have failed.\n");

  }

}

chdir("${cwd}") or die("Couldn't chdir to ${cwd}.\n");
rmtree("${cwd}/vects/$tardir") or die("Couldn't remove ${cwd}/vects/$tardir");


 
