#!/usr/bin/perl

use Shell qw(date ls);
use Time::Local;

#Jade W. 05/01/2017 edits to merge 2 day old granules, and 
#		send to archive directory. Then remove 3 day old granules


$abbaArchive="abbaArchive";
$fimmaArchive="fimmaArchive";
$modisArchive="modisArchive";
$viirsArchive="viirsArchive";
$datadir = "/data/ftp/pub/FIRE";
$homedir = "/home/oper/hms";
#$datadir = "/data/ftp/pub/FIRE/test";
#$homedir = "/data/ftp/pub/FIRE/test/Jade";
#$homedir = "/home/oper/hms";

($sec, $min, $hour, $mday, $month, $year, $wday, $yday, $isdat) = localtime(time - 2*24*60*60);
$year += 1900;

print "\$year is $year and \$mday is $mday \$month is $month \$hour $hour \$min $min\n";

$jday1 = ymd2yjday($year, $month, $mday);
#$julian_day = $year . $julian_day;
print " \$year $year \$jday1 $jday1\n";

($sec4, $min4, $hour4, $mday4, $month4, $year4, $wday, $yday, $isdat) = localtime(time - 1*24*60*60);
$year4 += 1900;
$jday4 = ymd2yjday($year4, $month4, $mday4);
print "\$year4 is $year4 and \$mday4 is $mday4 \$month4 is $month4 \$jday4 $jday4\n";
#die;

#added for one day before merge
($sect, $mint, $hourt, $mdayt, $montht, $yeart, $wday, $yday, $isdat) = localtime(time - 3*24*60*60);
$yeart += 1900;
$jdayt = ymd2yjday($yeart, $montht, $mdayt);
print "\$yeart is $yeart and \$mdayt is $mdayt \$montht is $montht \$jdayt $jdayt\n";
###Testing June 22, 2017####
$jday1=192;
$jday4=193;
#Get age at midnight
$hr=0;
$min=0;
$midnight=&age_min($year,$jday1,$hr,$min);
$dayend=$midnight+1440;
print "\$midnight $midnight \$dayend $dayend\n";

$abbafinal="wf_abba_global$year$jday1.v65.txt";
$fimmafinal="fimma_r_global$year$jday1.dat";
$modisfinal="MOD14.global$year$jday1.v5.0.01.dat";
$viirsfinal="VIIRSNDE_global$year$jday1.v1.0.txt";

#GOES - WFABBA section
system("ls $datadir/ABBA/f${year}${jday1}*g* > ./$abbaArchive");
#system("ls $datadir/ABBA/f${year4}${jday4}*g* >> ./$abbaArchive");
open(OUTPUTABBA, ">./$abbafinal");
open(ABBA, "<./$abbaArchive");
 @lines = <ABBA>;
 #print @lines;
 chomp @lines;
print OUTPUTABBA "    Lon,     Lat,   Temp4,  Temp11,  Size(km2),  Temp(K),  Ecosys,Fireflag,  Sat,  YearDay,   Time\n";
 foreach $linein (@lines) {
   chomp $linein ;
   print "$linein\n";
   @sat=split(/\./, $linein);
   @sat2=split(/g/, $sat[2]);
   $id=@sat2[1];
   @date=split(/f/, $linein);
   #print "@date\n";
   #$fyear=substr($date[1],0,4);
   $fyear=substr($date[2],0,4);
   $fday=substr($date[2],4,3);
   #$fday=substr($date[1],4,3);
   $fhr=substr($date[2],7,2);
   #$fmin=substr($date[1],9,2);
   $fmin=substr($date[2],9,2);
   $fage=&age_min ($fyear,$fday,$fhr,$fmin);
   
   #print "\$fage $fage \$fyear $fyear \$fday $fday \$fhr $fhr \n";
   if ($id eq '15') {$off = 9;}
   elsif ($id eq '13') {$off = 6;}
   else {$off = 8;}
   $off=$off*60;
#   if (($fage >= $midnight+$off) and ($fage <= $dayend + $off)) {
     $val=0;
     open(TEMP, "<$linein");
     @newlines = <TEMP>; close(TEMP);
     foreach $newlinein (@newlines) {
       chomp $newlinein;
       if($val != 0){
	   @lonlat=split(/,/,$newlinein);
#	   if((@lonlat[0]<0 or @lonlat[0]>160) and @lonlat[1]>7){
	       print OUTPUTABBA "$newlinein,     $id,  $fyear$fday,   $fhr$fmin\n";
#	   }# end if
       }# end if
       $val=1;
     }# end foreach
#     system("rm $linein");
 #  }# end if
 }# end foreach
