#!/usr/bin/env perl
##########################################################################
#
# routine: podwhk.pl
#
# purpose: Creates a new pod file for each POD entry in the podlist file,
#          where each new pod file contains only 1 exposure.
#
# modification history:
#
#   date    opr     who     reason
# -------- -----  --------  --------------------------------------
# 09/03/00 43165  MSwam     first version
# 10/19/04 50663  MSwam     skip EPC if in podlist file
# 
##########################################################################
#
# prepend the Perl include variable using all components of PATH
# (this allows us to reuse other OTFR Perl code)
#
$PATH  = $ENV{"PATH"};
@parts = split /:/, $PATH;
while (defined($val = pop(@parts))) {
   if (substr($val,0,1) eq "/") { unshift(@INC, $val)}
}

#
# include these modules
#
require 'printmsg.pl';       # prints a formatted status message
require 'otfr_setup.pl';     # OTFR pipeline set-up for processing a request

OTFR_setup();

PrintMsg("I","Processing $p_dir");

# open the PODLIST file listing exposures and podfile names
$infile = $p_dir . ".podlist";
if (!open(PODLIST, "$infile")) {
   PrintMsg("E","ERROR: failed to open infile $infile\n"); 
   exit $quit_this_dataset;
}

#
# read each podlist entry, extract the exposure into a new pod file
#
while (<PODLIST>) {
   #
   # split the read buffer ($_) into fields and skip this line if EDT type
   ($exp, $pod, $indicator) = split(/ /,$_);  
   chomp($indicator);
   if ($indicator eq "EDT" or $indicator eq "EPC") {
      PrintMsg("D","$indicator needs no whacking...skip on\n"); 
      next;
   }

   # lower case them
   $exp = lc($exp);
   $pod = lc($pod);

   # verify pod file exists
   $inpod = $pod . ".pod";
   if (! -e $inpod ) {
       PrintMsg("E","podwhacker: ERROR - $inpod not found.\n");
       exit $quit_this_dataset;
   }

   #
   # form the output pod file name from the podfilename and exposure name
   #
   $outpod = $pod . "_" . $exp . ".pod";
   PrintMsg("D","podwhacker: $outpod");

   #
   # remove any pre-existing output file with that name
   unlink($outpod);

   #
   # append the pod file extension and extract the exposure into a new pod file 
   $pod .= ".pod";
   `podwhacker -f $pod -n $exp -o $outpod`;
   if ($? != 0) {
      PrintMsg("E","ERROR: podwhacker failed for $pod, $exp, $outpod\n");
      exit $quit_this_dataset;
   }
   #
   # verify whacked-POD exists (an extra success test)
   if (! -e $outpod ) {
       PrintMsg("E","podwhacker: ERROR - $outpod not created.\n");
       exit $quit_this_dataset;
   }
}
close(PODLIST);

# complete, exit success
exit $all_is_well;
