#!/usr/bin/perl



$FGDCDir="/prodmtdata001/geo/gpms/output/fgdc";
$TargetDir="/home/m/mccre004/GPMSscripts/FileMoverDir";

opendir DHFGDC, $FGDCDir;

$beginCounter=16650;

$endCounter=$beginCounter+100;

#$counter=$beginCounter;

foreach $dir (readdir DHFGDC){
#print "\$dir = $dir\n";

if ($counter >=$beginCounter and $counter<=$endCounter and $dir ne  "." and $dir ne ".."){

print "\$beginCounter = $beginCounter\n";
print "\$endCounter = $endCounter\n"; 
print "$counter: \$dir = $dir\n";
print "----------------------------------------------\n";

$FGDCoutputFile = $FGDCDir . "/" . $dir; 
#print "\$FGDCoutputFile = $FGDCoutputFile";

opendir FGDCFILE, "$FGDCoutputFile";

foreach $file (readdir FGDCFILE){
#print "\$file = $file\n";
$FGDCoutputFileB = $FGDCoutputFile . "/" . $file;
#print "\$FGDCoutputFileB = $FGDCoutputFileB\n";

$postSecond=substr($file,8);
#print "\$postSecond = $postSecond\n";
$UnderScoreLocation=index($postSecond,"_")+1;
$dotLocation=index($postSecond,".");
$Themelength=$dotLocation-$UnderScoreLocation;

$Theme=substr($postSecond,$UnderScoreLocation,$Themelength);
#print "\$Theme = $Theme\n";

$ThemDir = $TargetDir ."/" . $Theme;
$ThemDirFile = $ThemDir . "/" . $file;

if (-e $ThemDir){

}else{
system "mkdir $ThemDir";
};


if (-e $ThemDirFile){

$AgeThemDirFile = -M $ThemDirFile;#already moved
$AgeFGDCoutputFile = -M $FGDCoutputFile;#to be moved

if (  $AgeFGDCoutputFile <$AgeThemDirFile){
system "cp $FGDCoutputFileB $ThemDir";
$moveCounter++;
};

}else{

system "cp $FGDCoutputFileB $ThemDir";
$moveCounter++;
};#if (-e $ThemDirFile){


};# foreach $file (readdir FGDCFILE){

$counter++;
}else{
#print "not reading directory\n";
$counter++;

};#if ($counter >=$beginCounter and $counter<=$endCounter and $dir ne  "." and $dir ne ".."){

#$counter++;
#}else{
#print "not reading directory\n";
#$counter++;
};# foreach $dir (readdir DHFGDC){a

print "$counter directories under $FGDCDir have been opened and $moveCounter files have been moved to $TargetDir (\$endCounter = $endCounter)\n"; 
