#!/usr/bin/perl

# daylight.pl takes in arguments from daylight.html

# First tell browser that this is an HTML document being printed

print "Content-type:text/html\n\n";

# The following formats the incoming arguments and puts them into the
# vector $FORM with fields year, month, day, ns, lat, ew, lon

read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
@pairs = split(/&/, $buffer);
foreach $pair (@pairs) {
    ($name, $value) = split(/=/, $pair);
    $value =~ tr/+/ /;
    $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
    $value =~ s/\n/ /g; # replace newlines with spaces
    $FORM{$name} = $value;
}

# The nitty-gritty calculations

# Sets up global varables, such as distances, periods, and angles

$Pi = 3.141592653; $r = 6400; $c = 150000000; $light = 0;
$p = $Pi / 262800 / 1;		# My editor color codes and uses / to represent comments.
$w = $Pi / 720 / 1;		# Doesn't look good when I divide once, so I divide twice.
$alpha = $Pi * 11 / 90 / 1;

# Converts the variables from the web page
# from degrees and days to radians and minutes
$phi = $FORM{ns} * $FORM{lat} * $Pi / 180 / 1;
$theta = $FORM{ew} * $FORM{lon} * $Pi / 180 / 1;
$d = ($FORM{month} + $FORM{day});	# $d used to print web page
$t = $d * 1440 + 14400;		# Add 14400 to change for Dec. 21 being the shortest day

# Sets a for-loop from 0 to 1439 (1440 minutes in a day, one rotation)

for($i = 0; $i < 1440; $i++) {

    # Vector s if from the sun to the earth
    # ($t + $i makes the earth revolve every minute as well)
    $s1 = $c * cos($p * ($t + $i));
    $s2 = $c * sin($p * ($t + $i));
    $s3 = 0;

    # Vector e is from center of earth to a point on earth
    $e1 = $r * cos($phi) * cos($theta + $w * ($t + $i));
    $e2 = $r * cos($phi) * sin($theta + $w * ($t + $i));
    $e3 = $r * sin($phi);

    # Vector p is the point on the earth tilted
    # Before the days were off by half a year
    # The matrix was inverted to compensate for this
    # Either this or adding 262800 minutes to the current minute
    $p1 = $e1 * cos($alpha) + $e3 * sin($alpha);
    $p2 = $e2;
    $p3 = -$e1 * sin($alpha) + $e3 * cos($alpha);

    # $l is the distance between the center of the sun and the new point
    $l = sqrt(($s1 + $p1)**2 + ($s2 + $p2)**2 + ($s3 + $p3)**2);

    # If this new point is closer to the sun than the center of the earth is,
    # light is showing on that point on the earth.
    if($l < $c) {$light++;}
}

# Convert $light (number of light minutes) to $h:$m (hours and minutes)
$h = int($light / 60) / 1;
$m = $light % 60;


# Prints HTML document

print <<EndOfHTML;
<html>
<head>
<title>Results</title>
</head>
<body>
<h2>Results for the amount of sunlight on day $d:</h2>
<p>The sun will shine for $h hours and $m minutes on this day.
</body>
</html>
EndOfHTML
