#!/opt/perl/bin/perl
use File::Basename;
use File::Copy;
use File::Path;
use GPS::Defaults;
use GPS::RcvrAnt;
use GPS::APC;
use GOA::PCenter;
use Data::Dumper;
use GPS::DATES;
my $today = get_date('today','cal,time');
my %par = get_defaults( env => \%ENV );
my $dir = $par{STA_INFO_DIR}; #cwd;
my $pc_dir = "$dir/phase_center_maps/by_antenna_type";

my $igs_dir = $par{IGS_INFO_DIR};

my ($atx_dir,$atx_file,$wwww,$igsYY);
my $wwww = get_date('today','gpsw');
my $ra = new GPS::RcvrAnt;
my @pc_dirs=();

my $file = $ARGV[0];

##
  $atx_dir = dirname $file;
  $atx_file = basename $file;
  # Extract the IGS reference frame number and GPS week number
  if ( $atx_file =~ /^igs(\d\d)_(\d\d\d\d)\.atx$/ ) {
    #$wwww = unpack ('x6a4',$atx_file);
    $igsYY="igs$1";
	$wwww=$2;
	$pc_dir = "$dir/phase_center_maps/by_antenna_type.$wwww";
  }
  elsif ( $atx_file =~ /^ant_info.abs.atx$/ ) {
    $igsYY="ngs";
    $wwww='';
    $pc_dir = "$dir/phase_center_maps/by_antenna_type";
  }
  else {
	  print "Unknown file type $file\n";
	  exit 1;
  }

  # Delete existing files in the phase center directory
  if ( -d $pc_dir ) {
    my @files = glob("$pc_dir/*");
    unlink(@files) == @files or warn "Couldn't unlink all files in $pc_dir\n";
  }
  else {
    mkpath $pc_dir;
  }

  if ( $igsYY ) {
    unlink "$igsYY.atx"; 
    copy "$atx_dir/$atx_file", "$igsYY.atx";
    symlink "$igsYY.atx", $atx_file;
    system (" cat $igs_dir/extras.atx $igs_dir/zero.atx >> $igsYY.atx" );
  }

  my $apc = GPS::APC->new( file => $atx_file );
  mk_grn($apc);
  mk_sat($apc);

 ###

sub mk_grn {
  my $apc = shift;
  my @list = sort  grep { ! /(BLOCK I|GLONASS)/  } @{$apc->list('igs')};
  my $pc = GOA::PCenter->new( );
  open(my $ga,"> $dir/phase_center_maps/ant_goa.$atx_file") or die "Couldn't open $dir/phase_center_maps/ant_goa.$atx_file";
  my $header = header_ant_goa($atx_file);
  print $ga $header;
  foreach my $code ( @list ) {
    my $goa_ant =  $apc->{$code}{goa_name}; 	
	next if -e "$pc_dir/$goa_ant";
    my $offs = $apc->goa_offsets( igs_code => $code );
    foreach my $pc_type (  keys %$offs  ) {
        my $comment = " |$code| $apc->{$code}{comment}";
           $comment .= " LC = 2.5457*L1-1.5457*L2" if $pc_type eq 'LC' || $pc_type eq 'PC'; 
        $pc->add( goa_ant => $goa_ant,
                  pc_type => $pc_type,
	              east    => $offs->{$pc_type}{east},
	              north   => $offs->{$pc_type}{north},
	              up      => $offs->{$pc_type}{up},
	              comment => $comment 
	             );
    }  
    $src = $atx_file; # basename($apc->{$code}{comment});
    print $ga sprintf("%-20s %-9s |%-20s|\n",$code,$goa_ant,$src );
	open( my $fh, "> $pc_dir/$goa_ant") 
       or die "Couldn't open $pc_dir/$goa_ant $!\n";
    print $fh $apc->nml_ground( igs_code => $code );
    close($fh);
   }
   close($ga);
   copy ("$dir/phase_center_maps/ant_goa.$atx_file","$dir/ant_goa");
   $pc->print( file => "$dir/phase_center_maps/pcenter.$atx_file" );
   $pc->print( file => "$dir/pcenter" );
}

sub mk_sat {
  my $apc = shift;
  my ($sdate,$edate,$gps,$prn);
  my $sat_sys = 'G'; #GPS
  foreach my $igs_code ( $apc->list  ) {
     $edate = '00000000';
     my $a = $apc->{$igs_code};
     next if ! exists $a->{sat_code_nn};
     next if  $a->{sat_code_nn} !~ /^$sat_sys/;
     $sdate = sprintf"%4d%02d%02d",@{$a}{qw/syyyy smm sdd/};
     if ( exists $a->{eyyyy} ) {
       $edate = sprintf"%4d%02d%02d",@{$a}{qw/eyyyy emm edd/};
     }
     $gps = $a->{sat_code_nnn};
     $gps =~ s/^$sat_sys//; $gps =~ s/^0+//;
     $gps = sprintf 'GPS%02d',$gps;
     open( my $fh , "> $pc_dir/$gps.$sdate.$edate" );
     print $fh $apc->nml_sat( igs_code => $igs_code);
    close $fh;
  }  
}


sub header_ant_goa {
my $h = <<EOT; 
#ant_goa : antenna codes mapping table. 
#          Automatically generated from $atx_file
#Updated : $today	 
#------------------------------------------------------------
# GIPSY OASIS (GOA) antenna codes used in pcenter 
# are 9 char. long so we need to convert the IGS codes 
# to an internal  9 char. long GIPSY antenna code.
# The conventions are to assign the first 2 char. to the
# antenna's vendor, and use the last character for the dome.
# the last character, of the remaining after truncating 
# the name, is replaced by A,B,C etc. to make a unique name.
#
#
# Marcelo Santillan Nov. 2004.
# marcelo\@geology.cwu.edu
# Geodesy Lab & PANGA 
# Central Washington University
#-----------------------------------------------------------	
#
#
#VENDOR                         GOA code
#---------------------------------------	
EOT

my %gv= %GPS::RcvrAnt::goa_vendor_name;
my %gd= %GPS::RcvrAnt::goa_dome;
foreach my $v ( sort keys %gv ) {
    $h.=sprintf("#%-30s %2s\n",$v, $gv{$v});
}
$h.= qq/
#Dome  GOA code
/;
foreach my $d ( sort keys %gd ) {
    $h.=sprintf("#%4s %2s\n",$d, $gd{$d});
}
 
$h.= qq/
#GV,DD:  GOA Vendor,Dome
#IGS 15 char.   DOME GV-----DD 
#2345678901234567890 123456789 |
/;

#print $h;
return $h
}
