]> git.ipfire.org Git - thirdparty/util-linux.git/blobdiff - misc-utils/cal.c
hardlink: retire NIOBUF in favour of more common BUFSIZ
[thirdparty/util-linux.git] / misc-utils / cal.c
index c687c6c9d1e396c560b695369a31c3a93c46f627..c7e8d9511ec592f27da61bd981ba88105fd90bbb 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 MONTHS_IN_ROW 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.
 #include "mbsalign.h"
 #include "strutils.h"
 #include "optutils.h"
+#include "timeutils.h"
+#include "ttyutils.h"
+
+#define DOY_MONTH_WIDTH        27      /* -j month width */
+#define DOM_MONTH_WIDTH        20      /* month width */
 
 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>
 #endif
 
-static int setup_terminal(char *term)
+static int setup_terminal(char *term
+#if !defined(HAVE_LIBNCURSES) && !defined(HAVE_LIBNCURSESW)
+                       __attribute__((__unused__))
+#endif
+               )
 {
 #if defined(HAVE_LIBNCURSES) || defined(HAVE_LIBNCURSESW)
        int ret;
 
-       if (setupterm(term, STDOUT_FILENO, &ret) != OK || ret != 1)
+       if (setupterm(term, STDOUT_FILENO, &ret) != 0 || ret != 1)
                return -1;
 #endif
        return 0;
@@ -108,7 +118,11 @@ static void my_putstring(char *s)
                fputs(s, stdout);
 }
 
