#!/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::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 = "final";
my $help = '';
my $abs_pc = 1;
my $frame = 'raw';
GetOptions(
     'ac=s'        => \$ac,
     'igs_abs'   => \$abs_pc,
     'abs_pc'    => \$abs_pc,
     'proj=s'      => \$proj,
     'date=s'      => \$date,
     'frame:s'      => \$frame,
     'upload!'     => \$upload,
     'orb:s'       => \$orb,
     'help!'       => \$help,
)or die "Error in options\n";

my $p = "a";
if ( $proj =~ /pbo-camp-(\w)/ ) {
  $p = $1;
} elsif ( $proj =~ /pbo-reanalysis/ ) {
 $p = 'e';
} elsif ( $proj =~ /pbo-supplemental6/ ) {
 $p = 'f';
}
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");

#if ( $abs_pc ) {
# $par{STA_INFO_DIR} .= '.abs';
#}

my $dir = "$par{PPP_DIR_ARCHIVE}/$ac/$y/$cal";
my $rcdir = "$par{RAW_COMB_DIR_ARCHIVE}/$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_ARCHIVE}/$ac \n";
my (@stacovs,@stats);

my $i=1;
foreach my $s ( @sites ) {
    my $sta = "$dir/$s/$cal.$s.$frame.stacov";
    if ( -e $sta ) {
      push @stacovs,$sta; 
      $i++;
      #printf ("%3d %s\n",$i++,"$cal.$s.$type.stacov");
      push @stats,`pbo-stats $dir/$s/$cal.$s.postfit.log.Z`
    }
}
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";
#`catcov @stacovs | grep -v no_ant_ht_src > $stacov`;
print "Running Find in make_pbo_pp_snx";
`find $dir -name '*.$frame.stacov' | xargs catcov | grep -v no_ant_ht_src > $stacov`;

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";
}
print "stacov2sinex -s $par{STA_INFO_DIR}/cwu_db.snx $stacov $snx\n"; 
`stacov2sinex -s $par{STA_INFO_DIR}/cwu_db.snx $stacov $snx `; 

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;

#make_atm($cal);

#`gzip $snx`;

sub make_atm {
   my $cal = shift;
   my $d = get_date($cal,'cal,num');
   my $gwd = get_date($cal,'gwd');
   my $yyyy = unpack ('a4',$cal);
   my $dir = "$par{PPP_DIR_ARCHIVE}/$ac/$yyyy/$cal";
   opendir ( my $ndh, $dir) or die "couldn't open $dir $!\n";
   my @sites = grep { /^....$/ } readdir($ndh);
   my $atm = "CWU$gwd.$d.$p.met";
   my $i=0;
   open(my $fh, '>',$atm) or die "Couldn't open $atm for writing $!\n";
   foreach my $s ( sort @sites ) {
      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";
      my $trop = "$dir/$s/$cal.$s.tropotable";
      $trop = -e $trop ? $trop : "$cal.$s.tropotable";
      #print "$tdp.Z\n"; 
      if ( -e "$tdp.Z" ) {
       system("
        gzip -dfc $tdp.Z > $tdp
        gzip -dfc $qr_nml.Z > $qr_nml
        gzip -dfc $wash_nml.Z > $wash_nml
        tropo_table -tdp $tdp  -net $s -out $cal.$s.tropotable -qr_nml $qr_nml -wash_nml $wash_nml
        \\rm $tdp $qr_nml $wash_nml
       ");
      }
      else {
        next;
      }
      
      if ( -e "$trop.Z" ) {
        `gzip -df $trop.Z`;
      }
      
      if ( ! -e $trop ) { 
        next;
      }
      
      if ( ! $i++ ) {
        print $fh slurp($trop);
      }
      else {
        print $fh grep { ! /^#/ } slurp($trop);
      }
      unlink $trop if -e $trop;
   }
   close $fh;
   `gzip -f $atm`;
}

