#!/usr/bin/perl
use FileHandle;

if (($#ARGV + 1) < 4){die <<EOS;}
*** Preprocessing of a set of RSAT2 SLC images using par_RSAT2_SLC
*** Copyright 2012, Gamma Remote Sensing, v1.1 20-Nov-2012 clw/km ***
*** Preprocessing of Radarsat-2 SLC products ***

usage: $0 <SLC_list>  <pol> <out_dir> <log>
    SLC_list  (input) parameter file with 2 entries/line
		  1. directory (including path) containing RSAT2 SLC products (RS2...SLC)
		  2. unique scene identifier (date)
    pol       polarization to extract: HH, HV, VH, VV
    out_dir   directory for output SLC data files and SLC parameter files
    log       (output) processing log file
EOS


$pol = $ARGV[1];
$out_dir = $ARGV[2];
$log = "$out_dir/$ARGV[3]";

unless (-d $out_dir) {
  print "creating output directory for SLC images and SLC image parameter files: $out_dir\n";
  $exit = system("mkdir $out_dir");
  $exit == 0 or die "ERROR $0: non-zero exit status: mkdir $out_dir\n"
}

open(LOG,">$log") or die "ERROR $0: cannot open log file: $log\n";
LOG->autoflush;		#set filehandle special variable to flush output immediately
print LOG "$0 @ARGV\n\n";	#print command line that was used
print "log file: $log\n";

$time = localtime;
print "PROCESSING START: $time\n\n";
print LOG "PROCESSING START: $time\n\n";
open(SLIST, "<$ARGV[0]") or die "ERROR $0: RSAT2 SLC list does not exist: $ARGV[0]\n";
print "SLC list: $ARGV[0]\n";

LINE: while (<SLIST>) {		#read list of directories with unreformated SLC data
  chomp $_;
  next LINE if /^$/; 		#skip blank lines in input list
  next LINE if /^#/; 		#skip comments in the input list
  @fields = split;		#extract the identifier
  $path = $fields[0];
  $id = $fields[1];
  print "\npath: $path  id: $id\n";

  print "Polarization:  $pol\n";
  $dat = "$path/imagery_$pol.tif";
  -e $dat or die "ERROR: data does not exist $dat\n";

  $slc = "$out_dir"."\/".$id."_".$pol.".slc";
  $slc_par = "$out_dir"."\/".$id."_".$pol.".slc.par";

  print "SLC: $slc  SLC_par: $slc_par\n\n";
  $prod = "$path/product.xml";
  $lut = "$path/lutSigma.xml";
  execute("par_RSAT2_SLC $prod $lut $dat $pol $slc_par $slc", $log);
}

$time = localtime;
print "\nPROCESSING END: $time\n";
print LOG "\nPROCESSING END: $time\n";
exit 0;

sub extract_param{
  my ($infile,$keyword) = @_;
  open(PAR_IN,$infile) || die "ERROR $0: cannot open parameter file: $infile\n";

  while(<PAR_IN>){
    chomp;
    @tokens = split;
    if($tokens[0] eq $keyword){close PAR_IN; return @tokens;}
  }
  close PAR_IN;
  die "ERROR $0: keyword $keyword not found in file: $infile\n";
}

sub execute{
  my ($command, $log) = @_;
  print "$command\n";
  print LOG ("\n${command}\n");
  close LOG;
  $exit = system("$command 1>> $log 2>&1");
  $exit == 0 or die "ERROR $0: non-zero exit status: $command\n";
  if (-e $log){
    open(LOG,">>$log") or die "ERROR $0: cannot open log file: $log\n";
  }
  else {
    open(LOG,">$log") or die "ERROR : cannot open log file: $log\n";
  }
  LOG->autoflush;
}
