#!/usr/bin/perl

use Time::Local;

my @month =  ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');

# set game start
my $game_start = 970444800; # 2 October 2000, 00:00:00 UTC, in seconds since the epoch
my ($game_start_month, $game_start_year) = (gmtime($game_start))[4 .. 5];

# get year and month for calendar
my $year = pop @ARGV;
my $month = pop @ARGV;

# gmtime returns year-1900, month begining with 0
$year -= 1900 if defined($year);
$month-- if defined($month);

my ($start, $stop);

# determine stop date
if (defined($month)) {
	# both month and year specified
   die "ncal.pl: illegal month: use 1-12\n" if $month > 11 or $month < 0;
   $stop = timegm(0, 0, 0, 1, ($month+1)%12, $year+(($month+1) > 11)*1)-86400;
}
elsif (defined($year)) {
	# just year
   $month = $year > $game_start_year ? 0 : $game_start_month;
   $stop = timegm(0, 0, 0, 1, 0, $year+1)-86400;
}
else {
	# current month
   ($month, $year) = (gmtime)[4 .. 5];
   $stop = timegm(0, 0, 0, 1, ($month+1)%12, $year + (($month+1) > 11)*1)-86400;
}

die "ncal.pl: illegal date: use dates post 1 Oct 2000\n" if $year < $game_start_year or ($year == $game_start_year and $month < $game_start_month);

# set start date
$start = $month == $game_start_month ? $game_start : timegm(0, 0, 0, 1, $month, $year);

$year+=1900;

# get start nweek
my $nweek = int(($start-$game_start)/864000)+1;

my $t = $start;
while ($t <= $stop) {
	for (my $i = $t == $start ? (int((($start-$game_start)%864000)/86400))%7 : 0; $i <= 9; $i++) {
		my $day = (gmtime($t))[3];
		if ($t > $stop) {
			print ' ' x (30-3*$i);
			last;	
		}	
		elsif ($t == $start or $day == 1) {
			if ($t != $start) {
				$month = ($month+1)%12;
				printf("%s%2d\n", ' ' x (35-3*$i), $nweek) if $i != 0;
			}
			print "\n", ' ' x int((29-length("$month[$month] $year"))/2), "$month[$month] $year\n", ' ' x (3*$i);
		}
		printf("%2d ", $day);
		$t+=86400;
	}
	printf("     %2d\n", $nweek);
	$nweek++;
}

print "\n";

