#!/usr/bin/perl

# Perl script to convert USGS station list to UCB coord list format

use Getopt::Std;

$gs_sta_file = "/work/ftp/pub/doc/ncsn/ncsn.stations";

sub print_syntax {
    my($cmdname) = @_;
    $cmdname = $1 if ($cmdname =~ m|^.*/([^/]+)$|);
    printf	
	"$cmdname - Convert NCSN station list to UCB instr.db.coord format
Syntax:
$cmdname [-h] [-d n] [-i NCSN_station_file]
where:
	-h   Print this synopsis.
	-i NCSN_station_file - read from an NCSN_station_file instead of
             the default file: $gs_sta_file
        -s   Use SEED channel name instead of USGS channel name\n";
    exit(1);
}

getopts("hi:s");

&print_syntax if ($opt_h);

$gs_sta_file = $opt_i if ($opt_i);

$depth = 0;
$rate = 100.0;

open(NCSN, "< $gs_sta_file") or die "Error opening $gs_sta_file: $!\n";
print <<EOF;
Stat Net Cha Lo        Rate        Start time            End time          Lat        Lon   Elev Depth     Dip Azimuth  Instrument
------------------------------------------------------------------------------------------------------------------------------------
EOF

#         1         2         3         4         5         6         7         8         9         0         1         2         3         4         5
#123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890
#AAR  NC VHZ AARM V  AARV AARS 39 16.5561 121  1.6179   911 A  AIRPORT ROAD SITE      GSM 19760720 30000000  19760720 30000000 EHZ -- AARV
#    | |                      |  |       |   |       |    |                              |        |        |                  |  |       
while (<NCSN>) {
    ($sta,$net,$gs_chan,$j1,$lat_d,$lat_m,$lon_d,$lon_m,$elev,$j2,$on_y,$on_m,$on_d,$off_y,$off_m,$off_d,$seedchan,$loc,$j3) = 
	unpack "A5A3A4A18A3A8A4A8A4A51A4A2A3A4A2A3A3A3A5", $_;
    $sta =~ s/\s//g;
    $net =~ s/\s//g;
    if ($opt_s) {
	$chan = $seedchan;
    }
    else {
	$chan = $gs_chan;
    }
    $chan =~ s/\s//g;
    next unless ($net eq "NC");
    fix_date(\$on_m);
    fix_date(\$on_d);
    fix_date(\$off_m);
    fix_date(\$off_d);
    $on = `caldate -f %Y,%j,%H:%M:%S "$on_y/$on_m/$on_d,00:00:00"`;
    chomp $on;
    $off = `caldate -f %Y,%j,%H:%M:%S "$off_y/$off_m/$off_d,00:00:00"`;
    chomp $off;
    next if ($on == "" || $off == "");
    $lat = $lat_d + $lat_m / 60.0;
    $lon = -($lon_d + $lon_m / 60.0);

    printf "%-5s %2s %3s %2s %11.7f %s   %s    %9.5f %10.5f %6.1f %5.1f\n",
       $sta, $net, $chan, $loc, $rate,$on,$off,$lat,$lon,$elev,$depth;

}

close NCSN;
    
sub fix_date {
    my $dref = $_[0];

    if ($$dref == "  " || $$dref == "00") {
	$$dref = "01";
    }
    return;
}
