#! /usr/bin/perl -w

use File::Copy qw(copy);
use File::Copy qw(move);
use Cwd;

#present directory
$root = cwd();

opendir my $dh, $root
  or die "$0: opendir: $!";

my @dirs = grep {-d "$root/$_" && ! /^\.{1,2}$/} readdir($dh);

foreach $subdir (@dirs) {
  print "$subdir\n";

  $oldname=$subdir;
  $subdir =~  s/(?<!^)(\s|,)(?!$)/_/g;
  $subdir =~  s/\(|\)/_/g;
  move($oldname,$subdir);

  chdir($subdir);

  @files = glob('*.csv');
  foreach $file(@files){
    $oldname=$file;
    $file =~  s/(?<!^)(\s|,)(?!$)/_/g;
    $file =~  s/\(|\)/_/g;
    move($oldname,$file);
  }

  mkdir("Tmp");
  system("mv *.csv Tmp/");

  print("cat ./Tmp/*.csv | sed '/^[DE]/d' > $subdir.csv\n");
  system("cat ./Tmp/*.csv | sed '/^[DE]/d' > $subdir.csv");


  chdir($root);
}
