#!/usr/bin/perl

# Converts dbselect detailed output to text format
# Input from STDIN, output to STDOUT

use strict;

my $flag = 0;
my $catalog = undef;
my $contributor = undef;
my $dtime = undef;

while (<STDIN>) {
next if (!/^\d/);

my $line = $_;

if ($flag == 0) {
	print "#EventID | Time | Latitude | Longitude | Depth/km | Author | Catalog | Contributor | ContributorID | MagType | Magnitude | MagAuthor | EventLocationName\n";
	$flag = 1;
}

if (trim(substr($line,55,4)) eq "NC") {
	$catalog = "NCSS";
	$contributor = "NC";
} else {
	$catalog = "EGS";
	$contributor = trim(substr($line,60,7));
}

if (trim(substr($line,60,7)) eq "DDRT") {
	$catalog = "DD";
	$contributor = "NC";
}

$dtime = trim(substr($line,0,24));
$dtime =~ s/\ /T/g;
$dtime =~ s/\//-/g;

print trim(substr($line,132,8))."|";     # Event Id
print $dtime."|";                        # Time
print trim(substr($line,27,9))."|";      # Latitude
print trim(substr($line,36,10))."|";     # Longitude
print trim(substr($line,47,6))."|";      # Depth
print trim(substr($line,55,4))."|";      # Author
print $catalog."|";                      # Catalog
print $contributor."|";                  # Contributor
print "|";                               # Contributor Id
print "M".trim(substr($line,124,2))."|"; # Mag Type
print trim(substr($line,118,4))."|";     # Magnitude
print trim(substr($line,55,4))."|";      # Mag Author
print trim(substr($line,158,90))."\n";   # Event Location
}

sub trim 
{
    my @out = @_;
    for (@out) 
    {
        s/^\s+//;
        s/\s+$//;
    }
    return wantarray ? @out : $out[0];
}

