#!/opt/perl/bin/perl
use strict;
#use lib "$ENV{GPS_HOME_DIR}/bin/pm";
use GOA::Util;
use GPS::PRN_GPS;
use GPS::Defaults;
use GPS::DATES;
use GPS::FTP;
use File::Basename;
use File::Copy;
use Carp;
use Cwd;
use Getopt::Long;
my $here = cwd;
my %par=get_defaults( env => \%ENV );
my $author =<<FIN;

Marcelo Santillan, May. 2006
Geodesy Lab & PANGA 
Central Washington University

FIN

#GIPSY satellite phase center values
# the z-axis is directed from the satellite center of mass 
# towards the Earth center
#Block I
#dx = 0.21000 m
#dy = 0.00000 m
#dz = 0.854000 m 

#Block II & IIA
#dx = 0.2790 m 
#dy = 0.0000 m 
#dz = 0.9519 m 

#Block IIR 
#dx = 0.0580 m 
#dy = -0.0680 m 
#dz = -0.6300 m

################################################################
#IGS satellite phase center values
#Block II & IIA 
#dx = 0.279 m  	
#dy = 0.000 m  	
#dz = 1.023 m

#Block IIR 	
#dx = 0.000 m 	
#dy = 0.000 m 	
#dz = 0.000 m

my %sat_off = ( I   => { IGS => { x => 2.1000e-4   , y => 0.0           , z => 8.5400e-4       },
                         #IGS => { x => 0.0         , y => 0.0           , z => 0.0             },
                         JPL => { x => 2.1000e-4   , y => 0.0           , z => 8.5400e-4       }
                       },
                II  => { IGS => { x => 0.279e-3    , y => 0.000e-3      , z => 1.023e-3        }, 
                         JPL => { x => 2.790000e-04, y => 0.000000e+00  , z => 9.519000e-04    }
                       },
    	        IIA => { IGS => { x => 0.279e-3    , y => 0.000         , z => 1.023e-3        }, 
                         JPL => { x => 2.790000e-04, y => 0.000000e+00  , z => 9.519000e-04    }
                       },
                IIR => { IGS => { x => 0.000        , y => 0.000        , z => 0.000           }, 
                         JPL => { x => 5.800000e-05 , y => -6.800000e-05, z => -6.300000e-04   },
                       },
              );
my $progname = basename $0;
my $usage =<<EOT;
  $progname includes the information into the tdpfile
  for overriding the   satellite phase center offsets 
  that are hardcoded in GIPSY.
  
  Usage:
  $progname [-agency [jpl|igs] ] [-tdp tdpfile] 
            [-prngps PRN_GPS_file] [-help]
  
  Options:
    agency: IGS or JPL (default IGS )
    tdp   : tdpfile    (default TDPfile)
    prngps: PRN_GPS    (default /goa/etc/PRN_GPS )
 
 $author 
EOT
my $pcm_dir = $par{PCMAPS} || "$here/phase_center_maps/by_antenna_type"; 
my $pcm ='';
my $ac  = 'IGS';
my $tdpfile = 'TDPfile';
my $prn_gps = "$ENV{GOA_VAR}/etc/PRN_GPS";
my $clock_file = '';
my $args = @ARGV;
my $help='';
my $save='';
my $date='';
my $antcal='GPS_antcal_ref';
my $wwww='';
GetOptions (
             'ac:s'     => \$ac,
             'agency:s' => \$ac,
             'tdp:s'    => \$tdpfile,
             'date:s'   => \$date,
			 'antcal:s' => \$antcal,
             'prngps:s' => \$prn_gps,
             'savecopy' => \$save,
             'help'     => \$help,
) or die "Error in options\n";



if ( ! $args ) { die $usage };
if ( $help   ) { print $usage; exit; }
$ac = lc $ac;
if ( $ac !~ /^(IGS|JPL|JGP|CODE)$/i ) { 
  die "Unknown agency $ac. (agency : IGS,JPL,JGP,CODE )\n";
}
$pcm_dir = $par{PCMAPS}; #_ABS};
$wwww = get_wwww();
$pcm = pc_maps($date);
my $pg = GPS::PRN_GPS->new();
my @lines;


