]> git.ipfire.org Git - thirdparty/util-linux.git/blobdiff - misc-utils/cal.c
cal: fix julian calendars for large years
[thirdparty/util-linux.git] / misc-utils / cal.c
index bc53d4f8aaa0a5974cfa96e60d4821080a11fb1b..a854eaf9d073382d277bce99ea608746eeb0d064 100644 (file)
@@ -41,7 +41,7 @@
  *
  * 2000-09-01  Michael Charles Pruznick <dummy@netwiz.net>
  *             Added "-3" option to print prev/next month with current.
- *             Added over-ridable default NUM_MONTHS and "-1" option to
+ *             Added overridable default MONTHS_IN_ROW and "-1" option to
  *             get traditional output when -3 is the default.  I hope that
  *             enough people will like -3 as the default that one day the
  *             product can be shipped that way.
@@ -59,6 +59,7 @@
 
 #include <ctype.h>
 #include <getopt.h>
+#include <stdint.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include "nls.h"
 #include "mbsalign.h"
 #include "strutils.h"
+#include "optutils.h"
+#include "timeutils.h"
+
+static int has_term = 0;
+static const char *Senter = "", *Sexit = "";   /* enter and exit standout mode */
 
 #if defined(HAVE_LIBNCURSES) || defined(HAVE_LIBNCURSESW)
-# ifdef HAVE_NCURSES_H
-#  include <ncurses.h>
-# elif defined(HAVE_NCURSES_NCURSES_H)
-#  include <ncurses/ncurses.h>
+# if defined(HAVE_NCURSESW_TERM_H)
+#  include <ncursesw/term.h>
+# elif defined(HAVE_NCURSES_TERM_H)
+#  include <ncurses/term.h>
+# elif defined(HAVE_TERM_H)
+#  include <term.h>
 # endif
-# include <term.h>
-
-static void my_setupterm(const char *term, int fildes, int *errret)
-{
-       setupterm((char *)term, fildes, errret);
-}
-
-static void my_putstring(char *s)
-{
-       putp(s);
-}
+#endif
 
-static const char *my_tgetstr(char *s __attribute__((__unused__)), char *ss)
+static int setup_terminal(char *term
+#if !defined(HAVE_LIBNCURSES) && !defined(HAVE_LIBNCURSESW)
+                       __attribute__((__unused__))
+#endif
+               )
 {
-       const char *ret = tigetstr(ss);
-       if (!ret || ret == (char *)-1)
-               return "";
-
-       return ret;
-}
-
-#elif defined(HAVE_LIBTERMCAP)
-# include <termcap.h>
-
-static char termbuffer[4096];
-static char tcbuffer[4096];
-static char *strbuf = termbuffer;
+#if defined(HAVE_LIBNCURSES) || defined(HAVE_LIBNCURSESW)
+       int ret;
 
-static void my_setupterm(const char *term, int fildes __attribute__((__unused__)), int *errret)
-{
-       *errret = tgetent(tcbuffer, term);
+       if (setupterm(term, STDOUT_FILENO, &ret) != 0 || ret != 1)
+               return -1;
+#endif
+       return 0;
 }
 
 static void my_putstring(char *s)
 {
-       tputs(s, 1, putchar);
+#if defined(HAVE_LIBNCURSES) || defined(HAVE_LIBNCURSESW)
+       if (has_term)
+               putp(s);
+       else
+#endif
+               fputs(s, stdout);
 }
 
-static const char *my_tgetstr(char *s, char *ss __attribute__((__unused__)))
+static const char *my_tgetstr(char *ss
+#if !defined(HAVE_LIBNCURSES) && !defined(HAVE_LIBNCURSESW)
+                       __attribute__((__unused__))
+#endif
+               )
 {
-       const char *ret = tgetstr(s, &strbuf);
-       if (!ret)
-               return "";
+       const char *ret = NULL;
 
+#if defined(HAVE_LIBNCURSES) || defined(HAVE_LIBNCURSESW)
+       if (has_term)
+               ret = tigetstr(ss);
+#endif
+       if (!ret || ret == (char *)-1)
+               return "";
        return ret;
 }
 
-#else  /* ! (HAVE_LIBTERMCAP || HAVE_LIBNCURSES || HAVE_LIBNCURSESW) */
-
-static void my_putstring(char *s)
-{
-       fputs(s, stdout);
-}
-
-#endif /* end of LIBTERMCAP / NCURSES */
-
-#if defined(HAVE_LIBNCURSES) || defined(HAVE_LIBNCURSESW) || defined(HAVE_LIBTERMCAP)
-static const char      *term="";
-static int             Slen;           /* strlen of Senter+Sexit */
-#endif
-
-static const char      *Senter="", *Sexit="";/* enter and exit standout mode */
-static char            *Hrow;          /* pointer to highlighted row in month */
-
 #include "widechar.h"
 
