#!perl
#
#

use strict;
use warnings;
use File::Slurp;
use File::Copy;
use File::Temp;
use Getopt::Long;
use Cwd;

print "pulldata 1.0\n";

my $knots;
my @knotlist;
my $names;
my $cwd;

$cwd = getcwd;

GetOptions ( 'knots=s' => \$knots, 'namesonly' => \$names);

if ($knots) {
  $knots =~ s/\s//g;
  @knotlist = split( /,/ , $knots);
} else {
  print "Usage: pulldata --knots=<knots> --namesonly\n";
  print "       We expect the <knots> list to contain a list of comma-separated knot types.\n";
  die();
}

print "Assembling list of ".scalar @knotlist." knot types.\n";
print "Opening KnotDB.pl\n";

#open(DB,'KnotDB.pl');
my $DBFILE = read_file("${cwd}/knotdb/KnotDB.pl") or die("Couldn't open $cwd/knotdb/KnotDB.pl");
my %knots;
eval($DBFILE);

my $thisknot;
my @data;

foreach $thisknot (@knotlist) {

  my $filename;
  $filename = $thisknot."_configs.dat";

  open (KO,">${cwd}/data/$filename") or die("Couldn't open ${cwd}/data/$filename\n");

  my $thisfile;

  foreach $thisfile (@{$knots{$thisknot}{allfiles}}) {

    if ($knots{$thisfile}{residual} < 0.01) {

      unless ($names) {

	print KO "$thisfile, $knots{$thisfile}{upperbound}, $knots{$thisfile}{writhe}, ".$knots{$thisfile}{edges}/$knots{$thisfile}{upperbound}.", $knots{$thisfile}{residual} \n";

      } else {

	print KO "$thisfile\n";

      }

    }

  }

  close KO;

  print "$thisknot data -> $filename\n";

}
