#!/usr/bin/perl

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

$preCorrect = substr($0,0,2);

$correctname=substr($0,0);
#print "\$correctname = $correctname\n";

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 [-file=<file>][-output_dir=<output_dir>][-profile=<profile>]\n";
    print "Example:\n";
    print "perl $correctname -file=filename -output_dir=outputDirectory -profile=profile \n";
    print "where -file is the full path of the file to be validated\n";
    print "-output_dir is the full path where the newly created files are going\n";
    print "and -profile is the profile of the file. This value is either v for vector files or k for KML files\n";
};

%gOptions;
&GetOptions(\%gOptions, qw(file=s output_dir=s profile=s));
unless ($gOptions{file} and $gOptions{output_dir} and $gOptions{profile}) {
        usage();
        exit(1);
};

#print "This program is working!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n";
print "\nversion: MRF2ISO_FGDC_Single_Ver1\n";


#---------------------------------------------------------------constansts----------------------------------------------------------------------
$root = "/mt/apps";
#          /mtdata/geo/shpgen/tigerline/fe_2007/
$rootout="/mtdata/geo";

#--------------------------------------------------------------dealing with the directory-------------------------------------------------------------
chomp($FullFile=$gOptions{file});
chomp($outDir=$gOptions{output_dir});
chomp($profile=$gOptions{profile});

#print "\$FullFile = $FullFile\n";
#print "\$outDir = $outDir\n";
#print "\$profile= $profile\n";

$stylesheet ="$root/gpms/FGDC2MRF/MIF2MRF.xsl";
$SeriesInfo="$rootout/gpms/output/ISOParent";
$EADir= "EAFiles";
chmod 0777, "$SeriesInfo";

$slashpos= rindex($FullFile, "/") +1;
$newfilename = substr($FullFile,$slashpos);
$dotlocation = index($newfilename, ".");
$finalfilename=substr($newfilename, 0, $dotlocation);
$errorDir=$outDir . "/" . "$finalfilename" . "Error";

#-----------------------------------------------------counter variable mangement section--------------------------------------------------------------------
$invalidcounter=0;
$badxmlcounter=0;
$nopostcounter=0;
$fgdcoutcounter=0;
$fgdcoutcountera=0;
$flag_array_countera=0;
$postarraycounter=0;
$passcounter=0;
$mifarraycounter=0;
#------------------------------------------------------error trap--------------------------------------------------------------------------------------------
&xsdcheck;
&xsltcheck;
&FGDC2MRFcheck;
&xsl4mrf2fgdccheck;


if (-e $FullFile){
}else{
print "\n $FullFile coluld not be found!!!!!!!!!   Please make sure that the file exists and that the path is correct!!!!!!!!!!!!!!!!!!!!!!!!\n\n";
exit(1);
};


#-----------------------------------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";


#-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------




