#!/usr/bin/perl

# BIG BROTHER SERVICE AVAILABILITY REPORT SCRIPT
#      
# Nick Metrowsky
# nmetro@colorado.edu
# University of Colorado (JILA)
# 15 june, 2001
#
# Version: 1.7
#
#------------------------------------------------------------------------------------   
#
# Inspired by the bb-rep.sh script written by:
#
# Robert-Andre Croteau
# Version 1.5a
# Aug 16th, 2000
#
######################################################################################
#   
# This program is not part of the original Big Brother Distribution, but is
# considered a plug-in replacement for the distributed bb-rep.sh. As author,
# I give permission for anyone to use this program to enhance their use of
# Big Brother. This program can be modified or improved, as desired. If someone
# feels that a universal change is needed (to fix a bug or add a feature), please
# post those changes to the Big Brother mailing list (bb@bb4.com). 
#
# As with the rest of Big Brother, this code cannot be sold or used for commercial gain.
#
# Copyright 1999, 2000
# The University of Colorado
# All Rights Reserved
#
######################################################################################
#
# Change History:
#
# 1.7	15 June, 2001		Changed history file records to display duration in
#				DDd-HH:MM:SS format instead of seconds.
#				Fixed a minor bug with prime time report generation.
#
# 1.6   2 November, 2000	Fixed a syntax error on line 242, replaced "Now" with
#				"Nov".
#
# 1.5	14 September, 2000	Fixed font on host name/service display.
#				Added support for BB V1.5a and later.
#
# 1.4	25 August, 2000		Split Host and Services in selection criteria.
#
# 1.3   17 July, 2000  		Deactivated automatic refresh and fixed Browser Title.
#
# 1.2	23 June, 2000		Added capability to select events based upon the Big
#				Brother event color status. There are two selections:
#					1. Select All Events
#					2. Select only green, yellow, red and clear
#					   events. Blue and purple events are ignored
#					   in all calculations.
#				This idea came from Nicolas Chuche <nchuche@teaser.fr>.
#				Repackaged bb-hist.pl and bb-rep.pl into two separate kits.
#			
#
# 1.1   12 June, 2000   	Added Host Select and Service Select capabilities. One
#				can now select a specific service across all hosts or
#				select a specific host. This change was courtesy of
#				Jim Greene <jjg@interactive8.com>.
#				Added capability to select reporting for prime time
#				period or 24 hour time period. This idea came from
#				Nicolas Chuche <nchuche@teaser.fr> and from John Horne
#				<J.Horne@plymouth.ac.uk>, whose contribution helped
#				in developing the logic.
#
# 1.0	10 May, 2000		First Release
#
######################################################################################
 
# Flags for Big Brother Versions
#
$BB_V15A="TRUE";			# Set to "TRUE" if you are running BB V1.5a or Later.
					# Set to "FALSE", if you are ruuning BB V1.5 or earlier.

$BB_TYPE="NEW";				# Set to "NEW" for BB V1.3 or later. Set
					#  to "OLD" for BB prior to BB V1.3.
#   
# ************* NOTICE!!! ************
# BBWEB MUST BE SET CORRECTLY FOR THIS TO WORK
#   
if ($BB_V15A eq "TRUE") {
	$BBWEB="/bb";			# Location of Big Brother Web Server
	$BBWEBCGI="/cgi-bin";		# Location of Big Brother Web Server cgi-scripts
} else {
	$BBWEB="http://mrtg.calmco.com/bb";	# Location of Big Brother Web Server
	$BBWEBCGI="http://mrtg.calmco.com/cgi-bin"; # Location of Big Brother Web Server cgi-scripts
}

# BBHOME IS THE ROOT DIRECTORY OF BIG BROTHER!!!
# YOU MUST SET THE NEXT LINE TO WHERE BB LIVES

$BBHOME="/home/bb/bb";		# Location of Big Brother Directory
$BBINC="$BBHOME/etc/bbinc.sh";		# Location of Big Brother Include File
$BBDEF="$BBHOME/etc/bbdef.sh";		# Location of Big Brother Definitions File
$BBHIST="/home/bb/bbvar/hist/avail";		# Location of Big Brother History Files
$BBHEADER="$BBHOME/web";		# Location of Big Brother Header/Footer Files

# Set Fonts and Colors

$TEXT_COLOR="silver";			# Color for Big Brother Text
$TEXT_FONT="Tahoma, Arial, Helvetica";	# Font for Big Brother Text
$HEADER_COLOR="cyan";			# Color for Big Brother Header/Notes
$HEADER_FONT="Tahoma, Arial, Helvetica"; # Font for Big Brother Header/Notes
$DATA_BKG_COLOR="#333333";		# Background Color for Data Text
$DATA_FONT="Tahoma, Arial, Helvetica";	# Font for Data Text
$TITLE_BKG_COLOR="#000033";		# Background Color for Title Header Text
$TITLE_FONT="Tahoma, Arial, Helvetica";	# Font for Title Header Text

# Set Flags

$BLUE_FLAG="FALSE";			# Set to "TRUE", if you want an incomplete
					#  time period to put data in the blue
					#  column. Set to "FALSE", if you do not
					#  want this behavior.

$PRIME_HOURS="07 22";			# Hours during prime time
					# Default: 08:00:00 through 16:59:59

$PRIME_DAYS="Mon Tue Wed Thu Fri Sat";	# Days during prime time
					# Default: Monday through Friday

# No User changes are required beyond this point

######################################################################################

# Exit out if $BBHOME is not defined

if ($BBHOME eq "") {
        print "Content-type: text/html\n\n";
	print "<HTML><BODY>";
	print "<H1>ERROR!<BR>BBHOME IS NOT SET IN bb-rep.pl</H1></BODY></HTML>";
        exit 1
}

######################################################################################

# Exit out if $BBWEB is not defined

if ($BBWEB eq "") {
        print "Content-type: text/html\n\n";
	print "<HTML><BODY>";
	print "<H1>ERROR!<BR>BBWEB IS NOT SET IN bb-rep.pl</H1></BODY></HTML>";
        exit 1
}

######################################################################################