close(OUTPUTABBA);
close(ABBA);
#die;
#Archival
#system ("mv $datadir/ABBA/$abbafinal ./");
#system("rm $datadir/ABBA/f${yeart}${jdayt}*g*");
exit;
#AVHRR - FIMMA section
system("ls $datadir/FIMMA/g*${year}${jday1}*.dat $datadir/FIMMA/m*${year}${jday1}*.dat | sort -t_ -k2 > $homedir/$fimmaArchive");
system("ls $datadir/FIMMA/g*${year4}${jday4}*.dat $datadir/FIMMA/m*${year}${jday4}*.dat | sort -t_ -k2 >> $homedir/$fimmaArchive");

#system("ls $datadir/FIMMA/g*${year}${jday1}*.dat > $homedir/$fimmaArchive");
#system("ls $datadir/FIMMA/m*${year}${jday1}*.dat >> $homedir/$fimmaArchive");
#system("ls $datadir/FIMMA/g*${year4}${jday4}*.dat >> $homedir/$fimmaArchive");
#system("ls $datadir/FIMMA/m*${year4}${jday4}*.dat >> $homedir/$fimmaArchive");
open(OUTPUTFIMMA, ">./$fimmafinal");
open(FIMMA, "<$homedir/$fimmaArchive");
 @lines = <FIMMA>;
