#!/opt/perl/bin/perl
use warnings;
use strict;
use Getopt::Long;
use File::Basename;
use File::Copy;
use GPS::DATES qw(get_date cal2jd jd2gpsw dow2gdow jd2dow );
use GPS::Defaults;
use GOA::Util;
my $progname = basename $0;
my $usage = qq(
  $progname -proj pbo-rapid -date 2005-07-07 
);

die "$usage \n" unless @ARGV;

my $proj = 'pbo-week';
my $date = '';
my $ac = 'igs';
my $help = '';
my $frame='itrf05';
   $frame='igs08';
GetOptions(
     'ac=s'   => \$ac,
     'proj=s' => \$proj,
     'date=s' => \$date,
     'frame:s' => \$frame,
     'help!'  => \$help,
)or die "Error in options\n";

my %par = get_defaults( );

$date = get_date($date,"cal") if $date;

my $type = "comb";
   $type .= '.r' if $proj eq 'pbo-rapid';
my $p = "b";
$p = "e" if $proj =~ /^pbo-final/;
$p = "e" if $proj =~ /^pbo-reanalysis/;
$p = 'c' if $proj eq 'pbo-supplemental';
$p = 'f' if $proj eq 'pbo-supplemental6';
$p = '' if $proj eq 'panga';
if ( $proj =~ /^pbo-camp-([a-z]+)/ ) {
  $p = $1;
}
my($yyyy) = split /-/,$date;
my $dir = "$par{RAW_COMB_DIR}/$ac/$proj/$yyyy";
if ( ! -d $dir ) {
    `mkdir -p $dir`;
}
chdir $dir or die "$!\n";
opendir(DIR,$dir);

my @files = grep !/^\.+/,readdir(DIR);
my (%fsnx,%fsta);
foreach my $f ( @files ) { 	
    if ( $f =~ /snx$/ ) {
      my ($ag,$gpsw,$gdow,$date,$p,$ext)=unpack("A3A4A1x1A8x1A1x1A3",$f);	    
      $fsnx{$date}=$f;
    }
    if ( $f =~ /stacov$/ ) {
       my ($cal,undef,undef) = split(/\./,$f);
       $cal =~ s/-//g;
       $fsta{$cal}=$f;
    }
}

if ( $date ) {
  %fsta=();
  my $d = $date;
  $d =~ s/-//g;
  print $d,"\n";
  $fsta{$d}=glob("$date.$type.stacov");
}

#print "@sites\n";

foreach my $d ( sort keys %fsta ) {
   if ( ! exists $fsnx{$d} || $date ) {
     my $cal = sprintf("%4d-%02d-%02d",unpack("A4A2A2",$d));
     make_atm($cal,$proj);
     my $jd = cal2jd($cal);
     my $gpsw = sprintf("%04d",jd2gpsw($jd));
     my $gdow = dow2gdow(jd2dow($jd));
     my $snx = "CWU$gpsw$gdow.$d.$p.snx";
     if ( -e "$cal.stats" ) { move( "$cal.stats", "cwu$gpsw$gdow.$d.$p.rms"); }
     my $stacov = $fsta{$d};
     print "$stacov $snx\n";
     unlink($snx);
     #using modified version of stacov2sinex
     print "stacov2sinex -s  $par{STA_INFO_DIR}/cwu_db.snx $stacov $snx\n"; 
     my $output = `stacov2sinex -s  $par{STA_INFO_DIR}/cwu_db.snx $stacov $snx 2>&1`;
     print $output,"\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 $proj = shift;
      my $n = 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{AMB_DIR}/$ac/$proj/$yyyy/$cal";

      # Build the input file names
      my $wash_nml = "$dir/$n/$cal.$n.wash_amb.nml";
      my $qr_nml = "$dir/$n/$cal.$n.qregres.nml";
      my $tdp = "$dir/$n/$cal.$n.TDPTABLE";
      my $tropo_apriori = "$dir/$n/$cal.$n.TDPdry";

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

      # Uncompress stuff that we need (this could be done better) 
      my @uncompressed = ();
      foreach my $file ( ($tdp,$qr_nml,$wash_nml,$tropo_apriori) ) {
	  if ( -e "$file.Z" ) {
	      `gzip -df "$file.Z" > $file`;
	      push(@uncompressed,$file);
          }
       }
       # Run tropotable
       my $time = localtime;
       if ( -e $tropo_apriori ) {
           print "$time INFO - tropo_table.py --tdp $tdp --net $n --out $trop --qr_nml $qr_nml --wash_nml $wash_nml --dryz $tropo_apriori\n";
           system("
	   tropo_table.py --tdp $tdp --net $n --out $trop --qr_nml $qr_nml --wash_nml $wash_nml --dryz $tropo_apriori
           ");
       } else {
           print "$time INFO - tropo_table.py --tdp $tdp --net $n --out $trop --qr_nml $qr_nml --wash_nml $wash_nml\n";
           system("
	   tropo_table.py --tdp $tdp --net $n --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;
   my $proj = shift;

   # Build the AMB 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{AMB_DIR}/$ac/$proj/$yyyy/$cal";

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

   # Iterate over each site
   my $i = 0;
   foreach my $n ( sort @nets ) {
      my $trop = "$dir/$n/$cal.$n.tropotable";
    
      # Check to see whether we already have a tropotable file (compressed)  
      if ( -e "$trop.Z" ) {
	print "Using existing $trop.Z\n";
        `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 ) { 
	  print "Could not find $trop, running tropo_table.py\n";
	  # If we have no file, create one
          run_tropo_table($cal,$proj,$n); 
      }
     
      # 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;

   print "Compressing $atm\n";
   `gzip -f $atm`;
}