# Get Big Brother Release Version and Date from $BBHOME/etc/bbinc.sh

	open BBINC, "grep \"^BBREL=\" $BBINC |";		# Get Big Brother Release Version
	while (<BBINC>) { $vers_in=$_; }
	close BBINC;

	open BBINC, "grep \"^BBRELDATE=\" $BBINC |";	# Get Big Brother Release Date
	while (<BBINC>) { $reldate_in=$_; }
	close BBINC;

	open BBINC, "grep \"^BBSKIN=\" $BBINC |";	# Get Big Brother Skin Directory
	while (<BBINC>) { $skin_in=$_; }
	close BBINC;

	open BBDEF, "grep \"^FQDN=\" $BBDEF |";		# Get Big Brother Skin Directory
	while (<BBDEF>) { $fqdn_in=$_; }
	close BBDEF;

	(undef,$vers,undef) = split(/\"/,$vers_in);	  # Extract Version
	(undef,$reldate,undef) = split(/\"/,$reldate_in); # Extract Release Date
	(undef,$skin,undef) = split(/\"/,$skin_in);	# Extract Skin Directory
	(undef,$fqdn,undef) = split(/\"/,$fqdn_in);	# Extract FQDN Definition

$BBREL=$vers;			# Current Big Brother Version
$BBRELDATE=$reldate;		# Current Big Brother Release Date
if ($BB_V15A eq "TRUE") {
	$skin=~s/\${/&/g;       # Remove "${"
	$skin=~s/}//g;          # Also remove "}"
	$skin=~s/&BBWEB/$BBWEB/g; # Replace "&BBWEB" wuth "$BBWEB"
	$BBSKIN="$skin";        # Current Big Brother Skin Directory
} else {
	$BBSKIN="$BBWEB/$skin"; # Current Big Brother Skin Directory
}

######################################################################################

# Start of bb-rep cgi script

use CGI;						# Call perl CGI library
use POSIX;						# Call perl POSIX Library
use Time::Local;					# Date/Time Conversion
$now = time();						# Current time in seconds

($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($now);
$alpha_now = strftime("%a %b %d %H:%M:%S %Y",$sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst);
(undef,$this_month,$this_day,undef,$this_year)=split(" ",$alpha_now);

{
	$query = new CGI;				# Initialize CGI
	$req=$query->request_method();			# Determine POST or GET
        $this_script = $query->script_name();		# Get name of script
	&display_headers();				# Display BB Headers

	$month_test=$query->param('start_month');
	$histfile_test=$query->param('histfile');

        if (($month_test ne "") && ($histfile_test eq "")) {
		$start_month = $query->param('start_month');	# Start month of time period
		$start_day = $query->param('start_day');	# Start day of time period
		$start_year = $query->param('start_year');	# Start year of time period
		$end_month = $query->param('end_month');	# End month of time period
		$end_day = $query->param('end_day');		# End day of time period
		$end_year = $query->param('end_year');		# End year of time period
		$display_states = $query->param('display_states'); # All BB States or only green, yellow, red & clear states
		$prime_flag = $query->param('prime_flag');	# Prime Time Flag
		if ($prime_flag eq "Prime_Time") {
			$prime_start_hour = $query->param('prime_start_hour');
			$prime_end_hour = $query->param('prime_end_hour');
			if ($prime_start_hour > $prime_end_hour) {
				$PRIME_HOURS="$PRIME_HOURS";
			} else {
				$PRIME_HOURS=$prime_start_hour." ".$prime_end_hour;
			}
			@prime_days = $query->param('prime_days');
		        $num_prime_days=scalar(@prime_days);
		        $prime_days_counter=0;
			while ($prime_days_counter < $num_prime_days) {
				if ($prime_days_counter == 0) {
					$PRIME_DAYS=$prime_days[$prime_days_counter];
					$hold_prime_days=$prime_days[$prime_days_counter];
				} else {
					$PRIME_DAYS=$PRIME_DAYS." ".$prime_days[$prime_days_counter];
					$hold_prime_days=$hold_prime_days."+".$prime_days[$prime_days_counter];
	                	}
				$prime_days_counter++;
			}			

			($prime_start_hour,$prime_end_hour)=split(/ /,$PRIME_HOURS);
			$prime_secs = ($prime_end_hour * 3600) - ($prime_start_hour * 3600);
			$non_prime_secs = 86400 - $prime_secs;
			$prime_start_secs = $prime_start_hour * 3600;
			$prime_end_secs = $prime_end_hour * 3600;
		}

                @month{qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec)} = (00..11);
                $start_mon = $month{$start_month};
                $end_mon = $month{$end_month};

		$start_time=timelocal(0, 0, 0, $start_day, $start_mon, $start_year);
		$end_time=timelocal(59, 59, 23, $end_day, $end_mon, $end_year);

		if ($end_time > $now) {			# If today, go to cuurent time of day
			$end_time=timelocal($sec, $min, $hour, $end_day, $end_mon, $end_year);
		}

		&check_date();					# Check the date entered
		if ($bad_date eq "") {

# The following formats the time in Day of Week Month Day Hour:Minute:Second Year ASCII Format

			($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($start_time);
			$alpha_start = strftime("%b %e %Y",$sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst);

			($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($end_time);
			$alpha_end = strftime("%b %e %Y",$sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst);

			if ($display_states eq "All_States") {
				$bb_events = "States: green yellow red purple clear blue"; 
			} else {
				$bb_events = "States: green yellow red clear"; 
			}
			if ($prime_flag eq "Prime_Time") {
				print "<FONT SIZE=+1 COLOR=\"$TEXT_COLOR\" FACE=\"$TEXT_FONT\"><CENTER>Olympus Servicing L.P.<BR>Real-time Service Availability Report<BR>$alpha_start - $alpha_end<BR>Prime Time Hours: $prime_start_hour - $prime_end_hour<BR>Prime Time Days: $PRIME_DAYS<BR>$bb_events</CENTER><CENTER>";
			} else {
				print "<FONT SIZE=+1 COLOR=\"$TEXT_COLOR\" FACE=\"$TEXT_FONT\"><CENTER>Olympus Servicing L.P.<BR>Real-time Service Availability Report<BR>$alpha_start - $alpha_end<BR>24 Hours<BR>7 Days<BR>$bb_events</CENTER><CENTER>";
			}
			print "<BR></FONT>";
			print "<TABLE BORDER=0 BGCOLOR=\"#000000\" CELLSPACING=2><TR BGCOLOR=\"$TITLE_BKG_COLOR\">";	
			print "<TD><CENTER><FONT SIZE=-1 FACE=\"$HEADER_FONT\" COLOR=\"$HEADER_COLOR\">Service</CENTER></TD>";
			print "<TD><CENTER><FONT SIZE=-1 FACE=\"$HEADER_FONT\" COLOR=\"$HEADER_COLOR\">OK</CENTER></TD>";
			print "<TD><CENTER><FONT SIZE=-1 FACE=\"$HEADER_FONT\" COLOR=\"$HEADER_COLOR\">Attention</CENTER></TD>";
			print "<TD><CENTER><FONT SIZE=-1 FACE=\"$HEADER_FONT\" COLOR=\"$HEADER_COLOR\">Trouble</CENTER></TD>";
			if ($display_states eq "All_States") {
				print "<TD><CENTER><FONT SIZE=-1 FACE=\"$HEADER_FONT\" COLOR=\"$HEADER_COLOR\">No Report</CENTER></TD>";
			}
			print "<TD><CENTER><FONT SIZE=-1 FACE=\"$HEADER_FONT\" COLOR=\"$HEADER_COLOR\">Unavailable</CENTER></TD>";
			if ($display_states eq "All_States") {
				print "<TD><CENTER><FONT SIZE=-1 FACE=\"$HEADER_FONT\" COLOR=\"$HEADER_COLOR\">Offline</CENTER></TD>";
			}
			print "</TR>";

# This is the core of the script, it runs all the following as subroutines

			opendir HISTDIR,"$BBHIST";				# Get Big Brother History Directory
			@histfiles_unsrt = readdir HISTDIR;			# Get Contents into an array

# Begin V1.1 Update - 30 May, 2000 - Jim Greene <jjg@interactive8.com> - Contributed Code
# Revised: V1.4 - 25 August, 2000 - Split Hosts and Services on Selection Criteria

			$regexed=$query->param('regex');			# Get value of selection
			$regexeds=$query->param('regexs');			# Get value of selection
			if (($regexed) && !($regexeds)) {
				@histfiles_mix = grep /$regexed/, @histfiles_unsrt; # Search through all hosts
				@histfiles_unsrt = @histfiles_mix;		#  and save what was requested.
			}
			if (($regexeds) && !($regexed)) {
				@histfiles_mix = grep /$regexeds/, @histfiles_unsrt; # Search through all services
				@histfiles_unsrt = @histfiles_mix;		#  and save what was requested.
			}
			if (($regexeds) && ($regexed)) {
				@histfiles_mix = grep /$regexed/, @histfiles_unsrt; # Search through all hosts
				@histfiles_mixx = grep /$regexeds/, @histfiles_mix; # Search through all hosts
				@histfiles_unsrt = @histfiles_mixx;		#  and save what was requested.
			}

# End V1.1/V1.4 Update
			closedir HISTDIR;					# Close Directory
			@histfiles = sort @histfiles_unsrt;			# Sort in alphabetical order
			$hist_file_counter = scalar(@histfiles);		# Get Number of files in directory
			$count_hist_recs=0;					# Initialize Counter
			while ($count_hist_recs < $hist_file_counter) {		# Loop through all entries
				$hist_detail="FALSE";				# Turn off History Detail Flag
				$hist_name_rec_in = $histfiles[$count_hist_recs]; # Get history file name
				$count_hist_recs++;				#  until we get through them all.
				$hist_name_rec = "$BBHIST/$hist_name_rec_in";	# Format for use later
				&init_vars();					# Initialize data hold areas
				($path,$raw_histfile) = split("$BBHIST/",$hist_name_rec); # Obtain History file Name from History Directory File
				&fix_hist_file();				# Extract vital info for history file name
				if ($prime_flag eq "All_Times") {
					&process_hist();			# Process all history records
				} else {
					&process_prime_hist();			# Process only prime time history records
				}
				if ($standard_histrec eq "TRUE") {		# Skip Event Log History Files
					&calc_perc();				# Calaculate percentage information
					&display_record();			# Display results for service
				}
			}

			print "<TR BGCOLOR=\"#000000\">";
			print "<TD COLSPAN=7 ALIGN=CENTER><FONT FACE=\"$HEADER_FONT\" COLOR=\"$HEADER_COLOR\" SIZE=-1><B>[Percentages may not total 100%]</B></TD></TR></TABLE>";
		} else {
			print "<CENTER>Incorrect Date Entered: $start_month $start_day $start_year - $end_month $end_day $end_year</center>";
		}
		&display_footers();						# Display BB footers
	}

	if (($month_test eq "") && ($histfile_test ne "")) {
		&init_vars();				# Initialize data hold areas
		$start_time = $query->param('start_time'); # Start time of period
		$end_time = $query->param('end_time');	# End Time of period
		$total_secs = $query->param('total_secs'); # Total Seconds in period
		$display_states = $query->param('display_states'); # All BB States or only green, yellow, red & clear states
		$noncrit_secs = $query->param('noncrit_secs'); # Total Seconds for purple and blue states
		$prime_flag = $query->param('prime_flag'); # Prime Time Flag
		if ($prime_flag eq "Prime_Time") {
			$prime_start_hour = $query->param('prime_start_hour');
			$prime_end_hour = $query->param('prime_end_hour');
			if ($prime_start_hour > $prime_end_hour) {
				$PRIME_HOURS="$PRIME_HOURS";
			} else {
				$PRIME_HOURS=$prime_start_hour." ".$prime_end_hour;
			}
			$hold_prime_days = $query->param('prime_days');
			@prime_days=split(/\+/,$hold_prime_days);
			$num_prime_days=scalar(@prime_days);
		        $prime_days_counter=0;
			while ($prime_days_counter < $num_prime_days) {
				if ($prime_days_counter == 0) {
					$PRIME_DAYS=$prime_days[$prime_days_counter];
				} else {
					$PRIME_DAYS=$PRIME_DAYS." ".$prime_days[$prime_days_counter];
	                	}
				$prime_days_counter++;
			}			

			($prime_start_hour,$prime_end_hour)=split(/ /,$PRIME_HOURS);
			$prime_secs = ($prime_end_hour * 3600) - ($prime_start_hour * 3600);
			$non_prime_secs = 86400 - $prime_secs;
			$prime_start_secs = $prime_start_hour * 3600;
			$prime_end_secs = $prime_end_hour * 3600;
	        }

		$raw_histfile=$histfile_test;			# Name of History File

		($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($start_time);
		$alpha_start = strftime("%b %e %Y",$sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst);
		($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($end_time);
		$alpha_end = strftime("%b %e %Y",$sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst);

		&fix_hist_file();			# Extract vital info for history file name
		if ($display_states eq "All_States") {
			$bb_events = "States: green yellow red purple clear blue"; 
		} else {
			$bb_events = "States: green yellow red clear"; 
		}
		if ($prime_flag eq "Prime_Time") {
			print "<FONT SIZE=+1 COLOR=\"$TEXT_COLOR\" FACE=\"$TEXT_FONT\"><CENTER>$raw_histfile<BR>$alpha_start - $alpha_end<BR>Prime Time Hours: $prime_start_hour - $prime_end_hour<BR>Prime Time Days: $PRIME_DAYS<BR>$bb_events</CENTER><CENTER>";
		} else {
			print "<FONT SIZE=+1 COLOR=\"$TEXT_COLOR\" FACE=\"$TEXT_FONT\"><CENTER>$raw_histfile<BR>$alpha_start - $alpha_end<BR>24 Hours<BR>7 Days<BR>$bb_events</CENTER><CENTER>";
		}
		print "<BR></FONT>";
		print "<CENTER>";
		print "<TABLE BORDER=0 BGCOLOR=\"#000033\" CELLSPACING=3>";
		print "<TR BGCOLOR=\"$TITLE_BKG_COLOR\"><TD ALIGN=CENTER COLSPAN=5><FONT FACE=\"$TEXT_FONT\" COLOR=\"$TEXT_COLOR\"<B>History Log Entries</B></TD></TR>";
		print "<TR BGCOLOR=\"$TITLE_BKG_COLOR\">";
		print "<TD ALIGN=CENTER><FONT FACE=\"$HEADER_FONT\" COLOR=\"$HEADER_COLOR\" SIZE=-1><B>Event Start<B></TD>";
		print "<TD ALIGN=CENTER><FONT FACE=\"$HEADER_FONT\" COLOR=\"$HEADER_COLOR\" SIZE=-1><B>Event End<B></TD>";
		print "<TD ALIGN=CENTER><FONT FACE=\"$HEADER_FONT\" COLOR=\"$HEADER_COLOR\" SIZE=-1><B>Status<B></TD>";
		print "<TD ALIGN=CENTER><FONT FACE=\"$HEADER_FONT\" COLOR=\"$HEADER_COLOR\" SIZE=-1><B>Duration<B></TD>";
		print "<TD ALIGN=CENTER><FONT FACE=\"$HEADER_FONT\" COLOR=\"$HEADER_COLOR\" SIZE=-1><B>Percentage<B></TD></TR>";
		$hist_detail="TRUE";			# Turn on History Detail Flag
		if ($prime_flag eq "All_Times") {
			&process_hist();		# Process all history records
		} else {
			&process_prime_hist();		# Process only prime time history records
		}
		print "</TABLE><BR></CENTER>";		# Complete History Log Summary
		&calc_perc();				# Calaculate percentage information
		&data_summary();			# Display Availability Summary
		&display_footers();			# Dipslay BB Footer
        }

	if (($month_test eq "") && ($histfile_test eq "")) {
		&get_date_info($query);			# Get Date Range Parameters
		&display_footers();
        }
}

######################################################################################

sub init_vars {

# The following initializes variables for holding totals for each color within each time period

	$only_rec="FALSE";	# Flag for single record in history file
	$multirec="FALSE";	# Flag for multiple records in history file

	$green_sec=0;		# green status variable
	$yellow_sec=0;		# yellow status variable
	$red_sec=0;		# red status variable
	$purple_sec=0;		# purple status variable
	$clear_sec=0;		# clear status variable
	$blue_sec=0;		# blue status variable

	$period_secs=0;		# Clear time period seconds
}

######################################################################################

# Edit the history file name and extract some of its' important parts

sub fix_hist_file {
	$raw_histfile =~ y/a-zA-Z0-9,._\-//cd;		# Limit the characters that can be in there

	$HISTFILE = $raw_histfile;			# Get the history file name passed
        $HISTFILE =~ /\\([^\s\\]+)$/;			# Make sure there is no bad things in there
        ($HOSTNAME,$SERVICE) = split(/\./,$HISTFILE);	# Get the hostname and service name

	$HOSTDOTS=$HOSTNAME;				# Read the hostname
	$HOSTDOTS=~s/,/./g;				# Convert "," to "."
	$HOSTUDL=$HOSTNAME;				# Read the hostname
	$HOSTUDL=~s/,/_/g;				# Convert "." to "_"
}

######################################################################################

# Process the history file to compute percentages required for summaries. 

sub process_hist {
	$total_secs = $end_time - $start_time;		# Number of seconds in period

	open HISTFILE, " $BBHIST/$HISTFILE";
	while (<HISTFILE>) {
		$standard_histrec="";					# Standard History Record Flag
		($check,undef,undef,undef,undef,undef,undef,undef)=split(" ",$_);
		if (($check eq "Sun") || ($check eq "Mon") || ($check eq "Tue") ||
			($check eq "Wed") || ($check eq "Thu") || ($check eq "Fri") ||
			($check eq "Sat")) {
				$standard_histrec="TRUE";		# Standard History Record File
				$hist_rec=substr($_,25,60);		# State, timestamp and seconds - status data
				$save_hist_rec=$_;			# Keep a copy of history record for detail
				($color,$timestamp,$seconds)=split(/\s+/,$hist_rec);	# Formatted History Record

				if (($only_rec eq "FALSE") && ($multirec eq "FALSE") && ($seconds eq "")) {
					$only_rec = "TRUE";
					$datacycle = $end_time - $timestamp;
					if ($datacycle > $total_secs) {
						$period_secs = $total_secs;
					} else {
						$period_secs = $datacycle;
						$blue_sec = $blue_sec + ($total_secs - $period_secs);
					}
					if ($period_secs >= 0) {
						if ($hist_detail eq "TRUE") {
							if ($display_states eq "All_States") {
								&hist_all(); 
							}
							if ((($color eq "green") || ($color eq "yellow") || ($color eq "red") ||
								($color eq "clear")) && ($display_states eq "Critical_States")) {
									&hist_all(); 
							}
						}
						if ($color eq "green") { $green_sec = $green_sec + $period_secs };
						if ($color eq "yellow") { $yellow_sec = $yellow_sec + $period_secs };
						if ($color eq "red") { $red_sec = $red_sec + $period_secs };
						if ($color eq "purple") { $purple_sec = $purple_sec + $period_secs };
						if ($color eq "clear") { $clear_sec = $clear_sec + $period_secs };
						if ($color eq "blue") { $blue_sec = $blue_sec + $period_secs };
					}
				}

				if ($only_rec eq "FALSE") {
					$multirec = "TRUE";
					if ($timestamp >= $start_time) {
						if ($seconds ne "") {
							$check_end = ($timestamp + $seconds) - $end_time;
							if ($check_end > 0) {
								$period_secs = $seconds - $check_end;
							} else {
								$period_secs = $seconds;
							}
						} else {
							$period_secs = $end_time - $timestamp;
						}
					} else {
						if ($seconds ne "") {
							$end_cycle = $end_time - $timestamp;
							$this_cycle = $end_time - $start_time;
							$datacycle = $this_cycle - $end_cycle;
							$period_secs = $datacycle + $seconds;
							if ($period_secs > $total_secs) {
								$period_secs = $total_secs;
							}
						}				
						if ($seconds eq "") {
							$datacycle = $end_time - $timestamp;
							if ($datacycle > $total_secs) {
								$period_secs = $total_secs;
							} else {
								$period_secs = $datacycle;
							}
						}
					}
					if ($period_secs >= 0) {
						if ($hist_detail eq "TRUE") {
							if ($display_states eq "All_States") {
								&hist_all(); 
							}
							if ((($color eq "green") || ($color eq "yellow") || ($color eq "red") ||
								($color eq "clear")) && ($display_states eq "Critical_States")) {
									&hist_all(); 
							}
						}
						if ($color eq "green") { $green_sec = $green_sec + $period_secs };
						if ($color eq "yellow") { $yellow_sec = $yellow_sec + $period_secs };
						if ($color eq "red") { $red_sec = $red_sec + $period_secs };
						if ($color eq "purple") { $purple_sec = $purple_sec + $period_secs };
						if ($color eq "clear") { $clear_sec = $clear_sec + $period_secs };
						if ($color eq "blue") { $blue_sec = $blue_sec + $period_secs };
					}
				}
			}
		}

	close HISTFILE;
}

######################################################################################

# Process the history file to compute percentages required for summaries for prime time
#  records only. 

sub process_prime_hist {

	$rec_count=0;
	$total_secs=0;

	($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($end_time);
	$end_time=timelocal(00, 00, $prime_end_hour, $mday, $mon, $year);

	if ($end_time > $now) {			# If today, go to cuurent time of day
		$end_time=timelocal($sec, $min, $hour, $mday, $mon, $year);
	}

	open HISTFILE, " $BBHIST/$HISTFILE";
	while (<HISTFILE>) {
		$standard_histrec="";					# Standard History Record Flag
		($check,undef,undef,undef,undef,undef,undef,undef)=split(" ",$_);
		if (($check eq "Sun") || ($check eq "Mon") || ($check eq "Tue") ||
			($check eq "Wed") || ($check eq "Thu") || ($check eq "Fri") ||
			($check eq "Sat")) {
				$standard_histrec="TRUE";		# Standard History Record File
				$hist_rec=substr($_,25,60);		# State, timestamp and seconds - status data
				$save_hist_rec=$_;			# Keep a copy of history record for detail
				($color,$timestamp,$seconds)=split(/\s+/,$hist_rec);	# Formatted History Record
					
				if ($seconds eq "") { $seconds = $end_time - $timestamp; }

				$end_timestamp = $timestamp + $seconds;

				$first_rec="TRUE";
				$skip_once="FALSE";
				$process_rec="FALSE";

				if (($end_timestamp >= $start_time) && ($end_timestamp <= $end_time)) {
					$process_rec="TRUE";
					$check_secs = $end_timestamp - $start_time;
					if ($check_secs < $seconds) {
						$timestamp = $start_time;
						$seconds = $check_secs;
					}
				}
				if ($end_timestamp > $end_time) {
					$diff_secs = $end_timestamp - $end_time;
					$check_secs = $seconds - $diff_secs;
					if ($check_secs > 0) {
						$seconds = $seconds - $diff_secs;
						$end_timestamp = $end_time;
						$process_rec="TRUE";
					}
				}

				while (($timestamp < $end_timestamp) && ($process_rec eq "TRUE")) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($timestamp);
					$alpha_ts = strftime("%a %b %d %H:%M:%S %Y",$sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst);
					if (($hour >= $prime_start_hour) && ($hour < $prime_end_hour)) {
						$prime_code = "P";
					} else {
					 	$prime_code = "N";
					}

					if ($first_rec eq "TRUE") {
						$first_rec = "FALSE";
						$skip_once = "TRUE";
						$time_now = $sec + ($min * 60) + ($hour * 3600);
						if ($prime_code eq "P") {
							$check_timestamp = $timestamp + $prime_secs;
							$to_end_prime_secs = $prime_end_secs - $time_now;
							if ($check_timestamp > $end_timestamp) {
								$secs = ($end_timestamp - $check_timestamp) + $prime_secs;
								$secs_diff = 0;
								if ($secs > $to_end_prime_secs) {
									$secs_diff = $secs - $to_end_prime_secs;
									$xtimestamp = $end_timestamp - $secs_diff;
									$secs = $to_end_prime_secs;
									($xsec,$xmin,$xhour,$xmday,$xmon,$xyear,$xwday,$xyday,$xisdst) = localtime($xtimestamp);
									$xalpha_ts = timelocal($xsec,$xmin,$xhour,$cmday,$cmon,$cyear);
								}
							} else {
								$secs = $prime_end_secs - $time_now;
							}
							$asc_wkday=substr($alpha_ts,0,3);
							$check_wkday=grep /$asc_wkday/,$PRIME_DAYS;
							if ($check_wkday == 0) {
								$new_rec=$alpha_ts." ".$timestamp." ".$secs." ".$color." N";
							} else {
								$new_rec=$alpha_ts." ".$timestamp." ".$secs." ".$color." ".$prime_code;
							}
							if (($prime_code eq "P") && ($timestamp > $start_time) && ($check_wkday > 0)) {
								$total_secs = $total_secs + $secs;
								$rec_array[$rec_count]=$new_rec;
								$rec_count++;
							}
							$timestamp = $timestamp + $secs;
							$secs = 0;
						}
						if ($prime_code eq "N") {
							$check_timestamp = $timestamp + $non_prime_secs;
							$to_start_prime_secs = $time_now - $prime_start_secs;
							if ($check_timestamp > $end_timestamp) {
								$secs = ($end_timestamp - $check_timestamp) + $non_prime_secs;
								$secs_diff = 0;
								if ($secs > $to_start_prime_secs) {
									$secs_diff = $secs - $to_start_prime_secs;
									$xtimestamp = $start_timestamp - $secs_diff;
									$secs = $to_start_prime_secs;
									($xsec,$xmin,$xhour,$xmday,$xmon,$xyear,$xwday,$xyday,$xisdst) = localtime($xtimestamp);
									$xalpha_ts = timelocal($xsec,$xmin,$xhour,$cmday,$cmon,$cyear);
								}
							} else {
								($csec,$cmin,$chour,$cmday,$cmon,$cyear,$cwday,$cyday,$cisdst) = localtime($check_timestamp);
								$new_check_timestamp = timelocal(00, 00, $prime_start_hour, $cmday, $cmon, $cyear);
								$secs = $new_check_timestamp - $timestamp;
								$prime_code="N";
							}
							if ($secs < 0) { $secs = $secs * -1; }
							$new_rec=$alpha_ts." ".$timestamp." ".$secs." ".$color." ".$prime_code;
							$hold_timestamp = $timestamp;
							&fix_nonprime_rec();
							$timestamp = $hold_timestamp;
							$timestamp = $timestamp + $secs;
							$secs = 0;
						}
					}
					if ($prime_code eq "P") {
						if ($skip_once eq "TRUE") {
							$skip_once="FALSE";
						} else {
							$check_timestamp = $timestamp + $prime_secs;
							if ($check_timestamp > $end_timestamp) {
								$secs = ($end_timestamp - $check_timestamp) + $prime_secs;
							} else {
								$secs = $prime_secs;
							}
							$asc_wkday=substr($alpha_ts,0,3);
							$check_wkday=grep /$asc_wkday/,$PRIME_DAYS;
							if ($check_wkday == 0) {
								$new_rec=$alpha_ts." ".$timestamp." ".$secs." ".$color." N";
							} else {
								$new_rec=$alpha_ts." ".$timestamp." ".$secs." ".$color." ".$prime_code;
							}
							if (($prime_code eq "P") && ($timestamp > $start_time) && ($check_wkday > 0)) {
								$total_secs = $total_secs + $secs;
								$rec_array[$rec_count]=$new_rec;
								$rec_count++;
							}
							$timestamp = $timestamp + $secs;
							$secs = 0;
						}
					}
					if ($prime_code eq "N") {
						if ($skip_once eq "TRUE") {
							$skip_once="FALSE";
						} else {
							$check_timestamp = $timestamp + $non_prime_secs;
							if ($check_timestamp > $end_timestamp) {
								$secs = ($end_timestamp - $check_timestamp) + $non_prime_secs;
							} else {
								$secs = $non_prime_secs;
							}
							$new_rec=$alpha_ts." ".$timestamp." ".$secs." ".$color." ".$prime_code;
							$timestamp = $timestamp + $secs;
							$secs = 0;
						}
					}
				}
			}
		}

	close HISTFILE;

	$counter=0;

	while ($counter < $rec_count) {
		$prime_hist_rec=$rec_array[$counter];
		$hist_rec=substr($prime_hist_rec,25,60);	# State, timestamp and seconds - status data
		$save_hist_rec=$prime_hist_rec;			# Keep a copy of history record for detail
		($timestamp,$seconds,$color,$prime_code)=split(/\s+/,$hist_rec); # Formatted History Record

		if ($prime_code eq "P") {
			$period_secs = $seconds;
			if ($period_secs >= 0) {
				if ($hist_detail eq "TRUE") {
					if ($display_states eq "All_States") {
						&hist_all(); 
					}
					if ((($color eq "green") || ($color eq "yellow") || ($color eq "red") ||
						($color eq "clear")) && ($display_states eq "Critical_States")) {
							&hist_all(); 
					}
				}
				if ($color eq "green") { $green_sec = $green_sec + $period_secs };
				if ($color eq "yellow") { $yellow_sec = $yellow_sec + $period_secs };
				if ($color eq "red") { $red_sec = $red_sec + $period_secs };
				if ($color eq "purple") { $purple_sec = $purple_sec + $period_secs };
				if ($color eq "clear") { $clear_sec = $clear_sec + $period_secs };
				if ($color eq "blue") { $blue_sec = $blue_sec + $period_secs };
			}
		}
		$counter++;
	}
}

######################################################################################

# Subroutine to split prime time period from nonprime time record

sub fix_nonprime_rec {
	$seconds = $secs;
	$check_timestamp = $timestamp + $seconds;
	($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($check_timestamp);
	if (($hour >= $prime_start_hour) && ($hour < $prime_end_hour)) {
		$nonprime_end_time=timelocal(00, 00, $prime_start_hour, $mday, $mon, $year);
		$check_secs = $check_timestamp - $nonprime_end_time;
		if ($check_secs > 0) {
			$timestamp = $nonprime_end_time;
			$seconds = $check_secs;
			$asc_hist=strftime("%a %b %d %H:%M:%S %Y",00,00,$prime_start_hour,$mday,$mon,$year,$wday,$yday,$isdst);
			$asc_hist_wkday=substr($asc_hist,0,3);
			$check_wkday=grep /$asc_hist_wkday/,$PRIME_DAYS;
			if ($check_wkday > 0) {
				$prime_code = "P";
			} else {
				$prime_code = "N";
			}
			$new_rec=$asc_hist." ".$timestamp." ".$seconds." ".$color." ".$prime_code;
			if (($prime_code eq "P") && ($timestamp > $start_time) && ($check_wkday > 0)) {
				$rec_array[$rec_count]=$new_rec;
				$rec_count++;
				$total_secs = $total_secs + $seconds;
			}
		}
	}
}

######################################################################################

# The following calculates percentages for the various data periods

sub calc_perc {
	if ($total_secs > 0) {
		if ($display_states eq "Critical_States") {
			$total_secs = $total_secs - ($purple_sec + $blue_sec);
		}
		if ($total_secs <= 0) { $total_secs = 1; }
		$noncrit_secs = $blue_sec + $purple_sec;
		$green_per = ($green_sec / $total_secs) * 100.00;
		$yellow_per = ($yellow_sec / $total_secs) * 100.00;
		$red_per = ($red_sec / $total_secs) * 100.00;
		$clear_per = ($clear_sec / $total_secs) * 100.00;
		if ($display_states eq "Critical_States") {
			$total_per = ($green_per + $yellow_per + $red_per + $clear_per);
		} else {
			$purple_per = ($purple_sec / $total_secs) * 100.00;
			$blue_per = ($blue_sec / $total_secs) * 100.00;
			$total_per = ($green_per + $yellow_per + $red_per + $purple_per + $clear_per + $blue_per);
			if ($BLUE_FLAG eq "TRUE") {
				if ($total_per < 100) {
					$blue_per = $blue_per + (100 - $total_per);
				}
			}
		}
	}
}

######################################################################################

# Start with the page headings

sub display_headers {
	if ($BB_TYPE eq "NEW") {
		print $query->header;		# Required by perl CGI library
		$head_count = 0;
		open HEADER_FILE," $BBHEADER/hist_header"; 
		while (<HEADER_FILE>) {
			$head_count++;
			$_=~s/history/availability report/g;
			$_=~s/Big Brother Statistical Status/Big Brother Availability Report/g;
			$_=~s/: &BBHOST//g;
			$_=~s/&BBIP/Detail & Summary/g;
			$_=~s/ - &BBSVC//g;
                        $_=~s/<META HTTP-EQUIV="REFRESH" CONTENT="60">//g;
			if ($BB_V15A eq "FALSE") {
				$_=~s/gifs\//$BBWEB\/gifs\//g;
				$_=~s/help\//$BBWEB\/help\//g;
				$_=~s/bb2.html/$BBWEB\/bb2.html/g;
			}
			$_=~s/&BBRELDATE/$BBRELDATE/g;
			$_=~s/&BBREL/$BBREL/g;
	       		$_=~s/&BBDATE/$alpha_now/g;
			$_=~s/&BBBACKGROUND/$BBWEB\/gifs\/bkg-blue.gif/g;
        		$_=~s/&BBHOST/$HOSTDOTS/g;
			$_=~s/&BBSVC/$SERVICE/g;
        		$_=~s/&BBWEB/$BBWEB/g;
                        $_=~s/&BBSKIN/$BBSKIN/g;
			$_=~s/#00FFAA/#00FF60/g;

		# The first record of hist_header causes problems for the perl CGI
		#  library; therefore, the following will skip the first record.
		#  The "print $query->header" line above is all that is needed.

			if ($head_count > 1) {
				print "$_";
			}
		}
		close HEADER_FILE; 
	} else {
		print $query->header;
		print $query->start_html("Big Brother Service Availability Report: $HOSTDOTS - $SERVICE");
		print "<STYLE TYPE=\"text/css\"><!-- A:link {text-decoration: none}A:visited{text-decoration:none}A:active{text-decoration:none}--></STYLE>";
		print "</HEAD><BODY bgcolor=\"#000000\" background=\"$BBWEB/gifs/bkg-blue.gif\" link=\"#00FF60\" vlink=\"#FFFF44\" text=\"$TEXT_COLOR\">";

		print "<CENTER>";
		print "<TABLE SUMMARY=\"Navigation\" WIDTH=100%><TR><TD VALIGN=TOP ALIGN=LEFT>";
		print "<A HREF=\"http://bb4.com\"><IMG SRC=\"$BBWEB/gifs/bb.gif\" ALT=\"Get Big Brother\""; 
		print " BORDER=0></A><BR><TD>";
		print "<TD VALIGN=TOP ALIGN=RIGHT><FONT FACE=\"$TEXT_FONT\" SIZE=+1 COLOR=\"$TEXT_COLOR\">";
		print "<B>service availability</B><BR>";
		print "<B>$alpha_now</B></TD></TR></TABLE><BR>";

		print "</CENTER>";
		print "<BR><BR CLEAR=ALL></P>";
	}
}

######################################################################################

# The following section displays summaries for time period

sub display_record {
	print "<TR><TD ALIGN=CENTER COLSPAN=7><FONT FACE=\"$TEXT_FONT\" COLOR=\"$TEXT_COLOR\"></TD></TR>";
	print "<TR BGCOLOR=\"$DATA_BKG_COLOR\">";
	print "<TD><FONT COLOR=\"$TEXT_COLOR\"><A HREF=\"$BBWEBCGI/bb-rep.sh?histfile=$HOSTNAME.$SERVICE&start_time=$start_time&end_time=$end_time&total_secs=$total_secs&prime_flag=$prime_flag&prime_start_hour=$prime_start_hour&prime_end_hour=$prime_end_hour&prime_days=$hold_prime_days&display_states=$display_states&noncrit_secs=$noncrit_secs\"><FONT FACE=\"$TITLE_FONT\">$HOSTNAME.$SERVICE</a></TD>";
	print "<TD ALIGN=CENTER><FONT FACE=\"$TITLE_FONT\" COLOR=\"#00ff60\"><B>";
	printf "%7.2f", ${green_per};
	print "%</B></TD>";
	print "<TD ALIGN=CENTER><FONT FACE=\"$TITLE_FONT\" COLOR=\"#ffff00\"><B>";
	printf "%7.2f", ${yellow_per};
	print "%</B></TD>";
	print "<TD ALIGN=CENTER><FONT FACE=\"$TITLE_FONT\" COLOR=\"#ff8080\"><B>";
	printf "%7.2f", ${red_per};
	print "%</B></TD>";
	if ($display_states eq "All_States") {
		print "<TD ALIGN=CENTER><FONT FACE=\"$TITLE_FONT\" COLOR=\"#ff60ff\"><B>";
		printf "%7.2f", ${purple_per};
		print "%</B></TD>";
	}
	print "<TD ALIGN=CENTER><FONT FACE=\"$TITLE_FONT\" COLOR=\"#ffffff\"><B>";
	printf "%7.2f", ${clear_per};
	print "%</B></TD>";
	if ($display_states eq "All_States") {
		print "<TD ALIGN=CENTER><FONT FACE=\"$TITLE_FONT\" COLOR=\"#00a0ff\"><B>";
		printf "%7.2f", ${blue_per};
		print "%</B></TD>";
	}
	print "</TR>";
}

######################################################################################

# The following section displays footers

sub display_footers {
	print "</TD></TR></TABLE>";
	if ($BB_TYPE eq "NEW") {
		open FOOTER_FILE," $BBHEADER/hist_footer"; 
		while (<FOOTER_FILE>) {
			if ($BB_V15A eq "FALSE") {
				$_=~s/gifs\//$BBWEB\/gifs\//g;
				$_=~s/help\//$BBWEB\/help\//g;
			}
			$_=~s/&BBREL/$BBREL/g;
                        $_=~s/&BBSKIN/$BBSKIN/g;
			print "$_";
		}
		close FOOTER_FILE; 
	} else {
		print "<!-- Footer for pages by bb-rep.sh, lives in $BBHOME/web/hist_footer -->";

		print "<CENTER><BR><BR><HR WIDTH=\"80%\">";
		print "<TABLE WIDTH=\"80%\" BORDER=0><TR>";
		print "<TD ALIGN=\"center\" WIDTH=\"16%\">";
		print "<FONT FACE=\"$TEXT_FONT\" COLOR=\"$TEXT_COLOR\">";
		print "<IMG SRC=\"$BBWEB/gifs/green.gif\" WIDTH=\"16\" HEIGHT=\"16\" BORDER=\"0\"";
		print "ALIGN=\"middle\" ALT=\"green\"></A>ok</TD>";
		print "<TD ALIGN=\"center\" WIDTH=\"16%\">";
		print "<FONT FACE=\"$TEXT_FONT\" COLOR=\"$TEXT_COLOR\">";
		print "<IMG SRC=\"$BBWEB/gifs/yellow.gif\" WIDTH=\"16\" HEIGHT=\"16\" BORDER=\"0\"";
		print "ALIGN=\"middle\" ALT=\"yellow\"></A>attention</TD>";
		print "<TD ALIGN=\"center\" WIDTH=\"16%\">";
		print "<FONT FACE=\"$TEXT_FONT\" COLOR=\"$TEXT_COLOR\">";
		print "<IMG SRC=\"$BBWEB/gifs/red.gif\" WIDTH=\"16\" HEIGHT=\"16\" BORDER=\"0\"";
		print "ALIGN=\"middle\" ALT=\"red\"></A>trouble</TD>";
		print "<TD ALIGN=\"center\" WIDTH=\"16%\">";
		print "<FONT FACE=\"$TEXT_FONT\" COLOR=\"$TEXT_COLOR\">";
		print "<IMG SRC=\"$BBWEB/gifs/purple.gif\" WIDTH=\"16\" HEIGHT=\"16\" BORDER=\"0\"";
		print "ALIGN=\"middle\" ALT=\"purple\"></A>no report</TD>";
		print "<TD ALIGN=\"center\" WIDTH=\"16%\">";
		print "<FONT FACE=\"$TEXT_FONT\" COLOR=\"$TEXT_COLOR\">";
		print "<IMG SRC=\"$BBWEB/gifs/clear.gif\" WIDTH=\"16\" HEIGHT=\"16\" BORDER=\"0\"";
		print "ALIGN=\"middle\" ALT=\"clear\"></A>unavailable</TD>";
		print "<TD ALIGN=\"center\" WIDTH=\"16%\">";
		print "<FONT FACE=\"$TEXT_FONT\" COLOR=\"$TEXT_COLOR\">";
		print "<IMG SRC=\"$BBWEB/gifs/blue.gif\" WIDTH=\"16\" HEIGHT=\"16\" BORDER=\"0\"";
		print "ALIGN=\"middle\" ALT=\"blue\"></A>offline</TD>";
		print "</TR></TABLE>";
		print "</CENTER>";
		print "<HR WIDTH=\"80%\">";
		print "<BR><BR>";
		print "<CENTER>";
		print "<H6>";
		print "<!-- The license agreement requires a link back to the BB main site -->";
		print "<FONT FACE=\"$TEXT_FONT\" COLOR=\"$TEXT_COLOR\">";
		print "<A HREF=\"http://bb4.com\">";
		print "Big Brother Systems &amp; Network Monitor $vers</A><BR>";
		print "Copyright &copy; 1997-2000 BB4 Technologies Inc.<BR>";
		print "All Rights Reserved";
		print "</FONT></H6></CENTER>";
	}
	print "</BODY></HTML>";
}

######################################################################################
                        
# Subroutine to obtain user computing resource request information.
                        
sub get_date_info {   
	print "<CENTER><TABLE><TR BGCOLOR=\"$TITLE_BKG_COLOR\"><TD><CENTER>";
	print "<FONT COLOR=\"$TEXT_COLOR\" FACE=\"$TEXT_FONT\">Olympus Servicing L.P. Real-time Availability Report</FONT></CENTER></TD></TR>";
	print "<TR BGCOLOR=\"$DATA_BKG_COLOR\"><TD>";
        my($query) = @_;
	print "<FORM ACTION=\"$this_script\" METHOD=\"GET\">";
	print "<CENTER>";
	print $query->popup_menu(-name=>'start_month',
		-values=>['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],
		-default=>$this_month,
		-labels=>" ");
	print $query->popup_menu(-name=>'start_day',
		-values=>['01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31'],
# DRW		-default=>$this_day,
		-default=>$01,
		-labels=>" ");
	print $query->popup_menu(-name=>'start_year',
		-values=>['1998','1999','2000','2001','2002','2003','2004','2005','2006','2007','2008','2009','2010'],
		-default=>$this_year,
		-labels=>" ");
	print "<FONT COLOR=\"$TEXT_COLOR\" FACE=\"$TEXT_FONT\">- to - </FONT>";
	print $query->popup_menu(-name=>'end_month',
		-values=>['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],
		-default=>$this_month,
		-labels=>" ");
	print $query->popup_menu(-name=>'end_day',
		-values=>['01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31'],
		-default=>$this_day,
		-labels=>" ");
	print $query->popup_menu(-name=>'end_year',
		-values=>['1998','1999','2000','2001','2002','2003','2004','2005','2006','2007','2008','2009','2010'],
		-default=>$this_year,
		-labels=>" ");
	print "<BR>";

# Begin V1.1 Update - 30 May, 2000 - Jim Greene <jjg@interactive8.com> - Contributed Code
# Revised: V1.4 - 25 August, 2000 - Split Hosts and Services on Selection Criteria

	opendir HISTDIR,"$BBHIST";				# Open History Directory
	@histfiles_unsrt = readdir HISTDIR;			# Get the directory's contents
	closedir HISTDIR;					# Close the history directory
	@histfiles = grep /^\w.*\./, @histfiles_unsrt;		# Make sure we only have only good files
	%temphost;						# Initialize temphost
	%tempserv;						# and tempserv arrays

	foreach $file (@histfiles) {				# Loop through the history file names
		if ($fqdn eq "TRUE") {				# If fully qualified domain names are used
			$good_rec = grep /\,/, $file;		#  then check for only commas in filename
			if ($good_rec > 0) {	 		#  and skip over event log files
				($host, $serv) = split /\./, $file; # Get hostname and service
				$temphost{$host}++;		# Save hostname
				$tempserv{$serv}++;		# Save service
			}
		} else {
			($host, $serv) = split /\./, $file;	# Get hostname and service
			if ($serv ne "") {			# Skip over event log files, if no service name
				$temphost{$host}++;		# Save hostname
				$tempserv{$serv}++;		# Save service
			}
		}

	}

	@hosts = sort keys %temphost;				# Sort the hosts
	@servs = sort keys %tempserv;				# Sort the services
	@hostside = map { $_ .= "\\..*" } @hosts;		# Duplicate host array
	@servside = map { $_ = ".*\\.$_" } @servs;		# Duplicate services array
	@bigregexarray = ('');					# Allow selection of everything
	@biglabelarray = ('All Hosts');				# Message to that affect
	@bigregexarrays = ('');					# Allow selection of everything
	@biglabelarrays = ('All Services');			# Message to that affect
	push @bigregexarrays, @servside;			# Insert all services to select
	push @biglabelarrays, sort keys %tempserv;		# Insert the labels as well
	push @bigregexarray, @hostside;				# Insert all hosts to slecet
	push @biglabelarray, sort keys %temphost;		# Insert labels as well
	%bighash;						# Initilize array
	%bighashs;						# Initilize array
	for ($i=0; $i <= $#bigregexarray; $i++) {		# Build an array of selection criteria
		$bighash{$bigregexarray[$i]} = $biglabelarray[$i];
	}
	for ($i=0; $i <= $#bigregexarrays; $i++) {		# Build an array of selection criteria
		$bighashs{$bigregexarrays[$i]} = $biglabelarrays[$i];
	}

	print $query->popup_menu(-name=>'regex',		# Now allow the user to select the
		-values=>[@bigregexarray],			# host required. The
		-default=>'',					# default is to select everything.
		-labels=>\%bighash);				# This makes it easy to select.

	print $query->popup_menu(-name=>'regexs',		# Now allow the user to select the
		-values=>[@bigregexarrays],			# service required. The
		-default=>'',					# default is to select everything.
		-labels=>\%bighashs);				# This makes it easy to select.

# End V1.1/V1.4 Update

	print $query->popup_menu(-name=>'display_states',
		-values=>['All_States','Critical_States'],
#		-default=>'All_States',
# DRW, change value to set defualt on bb-avail.sh load
		-default=>'Critical_States',
		-labels=>" ");
	print $query->popup_menu(-name=>'prime_flag',
		-values=>['All_Times','Prime_Time'],
#		-default=>'Prime_Time',
# DRW, change value to set defualt on bb-avail.sh load
		-default=>'All_Times',
		-labels=>" ");
	($prime_start_hour,$prime_end_hour)=split(/ /,$PRIME_HOURS);
	@prime_days_default=split(/ /,$PRIME_DAYS);
        print "<HR><FONT COLOR=\"$TEXT_COLOR\" FACE=\"$TEXT_FONT\">Prime Time Selection</FONT><BR>";
	print $query->popup_menu(-name=>'prime_start_hour',
		-values=>['00','01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23'],
		-default=>$prime_start_hour,
		-labels=>" ");
        print "<FONT COLOR=\"$TEXT_COLOR\" FACE=\"$TEXT_FONT\"> - to - </FONT>";
	print $query->popup_menu(-name=>'prime_end_hour',
		-values=>['00','01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23'],
		-default=>$prime_end_hour,
		-labels=>" ");
	print $query->checkbox_group(-name=>'prime_days',
		-values=>['Sun','Mon','Tue','Wed','Thu','Fri','Sat'],
		-default=>\@prime_days_default,
		-linebreak=>'false',
		-labels=>\%labels,
		-columns=>7);
	print "<HR>";
	print $query->submit('Send','Generate Real-time Report');
	print $query->endform;
	print "</CENTER></TD></TR></TABLE></CENTER>";
	print $query->end_html;
}

######################################################################################

# Subroutine to check date range entered

sub check_date {
	$bad_date="";
	if ($end_time < $start_time) { $bad_date = "TRUE"; }
	if (($end_time > $now) || ($start_time > $now)) { $bad_date = "TRUE"; }
	if ((($start_month eq "Apr") || ($start_month eq "Jun") || ($start_month eq "Sep") || ($start_month eq "Nov")) &&
		($start_day > 30)) { $bad_date = "TRUE"; }
	if ((($end_month eq "Apr") || ($end_month eq "Jun") || ($end_month eq "Sep") || ($end_month eq "Nov")) &&
		($end_day > 30)) { $bad_date = "TRUE"; }
	if ($start_month eq "Feb") {
		$year_check = $start_year % 4;
		if (($year_check > 0) && ($start_day > 28)) { $bad_date = "TRUE"; }
		if (($year_check == 0) && ($start_day > 29)) { $bad_date = "TRUE"; }
	} 
	if ($end_month eq "Feb") {
		$year_check = $end_year % 4;
		if (($year_check > 0) && ($end_day > 28)) { $bad_date = "TRUE"; }
		if (($year_check == 0) && ($end_day > 29)) { $bad_date = "TRUE"; }
	} 
}

######################################################################################

# Subroutine to print supporting history records

sub hist_all {
	$hist_rec=substr($save_hist_rec,25,60);				# History Data
	$hist_date=substr($save_hist_rec,0,25);				# Alpha Date
	($hdow,$hmon,$hday,$htime,$hyear) = split(/\s+/,$hist_date);    # Split up Alpha Date
	$hist_date_udl=$hdow."_".$hmon."_".$hday."_".$htime."_".$hyear; #  and place "_" between fields.

	if ($prime_flag eq "All_Times") {
		($color,$timestamp,$seconds)=split(/\s+/,$hist_rec);	# Formatted History Record
	} else {
		($timestamp,$seconds,$color,$prime_code)=split(/\s+/,$hist_rec); # Formatted Prime Time History Record
	}

	if ($timestamp > $start_time) {
		($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($timestamp);
		$alpha_start = strftime("%a %b %d %H:%M:%S %Y",$sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst);
	} else {
		($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($start_time);
		$alpha_start = strftime("%a %b %d %H:%M:%S %Y",$sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst);
	}

	if ($seconds eq "") {
		($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($end_time);
		$alpha_end = strftime("%a %b %d %H:%M:%S %Y",$sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst);
	} else {
		$new_timestamp = $timestamp + $seconds;
		if ($new_timestamp > $end_time) {
			($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($end_time);
			$alpha_end = strftime("%a %b %d %H:%M:%S %Y",$sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst);
		} else {
			($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($new_timestamp);
			$alpha_end = strftime("%a %b %d %H:%M:%S %Y",$sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst);
		}
	}

	if ($display_states eq "All_States") {
		$log_percent = ($period_secs / $total_secs) * 100;
	}
	if (($display_states eq "Critical_States") && (($color eq "purple") || ($color eq "blue"))) {	
		$log_percent = 0;
	}
	if (($display_states eq "Critical_States") && (($color eq "green") || ($color eq "yellow") ||
		($color eq "red") || ($color eq "clear"))) {
			$log_percent = ($period_secs / ($total_secs - $noncrit_secs)) * 100;
	}
	if ($color ne "") {
		print "<TR BGCOLOR=\"$DATA_BKG_COLOR\"><TD ALIGN=LEFT><FONT FACE=\"$DATA_FONT\">$alpha_start</TD><TD ALIGN=CENTER>";
		print "<FONT FACE=\"$DATA_FONT\">$alpha_end</TD><TD ALIGN=CENTER>";
		if (($BB_TYPE eq "NEW") && ($prime_flag eq "All_Times")) {
			print "<A HREF=\"$BBWEBCGI/bb-histlog.sh?HOST=$HOSTUDL&SERVICE=$SERVICE&TIMEBUF=$hist_date_udl\">";
		}
		print "<IMG SRC=\"$BBWEB/gifs/$color.gif\" BORDER=0 HEIGHT=16 WIDTH=16 ALT=\"$color\"></TD>";
		secs_dur();
		print "<TD ALIGN=CENTER><FONT FACE=\"$DATA_FONT\">$duration</TD>";
		print "<TD ALIGN=CENTER><FONT FACE=\"$DATA_FONT\">";
		printf "%7.2f", ${log_percent};
		print "%</TD></TR>";
	}
}

######################################################################################

# This subroutine will display the service availability summary

sub data_summary {
	print "<TABLE BORDER=0 BGCOLOR=\"$DATA_BKG_COLOR\" CELLSPACING=3>";
	print "<TR>";
	print "<TD ALIGN=CENTER COLSPAN=6 BGCOLOR=\"$TITLE_BKG_COLOR\"><FONT FACE=\"$TEXT_FONT\" COLOR=\"$TEXT_COLOR\"><B>Availability Summary</B></TD></TR>";
	print "<TR><TD ALIGN=CENTER><IMG SRC=\"$BBWEB/gifs/green.gif\" ALT=\"green\" HEIGHT=16 WIDTH=16 BORDER=0></TD>";
	print "<TD ALIGN=CENTER><IMG SRC=\"$BBWEB/gifs/yellow.gif\" ALT=\"yellow\" HEIGHT=16 WIDTH=16 BORDER=0></TD>";
	print "<TD ALIGN=CENTER><IMG SRC=\"$BBWEB/gifs/red.gif\" ALT=\"red\" HEIGHT=16 WIDTH=16 BORDER=0></TD>";
	if ($display_states eq "All_States") {
		print "<TD ALIGN=CENTER><IMG SRC=\"$BBWEB/gifs/purple.gif\" ALT=\"purple\" HEIGHT=16 WIDTH=16 BORDER=0></TD>";
	}
	print "<TD ALIGN=CENTER><IMG SRC=\"$BBWEB/gifs/clear.gif\" ALT=\"clear\" HEIGHT=16 WIDTH=16 BORDER=0></TD>";
	if ($display_states eq "All_States") {
		print "<TD ALIGN=CENTER><IMG SRC=\"$BBWEB/gifs/blue.gif\" ALT=\"blue\" HEIGHT=16 WIDTH=16 BORDER=0></TD></TR>";
	}	
	print "<TR BGCOLOR=\"$DATA_BKG_COLOR\">";
	print "<TD ALIGN=CENTER><FONT FACE=\"$DATA_FONT\"><B>";
	printf "%7.2f", ${green_per};
	print "%</B></TD>";
	print "<TD ALIGN=CENTER><FONT FACE=\"$DATA_FONT\"><B>";
	printf "%7.2f", ${yellow_per};
	print "%</B></TD>";
	print "<TD ALIGN=CENTER><FONT FACE=\"$DATA_FONT\"><B>";
	printf "%7.2f", ${red_per};
	print "%</B></TD>";
	if ($display_states eq "All_States") {
		print "<TD ALIGN=CENTER><FONT FACE=\"$DATA_FONT\"><B>";
		printf "%7.2f", ${purple_per};
		print "%</B></TD>";
	}
	print "<TD ALIGN=CENTER><FONT FACE=\"$DATA_FONT\"><B>";
	printf "%7.2f", ${clear_per};
	print "%</B></TD>";
	if ($display_states eq "All_States") {
		print "<TD ALIGN=CENTER><FONT FACE=\"$DATA_FONT\"><B>";
		printf "%7.2f", ${blue_per};
		print "%</B></TD>";
	}
	print "</TR></TABLE>";
	print "<TD COLSPAN=6 ALIGN=CENTER><FONT FACE=\"$HEADER_FONT\" COLOR=\"$HEADER_COLOR\" SIZE=-1><B>[Percentages may not total 100%]</B></TD></TR></TABLE>";
	print "</TD></TR></TABLE>";
}

# Subroutine to convert seconds into DDd-HH:MM:SS format

sub secs_dur {

$rem1 =  $period_secs % (24 * 3600);		# Days - Remainder Seconds 
$days = ($period_secs - $rem1) / (24 * 3600);	# Whole Days
$rem2 = $rem1 / 3600;				# Hours + Remainder Seconds
$rem3 = $rem1 % 3600;				# Hours - Remainder Seconds
$rhours = ($rem1 - $rem3) / 3600;		# Whole Hours
$rem4 = $rem3 / 60;				# Minutes + Remainder Seconds
$rsecs = $rem3 % 60;				# Remainder Seconds
$rmins = ($rem3 - $rsecs) / 60;			# Whole Minutes

if ($rsecs < 10) {
	$psecs = "0".$rsecs;
} else {
	$psecs = $rsecs;
}
if ($rmins < 10) {
	$pmins = "0".$rmins;
} else {
	$pmins = $rmins;
}
if ($rhours < 10) {
	$phours = "0".$rhours;
} else {
	$phours = $rhours;
}
$duration = $days."d-".$phours.":".$pmins.":".$psecs;

}