-/* allow compile-time define to over-ride default */
-#ifndef NUM_MONTHS
-# define NUM_MONTHS 1
-#endif
-
-#if ( NUM_MONTHS != 1 && NUM_MONTHS !=3 )
-# error NUM_MONTHS must be 1 or 3
-#endif
+enum {
+       GREGORIAN               = INT32_MIN,
+       ISO                     = INT32_MIN,
+       GB1752                  = 1752,
+       DEFAULT_REFORM_YEAR     = 1752,
+       JULIAN                  = INT32_MAX
+};
 
 enum {
        SUNDAY = 0,
@@ -166,15 +153,26 @@ enum {
        NONEDAY
 };
 
-#define        FIRST_WEEKDAY           SATURDAY        /* Jan 1st, 1 was a Saturday */
-#define REFORMATION_YEAR       1752            /* Signed-off-by: Lord Chesterfield */
-#define REFORMATION_MONTH      9               /* September */
-#define        FIRST_MISSING_DAY       639799          /* 3 Sep 1752 */
+enum {
+       JANUARY = 1,
+       FEBRUARY,
+       MARCH,
+       APRIL,
+       MAY,
+       JUNE,
+       JULY,
+       AUGUST,
+       SEPTEMBER,
+       OCTOBER,
+       NOVEMBER,
+       DECEMBER
+};
+
+#define REFORMATION_MONTH      SEPTEMBER
 #define        NUMBER_MISSING_DAYS     11              /* 11 day correction */
 #define YDAY_AFTER_MISSING     258             /* 14th in Sep 1752 */
 
-#define DAYS_IN_YEAR           365             /* the common case, leap years are calculated */
-#define MONTHS_IN_YEAR         12
+#define MONTHS_IN_YEAR         DECEMBER
 #define DAYS_IN_MONTH          31
 #define        MAXDAYS                 42              /* slots in a month array */
 #define        SPACE                   -1              /* used in day array */
@@ -183,43 +181,16 @@ enum {
 
 #define        DAY_LEN                 3               /* 3 spaces per day */
 #define        WEEK_LEN                (DAYS_IN_WEEK * DAY_LEN)
-#define        HEAD_SEP                2
-#define MONTH_COLS             3               /* month columns in year view */
+#define MONTHS_IN_YEAR_ROW     3               /* month columns in year view */
 #define WNUM_LEN                3
 
-#define TODAY_FLAG             0x400           /* flag day for highlighting */
-
-#define FMT_ST_LINES 9
 #define FMT_ST_CHARS 300       /* 90 suffices in most locales */
-struct fmt_st
-{
-       char s[FMT_ST_LINES][FMT_ST_CHARS];
-};
 
 static const int days_in_month[2][13] = {
        {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
        {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
 };
 
-/* September 1752 is special, and has static assignments for both date
- * and Julian representations.  */
-static const int d_sep1752[MAXDAYS / 2] = {
-       SPACE,  SPACE,  1,      2,      14,     15,     16,
-       17,     18,     19,     20,     21,     22,     23,
-       24,     25,     26,     27,     28,     29,     30
-}, j_sep1752[MAXDAYS / 2] = {
-       SPACE,  SPACE,  245,    246,    258,    259,    260,
-       261,    262,    263,    264,    265,    266,    267,
-       268,    269,    270,    271,    272,    273,    274
-}, empty[MAXDAYS] = {
-       SPACE,  SPACE,  SPACE,  SPACE,  SPACE,  SPACE,  SPACE,
-       SPACE,  SPACE,  SPACE,  SPACE,  SPACE,  SPACE,  SPACE,
-       SPACE,  SPACE,  SPACE,  SPACE,  SPACE,  SPACE,  SPACE,
-       SPACE,  SPACE,  SPACE,  SPACE,  SPACE,  SPACE,  SPACE,
-       SPACE,  SPACE,  SPACE,  SPACE,  SPACE,  SPACE,  SPACE,
-       SPACE,  SPACE,  SPACE,  SPACE,  SPACE,  SPACE,  SPACE
-};
-
 enum {
        WEEK_NUM_DISABLED = 0,
        WEEK_NUM_MASK=0xff,
@@ -230,57 +201,86 @@ enum {
 /* utf-8 can have up to 6 bytes per char; and an extra byte for ending \0 */
 static char day_headings[(WEEK_LEN + 1) * 6 + 1];
 
+struct cal_request {
+       int day;
+       int month;
+       int32_t year;
+       int week;
+       int start_month;
+};
+
 struct cal_control {
        const char *full_month[MONTHS_IN_YEAR]; /* month names */
+       const char *abbr_month[MONTHS_IN_YEAR]; /* abbreviated month names */
+
+       int reform_year;                /* Gregorian reform year */
        int colormode;                  /* day and week number highlight */
-       int num_months;                 /* number of months horizontally in print out */
+       int num_months;                 /* number of requested months */
+       int span_months;                /* span the date */
+       int months_in_row;              /* number of months horizontally in print out */
        int weekstart;                  /* day the week starts, often Sun or Mon */
        int weektype;                   /* WEEK_TYPE_{NONE,ISO,US} */
-       int weeknum;                    /* requested --week=<number> */
        size_t day_width;               /* day width in characters in printout */
        size_t week_width;              /* 7 * day_width + possible week num */
+       int gutter_width;               /* spaces in between horizontal month outputs */
+       struct cal_request req;         /* the times user is interested */
        unsigned int    julian:1,       /* julian output */
-                       yflag:1;        /* print whole year */
+                       header_year:1,  /* print year number */
+                       header_hint:1;  /* does month name + year need two lines to fit */
+};
+
+struct cal_month {
+       int days[MAXDAYS];              /* the day numbers, or SPACE */
+       int weeks[MAXDAYS / DAYS_IN_WEEK];
+       int month;
+       int32_t year;
+       struct cal_month *next;
 };
 
 /* function prototypes */
-static int leap_year(long year);
+static int leap_year(const struct cal_control *ctl, int32_t year);
+static int monthname_to_number(struct cal_control *ctl, const char *name);
 static void headers_init(struct cal_control *ctl);
-static int do_monthly(int day, int month, long year, struct fmt_st *out, int header_hint,
-                     const struct cal_control *ctl);
-static void monthly(int day, int month, long year, const struct cal_control *ctl);
-static int two_header_lines(int month, long year, const struct cal_control *ctl);
-static void monthly3(int day, int month, long year, const struct cal_control *ctl);
-static char *append_weeknum(char *p, int *dp, int month, long year, int cal, int row,
-                           const struct cal_control *ctl);
-static void yearly(int day, long year, const struct cal_control *ctl);
-static void day_array(int day, int month, long year, int *days, const struct cal_control *ctl);
-static int day_in_year(int day, int month, long year);
-static int day_in_week(int day, int month, long year);
-static int week_number(int day, int month, long year, const struct cal_control *ctl);
-static int week_to_day(long year, const struct cal_control *ctl);
-static char *ascii_day(char *p, int day, const struct cal_control *ctl);
-static char *ascii_weeknum(char *p, int weeknum, const struct cal_control *ctl);
+static void cal_fill_month(struct cal_month *month, const struct cal_control *ctl);
+static void cal_output_header(struct cal_month *month, const struct cal_control *ctl);
+static void cal_output_months(struct cal_month *month, const struct cal_control *ctl);
+static void monthly(const struct cal_control *ctl);
+static void yearly(const struct cal_control *ctl);
+static int day_in_year(const struct cal_control *ctl, int day,
+                      int month, int32_t year);
+static int day_in_week(const struct cal_control *ctl, int day,
+                      int month, int32_t year);
+static int week_number(int day, int month, int32_t year, const struct cal_control *ctl);
+static int week_to_day(const struct cal_control *ctl);
 static int center_str(const char *src, char *dest, size_t dest_size, size_t width);
 static void center(const char *str, size_t len, int separate);
-static void __attribute__((__noreturn__)) usage(FILE *out);
+static int parse_reform_year(const char *reform_year);
+static void __attribute__((__noreturn__)) usage(void);
 
 int main(int argc, char **argv)
 {
        struct tm *local_time;
+       char *term;
        time_t now;
-       int ch, day = 0, month = 0;
-       long year;
+       int ch = 0, yflag = 0, Yflag = 0;
+
        static struct cal_control ctl = {
+               .reform_year = DEFAULT_REFORM_YEAR,
                .weekstart = SUNDAY,
-               .num_months = NUM_MONTHS,
-               .colormode = UL_COLORMODE_AUTO,
+               .num_months = 1,                /* default is "cal -1" */
+               .span_months = 0,
+               .colormode = UL_COLORMODE_UNDEF,
                .weektype = WEEK_NUM_DISABLED,
-               .day_width = DAY_LEN
+               .day_width = DAY_LEN,
+               .gutter_width = 2,
+               .req.day = 0,
+               .req.month = 0
        };
 
        enum {
-               OPT_COLOR = CHAR_MAX + 1
+               OPT_COLOR = CHAR_MAX + 1,
+               OPT_ISO,
+               OPT_REFORM
        };
 
        static const struct option longopts[] = {
@@ -289,30 +289,38 @@ int main(int argc, char **argv)
                {"sunday", no_argument, NULL, 's'},
                {"monday", no_argument, NULL, 'm'},
                {"julian", no_argument, NULL, 'j'},
+               {"months", required_argument, NULL, 'n'},
+               {"span", no_argument, NULL, 'S'},
                {"year", no_argument, NULL, 'y'},
                {"week", optional_argument, NULL, 'w'},
                {"color", optional_argument, NULL, OPT_COLOR},
+               {"reform", required_argument, NULL, OPT_REFORM},
+               {"iso", no_argument, NULL, OPT_ISO},
                {"version", no_argument, NULL, 'V'},
+               {"twelve", no_argument, NULL, 'Y'},
                {"help", no_argument, NULL, 'h'},
                {NULL, 0, NULL, 0}
        };
 
+       static const ul_excl_t excl[] = {       /* rows and cols in ASCII order */
+               { 'Y','n','y' },
+               { 0 }
+       };
+       int excl_st[ARRAY_SIZE(excl)] = UL_EXCL_STATUS_INIT;
+
        setlocale(LC_ALL, "");
        bindtextdomain(PACKAGE, LOCALEDIR);
        textdomain(PACKAGE);
        atexit(close_stdout);
 
-#if defined(HAVE_LIBNCURSES) || defined(HAVE_LIBNCURSESW) || defined(HAVE_LIBTERMCAP)
-       if ((term = getenv("TERM"))) {
-               int ret;
-               my_setupterm(term, STDOUT_FILENO, &ret);
-               if (ret > 0) {
-                       Senter = my_tgetstr("so","smso");
-                       Sexit = my_tgetstr("se","rmso");
-                       Slen = strlen(Senter) + strlen(Sexit);
+       term = getenv("TERM");
+       if (term) {
+               has_term = setup_terminal(term) == 0;
+               if (has_term) {
+                       Senter = my_tgetstr("smso");
+                       Sexit = my_tgetstr("rmso");
                }
        }
-#endif
 
 /*
  * The traditional Unix cal utility starts the week at Sunday,
@@ -344,18 +352,23 @@ int main(int argc, char **argv)
                val.string = nl_langinfo(_NL_TIME_WEEK_1STDAY);
 
                wfd = val.word;
-               wfd = day_in_week(wfd % 100, (wfd / 100) % 100, wfd / (100 * 100));
+               wfd = day_in_week(&ctl, wfd % 100, (wfd / 100) % 100,
+                                 wfd / (100 * 100));
                ctl.weekstart = (wfd + *nl_langinfo(_NL_TIME_FIRST_WEEKDAY) - 1) % DAYS_IN_WEEK;
        }
 #endif
+       while ((ch = getopt_long(argc, argv, "13mjn:sSywYVh", longopts, NULL)) != -1) {
+
+               err_exclusive_options(ch, longopts, excl, excl_st);
 
-       while ((ch = getopt_long(argc, argv, "13mjsywVh", longopts, NULL)) != -1)
                switch(ch) {
                case '1':
-                       ctl.num_months = 1;             /* default */
+                       /* default */
                        break;
                case '3':
                        ctl.num_months = 3;
+                       ctl.span_months = 1;
+                       ctl.months_in_row = 3;
                        break;
                case 's':
                        ctl.weekstart = SUNDAY;         /* default */
@@ -368,140 +381,243 @@ int main(int argc, char **argv)
                        ctl.day_width = DAY_LEN + 1;
                        break;
                case 'y':
-                       ctl.yflag = 1;
+                       yflag = 1;
+                       break;
+               case 'Y':
+                       Yflag = 1;
+                       break;
+               case 'n':
+                       ctl.num_months = strtou32_or_err(optarg,
+                                               _("invalid month argument"));
+                       break;
+               case 'S':
+                       ctl.span_months = 1;
                        break;
                case 'w':
                        if (optarg) {
-                               ctl.weeknum = strtos32_or_err(optarg,
+                               ctl.req.week = strtos32_or_err(optarg,
                                                _("invalid week argument"));
-                               if (ctl.weeknum < 1 || 53 < ctl.weeknum)
-                                       errx(EXIT_FAILURE,_("illegal week value: use 1-53"));
+                               if (ctl.req.week < 1 || 54 < ctl.req.week)
+                                       errx(EXIT_FAILURE,_("illegal week value: use 1-54"));
                        }
                        ctl.weektype = WEEK_NUM_US;     /* default per weekstart */
                        break;
                case OPT_COLOR:
+                       ctl.colormode = UL_COLORMODE_AUTO;
                        if (optarg)
                                ctl.colormode = colormode_or_err(optarg,
                                                _("unsupported color mode"));
                        break;
+               case OPT_REFORM:
+                       ctl.reform_year = parse_reform_year(optarg);
+                       break;
+               case OPT_ISO:
+                       ctl.reform_year = ISO;
+                       break;
                case 'V':
                        printf(UTIL_LINUX_VERSION);
                        return EXIT_SUCCESS;
                case 'h':
-                       usage(stdout);
-               case '?':
+                       usage();
                default:
-                       usage(stderr);
+                       errtryhelp(EXIT_FAILURE);
                }
+       }
+
        argc -= optind;
        argv += optind;
 
        if (ctl.weektype) {
-               ctl.weektype = ctl.weeknum & WEEK_NUM_MASK;
+               ctl.weektype = ctl.req.week & WEEK_NUM_MASK;
                ctl.weektype |= (ctl.weekstart == MONDAY ? WEEK_NUM_ISO : WEEK_NUM_US);
                ctl.week_width = (ctl.day_width * DAYS_IN_WEEK) + WNUM_LEN;
        } else
                ctl.week_width = ctl.day_width * DAYS_IN_WEEK;
 
-       time(&now);
+       if (argc == 1 && !isdigit_string(*argv)) {
+               usec_t x;
+               /* cal <timestamp> */
+               if (parse_timestamp(*argv, &x) == 0)
+                       now = (time_t) (x / 1000000);
+               /* cal <monthname> */
+               else if ((ctl.req.month = monthname_to_number(&ctl, *argv)) > 0)
+                       time(&now);     /* this year */
+               else
+                       errx(EXIT_FAILURE, _("failed to parse timestamp or unknown month name: %s"), *argv);
+               argc = 0;
+       } else
+               time(&now);
+
        local_time = localtime(&now);
 
        switch(argc) {
        case 3:
-               day = strtos32_or_err(*argv++, _("illegal day value"));
-               if (day < 1 || DAYS_IN_MONTH < day)
+               ctl.req.day = strtos32_or_err(*argv++, _("illegal day value"));
+               if (ctl.req.day < 1 || DAYS_IN_MONTH < ctl.req.day)
                        errx(EXIT_FAILURE, _("illegal day value: use 1-%d"), DAYS_IN_MONTH);
-               /* FALLTHROUGH */
+               /* fallthrough */
        case 2:
-               month = strtos32_or_err(*argv++, _("illegal month value: use 1-12"));
-               if (month < 1 || MONTHS_IN_YEAR < month)
+               if (isdigit(**argv))
+                       ctl.req.month = strtos32_or_err(*argv++, _("illegal month value: use 1-12"));
+               else {
+                       ctl.req.month = monthname_to_number(&ctl, *argv);
+                       if (ctl.req.month < 0)
+                               errx(EXIT_FAILURE, _("unknown month name: %s"), *argv);
+                       argv++;
+               }
+               if (ctl.req.month < 1 || MONTHS_IN_YEAR < ctl.req.month)
                        errx(EXIT_FAILURE, _("illegal month value: use 1-12"));
-               /* FALLTHROUGH */
+               /* fallthrough */
        case 1:
-               year = strtol_or_err(*argv++, _("illegal year value"));
-               if (year < SMALLEST_YEAR)
+               ctl.req.year = strtos32_or_err(*argv++, _("illegal year value"));
+               if (ctl.req.year < SMALLEST_YEAR)
                        errx(EXIT_FAILURE, _("illegal year value: use positive integer"));
-               if (day) {
-                       int dm = days_in_month[leap_year(year)][month];
-                       if (day > dm)
+               if (ctl.req.year == JULIAN)
+                       errx(EXIT_FAILURE, _("illegal year value"));
+               if (ctl.req.day) {
+                       int dm = days_in_month[leap_year(&ctl, ctl.req.year)]
+                                             [ctl.req.month];
+                       if (ctl.req.day > dm)
                                errx(EXIT_FAILURE, _("illegal day value: use 1-%d"), dm);
-                       day = day_in_year(day, month, year);
-               } else if ((long) (local_time->tm_year + 1900) == year) {
-                       day = local_time->tm_yday + 1;
+                       ctl.req.day = day_in_year(&ctl, ctl.req.day,
+                                                 ctl.req.month, ctl.req.year);
+               } else if ((int32_t) (local_time->tm_year + 1900) == ctl.req.year) {
+                       ctl.req.day = local_time->tm_yday + 1;
+               }
+               if (!ctl.req.month && !ctl.req.week) {
+                       ctl.req.month = local_time->tm_mon + 1;
+                       yflag = 1;
                }
-               if (!month && !ctl.weeknum)
-                       ctl.yflag = 1;
                break;
        case 0:
-               day = local_time->tm_yday + 1;
-               year = local_time->tm_year + 1900;
-               month = local_time->tm_mon + 1;
+               ctl.req.day = local_time->tm_yday + 1;
+               ctl.req.year = local_time->tm_year + 1900;
+               if (!ctl.req.month)
+                       ctl.req.month = local_time->tm_mon + 1;
                break;
        default:
-               usage(stderr);
+               warnx(_("bad usage"));
+               errtryhelp(EXIT_FAILURE);
        }
 
-       if (0 < ctl.weeknum) {
-               int yday = week_to_day(year, &ctl);
-               int leap = leap_year(year);
+       if (0 < ctl.req.week) {
+               int yday = week_to_day(&ctl);
+               int leap = leap_year(&ctl, ctl.req.year);
+               int m = 1;
 
                if (yday < 1)
-                       errx(EXIT_FAILURE, _("illegal week value: year %ld "
+                       errx(EXIT_FAILURE, _("illegal week value: year %d "
                                             "doesn't have week %d"),
-                                       year, ctl.weeknum);
-               month = 1;
-               while (month <= 12 && yday > days_in_month[leap][month])
-                       yday -= days_in_month[leap][month++];
-               if (month > 12) {
+                                       ctl.req.year, ctl.req.week);
+               while (m <= DECEMBER && yday > days_in_month[leap][m])
+                       yday -= days_in_month[leap][m++];
+               if (DECEMBER < m && ctl.weektype & WEEK_NUM_ISO) {
                        /* In some years (e.g. 2010 in ISO mode) it's possible
                         * to have a remnant of week 53 starting the year yet
                         * the year in question ends during 52, in this case
                         * we're assuming that early remnant is being referred
                         * to if 53 is given as argument. */
-                       if (ctl.weeknum == week_number(31, 12, year - 1, &ctl))
-                               month = 1;
-                       else
+                       if (ctl.req.week != week_number(31, DECEMBER, ctl.req.year - 1, &ctl))
                                errx(EXIT_FAILURE,
-                                       _("illegal week value: year %ld "
+                                       _("illegal week value: year %d "
                                          "doesn't have week %d"),
-                                       year, ctl.weeknum);
+                                       ctl.req.year, ctl.req.week);
                }
+               if (!ctl.req.month)
+                       ctl.req.month = MONTHS_IN_YEAR < m ? 1 : m;
        }
 
        headers_init(&ctl);
 
-       if (!colors_init(ctl.colormode)) {
-               day = 0;
+       if (!colors_init(ctl.colormode, "cal")) {
+               ctl.req.day = 0;
                ctl.weektype &= ~WEEK_NUM_MASK;
        }
 
-       if (ctl.yflag) {
-               if (ctl.julian)
-                       ctl.num_months = MONTH_COLS - 1;
-               else
-                       ctl.num_months = MONTH_COLS;
-               yearly(day, year, &ctl);
-       } else if (ctl.num_months == 1)
-               monthly(day, month, year, &ctl);
-       else if (ctl.num_months == 3)
-               monthly3(day, month, year, &ctl);
+       if (yflag || Yflag) {
+               ctl.gutter_width = 3;
+               ctl.num_months = MONTHS_IN_YEAR;
+               if (yflag) {
+                       ctl.req.start_month = 1;        /* start from Jan */
+                       ctl.header_year = 1;            /* print year number */
+               }
+       }
+
+       if (ctl.num_months > 1 && ctl.months_in_row == 0)
+               ctl.months_in_row = ctl.julian ? MONTHS_IN_YEAR_ROW - 1 :
+                                                MONTHS_IN_YEAR_ROW;
+       else if (!ctl.months_in_row)
+               ctl.months_in_row = 1;
+
+       if (yflag || Yflag)
+               yearly(&ctl);
+       else
+               monthly(&ctl);
 
        return EXIT_SUCCESS;
 }
 
 /* leap year -- account for gregorian reformation in 1752 */
-static int leap_year(long year)
+static int leap_year(const struct cal_control *ctl, int32_t year)
 {
-       if (year <= REFORMATION_YEAR)
+       if (year <= ctl->reform_year)
                return !(year % 4);
        else
                return ( !(year % 4) && (year % 100) ) || !(year % 400);
 }
 
+static void init_monthnames(struct cal_control *ctl)
+{
+       size_t i;
+
+       if (ctl->full_month[0] != NULL)
+               return;         /* already initialized */
+
+       for (i = 0; i < MONTHS_IN_YEAR; i++)
+               ctl->full_month[i] = nl_langinfo(MON_1 + i);
+}
+
+static void init_abbr_monthnames(struct cal_control *ctl)
+{
+       size_t i;
+
+       if (ctl->abbr_month[0] != NULL)
+               return;         /* already initialized */
+
+       for (i = 0; i < MONTHS_IN_YEAR; i++)
+               ctl->abbr_month[i] = nl_langinfo(ABMON_1 + i);
+}
+
+static int monthname_to_number(struct cal_control *ctl, const char *name)
+{
+       size_t i;
+
+       init_monthnames(ctl);
+       for (i = 0; i < MONTHS_IN_YEAR; i++)
+               if (strcasecmp(ctl->full_month[i], name) == 0)
+                       return i + 1;
+
+       init_abbr_monthnames(ctl);
+       for (i = 0; i < MONTHS_IN_YEAR; i++)
+               if (strcasecmp(ctl->abbr_month[i], name) == 0)
+                       return i + 1;
+
+       return -EINVAL;
+}
+
 static void headers_init(struct cal_control *ctl)
 {
        size_t i, wd;
        char *cur_dh = day_headings;
+       char tmp[FMT_ST_CHARS];
+       int year_len;
+
+       year_len = snprintf(tmp, sizeof(tmp), "%04d", ctl->req.year);
+
+       if (year_len < 0 || (size_t)year_len >= sizeof(tmp)) {
+               /* XXX impossible error */
+               return;
+       }
 
        for (i = 0; i < DAYS_IN_WEEK; i++) {
                size_t space_left;
@@ -517,288 +633,254 @@ static void headers_init(struct cal_control *ctl)
                                     space_left, ctl->day_width - 1);
        }
 
-       for (i = 0; i < MONTHS_IN_YEAR; i++)
-               ctl->full_month[i] = nl_langinfo(MON_1 + i);
+       init_monthnames(ctl);
+
+       for (i = 0; i < MONTHS_IN_YEAR; i++) {
+               /* The +1 after year_len is space in between month and year. */
+               if (ctl->week_width < strlen(ctl->full_month[i]) + year_len + 1)
+                       ctl->header_hint = 1;
+       }
 }
 
-static int do_monthly(int day, int month, long year, struct fmt_st *out,
-                     int header_hint, const struct cal_control *ctl)
+static void cal_fill_month(struct cal_month *month, const struct cal_control *ctl)
 {
-       int col, row, days[MAXDAYS];
-       char *p, lineout[FMT_ST_CHARS];
-       int pos = 0;
-
-       day_array(day, month, year, days, ctl);
-
-       if (header_hint < 0)
-               header_hint = two_header_lines(month, year, ctl);
-       if (header_hint) {
-               snprintf(lineout, sizeof(lineout), _("%s"), ctl->full_month[month - 1]);
-               center_str(lineout, out->s[pos], ARRAY_SIZE(out->s[pos]), ctl->week_width - 1);
-               pos++;
-               snprintf(lineout, sizeof(lineout), _("%ld"), year);
-               center_str(lineout, out->s[pos], ARRAY_SIZE(out->s[pos]), ctl->week_width - 1);
-               pos++;
-       } else {
-               /* TRANSLATORS: %s is the month name, %ld the year number.
-                * You can change the order and/or add something here;
-                * e.g. for Basque the translation should be "%2$ldko %1$s".
-                */
-               snprintf(lineout, sizeof(lineout), _("%s %ld"),
-                       ctl->full_month[month - 1], year);
-               center_str(lineout, out->s[pos], ARRAY_SIZE(out->s[pos]), ctl->week_width - 1);
-               pos++;
+       int first_week_day = day_in_week(ctl, 1, month->month, month->year);
+       int month_days;
+       int i, j, weeklines = 0;
+
+       if (ctl->julian)
+               j = day_in_year(ctl, 1, month->month, month->year);
+       else
+               j = 1;
+       month_days = j + days_in_month[leap_year(ctl, month->year)][month->month];
+
+       /* True when Sunday is not first day in the output week. */
+       if (ctl->weekstart) {
+               first_week_day -= ctl->weekstart;
+               if (first_week_day < 0)
+                       first_week_day = DAYS_IN_WEEK - ctl->weekstart;
+               month_days += ctl->weekstart - 1;
        }
 
-       snprintf(out->s[pos++], FMT_ST_CHARS, "%s%s",
-                               (ctl->weektype ? "   " : ""),
-                               day_headings);
-
-       for (row = 0; row < DAYS_IN_WEEK - 1; row++) {
-               int has_hl = 0;
-               p = lineout;
-               if (ctl->weektype)
-                       for (col = 0; col < DAYS_IN_WEEK; col++) {
-                               int xd = days[row * DAYS_IN_WEEK + col];
-                               if (xd != SPACE) {
-                                       int wn = week_number(xd & ~TODAY_FLAG,
-                                                       month, year, ctl);
-                                       p = ascii_weeknum(p, wn, ctl);
-                                       break;
-                               } else if (col+1 == DAYS_IN_WEEK)
-                                       p += sprintf(p,"   ");
-                       }
-               for (col = 0; col < DAYS_IN_WEEK; col++) {
-                       int xd = days[row * DAYS_IN_WEEK + col];
-                       if (xd != SPACE && (xd & TODAY_FLAG))
-                               has_hl = 1;
-                       p = ascii_day(p, xd, ctl);
+       /* Fill day array. */
+       for (i = 0; i < MAXDAYS; i++) {
+               if (0 < first_week_day) {
+                       month->days[i] = SPACE;
+                       first_week_day--;
+                       continue;
+               }
+               if (j < month_days) {
+                       if (month->year == ctl->reform_year &&
+                           month->month == REFORMATION_MONTH &&
+                           (j == 3 || j == 247))
+                               j += NUMBER_MISSING_DAYS;
+                       month->days[i] = j;
+                       j++;
+                       continue;
                }
-               *p = '\0';
-               snprintf(out->s[row+pos], FMT_ST_CHARS, "%s", lineout);
-               if (has_hl)
-                       Hrow = out->s[row+pos];
+               month->days[i] = SPACE;
+               weeklines++;
        }
-       pos += row;
-       return pos;
-}
-
-static void monthly(int day, int month, long year, const struct cal_control *ctl)
-{
-       int i, rows;
-       struct fmt_st out;
 
-       rows = do_monthly(day, month, year, &out, -1, ctl);
-       for (i = 0; i < rows; i++) {
-               my_putstring(out.s[i]);
-               my_putstring("\n");
+       /* Add week numbers */
+       if (ctl->weektype) {
+               int weeknum = week_number(1, month->month, month->year, ctl);
+               weeklines = MAXDAYS / DAYS_IN_WEEK - weeklines / DAYS_IN_WEEK;
+               for (i = 0; i < MAXDAYS / DAYS_IN_WEEK; i++) {
+                       if (0 < weeklines) {
+                               if (52 < weeknum)
+                                       weeknum = week_number(month->days[i * DAYS_IN_WEEK], month->month, month->year, ctl);
+                               month->weeks[i] = weeknum++;
+                       } else
+                               month->weeks[i] = SPACE;
+                       weeklines--;
+               }
        }
 }
 
-static int two_header_lines(int month, long year, const struct cal_control *ctl)
+static void cal_output_header(struct cal_month *month, const struct cal_control *ctl)
 {
-       char lineout[FMT_ST_CHARS];
-       size_t len;
-       snprintf(lineout, sizeof(lineout), "%ld", year);
-       len = strlen(lineout);
-       len += strlen(ctl->full_month[month - 1]) + 1;
-       if (ctl->week_width - 1 < len)
-               return 1;
-       return 0;
-}
+       char out[FMT_ST_CHARS];
+       struct cal_month *i;
 
-static void monthly3(int day, int month, long year, const struct cal_control *ctl)
-{
-       char lineout[FMT_ST_CHARS];
-       int i;
-       int rows, two_lines;
-       struct fmt_st out_prev;
-       struct fmt_st out_curm;
-       struct fmt_st out_next;
-       int prev_month, next_month;
-       long prev_year, next_year;
-
-       memset(&out_prev, 0, sizeof(struct fmt_st));
-       memset(&out_curm, 0, sizeof(struct fmt_st));
-       memset(&out_next, 0, sizeof(struct fmt_st));
-       if (month == 1) {
-               prev_month = MONTHS_IN_YEAR;
-               prev_year  = year - 1;
-       } else {
-               prev_month = month - 1;
-               prev_year  = year;
-       }
-       if (month == MONTHS_IN_YEAR) {
-               next_month = 1;
-               next_year  = year + 1;
+       if (ctl->header_hint || ctl->header_year) {
+               for (i = month; i; i = i->next) {
+                       sprintf(out, _("%s"), ctl->full_month[i->month - 1]);
+                       center(out, ctl->week_width - 1, i->next == NULL ? 0 : ctl->gutter_width);
+               }
+               if (!ctl->header_year) {
+                       my_putstring("\n");
+                       for (i = month; i; i = i->next) {
+                               sprintf(out, _("%04d"), i->year);
+                               center(out, ctl->week_width - 1, i->next == NULL ? 0 : ctl->gutter_width);
+                       }
+               }
        } else {
-               next_month = month + 1;
-               next_year  = year;
-       }
-       two_lines = two_header_lines(prev_month, prev_year, ctl);
-       two_lines += two_header_lines(month, year, ctl);
-       two_lines += two_header_lines(next_month, next_year, ctl);
-       if (0 < two_lines)
-               rows = FMT_ST_LINES;
-       else
-               rows = FMT_ST_LINES - 1;
-       do_monthly(day, prev_month, prev_year, &out_prev, two_lines, ctl);
-       do_monthly(day, month,      year,      &out_curm, two_lines, ctl);
-       do_monthly(day, next_month, next_year, &out_next, two_lines, ctl);
-
-       for (i = 0; i < (two_lines ? 3 : 2); i++) {
-               snprintf(lineout, sizeof(lineout),
-                       "%s  %s  %s\n", out_prev.s[i], out_curm.s[i], out_next.s[i]);
-               my_putstring(lineout);
+               for (i = month; i; i = i->next) {
+                       sprintf(out, _("%s %04d"), ctl->full_month[i->month - 1], i->year);
+                       center(out, ctl->week_width - 1, i->next == NULL ? 0 : ctl->gutter_width);
+               }
        }
-       for (i = two_lines ? 3 : 2; i < rows; i++) {
-               int w1, w2, w3;
-               w1 = w2 = w3 = ctl->week_width;
-
-#if defined(HAVE_LIBNCURSES) || defined(HAVE_LIBNCURSESW) || defined(HAVE_LIBTERMCAP)
-               /* adjust width to allow for non printable characters */
-               w1 += (out_prev.s[i] == Hrow ? Slen : 0);
-               w2 += (out_curm.s[i] == Hrow ? Slen : 0);
-               w3 += (out_next.s[i] == Hrow ? Slen : 0);
-#endif
-               snprintf(lineout, sizeof(lineout), "%-*s %-*s %-*s\n",
-                      w1, out_prev.s[i],
-                      w2, out_curm.s[i],
-                      w3, out_next.s[i]);
-
-               my_putstring(lineout);
+       my_putstring("\n");
+       for (i = month; i; i = i->next) {
+               if (ctl->weektype) {
+                       if (ctl->julian)
+                               sprintf(out, "%*s%s", (int)ctl->day_width - 1, "", day_headings);
+                       else
+                               sprintf(out, "%*s%s", (int)ctl->day_width, "", day_headings);
+                       my_putstring(out);
+               } else
+                       my_putstring(day_headings);
+               if (i->next != NULL) {
+                       sprintf(out, "%*s", ctl->gutter_width, "");
+                       my_putstring(out);
+               }
        }
+       my_putstring("\n");
 }
 
-static char *append_weeknum(char *p, int *dp,
-                        int month, long year, int cal,
-                        int row, const struct cal_control *ctl)
+static void cal_output_months(struct cal_month *month, const struct cal_control *ctl)
 {
-       int col;
-
-       for (col = 0; col < DAYS_IN_WEEK; col++) {
-               int xd = dp[row * DAYS_IN_WEEK + col];
+       char out[FMT_ST_CHARS];
+       int reqday, week_line, d;
+       int skip;
+       struct cal_month *i;
+
+       for (week_line = 0; week_line < MAXDAYS / DAYS_IN_WEEK; week_line++) {
+               for (i = month; i; i = i->next) {
+                       /* Determine the day that should be highlighted. */
+                       reqday = 0;
+                       if (i->month == ctl->req.month && i->year == ctl->req.year) {
+                               if (ctl->julian)
+                                       reqday = ctl->req.day;
+                               else
+                                       reqday = ctl->req.day + 1 -
+                                                day_in_year(ctl, 1, i->month,
+                                                            i->year);
+                       }
 
-               if (xd != SPACE) {
-                       int weeknum = week_number(xd & ~TODAY_FLAG,
-                                              month + cal + 1, year, ctl);
-                       p = ascii_weeknum(p, weeknum, ctl);
-                       break;
-               } else if (col+1 == DAYS_IN_WEEK)
-                       p += sprintf(p,"   ");
+                       if (ctl->weektype) {
+                               if (0 < i->weeks[week_line]) {
+                                       if ((ctl->weektype & WEEK_NUM_MASK) ==
+                                           i->weeks[week_line])
+                                               sprintf(out, "%s%2d%s", Senter, i->weeks[week_line],
+                                                      Sexit);
+                                       else
+                                               sprintf(out, "%2d", i->weeks[week_line]);
+                               } else
+                                       sprintf(out, "%2s", "");
+                               my_putstring(out);
+                               skip = ctl->day_width;
+                       } else
+                               /* First day of the week is one char narrower than the other days,
+                                * unless week number is printed.  */
+                               skip = ctl->day_width - 1;
+
+                       for (d = DAYS_IN_WEEK * week_line;
+                            d < DAYS_IN_WEEK * week_line + DAYS_IN_WEEK; d++) {
+                               if (0 < i->days[d]) {
+                                       if (reqday == i->days[d])
+                                               sprintf(out, "%*s%s%*d%s", skip - (ctl->julian ? 3 : 2),
+                                                      "", Senter, (ctl->julian ? 3 : 2),
+                                                      i->days[d], Sexit);
+                                       else
+                                               sprintf(out, "%*d", skip, i->days[d]);
+                               } else
+                                       sprintf(out, "%*s", skip, "");
+                               my_putstring(out);
+                               if (skip < (int)ctl->day_width)
+                                       skip++;
+                       }
+                       if (i->next != NULL) {
+                               sprintf(out, "%*s", ctl->gutter_width, "");
+                               my_putstring(out);
+                       }
+               }
+               if (i == NULL) {
+                       int extra = ctl->num_months > 3 ? 0 : 1;
+                       sprintf(out, "%*s\n", ctl->gutter_width - extra, "");
+                       my_putstring(out);
+               }
        }
-       return p;
 }
 
-static void yearly(int day, long year, const struct cal_control *ctl)
+static void monthly(const struct cal_control *ctl)
 {
-       int col, i, month, row, which_cal;
-       int days[MONTHS_IN_YEAR][MAXDAYS];
-       char *p;
-       /* three weeks + separators + \0 */
-       int weeknumlen = (ctl->weektype ? WNUM_LEN : 0);
-       char lineout[ weeknumlen + sizeof(day_headings) + 2 +
-                     weeknumlen + sizeof(day_headings) + 2 +
-                     weeknumlen + sizeof(day_headings) + 1 ];
-
-       snprintf(lineout, sizeof(lineout), "%ld", year);
-
-       /* 2013-04-28: The -1 near HEAD_SEP makes year header to be aligned
-        * exactly how it has been aligned for long time, but it is
-        * unexplainable.  */
-       center(lineout, (ctl->week_width + HEAD_SEP) * ctl->num_months - HEAD_SEP - 1, 0);
-       my_putstring("\n\n");
-
-       for (i = 0; i < MONTHS_IN_YEAR; i++)
-               day_array(day, i + 1, year, days[i], ctl);
-
-       for (month = 0; month < MONTHS_IN_YEAR; month += ctl->num_months) {
-               center(ctl->full_month[month], ctl->week_width - 1, HEAD_SEP + 1);
-               if (ctl->julian) {
-                       center(ctl->full_month[month + 1], ctl->week_width - 1, 0);
-               } else {
-                       center(ctl->full_month[month + 1], ctl->week_width - 1, HEAD_SEP + 1);
-                       center(ctl->full_month[month + 2], ctl->week_width - 1, 0);
+       struct cal_month m1,m2,m3, *m;
+       int i, rows, new_month, month = ctl->req.start_month ? ctl->req.start_month : ctl->req.month;
+       int32_t year = ctl->req.year;
+
+       /* cal -3, cal -Y --span, etc. */
+       if (ctl->span_months) {
+               new_month = month - ctl->num_months / 2;
+               if (new_month < 1) {
+                       month = new_month + MONTHS_IN_YEAR;
+                       year--;
                }
-               if (ctl->julian)
-                       snprintf(lineout, sizeof(lineout),
-                                "\n%*s%s%*s %*s%s\n",
-                                weeknumlen,"", day_headings, HEAD_SEP, "",
-                                weeknumlen,"", day_headings);
                else
-                       snprintf(lineout, sizeof(lineout),
-                                "\n%*s%s%*s %*s%s%*s %*s%s\n",
-                                weeknumlen,"", day_headings, HEAD_SEP, "",
-                                weeknumlen,"", day_headings, HEAD_SEP, "",
-                                weeknumlen,"", day_headings);
+                       month = new_month;
+       }
 
-               my_putstring(lineout);
-               for (row = 0; row < DAYS_IN_WEEK - 1; row++) {
-                       p = lineout;
-                       for (which_cal = 0; which_cal < ctl->num_months; which_cal++) {
-                               int *dp = &days[month + which_cal][row * DAYS_IN_WEEK];
-
-                               if (ctl->weektype)
-                                       p = append_weeknum(p, days[month + which_cal],
-                                                       month, year, which_cal,
-                                                       row, ctl);
-
-                               for (col = 0; col < DAYS_IN_WEEK; col++)
-                                       p = ascii_day(p, *dp++, ctl);
-                               p += sprintf(p, "  ");
+       m1.next = (ctl->months_in_row > 1) ? &m2 : NULL;
+       m2.next = (ctl->months_in_row > 2) ? &m3 : NULL;
+       m3.next = NULL;
+
+       rows = (ctl->num_months - 1) / ctl->months_in_row;
+       for (i = 0; i < rows + 1 ; i++){
+               if (i == rows){
+                       switch (ctl->num_months % ctl->months_in_row){
+                               case 1:
+                                       m1.next = NULL;
+                                       /* fallthrough */
+                               case 2:
+                                       m2.next = NULL;
+                                       /* fallthrough */
                        }
-                       *p = '\0';
-                       my_putstring(lineout);
-                       my_putstring("\n");
                }
+               for (m = &m1; m; m = m->next){
+                       m->month = month++;
+                       m->year = year;
+                       if (MONTHS_IN_YEAR < month) {
+                               year++;
+                               month = 1;
+                       }
+                       cal_fill_month(m, ctl);
+               }
+               cal_output_header(&m1, ctl);
+               cal_output_months(&m1, ctl);
        }
-       my_putstring("\n");
 }
 
-/*
- * day_array --
- *     Fill in an array of 42 integers with a calendar.  Assume for a moment
- *     that you took the (maximum) 6 rows in a calendar and stretched them
- *     out end to end.  You would have 42 numbers or spaces.  This routine
- *     builds that array for any month from Jan. 1 through Dec. 9999.
- */
-static void day_array(int day, int month, long year, int *days, const struct cal_control *ctl)
+static void yearly(const struct cal_control *ctl)
 {
-       int julday, daynum, dw, dm;
-       const int *sep1752;
-
-       memcpy(days, empty, MAXDAYS * sizeof(int));
-       if (year == REFORMATION_YEAR && month == REFORMATION_MONTH) {
-               sep1752 = ctl->julian ? j_sep1752 : d_sep1752;
-               memcpy(days, sep1752 + ctl->weekstart,
-                      ((MAXDAYS / 2) - ctl->weekstart) * sizeof(int));
-               for (dm = 0; dm < MAXDAYS / 2; dm++)
-                       if (j_sep1752[dm] == day)
-                               days[dm] |= TODAY_FLAG;
-               return;
-       }
-       dm = days_in_month[leap_year(year)][month];
-       dw = (day_in_week(1, month, year) - ctl->weekstart + DAYS_IN_WEEK) % DAYS_IN_WEEK;
-       julday = day_in_year(1, month, year);
-       daynum = ctl->julian ? julday : 1;
-
-       while (dm--) {
-               days[dw] = daynum++;
-               if (julday++ == day)
-                       days[dw] |= TODAY_FLAG;
-               dw++;
+       char out[FMT_ST_CHARS];
+       int year_width = 0;
+
+       year_width += (ctl->week_width + 1) * (ctl->julian ? 2 : 3);
+       if (ctl->julian)
+               year_width--;
+
+       if (ctl->header_year) {
+               sprintf(out, "%04d", ctl->req.year);
+               center(out, year_width, 0);
+               my_putstring("\n\n");
        }
+       monthly(ctl);
+
+       /* Is empty line at the end year output really needed? */
+       my_putstring("\n");
 }
 
 /*
  * day_in_year --
  *     return the 1 based day number within the year
  */
-static int day_in_year(int day, int month, long year)
+static int day_in_year(const struct cal_control *ctl,
+                      int day, int month, int32_t year)
 {
        int i, leap;
 
-       leap = leap_year(year);
+       leap = leap_year(ctl, year);
        for (i = 1; i < month; i++)
                day += days_in_month[leap][i];
        return day;
@@ -811,80 +893,94 @@ static int day_in_year(int day, int month, long year)
  *     3 Sep. 1752 through 13 Sep. 1752, and returns invalid weekday
  *     during the period of 11 days.
  */
-static int day_in_week(int day, int month, long year)
+static int day_in_week(const struct cal_control *ctl, int day,
+                      int month, int32_t year)
 {
-       static const int reform[] = {
-               SUNDAY, WEDNESDAY, TUESDAY, FRIDAY, SUNDAY, WEDNESDAY,
-               FRIDAY, MONDAY, THURSDAY, SATURDAY, TUESDAY, THURSDAY
-       };
-       static const int old[] = {
-               FRIDAY, MONDAY, SUNDAY, WEDNESDAY, FRIDAY, MONDAY,
-               WEDNESDAY, SATURDAY, TUESDAY, THURSDAY, SUNDAY, TUESDAY
-       };
-       if (year != 1753)
-               year -= month < 3;
+       /*
+       * The magic constants in the reform[] array are, in a simplified
+       * sense, the remaining days after slicing into one week periods the total
+       * days from the beginning of the year to the target month. That is,
+       * weeks + reform[] days gets us to the target month. The exception is,
+       * that for the months past February 'DOY - 1' must be used.
+       *
+       *   DoY (Day of Year): total days to the target month
+       *
+       *   Month            1  2  3  4   5   6   7   8   9  10  11  12
+       *   DoY              0 31 59 90 120 151 181 212 243 273 304 334
+       *   DoY % 7          0  3
+       *   DoY - 1 % 7      - --  2  5   0   3   5   1   4   6   2   4
+       *       reform[] = { 0, 3, 2, 5,  0,  3,  5,  1,  4,  6,  2,  4 };
+       *
+       *  Note: these calculations are for non leap years.
+       */
+       static const int reform[] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 };
+       static const int old[]    = { 5, 1, 0, 3, 5, 1, 3, 6, 2, 4, 0, 2 };
+
+       if (year != ctl->reform_year + 1)
+               year -= month < MARCH;
        else
-               year -= (month < 3) + 14;
-       if (REFORMATION_YEAR < year
-           || (year == REFORMATION_YEAR && 9 < month)
-           || (year == REFORMATION_YEAR && month == 9 && 13 < day))
-               return (year + (year / 4) - (year / 100) + (year / 400) + reform[month - 1] +
-                       day) % 7;
-       if (year < REFORMATION_YEAR
-           || (year == REFORMATION_YEAR && month < 9)
-           || (year == REFORMATION_YEAR && month == 9 && day < 3))
-               return (year + year / 4 + old[month - 1] + day) % 7;
+               year -= (month < MARCH) + 14;
+       if (ctl->reform_year < year
+           || (year == ctl->reform_year && REFORMATION_MONTH < month)
+           || (year == ctl->reform_year
+               && month == REFORMATION_MONTH && 13 < day)) {
+               return ((int64_t) year + (year / 4)
+                       - (year / 100) + (year / 400)
+                       + reform[month - 1] + day) % DAYS_IN_WEEK;
+       }
+       if (year < ctl->reform_year
+           || (year == ctl->reform_year && month < REFORMATION_MONTH)
+           || (year == ctl->reform_year && month == REFORMATION_MONTH && day < 3))
+               return ((int64_t) year + year / 4 + old[month - 1] + day)
+                       % DAYS_IN_WEEK;
        return NONEDAY;
 }
 
 /*
  * week_number
- *      return the week number of a given date, 1..53.
+ *      return the week number of a given date, 1..54.
  *      Supports ISO-8601 and North American modes.
  *      Day may be given as Julian day of the year mode, in which
  *      case the month is disregarded entirely.
  */
-static int week_number(int day, int month, long year, const struct cal_control *ctl)
+static int week_number(int day, int month, int32_t year, const struct cal_control *ctl)
 {
        int fday = 0, yday;
-       int wday = day_in_week(1, 1, year);
+       const int wday = day_in_week(ctl, 1, JANUARY, year);
 
        if (ctl->weektype & WEEK_NUM_ISO)
                fday = wday + (wday >= FRIDAY ? -2 : 5);
-       else
-               /* WEEK_NUM_US
-                * - according to gcal, the first Sun is in the first week
-                * - according to wikipedia, the first Sat is in the first week
-                */
-               fday = wday + (wday == SUNDAY ? 6 : -1);
-
+       else {
+               /* WEEK_NUM_US: Jan 1 is always First week, that may
+                * begin previous year.  That means there is very seldom
+                * more than 52 weeks, */
+               fday = wday + 6;
+       }
        /* For julian dates the month can be set to 1, the global julian
         * variable cannot be relied upon here, because we may recurse
         * internally for 31.12. which would not work. */
-       if (day > 31)
-               month = 1;
+       if (day > DAYS_IN_MONTH)
+               month = JANUARY;
 
-       yday = day_in_year(day,month,year);
-       if (year == REFORMATION_YEAR) {
-               if (yday >= YDAY_AFTER_MISSING)
-                       fday -= NUMBER_MISSING_DAYS;
-       }
+       yday = day_in_year(ctl, day, month, year);
+       if (year == ctl->reform_year && yday >= YDAY_AFTER_MISSING)
+               fday -= NUMBER_MISSING_DAYS;
 
        /* Last year is last year */
-       if (yday + fday < 7)
-               return week_number(31, 12, year - 1, ctl);
+       if (yday + fday < DAYS_IN_WEEK)
+               return week_number(31, DECEMBER, year - 1, ctl);
 
        /* Or it could be part of the next year.  The reformation year had less
         * days than 365 making this check invalid, but reformation year ended
         * on Sunday and in week 51, so it's ok here. */
        if (ctl->weektype == WEEK_NUM_ISO && yday >= 363
-           && day_in_week(day, month, year) >= MONDAY
-           && day_in_week(day, month, year) <= WEDNESDAY
-           && day_in_week(31, 12, year) >= MONDAY
-           && day_in_week(31, 12, year) <= WEDNESDAY)
-               return  week_number(1, 1, year + 1, ctl);
+           && day_in_week(ctl, day, month, year) >= MONDAY
+           && day_in_week(ctl, day, month, year) <= WEDNESDAY
+           && day_in_week(ctl, 31, DECEMBER, year) >= MONDAY
+           && day_in_week(ctl, 31, DECEMBER, year) <= WEDNESDAY)
+               return week_number(1, JANUARY, year + 1, ctl);
 
-       return (yday + fday) / 7;
+       return (yday + fday) / DAYS_IN_WEEK;
 }
 
 /*
@@ -894,12 +990,12 @@ static int week_number(int day, int month, long year, const struct cal_control *
  *      for ISO-8601 modes. For North American numbering this
  *      always returns a Sunday.
  */
-static int week_to_day(long year, const struct cal_control *ctl)
+static int week_to_day(const struct cal_control *ctl)
 {
        int yday, wday;
 
-       wday = day_in_week(1, 1, year);
-       yday = ctl->weeknum * 7 - wday;
+       wday = day_in_week(ctl, 1, JANUARY, ctl->req.year);
+       yday = ctl->req.week * DAYS_IN_WEEK - wday;
 
        if (ctl->weektype & WEEK_NUM_ISO)
                yday -= (wday >= FRIDAY ? -2 : 5);
@@ -911,62 +1007,6 @@ static int week_to_day(long year, const struct cal_control *ctl)
        return yday;
 }
 
-static char *ascii_day(char *p, int day, const struct cal_control *ctl)
-{
-       int display, val;
-       int highlight = 0;
-       static char *aday[] = {
-               "",
-               " 1", " 2", " 3", " 4", " 5", " 6", " 7",
-               " 8", " 9", "10", "11", "12", "13", "14",
-               "15", "16", "17", "18", "19", "20", "21",
-               "22", "23", "24", "25", "26", "27", "28",
-               "29", "30", "31",
-       };
-
-       if (day == SPACE) {
-               memset(p, ' ', ctl->day_width);
-               return p + ctl->day_width;
-       }
-       if (day & TODAY_FLAG) {
-               day &= ~TODAY_FLAG;
-               p += sprintf(p, "%s", Senter);
-               highlight = 1;
-       }
-       if (ctl->julian) {
-               if ((val = day / 100)) {
-                       day %= 100;
-                       *p++ = val + '0';
-                       display = 1;
-               } else {
-                       *p++ = ' ';
-                       display = 0;
-               }
-               val = day / 10;
-               if (val || display)
-                       *p++ = val + '0';
-               else
-                       *p++ = ' ';
-               *p++ = day % 10 + '0';
-       } else {
-               *p++ = aday[day][0];
-               *p++ = aday[day][1];
-       }
-       if (highlight)
-               p += sprintf(p, "%s", Sexit);
-       *p++ = ' ';
-       return p;
-}
-
-static char *ascii_weeknum(char *p, int weeknum, const struct cal_control *ctl)
-{
-       if ((ctl->weektype & WEEK_NUM_MASK) == weeknum)
-               p += sprintf(p, "%s%2d%s ", Senter, weeknum, Sexit);
-       else
-               p += sprintf(p, "%2d ", weeknum);
-       return p;
-}
-
 /*
  * Center string, handling multibyte characters appropriately.
  * In addition if the string is too large for the width it's truncated.
@@ -992,10 +1032,36 @@ static void center(const char *str, size_t len, int separate)
        }
 }
 
-static void __attribute__ ((__noreturn__)) usage(FILE * out)
+static int parse_reform_year(const char *reform_year)
+{
+       size_t i;
+
+       struct reform {
+               char *name;
+               int val;
+       };
+
+       struct reform years[] = {
+       {"gregorian",   GREGORIAN},
+       {"iso",         ISO},
+       {"1752",        GB1752},
+       {"julian",      JULIAN},
+       };
+
+       for (i = 0; i < ARRAY_SIZE(years); i++) {
+               if (strcasecmp(reform_year, years[i].name) == 0) {
+                       return years[i].val;
+               }
+       }
+       errx(EXIT_FAILURE, "invalid --reform value: '%s'", reform_year);
+}
+
+static void __attribute__((__noreturn__)) usage(void)
 {
+       FILE *out = stdout;
        fputs(USAGE_HEADER, out);
        fprintf(out, _(" %s [options] [[[day] month] year]\n"), program_invocation_short_name);
+       fprintf(out, _(" %s [options] <timestamp|monthname>\n"), program_invocation_short_name);
 
        fputs(USAGE_SEPARATOR, out);
        fputs(_("Display a calendar, or some part of it.\n"), out);
@@ -1004,17 +1070,23 @@ static void __attribute__ ((__noreturn__)) usage(FILE * out)
        fputs(USAGE_OPTIONS, out);
        fputs(_(" -1, --one             show only a single month (default)\n"), out);
        fputs(_(" -3, --three           show three months spanning the date\n"), out);
+       fputs(_(" -n, --months <num>    show num months starting with date's month\n"), out);
+       fputs(_(" -S, --span            span the date when displaying multiple months\n"), out);
        fputs(_(" -s, --sunday          Sunday as first day of week\n"), out);
        fputs(_(" -m, --monday          Monday as first day of week\n"), out);
-       fputs(_(" -j, --julian          output Julian dates\n"), out);
+       fputs(_(" -j, --julian          use day-of-year for all calendars\n"), out);
+       fputs(_("     --reform <val>    Gregorian reform date (1752|gregorian|iso|julian)\n"), out);
+       fputs(_("     --iso             alias for --reform=iso\n"), out);
        fputs(_(" -y, --year            show the whole year\n"), out);
+       fputs(_(" -Y, --twelve          show the next twelve months\n"), out);
        fputs(_(" -w, --week[=<num>]    show US or ISO-8601 week numbers\n"), out);
        fputs(_("     --color[=<when>]  colorize messages (auto, always or never)\n"), out);
+       fprintf(out,
+               "                         %s\n", USAGE_COLORS_DEFAULT);
 
        fputs(USAGE_SEPARATOR, out);
-       fputs(USAGE_HELP, out);
-       fputs(USAGE_VERSION, out);
-       fprintf(out, USAGE_MAN_TAIL("cal(1)"));
+       printf(USAGE_HELP_OPTIONS(23));
+       printf(USAGE_MAN_TAIL("cal(1)"));
 
-       exit(out == stderr ? EXIT_FAILURE : EXIT_SUCCESS);
+       exit(EXIT_SUCCESS);
 }