#!/bin/perl

# This program searches the current directory, presumably full of gridstuffer output, and extracts the 
# .final.vect files, renaming them, and copying them to the current directory.

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

# We start by looking for subdirectories.

my @subdirs;
@subdirs = <*>;

my $cwd;

$cwd = getcwd;

print "Found ".scalar @subdirs." potential output directories.\n";

foreach (@subdirs) {
  
  next unless -d "$cwd/$_";

  chdir "$cwd/$_" or die("Could not read directory $_\n");
  
  my @knotdirs;
  @knotdirs = <*.rr>;
    
  my $rrdir;
  
  foreach $rrdir (@knotdirs) {
    
    chdir $rrdir or die("Could not read directory $rrdir\n");
    
    my @finalfiles;
    @finalfiles = <*.final.vect>;
    
    my $oldname;
    my $newname;
    
    $oldname = $finalfiles[0];

    my @namebits;

    @namebits = split('\_',$oldname);

    $newname = "kl_$namebits[1]_$namebits[2]_$namebits[3]_r1e-2.vect";
    
    copy($oldname,"../../$newname");
    
    print "Copied $oldname to $newname.\n";
    
  }

}

die("done");
