#!/usr/bin/perl
use FileHandle;

$azbw_frac = 0.9;		#fraction of the azimuth spectrum to process

if (($#ARGV + 1) < 3){die <<EOS;}
*** $0
*** Copyright 2006, Gamma Remote Sensing, v2.2 19-Jun-2014 clw ***
*** Radarsat CEOS format raw data pre-processing and parameter setup ***

usage: $0 <CEOS_list> <out_dir> <log> <proc_list> <mode> [keyword] [value]
    CEOS_list	(input) parameter file with 2 entries/line 
		  1. directory (including path) containing RSI Radarsat CEOS data set  
		  2. unique scene identifier (date)  
    out_dir     directory for output fixed raw data files and processing parameter files
    log         (output) processing log file  
    proc_list   (output) (processing list for use by RSAT_proc_all)
    mode        processing mode:
		  1: create MSP processing parameter files, fix + concatenate raw data, estimate Doppler ambiguity from attitude
		  2: (optional) Doppler ambiguity from raw data rather than nominal attitude 
		  3: estimate 2d Doppler centroid function
    		  4: set value in the processing parameter files for a keyword:value pair
		  5: generate processing list for use by RSAT_proc_all
    keyword 	keyword in the MSP processing parameter file (example: doppler_polynomial)
    value	new value delimited by double quotes (example: "317.0 0. 0. 0.")
       
EOS

$mode = $ARGV[4];
if(($mode != 1) && ($mode != 2) && ($mode != 3) && ($mode != 4) && ($mode != 5)){die "ERROR $0: invalid RSAT_pre_proc processing mode: $mode\n";}

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

unless (-d $out_dir) {
  print "creating output directory for fixed raw data and MSP processing 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";

$proc_par_in = "$out_dir/proc_par.in";
if($mode == 1){				#file to contain inputs to ERS_proc_* programs
  open(MPAR, ">$proc_par_in") or die "ERROR $0: cannot create file with inputs to RSAT_raw: $proc_par_in\n\n";
}
  
if($mode == 4){
  if (($#ARGV + 1) != 7){die "ERROR $0: keyword value pair are missing from the command line\n";}
  $key =  $ARGV[5];
  $value = $ARGV[6];
  print "updating value in the MSP processing parameter files\n";
  print "keyword: $key   new value: $value\n";
} 

if($mode == 5){
  $proc_list = $ARGV[3];
  print "processing list file: $proc_list\n";
  open(PROCF,">$proc_list") or die "ERROR $0: cannot open output processing list file: $proc_list\n";
}

open(SLIST, "<$ARGV[0]") or die "ERROR $0: CEOS list does not exist: $ARGV[0]\n";
print "CEOS list: $ARGV[0]\n"; 

LINE: while (<SLIST>) {		#read list of directories with unreformated raw 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";

  $RSAT_sensor = "$out_dir"."\/RSAT_".$id.".par";
  $PROC_par = "$out_dir"."\/p".$id.".slc.par";

  if($mode == 1){
    print "CEOS leader: $ceos   PROC_par: $PROC_par\n";
    $ceos ="$path/lea_01.001";	#CEOS data are in a further subdirectory!
    $dat1 = "$path/dat_01.001";
    $dat2 = "$path/dat_02.001";
    
    unless (-e $ceos){		#some data sets have filenames in capitols others not
      $ceos = "$path/LEA_01.001";
      $dat1  = "$path/DAT_01.001";
      $dat2 = "$path/DAT_02.001";
    }
    unless (-e $dat2){		#no second data segment to concatenate
      $dat2 = "";
    }    
    $fix = "$out_dir/$id.fix";
    if (-e $fix){
      unlink $fix;
    }
    print MPAR "\n\n\n\n\n\n\n\n\n\n\n";
    close MPAR;
    execute("RSAT_raw $ceos $RSAT_sensor $PROC_par $dat1 $dat2 $fix < $proc_par_in", $log);
  }
  
  if($mode == 2){
    @lines = extract_param($PROC_par, "total_raw_echoes:");
    $nl = $lines[1];
    $nl2 = $nl/2 - 4096;	#center MLBF estimation block
    print "CEOS leader: $ceos   PROC_par: $PROC_par  total echoes: $nl\n";
    $fix = "$out_dir/$id.fix";
    execute("dop_ambig $RSAT_sensor $PROC_par $fix 2 $nl2", $log);
  } 

  if($mode == 3){
    print "CEOS leader: $ceos   PROC_par: $PROC_par\n";
    $fix = "$out_dir/$id.fix";
    $dop2d = "$out_dir/$id.dop2d";
    execute("doppler_2d $RSAT_sensor $PROC_par $fix $dop2d", $log);
  }    

  if($mode == 4){
    print "PROC_par: $PROC_par\n";
    (-e $PROC_par) or die"ERROR $0: processing parameter file does not exist: $PROC_par\n"; 
    execute("set_value $PROC_par $PROC_par $key \"$value\"", $log); 
  }
 
  if($mode == 5){
    @dpoly = extract_param($PROC_par, "doppler_polynomial:");
    $fd = $dpoly[1];
    $fd_rate = $dpoly[2];
    printf PROCF  "$id - - - - %8.1f %12.5e $azbw_frac\n", $fd, $fd_rate;
    printf LOG   "$id - - - - %8.1f %12.5e $azbw_frac\n", $fd, $fd_rate;
    printf "$id - - - - %8.1f %12.5e $azbw_frac\n", $fd, $fd_rate;
  }  
} 
 
$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) = @_;  
  if (-e $log){open(LOG,">>$log") or die "ERROR $0: cannot open log file: $log  command: $command\n";}
  else {open(LOG,">$log") or die "ERROR $0: cannot open log file: $log  command: $command\n";} 
  LOG->autoflush; 
  print "$command\n";
  print LOG ("\n${command}\n");
  close LOG;  
  $exit = system("$command 1>> $log");
  $exit == 0 or die "ERROR $0: non-zero exit status: $command\n"
}