my %seen=();
my @gps_sats = grep { ! $seen{$_}++ } map { /BIASGPS(\d\d)/;$1 } grep { /SAT BIASGPS/ }slurp($tdpfile);
#`cat TDPfile | grep -P 'SAT BIASGPS\d\d' | awk '{print $6}' | sort -u | cut -c8-10`;
chomp @gps_sats;
my %gps_in_tdp=();
@gps_in_tdp{@gps_sats}=@gps_sats;

##### no need for IGS, 
#open(TDP,"< $tdpfile") or croak "Couldn't open $tdpfile for reading $!\n";
##### igs tdp doesn't have *_OFF and jgp doesn't use this script. 
#@lines = grep { !/[XYR]_OFF/ } <TDP>;
####
my @offsets;
my ($t,$x,$y,$z,$block,$gx,$gy,$gz,$gps,$pc) ;
   %seen=();
#my $fmt = " %14.4f                 0  %14.7f     1.0e-7      %8s   GPS%02d\n";
#my $fmt = " %14.4f  %15.7f %15.7f 1.0 %8s   GPS%02d\n";
my $fmt = "0.0 %.15g %.15g 1.0 %8s%8s\n";
for my $g ( 1 .. 61 ) {
   next if ! exists $gps_in_tdp{$g};
   ($x,$y,$z)=(0.0)x3;
   $gps = sprintf "GPS%02d", $g;
   #print $pg->prn( gps => $g,date => $date),"\n";
   $block = $pg->block( gps => $g );
   $gx = $sat_off{ $block }{JPL}{x}; 
   $gy = $sat_off{ $block }{JPL}{y}; 
   $gz = $sat_off{ $block }{JPL}{z}; 
   ($pc) = grep { /$gps/ } @$pcm;   
   ($x,$y,$z) = xyz($pc);   
   $x -= $gx; 
   $y -= $gy; 
   $z -= $gz; 
   push @offsets, sprintf $fmt, $gx,$x,'X_OFF',$gps;   
   push @offsets, sprintf $fmt, $gy,$y,'Y_OFF',$gps;   
   push @offsets, sprintf $fmt, $gz,$z,'R_OFF',$gps;   
}

#system ("cat <<EOT > tdp_gps_pc.abs
#@lines
#EOT
#");

push @lines,@offsets;


copy $tdpfile, "$tdpfile.orig" if -e $tdpfile && $save ;

#open(TDP,"> $tdpfile") or die "Couldn't open $tdpfile for writing $!\n";

# append only
open(TDP,">> $tdpfile") or die "Couldn't open $tdpfile for writing $!\n";

print TDP @lines;

close (TDP);

sub ecc {
  my $g = shift;
  return xyz($g)
}
sub get_wwww {
  my ($wwww) = map { /igs0\d_(....)\.(atx|xyz)/;$1 } grep { /^SAT / } slurp($antcal);
  return $wwww
}
sub xyz {
  my $pc =  shift;
  my ($x,$y,$z)=(0.0)x3;
  open ( my $fh, "< $pcm_dir.$wwww/$pc" ) or croak "couldn't open $pc $!\n";
  while ( <$fh> ) {
    chomp;
    next if  ! /ECCENTRICITY/ ;
    s/\s*$//g;
    s/^.*XYZ\s*://;
    ($x,$y,$z) = split ' ',$_;
    last;
  }
  return ($x,$y,$z)
}
sub pc_maps {
  my $date = shift || 'today' ;
  $date = get_date($date,'cal,num');
  my $dir = "$pcm_dir.$wwww";
  opendir(my $dh , $dir) or croak "Couldn't open $dir $!\n";
  my @pc_maps = sort grep { /^GPS\d\d\./ } readdir $dh;
  my ($gps,$sdate,$edate);
  my @out=();
  foreach my $pc ( @pc_maps ) {
    ($gps,$sdate,$edate) = split /\./,$pc;
    next if $sdate > $date;
    next if $edate ne '00000000' && $edate < $date;
    push @out,$pc;
  }
  return \@out
}

