#
#
# check_composite_filenames.pl : Check filenames against knottype to make sure that files are correctly labelled.
#
#

my @files;
chdir("./compositevects");
@files = <*.vect>;

my $file;

foreach $file (@files) {

  $tag = "";

  # First, we parse the existing filename

  my $parsedfile;
  $parsedfile = $file;
  $parsedfile =~ s/kl\_//g;
  $parsedfile =~ s/\.vect//g;
  $parsedfile =~ s/r_m/mr/g;
  
  my @fname_summands;
  @fname_summands = split(/\_\#\_/,$parsedfile);
  my $lastguy;
  $lastguy = pop(@fname_summands);

  #print "Lastguy -> $lastguy\n";
  my $ktype;

  if ($lastguy =~ m/(\d+\_\d+)\_(.+)/) {
    
    my @modarray;
    
    $ktype = $1;
    @modarray = split(/\_/,$2);
    
    if ($modarray[0] =~ /^(m|r|rm|mr)$/) {
      
      $ktype = $ktype."_".$1;
      shift(@modarray);
      $tag = join("_",@modarray);
      
    } else {
      
      $tag = join("_",@modarray);
      
    }

  } else {

    $ktype = $lastguy;

  }

  #print "ktype -> $ktype, tag -> $tag.\n";
  
  push(@fname_summands,$ktype);
  @fname_summands = sort(@fname_summands);

  # We now need to check the knot type for this knot.
  
  my @knottypes;
  open(KNOTTYPE, "knottype -qk $file |");
  while (<KNOTTYPE>) {
    if ($_ =~ m/\|(.+)\|/) {
      push(@knottypes,$1);
    } 
  }
  close KNOTTYPE;

  # We now display the results of the comparison.

  my $knottype; 

  my $notok;
  $notok = 1;
  my @export_summands;

  foreach $knottype (@knottypes) { 

    # We now change from the Whitten group notation to the m|r|mr notation.
    
    $knottype =~ s/\(1,1,e\)/e/g;
    $knottype =~ s/\(-1,1,e\)/m/g;
    $knottype =~ s/\(1,-1,e\)/r/g;
    $knottype =~ s/\(-1,-1,e\)/mr/g;
    $knottype =~ s/ /\_/g;
    $knottype =~ s/></:/g;
    $knottype =~ s/<//g;
    $knottype =~ s/>//g;
    $knottype =~ s/\_e//g;
    
    my @summands;
    @summands = split(/:/,$knottype);
    @summands = sort(@summands);
    
    # We can now compare the lists of summands. 
    
    # print ("(computed summands) : @summands \n");
    
    my $diff_flag = 0;
    my $i;
    
    if (scalar @summands ne scalar @fname_summands) { 

      $diff_flag = 1;
      
    } else {
      
      foreach $i (0..$#summands) {
	
	if ($summands[$i] ne $fname_summands[$i]) { $diff_flag = 1; }
	
      }

      @export_summands = @summands;

    }

    if ($diff_flag == 0) { $notok = 0; }

  }
       
  if ($notok) { 

    print ("$file tag -> $tag\n");
    print ("(summands         ) : @fname_summands \n");
    print ("(computed summands) : @export_summands \n");

    my $newfname;
    $newfname = "kl_".join("_#_",@export_summands)."_${tag}Corrected.vect";

    print("DIFFERENT. Filename should be $newfname.\n");

  }

}
 
