#!/opt/perl/bin/perl
use strict;
use Carp;
use GPS::DATES;
use GPS::Defaults;
use File::Basename;
use File::Path;
use Getopt::Long;
my $progname = basename ($0);
my $help='';
my $stats = '';
my $date = '';  # generic date
my $sdate = '';  # generic date
my $edate = '';  # generic date
my ($doy,$cal,$gwd)=('')x3;
my $proj='';
my $ac = 'igs';
my $net='^[A-Z_]+$';
   $net = '';
my $rev = 0;
my $snx = 0;
my $force = 0;
my $orb_type = '';
my $args = @ARGV;
my $author =<<FIN;

Marcelo Santillan, April 2006
Geodesy Lab & PANGA
Central Washington University
FIN
my $usage =<<EOT;
$progname : Merge bias fixed networks 
  and make sinex files if requested.
  
Usage:
  $progname -proj proj [-date date] [-snx] [-force]


by default if no date is supplied $progname will 
merge the days that in 
Ambiguity_processing/proj/yyyy/yyyy-mm-dd/
that are not present in
Raw_combinations/proj


Example:
  to merge all the days that are not still done. 

  $progname -proj pbo-week 

  merge pbo-week 2005-04-01, even if was already merged.

  $progname -proj pbo-week -date 2005-04-01 -snx [-orb [rapid|final|ultra|predicted]]
 
$author
EOT
#Get command line options
GetOptions( 'ac=s'   => \$ac,
            "proj=s" => \$proj,
            "date:s" => \$date,
            "sdate:s" => \$sdate,
            "edate:s" => \$edate,
            "net:s"  => \$net,
            'force' => \$force,
            'orb:s' => \$orb_type,
            'rev'   => \$rev,
            "snx!" => \$snx,
	        "help"  => \$help
	   ) || die "error in options";

if ( ! $args ) { die "$usage\n" };
if (  $help ) {  print "$usage\n";exit; }

my %par=get_defaults();

if ( ! -e "$par{AMB_DIR}/$ac/$proj" ) {
  croak "$par{AMB_DIR}/$ac/$proj doesn't exists $!\n";
}

my $yyyy = '.';
my $cal = '.';
if ( $date ) {  
  $cal = get_date($date,'cal');
  ($yyyy) = split /-/,$cal;
  $force = 1;
}
if ( ! -e "$par{RAW_COMB_DIR}/$ac/$proj/$yyyy" ) {
  #mkdir "$par{RAW_COMB_DIR_ARCHIVE}/$ac/$proj";
  mkpath "$par{RAW_COMB_DIR}/$ac/$proj/$yyyy";
}

$orb_type = $orb_type =~ /rapid/i      ? 'r.' : 
            $orb_type =~ /ultra/i      ? 'u.' :
            $orb_type =~ /predicted/i  ? 'p.' :
                                         ''  ;  # final

#$stats = 1 if $proj =~ /^pbo/;
$stats = 1;
if ( $sdate ) {
  $sdate = get_date($sdate,'cal,num');
}
$sdate = $date if ! $sdate && $date ;

if ( $edate ) {
 $edate = get_date($edate,'cal,num');
}
$edate = $sdate if ! $edate && $sdate;

my $tmpdir =  "tmp.$$";
#print "$proj $date $cal $yyyy snx=$snx $par{AMB_DIR_ARCHIVE}\n";

opendir(my $amb_dh ,"$par{AMB_DIR}/$ac/$proj") 
       or croak "Couldn't open $par{AMB_DIR}/$ac/$proj $!\n";
my @years = sort grep /$yyyy/,grep !/\./,readdir($amb_dh);
close($amb_dh);
#print "@years\n";

chdir "$par{RAW_COMB_DIR}/$ac/$proj/$yyyy";

foreach my $y ( @years ) {
   opendir(my $y_dh,"$par{AMB_DIR}/$ac/$proj/$y")
        or croak "Couldn't open $par{AMB_DIR}/$ac/$proj/$y $!\n";
   my @days = grep !/\.+/,readdir($y_dh);
   @days = sort grep /^$cal/,@days;
   close($y_dh);
   my $ii=1;
   foreach my $d ( @days ) {
     next if -e "$d.comb.stacov" && ! $force;
     my $c = $d;  $c =~ s/-//g;
     if ( ! $date && $sdate ) { next if $c < $sdate; }
     if ( ! $date && $edate ) { next if $c > $edate; }
     print "Merging $d\n";
     opendir( my $net_dh,"$par{AMB_DIR}/$ac/$proj/$y/$d");
     my @nets = sort grep /^[A-Z]/,readdir($net_dh);
     close($net_dh);
     #print "|",join '|',@nets,"|\n";
     my %n = ();
     @n{@nets} = @nets; 
     @nets = sort grep { /^NA_/ }  keys %n;
     push @nets, sort grep { ! /^NA_/ } keys %n;
     $ii=1;
     foreach my $n ( @nets ) {
         next if ! $n;
         next if $net && $n !~ /$net/;
         my $file = "$par{AMB_DIR}/$ac/$proj/$y/$d/$n/$d.fix.".$orb_type."stacov";
         if ( -e $file ) {
           print sprintf ("%-11s ",$n); 
           print "\n" if ($ii++ % 7) == 0;
           splitcov($d,$file); 
         }
         else {
           carp "Warning: $file doesn't exists! \n";
         }
     }
     print "\n";
     my @sta = glob("$tmpdir/*.stacov");
    #`catcov $tmpdir/*.stacov|grep -v no_ant_ht_src > $d.comb.stacov`;
    if ( @sta ) {
     `catcov @sta|grep -v no_ant_ht_src > $d.comb.${orb_type}stacov` ;
      mk_stats( $d,\@nets ) if $stats;
      system("make_pbo_amb_snx -proj $proj -date $d -ac $ac") if $snx;
      (unlink @sta) == @sta
           or carp "Couldn't unlink all of $tmpdir/*.stacov $!\n";
    }
   }
}
my @junk = glob("$tmpdir/*");
(unlink @junk ) == @junk 
   or carp "Couldn't unlink all of $tmpdir/* $!\n";

rmdir $tmpdir;

sub splitcov {
  my $cal = shift;
  my $file = shift;
  mkdir $tmpdir if ! -e $tmpdir;

  chdir $tmpdir;
  system("splitcov",$file);

  my @dup = glob("dup*.stacov");
  (unlink @dup) == @dup 
         or carp "Couldn't unlink all of dup*.stacov $!\n";
  
  chdir "..";
  
}


sub mk_stats {
   my $cal = shift;
   my $nets = shift;
   my ($y) = split /-/ ,$cal;
   my $header ="* Site   Num        RMS\n*                  (mm)\n";
   open(my $fh,"> $cal.stats");
   print $fh $header;
   print "Making stats for $cal ...";
   my %stats=();
   foreach my $n ( @$nets) {
      my $postfit = "$par{AMB_DIR}/$ac/$proj/$y/$cal/$n/$cal.$n.postfit.log.Z";
      #print "pbo-stats $postfit >> $cal.stats\n";
      if ( -e $postfit ) {
        foreach my $l (  `pbo-stats $postfit` ) {
          my ($site) = split ' ',$l;
          $stats{$site}=$l;
        }
      }
   }
   foreach my $s ( sort keys %stats ) {
     print $fh $stats{$s};
   }
   print "done\n";
}