if ($profile eq 'v' or $profile eq 'V'){
#print "dealing with vector files!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n";
$percentVectorCounter++;
$vectorIndicatorCounter++;

print SAVEOUT "now validating $FullFile against the Vector Profile-----------------------------\n";

if ($valcounter >0){
close STDERR;
system "rm $TMP";
};

$MRF = $finalfilename . ".mrf";
$TMP = "TMP" . "-" . $newfilename;
$valcounter++;

#making the error file and redirecting the STDERR to the error file
#have a new $dotlocation variable because the $filename and $newfilename variables are different lengths
$errmain= substr($newfilename, 0, $dotlocation);
$errfile = $errmain .".err";
open STDERR,">$errfile";

$filecounter++;
my @csax = "java com.saxonica.Validate -t -val:strict  -s:$FullFile -xsd:/mt/apps/gpms/xsd/Vector.xsd";
my $mrf = system(@csax);
$SizeErrorFile= -s $errfile;


open ERRHANDLE, "$errfile ";
while (<ERRHANDLE>){
  if($_=~/does not exist/){
   #doesNotExist[$doesNotExistCounter]=$errfile;
   #$doesNotExistCounter++;
   #system "rm $errfile";
   system "rm $TMP";
   print "$FullFile does not exist or could not be found. Please make sure the path is correct\n";
   exit(1);
 }elsif ($_=~/Validation error/){
 $mrf =512;
};
};
close ERRHANDLE;

#print "\$mrf = $mrf\n";
if ($mrf == 0){
system "rm $errfile";
$good="yes";
}elsif ($mrf != 0){
print SAVEOUT  "The file has failed validation! Please see the $errfile error file in the $errorDir directory.\n\n";
exit(2);
system "mkdir $errorDir";
system "cp $FullFile $errorDir";
system "mv $errfile $errorDir";

};

#-------------------------------------------------------------------------kml----------------------------------------------------------------
}elsif($profile eq 'k' or $profile eq 'K'){

$percentKMLCounter++;
$KMLIndicatorCounter++;

print SAVEOUT "now validating $FullFile against the KML Profile-----------------------------\n";

if ($valcounter >0){
close STDERR;
system "rm $TMP";
};

$valcounter++;

$errmain= substr($newfilename, 0, $dotlocation);
$errfileKML = $errmain .".err";
#print SAVEOUT "\$errfileKML = $errfileKML\n";
open STDERR,">$errfileKML";



#starts schema aware transformation. This will cause the transformation to fail if the document is invalid

$filecounter++;
my @csax = "java com.saxonica.Validate -t -val:strict -s:$FullFile -xsd:/mt/apps/gpms/xsd/KML.xsd";
my $mrf = system(@csax);
#print SAVEOUT "\$mrf = $mrf\n";

open ERRHANDLE, "$errfileKML";
while (<ERRHANDLE>){
  if($_=~/does not exist/){
   #$doesNotExist[$doesNotExistCounter]=$errfile;
   #$doesNotExistCounter++;
   print SAVEOUT  "The file has failed validation! Please see the $errfile error file in the $errorDir directory.\n\n";
   exit(2);
   #system "rm $errfile";
   system "rm $TMP";
 }elsif ($_=~/Validation error/){
 $mrf =512;
};
};
close ERRHANDLE;


#print SAVEOUT "pr if!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n";
if ($mrf == 0){

#print SAVEOUT "The file has passed!!!!!!!!!!!!!!!!!!\n";
#print SAVEOUT "\$errfileKML = $errfileKML\n";
#system "rm $errfileKML";
#system "rm *.err";
unlink $errfileKML;
$good="yes";
}elsif ($mrf != 0){
print SAVEOUT  "The file has failed validation! Please see the $errfileKML error file in the $errorDir directory.\n\n";
exit(2);
system "mkdir $errorDir";
system "cp $FullFile $errorDir";
system "mv $errfileKML $errorDir";
};
#};



};

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

