#!/usr/bin/perl -w
#
#  PURPOSE: THE PERL SCRIPT lmp_scp_retrieve.pl RETREIVES RAW
#  SATELLITE CLOUD PRODUCT (SCP) DATA.  THIS SCRIPT IS CALLED
#  IN THE SHELL SCRIPT lmp_scpprep.sh
#
########################################################################  
#         OPEN THE INPUT FILE

###open (INFILE, "< tcus_east") || die "Error opening input file: $!\n";
$iflag=0;
$sflag=0;

########  OPEN THE OUTPUT FILE
open (OUTFILE, "> SCP_raw_out.txt") || die "Error opening output file: $!\n";

HEADER:  while (<>) {

   $iflag++;
## debug   print "iflag=$iflag line=$_\n";
   if ($iflag == 1){
      $head =  $_;
      chomp($head);
      print "HEADER: input = $head\n";
   }
   if ($iflag == 2){
      $dayhr =  $_;
      chomp($dayhr);
      print "DAYHR: input = $dayhr\n";
   }
   if ($iflag == 3){
      $cdayhr =  $_;
      chomp($cdayhr);
      print "CDAYHR: input = $cdayhr\n";
   }
      
   if ($iflag > 3){
      if ($_ =~ /$head/ && ($_ =~ /$dayhr/ || $_ =~ /$cdayhr/)) {
         $sflag = 1;
         print OUTFILE "$_";
         last HEADER;
      }
   }
}
#######  STOP IF INCORRECT INPUTS  ############
if ($sflag == 0){
   print "$head and $dayhr or $cdayhr ERROR: not found in tcus_east or tcus_west file\n";
   close OUTFILE;
   exit(5);
}
#######################################################

PRINT: while (<>) {
   if ($_ =~ /$head/ && $_ !~ /$dayhr/ && $_ !~ /$cdayhr/) {

      $sflag=0;
      
### debug      print "condition not met $_ head=$head dayhr=$dayhr cdayhr=$cdayhr sflag=$sflag\n";      
###   close OUTFILE;
###   exit(0);
   }
   if ($_ =~ /$head/ && ($_ =~ /$dayhr/ || $_ =~ /$cdayhr/)) {

      $sflag = 1;
      
### debug       print "condition met $_ head=$head dayhr=$dayhr cdayhr=$cdayhr sflag=$sflag\n";   
   }
   if ($sflag == 1){
### debug      print "sflag = 1 line = $_\n";
      print OUTFILE "$_";
   }
} 

close OUTFILE;
####close INFILE;
exit(0);




