#!/usr/bin/perl -w

# oi_avhrr_level_0.pl serves the level 0 J. Bisagni's OI avhrr 
# data. 

$version = "May 13, 2002, V1.01";

# Modified May 13, 2002. V1.01.  Change next script to run to
#	be oi_avhrr_level_1.active.  rcg
# Original version, V1.00, May 10, 2002

# Robert C. Groman

# Assumptions:
#	1. Data are stored in a directory tree given in the 
# configuration file with the parameter of dir_root.  The file 
# is specified via the first passed parameter.
#	2. Script arguments are
#		ARGV[0] - configuration file
#		ARGV[1] - initial subdirectory to look into 
#					(e.g. globec_std)
#		ARGV[2] - image type (e.g.OI)
#		ARGV[3] - year (e.g. 1999)
#	3. Data have file names in the following form:
#		<image type><two digit year><3 digit year day>\
#			<1 digit year day fraction>.\
#			<file type>.<optional compressed, Z>
# These files are located in the year sub-directory specified in 
# the passed argument list
#	4. File types to process are specified in the 
# configuration file with the parameter of file_types, as for 
# example:
#			file_types=OI

$date = scalar localtime;

($configuration_file, $init_dir, $image_type, $year) = @ARGV;

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

print STDOUT ("#Program $0 Version: $version\n");
print STDOUT ("#   configuration file is $configuration_file\n");

@required = (
	"dir_root",
	"file_types",
	"script_root");

&read_configuration_file($configuration_file);

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

if (exists $config_param{'debug'} and defined $config_param{'debug'}) {
	$debug = $config_param{'debug'};
}
else {
	$debug = 'no';
}
#print STDOUT ("debug=$debug\n");

print STDOUT ("#Directory ", $init_dir, ".  Image type is ", 
	$image_type, 
	".  Year is ", $year, ".\n");
&make_log_entry ("Directory=$init_dir", "Image type=$image_type", 
	"Year=$year");

for ($i=0; $i<=$#required; $i++) {
	unless (exists $config_param{$required[$i]} ) { 
	   $okay="no"; 
	   &sendmessage ($error,
	   	"$required[$i] is missing from configuration ",
	   	"file=$configuration_file");
	   &make_log_entry (
		"$required[$i] is missing from configuration file",
	   	"file=$configuration_file");
	}
	else {
#		print STDOUT (
#			"#  $required[$i]=$config_param{$required[$i]}\n");
		&make_log_entry (
			"$required[$i]=$config_param{$required[$i]}");
	}
}
if ( $okay eq "no") { 
	&sendmessage ($error,
		"One or more parameters are missing from the configuration file",
		"Cannot continue.");
	&make_log_entry (
		"One or more parameters missing from configuration file=$configuration_file");
	exit;
}

&process_data;

undef $error;
undef $warning;
undef $version;

&make_log_entry ("<<<<<<<End of $0");

exit;

#------------------------------------------------------------------------
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 STDOUT ("#**debug, 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 :equal sign in line of config file=$filename",
			"Line is=$_");
		next;
	}
#	print STDOUT ("***debug, config input line=$_\n");
	($parameter, $value) = split /:=/;
	$config_param{$parameter} = $value;
#	print STDOUT ("#**debug, config_param{$parameter}=",
#		$config_param{$parameter}, "\n");
}
close CONFIG_FILE;
}

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

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 ( 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 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;
}

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

sub process_data {

# Process the level 0 for the avhrr data

my (@files, $data_dir, $error, $file_pattern, $file_type, @file_types, 
	$i, %month, $next_script, $numb_files);

$data_dir = $config_param{"dir_root"} . "/" . $init_dir . "/" . $year;

$next_script = $config_param{"script_root"} . "/" . 
	"oi_avhrr_level_1.active";

unless (chdir $data_dir) {
	&sendmessage ($error, "Could not change directory to $data_dir", 
		"Cannot continue");
	return "No good";
}
&make_log_entry ("Change directory=$data_dir");

@file_types = split ",", $config_param{"file_types"};
if ($#file_types < 0) {@file_types = ($config_param{"file_types"}) };

print STDOUT 
  ("#***debug, config_param{'file_types'}=$config_param{'file_types'}\n")
	if $debug eq 'yes';

foreach $file_type (@file_types) {
	$file_pattern = $image_type . '*' .  '\.' . $file_type . '*';
	&make_log_entry ("Collecting files with pattern=$file_pattern");
	push @files, glob ($file_pattern);
}
$numb_files = @files;
&make_log_entry ("Number of files to process=$numb_files");

# Now determine months available.

foreach $file (@files) {
	$month{&whatmonth($file)} = 'yes';
	print STDOUT ("#***debug, file=$file, month=$month\n") 
		if $debug eq 'yes';
}

print STDOUT ("month\tyear\t\>\n");
print STDOUT ("status[width=11]\tyrday_utc\ttime\n");

for ($i=1; $i <= 12; $i++) {
	if (defined $month{$i} and $month{$i} eq 'yes') {
		print STDOUT (
			"$i\t$year\t($next_script ",
			"$configuration_file $i $image_type ",
			"$year $data_dir)\n");
	}
}
return 1;
}

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

sub whatmonth {

# Given the file in $_[0], parse the name and see what month it 
# is in.  Return value of the month it is in.  OI filenames use
# yearday starting at 0, so 000.5 means January 1 at noon.

# Assume the year to be $year

my (@days, $yrday, $todal_days);

@days = (0, 31, 28, 31,30,31,30,31,31,30,31,30,31);

$yrday = $_[0];
print STDOUT ("#***debug, yrday=$yrday\n") if $debug eq 'yes';
$yrday =~ s/\w{2,3}\d\d(\d\d\d\d)\..*/$1/;
print STDOUT ("#***debug, after substitution, yrday=$yrday\n")
	if $debug eq 'yes';

$yrday = int($yrday/10) + 1;

if ($yrday eq $_[0]) {
	&make_log_entry("Could not parse for month in file=$_[0]");
	return 0;
}

# Determine leap year

if ( $year/4 == int ($year/4) and $year/100 != int ($year/100) ) 
	{ $days[2] = 29 }
if ( $year/4 == int ($year/4) and $year/100 == int ($year/100)  
	and $year/400 == int ($year/400) ) { $days[2] = 29 }

$total_days = 31;
$month = "nd";
for ($i=2; $i <=13; $i++) {
	$month = $i - 1;
	if ( $yrday >  $total_days) {
		$total_days = $total_days + $days[$i];
	}
	else {
		last;
	}
}

return $month;
}

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



