#!/opt/perl/bin/perl
use strict;
use File::Basename;
use Scalar::Util qw(looks_like_number);
use Pod::Text::Termcap;
use Getopt::Long;
use GOA::Util;
use GPS::DATES;

my $progname = basename $0;
my ($tdp,$wash_nml,$qr_nml,$out,$tropo_apriori,$help);
my $date = '';
my $net='';
$out = "troptable";
$wash_nml='wash.nml';
$qr_nml='qregres.nml';
$tdp='TDPTABLE';
$tropo_apriori='TDPdry';
my $args = @ARGV;
GetOptions( 'tdp:s' => \$tdp,
            'wash_nml:s'   => \$wash_nml,
            'qr_nml:s'   => \$qr_nml,
            'out:s' => \$out,
            'net:s' => \$net,
            'date:s' => \$date,
	    'dryz:s' => \$tropo_apriori,
            'help' => \$help,
            
          ) or die "Error in options\n";

if ( ! $args || $help || ! $net ) {
  usage();
  exit 1;
}

$net = uc $net;

my $trop = {};

read_nml($trop,$wash_nml);
read_nml($trop,$qr_nml);
$tdp =  'tdp_final' if -e 'tdp_final';
my %wtrop = read_tdp($tdp);
open(my $fh, '>', $out ) or die "Couldn't open $out $!\n";
print $fh qq(#For more information about Troposphere Parameters, in a system with GOA 5.0 type: gd2p.pl -h_wash 
# GRADDRIFT = $trop->{GRADDRIFT} km/sqrt(sec)
# TROPDRIFT = $trop->{TROPDRIFT} km/sqrt(sec)
# SECS[J2000]  ZD[m] TROP_DRY[m] WETZ[m] WETZ_SIG[m] TRPAZSIN[km] TRPAZCOS[km]  TRPAZSIN_SIG[km] TRPAZCOS_SIG[km] SITE SNET  MAP_FUNC
);
my ($h,$zd,$wz,$azs,$azc,$azs_sig,$azc_sig,$wz_sig);
foreach my $s ( sort keys %wtrop ) {
  my $map = $trop->{$s}{trop_map};
  my $tdry = $trop->{$s}{trop_dry};
  foreach my $secs ( sort { $a <=> $b } keys %{$wtrop{$s}} ) {
     # Interpolate the dry tropospheric delay from the VMF1 model
     # if the file exists
     if ( -e $tropo_apriori ) {
       my $output = `interpolate_dry.py -i $tropo_apriori -t $secs -s $s`;
       (undef,$tdry) = split(' ',$output);
       if ( ! looks_like_number($tdry) ) {
           next;
       }
     }
     $h=$wtrop{$s}{$secs};
     $wz = $h->{WETZTROP}{value};
     $azs =$h->{TRPAZSIN}{value};
     $azc =$h->{TRPAZCOS}{value};
     $wz_sig = $h->{WETZTROP}{sig};
     $azs_sig =$h->{TRPAZSIN}{sig};
     $azc_sig =$h->{TRPAZCOS}{sig};
     $zd = $wz+$tdry;
     print $fh "$secs $zd $tdry $wz $wz_sig  $azs $azc $azs_sig $azc_sig $s $net $map\n";
  }
}

sub read_nml {
   my $trop = shift;
   my $file = shift;
   open(my $fh, $file) or die "Couldn't open $file $!\n";
   my %l =();
   my ($i,$site,$tdry,$tmap,$tg,$tg_val);
   while( <$fh> ) {
      if ( /(TROPDRIFT|GRADDRIFT)\s*=\s*(.*)$/i ) {
         $tg=uc $1;
         $tg_val=trim($2);
         $trop->{$tg}=$tg_val;
      }
      if ( /NMLname\(\s*(\d+)\s*\)\s*=\s*'(....)'/i ) {
         $i=$1;
         $site = uc $2;
         $l{$i}=$site;
         $trop->{$site}={};
      }
      if ( /NMLTropMap\(\s*(\d+)\s*\)\s*=\s*'(.+?)'/i ) {
        $i=$1;
        $tmap = $2;
        $site = $l{$i};
        $trop->{$site}{trop_map} = $tmap;
      }
      if ( /NMLTROP_DRY\(\s*(\d+)\s*\)\s*=\s*(.+?)(\s|)$/i ) {
        $i=$1;
        $tdry = $2;
        $site = $l{$i};
        $trop->{$site}{trop_dry} = $tdry;
        #print "Key: $i Name:$site |$tdry| $tmap\n"; 
      }
   }
   #return %trop
}

sub read_tdp {
   my $file = shift;
   open(my $fh, $file) or die "Couldn't open $file $!\n";
   my ($secs,$value,$sig,$par,$site,$name);
   my %wtrop = ();
   while( <$fh> ) {
     next if ! /(WETZTROP|TRPAZ)/ ;
     ($secs,$value,$sig,$name) = (split(' ',$_))[0,2,3,4];
     ($par,$site) = unpack('a8a4',$name);
     $wtrop{$site}{$secs}{$par}={ value =>$value, sig =>$sig};
   }
   return %wtrop
}

sub usage {
  my $pod=Pod::Text::Termcap->new();
  $pod->parse_from_filehandle(man_page());
}

sub man_page {
my $man =qq(
=head1 NAME

$progname

script_template

=head1 OPTIONS

=over 3

=item -i input_file

=item -o output_file

=back

=head1 EXAMPLES

=over 3

=item $progname  -net ak_a  


=back

=head1 AUTHOR

Victor Marcelo Santillan <marcelo\@geology.cwu.edu>

=head1 COPYRIGHT

Copyright \(c\) 2007 

Central Washington University

=cut
);
open(my $fh,"<",\$man ) or die "$!\n";
return $fh
}