print OUTPUTFIMMA "     Lon,     Lat,   Temp3,   Temp4,   Temp5,Landcover, Sat,   YearDay,   Time, Station\n";
 foreach $linein (@lines) {
   chomp $linein ;
   print "$linein\n";
   @sat=split(/\//, $linein);
   @sat2=split(/_/, $sat[-1]);
   $satc=substr($sat2[0],0,1); if ($satc eq 'g'){$satc = 'n'}
   $id=substr($sat2[0],1);
   @date=split(/r/, $linein);
   $fyear=substr($date[1],0,4);
   $fday=substr($date[1],4,3);
   $fhr=substr($date[1],8,2);
   $fmin=substr($date[1],10,2);
   @sat4=split(/\./,$linein);
   $sta=@sat4[1];
   $fage=&age_min ($fyear,$fday,$fhr,$fmin);
   #if($id eq '15') {$off = 8;}
   if($id eq '19') {$off = 4;}
   #elsif ($id eq '18') {$off = 3;}
   elsif ($id eq '18') {$off = 6;}
   #elsif ($id eq '16') {$off = 3;}
   #elsif ($id eq '01') {$off = 12;}
   #elsif ($id eq '02') {$off = 12;}
   elsif ($id eq '01') {$off = 10;}
   elsif ($id eq '02') {$off = 10;}
   else {$off = 8;}
   $off=$off*60;
 #  if (($fage >= $midnight+$off) and ($fage <= $dayend + $off)) {
     $val=0;
     open(TEMP, "<$linein");
     @newlines = <TEMP>; close(TEMP);
     foreach $newlinein (@newlines) {
       chomp $newlinein ;
       if($val != 0){
	    @lonlat=split(/,/,$newlinein);
#	   if((@lonlat[0]<0 or @lonlat[0]>160) and @lonlat[1]>7){
	        print OUTPUTFIMMA "$newlinein,     $satc$id,   $fyear$fday,   $fhr$fmin,   $sta\n";
#	   }# end if  
       }# end if
       $val=1;
     }# end foreach
#     system("rm $linein");
#   }# end if
 }# end foreach
close(OUTPUTFIMMA);
close(FIMMA);
#Archival
#system ("mv $datadir/FIMMA/$fimmafinal ./");
#system("rm $datadir/FIMMA/g*${yeart}${jdayt}*.dat");
#system("rm $datadir/FIMMA/m*${yeart}${jdayt}*.dat");

#MODIS section
#system("ls $datadir/MODIS/MOD*dat > $homedir/$modisArchive");
system("ls $datadir/MODIS/MOD*${year}${jday1}*.dat > $homedir/$modisArchive");
system("ls $datadir/MODIS/MOD*${year4}${jday4}*.dat >> $homedir/$modisArchive");
open(OUTPUTMODIS, ">./$modisfinal");
open(MODIS, "<$homedir/$modisArchive");
 @lines = <MODIS>;
print OUTPUTMODIS "          Lon,          Lat,    Mask, Confidence,     Frp(MW),       Sat,   YearDay,   Time\n";
 foreach $linein (@lines) {
   chomp $linein ;
   print "$linein\n";
   @sat=split(/MOD14/, $linein);
   $id=substr(@sat[1],1,1);
   $fyear=substr($sat[1],2,4);
   $fday=substr($sat[1],6,3);
   $fhr=substr($sat[1],10,2);
   $fmin=substr($sat[1],12,2);
   $fage=&age_min ($fyear,$fday,$fhr,$fmin);
   if($id eq 'A') {
     $off = 12;
     $id='0';
     $sat1='A';
   }
   elsif ($id eq 'P') {
     $off = 2;
     $id='1';
     $sat1='P';
   }
   $off=$off*60;
#   if (($fage >= $midnight+$off) and ($fage <= $dayend + $off)) {
     #print "$linein\n";
     $val=0;
     open(TEMP, "<$linein");
     @newlines = <TEMP>; close(TEMP);
     foreach $newlinein (@newlines) {
       chomp $newlinein ;
       if($val != 0){
	   @lonlat=split(/,/,$newlinein);
#	   if((@lonlat[0]<0 or @lonlat[0]>160) and @lonlat[1]>7){
		#print "$newlinein\n";
		#print "@lonlat[0],@lonlat[1],@lonlat[2],@lonlat[3],@lonlat[4], \n";
	       #print OUTPUTMODIS "$newlinein,         $sat1,   $fyear$fday,   $fhr$fmin\n";
	       print OUTPUTMODIS "@lonlat[0..2],       @lonlat[3..4],         $sat1,   $fyear$fday,   $fhr$fmin\n";
#	   }# end if
       }# end if
       $val=1;
     }# end foreach
#     system("rm $linein");
     $linein =~ s/\.dat/\.meta/;
	print "$linein\n";
#     system("rm $linein");
 #  }# end if
 }# end foreach

close(OUTPUTMODIS);
close(MODIS);
#Archival
#system ("mv $datadir/MODIS/$modisfinal ./");
#system("rm $datadir/MODIS/MOD*${yeart}${jdayt}*.dat");
#system("rm $datadir/MODIS/MOD*${yeart}${jdayt}*.meta");

#VIIRS section
system("ls $datadir/VIIRS/VIIRS.NDE*${year}${jday1}*.dat > $homedir/$viirsArchive");
system("ls $datadir/VIIRS/VIIRS.NDE*${year4}${jday4}*.dat >> $homedir/$viirsArchive");
open(OUTPUTVIIRS, ">./$viirsfinal");
open(VIIRS, "<$homedir/$viirsArchive");
 @lines = <VIIRS>;
print OUTPUTVIIRS "      Lon,         Lat,   Mask, Conf, brt_t13(K),    frp(MW),   line, sample,  Sat,   YearDay,   Time\n";
 foreach $linein (@lines) {
   chomp $linein ;
   print "$linein\n";
   @hold=split(/VIIRS/, $linein,1);
   @sat=@hold;
   @sat[0]=substr(@hold[0],0,25);
   @sat[1]=substr(@hold[0],30,20);
   $id=substr(@sat[1],1,3);
   $fyear=substr($sat[1],4,4);
   $fday=substr($sat[1],8,3);
   $fhr=substr($sat[1],12,2);
   $fmin=substr($sat[1],14,2);
   $fage=&age_min ($fyear,$fday,$fhr,$fmin);
   $off = 3;

   $off=$off*60;
#   if (($fage >= $midnight+$off) and ($fage <= $dayend + $off)) {
   # print "$linein\n";
     $val=0;
     open(TEMP, "<$linein");
     @newlines = <TEMP>; close(TEMP);
$ct=0;
     foreach $newlinein (@newlines) {
#     for my $i (0 .. $#newlinein) {
       chomp $newlinein ;
       if($val != 0){
           @lonlat=split(/,/,$newlinein);
 #          if((@lonlat[5]<0 or @lonlat[5]>160) and @lonlat[6]>7){
#$ct=$ct+1;
print "@lonlat[5..6] $newlinein\n";
 #               if ($ct eq 0 or 4 or 5) {print "@lonlat[5]\n"};
		print OUTPUTVIIRS "@lonlat[5..12],   $id,   $fyear$fday,   $fhr$fmin\n";
#           }# end if
       }# end if
       $val=1;
     }# end foreach
     #system("rm $linein");
   }# end if
# }# end foreach

close(OUTPUTVIIRS);
close(VIIRS);
#Archival
#system ("mv $datadir/VIIRS/$viirsfinal ./");
#system("rm $datadir/VIIRS/VIIRS.NDE*${yeart}${jdayt}*.dat");


#=====================Sub ymd2yjday()=========================================
sub ymd2yjday {

my ($year, $month, $mday) = @_;

my (%month2jday) =  (
                           'noleapyear' =>
                             [
                                0,
                                31,
                                59,
                                90,
                                120,
                                151,
                                181,
                                212,
                                243,
                                273,
                                304,
                                334,
                                365,
                             ],

                           'leapyear'   =>
                             [
                                0,
                                31,
                                60,
                                91,
                                121,
                                152,
                                182,
                                213,
                                244,
                                274,
                                305,
                                335,
                                366,
                             ],
                        );

my ($currentyear, $jday);

#print "Inside FUNC \$year $year \$month is $month \$mday $mday\n";
if ((($year % 4 == 0) && ($year % 100 != 0)) || ($year % 400 == 0)) {
  $currentyear = 'leapyear';
}
else {
  $currentyear = 'noleapyear';
}
#print "\$month2jday->{$currentyear}->[$month] is $month2jday{$currentyear}[$month]\n";

#$jday = $month2jday{$currentyear}[$month] + $mday;
$jday = sprintf("%3.3d", $month2jday{$currentyear}[$month] + $mday);
#print "\$jday is $jday\n";
return ($jday);
}

#==========================sub age_min=======================================
sub age_min
{
$year=$_[0];
$julday=$_[1];
$hour=$_[2];
$minute=$_[3];

$fourcentury=$year % 4;
$century=$year % 100;
$leapyear=$year % 4;

#Compute age in minutes
if($fourcentury == 1) {$age= $year*527040 + $julday*1440 + $hour*60 + $minute}
elsif($century == 1) {$age= $year*525600 + $julday*1440 + $hour*60 + $minute}
elsif($leapyear == 1) {$age= $year*527040 + $julday*1440 + $hour*60 + $minute}
else {$age= $year*525600 + $julday*1440 + $hour*60 + $minute}

return($age);
}

