#!/usr/bin/perl

use Getopt::Long;
use File::Copy;

$correctname=substr($0,0);

use lib "/mt/apps/gpms/DateTrans/lib";
use DateTrans qw(monName monNumber timeFormat AmPmFormat dayNumbeFormat);

use lib "/mt/apps/gpms/DateTrans/lib";
use  xsdxsltcheck qw(xsdcheck xsltcheck FGDC2MRFcheck xsl4mrf2fgdccheck);

use File::Basename;

sub usage() {
    print "Usage: perl $correctname [-directory=<directory>]\n";
    print "Example:\n";
    print "perl $correctname  -directory=/dir/subdir \n";
       print "/dir/subdir is the directory containing the files to be validated\n";

}
%gOptions;
&GetOptions(\%gOptions, qw(directory=s));
unless ($gOptions{directory} ) {
        usage();
        exit(1);
};

#---------------------------------------------file mangement section-1---------------------------------------------------------------------------------------
chomp($indir= $gOptions{directory});
#print "\$indir = $indir\n";
#------------------------------------error trap-------------------------------------------------------------------------------------------------------------
if (-e $indir){
}else{
print "The directory $indir could not be found!!!!\n";
};

#------------------------------------getting the date---------------------------------------------------------------------------------------------------------

my $now=`date`;
$mon = substr($now,4,3);
$day=substr($now,8,2);
$year =substr($now,24,4);
$hour = substr($now,11,2);
$min = substr($now,14,2);
my $daynum= dayNumbeFormat($day);

#converting the date to a number
my $monName=monName($mon);
my $monnum =monNumber($mon);

$dateString =$year . $monnum . $daynum . $hour . $min;

#--------------------setting up the variables and the  output directories-------------------------------------------------------------------------------------------------

$badTransformCounter=0;
$outdir="/mtdata001/geo/gpms/output/fgdc";
$outISO="/mtdata001/geo/gpms/output/ISO";
$logDir="/mtdata001/geo/gpms/log";

$subDirectory= "SeriesCollection" . $dateString;

$newLog =  $logDir . "/" . $subDirectory;
$newDir= $outdir . "/" . $subDirectory; 
$newISO = $outISO . "/". $subDirectory;

$root = "/mt/apps";

system "mkdir $newDir";
system "mkdir $newLog";
system "mkdir $newISO";

#----------------------------------------------------reading in all the files ------------------------------------------------------------------------

opendir INPUTDIR, $indir or die "cannot open $dir: $!";

foreach $file (readdir INPUTDIR){
$CompleteFile = $indir . "/" . $file;
$DirList[$DirListCounter]=$CompleteFile;
$DirListCounter++
};

#-----------------------------------redirecting the output---------------------------------------------------------------------------------------------------
open (SAVEOUT,">&STDOUT");

#----------------------------------------------------------Saxon-----------------------------------------------------------------------------------------

$ENV{'PATH'} = "/apps/saxon/jdk1.5.0_24/bin::/apps/saxon/saxon9ee.jar::/apps/saxon:$rootout/mrf/$newerrdir:$ENV{'PATH'}";

$cp = "CLASSPATH";#goodone
$ENV{$cp} = "/apps/saxon/jdk1.5.0_24/lib/:/apps/saxon/saxon9ee.jar:/apps/saxon/saxon9ee.jar $CLASSPATH:/usr/share/java/saxon.jar";

#--------------------------------------------------------transforming the files-------------------------------------------------------------------------------

