#!/usr/bin/env perl
#
## Copyright (c) 1995-2020 University Corporation for Atmospheric Research
## All rights reserved
#
my $pkgdoc = <<'EOD';
#/**----------------------------------------------------------------------
# @file       trigZero2one.pl
# Convert one COSMIC-2 level 0 file into level 1 files as specified
# in the COSMIC level 1 data standard:
#
# http://cosmic.cosmic.ucar.edu/cdaac/fileFormats/
#
# Assumptions:
#
# 1) This program will be called on input files in time order.  Data from
#    earlier files will be thrown out once a later file is processed.
#
# @author     Doug Hunt
# @since      10/09/2014
# @version    $URL: svn://svn1.cosmic.ucar.edu/trunk/src/BJutils/trigZero2one.pl $ $Id: trigZero2one.pl 26182 2020-07-17 21:48:57Z dhunt $
# @cdaacTask  yes
# @usage      trigZero2one.pl trgLv0_2020.200.00.08.001.HAWAII_tlm.gz
# @           [--verbose] [--[no]dump_occs]
# @           If --verbose is specified, then report on individual packets
# @           If --dump_occs is specified (not the default) then generate a listing of occultation locations and heights
# @           based on the lat,lon,height info in the OCCDq12a/b packets
# -----------------------------------------------------------------------*/
EOD

$|++;

use lib qw (.);
use strict;
use warnings;

use TimeClass;   # OO time/date conversion library
use BJTools;
use Level1aTools;
use PDL;
use Getopt::Long;
use SatInfo;
use List::Util qw();
use RSTools;
use Cosmic2Parser;
use Dplib;

if (@ARGV == 0) {
  print $pkgdoc;
  exit -1;
}

# deal with command line options, default is to clean everything.
my $verbose   = 0;
my $dump_occs = 0;
GetOptions (
	    "verbose!"   => \$verbose,
            "dump_occs!" => \$dump_occs,
          ) || die "Cannot parse command line options!";

my $infile = my $inpath = shift;

# Jun added, 20251208----bg
my $opnGns_output = shift;
my $podCrx_output = shift;
my $scnRaw_output = shift;
my $opnScn_output = shift;
my $goxSOH_output = shift;
print "opnGns=$opnGns_output\n";
print "podCrx=$podCrx_output\n";
print "scnRaw=$scnRaw_output\n";
print "opnScn=$opnScn_output\n";
print "goxSOH=$goxSOH_output\n";
# Jun added, 20251208----ed


# Find date, LEO ID and dump number from input path: goxBin_2011.134.005.02.B_bj
my ($fileyr, $filedoy, $hr, $min, $leoid, $groundstation) = ($infile =~ /trgLv0_(\d\d\d\d)\.(\d\d\d)\.(\d\d)\.(\d\d)\.(\d\d\d)\.(.*?)\_tlm\.gz/);
my $filedate = "$fileyr.$filedoy";

my $mission = 'coseq'; # COSMIC-2 (Cosmic Equatorial)

print "trigZero2one.pl:  processing $infile\n";

# Some logic is necessary to determine dump id.
# This is processing center specific!  Just call it '1' for a place-holder
my $ndump = 1;

# Remove spacecraft and ground station headers if requested
# Note that $trig_data is a scalar reference not a scalar
my @opt = (CORTEX => 1, IP_UDP => 1, VERBOSE => $verbose);
my $trig_data = BJTools::unwrap_headers ($inpath, @opt);

# May need to know l2p from l2c.  For early C-2, there is no way to tell.
my %l2c_map;
my $l2c_file = "L2C_Sats.txt"; # Original file supplied with reader.  For newer data, L2C vs. L2P is specified in the data.
if (-s $l2c_file) {
  my ($prn, $isl2c) = rcols $l2c_file, 0, 1;
  my @isl2c = $isl2c->list;
  foreach my $p ($prn->list) {
    $l2c_map{$p} = shift(@isl2c);
  }
}

push (@opt, (L2CMAP => \%l2c_map));
my $parser = Cosmic2Parser->new({TMPDIR => 'memory'});
$parser->parseLv0($trig_data,$leoid); # Jun add leoid
$parser->report; # print report of parsing success

my $firmware_version = $parser->{FIRMWARE_VERSION} ? $parser->{FIRMWARE_VERSION} : 'v433-';
print "Firmware version = $firmware_version\n";

# Create a diagnostic occultation location list if requested
if ($dump_occs) {
  (my $outfile = $inpath) =~ s/\.gz//;
  $outfile .= ".txt";
  $parser->dump_occs($outfile);
}

# Find dates for output files from times in input file
my $datastart  = $parser->{FIRSTTIME};
my $dataend    = $parser->{LASTTIME};

#
## Extract POD data (OBSDq12a/b)
#

