#!/usr/bin/perl
#
# Extracts CMT solutions from a Master file (concatenated dek format)
# and creates a file with the possible matches to that day.
#
# Usage: cmtday.pl 19960606
#
# New: Check file size of output file
# New: Also works for a list of files
# New: Also takes care of blanks instead of zeros in CMT file
#
# Last modified by fjsimons@alum.mit.edu, July 09, 2008

use File::stat;

# Loop over file list
while (<@ARGV>){
    if($_){
	printf("Working on %s\n",$_);
	
	my $year = substr($_,2,2);
	my $month = substr($_,4,2);
	my $day = substr($_,6,2);

# Check spaces as well as zeroes:
# Change character in a string
	$monnz = $month;
	$monnz =~ s/^0/ /;
 	$daynz = $day;
	$daynz =~ s/^0/ /;   

#	printf("%s/%s/%s\n",$month,$day,$year);	
#	printf("%s/%s/%s\n",$monnz,$daynz,$year);	
	
	@file = $ENV{"IFILES"}."/CMT/CMT-events";
	
	open(fid1,"@file") || die "Can't find CMT file.\n";
	
	my $newfile = "$_.cmt";
	
	open(fid2,">>$newfile") || die "Can't open file locally.\n";
	
	$count = 0;
	
	while(<fid1>){
	    if (/$month\/$day\/$year/  
		or /$monnz\/$day\/$year/ 
		or /$month\/$daynz\/$year/ 
		or /$monnz\/$daynz\/$year/ 
		or $count >0 and $count <4) {
		$count += 1;
		print fid2;
	    }
	    if ($count == 4){$count=0}
	}
	
	close(fid1);
	close(fid2);
	
	$fstat = stat($newfile);
	
	if ($fstat->size==0){
	    printf("%s\n","No match found. No files created.");
	    unlink($newfile);
	}
	else{
	    printf("Match found. Check new file:\n%s\n",$newfile);    
	}
    }
    else{
	printf("%s\n","Usage: cmtday.pl YEARMODY ... YEARMODY (file list)");
    }
}




