#!/bin/sh
#
#   Supercal script
#   by Russell Lowke   Dec 20th, 2001
#


nthElement()
{
    #
    # get nth element in list
    #

    shift $1
    echo $1
}


lastElement()
{
    #
    # get last element in list
    #
    
    for ITEM in $* ; do
        shift
    done
    echo $ITEM
}


addMonth()
{
    #
    # add a month(s) to MONTHS list
    #
    
    if [ "$PREVITEM" = "-" ] ; then
        # expand "mar - nov"
        STARTAT=`lastElement $MONTHS`

        while [ $THISITEM -gt $STARTAT ] ; do
            STARTAT=`expr $STARTAT + 1`
            MONTHS="$MONTHS $STARTAT"
        done
    else
        MONTHS="$MONTHS $THISITEM"
    fi
}


displayYear()
{
    #
    # Display calander $MONTHS
    #
    
    # check for zero args
    if [ $# = 0 ] && [ "$MONTHS" = "" ] ; then
        YEAR=""
    elif [ $# = 0 ] ; then
        DATE=`date`
        YEAR=`nthElement 6 $DATE`
    else
        YEAR=$1
    fi
    
    case "$YEAR" in
        "") #skip if year is empty 
            ;;
        *)
            # check for empty MONTHS list
            if [ "$MONTHS" = "" ] ; then
                # print entire year
                cal $YEAR
            else
                for THISMONTH in $MONTHS ; do
                    cal $THISMONTH $YEAR
                done
            fi ;;
    esac
    
    # clear months list
    MONTHS=""
}

name2Num()
{
    #
    # name2num: converts a single argument to the corresponding month number
    #

	M=$* ; RETVAL=0
	case $1 in
		jan*|Jan*)    M=1	   ;;
		feb*|Feb*)    M=2	   ;;
		mar*|Mar*)    M=3	   ;;
		apr*|Apr*)    M=4	   ;;
		may*|May*)    M=5	   ;;
		jun*|Jun*)    M=6	   ;;
		jul*|Jul*)    M=7	   ;;
		aug*|Aug*)    M=8	   ;;
		sep*|Sep*)    M=9	   ;;
		oct*|Oct*)    M=10     ;;
		nov*|Nov*)    M=11     ;;
		dec*|Dec*)	  M=12	   ;;
		[1-9]|1[012]) M=$1     ;;    # accept nums, too
		*)		      RETVAL=1 ;;	 # error condition
	esac
	echo $M
	exit $RETVAL
}


    MONTHS=""

    if [ $# = 0 ] ; then
        echo "No parameters"
    else
        
        while [ $# -gt 0 ] ; do
            PREVITEM=$THISITEM
            
            # convert month names to numbers
            THISITEM=`name2Num $1`

            # for values 1 to 12 addMonth,
            # ignore -, otherwise display year.
            case "$THISITEM" in
                [1-9])                addMonth;;
                [0-9][0-2])           addMonth;;
                -) ;;
                *) displayYear $THISITEM;;
            esac
            
            shift
        done
    fi

    # display year once list has finished
    displayYear

    exit 1
