#!/opt/perl/bin/perl
use strict;
use warnings;
use GPS::DATES;
my $usage = qq{
	Usage : log2sta_pos site [agency]
	site   : 4 char. site name
	agency : unavco,sopac,cors,panga,igscb (default: unavco)
};

my $site = shift || die "$usage";

my $agency = shift || "unavco";

 $site = lc($site);
my $SITE = uc( $site );

my ($year, $mon, $mday, $hour, $min, $sec, $duration , @xyz, @v); 
$duration = 1000001.00;
@v=(0,0,0);
$hour=0;
$min=0;
$sec=0;

my @secs = ( "'site identification'", "receiver", "antenna" );
my @date;
foreach my $ssec ( @secs ) {
   @date = `parse_log -s $site -a $agency -section $ssec -field 'date'`;
   ($year,$mon,$mday) = getdate(@date);
   last if (  $year &&  $mon && $mday );
};
die "Couldn't parse date\n" if  ! $year && $mon && $mday;
#exit;
#my $date;
#my (undef,undef,$cal)= split(/\:/,$date);
#chomp($cal);
#$cal =~ s/^\s+//;
#$cal =~ s/\s+$//;
#($year,$mon,$mday)=unpack("a4x1a2x1a2",$cal) if $cal =~ /\d{4}-\d+-\d+/;


my @coords =grep /coordinate/, `parse_log -s $site -a $agency -section 'site location' -field coordinate `;

if ( ! @coords ) { die "Couldn't parse coordinates\n"; };

foreach my $c ( @coords ) {
	chomp($c);
	my (undef,undef,$x)=split(/\:/,$c);
	push(@xyz,$x);	
	
};
#print "$site $cal @xyz\n";

my $mdhsf = " %.2d"x4;
my $xyzf = "%15.4f"x3;
my $vf   = "%15.8E"x3;
my $comment = "parsed from $agency sitelog";

printf(" %.4s %.4d$mdhsf %5.2f %10.2f $xyzf $vf $comment\n", $SITE,
       $year, $mon, $mday, $hour, $min, $sec, $duration , @xyz, @v ,$comment);




sub getdate {
  my @d = @_;
  @d = grep /date installed/, map { lc($_) } @d;
  my ($year,$mon,$mday);
  foreach my $date ( @d ) {
     my (undef,undef,$cal)= split(/\:/,$date);
     if ( $cal ) {
        chomp($cal);
        $cal =~ s/^\s+//;
        $cal =~ s/\s+$//;
        ($year,$mon,$mday)=unpack("a4x1a2x1a2",get_date($cal,'cal')) ;
        #($year,$mon,$mday)=unpack("a4x1a2x1a2",$cal) if $cal =~ /\d{4}-\d+-\d+/;
     };
  };
  
  return ($year,$mon,$mday)

}
