#!/usr/bin/perl -w

#-----------------------------------------
# Perl code for a cal replacement
# Works to ISO8601 weeks, and shows week
# number
#
# ADSB 23 November 1998
#
# Inelegant, unfinished, etc...
#-----------------------------------------

use POSIX;
require "weeknums.pl";

@shortdays=("Mo","Tu","We","Th","Fr","Sa","Su");
@months=("January","February","March","April","May","June","July","August","September","October","November","December");
@monthlens=(31,28,31,30,31,30,31,31,30,31,30,31);

if ($#ARGV < 0) {
        $year=1900+(localtime)[5];
} else {
	$year=$ARGV[0];
}

if ($year % 4 == 0) {
	$monthlens[1]++;
}

@tm=(0,0,12,1,0,$year-1900,0,0);
$time=mktime(@tm);
@tm=localtime($time);
if ($tm[6] == 0) { $tm[6] = 7;}
if ($tm[6] > 4) {
	$week=0;
} else {
	$week=1;
}

print "$year\n";

if ($#ARGV > 0) {
	$i=$ARGV[1];
	$i--;
	&doMonth($i);
} else {
	for ($i=0; $i<12; $i++) {
		&doMonth($i);
	}
}


sub doMonth {
	$i=$_[0];
	$month=$months[$i];
	print "\n$month\n";
	print "Wk  ";
	for ($k=0 ; $k<7; $k++) {
		print "$shortdays[$k] ";
	}
	print "\n";
	printMonth($i);
}

sub getStartMonth {
	local ($year,$month,@tm,$time);

	($year,$month)=@_;
        @tm=(0,0,12,1,$month,$year-1900,0,0);
        $time=mktime(@tm);
	@tm=localtime($time);
	if ($tm[6]==0) {$tm[6]=7;}
	--$tm[6];
}

sub printMonth {
	local ($j);
	$mon=$_[0];
	$startmonth=&getStartMonth($year,$mon);
	if (($startmonth == 0) or ($mon == 0)) {
		if ($week < 10) { print " ";}
		print "$week  ";
		$week++;
	} else {
		print "    ";
	}
	print "   " x $startmonth;
	for ($j=1; $j <= $monthlens[$mon]; $j++) {
		if ($j<10) {
			print " ";
		}
		print "$j ";
		$startmonth++;
		if ($startmonth%7 == 0) {
			print "\n";
			if ($j < $monthlens[$mon]) {
				if ($week < 10) { print " ";}
				print "$week  ";
				$week++;
			}
		}
	}
	if ($startmonth%7 != 0) {print "\n";}
}

