#!/usr/bin/perl -w
#
# sc3xml2nllinput.pl
# 2015 by Stefan Heimers, Swiss Seismological Service
#
# Create a line for the Grid2time input files for each station
# found in the xml inventory. Can be used on a single file
# given on the command line or will by default output 
# all stations in the inventory (directory hardcoded below)

use strict;
use warnings;
use XML::LibXML;
use DateTime::Format::Strptime;

# input directory, needs the trailing slash
my $inputdir=$ENV{"HOME"} . "/svn/stations/responses/xml/";


#if a single file is specified:
my $nr_args = $#ARGV + 1;
if ($nr_args  == 1){
    process_file($ARGV[0]);
}
else{
    opendir (DIRECTORY, $inputdir) or die $!;
    while (my $file = readdir(DIRECTORY)) {
	my $needwrite = 0;
	if ( $file =~ m/\.xml$/){
	    process_file($inputdir . $file);
	}
    }
    closedir(DIRECTORY);
}



sub process_file{
    my $p = XML::LibXML->new();
    my $doc = $p->parse_file($_[0]); # sc3 input file
    my $xc = XML::LibXML::XPathContext->new( $doc->documentElement()  );
    $xc->registerNs('ns', 'http://geofon.gfz-potsdam.de/ns/seiscomp3-schema/0.7');
    my @stations = $xc->findnodes("//ns:seiscomp/ns:Inventory/ns:network/ns:station");
    foreach my $station(@stations){
	my $code = $station->getAttribute("code");
	my $latitude  = "0";
	my $longitude = "0";
	my $elevation = "0";
	foreach my $node($station->getChildNodes) {
	    my $nodename = $node->getName();
	    if ( $nodename eq "latitude"){
		$latitude = $node->textContent;
	    }
	    if ( $nodename eq "longitude"){
		$longitude = $node->textContent;
	    }
	    if ( $nodename eq "elevation"){
		$elevation = $node->textContent;
	    }
	}
	$elevation = $elevation / 1000;
	print "GTSRCE $code  LATLON  $latitude   $longitude   0.0  $elevation\n";
    }
}