my @antid = sort keys %{$parser->{OUTFILES}{lorate}};
foreach my $antid (@antid) {

  #my $lrfile = sprintf ("podCrx_$filedate.%03d.%02d.%02d_rnx", $leoid, $ndump, $antid); # Original code
  # Jun modified 20251208 ----------------------bg
  my $lrfile = sprintf ("podCrx_$filedate.%02d.%02d.%03d.%02d.${groundstation}_rnx", $hr,$min,$leoid,$antid); 
  #print "filedate=$filedate\n";
  #print "hr=$hr\n";
  #print "min=$min\n";
  #print "leoid=$leoid\n";
  #print "antid=$antid\n";
  #print "groundstation=$groundstation\n";
  $lrfile = "$podCrx_output/$lrfile";
  print "lrfile=$lrfile\n";
  #exit;
  ## Jun modified 20251208 ----------------------ed

  my $lrdata = $parser->{OUTFILES}{lorate}{$antid};
  my $opt    = {COMPRESS => 0, RNXVER => '2.11', FIRMWARE_VERSION => $firmware_version};
  Level1aTools::twoA_to_rinex($lrdata,$lrfile,$antid,sprintf("C2E%01d",$leoid),$mission,$opt);
  my $fs = -s $lrfile;
  print "FILE CREATION: ", Dplib::simplefn($lrfile), " size = $fs\n";
}


#
## Extract high rate occultation data (OCCDq12b)
#

#
## Data descriptors for the opnGns high rate data file.  See the data format doc:
## GNSS_High_Rate_Binary_Format_v2.0.pdf for details.
#

my $hrdata = $parser->{OUTFILES}{hirate};
foreach my $antid (sort keys %$hrdata) {

  #my $hrfile = sprintf ("opnGns_$filedate.%03d.%02d.%02d_bin", $leoid, $ndump, $antid); #Original code
  #Jun modified 20251208 ----------------------bg
  my $hrfile = sprintf ("opnGns_$filedate.%02d.%02d.%03d.%02d.${groundstation}_bin", $hr,$min,$leoid,$antid);
  $hrfile = "$opnGns_output/$hrfile";
  print "hrfile=$hrfile\n";
  #exit;
  #Jun modified 20251208 ----------------------ed
  Level1aTools::sort_opnGns_v2 ($hrdata->{$antid}, $hrfile);

  print "FILE CREATION: ", Dplib::simplefn($hrfile), "\n";
}

#
## Extract scintillation data from OBSDq12a packets
#

print "Extracting OBSDq12a SCIN data\n";

# %scindata is a hash by antenna id:
# $scindata{antid}{time}{prn}[l1_s4, l1_sigphi, l2_s4, l2_sigphi]
my $scindata = $parser->{OUTFILES}{'lorate_scin'};

foreach my $antid (sort keys %$scindata) {

  #my $scinfile = sprintf ("scnRaw_$filedate.%03d.%02d.%02d_txt", $leoid, $ndump, $antid); #Original code
  # Jun modified 20251208 ----------------------bg
  my $scinfile = sprintf ("scnRaw_$filedate.%02d.%02d.%03d.%02d.${groundstation}_txt", $hr,$min,$leoid,$antid);
  $scinfile="$scnRaw_output/$scinfile";
  print "scinfile=$scinfile\n";
  #exit;
  # Jun modified 20251208 ----------------------ed



  open  (my $OUT, '>', $scinfile) or die "Cannot open $scinfile for output";
  print {$OUT} "# GPS_seconds Number_of_GPS_satellites_this_epoch list_of_PRNs\n";
  print {$OUT} "# One PRN per line:  L1_S4, L1_SIGPHI, L2_S4, L2_SIGPHI\n";
  foreach my $time (sort keys %{$scindata->{$antid}}) {
    my @prns = sort keys %{$scindata->{$antid}{$time}};
    printf {$OUT} "%10d  %2d".(' %3s' x @prns)."\n", $time, scalar(@prns), @prns;
    foreach my $prn (@prns) {
      printf {$OUT} "%14.7f %14.7f %14.7f %14.7f\n", @{$scindata->{$antid}{$time}{$prn}};
    }
  }
  close $OUT;
  print "FILE CREATION: ", Dplib::simplefn($scinfile), "\n";
}

#
## Extract LOG data
#

print "Extracting LOG data\n";
my $logdata = '';
my @data_types = grep { defined $parser->{OUTFILES}{$_} } (qw(logm.txt fdir.txt navg.txt cmdr.txt));
$logdata .= BJTools::logData (\$parser->{OUTFILES}{$_}) foreach (@data_types);

# Print out any GOX log data
if (length($logdata) > 0) {
  #my $logfile = sprintf ("goxSOH_$filedate.%03d.%02d_txt", $leoid, $ndump); #Original code
  #Jun modified 20251208 ----------------------bg
  my $logfile = sprintf ("goxSOH_$filedate.%02d.%02d.%03d.${groundstation}_txt", $hr,$min,$leoid);
  $logfile="$goxSOH_output/$logfile";
  print "logfile=$logfile\n";
  #Jun modified 20251208 ----------------------ed

  open (OUT, ">$logfile") || die "Cannot open $logfile for output";
  print OUT $logdata;
  close OUT;
  print "FILE CREATION: ", Dplib::simplefn($logfile), "\n";
}

#
## Extract high-rate scintillation data from SCNThrat packets
#
#Level1aTools::write_all_opnScn ($parser->{OUTFILES}, $filedate, $ndump, $leoid, $mission); #original code
#Jun modified 20251208 ----------------------bg
Level1aTools::write_all_opnScn ($parser->{OUTFILES}, $filedate, $ndump, $leoid, $mission,$opnScn_output,$hr,$min,$groundstation);
#Jun modified 20251208 ----------------------ed

print "Done!\n";

exit;
