#!/usr/bin/perl 
# 
# Reads CMT Master file  (concatenated dek format) and spits out a list of
# longitude, latitude, depth, magnitude, for histogram comparisons.
# Now with the addition of the month and the year
#
# Last modified by fjsimons@alum.mit.edu, July 09, 2008

if ($#ARGV == -1) {
    @file = $ENV{"IFILES"}."/CMT/CMT-events";
}
else {
    @file = @ARGV[0];
}

open(fid1,"@file") || die "Can't find CMT file.\n";
open(fid2,">>cmtlist") || die "Can't open file locally.\n";

$count = 0;
while(<fid1>){
    if ($count <4) {
	$count += 1;
	if ($count ==1) {
	    @line = split;
		($month,$day,$year)=split("\/",@line[1]);
	}
	if ($count ==2) {
	    $lat = substr($_,43,7);
	    $lon = substr($_,55,8);
	    $dep = substr($_,68,6);
	    if($lon<0){$lon=$lon+360};
	}
	if ($count ==3) {
	    my $ex = substr($_,11,3);
	    $Mrr=10**$ex*substr($_,14,6);
	    $Mtt=10**$ex*substr($_,25,6);
	    $Mpp=10**$ex*substr($_,36,6);
	    $Mrt=10**$ex*substr($_,47,6);
	    $Mrp=10**$ex*substr($_,58,6);
	    $Mtp=10**$ex*substr($_,69,6);
	    # Use DT (5.91) and Shearer (9.41)	
            # If DUR is larger than 9.99 split doesn't work anymore; 
            # so need to work with substr instead.
	    # If you split the line you don't get the right result
	    $mag=2/3/log(10)*log(1/sqrt(2)*sqrt($Mrr**2+$Mtt**2+$Mpp**2+2*($Mrt**2)+2*($Mrp**2)+2*($Mtp**2)))-10.7;  
	}
    }
    if ($count ==4){
	printf(fid2 "%8.4f %9.4f %5.1f %3.2f %2.2i %2.2i %2.2i\n",
	       $lat,$lon,$dep,$mag,$year,$month,$day);

	$count=0}
}

close(fid1);
close(fid2);


