#!/opt/perl/bin/perl
use warnings;
use strict;
use Cwd;
use GPS::DATES qw(get_date cal2jd jd2gpsw dow2gdow jd2dow );
use GPS::Defaults;
use File::Temp qw(tempfile);
use File::Basename;
use Getopt::Long;
use GOA::Util;

my $progname = basename($0);

my $usage = qq(
 Usage:
  $progname proj_name date
  
  date: 2005,123    year,doy
        2005-05-01  calendar
	05MAY01     date
	20050501    num calendar
	13340       GPS Week+day of week
  
  $progname pbo-rapid 2005-07-07 
);

die "$usage \n" unless @ARGV;
my %par = get_defaults();

my $proj = 'pbo-rapid';

my $date = '';

my $upload = 0;
my $ac = 'igs';
my $orb= "rapid";
my $help = '';
my $frame = 'raw';
GetOptions(
     'ac=s'        => \$ac,
     'proj=s'      => \$proj,
     'date=s'      => \$date,
     'frame:s'      => \$frame,
     'upload!'     => \$upload,
     'orb:s'       => \$orb,
     'help!'       => \$help,
)or die "Error in options\n";

# For the pbo-rapid (daily) solutions, make SINEX files from the
# igs08 frame stacov files, otherwise, use the raw stacov files
if ($proj eq 'pbo-rapid') {
    #$frame = 'igs08'; # Only valid until 2014-10-26
    $frame = 'igb08';
}

if ($orb eq 'rapid') {
    # For rapid orbits, we need to use the 'r' stacov file
    $frame = "$frame.r";
}


my $p = "a";
$p = "b" if $proj eq 'pbo-week';
$p = "e" if $proj eq 'pbo-reanalysis';
$p = 'c' if $proj eq 'pbo-supplemental';
$p = 'f' if $proj eq 'pbo-supplemental6';
$p = '' if $proj eq 'panga';

my $cal = get_date($date,"cal");
#my $gwd = get_date($date,"gwd");
my $jd = get_date($date,'jd');
my $gpsw = sprintf("%04d",jd2gpsw($jd));
my $gdow = dow2gdow(jd2dow($jd));
my $gwd = "$gpsw$gdow";
my ($y,$m,$d) = unpack("a4x1a2x1a2",$cal);
$date = get_date($date,"cal,num");

my $dir = "$par{PPP_DIR}/$ac/$y/$cal";
my $rcdir = "$par{RAW_COMB_DIR}/$ac/$proj/$y" ; 

if ( ! -d $rcdir ) { 
  `mkdir -p $rcdir`;
}

my $fstat = "cwu$gwd.$date.$p.rms";
open (FILE,"> $rcdir/$fstat") 
 or die "Couldn't open $rcdir/$fstat for writing $!\n";

my @sites = `get_sites_from_proj_list $proj`;
chomp @sites;


#print "@sites\n";

chdir $rcdir ; 

print cwd. "\n"; 
print "$par{PPP_DIR}/$ac \n";
my (@stacovs,@stats);

my $time = localtime;
print "$time INFO - Starting pbo-stats\n";
my($site_fh,$site_file) = tempfile(UNLINK=>1);
my $i=1;
foreach my $s ( @sites ) {
    my $sta = "$dir/$s/$cal.$s.$frame.stacov";
    if ( -e $sta ) {
      push @stacovs,$sta; 
      print $site_fh "$sta\n";
      $i++;
      #printf ("%3d %s\n",$i++,"$cal.$s.$type.stacov");
      push @stats,`pbo-stats $dir/$s/$cal.$s.postfit.log.Z`
    }
}
$time = localtime;
print "$time INFO - Done pbo-stats\n";
print "# Processing summary for $cal , GPSWEEK DAY: $gwd\n";
print "# Sites processed: ", scalar @stacovs,"\n";
chomp @stats;
print FILE <<EOT;
* Site   Num        RMS 
*                  (mm)
EOT
print FILE ( map { "$_\n" } sort @stats );

my $snx = "CWU$gwd.$date.$p.snx";
my $stacov = "$cal.comb.r.stacov";   # "$cal.$proj.stacov";
print "Running catcov.pl -i $site_file | grep -v no_ant_ht_src > $stacov\n";
$time = localtime;
print "$time INFO - Starting catcov\n";
`catcov.pl -i $site_file | grep -v no_ant_ht_src > $stacov`;
#`find $dir -name '*.$frame.stacov' | xargs catcov | grep -v no_ant_ht_src > $stacov`;
$time = localtime;
print "$time INFO - Done catcov\n";

if ( ! -e $stacov ) {
    die "Could not create file $stacov\n";
}
unlink($snx);


