#!/usr/local/bin/perl -w
#
# ctd_so_level2.pl

# Southern Ocean CTD data file processing routine - level 2

$version = "V1.01/December 23, 2002";

# December 23, 2002. V1.01. Check for "strange characters in field names and
#	replace with underscores.  rcg
# December 17, 2002. V1.00.  R.C. Groman
# Copywrite Woods Hole Oceanographic Institution

# Reads the data file specified as $ARGV[1] and outputs the lines
# with the first line field names changes so "/" is changed to
# "_per_" and "-" is replaced by "_".  On output, white spaces are
# replaced by a single tab.

# Passed parameter
#	$ARGV[0] = configuration file
#	$ARGV[1] = CTD data file, separated by commas
#			if more than 1

# Asuumptions
#	1. The first line of the data file contains the field names and
# the field names are processes so that "-" becomes "_" and "/" becomes
# "_per_".
#	2. The value -9.990e-29 is treated as the missing value and is
# replaced with nd.


$i_am_level=2;

$| = 1;
$error = "&x";
$warning = "#";


$date = scalar localtime;
$day_today = (localtime)[3];
if ($day_today < 10 ) {$day_today = "0" . $day_today}
$month_today = (localtime)[4];
$month_today++;
if ($month_today < 10 ) {$month_today = "0" . $month_today}
$year_today = (localtime)[5];
if ($year_today < 1000) {$year_today = $year_today + 1900;}
$hour_today = (localtime)[2];
if ($hour_today < 10 ) {$hour_today = "0" . $hour_today;}
$minute_today = (localtime)[1];
if ($minute_today < 10 ) {$minute_today = "0" . $minute_today;}
$time_today = $hour_today . $minute_today;
$time_stamp = $year_today . $month_today . $day_today . $time_today;

unless ( defined $ARGV[0] ) {
	print STDOUT ("$error Displayed by $0, $version\n",
		"$error Required configuration file not specified.\n");
	exit;
}

$configuration_file = $ARGV[0];

@required = (
);

&read_configuration_file($configuration_file);

$debug = 'no';
if (exists $config_param{'debug'} and defined $config_param{'debug'} ) {
	if ($config_param{'debug'} =~ m/^y/i or 
	   $config_param{'debug'} =~ m/^1/ or 
	   $config_param{'debug'} =~ m/^t/i) {;
		$debug = "yes";
	}
	elsif ($config_param{'debug'} =~ m/^keep/i ) {
		$debug = "keep";
	}
}

&make_log_entry (">>>>>>>Begin Program=$0",
	"Date of run=$date\tVersion=$version",
	"Configuration file=$configuration_file");


print STDOUT ("#Displayed by $0, $version\n");
unless (defined $ARGV[1] ) {
	&make_log_entry("Data file not passed along");
	&sendmessage($error, "Required data file name not passed along",
		"Cannot continue");
	exit;
}
$data_file = $ARGV[1];
print STDOUT ("#  Data file is $data_file\n");

$status = ' ';
foreach (@required) {
	unless (exists $config_param{$_} and defined $config_param{$_} ) {
		$status = $status . ' ' . $_;
	}
}

unless ($status eq ' ') {
	&make_log_entry(
		"Required configuration parameters not defined=$status");
	&sendmessage($error, "Required configuration parameters $status",
		"not defined.");
	exit;
}
   

unless (open DATA, "$data_file" ) {
	$status = $!;
	&make_log_entry("Could not open data file=$data_file",
		"Status=$status", "Data file=$data_file");
		&sendmessage($error,
			"Could not open data file $data_file",
			"Status was $status");
		exit;
	}
	
# Process first record, i.e. field names

$data = <DATA>;
@field_names = split /\s+/, $data;
for ($i=0; $i<=$#field_names; $i++) {
	$field_names[$i] =~ s$/$_per_$g;
	$field_names[$i] =~ s/-/_/g;
	$field_names[$i] =~ s/\W/_/g;
	$field_names[$i] =~ s/__/_/g;
	print STDOUT ("$field_names[$i]\t");
}
print STDOUT ("\n");

# Replace white spaces in data lines with tabs.

while ( <DATA> ) {
	$data = $_;
	chomp $data;
	$data =~ tr /\s/\t/s;
	$data =~ s/\015//g;
	$data =~ s/\t\t/\t/g;
	$data =~ s/-9.990e-29/nd/g;
	print STDOUT ($data, "\n");	
}
close DATA;

undef $error;
undef $warning;
undef $time_stamp;
undef $i_am_level;

&make_log_entry ("<<<<<<<End Program=$0");

exit 0;

#---------------------------------------------------------------------------

sub sendmessage {

#Send a message to the user.
#The message sent will be in the strings $_[0] and $_[1]

my ( @args, $mailfile, $message0, $message1, $prefix, $who);
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst);