-static const char *my_tgetstr(char *s __attribute__ ((__unused__)), char *ss)
+static const char *my_tgetstr(char *ss
+#if !defined(HAVE_LIBNCURSES) && !defined(HAVE_LIBNCURSESW)
+                       __attribute__((__unused__))
+#endif
+               )
 {
        const char *ret = NULL;
 
@@ -123,6 +137,14 @@ static const char *my_tgetstr(char *s __attribute__ ((__unused__)), char *ss)
 
 #include "widechar.h"
 
+enum {
+       GREGORIAN               = INT32_MIN,
+       ISO                     = INT32_MIN,
+       GB1752                  = 1752,
+       DEFAULT_REFORM_YEAR     = 1752,
+       JULIAN                  = INT32_MAX
+};
+
 enum {
        SUNDAY = 0,
        MONDAY,
@@ -150,7 +172,6 @@ enum {
        DECEMBER
 };
 
-#define REFORMATION_YEAR       1752            /* Signed-off-by: Lord Chesterfield */
 #define REFORMATION_MONTH      SEPTEMBER
 #define        NUMBER_MISSING_DAYS     11              /* 11 day correction */
 #define YDAY_AFTER_MISSING     258             /* 14th in Sep 1752 */
@@ -194,8 +215,11 @@ struct cal_request {
 
 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 requested mounths */
+       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 */
@@ -218,29 +242,53 @@ struct cal_month {
 };
 
 /* function prototypes */
-static int leap_year(int32_t 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 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(int day, int month, int32_t year);
-static int day_in_week(int day, int month, int32_t year);
+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);
+
+#ifdef TEST_CAL
+static time_t cal_time(time_t *t)
+{
+       char *str = getenv("CAL_TEST_TIME");
+
+       if (str) {
+               uint64_t x = strtou64_or_err(str, "failed to parse CAL_TEST_TIME");
+
+               *t = x;
+               return *t;
+       }
+
+       return time(t);
+}
+#else
+# define cal_time(t)   time(t)
+#endif
 
 int main(int argc, char **argv)
 {
        struct tm *local_time;
+       char *term;
        time_t now;
        int ch = 0, yflag = 0, Yflag = 0;
+
        static struct cal_control ctl = {
+               .reform_year = DEFAULT_REFORM_YEAR,
                .weekstart = SUNDAY,
-               .num_months = 1,                /* default is "cal -1" */
                .span_months = 0,
                .colormode = UL_COLORMODE_UNDEF,
                .weektype = WEEK_NUM_DISABLED,
@@ -251,7 +299,9 @@ int main(int argc, char **argv)
        };
 
        enum {
-               OPT_COLOR = CHAR_MAX + 1
+               OPT_COLOR = CHAR_MAX + 1,
+               OPT_ISO,
+               OPT_REFORM
        };
 
        static const struct option longopts[] = {
@@ -265,13 +315,15 @@ int main(int argc, char **argv)
                {"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 in ASCII order */
+       static const ul_excl_t excl[] = {       /* rows and cols in ASCII order */
                { 'Y','n','y' },
                { 0 }
        };
@@ -280,20 +332,16 @@ int main(int argc, char **argv)
        setlocale(LC_ALL, "");
        bindtextdomain(PACKAGE, LOCALEDIR);
        textdomain(PACKAGE);
-       atexit(close_stdout);
-
-#if defined(HAVE_LIBNCURSES) || defined(HAVE_LIBNCURSESW)
-       {
-               char *term = getenv("TERM");
-               if (term) {
-                       has_term = setup_terminal(term) == 0;
-                       if (has_term) {
-                               Senter = my_tgetstr("so", "smso");
-                               Sexit = my_tgetstr("se", "rmso");
-                       }
+       close_stdout_atexit();
+
+       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,
@@ -325,7 +373,8 @@ 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
@@ -335,12 +384,11 @@ int main(int argc, char **argv)
 
                switch(ch) {
                case '1':
-                       /* default */
+                       ctl.num_months = 1;
                        break;
                case '3':
                        ctl.num_months = 3;
                        ctl.span_months = 1;
-                       ctl.months_in_row = 3;
                        break;
                case 's':
                        ctl.weekstart = SUNDAY;         /* default */
@@ -380,14 +428,18 @@ int main(int argc, char **argv)
                                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;
+                       print_version(EXIT_SUCCESS);
                case 'h':
-                       usage(stdout);
-               case '?':
+                       usage();
                default:
-                       usage(stderr);
+                       errtryhelp(EXIT_FAILURE);
                }
        }
 
@@ -401,7 +453,20 @@ int main(int argc, char **argv)
        } 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)
+                       cal_time(&now); /* this year */
+               else
+                       errx(EXIT_FAILURE, _("failed to parse timestamp or unknown month name: %s"), *argv);
+               argc = 0;
+       } else
+               cal_time(&now);
+
        local_time = localtime(&now);
 
        switch(argc) {
@@ -409,43 +474,55 @@ int main(int argc, char **argv)
                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:
-               ctl.req.month = strtos32_or_err(*argv++, _("illegal month value: use 1-12"));
+               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:
                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 (ctl.req.year == INT32_MAX)
+               if (ctl.req.year == JULIAN)
                        errx(EXIT_FAILURE, _("illegal year value"));
                if (ctl.req.day) {
-                       int dm = days_in_month[leap_year(ctl.req.year)][ctl.req.month];
+                       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);
-                       ctl.req.day = day_in_year(ctl.req.day, ctl.req.month, ctl.req.year);
+                       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 (!ctl.num_months)
+                               yflag = 1;
                }
                break;
        case 0:
                ctl.req.day = local_time->tm_yday + 1;
                ctl.req.year = local_time->tm_year + 1900;
-               ctl.req.month = local_time->tm_mon + 1;
+               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.req.week) {
                int yday = week_to_day(&ctl);
-               int leap = leap_year(ctl.req.year);
+               int leap = leap_year(&ctl, ctl.req.year);
                int m = 1;
 
                if (yday < 1)
@@ -472,26 +549,51 @@ int main(int argc, char **argv)
 
        headers_init(&ctl);
 
-       if (!colors_init(ctl.colormode, "cal")) {
-               ctl.req.day = 0;
-               ctl.weektype &= ~WEEK_NUM_MASK;
+       if (colors_init(ctl.colormode, "cal") == 0) {
+               /*
+                * If standout mode available (Senter and Sexit are set) and
+                * user or terminal-colors.d do not disable colors than
+                * ignore colors_init().
+                */
+               if (*Senter && *Sexit && colors_mode() != UL_COLORMODE_NEVER) {
+                       /* let use standout mode */
+                       ;
+               } else {
+                       /* disable */
+                       Senter = ""; Sexit = "";
+                       ctl.req.day = 0;
+                       ctl.weektype &= ~WEEK_NUM_MASK;
+               }
        }
 
        if (yflag || Yflag) {
                ctl.gutter_width = 3;
-               ctl.num_months = MONTHS_IN_YEAR;
+               if (!ctl.num_months)
+                       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)
+       if (ctl.num_months > 1 && ctl.months_in_row == 0) {
+               ctl.months_in_row = MONTHS_IN_YEAR_ROW;         /* default */
+
+               if (isatty(STDOUT_FILENO)) {
+                       int w = get_terminal_width(STDOUT_FILENO);
+                       int mw = ctl.julian ? DOY_MONTH_WIDTH : DOM_MONTH_WIDTH;
+                       int extra = ((w / mw) - 1) * ctl.gutter_width;
+                       int new_n = (w - extra) / mw;
+
+                       if (new_n < MONTHS_IN_YEAR_ROW)
+                               ctl.months_in_row = new_n;
+               }
+       } else if (!ctl.months_in_row)
                ctl.months_in_row = 1;
 
+       if (!ctl.num_months)
+               ctl.num_months = 1;             /* display at least one month */
+
        if (yflag || Yflag)
                yearly(&ctl);
        else
@@ -501,14 +603,53 @@ int main(int argc, char **argv)
 }
 
 /* leap year -- account for gregorian reformation in 1752 */
-static int leap_year(int32_t 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(ALTMON_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(_NL_ABALTMON_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;
@@ -516,7 +657,7 @@ static void headers_init(struct cal_control *ctl)
        char tmp[FMT_ST_CHARS];
        int year_len;
 
-       year_len = snprintf(tmp, sizeof(tmp), "%d", ctl->req.year);
+       year_len = snprintf(tmp, sizeof(tmp), "%04d", ctl->req.year);
 
        if (year_len < 0 || (size_t)year_len >= sizeof(tmp)) {
                /* XXX impossible error */
@@ -537,8 +678,9 @@ static void headers_init(struct cal_control *ctl)
                                     space_left, ctl->day_width - 1);
        }
 
+       init_monthnames(ctl);
+
        for (i = 0; i < MONTHS_IN_YEAR; i++) {
-               ctl->full_month[i] = nl_langinfo(MON_1 + 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;
@@ -547,15 +689,15 @@ static void headers_init(struct cal_control *ctl)
 
 static void cal_fill_month(struct cal_month *month, const struct cal_control *ctl)
 {
-       int first_week_day = day_in_week(1, month->month, month->year);
+       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(1, month->month, month->year);
+               j = day_in_year(ctl, 1, month->month, month->year);
        else
                j = 1;
-       month_days = j + days_in_month[leap_year(month->year)][month->month];
+       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) {
@@ -573,7 +715,9 @@ static void cal_fill_month(struct cal_month *month, const struct cal_control *ct
                        continue;
                }
                if (j < month_days) {
-                       if (month->year == REFORMATION_YEAR && month->month == REFORMATION_MONTH && (j == 3 || j == 247))
+                       if (month->year == ctl->reform_year &&
+                           month->month == REFORMATION_MONTH &&
+                           (j == 3 || j == 247))
                                j += NUMBER_MISSING_DAYS;
                        month->days[i] = j;
                        j++;
@@ -606,19 +750,19 @@ static void cal_output_header(struct cal_month *month, const struct cal_control
 
        if (ctl->header_hint || ctl->header_year) {
                for (i = month; i; i = i->next) {
-                       sprintf(out, _("%s"), ctl->full_month[i->month - 1]);
+                       snprintf(out, sizeof(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, _("%d"), i->year);
+                               snprintf(out, sizeof(out), "%04d", i->year);
                                center(out, ctl->week_width - 1, i->next == NULL ? 0 : ctl->gutter_width);
                        }
                }
        } else {
                for (i = month; i; i = i->next) {
-                       sprintf(out, _("%s %d"), ctl->full_month[i->month - 1], i->year);
+                       snprintf(out, sizeof(out), "%s %04d", ctl->full_month[i->month - 1], i->year);
                        center(out, ctl->week_width - 1, i->next == NULL ? 0 : ctl->gutter_width);
                }
        }
@@ -626,14 +770,14 @@ static void cal_output_header(struct cal_month *month, const struct cal_control
        for (i = month; i; i = i->next) {
                if (ctl->weektype) {
                        if (ctl->julian)
-                               sprintf(out, "%*s%s", (int)ctl->day_width - 1, "", day_headings);
+                               snprintf(out, sizeof(out), "%*s%s", (int)ctl->day_width - 1, "", day_headings);
                        else
-                               sprintf(out, "%*s%s", (int)ctl->day_width, "", day_headings);
+                               snprintf(out, sizeof(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, "");
+                       snprintf(out, sizeof(out), "%*s", ctl->gutter_width, "");
                        my_putstring(out);
                }
        }
@@ -655,21 +799,22 @@ static void cal_output_months(struct cal_month *month, const struct cal_control
                                if (ctl->julian)
                                        reqday = ctl->req.day;
                                else
-                                       reqday =
-                                           ctl->req.day + 1 - day_in_year(1, i->month,
-                                                                          i->year);
+                                       reqday = ctl->req.day + 1 -
+                                                day_in_year(ctl, 1, i->month,
+                                                            i->year);
                        }
 
                        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);
+                                               snprintf(out, sizeof(out), "%s%2d%s",
+                                                               Senter, i->weeks[week_line],
+                                                               Sexit);
                                        else
-                                               sprintf(out, "%2d", i->weeks[week_line]);
+                                               snprintf(out, sizeof(out), "%2d", i->weeks[week_line]);
                                } else
-                                       sprintf(out, "%2s", "");
+                                       snprintf(out, sizeof(out), "%2s", "");
                                my_putstring(out);
                                skip = ctl->day_width;
                        } else
@@ -681,44 +826,45 @@ static void cal_output_months(struct cal_month *month, const struct cal_control
                             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),
+                                               snprintf(out, sizeof(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]);
+                                               snprintf(out, sizeof(out), "%*d", skip, i->days[d]);
                                } else
-                                       sprintf(out, "%*s", skip, "");
+                                       snprintf(out, sizeof(out), "%*s", skip, "");
                                my_putstring(out);
                                if (skip < (int)ctl->day_width)
                                        skip++;
                        }
                        if (i->next != NULL) {
-                               sprintf(out, "%*s", ctl->gutter_width, "");
+                               snprintf(out, sizeof(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);
-               }
+               if (i == NULL)
+                       my_putstring("\n");
        }
 }
 
 static void monthly(const struct cal_control *ctl)
 {
        struct cal_month m1,m2,m3, *m;
-       int i, rows, new_month, month = ctl->req.start_month ? ctl->req.start_month : ctl->req.month;
+       int i, rows, 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;
+               int new_month = month - ctl->num_months / 2;
                if (new_month < 1) {
-                       month = new_month + MONTHS_IN_YEAR;
-                       year--;
-               }
-               else
+                       new_month *= -1;
+                       year -= (new_month / MONTHS_IN_YEAR) + 1;
+
+                       if (new_month > MONTHS_IN_YEAR)
+                               new_month %= MONTHS_IN_YEAR;
+                       month = MONTHS_IN_YEAR - new_month;
+               } else
                        month = new_month;
        }
 
@@ -762,25 +908,23 @@ static void yearly(const struct cal_control *ctl)
                year_width--;
 
        if (ctl->header_year) {
-               sprintf(out, "%d", ctl->req.year);
+               snprintf(out, sizeof(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, int32_t 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;
@@ -793,31 +937,46 @@ static int day_in_year(int day, int month, int32_t 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, int32_t 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 != REFORMATION_YEAR + 1)
+       /*
+       * 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 < MARCH) + 14;
-       if (REFORMATION_YEAR < year
-           || (year == REFORMATION_YEAR && REFORMATION_MONTH < month)
-           || (year == REFORMATION_YEAR && month == REFORMATION_MONTH && 13 < day)) {
-               int64_t long_year = year;
-               return (long_year + (year / 4) - (year / 100) + (year / 400) + reform[month - 1] +
-                       day) % DAYS_IN_WEEK;
+       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 < REFORMATION_YEAR
-           || (year == REFORMATION_YEAR && month < REFORMATION_MONTH)
-           || (year == REFORMATION_YEAR && month == REFORMATION_MONTH && day < 3))
-               return (year + year / 4 + old[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;
 }
 
@@ -831,7 +990,7 @@ static int day_in_week(int day, int month, int32_t year)
 static int week_number(int day, int month, int32_t year, const struct cal_control *ctl)
 {
        int fday = 0, yday;
-       const int wday = day_in_week(1, JANUARY, year);
+       const int wday = day_in_week(ctl, 1, JANUARY, year);
 
        if (ctl->weektype & WEEK_NUM_ISO)
                fday = wday + (wday >= FRIDAY ? -2 : 5);
@@ -847,11 +1006,9 @@ static int week_number(int day, int month, int32_t year, const struct cal_contro
        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 < DAYS_IN_WEEK)
@@ -861,10 +1018,10 @@ static int week_number(int day, int month, int32_t year, const struct cal_contro
         * 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, DECEMBER, year) >= MONDAY
-           && day_in_week(31, DECEMBER, year) <= WEDNESDAY)
+           && 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) / DAYS_IN_WEEK;
@@ -881,13 +1038,16 @@ static int week_to_day(const struct cal_control *ctl)
 {
        int yday, wday;
 
-       wday = day_in_week(1, JANUARY, ctl->req.year);
+       wday = day_in_week(ctl, 1, JANUARY, ctl->req.year);
        yday = ctl->req.week * DAYS_IN_WEEK - wday;
 
+       if (ctl->req.year == ctl->reform_year && yday >= YDAY_AFTER_MISSING)
+               yday += NUMBER_MISSING_DAYS;
+
        if (ctl->weektype & WEEK_NUM_ISO)
                yday -= (wday >= FRIDAY ? -2 : 5);
        else
-               yday -= (wday == SUNDAY ? 6 : -1);      /* WEEK_NUM_US */
+               yday -= 6;      /* WEEK_NUM_US */
        if (yday <= 0)
                return 1;
 
@@ -919,10 +1079,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);
@@ -935,7 +1121,9 @@ static void __attribute__ ((__noreturn__)) usage(FILE * 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);
@@ -944,9 +1132,8 @@ static void __attribute__ ((__noreturn__)) usage(FILE * 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);
 }