: # feed this into perl *-*-perl-*-*
    eval 'exec perl -S $0 "$@"'
    if $running_under_some_shell;

#
# Print out the Shift Summary data in readable form.
# Email the raw data to a list of users
# Email the readable form to a list of users
#
# (saw) 1997
# (saw) July 8, 1998  Update for new terms.
# (rom) July 20, 1998  replace Hall C --> A

use FileHandle;

$dohtml=1;			# Set to 1 to place entries in the Hall A log
				# book.  For use in other halls, adjust the
				# path in the $command towards the end of this
				# file.

if(@ARGV[0]) {
    $dbinp_file = @ARGV[0];
    $dbentry = 1;
} else {
    $dbentry = 0;
}

if($dbentry) {
    $def = $dbinp_file;
} else { 
    $def = 'HallAccount.def';	# Hall specific definitions
}
$dat = 'HallAccount.sav';	# Shift summary data
$report = 'HallAccount.report'; # Printable version of report
$html = 'HallAccount.html';
$tempfile = 'HallAccount.temp'; # Temporary file

open(DEF,"<".$def)|| die "Cannot open definitions file: $def.\n $! \n";

open(REPORT,">".$report)|| die "Cannot open report output file: $report.\n $! \n";
if($dohtml) {
    open(HTML,">".$html)|| die "Cannot open report html file: $html.\n $! \n";
}
    

# Read .def file.  Skip until a line ending with a : is found.

$report_mailing_list = "";
$rawdata_mailing_list = "";
while(<DEF>){
    chomp;
    last if (/^End File$/);
    next if( not /:$/);
    chop;			# Remove the :
    if(/Hallname/) {
	$hallname = <DEF>;
	chomp($hallname);
    } elsif (/Printer/) {
	$printer = <DEF>;
	chomp($printer);
    } elsif (/Directory/) {
	$directory = <DEF>;
	chomp($directory);
    } elsif (/Experiment/) {
	$experiment = <DEF>;
	chomp($experiment);
    } elsif (/Report Mailing List/) {
	$report_mailing_list = <DEF>;
	chomp($report_mailing_list);
    } elsif (/Rawdata Mailing List/) {
	$rawdata_mailing_list = <DEF>;
	chomp($rawdata_mailing_list);
    } elsif (/Reasons/) {
	$nreasons=0;
	while(<DEF>) {
	    chomp;
	    last if (/End Reasons/);
	    $reasons[$nreasons++] = $_;
	}
    }
}

if (not $dbentry) {
    open(DEF,"<".$dat)
	|| die "Cannot open shift summary data file: $dat.\n $! \n";
} # Else continue reading the same file.