$prefix=$_[0];
$message0=$_[1];
$message1=$_[2];
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time);
if ($year >= 100 and $year <= 1000) {$year = $year + 1900}
if ($year < 1900) { $year = $year + 2000; }
$mon++;
if ($mon < 10) { $mon = "0" . $mon; }
if ($mday < 10) {$mday = "0" . $mday; }
if ($hour < 10) { $hour = "0" . $hour; }
if ($min < 10) { $min = "0" . $min; }
if ($sec < 10) { $sec = "0" . $sec; }
undef $wday;
undef $isdst;
$mailfile="/tmp/sendmess" . $year . $yday . $hour . $min . $sec . ".tmp";
if ( -e $mailfile) { unlink $mailfile }

if ( open TEMPFILE, ">$mailfile") {
	print TEMPFILE ("Message from $0\n");
	if ( exists $ENV{'REMOTE_HOST'} ) {$who=$ENV{'REMOTE_HOST'} ; }
	elsif (exists $ENV{'REMOTE_ADDR'} ) {$who=$ENV{'REMOTE_ADDR'} ; }
	else {$who="not available"; }
	print TEMPFILE (" Date of message: $year/$mon/$mday $hour:$min\n");
	print TEMPFILE (" From: $who\n");
	print TEMPFILE (" $message0\n");
	print TEMPFILE (" $message1\n");
	close TEMPFILE;
	`/bin/mail -s "Probem with $0" dmo\@globec.whoi.edu <$mailfile`;
	unlink $mailfile;
}

print STDOUT ($prefix," $message0\n");
print STDOUT ($prefix," $message1\n");
print STDOUT ($prefix," Above message from $0\n");
print STDOUT ($prefix," Date of message: $year/$mon/$mday $hour:$min\n");

return 0;
}

#---------------------------------------------------------------------------

sub read_configuration_file {

# Open and read configuration file specified as first passed parameter 
# $_[0]. Return the contents of the file as the hash array %config_param.
# Lines beginning with "#" are treated as comments.  It is assumed
# that the indirect file contains lines as

#	parameter := value

# and this information is stored as 

#	$config_param{"parameter"} = value

my $filename = $_[0];
my ($parameter, $value);

#print STDERR ("#***debug, $0 indirect filename=$filename\n");

unless (defined $filename ) {
	&sendmessage ($error,
		"Could not open configuration file",
		"File name not specified.  Cannot continue.");
	exit;
}
unless (open CONFIG_FILE, $filename) {
	&sendmessage ($error,
		"Could not open configuration file=$filename",
		"Error code=$!.  Cannot continue.");
	exit;
}
while (<CONFIG_FILE>) {
	chomp;
#	s/\s//g;
	if (m/^#/) { next;}
	unless ( m/\S+/ ) {next;}
	unless ( m/:=/ ) {
		&sendmessage ($warning,
			"No ':=' in line of configuration file=$filename",
			"Line is=$_");
		next;
	}
#	print STDERR ("***debug, $0 config input line=$_\n");
	($parameter, $value) = split /:=/;
	$parameter =~ s/\s//g;
	unless ($parameter eq 'comment' ) {
		$value =~ s/\s//g;
	}
	else {
		$value =~ s/^\s//g;
	}
	$config_param{$parameter} = $value;
#	print STDERR ("#**debug, $0 config_param{$parameter}=",
#		$config_param{$parameter}, "\n");
}
close CONFIG_FILE;
}

#----------------------------------------------------------------------------

sub make_log_entry {

# Make a log entry with @_ if the log file $config_param{"logfile"} 
# exists.  Each entry in @_ are separated by tabs.

my ($login, @month, $temp);
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst);

($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time);
if ($year >= 100 and $year <= 1000) {$year = $year + 1900}
if ($year < 1900) { $year = $year + 2000; }
$mon++;
if ($mon < 10) { $mon = "0" . $mon; }
if ($mday < 10) {$mday = "0" . $mday; }
if ($hour < 10) { $hour = "0" . $hour; }
if ($min < 10) { $min = "0" . $min; }
if ($sec < 10) { $sec = "0" . $sec; }

if (exists $config_param{"logfile"} ) {
	$temp = ">>" . $config_param{'logfile'};
	unless ( open LOGFILE, $temp ) {
		&sendmessage ($warning, "Could not open logfile=$temp",
			"Error code=$!");
	}
	else {
		$login = getlogin || (getpwuid($<))[0] || "Intruder!!";
		$login="\tusername=" . $login;
		print LOGFILE ($year, "/" . $mon . "/" . $mday . ":" . $hour . $min . "." . 
			$sec, $login);
		foreach (@_) {
			print LOGFILE ("\t", $_);
		}
		print LOGFILE ("\n");
		close LOGFILE;
	}
}
return;
}

