#!/usr/local/bin/kermit +

; c a l e n d a r
;
; Prints a calendar of the given month of the given year, or if no year
; and month given, of the current month. To print a single month, e.g.
; March 2002:
;
;   calendar 2002 3
;
; To print a year (e.g. 2002):
;
;   for \%i 1 12 1 { take calendar 2002 \%i } 
;
; Requires:    C-Kermit 8.0 or later or K95 1.1.21 or later.
; Illustrates: Date arithmetic using Modified Julian Date (MJD).
; Author:      F. da Cruz, Columbia University, March 2002.
;
local mm yyyy yyyymm dayone \&m[] \%a \%d \%e \%i \%s       ; Local variables
dcl \&m[] = Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec ; Month names

; Validate arguments...

define usage {
    if def \%1 echo \%1
    exit 1 Usage: \fbasename(\v(cmdfile)) yyyy mm
}
switch \v(argc) {
  :1, .\%1 := \:(\v(ndate)[1:4]), .\%2 := \:(\v(ndate):[5:2]), break
  :3, break
  :default, usage
}
if not numeric \%1 usage "Year not numeric"
if not numeric \%2 usage "Month not numeric"
if ( < \%1 1859 || > \%1 9999 ) usage "Year out of range (1859-9999)"
if ( < \%2 1 || > \%2 12 ) usage "Month out of range (1-12)"

; Interpret arguments...

.mm     := \flpad(\%2,2,0)                ; 2-digit month
.yyyy   := \%1                            ; 4-digit year
.yyyymm := \m(yyyy)\m(mm)                 ; Month and year
.dayone := \m(yyyymm)01                   ; First day of month

.\%d ::= \fmjd(\m(dayone) +1month) - \fmjd(\m(dayone))  ; Days in month
.\%e :=  \fnday(\m(dayone))               ; Day of week of first day of month
.\%s ::= \fmod((7-\%e),7)                 ; Day of week of Saturday

; Print calendar...

echo                                      ; Heading
echo " \&m[\%2] \%1"
echo "  S  M  T  W  T  F  S"
xecho "\frepeat({   },\%e)"               ; Spacer for first week

for \%i 1 \%d 1 {                         ; Loop for each day of month
  xecho \flpad(\%i,3)                     ; Print the day number
  if == \fmod(\%i,7) \%s echo             ; End of week - start new line
}
if != \fmod(\%i,7) (\%s+1) echo           ; If week ended on Saturday

echo                                      ; Blank line at end
if kerbang exit 0
