(root)/
util-linux-2.39/
misc-utils/
cal.c
       1  /*
       2   * Copyright (c) 1989, 1993, 1994
       3   *	The Regents of the University of California.  All rights reserved.
       4   *
       5   * This code is derived from software contributed to Berkeley by
       6   * Kim Letkeman.
       7   *
       8   * Redistribution and use in source and binary forms, with or without
       9   * modification, are permitted provided that the following conditions
      10   * are met:
      11   * 1. Redistributions of source code must retain the above copyright
      12   *    notice, this list of conditions and the following disclaimer.
      13   * 2. Redistributions in binary form must reproduce the above copyright
      14   *    notice, this list of conditions and the following disclaimer in the
      15   *    documentation and/or other materials provided with the distribution.
      16   * 3. All advertising materials mentioning features or use of this software
      17   *    must display the following acknowledgement:
      18   *	This product includes software developed by the University of
      19   *	California, Berkeley and its contributors.
      20   * 4. Neither the name of the University nor the names of its contributors
      21   *    may be used to endorse or promote products derived from this software
      22   *    without specific prior written permission.
      23   *
      24   * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
      25   * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
      26   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
      27   * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
      28   * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
      29   * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
      30   * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
      31   * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
      32   * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
      33   * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
      34   * SUCH DAMAGE.
      35   */
      36  
      37  /* 1999-02-01	Jean-Francois Bignolles: added option '-m' to display
      38   *		monday as the first day of the week.
      39   * 1999-02-22 Arkadiusz Miƛkiewicz <misiek@pld.ORG.PL>
      40   * - added Native Language Support
      41   *
      42   * 2000-09-01  Michael Charles Pruznick <dummy@netwiz.net>
      43   *             Added "-3" option to print prev/next month with current.
      44   *             Added overridable default MONTHS_IN_ROW and "-1" option to
      45   *             get traditional output when -3 is the default.  I hope that
      46   *             enough people will like -3 as the default that one day the
      47   *             product can be shipped that way.
      48   *
      49   * 2001-05-07  Pablo Saratxaga <pablo@mandrakesoft.com>
      50   *             Fixed the bugs with multi-byte charset (zg: cjk, utf-8)
      51   *             displaying. made the 'month year' ("%s %d") header translatable
      52   *             so it can be adapted to conventions used by different languages
      53   *             added support to read "first_weekday" locale information
      54   *             still to do: support for 'cal_direction' (will require a major
      55   *             rewrite of the displaying) and proper handling of RTL scripts
      56   */
      57  
      58  #include <sys/types.h>
      59  
      60  #include <ctype.h>
      61  #include <getopt.h>
      62  #include <stdint.h>
      63  #include <stdio.h>
      64  #include <stdlib.h>
      65  #include <string.h>
      66  #include <time.h>
      67  #include <unistd.h>
      68  #include <errno.h>
      69  
      70  #include "c.h"
      71  #include "closestream.h"
      72  #include "colors.h"
      73  #include "nls.h"
      74  #include "mbsalign.h"
      75  #include "strutils.h"
      76  #include "optutils.h"
      77  #include "timeutils.h"
      78  #include "ttyutils.h"
      79  #include "xalloc.h"
      80  
      81  #define DOY_MONTH_WIDTH	27	/* -j month width */
      82  #define DOM_MONTH_WIDTH	20	/* month width */
      83  
      84  enum {
      85  	CAL_COLOR_TODAY,
      86  	CAL_COLOR_HEADER,
      87  	CAL_COLOR_WEEKNUMBER,
      88  	CAL_COLOR_WORKDAY,
      89  	CAL_COLOR_WEEKEND
      90  };
      91  
      92  static const struct { const char * const scheme; const char * dflt; } colors[] =
      93  {
      94          [CAL_COLOR_TODAY]      = { "today",      UL_COLOR_REVERSE },
      95          [CAL_COLOR_WEEKNUMBER] = { "weeknumber", UL_COLOR_REVERSE },
      96          [CAL_COLOR_HEADER]     = { "header",     ""               },
      97  	[CAL_COLOR_WORKDAY]    = { "workday",    ""               },
      98  	[CAL_COLOR_WEEKEND]    = { "weekend",    ""               }
      99  };
     100  
     101  static inline void cal_enable_color(int id)
     102  {
     103  	color_scheme_enable(colors[id].scheme, colors[id].dflt);
     104  }
     105  
     106  static inline const char *cal_get_color_sequence(int id)
     107  {
     108  	return color_scheme_get_sequence(colors[id].scheme, colors[id].dflt);
     109  }
     110  
     111  static inline void cal_disable_color(int id)
     112  {
     113  	const char *seq = cal_get_color_sequence(id);
     114  	if (seq && seq[0])
     115  		color_disable();
     116  }
     117  
     118  static inline const char *cal_get_color_disable_sequence(int id)
     119  {
     120  	const char *seq = cal_get_color_sequence(id);
     121  	if (seq && seq[0])
     122  		return UL_COLOR_RESET;
     123  	else
     124  		return "";
     125  }
     126  
     127  #include "widechar.h"
     128  
     129  enum {
     130  	GREGORIAN		= INT32_MIN,
     131  	ISO			= INT32_MIN,
     132  	GB1752			= 1752,
     133  	DEFAULT_REFORM_YEAR	= 1752,
     134  	JULIAN			= INT32_MAX
     135  };
     136  
     137  enum {
     138  	SUNDAY = 0,
     139  	MONDAY,
     140  	TUESDAY,
     141  	WEDNESDAY,
     142  	THURSDAY,
     143  	FRIDAY,
     144  	SATURDAY,
     145  	DAYS_IN_WEEK,
     146  	NONEDAY
     147  };
     148  
     149  enum {
     150  	JANUARY = 1,
     151  	FEBRUARY,
     152  	MARCH,
     153  	APRIL,
     154  	MAY,
     155  	JUNE,
     156  	JULY,
     157  	AUGUST,
     158  	SEPTEMBER,
     159  	OCTOBER,
     160  	NOVEMBER,
     161  	DECEMBER
     162  };
     163  
     164  #define REFORMATION_MONTH	SEPTEMBER
     165  #define	NUMBER_MISSING_DAYS	11		/* 11 day correction */
     166  #define YDAY_AFTER_MISSING	258             /* 14th in Sep 1752 */
     167  
     168  #define MONTHS_IN_YEAR		DECEMBER
     169  #define DAYS_IN_MONTH		31
     170  #define	MAXDAYS			42		/* slots in a month array */
     171  #define	SPACE			-1		/* used in day array */
     172  
     173  #define SMALLEST_YEAR		1
     174  
     175  #define	DAY_LEN			3		/* 3 spaces per day */
     176  #define	WEEK_LEN		(DAYS_IN_WEEK * DAY_LEN)
     177  #define MONTHS_IN_YEAR_ROW	3		/* month columns in year view */
     178  #define WNUM_LEN                3
     179  
     180  #define FMT_ST_CHARS 300	/* 90 suffices in most locales */
     181  
     182  static const int days_in_month[2][13] = {
     183  	{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
     184  	{0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
     185  };
     186  
     187  enum {
     188  	WEEK_NUM_DISABLED = 0,
     189  	WEEK_NUM_MASK=0xff,
     190  	WEEK_NUM_ISO=0x100,
     191  	WEEK_NUM_US=0x200,
     192  };
     193  
     194  enum {
     195  	COLUMNS_MAX_THREE = -1,
     196  	COLUMNS_AUTO = -2,
     197  };
     198  
     199  /* utf-8 can have up to 6 bytes per char; and an extra byte for ending \0 */
     200  static char day_headings[(WEEK_LEN + 1) * 6 + 1];
     201  
     202  struct cal_request {
     203  	int day;
     204  	int month;
     205  	int32_t year;
     206  	int week;
     207  	int start_month;
     208  };
     209  
     210  struct cal_control {
     211  	const char *full_month[MONTHS_IN_YEAR];	/* month names */
     212  	const char *abbr_month[MONTHS_IN_YEAR];	/* abbreviated month names */
     213  	const char *weekdays[DAYS_IN_WEEK];     /* day names */
     214  
     215  	int reform_year;		/* Gregorian reform year */
     216  	int colormode;			/* day and week number highlight */
     217  	int num_months;			/* number of requested months */
     218  	int span_months;		/* span the date */
     219  	int months_in_row;		/* number of months horizontally in print out */
     220  	int weekstart;			/* day the week starts, often Sun or Mon */
     221  	int weektype;			/* WEEK_TYPE_{NONE,ISO,US} */
     222  	size_t day_width;		/* day width in characters in printout */
     223  	size_t week_width;		/* 7 * day_width + possible week num */
     224  	size_t month_width;		/* width of a month (vertical mode) */
     225  	int gutter_width;		/* spaces in between horizontal month outputs */
     226  	struct cal_request req;		/* the times user is interested */
     227  	unsigned int	julian:1,	/* julian output */
     228  			header_year:1,	/* print year number */
     229  			header_hint:1,	/* does month name + year need two lines to fit */
     230  			vertical:1;	/* display the output in vertical */
     231  };
     232  
     233  struct cal_month {
     234  	int days[MAXDAYS];		/* the day numbers, or SPACE */
     235  	int weeks[MAXDAYS / DAYS_IN_WEEK];
     236  	int month;
     237  	int32_t year;
     238  	struct cal_month *next;
     239  };
     240  /* function prototypes */
     241  static int leap_year(const struct cal_control *ctl, int32_t year);
     242  static int monthname_to_number(struct cal_control *ctl, const char *name);
     243  static void weekdays_init(struct cal_control *ctl);
     244  static void headers_init(struct cal_control *ctl);
     245  static void cal_fill_month(struct cal_month *month, const struct cal_control *ctl);
     246  static void cal_output_header(struct cal_month *month, const struct cal_control *ctl);
     247  static void cal_output_months(struct cal_month *month, const struct cal_control *ctl);
     248  static void cal_vert_output_months(struct cal_month *month, const struct cal_control *ctl);
     249  static void monthly(const struct cal_control *ctl);
     250  static void yearly(const struct cal_control *ctl);
     251  static int day_in_year(const struct cal_control *ctl, int day,
     252  		       int month, int32_t year);
     253  static int day_in_week(const struct cal_control *ctl, int day,
     254  		       int month, int32_t year);
     255  static int week_number(int day, int month, int32_t year, const struct cal_control *ctl);
     256  static int week_to_day(const struct cal_control *ctl);
     257  static int center_str(const char *src, char *dest, size_t dest_size, size_t width);
     258  static void center(const char *str, size_t len, int separate);
     259  static int left_str(const char *src, char *dest, size_t dest_size, size_t width);
     260  static void left(const char *str, size_t len, int separate);
     261  static int parse_reform_year(const char *reform_year);
     262  static void __attribute__((__noreturn__)) usage(void);
     263  
     264  #ifdef TEST_CAL
     265  static time_t cal_time(time_t *t)
     266  {
     267  	char *str = getenv("CAL_TEST_TIME");
     268  
     269  	if (str) {
     270  		uint64_t x = strtou64_or_err(str, "failed to parse CAL_TEST_TIME");
     271  
     272  		*t = x;
     273  		return *t;
     274  	}
     275  
     276  	return time(t);
     277  }
     278  #else
     279  # define cal_time(t)	time(t)
     280  #endif
     281  
     282  int main(int argc, char **argv)
     283  {
     284  	struct tm local_time;
     285  	time_t now;
     286  	int ch = 0, yflag = 0, Yflag = 0, cols = COLUMNS_MAX_THREE;
     287  
     288  	static struct cal_control ctl = {
     289  		.reform_year = DEFAULT_REFORM_YEAR,
     290  		.weekstart = SUNDAY,
     291  		.span_months = 0,
     292  		.colormode = UL_COLORMODE_UNDEF,
     293  		.weektype = WEEK_NUM_DISABLED,
     294  		.day_width = DAY_LEN,
     295  		.gutter_width = 2,
     296  		.req.day = 0,
     297  		.req.month = 0
     298  	};
     299  
     300  	enum {
     301  		OPT_COLOR = CHAR_MAX + 1,
     302  		OPT_ISO,
     303  		OPT_REFORM
     304  	};
     305  
     306  	static const struct option longopts[] = {
     307  		{"one", no_argument, NULL, '1'},
     308  		{"three", no_argument, NULL, '3'},
     309  		{"sunday", no_argument, NULL, 's'},
     310  		{"monday", no_argument, NULL, 'm'},
     311  		{"julian", no_argument, NULL, 'j'},
     312  		{"months", required_argument, NULL, 'n'},
     313  		{"span", no_argument, NULL, 'S'},
     314  		{"year", no_argument, NULL, 'y'},
     315  		{"week", optional_argument, NULL, 'w'},
     316  		{"color", optional_argument, NULL, OPT_COLOR},
     317  		{"reform", required_argument, NULL, OPT_REFORM},
     318  		{"iso", no_argument, NULL, OPT_ISO},
     319  		{"version", no_argument, NULL, 'V'},
     320  		{"twelve", no_argument, NULL, 'Y'},
     321  		{"help", no_argument, NULL, 'h'},
     322  		{"vertical", no_argument, NULL,'v'},
     323  		{"column", required_argument, NULL,'c'},
     324  		{NULL, 0, NULL, 0}
     325  	};
     326  
     327  	static const ul_excl_t excl[] = {       /* rows and cols in ASCII order */
     328  		{ 'Y','n','y' },
     329  		{ 0 }
     330  	};
     331  	int excl_st[ARRAY_SIZE(excl)] = UL_EXCL_STATUS_INIT;
     332  
     333  	setlocale(LC_ALL, "");
     334  	bindtextdomain(PACKAGE, LOCALEDIR);
     335  	textdomain(PACKAGE);
     336  	close_stdout_atexit();
     337  
     338  /*
     339   * The traditional Unix cal utility starts the week at Sunday,
     340   * while ISO 8601 starts at Monday. We read the start day from
     341   * the locale database, which can be overridden with the
     342   * -s (Sunday) or -m (Monday) options.
     343   */
     344  #if HAVE_DECL__NL_TIME_WEEK_1STDAY
     345  	/*
     346  	 * You need to use 2 locale variables to get the first day of the week.
     347  	 * This is needed to support first_weekday=2 and first_workday=1 for
     348  	 * the rare case where working days span across 2 weeks.
     349  	 * This shell script shows the combinations and calculations involved:
     350  	 *
     351  	 * for LANG in en_US ru_RU fr_FR csb_PL POSIX; do
     352  	 *   printf "%s:\t%s + %s -1 = " $LANG $(locale week-1stday first_weekday)
     353  	 *   date -d"$(locale week-1stday) +$(($(locale first_weekday)-1))day" +%w
     354  	 * done
     355  	 *
     356  	 * en_US:  19971130 + 1 -1 = 0  #0 = sunday
     357  	 * ru_RU:  19971130 + 2 -1 = 1
     358  	 * fr_FR:  19971201 + 1 -1 = 1
     359  	 * csb_PL: 19971201 + 2 -1 = 2
     360  	 * POSIX:  19971201 + 7 -1 = 0
     361  	 */
     362  	{
     363  		int wfd;
     364  		union { unsigned int word; char *string; } val;
     365  		val.string = nl_langinfo(_NL_TIME_WEEK_1STDAY);
     366  
     367  		wfd = val.word;
     368  		wfd = day_in_week(&ctl, wfd % 100, (wfd / 100) % 100,
     369  				  wfd / (100 * 100));
     370  		ctl.weekstart = (wfd + *nl_langinfo(_NL_TIME_FIRST_WEEKDAY) - 1) % DAYS_IN_WEEK;
     371  	}
     372  #endif
     373  	while ((ch = getopt_long(argc, argv, "13mjn:sSywYvc:Vh", longopts, NULL)) != -1) {
     374  
     375  		err_exclusive_options(ch, longopts, excl, excl_st);
     376  
     377  		switch(ch) {
     378  		case '1':
     379  			ctl.num_months = 1;
     380  			break;
     381  		case '3':
     382  			ctl.num_months = 3;
     383  			ctl.span_months = 1;
     384  			break;
     385  		case 's':
     386  			ctl.weekstart = SUNDAY;		/* default */
     387  			break;
     388  		case 'm':
     389  			ctl.weekstart = MONDAY;
     390  			break;
     391  		case 'j':
     392  			ctl.julian = 1;
     393  			ctl.day_width = DAY_LEN + 1;
     394  			break;
     395  		case 'y':
     396  			yflag = 1;
     397  			break;
     398  		case 'Y':
     399  			Yflag = 1;
     400  			break;
     401  		case 'n':
     402  			ctl.num_months = strtou32_or_err(optarg,
     403  						_("invalid month argument"));
     404  			break;
     405  		case 'S':
     406  			ctl.span_months = 1;
     407  			break;
     408  		case 'w':
     409  			if (optarg) {
     410  				ctl.req.week = strtos32_or_err(optarg,
     411  						_("invalid week argument"));
     412  				if (ctl.req.week < 1 || 54 < ctl.req.week)
     413  					errx(EXIT_FAILURE,_("illegal week value: use 1-54"));
     414  			}
     415  			ctl.weektype = WEEK_NUM_US;	/* default per weekstart */
     416  			break;
     417  		case OPT_COLOR:
     418  			ctl.colormode = UL_COLORMODE_AUTO;
     419  			if (optarg)
     420  				ctl.colormode = colormode_or_err(optarg,
     421  						_("unsupported color mode"));
     422  			break;
     423  		case OPT_REFORM:
     424  			ctl.reform_year = parse_reform_year(optarg);
     425  			break;
     426  		case OPT_ISO:
     427  			ctl.reform_year = ISO;
     428  			break;
     429  		case 'v':
     430  			ctl.vertical = 1;
     431  			break;
     432  		case 'c':
     433  			if (strcmp(optarg, "auto") == 0)
     434  				cols = COLUMNS_AUTO;
     435  			else
     436  				cols = strtosize_or_err(optarg, "foo");
     437  			break;
     438  		case 'V':
     439  			print_version(EXIT_SUCCESS);
     440  		case 'h':
     441  			usage();
     442  		default:
     443  			errtryhelp(EXIT_FAILURE);
     444  		}
     445  	}
     446  
     447  	argc -= optind;
     448  	argv += optind;
     449  
     450  	if (ctl.weektype) {
     451  		ctl.weektype = ctl.req.week & WEEK_NUM_MASK;
     452  		ctl.weektype |= (ctl.weekstart == MONDAY ? WEEK_NUM_ISO : WEEK_NUM_US);
     453  		ctl.week_width = (ctl.day_width * DAYS_IN_WEEK) + WNUM_LEN;
     454  	} else
     455  		ctl.week_width = ctl.day_width * DAYS_IN_WEEK;
     456  	/*
     457  	 * The day_width includes the space between days,
     458  	 * as there is no leading space, remove 1
     459  	 * */
     460  	ctl.week_width -= 1;
     461  
     462  	if (argc == 1 && !isdigit_string(*argv)) {
     463  		usec_t x;
     464  		/* cal <timestamp> */
     465  		if (parse_timestamp(*argv, &x) == 0)
     466  			now = (time_t) (x / 1000000);
     467  		/* cal <monthname> */
     468  		else if ((ctl.req.month = monthname_to_number(&ctl, *argv)) > 0)
     469  			cal_time(&now);	/* this year */
     470  		else
     471  			errx(EXIT_FAILURE, _("failed to parse timestamp or unknown month name: %s"), *argv);
     472  		argc = 0;
     473  	} else
     474  		cal_time(&now);
     475  
     476  	localtime_r(&now, &local_time);
     477  
     478  	switch(argc) {
     479  	case 3:
     480  		ctl.req.day = strtos32_or_err(*argv++, _("illegal day value"));
     481  		if (ctl.req.day < 1 || DAYS_IN_MONTH < ctl.req.day)
     482  			errx(EXIT_FAILURE, _("illegal day value: use 1-%d"), DAYS_IN_MONTH);
     483  		/* fallthrough */
     484  	case 2:
     485  		if (isdigit(**argv))
     486  			ctl.req.month = strtos32_or_err(*argv++, _("illegal month value: use 1-12"));
     487  		else {
     488  			ctl.req.month = monthname_to_number(&ctl, *argv);
     489  			if (ctl.req.month < 0)
     490  				errx(EXIT_FAILURE, _("unknown month name: %s"), *argv);
     491  			argv++;
     492  		}
     493  		if (ctl.req.month < 1 || MONTHS_IN_YEAR < ctl.req.month)
     494  			errx(EXIT_FAILURE, _("illegal month value: use 1-12"));
     495  		/* fallthrough */
     496  	case 1:
     497  		ctl.req.year = strtos32_or_err(*argv++, _("illegal year value"));
     498  		if (ctl.req.year < SMALLEST_YEAR)
     499  			errx(EXIT_FAILURE, _("illegal year value: use positive integer"));
     500  		if (ctl.req.year == JULIAN)
     501  			errx(EXIT_FAILURE, _("illegal year value"));
     502  		if (ctl.req.day) {
     503  			int dm = days_in_month[leap_year(&ctl, ctl.req.year)]
     504  					      [ctl.req.month];
     505  			if (ctl.req.day > dm)
     506  				errx(EXIT_FAILURE, _("illegal day value: use 1-%d"), dm);
     507  			ctl.req.day = day_in_year(&ctl, ctl.req.day,
     508  						  ctl.req.month, ctl.req.year);
     509  		} else if ((int32_t) (local_time.tm_year + 1900) == ctl.req.year) {
     510  			ctl.req.day = local_time.tm_yday + 1;
     511  		}
     512  		if (!ctl.req.month && !ctl.req.week) {
     513  			ctl.req.month = local_time.tm_mon + 1;
     514  			if (!ctl.num_months)
     515  				yflag = 1;
     516  		}
     517  		break;
     518  	case 0:
     519  		ctl.req.day = local_time.tm_yday + 1;
     520  		ctl.req.year = local_time.tm_year + 1900;
     521  		if (!ctl.req.month)
     522  			ctl.req.month = local_time.tm_mon + 1;
     523  		break;
     524  	default:
     525  		warnx(_("bad usage"));
     526  		errtryhelp(EXIT_FAILURE);
     527  	}
     528  
     529  	if (0 < ctl.req.week) {
     530  		int yday = week_to_day(&ctl);
     531  		int leap = leap_year(&ctl, ctl.req.year);
     532  		int m = 1;
     533  
     534  		if (yday < 1)
     535  			errx(EXIT_FAILURE, _("illegal week value: year %d "
     536  					     "doesn't have week %d"),
     537  					ctl.req.year, ctl.req.week);
     538  		while (m <= DECEMBER && yday > days_in_month[leap][m])
     539  			yday -= days_in_month[leap][m++];
     540  		if (DECEMBER < m && ctl.weektype & WEEK_NUM_ISO) {
     541  			/* In some years (e.g. 2010 in ISO mode) it's possible
     542  			 * to have a remnant of week 53 starting the year yet
     543  			 * the year in question ends during 52, in this case
     544  			 * we're assuming that early remnant is being referred
     545  			 * to if 53 is given as argument. */
     546  			if (ctl.req.week != week_number(31, DECEMBER, ctl.req.year - 1, &ctl))
     547  				errx(EXIT_FAILURE,
     548  					_("illegal week value: year %d "
     549  					  "doesn't have week %d"),
     550  					ctl.req.year, ctl.req.week);
     551  		}
     552  		if (!ctl.req.month)
     553  			ctl.req.month = MONTHS_IN_YEAR < m ? 1 : m;
     554  	}
     555  
     556  	weekdays_init(&ctl);
     557  	headers_init(&ctl);
     558  
     559  	if (colors_init(ctl.colormode, "cal") == 0) {
     560  		/* disable */
     561  		ctl.req.day = 0;
     562  		ctl.weektype &= ~WEEK_NUM_MASK;
     563  	}
     564  
     565  	if (yflag || Yflag) {
     566  		ctl.gutter_width = 3;
     567  		if (!ctl.num_months)
     568  			ctl.num_months = MONTHS_IN_YEAR;
     569  		if (yflag) {
     570  			ctl.req.start_month = 1;	/* start from Jan */
     571  			ctl.header_year = 1;		/* print year number */
     572  		}
     573  	}
     574  
     575  	if (ctl.vertical)
     576  		ctl.gutter_width = 1;
     577  
     578  	if (ctl.num_months > 1 && ctl.months_in_row == 0) {
     579  		ctl.months_in_row = MONTHS_IN_YEAR_ROW;		/* default */
     580  
     581  		if (cols > 0)
     582  			ctl.months_in_row = cols;
     583  		else if (isatty(STDOUT_FILENO)) {
     584  			int w, mw, extra, new_n;
     585  
     586  			w = get_terminal_width(80);
     587  			mw = ctl.julian ? DOY_MONTH_WIDTH : DOM_MONTH_WIDTH;
     588  
     589  			if (w < mw)
     590  				w = mw;
     591  
     592  			extra = ((w / mw) - 1) * ctl.gutter_width;
     593  			new_n = (w - extra) / mw;
     594  
     595  			switch (cols) {
     596  			case COLUMNS_MAX_THREE:
     597  				if (new_n < MONTHS_IN_YEAR_ROW)
     598  					ctl.months_in_row = new_n > 0 ? new_n : 1;
     599  				break;
     600  			case COLUMNS_AUTO:
     601  				ctl.months_in_row = new_n > 0 ? new_n : 1;
     602  				break;
     603  			}
     604  		}
     605  	} else if (!ctl.months_in_row)
     606  		ctl.months_in_row = 1;
     607  
     608  	if (!ctl.num_months)
     609  		ctl.num_months = 1;		/* display at least one month */
     610  
     611  	if (yflag || Yflag)
     612  		yearly(&ctl);
     613  	else
     614  		monthly(&ctl);
     615  
     616  	return EXIT_SUCCESS;
     617  }
     618  
     619  /* leap year -- account for gregorian reformation in 1752 */
     620  static int leap_year(const struct cal_control *ctl, int32_t year)
     621  {
     622  	if (year <= ctl->reform_year)
     623  		return !(year % 4);
     624  
     625  	return ( !(year % 4) && (year % 100) ) || !(year % 400);
     626  }
     627  
     628  static void init_monthnames(struct cal_control *ctl)
     629  {
     630  	size_t i;
     631  
     632  	if (ctl->full_month[0] != NULL)
     633  		return;		/* already initialized */
     634  
     635  	for (i = 0; i < MONTHS_IN_YEAR; i++)
     636  		ctl->full_month[i] = nl_langinfo(ALTMON_1 + i);
     637  }
     638  
     639  static void init_abbr_monthnames(struct cal_control *ctl)
     640  {
     641  	size_t i;
     642  
     643  	if (ctl->abbr_month[0] != NULL)
     644  		return;		/* already initialized */
     645  
     646  	for (i = 0; i < MONTHS_IN_YEAR; i++)
     647  		ctl->abbr_month[i] = nl_langinfo(_NL_ABALTMON_1 + i);
     648  }
     649  
     650  static int monthname_to_number(struct cal_control *ctl, const char *name)
     651  {
     652  	size_t i;
     653  
     654  	init_monthnames(ctl);
     655  	for (i = 0; i < MONTHS_IN_YEAR; i++)
     656  		if (strcasecmp(ctl->full_month[i], name) == 0)
     657  			return i + 1;
     658  
     659  	init_abbr_monthnames(ctl);
     660  	for (i = 0; i < MONTHS_IN_YEAR; i++)
     661  		if (strcasecmp(ctl->abbr_month[i], name) == 0)
     662  			return i + 1;
     663  
     664  	return -EINVAL;
     665  }
     666  
     667  static void weekdays_init(struct cal_control *ctl)
     668  {
     669  	size_t wd;
     670  	int i;
     671  
     672  	for (i = 0; i < DAYS_IN_WEEK; i++) {
     673  		wd = (i + ctl->weekstart) % DAYS_IN_WEEK;
     674  		ctl->weekdays[i] = nl_langinfo(ABDAY_1 + wd);
     675  	}
     676  }
     677  static void headers_init(struct cal_control *ctl)
     678  {
     679  	size_t i;
     680  	char *cur_dh = day_headings;
     681  	char tmp[FMT_ST_CHARS];
     682  	int year_len;
     683  
     684  	year_len = snprintf(tmp, sizeof(tmp), "%04d", ctl->req.year);
     685  
     686  	if (year_len < 0 || (size_t)year_len >= sizeof(tmp)) {
     687  		/* XXX impossible error */
     688  		return;
     689  	}
     690  
     691  	for (i = 0; i < DAYS_IN_WEEK; i++) {
     692  		size_t space_left;
     693  
     694  		if (i)
     695  			strcat(cur_dh++, " ");
     696  		space_left = sizeof(day_headings) - (cur_dh - day_headings);
     697  
     698  		if (space_left <= (ctl->day_width - 1))
     699  			break;
     700  		cur_dh += center_str(ctl->weekdays[i], cur_dh,
     701  				     space_left, ctl->day_width - 1);
     702  	}
     703  
     704  	init_monthnames(ctl);
     705  
     706  	for (i = 0; i < MONTHS_IN_YEAR; i++) {
     707  		/* The +1 after year_len is space in between month and year. */
     708  		if (ctl->week_width < strlen(ctl->full_month[i]) + year_len)
     709  			ctl->header_hint = 1;
     710  	}
     711  }
     712  
     713  static void cal_fill_month(struct cal_month *month, const struct cal_control *ctl)
     714  {
     715  	int first_week_day = day_in_week(ctl, 1, month->month, month->year);
     716  	int month_days;
     717  	int i, j, weeklines = 0;
     718  
     719  	if (ctl->julian)
     720  		j = day_in_year(ctl, 1, month->month, month->year);
     721  	else
     722  		j = 1;
     723  	month_days = j + days_in_month[leap_year(ctl, month->year)][month->month];
     724  
     725  	/* True when Sunday is not first day in the output week. */
     726  	if (ctl->weekstart) {
     727  		first_week_day -= ctl->weekstart;
     728  		if (first_week_day < 0)
     729  			first_week_day = DAYS_IN_WEEK - ctl->weekstart;
     730  		month_days += ctl->weekstart - 1;
     731  	}
     732  
     733  	/* Fill day array. */
     734  	for (i = 0; i < MAXDAYS; i++) {
     735  		if (0 < first_week_day) {
     736  			month->days[i] = SPACE;
     737  			first_week_day--;
     738  			continue;
     739  		}
     740  		if (j < month_days) {
     741  			if (month->year == ctl->reform_year &&
     742  			    month->month == REFORMATION_MONTH &&
     743  			    (j == 3 || j == 247))
     744  				j += NUMBER_MISSING_DAYS;
     745  			month->days[i] = j;
     746  			j++;
     747  			continue;
     748  		}
     749  		month->days[i] = SPACE;
     750  		weeklines++;
     751  	}
     752  
     753  	/* Add week numbers */
     754  	if (ctl->weektype) {
     755  		int weeknum = week_number(1, month->month, month->year, ctl);
     756  		weeklines = MAXDAYS / DAYS_IN_WEEK - weeklines / DAYS_IN_WEEK;
     757  		for (i = 0; i < MAXDAYS / DAYS_IN_WEEK; i++) {
     758  			if (0 < weeklines) {
     759  				if (52 < weeknum)
     760  					weeknum = week_number(month->days[i * DAYS_IN_WEEK], month->month, month->year, ctl);
     761  				month->weeks[i] = weeknum++;
     762  			} else
     763  				month->weeks[i] = SPACE;
     764  			weeklines--;
     765  		}
     766  	}
     767  }
     768  
     769  static void cal_output_header(struct cal_month *month, const struct cal_control *ctl)
     770  {
     771  	char out[FMT_ST_CHARS];
     772  	struct cal_month *i;
     773  
     774  	cal_enable_color(CAL_COLOR_HEADER);
     775  
     776  	if (ctl->header_hint || ctl->header_year) {
     777  		for (i = month; i; i = i->next) {
     778  			snprintf(out, sizeof(out), "%s", ctl->full_month[i->month - 1]);
     779  			center(out, ctl->week_width, i->next == NULL ? 0 : ctl->gutter_width);
     780  		}
     781  		if (!ctl->header_year) {
     782  			fputc('\n', stdout);
     783  			for (i = month; i; i = i->next) {
     784  				snprintf(out, sizeof(out), "%04d", i->year);
     785  				center(out, ctl->week_width, i->next == NULL ? 0 : ctl->gutter_width);
     786  			}
     787  		}
     788  	} else {
     789  		for (i = month; i; i = i->next) {
     790  			snprintf(out, sizeof(out), "%s %04d", ctl->full_month[i->month - 1], i->year);
     791  			center(out, ctl->week_width, i->next == NULL ? 0 : ctl->gutter_width);
     792  		}
     793  	}
     794  	fputc('\n', stdout);
     795  	for (i = month; i; i = i->next) {
     796  		if (ctl->weektype) {
     797  			if (ctl->julian)
     798  				printf("%*s%s", (int)ctl->day_width - 1, "", day_headings);
     799  			else
     800  				printf("%*s%s", (int)ctl->day_width, "", day_headings);
     801  		} else
     802  			fputs(day_headings, stdout);
     803  		if (i->next != NULL)
     804  			printf("%*s", ctl->gutter_width, "");
     805  	}
     806  	cal_disable_color(CAL_COLOR_HEADER);
     807  	fputc('\n', stdout);
     808  }
     809  
     810  static void cal_vert_output_header(struct cal_month *month,
     811  				  const struct cal_control *ctl)
     812  {
     813  	char out[FMT_ST_CHARS];
     814  	struct cal_month *m;
     815  	int month_width;
     816  
     817  	month_width = ctl->day_width * (MAXDAYS / DAYS_IN_WEEK);
     818  
     819  	/* Padding for the weekdays */
     820  	printf("%*s", (int)ctl->day_width + 1, "");
     821  
     822  	if (ctl->header_hint || ctl->header_year) {
     823  		for (m = month; m; m = m->next) {
     824  			snprintf(out, sizeof(out), "%s", ctl->full_month[m->month - 1]);
     825  			left(out, month_width, ctl->gutter_width);
     826  		}
     827  		if (!ctl->header_year) {
     828  			fputc('\n', stdout);
     829  			/* Padding for the weekdays */
     830  			printf("%*s", (int)ctl->day_width + 1, "");
     831  
     832  			for (m = month; m; m = m->next) {
     833  				snprintf(out, sizeof(out), "%04d", m->year);
     834  				left(out, month_width, ctl->gutter_width);
     835  			}
     836  		}
     837  	} else {
     838  		for (m = month; m; m = m->next) {
     839  			snprintf(out, sizeof(out), "%s %04d", ctl->full_month[m->month - 1], m->year);
     840  			left(out, month_width, ctl->gutter_width);
     841  		}
     842  	}
     843  	fputc('\n', stdout);
     844  }
     845  
     846  #define fput_seq(_s)	do { if ((_s) && *(_s)) fputs((_s), stdout); } while(0)
     847  
     848  static void cal_output_months(struct cal_month *month, const struct cal_control *ctl)
     849  {
     850  	int reqday, week_line, d;
     851  	int skip;
     852  	struct cal_month *i;
     853  	int firstwork = ctl->weekstart == SUNDAY ? 1 : 0;	/* first workday in week */
     854  
     855  	/* Let's keep sequence cached rather than search it for each day */
     856  	const char *seq_wo_start = cal_get_color_sequence(CAL_COLOR_WORKDAY);
     857  	const char *seq_wo_end = cal_get_color_disable_sequence(CAL_COLOR_WORKDAY);
     858  	const char *seq_we_start = cal_get_color_sequence(CAL_COLOR_WEEKEND);
     859  	const char *seq_we_end = cal_get_color_disable_sequence(CAL_COLOR_WEEKEND);
     860  
     861  	for (week_line = 0; week_line < MAXDAYS / DAYS_IN_WEEK; week_line++) {
     862  		for (i = month; i; i = i->next) {
     863  			/* Determine the day that should be highlighted. */
     864  			reqday = 0;
     865  			if (i->month == ctl->req.month && i->year == ctl->req.year) {
     866  				if (ctl->julian)
     867  					reqday = ctl->req.day;
     868  				else
     869  					reqday = ctl->req.day + 1 -
     870  						 day_in_year(ctl, 1, i->month,
     871  							     i->year);
     872  			}
     873  
     874  			if (ctl->weektype) {
     875  				if (0 < i->weeks[week_line]) {
     876  					if ((ctl->weektype & WEEK_NUM_MASK) == i->weeks[week_line])
     877  						printf("%s%2d%s",
     878  						       cal_get_color_sequence(CAL_COLOR_WEEKNUMBER),
     879  						       i->weeks[week_line],
     880  						       cal_get_color_disable_sequence(CAL_COLOR_WEEKNUMBER));
     881  					else
     882  						printf("%2d", i->weeks[week_line]);
     883  				} else
     884  					printf("%2s", "");
     885  				skip = ctl->day_width;
     886  			} else
     887  				/* First day of the week is one char narrower than the other days,
     888  				 * unless week number is printed.  */
     889  				skip = ctl->day_width - 1;
     890  
     891  			for (d = DAYS_IN_WEEK * week_line;
     892  			     d < DAYS_IN_WEEK * week_line + DAYS_IN_WEEK; d++) {
     893  
     894  				int workday = d >= DAYS_IN_WEEK * week_line + firstwork &&
     895  					      d <= DAYS_IN_WEEK * week_line + firstwork + 4;
     896  
     897  				if (0 < i->days[d]) {
     898  					fput_seq(workday ? seq_wo_start : seq_we_start);
     899  
     900  					if (reqday == i->days[d])
     901  						printf("%*s%s%*d%s",
     902  							skip - (ctl->julian ? 3 : 2),
     903  							"", cal_get_color_sequence(CAL_COLOR_TODAY), (ctl->julian ? 3 : 2),
     904  							i->days[d], cal_get_color_disable_sequence(CAL_COLOR_TODAY));
     905  					else
     906  						printf("%*d", skip, i->days[d]);
     907  
     908  					fput_seq(workday ? seq_wo_end : seq_we_end);
     909  				} else
     910  					printf("%*s", skip, "");
     911  
     912  				if (skip < (int)ctl->day_width)
     913  					skip++;
     914  			}
     915  			if (i->next != NULL)
     916  				printf("%*s", ctl->gutter_width, "");
     917  		}
     918  		if (i == NULL)
     919  			fputc('\n', stdout);
     920  	}
     921  }
     922  
     923  static void
     924  cal_vert_output_months(struct cal_month *month, const struct cal_control *ctl)
     925  {
     926  	int i, reqday, week, d;
     927  	int skip;
     928  	struct cal_month *m;
     929  
     930  	skip = ctl->day_width;
     931  	for (i = 0; i < DAYS_IN_WEEK; i++) {
     932  		left(ctl->weekdays[i], ctl->day_width - 1, 0);
     933  		for (m = month; m; m = m->next) {
     934  			reqday = 0;
     935  			if (m->month == ctl->req.month && m->year == ctl->req.year) {
     936  				if (ctl->julian) {
     937  					reqday = ctl->req.day;
     938  				} else {
     939  					reqday = ctl->req.day + 1 -
     940  						 day_in_year(ctl, 1, m->month, m->year);
     941  				}
     942  			}
     943  			for (week = 0; week < MAXDAYS / DAYS_IN_WEEK; week++) {
     944  				d = i + DAYS_IN_WEEK * week;
     945  				if (0 < m->days[d]) {
     946  					if (reqday == m->days[d]) {
     947  						printf("%*s%s%*d%s",
     948  						       skip - (ctl->julian ? 3 : 2),
     949  						       "",
     950  						       cal_get_color_sequence(CAL_COLOR_TODAY),
     951  						       (ctl->julian ? 3 : 2),
     952  						       m->days[d],
     953  						       cal_get_color_disable_sequence(CAL_COLOR_TODAY));
     954  					} else {
     955  						printf("%*d",  skip, m->days[d]);
     956  					}
     957  				} else {
     958  					printf("%*s", skip, "");
     959  				}
     960  				skip = ctl->day_width;
     961  			}
     962  			if (m->next != NULL)
     963  				printf("%*s", ctl->gutter_width, "");
     964  		}
     965  		fputc('\n', stdout);
     966  	}
     967  	if (!ctl->weektype)
     968  		return;
     969  
     970  	printf("%*s", (int)ctl->day_width - 1, "");
     971  	for (m = month; m; m = m->next) {
     972  		for (week = 0; week < MAXDAYS / DAYS_IN_WEEK; week++) {
     973  			if (0 < m->weeks[week]) {
     974  				if ((ctl->weektype & WEEK_NUM_MASK) == m->weeks[week])
     975  					printf("%s%*d%s",
     976  						 cal_get_color_sequence(CAL_COLOR_WEEKNUMBER),
     977  						 skip - (ctl->julian ? 3 : 2),
     978  						 m->weeks[week],
     979  						 cal_get_color_disable_sequence(CAL_COLOR_WEEKNUMBER));
     980  				else
     981  					printf("%*d", skip, m->weeks[week]);
     982  			} else
     983  				printf("%*s", skip, "");
     984  		}
     985  		if (m->next != NULL)
     986  			printf("%*s", ctl->gutter_width, "");
     987  	}
     988  	fputc('\n', stdout);
     989  }
     990  
     991  
     992  static void monthly(const struct cal_control *ctl)
     993  {
     994  	struct cal_month *m, *ms;
     995  	int i, rows, month = ctl->req.start_month ? ctl->req.start_month : ctl->req.month;
     996  	int32_t year = ctl->req.year;
     997  
     998  	/* cal -3, cal -Y --span, etc. */
     999  	if (ctl->span_months) {
    1000  		int new_month = month - ctl->num_months / 2;
    1001  		if (new_month < 1) {
    1002  			new_month *= -1;
    1003  			year -= (new_month / MONTHS_IN_YEAR) + 1;
    1004  
    1005  			if (new_month > MONTHS_IN_YEAR)
    1006  				new_month %= MONTHS_IN_YEAR;
    1007  			month = MONTHS_IN_YEAR - new_month;
    1008  		} else
    1009  			month = new_month;
    1010  	}
    1011  
    1012  	ms = xcalloc(ctl->months_in_row, sizeof(*ms));
    1013  
    1014  	for (i = 0; i < ctl->months_in_row - 1; i++)
    1015  		ms[i].next = &ms[i + 1];
    1016  
    1017  	rows = (ctl->num_months - 1) / ctl->months_in_row;
    1018  	for (i = 0; i < rows + 1 ; i++){
    1019  		if (i == rows && ctl->num_months % ctl->months_in_row > 0)
    1020  			for (int n = (ctl->num_months % ctl->months_in_row) - 1; n < ctl->months_in_row; n++)
    1021  				ms[n].next = NULL;
    1022  
    1023  		for (m = ms; m; m = m->next){
    1024  			m->month = month++;
    1025  			m->year = year;
    1026  			if (MONTHS_IN_YEAR < month) {
    1027  				year++;
    1028  				month = 1;
    1029  			}
    1030  			cal_fill_month(m, ctl);
    1031  		}
    1032  		if (ctl->vertical) {
    1033  			if (i > 0)
    1034  				fputc('\n', stdout);		/* Add a line between row */
    1035  
    1036  			cal_vert_output_header(ms, ctl);
    1037  			cal_vert_output_months(ms, ctl);
    1038  		} else {
    1039  			cal_output_header(ms, ctl);
    1040  			cal_output_months(ms, ctl);
    1041  		}
    1042  	}
    1043  	free(ms);
    1044  }
    1045  
    1046  static void yearly(const struct cal_control *ctl)
    1047  {
    1048  	size_t year_width;
    1049  
    1050  	year_width = (size_t) ctl->months_in_row * ctl->week_width
    1051  		     + ((size_t) ctl->months_in_row - 1) * ctl->gutter_width;
    1052  
    1053  	if (ctl->header_year) {
    1054  		char out[FMT_ST_CHARS];
    1055  
    1056  		snprintf(out, sizeof(out), "%04d", ctl->req.year);
    1057  		center(out, year_width, 0);
    1058  		fputs("\n\n", stdout);
    1059  	}
    1060  	monthly(ctl);
    1061  }
    1062  
    1063  /*
    1064   * day_in_year --
    1065   *	return the 1 based day number within the year
    1066   */
    1067  static int day_in_year(const struct cal_control *ctl,
    1068  		       int day, int month, int32_t year)
    1069  {
    1070  	int i, leap;
    1071  
    1072  	leap = leap_year(ctl, year);
    1073  	for (i = 1; i < month; i++)
    1074  		day += days_in_month[leap][i];
    1075  	return day;
    1076  }
    1077  
    1078  /*
    1079   * day_in_week
    1080   *	return the 0 based day number for any date from 1 Jan. 1 to
    1081   *	31 Dec. 9999.  Assumes the Gregorian reformation eliminates
    1082   *	3 Sep. 1752 through 13 Sep. 1752, and returns invalid weekday
    1083   *	during the period of 11 days.
    1084   */
    1085  static int day_in_week(const struct cal_control *ctl, int day,
    1086  		       int month, int32_t year)
    1087  {
    1088  	/*
    1089  	* The magic constants in the reform[] array are, in a simplified
    1090  	* sense, the remaining days after slicing into one week periods the total
    1091  	* days from the beginning of the year to the target month. That is,
    1092  	* weeks + reform[] days gets us to the target month. The exception is,
    1093  	* that for the months past February 'DOY - 1' must be used.
    1094  	*
    1095  	*   DoY (Day of Year): total days to the target month
    1096  	*
    1097  	*   Month            1  2  3  4   5   6   7   8   9  10  11  12
    1098  	*   DoY              0 31 59 90 120 151 181 212 243 273 304 334
    1099  	*   DoY % 7          0  3
    1100  	*   DoY - 1 % 7      - --  2  5   0   3   5   1   4   6   2   4
    1101  	*       reform[] = { 0, 3, 2, 5,  0,  3,  5,  1,  4,  6,  2,  4 };
    1102  	*
    1103  	*  Note: these calculations are for non leap years.
    1104  	*/
    1105  	static const int reform[] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 };
    1106  	static const int old[]    = { 5, 1, 0, 3, 5, 1, 3, 6, 2, 4, 0, 2 };
    1107  
    1108  	if (year != ctl->reform_year + 1)
    1109  		year -= month < MARCH;
    1110  	else
    1111  		year -= (month < MARCH) + 14;
    1112  	if (ctl->reform_year < year
    1113  	    || (year == ctl->reform_year && REFORMATION_MONTH < month)
    1114  	    || (year == ctl->reform_year
    1115  		&& month == REFORMATION_MONTH && 13 < day)) {
    1116  		return ((int64_t) year + (year / 4)
    1117  			- (year / 100) + (year / 400)
    1118  			+ reform[month - 1] + day) % DAYS_IN_WEEK;
    1119  	}
    1120  	if (year < ctl->reform_year
    1121  	    || (year == ctl->reform_year && month < REFORMATION_MONTH)
    1122  	    || (year == ctl->reform_year && month == REFORMATION_MONTH && day < 3))
    1123  		return ((int64_t) year + year / 4 + old[month - 1] + day)
    1124  			% DAYS_IN_WEEK;
    1125  	return NONEDAY;
    1126  }
    1127  
    1128  /*
    1129   * week_number
    1130   *      return the week number of a given date, 1..54.
    1131   *      Supports ISO-8601 and North American modes.
    1132   *      Day may be given as Julian day of the year mode, in which
    1133   *      case the month is disregarded entirely.
    1134   */
    1135  static int week_number(int day, int month, int32_t year, const struct cal_control *ctl)
    1136  {
    1137  	int fday = 0, yday;
    1138  	const int wday = day_in_week(ctl, 1, JANUARY, year);
    1139  
    1140  	if (ctl->weektype & WEEK_NUM_ISO)
    1141  		fday = wday + (wday >= FRIDAY ? -2 : 5);
    1142  	else {
    1143  		/* WEEK_NUM_US: Jan 1 is always First week, that may
    1144  		 * begin previous year.  That means there is very seldom
    1145  		 * more than 52 weeks, */
    1146  		fday = wday + 6;
    1147  	}
    1148  	/* For julian dates the month can be set to 1, the global julian
    1149  	 * variable cannot be relied upon here, because we may recurse
    1150  	 * internally for 31.12. which would not work. */
    1151  	if (day > DAYS_IN_MONTH)
    1152  		month = JANUARY;
    1153  
    1154  	yday = day_in_year(ctl, day, month, year);
    1155  	if (year == ctl->reform_year && yday >= YDAY_AFTER_MISSING)
    1156  		fday -= NUMBER_MISSING_DAYS;
    1157  
    1158  	/* Last year is last year */
    1159  	if (yday + fday < DAYS_IN_WEEK)
    1160  		return week_number(31, DECEMBER, year - 1, ctl);
    1161  
    1162  	/* Or it could be part of the next year.  The reformation year had less
    1163  	 * days than 365 making this check invalid, but reformation year ended
    1164  	 * on Sunday and in week 51, so it's ok here. */
    1165  	if (ctl->weektype == WEEK_NUM_ISO && yday >= 363
    1166  	    && day_in_week(ctl, day, month, year) >= MONDAY
    1167  	    && day_in_week(ctl, day, month, year) <= WEDNESDAY
    1168  	    && day_in_week(ctl, 31, DECEMBER, year) >= MONDAY
    1169  	    && day_in_week(ctl, 31, DECEMBER, year) <= WEDNESDAY)
    1170  		return week_number(1, JANUARY, year + 1, ctl);
    1171  
    1172  	return (yday + fday) / DAYS_IN_WEEK;
    1173  }
    1174  
    1175  /*
    1176   * week_to_day
    1177   *      return the yday of the first day in a given week inside
    1178   *      the given year. This may be something other than Monday
    1179   *      for ISO-8601 modes. For North American numbering this
    1180   *      always returns a Sunday.
    1181   */
    1182  static int week_to_day(const struct cal_control *ctl)
    1183  {
    1184  	int yday, wday;
    1185  
    1186  	wday = day_in_week(ctl, 1, JANUARY, ctl->req.year);
    1187  	yday = ctl->req.week * DAYS_IN_WEEK - wday;
    1188  
    1189  	if (ctl->req.year == ctl->reform_year && yday >= YDAY_AFTER_MISSING)
    1190  		yday += NUMBER_MISSING_DAYS;
    1191  
    1192  	if (ctl->weektype & WEEK_NUM_ISO)
    1193  		yday -= (wday >= FRIDAY ? -2 : 5);
    1194  	else
    1195  		yday -= 6;	/* WEEK_NUM_US */
    1196  	if (yday <= 0)
    1197  		return 1;
    1198  
    1199  	return yday;
    1200  }
    1201  
    1202  /*
    1203   * Center string, handling multibyte characters appropriately.
    1204   * In addition if the string is too large for the width it's truncated.
    1205   * The number of trailing spaces may be 1 less than the number of leading spaces.
    1206   */
    1207  static int center_str(const char* src, char* dest,
    1208  		      size_t dest_size, size_t width)
    1209  {
    1210  	return mbsalign(src, dest, dest_size, &width,
    1211  			MBS_ALIGN_CENTER, MBA_UNIBYTE_FALLBACK);
    1212  }
    1213  
    1214  static void center(const char *str, size_t len, int separate)
    1215  {
    1216  	char lineout[FMT_ST_CHARS];
    1217  
    1218  	center_str(str, lineout, ARRAY_SIZE(lineout), len);
    1219  	fputs(lineout, stdout);
    1220  
    1221  	if (separate)
    1222  		printf("%*s", separate, "");
    1223  }
    1224  static int left_str(const char* src, char* dest,
    1225  		    size_t dest_size, size_t width)
    1226  {
    1227  	return mbsalign(src, dest, dest_size, &width,
    1228  			MBS_ALIGN_LEFT, MBA_UNIBYTE_FALLBACK);
    1229  }
    1230  
    1231  static void left(const char *str, size_t len, int separate)
    1232  {
    1233  	char lineout[FMT_ST_CHARS];
    1234  
    1235  	left_str(str, lineout, sizeof(lineout), len);
    1236  	fputs(lineout, stdout);
    1237  
    1238  	if (separate)
    1239  		printf("%*s", separate, "");
    1240  }
    1241  
    1242  static int parse_reform_year(const char *reform_year)
    1243  {
    1244  	size_t i;
    1245  
    1246  	struct reform {
    1247  		char *name;
    1248  		int val;
    1249  	};
    1250  
    1251  	struct reform years[] = {
    1252  	{"gregorian",	GREGORIAN},
    1253  	{"iso",		ISO},
    1254  	{"1752",	GB1752},
    1255  	{"julian",	JULIAN},
    1256  	};
    1257  
    1258  	for (i = 0; i < ARRAY_SIZE(years); i++) {
    1259  		if (strcasecmp(reform_year, years[i].name) == 0)
    1260  			return years[i].val;
    1261  	}
    1262  	errx(EXIT_FAILURE, "invalid --reform value: '%s'", reform_year);
    1263  }
    1264  
    1265  static void __attribute__((__noreturn__)) usage(void)
    1266  {
    1267  	FILE *out = stdout;
    1268  
    1269  	fputs(USAGE_HEADER, out);
    1270  	fprintf(out, _(" %s [options] [[[day] month] year]\n"), program_invocation_short_name);
    1271  	fprintf(out, _(" %s [options] <timestamp|monthname>\n"), program_invocation_short_name);
    1272  
    1273  	fputs(USAGE_SEPARATOR, out);
    1274  	fputs(_("Display a calendar, or some part of it.\n"), out);
    1275  	fputs(_("Without any arguments, display the current month.\n"), out);
    1276  
    1277  	fputs(USAGE_OPTIONS, out);
    1278  	fputs(_(" -1, --one             show only a single month (default)\n"), out);
    1279  	fputs(_(" -3, --three           show three months spanning the date\n"), out);
    1280  	fputs(_(" -n, --months <num>    show num months starting with date's month\n"), out);
    1281  	fputs(_(" -S, --span            span the date when displaying multiple months\n"), out);
    1282  	fputs(_(" -s, --sunday          Sunday as first day of week\n"), out);
    1283  	fputs(_(" -m, --monday          Monday as first day of week\n"), out);
    1284  	fputs(_(" -j, --julian          use day-of-year for all calendars\n"), out);
    1285  	fputs(_("     --reform <val>    Gregorian reform date (1752|gregorian|iso|julian)\n"), out);
    1286  	fputs(_("     --iso             alias for --reform=iso\n"), out);
    1287  	fputs(_(" -y, --year            show the whole year\n"), out);
    1288  	fputs(_(" -Y, --twelve          show the next twelve months\n"), out);
    1289  	fputs(_(" -w, --week[=<num>]    show US or ISO-8601 week numbers\n"), out);
    1290  	fputs(_(" -v, --vertical        show day vertically instead of line\n"), out);
    1291  	fputs(_(" -c, --columns <width> amount of columns to use\n"), out);
    1292  	fprintf(out,
    1293  	      _("     --color[=<when>]  colorize messages (%s, %s or %s)\n"), "auto", "always", "never");
    1294  	fprintf(out,
    1295  	        "                         %s\n", USAGE_COLORS_DEFAULT);
    1296  
    1297  	fputs(USAGE_SEPARATOR, out);
    1298  	printf(USAGE_HELP_OPTIONS(23));
    1299  	printf(USAGE_MAN_TAIL("cal(1)"));
    1300  
    1301  	exit(EXIT_SUCCESS);
    1302  }