$scheduled[0] = 0;$scheduled[1] = 0;$scheduled[2] = 0;$scheduled[3] = 0;
$scheduled[4] = 0;$scheduled[5] = 0;$scheduled[6] = 0;$scheduled[7] = 0;
while(<DEF>){
    chomp;
    if(/Leader/) {
	$leader = <DEF>;
	chomp($leader);
    } elsif (/Author/) {
	$author = <DEF>;
	chomp($author);
    } elsif (/Experiment/) {
	$experiment = <DEF>;
	chomp($experiment);
    } elsif (/Workers/) {
	$nworkers=0;
	while(<DEF>) {
	    chomp;
	    last if (/End Workers/);
	    $workers[$nworkers++] = $_ if /\w/; # Skip blank lines
	}
    } elsif (/BeamScheduled/) {
	$scheduledlist = <DEF>;
	chomp($scheduledlist);
	split('\|',$scheduledlist);	
	for($i=0;$i<8;$i++) {
	    $scheduled[$i] = @_[$i];
	}
    } elsif (/Starttime/) {
	$starttime = <DEF>;
	chomp($starttime);
	for($i=0;$i<9;$i++) {
	    $times[$i] = 100*($starttime + $i);
	    $times[$i] -= 2400 if $times[$i] > 2400;
	    $times[$i] = sprintf("%.4d",$times[$i]); # Make sure it is 4 digits
	}
    } elsif (/Startdate/) {
	$startdate = <DEF>;
	chomp($startdate);
    } elsif (/^HallData$/) {
	$j = 0;
	while(<DEF>) {
	    chomp;
	    last if (/End HallData/);
	    split('\|');
	    $dd_total = 0;
	    for($i=0;$i<8;$i++) {
		$dd[$j][$i] = @_[$i];
		if($dd[$j][$i] > 1) {
		    $dd_total[$j] += $dd[$j][$i]/60.0;
		} else {
		    $dd_total[$j] += $dd[$j][$i];
		}
	    }
	    $j++;
	}
    } elsif (/^Comments/) {
	$comments = "";
	while(<DEF>) {
	    last if(/^End Comments$/);
	    $comments = $comments.$_;
	}
    } elsif (/^Data$/) {
	for($j=0;$j<7;$j++) {
	    $data_total[$j] = 0;
	}
	for($i=0;$i<8;$i++) {
	    $line = <DEF>;
	    chomp($line);
	    ($data[0][$i],$data[1][$i],$data[2][$i],$data[3][$i],$data[4][$i],
	     $data[5][$i],$data[6][$i]) = split('\|',$line);
	    for($j=0;$j<7;$j++) {
		if($data[$j][$i] > 1) {
		    $data_total[$j] += $data[$j][$i]/60.0;
		} else {
		    $data_total[$j] += $data[$j][$i];
		}
	    }
	}
	$line = <DEF>;
    }
}
if($dbentry) {
    eval("use Mysql");
#
# First convert data that was kept in minutes into hours
#
    for($i=0;$i<8;$i++) {
	for($j=0;$j<6;$j += 3){
	    $sum = $data[$j][$i] + $data[$j+1][$i] + $data[$j+2][$i];
	    if($sum > 1.001) {
		$data[$j][$i] /= 60.0;
		$data[$j+1][$i] /= 60.0;
		$data[$j+2][$i] /= 60.0;
	    }
	}
# Data taking
	if($data[6][$i] > 1.001) { # Definitely minutes
	    $data[6][$i] /= 60.0;
	} elsif($data[6][$i] > 0.999) {
	    if(($data[6][$i] > $data[0][$i]) # Data taking can't exceed beam on
	       || ($data[6][$i] > $data[3][$i])) { # or experiment ready
		$data[6][$i] /= 60.0; # Must be a single minute.
	    }
	}
    }
    ($table_name=$hallname) =~ s/\s+/_/g;
    if (!($dbh = Mysql->Connect("","beam_time"))) {
	die "not connected: $Mysql::db_errstr\n";
    }
    ($month,$day,$year) = split('/',$startdate);
    if($year < 100) {
	if($year > 90) {
	    $year += 1900;
	} else {
	    $year += 2000;
	}
    }
    print "$month,$day,$year\n";
    $hour = $starttime;
    for($i=0;$i<8;$i++){
	if($hour == 24) {
	    $hour = 0;
	    $day++;
	    @month_lengths=(31,28,31,30,31,30,31,31,30,31,30,31);
	    $monlen=$month_lengths[$month-1];
	    $monlen++ if($month==2 && 
			 ($year%4==0 && ($year%100!=0 || $year%400==0)));
	    if($day > $monlen) {
		$day = 1;
		$month++;
		if($month>12){
		    $month=1;
		    $year++;
		}
	    }
	}
	$date = sprintf("%.4d-%.2d-%.2d %.2d:00:00",$year,$month,$day,$hour);
	$query = qq{INSERT INTO $table_name (Beam_avail_acceptable,
				       Beam_avail_not_request, Beam_not_avail,
				       Experiment_Ready, Configuration_change,
				       Enr, Hour, Data_taking, Scheduled,
				       Experiment)
			VALUES ($data[0][$i],$data[1][$i],$data[2][$i],
				$data[3][$i],$data[4][$i],$data[5][$i],
				"$date",$data[6][$i],$scheduled[$i],
				"$experiment")};
        if($sth=$dbh->Query($query)) {
            print "hour $i added to database\n";
        } else { # Assume that error is because date/time already exists
	    # and needs to be updated.
	    $query = qq{UPDATE $table_name SET
			    Beam_avail_acceptable=$data[0][$i],
			    Beam_avail_not_request=$data[1][$i],
			    Beam_not_avail=$data[2][$i], 
			    Experiment_Ready=$data[3][$i],
			    Configuration_change=$data[4][$i],
			    Enr=$data[5][$i],
			    Data_taking=$data[6][$i],
			    Scheduled=$scheduled[$i],
			    Experiment="$experiment" 
				WHERE Hour="$date"};
	    if($sth=$dbh->Query($query)) {
		print "hour $i updated in database\n";
	    } else {
		print "$query\n";
		print "$Mysql::db_errstr\n";
	    }
        }
        $hour += 1;
    }
} else {
format REPORT =
                            @>>>>>>>> Shift Summary
                            $hallname

                            @<<<<<<<<<<<      @<<<-@<<<
                            $startdate,       $times[0],$times[8]

   Experiment #:  @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
                  $experiment
   Shift Leader:  @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
                  $leader
   Shift Workers: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
                  join(", ",@workers);

   ==========================================================================|
                      |            Start hour of shift                |      |
                      ------------------------------------------------|Total |
                      @<<<  @<<<  @<<<  @<<<  @<<<  @<<<  @<<<  @<<<  |Time  |
$times[0],$times[1],$times[2],$times[3],$times[4],$times[5],$times[6],$times[7]
   ==========================================================================|
   Acceptable Beam    |     |     |     |     |     |     |     |     |      |
   in Use             |@#.##|@#.##|@#.##|@#.##|@#.##|@#.##|@#.##|@#.##|@#.## |
$data[0][0],$data[0][1],$data[0][2],$data[0][3],$data[0][4],$data[0][5],$data[0][6],$data[0][7],$data_total[0]
   -------------------------------------------------------------------|------|
   Beam Available     |     |     |     |     |     |     |     |     |      |
   but Not in Use     |@#.##|@#.##|@#.##|@#.##|@#.##|@#.##|@#.##|@#.##|@#.## |
$data[1][0],$data[1][1],$data[1][2],$data[1][3],$data[1][4],$data[1][5],$data[1][6],$data[1][7],$data_total[1]
   -------------------------------------------------------------------|------|
   Beam not Available |     |     |     |     |     |     |     |     |      |
   or Unacceptable    |@#.##|@#.##|@#.##|@#.##|@#.##|@#.##|@#.##|@#.##|@#.## |
$data[2][0],$data[2][1],$data[2][2],$data[2][3],$data[2][4],$data[2][5],$data[2][6],$data[2][7],$data_total[2]
   -------------------------------------------------------------------|------|
   Accelerator Con-   |     |     |     |     |     |     |     |     |      |
   figuration Change  |@#.##|@#.##|@#.##|@#.##|@#.##|@#.##|@#.##|@#.##|@#.## |
$data[3][0],$data[3][1],$data[3][2],$data[3][3],$data[3][4],$data[3][5],$data[3][6],$data[3][7],$data_total[3]
   ==========================================================================|
   Experiment         |     |     |     |     |     |     |     |     |      |
   Ready              |@#.##|@#.##|@#.##|@#.##|@#.##|@#.##|@#.##|@#.##|@#.## |
$data[4][0],$data[4][1],$data[4][2],$data[4][3],$data[4][4],$data[4][5],$data[4][6],$data[4][7],$data_total[4]
   -------------------------------------------------------------------|------|
   Planned Config-    |     |     |     |     |     |     |     |     |      |
   uration Change     |@#.##|@#.##|@#.##|@#.##|@#.##|@#.##|@#.##|@#.##|@#.## |
$data[5][0],$data[5][1],$data[5][2],$data[5][3],$data[5][4],$data[5][5],$data[5][6],$data[5][7],$data_total[5]
   -------------------------------------------------------------------|------|
   Unplanned          |     |     |     |     |     |     |     |     |      |
   Experiment Down    |@#.##|@#.##|@#.##|@#.##|@#.##|@#.##|@#.##|@#.##|@#.## |
$data[6][0],$data[6][1],$data[6][2],$data[6][3],$data[6][4],$data[6][5],$data[6][6],$data[6][7],$data_total[6]
   ==========================================================================|
   ==========================================================================|
.

write REPORT;

format REPORT_1 =
   Not Ready:         |     |     |     |     |     |     |     |     |      |
   @<<<<<<<<<<<<<<<<<<|@#.##|@#.##|@#.##|@#.##|@#.##|@#.##|@#.##|@#.##|@#.## |
$reasons[$i],$dd[$i][0],$dd[$i][1],$dd[$i][2],$dd[$i][3],$dd[$i][4],$dd[$i][5],$dd[$i][6],$dd[$i][7],$dd_total[$i]
   @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<|
   $separator;
.

REPORT->format_name("REPORT_1");
$separator="-------------------------------------------------------------------|------|";
for($i=0;$i<$nreasons;$i++) {
    if($i+1 >= $nreasons) {
	$separator="==========================================================================|";
    }
    write REPORT;
}

format REPORT_2 =

   Comments:
~~      ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
         $comments

   Data Entry by:
	@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
	$author
.

REPORT->format_name("REPORT_2");
$save_comments = $comments;
$save_author = $author;
write REPORT;
$comments = $save_comments;
$author = $save_author;

close REPORT;

#
# Email the raw data
#
if($rawdata_mailing_list =~ /\w/) {
    $command = qq{echo "Subject: $hallname Beamtime Accounting Raw Data\n" | /bin/cat - $def $dat | /bin/mail $rawdata_mailing_list};
    system($command);
}
#
# Email the pretty printout
#
if($report_mailing_list =~ /\w/) {
    $command = qq{echo "Subject: $hallname Beamtime Accounting\n" | /bin/cat - $report | /bin/mail $report_mailing_list};
    system($command);
}

if($dohtml) {
    $titles[0] = "Acceptable Beam<br>in Use";
    $titles[1] = "Beam Available<br>but Not in Use";
    $titles[2] = "Beam Not Available<br>or Unacceptable";
    $titles[3] = "Accelerator Con-<br>figuration Chage";
    $titles[4] = "Experiment<br>Ready";
    $titles[5] = "Planned Config-<br>uration Change";
    $titles[6] = "Unplanned<br>Experiment Down";
    print HTML qq{
	<center>$hallname<br>
	<br>$startdate    $times[0]-$times[8]</center>\n
	Experiment #: $experiment<br>\n
	Shift Leader: $leader<br>\n
	    Shift Workers: },join(", ",@workers),"<br><br>\n";
    print HTML "<table border=1><tr><th></th>";
    for($j=0;$j<8;$j++){
	print HTML "<th width=40>$times[$j]</th>";
    }
    print HTML "<th>Total Time</th></tr><tr></tr>\n";
    for($i=0;$i<7;$i++){
	print HTML "<tr></tr>\n" if ($i==4);
	print HTML "<tr><th>$titles[$i]</th>";
	if($i==6) {
	    $attribute=qq{bgcolor="#ffffc2"};
	} else {
	    $attribute="";
	}
	for($j=0;$j<8;$j++){
	    print HTML qq{<td align=center $attribute>$data[$i][$j]</td>};
	}
	print HTML "<td align=center $attribute>$data_total[$i]</td></tr>\n";
    }
    print HTML "<tr></tr><tr><th>Hall not<br>ready reasons</th></tr>\n";
    for($i=0;$i<$nreasons;$i++) {
	print HTML "<tr><th>$reasons[$i]</th>";
	for($j=0;$j<8;$j++){
	    print HTML "<td align=center>$dd[$i][$j]</td>";
	}
	print HTML "<td align=center>$dd_total[$i]</td></tr>\n";
    }
    print HTML "</table>\n";
    print HTML "<p>Comments: $comments\n";
    print HTML "<p>Data Entry by: $author\n";
    close(HTML);
    $command = qq{/home/adaq/halog/src/halogentry.html /home/adaq/ACCOUNT/HallAccount.html "Beam Time Accounting"};
    print "$command\n";
    system($command);
}
    
}
