#!/usr/local/bin/perl
# Calls the system 'cal' function to display a calendar: FORM
# File: calendar3.pl

$CAL = '/usr/bin/cal';
@years=(1990..2010);
%query = &get_query;
# 
# Set the year to the query, otherwise the current year
if ($query{'year'}) {
    $year = $query{'year'};
} else {
    chop($year=`date +%Y`);
}

# Print the header and the top of the document
print <<END;
Content-type: text/html

<HTML><HEAD><TITLE>Calendar</TITLE></HEAD>
<BODY>
<H1>Calendar for $year </H1>
END
    ;

# ------------------- CREATE THE FILL-OUT FORM -------------------
# Print the popup menu for the year.
print '<FORM METHOD=POST>',"\n";
print "YEAR: <SELECT NAME=year>\n";
foreach $y (@years) {
    $selected = ($y == $year) ? 'SELECTED' : '';
    print "<OPTION $selected>$y\n";
}
print "</SELECT>\n";

# Print the checkbox for Julian calendar.
$checked = 'CHECKED' if $query{'julian'};
print qq/<INPUT TYPE="checkbox" NAME="julian" $checked>Julian\n/;

# Submit button
print '<P><INPUT TYPE="submit" VALUE="Make Calendar">';
print "</FORM><HR>\n";

# ------------------- PRINT THE CALENDAR -------------------
unless ($year=~/^\d{4}$/) {
    print "<STRONG>ERROR</STRONG>Year must be exactly four digits\n";
    exit 0;
}

$extra_switches = '-j' if $query{'julian'};
chop($calendar_text=`$CAL $year`);

print <<END;
<PRE>
$calendar_text
</PRE>

<HR><A HREF="/">Welcome Page</A>
</BODY></HTML>
END

;

# ------------------ QUERY PARSING ROUTINE HERE ------------
sub get_query {
    local($query_string);
    local(@lines);
    local($method)=$ENV{'REQUEST_METHOD'};

    # If method is GET fetch the query from
    # the environment.
    if ($method eq 'GET') {
	$query_string = $ENV{'QUERY_STRING'};

	# If the method is POST, fetch the query from standard in
    } elsif ($method eq 'POST') {
	read(STDIN,$query_string,$ENV{'CONTENT_LENGTH'});
    }

    # No data.  Return an empty array.
    return () unless $query_string;	

    # We now have the query string.
    # Call parse_params() to split it into key/value pairs
    return &parse_params($query_string);
}

sub parse_params {
    local($tosplit) = @_;
    local(@pairs) = split('&',$tosplit);
    local($param,$value,%parameters);

    foreach (@pairs) {
	($param,$value) = split('=');
	$param = &unescape($param);
	$value = &unescape($value);
	if ($parameters{$param}) {
	    $parameters{$param} .= "$;$value";
	} else {
	    $parameters{$param} = $value;
	}
    }
    return %parameters;
}

sub unescape {
    local($todecode) = @_;
    $todecode =~ tr/+/ /;	# pluses become spaces
    $todecode =~ s/%([0-9A-Fa-f]{2})/pack("c",hex($1))/ge;
    return $todecode;
}