foreach $DirList (@DirList){
$LoopDirListCounter++;

$SlashLocation=rindex($DirList,"/")+1;
$NewOutputFileA =substr($DirList,$SlashLocation);

$FileType=substr($NewOutputFileA,0,2);
$SeriesCollection="SeriesCollection_";

if ($FileType  eq "tl"){
$firstPart=substr($NewOutputFileA,0,7);
$lastDash=rindex($NewOutputFileA,"_")+1;
$Theme=substr($NewOutputFileA,$lastDash);
$dotLocation=rindex($Theme,".");
$errTheme=substr($Theme,0,$dotLocation);
$NewOutputFile= $SeriesCollection . $firstPart . "_" . $Theme;
$NewOutputFileError= $SeriesCollection . $firstPart . "_" . $errTheme . ".err";
}elsif($FileType  eq "gz"){
$firstPart=substr($NewOutputFileA,0,7);
$firstDashLoc=index($NewOutputFileA,"_")+1;
$postFirstDash=substr($NewOutputFileA,$firstDashLoc);
$year=substr($postFirstDash,0,4);
$SecondDashLoc=index($postFirstDash,"_")+1;
$SecondDash=substr($postFirstDash,$SecondDashLoc);
$Theme=substr($SecondDash,2);
$errTheme=substr($Theme,0,$dotLocation);

$NewOutputFile= $SeriesCollection . $firstPart . $Theme;
$NewOutputFileError= $SeriesCollection . $firstPart . "_" . $errTheme . ".err";
};

$newPrev= $newDir. "/" .   $NewOutputFile;

if (-e $newPrev){
}else{
if ($NewOutputFile ne $$NewOutputFilePrev){
$TransformCounter++;
print SAVEOUT "$TransformCounter:now making  $NewOutputFile-----------------------------------------\n";
open STDOUT,">$NewOutputFile";
open STDERR, ">$NewOutputFileError";
my @csax = "java com.saxonica.Transform -outval:recover $DirList /mt/apps/gpms/SeriesCollectionXSDs/FGDC2Collection.xsl";
my $mif = system(@csax);
$$NewOutputFilePrev= $NewOutputFile;

if ($mif == 0){
$lastDot=rindex($NewOutputFile, ,".");
$newFGDC=substr($NewOutputFile,0,$lastDot);
$iso_var=  $newFGDC . ".iso.xml";
$iso_var_error = $newFGDC . ".iso.err";
print SAVEOUT "\$iso_var_error = $iso_var_error\n";

open STDOUT,">$iso_var";
open STDERR, ">$iso_var_error";
my @csax = "java com.saxonica.Transform -outval:recover $NewOutputFile  $root/gpms/FGDC2ISO/csdgm2iso19115-2_master.xslt";
my $ISOmif = system(@csax);
close STDERR;


if ($ISOmif == 0){ 
#print SAVEOUT "Now validating $NewOutputFile-------------------------\n";

#$ISOValidation= $iso_var=  $newFGDC . ".Validation.err";
#$ValidFile= $newFGDC . ".iso.xml";

#open STDOUT, ">$ValidFile";
#open STDERR, ">$ISOValidation"; 
#my @viso = "java com.saxonica.validate $NewOutputFile /mt/apps/gpms/ISOSchema/19139/schema.xsd";
#my $giso =system(@viso);

#print SAVEOUT "\$giso = $giso\n";

system "mv $NewOutputFile $newDir";
system "rm $NewOutputFileError";
system "rm $iso_var_error";
system "mv $iso_var $newISO";

#system "rm $NewOutputFile";

$goodTransformArray[$goodTransformCounter]=$NewOutputFile;
$goodTransformCounter++;



}else{
system"mv $NewOutputFile $newLog";
system"mv $NewOutputFileError  $newLog";
$badTransformCounter++;
$badTransform[$badTransformCounter]=$NewOutputFile;
};
};
};
};
};


#system "rm *.xml";
#----------------------------------------------------------------new LogFile----------------------------------------------------------------------------------------------------------------------
$LogName = $subDirectory . ".log";
$NewLogFile=$newLog . "/" . $LogName;

open LOG,">$NewLogFile";
#------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
$total = $badTransformCounter + $goodTransformCounter;

print SAVEOUT "\n A total of $total of input files were converted into Series Collection Files. Of theses $total files $goodTransformCounter files were successfully transformed and $badTransformCounter";
print SAVEOUT  " were not.\n"   ;

print LOG  "A total of $total of input files were converted into Series Collection Files. Of theses $total files $goodTransformCounter files were successfully transformed and $badTransformCounter";
print LOG  " were not.\n"   ;

if ($goodTransformCounter > 0){
print SAVEOUT "The following Collection Series files were created. These files can be seen in the $newDir directory:\n";
print LOG  "The following Collection Series files were created These files can be seen in the $newDir directory: \n";

foreach $goodTransformArray (@goodTransformArray){
if ($goodTransformArray ne ""){
$goodArrayCounter++;
print SAVEOUT "$goodArrayCounter: $goodTransformArray\n";
print LOG "$goodArrayCounter: $goodTransformArray\n";
};

}
print  SAVEOUT "\n\n";
};


if ($badTransformCounter >0){
print SAVEOUT "The following files could not be transformed. Please see the error files at $newLog\n";
print LOG "The following files could not be transformed. Please see the error files at $newLog\n";

foreach $badTransform (@badTransform){
if ($badTransform ne ""){
$badArrayCounter++;
print SAVEOUT "$badArrayCounter:$badTransform\n";
print LOG "$badArrayCounter:$badTransform\n";
};
};
print  SAVEOUT "\n\n"
};



if ($invalidISOCoounter >0){

print SAVEOUT "The following ISO files are invalid:\n";
print LOG "The following ISO files are invalid:\n";

$badISOCounter=1;
foreach $invalidISO (@invalidISO){
print SAVEOUT "$badISOCounter: $invalidISO\n";
print LOG "$badISOCounter: $invalidISO\n";
$badISOCounter++;
};
};
print SAVEOUT "Please see the log file at $NewLogFile. \n";
print SAVEOUT "\n";