#transorming the file!!!!!!!!!!!!!!xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
if ($good eq "yes"){

#all files need these---------------------------------------------------------------------------------------------------------------------------------
$slashLoc=rindex($FullFile,"/");
$file=substr($FullFile,$slashLoc+1);
$dotLocation=index($file,".");
$mainPart=substr($file,0,$dotLocation);
#print "\$mainPart = $mainPart\n";


#----------------fgde file----------------------------------------------------------------------------------------------------
$FgdcFile=$mainPart . ".xml";
$FgdcError =$mainPart . "_fgdc.err";

open STDOUT,">$FgdcFile";
open STDERR,">$FgdcError";

$fileCoversionCounter++;
print SAVEOUT "\n$fileCoversionCounter: Now transforming $FullFile to the FGDC format!!!!!!!!!!\n";#-outval:recover
my @csax = "java com.saxonica.Transform  $FullFile  $root/gpms/xsl/xsl4mrf2fgdc/MRF2FGDC.xsl";
my $fgdcout = system(@csax);

$fileCoversionCounter++;
if ($fgdcout == 0){
system "mv $FgdcFile $outDir";
system "rm $FgdcError";
}else{

print SAVEOUT  "The file has failed transformation from MRF to FGDC. Please see the $errfileKML error file in the $errorDir directory.\n\n";
system "mv $FgdcFile $errorDir";
system "mv $FgdcError $errorDir";
exit(1);
};

#----------------------------------------ISO file------------------------------------------------------------
$ISOname ="$mainPart.shp.iso.xml";
$ISONAMEerror="$mainPart.shp.iso.err";
open STDOUT,">$ISOname";
open STDERR,">$ISONAMEerror";


print SAVEOUT "$fileCoversionCounter: now transforming $FullFile to the ISO 19115-2 format\n";
my @csax = "java com.saxonica.Transform  -outval:recover $FullFile $root/gpms/mrf2ISO/mrf2ISOMaster.xsl";
my $mif = system(@csax);
$fileCoversionCounter++;

if ($mif ==0){
system "mv $ISOname $outDir";
system "rm $ISONAMEerror";
}else{
print SAVEOUT  "The file has failed transformation from MRF to ISO 19115-2. Please see the $errfileKML error file in the $errorDir directory.\n\n";
system "mv $ISOname $errorDir";
system "mv $ISONAMEerror $errorDir";
exit(1);
};


#dealing with the EA files-------------------------------------------------------
$firstUnderscoreLocation=index($mainPart,"_");
$preFirst=substr($mainPart,0,$firstUnderscoreLocation+1);
$postFirst=substr($mainPart,$firstUnderscoreLocation+1);

$secondUnderscorelocation=index($postFirst,"_");
$preSecond=substr($postFirst,0,$secondUnderscorelocation+1);
$postSecond=substr($postFirst,$secondUnderscorelocation+1);

$thirdUnderscoreLocation=index($postSecond,"_");
$postThird=substr($postSecond,$thirdUnderscoreLocation+1);

$ISOEAName = $preFirst . $preSecond . $postThird . ".shp.ea.iso.xml";

open STDOUT,">$ISOEAName";
open STDERR,">$ISOEANameError";

print SAVEOUT "$fileCoversionCounter: now transforming $FullFile to the ISO Entity and Attribute format\n ";
my @csaxEA = "java com.saxonica.Transform  -outval:recover $FullFile /mt/apps/gpms/mrf2ea/mrf2eamaster.xsl ";
my $eaInd = system(@csaxEA);
#print SAVEOUT "\$eaInd = $eaInd\n";
$fileCoversionCounter++;

if ($eaInd == 0){
system "mv $ISOEAName $outDir";
}else{
print SAVEOUT  "The file has failed transformation from MRF to ISO Entity and Attribute. Please see the $errfileKML error file in the $errorDir directory.\n\n";
system "mv $ISOEAName $errorDir";
system "mv $ISOEANameError $errorDir";
exit(1);
};

$transformCounter++;
$transformIndicatorCounter++;


#-----------------------------------------------------making the Series Information files

#print SAVEOUT "\$passArray = $passArray\n";
$type=substr($mainPart ,0,2);


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

if ($type eq "cb"){
#print SAVEOUT "dealing with cartographic files!!!!!!!!!!!!!!!!!!\n";

$locationFirstUnderscore=index($mainPart,"_")+1;
$postUnder1=substr($mainPart,$locationFirstUnderscore);

$locationOfSweondUnderscore=index($postUnder1,"_");
$year=substr($postUnder1,0,$locationOfSweondUnderscore);
$postUnder2=substr($postUnder1,$locationOfSweondUnderscore+1);

$locationOfThirdUnderscore=index($postUnder2,"_")+1;
$postUnder3=substr($postUnder2,$locationOfThirdUnderscore);


$locationOfFirstDot=index($postUnder3,".");
$themeScale=substr($postUnder3,0,$locationOfFirstDot);

$SeriesInfoFile="SeriesCollection_" . $type . "_" . $year . "_" . $themeScale . ".shp.iso.xml";
$seriesInfoError="SeriesCollection_" . $type . "_" . $year . "_" . $themeScale . ".err";
#print SAVEOUT "\$postUnder1 = $postUnder1\n";
#print SAVEOUT"\$year = $year\n";
#print SAVEOUT"\$postUnder2 = $postUnder2\n";
#print SAVEOUT"\$postUnder3=$postUnder3\n";

}elsif($type eq "sa"){
print SAVEOUT "dealing with sample files\n";
$locationFirstUnderscore=index($passArray,"_")+1;
$postUnder1=substr($passArray,$locationFirstUnderscore);
print SAVEOUT "\$postUnder1 = $postUnder1\n";


$locationOfSweondUnderscore=index($postUnder1,"_");
$year=substr($postUnder1,0,$locationOfSweondUnderscore);
$postUnder2=substr($postUnder1,$locationOfSweondUnderscore+1);

$locationOfThirdUnderscore=index($postUnder2,"_")+1;
$postUnder3=substr($postUnder2,$locationOfThirdUnderscore);


$locationOfFirstDot=index($postUnder3,".");
$themeScale=substr($postUnder3,0,$locationOfFirstDot);

$SeriesInfoFile="SeriesCollection_" . $postUnder1;
$seriesInfoError="SeriesCollection_" . $postUnder1 .  ".err";

}else{
$SeriesInfoFile="SeriesCollection_" . $type . "_" . $year . "_" . $themeScale . ".shp.iso.xml";
$seriesInfoError="SeriesCollection_" . $type . "_" . $year . "_" . $themeScale . ".err";
};


#$SeriesInfoFile="SeriesCollection_" . $type . "_" . $year . "_" . $themeScale . ".shp.iso.xml";
#$seriesInfoError="SeriesCollection_" . $type . "_" . $year . "_" . $themeScale . ".err";
#$SeriesInfo
$SeriesInfoFull= "$SeriesInfo/$SeriesInfoFile";
#print SAVEOUT "\$SeriesInfoFull = $SeriesInfoFull\n";

if (-e $SeriesInfoFull){
#print SAVEOUT "\n$SeriesInfoFull already exists!!!!!!!!!!!!!!\n\n";
}else{
open STDOUT,">$SeriesInfoFile";
open STDERR,">$seriesInfoError";

print SAVEOUT "$fileCoversionCounter: now transforming $FullFile to the ISO Series Information format\n\n ";
my @csaxSeries = "java com.saxonica.Transform  -outval:recover $FullFile /mt/apps/gpms/mrf2ISOParent/MRF2ISOParent.xsl ";
my $SeriesInd = system(@csaxSeries);
$fileCoversionCounter++;

if ($SeriesInd == 0){
system "mv $SeriesInfoFile $SeriesInfo";
system "rm $seriesInfoError";
$SeriesInfoArray[$SeriesInfoArrayCounter]=$SeriesInfoFile;
$SeriesInfoArrayCounter++;
}else{
print SAVEOUT  "The file has failed transformation from MRF to ISO Series Information. Please see the $errfileKML error file in the $errorDir directory.\n\n";
print SAVEOUT "We have an error\n";
system "mv $SeriesInfoFile $errorDir";
system "mv $seriesInfoError $errorDir";
exit(1);
};
};

if ($fileCoversionCounter == 4){
print SAVEOUT "\nSucess!!! The $FullFile has passed validation and has a FGDC, an ISO 19115, an Entity and Attribute and a Series Information file made for it!!!!!!!!!\n\n"; 
}else{
print SAVEOUT "\nSucess!!! The $FullFile has passed validation and has a FGDC, an ISO 19115, and an Entity and Attribute file made for it!!!!!!!!!\n\n";
};

exit(0);
}