#print "stacov2sinex -s $par{STA_INFO_DIR}/cwu_db.snx $cal.$proj.stacov $snx\n"; 
#`stacov2sinex -s $par{STA_INFO_DIR}/cwu_db.snx $cal.$proj.stacov $snx `; 
#use modified version until solve round up in antenna height
print "Current directory".cwd. "\n"; 
if ( ! -e $stacov ) {
  die "Combined stacov file $stacov was not created\n";
}
$time = localtime;
print "$time INFO - Starting stacov2sinex\n";
print "stacov2sinex -s $par{STA_INFO_DIR}/cwu_db.snx $stacov $snx\n"; 
`stacov2sinex -s $par{STA_INFO_DIR}/cwu_db.snx $stacov $snx `; 
$time = localtime;
print "$time INFO - Done stacov2sinex\n";

open(FILE,"< $snx");
my $np = (split(' ',readline(FILE)))[8];
printf ("%3d x 3 = %5d \nTotal SINEX PARS. =%5d \n%s\n",--$i,$i*3, $np, $snx) if -s $snx;

$time = localtime;
print "$time INFO - Starting tropo_table\n";
make_atm($cal);
$time = localtime;
print "$time INFO - Done tropo_table\n";

0;

=pod

=head1 run_tropo_table

For a particular site on a particular date, create a tropotable file.  Note
that it is far more expedient to create these at the time of point-positioning.

=cut

sub run_tropo_table {
      my $cal = shift;
      my $s = shift;

      # Build the directory name
      my $d = get_date($cal,'cal,num');
      my $gwd = sprintf("%05d",get_date($cal,'gwd'));
      my $yyyy = unpack ('a4',$cal);
      my $dir = "$par{PPP_DIR}/$ac/$yyyy/$cal";

      # Build the input file names
      my $wash_nml = "$dir/$s/$cal.$s.wash.nml";
      my $qr_nml = "$dir/$s/$cal.$s.qregres.nml";
      my $tdp = "$dir/$s/$cal.$s.tdp_final";

      # Build the output file name
      my $trop = "$dir/$s/$cal.$s.tropotable";

      # Uncompress stuff that we need (this could be done better) 
      my @uncompressed = ();
      foreach my $file ( ($tdp,$qr_nml,$wash_nml) ) {
	  if ( -e "$file.Z" ) {
	      `gzip -df "$file.Z" > $file`;
		  #anyinflate "$file.Z" => $file or die "Failed to uncompress $file.Z";
	      push(@uncompressed,$file);
          }
       }
       # Run tropotable
       my $time = localtime;
       print "$time INFO - tropo_table.py --tdp $tdp --net $s --out $trop --qr_nml $qr_nml --wash_nml $wash_nml\n";
       system("
	tropo_table.py --tdp $tdp --net $s --out $trop --qr_nml $qr_nml --wash_nml $wash_nml
       ");

       # Delete uncompressed versions of files
       foreach my $file (@uncompressed) {
           unlink $file;
       }
      }

=pod

=head1 make_atm

Determine whether a tropotable file exists for a particular site.  If it does,
uncompress it and concatenate it, otherwise, create one.  Creating a tropotable file
with this loop takes quite a bit of time, since each site is run serially.  If the
tropotable file is created during point-positioning, this saves time.

=cut

sub make_atm {
   my $cal = shift;

   # Build the PPP directory name
   my $d = get_date($cal,'cal,num');
   my $gwd = sprintf("%05d",get_date($cal,'gwd'));
   my $yyyy = unpack ('a4',$cal);
   my $dir = "$par{PPP_DIR}/$ac/$yyyy/$cal";

   # Find site names (from directory names)
   opendir ( my $ndh, $dir) or die "couldn't open $dir $!\n";
   my @sites = grep { /^....$/ } readdir($ndh);
 
   # Output file name
   my $atm = "CWU$gwd.$d.$p.met";
   open(my $fh, '>',$atm) or die "Couldn't open $atm for writing $!\n";

   # Iterate over each site
   my $i = 0;
   foreach my $s ( sort @sites ) {
      my $trop = "$dir/$s/$cal.$s.tropotable";
    
      # Check to see whether we already have a tropotable file (compressed)  
      if ( -e "$trop.Z" ) {
        `gzip -df $trop.Z > $trop`;
      }
      # Check to see whether we have an uncompressed tropotable file, or
      # that the original file wasn't compressed in the first place
      if ( ! -e $trop ) { 
	  # If we have no file, create one
          run_tropo_table($cal,$s); 
      }
      if ( ! -e $trop ) {
	      print "Could not make tropotable for $s\n";
	      next;
      }
     
      # For the first file, print the header, after that, just print the contents 
      if ( ! $i++ ) {
        print $fh slurp($trop);
      }
      else {
        print $fh grep { ! /^#/ } slurp($trop);
      }

      # Re-compress the tropotable file
      `compress $trop`;
   }
   close $fh;
   `gzip -f $atm`;
}
