Home | History | Annotate | Line # | Download | only in cal
cal.c revision 1.21
      1 /*	$NetBSD: cal.c,v 1.21 2007/12/19 16:45:41 joerg Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1989, 1993, 1994
      5  *	The Regents of the University of California.  All rights reserved.
      6  *
      7  * This code is derived from software contributed to Berkeley by
      8  * Kim Letkeman.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  * 3. Neither the name of the University nor the names of its contributors
     19  *    may be used to endorse or promote products derived from this software
     20  *    without specific prior written permission.
     21  *
     22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     32  * SUCH DAMAGE.
     33  */
     34 
     35 #include <sys/cdefs.h>
     36 #ifndef lint
     37 __COPYRIGHT("@(#) Copyright (c) 1989, 1993, 1994\n\
     38 	The Regents of the University of California.  All rights reserved.\n");
     39 #endif /* not lint */
     40 
     41 #ifndef lint
     42 #if 0
     43 static char sccsid[] = "@(#)cal.c	8.4 (Berkeley) 4/2/94";
     44 #else
     45 __RCSID("$NetBSD: cal.c,v 1.21 2007/12/19 16:45:41 joerg Exp $");
     46 #endif
     47 #endif /* not lint */
     48 
     49 #include <sys/types.h>
     50 
     51 #include <ctype.h>
     52 #include <err.h>
     53 #include <errno.h>
     54 #include <limits.h>
     55 #include <stdio.h>
     56 #include <stdlib.h>
     57 #include <string.h>
     58 #include <termcap.h>
     59 #include <time.h>
     60 #include <tzfile.h>
     61 #include <unistd.h>
     62 
     63 #define	SATURDAY 		6		/* 1 Jan 1 was a Saturday */
     64 
     65 #define	FIRST_MISSING_DAY 	reform->first_missing_day
     66 #define	NUMBER_MISSING_DAYS 	reform->missing_days
     67 
     68 #define	MAXDAYS			42		/* max slots in a month array */
     69 #define	SPACE			-1		/* used in day array */
     70 
     71 static int days_in_month[2][13] = {
     72 	{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
     73 	{0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
     74 };
     75 
     76 int empty[MAXDAYS] = {
     77 	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,
     78 	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,
     79 	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,
     80 	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,
     81 	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,
     82 	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,
     83 };
     84 int shift_days[2][4][MAXDAYS + 1];
     85 
     86 char *month_names[12] = {
     87 	"January", "February", "March", "April", "May", "June",
     88 	"July", "August", "September", "October", "November", "December",
     89 };
     90 
     91 char *day_headings = " S  M Tu  W Th  F  S";
     92 char *j_day_headings = "  S   M  Tu   W  Th   F   S";
     93 
     94 /* leap years according to the julian calendar */
     95 #define j_leap_year(y, m, d) \
     96 	(((m) > 2) && \
     97 	 !((y) % 4))
     98 
     99 /* leap years according to the gregorian calendar */
    100 #define g_leap_year(y, m, d) \
    101 	(((m) > 2) && \
    102 	 ((!((y) % 4) && ((y) % 100)) || \
    103 	  !((y) % 400)))
    104 
    105 /* leap year -- account for gregorian reformation at some point */
    106 #define	leap_year(yr) \
    107 	((yr) <= reform->year ? j_leap_year((yr), 3, 1) : \
    108 	g_leap_year((yr), 3, 1))
    109 
    110 /* number of julian leap days that have passed by a given date */
    111 #define j_leap_days(y, m, d) \
    112 	((((y) - 1) / 4) + j_leap_year(y, m, d))
    113 
    114 /* number of gregorian leap days that have passed by a given date */
    115 #define g_leap_days(y, m, d) \
    116 	((((y) - 1) / 4) - (((y) - 1) / 100) + (((y) - 1) / 400) + \
    117 	g_leap_year(y, m, d))
    118 
    119 /*
    120  * Subtracting the gregorian leap day count (for a given date) from
    121  * the julian leap day count (for the same date) describes the number
    122  * of days from the date before the shift to the next date that
    123  * appears in the calendar.  Since we want to know the number of
    124  * *missing* days, not the number of days that the shift spans, we
    125  * subtract 2.
    126  *
    127  * Alternately...
    128  *
    129  * There's a reason they call the Dark ages the Dark Ages.  Part of it
    130  * is that we don't have that many records of that period of time.
    131  * One of the reasons for this is that a lot of the Dark Ages never
    132  * actually took place.  At some point in the first millenium A.D., a
    133  * ruler of some power decided that he wanted the number of the year
    134  * to be different than what it was, so he changed it to coincide
    135  * nicely with some event (a birthday or anniversary, perhaps a
    136  * wedding, or maybe a centennial for a largish city).  One of the
    137  * side effects of this upon the Gregorian reform is that two Julian
    138  * leap years (leap days celebrated during centennial years that are
    139  * not quatro-centennial years) were skipped.
    140  */
    141 #define GREGORIAN_MAGIC 2
    142 
    143 /* number of centuries since the reform, not inclusive */
    144 #define	centuries_since_reform(yr) \
    145 	((yr) > reform->year ? ((yr) / 100) - (reform->year / 100) : 0)
    146 
    147 /* number of centuries since the reform whose modulo of 400 is 0 */
    148 #define	quad_centuries_since_reform(yr) \
    149 	((yr) > reform->year ? ((yr) / 400) - (reform->year / 400) : 0)
    150 
    151 /* number of leap years between year 1 and this year, not inclusive */
    152 #define	leap_years_since_year_1(yr) \
    153 	((yr) / 4 - centuries_since_reform(yr) + quad_centuries_since_reform(yr))
    154 
    155 struct reform {
    156 	const char *country;
    157 	int ambiguity, year, month, date;
    158 	long first_missing_day;
    159 	int missing_days;
    160 	/*
    161 	 * That's 2 for standard/julian display, 4 for months possibly
    162 	 * affected by the Gregorian shift, and MAXDAYS + 1 for the
    163 	 * days that get displayed, plus a crib slot.
    164 	 */
    165 } *reform, reforms[] = {
    166 	{ "DEFAULT",		0, 1752,  9,  3 },
    167 	{ "Italy",		1, 1582, 10,  5 },
    168 	{ "Spain",		1, 1582, 10,  5 },
    169 	{ "Portugal",		1, 1582, 10,  5 },
    170 	{ "Poland",		1, 1582, 10,  5 },
    171 	{ "France",		2, 1582, 12, 10 },
    172 	{ "Luxembourg",		2, 1582, 12, 22 },
    173 	{ "Netherlands",	2, 1582, 12, 22 },
    174 	{ "Bavaria",		0, 1583, 10,  6 },
    175 	{ "Austria",		2, 1584,  1,  7 },
    176 	{ "Switzerland",	2, 1584,  1, 12 },
    177 	{ "Hungary",		0, 1587, 10, 22 },
    178 	{ "Germany",		0, 1700,  2, 19 },
    179 	{ "Norway",		0, 1700,  2, 19 },
    180 	{ "Denmark",		0, 1700,  2, 19 },
    181 	{ "Great Britain",	0, 1752,  9,  3 },
    182 	{ "England",		0, 1752,  9,  3 },
    183 	{ "America",		0, 1752,  9,  3 },
    184 	{ "Sweden",		0, 1753,  2, 18 },
    185 	{ "Finland",		0, 1753,  2, 18 },
    186 	{ "Japan",		0, 1872, 12, 20 },
    187 	{ "China",		0, 1911, 11,  7 },
    188 	{ "Bulgaria",		0, 1916,  4,  1 },
    189 	{ "U.S.S.R.",		0, 1918,  2,  1 },
    190 	{ "Serbia",		0, 1919,  1, 19 },
    191 	{ "Romania",		0, 1919,  1, 19 },
    192 	{ "Greece",		0, 1924,  3, 10 },
    193 	{ "Turkey",		0, 1925, 12, 19 },
    194 	{ "Egypt",		0, 1928,  9, 18 },
    195 	{ NULL,			0,    0,  0,  0 },
    196 };
    197 
    198 int julian;
    199 int dow;
    200 int hilite;
    201 char *md, *me;
    202 
    203 void	init_hilite(void);
    204 int	getnum(const char *);
    205 void	gregorian_reform(const char *);
    206 void	reform_day_array(int, int, int *, int *, int *,int *,int *,int *);
    207 int	ascii_day(char *, int);
    208 void	center(char *, int, int);
    209 void	day_array(int, int, int *);
    210 int	day_in_week(int, int, int);
    211 int	day_in_year(int, int, int);
    212 void	monthrange(int, int, int, int, int);
    213 int	main(int, char **);
    214 void	trim_trailing_spaces(char *);
    215 void	usage(void);
    216 
    217 int
    218 main(int argc, char **argv)
    219 {
    220 	struct tm *local_time;
    221 	time_t now;
    222 	int ch, yflag;
    223 	long month, year;
    224 	int before, after, use_reform;
    225 	int yearly = 0;
    226 	char *when, *eoi;
    227 
    228 	before = after = 0;
    229 	use_reform = yflag = year = 0;
    230 	when = NULL;
    231 	while ((ch = getopt(argc, argv, "A:B:d:hjR:ry3")) != -1) {
    232 		switch (ch) {
    233 		case 'A':
    234 			after = getnum(optarg);
    235 			break;
    236 		case 'B':
    237 			before = getnum(optarg);
    238 			break;
    239 		case 'd':
    240 			dow = getnum(optarg);
    241 			if (dow < 0 || dow > 6)
    242 				errx(1, "illegal day of week value: use 0-6");
    243 			break;
    244 		case 'h':
    245 			init_hilite();
    246 			break;
    247 		case 'j':
    248 			julian = 1;
    249 			break;
    250 		case 'R':
    251 			when = optarg;
    252 			break;
    253 		case 'r':
    254 			use_reform = 1;
    255 			break;
    256 		case 'y':
    257 			yflag = 1;
    258 			break;
    259 		case '3':
    260 			before = after = 1;
    261 			break;
    262 		case '?':
    263 		default:
    264 			usage();
    265 			/* NOTREACHED */
    266 		}
    267 	}
    268 
    269 	argc -= optind;
    270 	argv += optind;
    271 
    272 	if (when != NULL)
    273 		gregorian_reform(when);
    274 	if (reform == NULL)
    275 		gregorian_reform("DEFAULT");
    276 
    277 	month = 0;
    278 	switch (argc) {
    279 	case 2:
    280 		month = strtol(*argv++, &eoi, 10);
    281 		if (month < 1 || month > 12 || *eoi != '\0')
    282 			errx(1, "illegal month value: use 1-12");
    283 		year = strtol(*argv, &eoi, 10);
    284 		if (year < 1 || year > 9999 || *eoi != '\0')
    285 			errx(1, "illegal year value: use 1-9999");
    286 		break;
    287 	case 1:
    288 		year = strtol(*argv, &eoi, 10);
    289 		if (year < 1 || year > 9999 || (*eoi != '\0' && *eoi != '/' && *eoi != '-'))
    290 			errx(1, "illegal year value: use 1-9999");
    291 		if (*eoi != '\0') {
    292 			month = strtol(eoi + 1, &eoi, 10);
    293 			if (month < 1 || month > 12 || *eoi != '\0')
    294 				errx(1, "illegal month value: use 1-12");
    295 		}
    296 		break;
    297 	case 0:
    298 		(void)time(&now);
    299 		local_time = localtime(&now);
    300 		if (use_reform)
    301 			year = reform->year;
    302 		else
    303 			year = local_time->tm_year + TM_YEAR_BASE;
    304 		if (!yflag) {
    305 			if (use_reform)
    306 				month = reform->month;
    307 			else
    308 				month = local_time->tm_mon + 1;
    309 		}
    310 		break;
    311 	default:
    312 		usage();
    313 	}
    314 
    315 	if (!month) {
    316 		/* yearly */
    317 		month = 1;
    318 		before = 0;
    319 		after = 11;
    320 		yearly = 1;
    321 	}
    322 
    323 	monthrange(month, year, before, after, yearly);
    324 
    325 	exit(0);
    326 }
    327 
    328 #define	DAY_LEN		3		/* 3 spaces per day */
    329 #define	J_DAY_LEN	4		/* 4 spaces per day */
    330 #define	WEEK_LEN	20		/* 7 * 3 - one space at the end */
    331 #define	J_WEEK_LEN	27		/* 7 * 4 - one space at the end */
    332 #define	HEAD_SEP	2		/* spaces between day headings */
    333 #define	J_HEAD_SEP	2
    334 #define	MONTH_PER_ROW	3		/* how many monthes in a row */
    335 #define	J_MONTH_PER_ROW	2
    336 
    337 void
    338 monthrange(int month, int year, int before, int after, int yearly)
    339 {
    340 	int startmonth, startyear;
    341 	int endmonth, endyear;
    342 	int i, row;
    343 	int days[3][MAXDAYS];
    344 	char lineout[256];
    345 	int inayear;
    346 	int newyear;
    347 	int day_len, week_len, head_sep;
    348 	int month_per_row;
    349 	int skip, r_off, w_off;
    350 
    351 	if (julian) {
    352 		day_len = J_DAY_LEN;
    353 		week_len = J_WEEK_LEN;
    354 		head_sep = J_HEAD_SEP;
    355 		month_per_row = J_MONTH_PER_ROW;
    356 	}
    357 	else {
    358 		day_len = DAY_LEN;
    359 		week_len = WEEK_LEN;
    360 		head_sep = HEAD_SEP;
    361 		month_per_row = MONTH_PER_ROW;
    362 	}
    363 
    364 	month--;
    365 
    366 	startyear = year - (before + 12 - 1 - month) / 12;
    367 	startmonth = 12 - 1 - ((before + 12 - 1 - month) % 12);
    368 	endyear = year + (month + after) / 12;
    369 	endmonth = (month + after) % 12;
    370 
    371 	if (startyear < 0 || endyear > 9999) {
    372 		errx(1, "year should be in 1-9999\n");
    373 	}
    374 
    375 	year = startyear;
    376 	month = startmonth;
    377 	inayear = newyear = (year != endyear || yearly);
    378 	if (inayear) {
    379 		skip = month % month_per_row;
    380 		month -= skip;
    381 	}
    382 	else {
    383 		skip = 0;
    384 	}
    385 
    386 	do {
    387 		if (newyear) {
    388 			(void)snprintf(lineout, sizeof(lineout), "%d", year);
    389 			center(lineout, week_len * month_per_row +
    390 			    head_sep * (month_per_row - 1), 0);
    391 			(void)printf("\n\n");
    392 			newyear = 0;
    393 		}
    394 
    395 		for (i = 0; i < skip; i++)
    396 			center("", week_len, head_sep);
    397 
    398 		for (; i < month_per_row; i++) {
    399 			int sep;
    400 
    401 			if (year == endyear && month + i > endmonth)
    402 				break;
    403 
    404 			sep = (i == month_per_row - 1) ? 0 : head_sep;
    405 			day_array(month + i + 1, year, days[i]);
    406 			if (inayear) {
    407 				center(month_names[month + i], week_len, sep);
    408 			}
    409 			else {
    410 				snprintf(lineout, sizeof(lineout), "%s %d",
    411 				    month_names[month + i], year);
    412 				center(lineout, week_len, sep);
    413 			}
    414 		}
    415 		printf("\n");
    416 
    417 		for (i = 0; i < skip; i++)
    418 			center("", week_len, head_sep);
    419 
    420 		for (; i < month_per_row; i++) {
    421 			int sep;
    422 
    423 			if (year == endyear && month + i > endmonth)
    424 				break;
    425 
    426 			sep = (i == month_per_row - 1) ? 0 : head_sep;
    427 			if (dow) {
    428 				printf("%s ", (julian) ?
    429 				    j_day_headings + 4 * dow :
    430 				    day_headings + 3 * dow);
    431 				printf("%.*s", dow * (julian ? 4 : 3) - 1,
    432 				       (julian) ? j_day_headings : day_headings);
    433 			} else
    434 				printf("%s", (julian) ? j_day_headings : day_headings);
    435 			printf("%*s", sep, "");
    436 		}
    437 		printf("\n");
    438 
    439 		for (row = 0; row < 6; row++) {
    440 			char *p = NULL;
    441 
    442 			memset(lineout, ' ', sizeof(lineout));
    443 			for (i = 0; i < skip; i++) {
    444 				/* nothing */
    445 			}
    446 			w_off = 0;
    447 			for (; i < month_per_row; i++) {
    448 				int col, *dp;
    449 
    450 				if (year == endyear && month + i > endmonth)
    451 					break;
    452 
    453 				p = lineout + i * (week_len + 2) + w_off;
    454 				dp = &days[i][row * 7];
    455 				for (col = 0; col < 7;
    456 				     col++, p += day_len + r_off) {
    457 					r_off = ascii_day(p, *dp++);
    458 					w_off += r_off;
    459 				}
    460 			}
    461 			*p = '\0';
    462 			trim_trailing_spaces(lineout);
    463 			(void)printf("%s\n", lineout);
    464 		}
    465 
    466 		skip = 0;
    467 		month += month_per_row;
    468 		if (month >= 12) {
    469 			month -= 12;
    470 			year++;
    471 			newyear = 1;
    472 		}
    473 	} while (year < endyear || (year == endyear && month <= endmonth));
    474 }
    475 
    476 /*
    477  * day_array --
    478  *	Fill in an array of 42 integers with a calendar.  Assume for a moment
    479  *	that you took the (maximum) 6 rows in a calendar and stretched them
    480  *	out end to end.  You would have 42 numbers or spaces.  This routine
    481  *	builds that array for any month from Jan. 1 through Dec. 9999.
    482  */
    483 void
    484 day_array(int month, int year, int *days)
    485 {
    486 	int day, dw, dm;
    487 	time_t t;
    488 	struct tm *tm;
    489 
    490 	t = time(NULL);
    491 	tm = localtime(&t);
    492 	tm->tm_year += TM_YEAR_BASE;
    493 	tm->tm_mon++;
    494 	tm->tm_yday++; /* jan 1 is 1 for us, not 0 */
    495 
    496 	for (dm = month + year * 12, dw = 0; dw < 4; dw++) {
    497 		if (dm == shift_days[julian][dw][MAXDAYS]) {
    498 			memmove(days, shift_days[julian][dw],
    499 				MAXDAYS * sizeof(int));
    500 			return;
    501 		}
    502 	}
    503 
    504 	memmove(days, empty, MAXDAYS * sizeof(int));
    505 	dm = days_in_month[leap_year(year)][month];
    506 	dw = day_in_week(1, month, year);
    507 	day = julian ? day_in_year(1, month, year) : 1;
    508 	while (dm--) {
    509 		if (hilite && year == tm->tm_year &&
    510 		    (julian ? (day == tm->tm_yday) :
    511 		     (month == tm->tm_mon && day == tm->tm_mday)))
    512 			days[dw++] = SPACE - day++;
    513 		else
    514 			days[dw++] = day++;
    515 	}
    516 }
    517 
    518 /*
    519  * day_in_year --
    520  *	return the 1 based day number within the year
    521  */
    522 int
    523 day_in_year(int day, int month, int year)
    524 {
    525 	int i, leap;
    526 
    527 	leap = leap_year(year);
    528 	for (i = 1; i < month; i++)
    529 		day += days_in_month[leap][i];
    530 	return (day);
    531 }
    532 
    533 /*
    534  * day_in_week
    535  *	return the 0 based day number for any date from 1 Jan. 1 to
    536  *	31 Dec. 9999.  Returns the day of the week of the first
    537  *	missing day for any given Gregorian shift.
    538  */
    539 int
    540 day_in_week(int day, int month, int year)
    541 {
    542 	long temp;
    543 
    544 	temp = (long)(year - 1) * 365 + leap_years_since_year_1(year - 1)
    545 	    + day_in_year(day, month, year);
    546 	if (temp < FIRST_MISSING_DAY)
    547 		return ((temp - dow + 6 + SATURDAY) % 7);
    548 	if (temp >= (FIRST_MISSING_DAY + NUMBER_MISSING_DAYS))
    549 		return (((temp - dow + 6 + SATURDAY) - NUMBER_MISSING_DAYS) % 7);
    550 	return ((FIRST_MISSING_DAY - dow + 6 + SATURDAY) % 7);
    551 }
    552 
    553 int
    554 ascii_day(char *p, int day)
    555 {
    556 	int display, val, rc;
    557 	char *b;
    558 	static char *aday[] = {
    559 		"",
    560 		" 1", " 2", " 3", " 4", " 5", " 6", " 7",
    561 		" 8", " 9", "10", "11", "12", "13", "14",
    562 		"15", "16", "17", "18", "19", "20", "21",
    563 		"22", "23", "24", "25", "26", "27", "28",
    564 		"29", "30", "31",
    565 	};
    566 
    567 	if (day == SPACE) {
    568 		memset(p, ' ', julian ? J_DAY_LEN : DAY_LEN);
    569 		return (0);
    570 	}
    571 	if (day < SPACE) {
    572 		b = p;
    573 		day = SPACE - day;
    574 	} else
    575 		b = NULL;
    576 	if (julian) {
    577 		if ((val = day / 100) != 0) {
    578 			day %= 100;
    579 			*p++ = val + '0';
    580 			display = 1;
    581 		} else {
    582 			*p++ = ' ';
    583 			display = 0;
    584 		}
    585 		val = day / 10;
    586 		if (val || display)
    587 			*p++ = val + '0';
    588 		else
    589 			*p++ = ' ';
    590 		*p++ = day % 10 + '0';
    591 	} else {
    592 		*p++ = aday[day][0];
    593 		*p++ = aday[day][1];
    594 	}
    595 
    596 	rc = 0;
    597 	if (b != NULL) {
    598 		char *t, h[64];
    599 		int l;
    600 
    601 		l = p - b;
    602 		memcpy(h, b, l);
    603 		p = b;
    604 
    605 		if (md != NULL) {
    606 			for (t = md; *t; rc++)
    607 				*p++ = *t++;
    608 			memcpy(p, h, l);
    609 			p += l;
    610 			for (t = me; *t; rc++)
    611 				*p++ = *t++;
    612 		} else {
    613 			for (t = &h[0]; l--; t++) {
    614 				*p++ = *t;
    615 				rc++;
    616 				*p++ = '\b';
    617 				rc++;
    618 				*p++ = *t;
    619 			}
    620 		}
    621 	}
    622 
    623 	*p = ' ';
    624 	return (rc);
    625 }
    626 
    627 void
    628 trim_trailing_spaces(char *s)
    629 {
    630 	char *p;
    631 
    632 	for (p = s; *p; ++p)
    633 		continue;
    634 	while (p > s && isspace((unsigned char)*--p))
    635 		continue;
    636 	if (p > s)
    637 		++p;
    638 	*p = '\0';
    639 }
    640 
    641 void
    642 center(char *str, int len, int separate)
    643 {
    644 
    645 	len -= strlen(str);
    646 	(void)printf("%*s%s%*s", len / 2, "", str, len / 2 + len % 2, "");
    647 	if (separate)
    648 		(void)printf("%*s", separate, "");
    649 }
    650 
    651 /*
    652  * gregorian_reform --
    653  *	Given a description of date on which the Gregorian Reform was
    654  *	applied.  The argument can be any of the "country" names
    655  *	listed in the reforms array (case insensitive) or a date of
    656  *	the form YYYY/MM/DD.  The date and month can be omitted if
    657  *	doing so would not select more than one different built-in
    658  *	reform point.
    659  */
    660 void
    661 gregorian_reform(const char *p)
    662 {
    663 	int year, month, date;
    664 	int i, days, diw, diy;
    665 	char c;
    666 
    667 	i = sscanf(p, "%d%*[/,-]%d%*[/,-]%d%c", &year, &month, &date, &c);
    668 	switch (i) {
    669 	case 4:
    670 		/*
    671 		 * If the character was sscanf()ed, then there's more
    672 		 * stuff than we need.
    673 		 */
    674 		errx(1, "date specifier %s invalid", p);
    675 	case 0:
    676 		/*
    677 		 * Not a form we can sscanf(), so void these, and we
    678 		 * can try matching "country" names later.
    679 		 */
    680 		year = month = date = -1;
    681 		break;
    682 	case 1:
    683 		month = 0;
    684 		/*FALLTHROUGH*/
    685 	case 2:
    686 		date = 0;
    687 		/*FALLTHROUGH*/
    688 	    case 3:
    689 		/*
    690 		 * At last, some sanity checking on the values we were
    691 		 * given.
    692 		 */
    693 		if (year < 1 || year > 9999)
    694 			errx(1, "%d: illegal year value: use 1-9999", year);
    695 		if (i > 1 && (month < 1 || month > 12))
    696 			errx(1, "%d: illegal month value: use 1-12", month);
    697 		if ((i == 3 && date < 1) || date < 0 ||
    698 		    date > days_in_month[1][month])
    699 			/*
    700 			 * What about someone specifying a leap day in
    701 			 * a non-leap year?  Well...that's a tricky
    702 			 * one.  We can't yet *say* whether the year
    703 			 * in question is a leap year.  What if the
    704 			 * date given was, for example, 1700/2/29?  is
    705 			 * that a valid leap day?
    706 			 *
    707 			 * So...we punt, and hope that saying 29 in
    708 			 * the case of February isn't too bad an idea.
    709 			 */
    710 			errx(1, "%d: illegal date value: use 1-%d", date,
    711 			     days_in_month[1][month]);
    712 		break;
    713 	}
    714 
    715 	/*
    716 	 * A complete date was specified, so use the other pope.
    717 	 */
    718 	if (date > 0) {
    719 		static struct reform Goestheveezl;
    720 
    721 		reform = &Goestheveezl;
    722 		reform->country = "Bompzidaize";
    723 		reform->year = year;
    724 		reform->month = month;
    725 		reform->date = date;
    726 	}
    727 
    728 	/*
    729 	 * No date information was specified, so let's try to match on
    730 	 * country name.
    731 	 */
    732 	else if (year == -1) {
    733 		for (reform = &reforms[0]; reform->year; reform++) {
    734 			if (strcasecmp(p, reform->country) == 0)
    735 				break;
    736 		}
    737 	}
    738 
    739 	/*
    740 	 * We have *some* date information, but not a complete date.
    741 	 * Let's see if we have enough to pick a single entry from the
    742 	 * list that's not ambiguous.
    743 	 */
    744 	else {
    745 		for (reform = &reforms[0]; reform->year; reform++) {
    746 			if ((year == 0 || year == reform->year) &&
    747 			    (month == 0 || month == reform->month) &&
    748 			    (date == 0 || month == reform->date))
    749 				break;
    750 		}
    751 
    752 		if (i <= reform->ambiguity)
    753 			errx(1, "%s: ambiguous short reform date specification", p);
    754 	}
    755 
    756 	/*
    757 	 * Oops...we reached the end of the list.
    758 	 */
    759 	if (reform->year == 0)
    760 		errx(1, "reform name %s invalid", p);
    761 
    762 	/*
    763 	 *
    764 	 */
    765 	reform->missing_days =
    766 		j_leap_days(reform->year, reform->month, reform->date) -
    767 		g_leap_days(reform->year, reform->month, reform->date) -
    768 		GREGORIAN_MAGIC;
    769 
    770 	reform->first_missing_day =
    771 		(reform->year - 1) * 365 +
    772 		day_in_year(reform->date, reform->month, reform->year) +
    773 		date +
    774 		j_leap_days(reform->year, reform->month, reform->date);
    775 
    776 	/*
    777 	 * Once we know the day of the week of the first missing day,
    778 	 * skip back to the first of the month's day of the week.
    779 	 */
    780 	diw = day_in_week(reform->date, reform->month, reform->year);
    781 	diw = (diw + 8 - (reform->date % 7)) % 7;
    782 	diy = day_in_year(1, reform->month, reform->year);
    783 
    784 	/*
    785 	 * We might need all four of these (if you switch from Julian
    786 	 * to Gregorian at some point after 9900, you get a gap of 73
    787 	 * days, and that can affect four months), and it doesn't hurt
    788 	 * all that much to precompute them, so there.
    789 	 */
    790 	date = 1;
    791 	days = 0;
    792 	for (i = 0; i < 4; i++)
    793 		reform_day_array(reform->month + i, reform->year,
    794 				 &days, &date, &diw, &diy,
    795 				 shift_days[0][i],
    796 				 shift_days[1][i]);
    797 }
    798 
    799 /*
    800  * reform_day_array --
    801  *	Pre-calculates the given month's calendar (in both "standard"
    802  *	and "julian day" representations) with respect for days
    803  *	skipped during a reform period.
    804  */
    805 void
    806 reform_day_array(int month, int year, int *done, int *date, int *diw, int *diy,
    807 	int *scal, int *jcal)
    808 {
    809 	int mdays;
    810 
    811 	/*
    812 	 * If the reform was in the month of october or later, then
    813 	 * the month number from the caller could "overflow".
    814 	 */
    815 	if (month > 12) {
    816 		month -= 12;
    817 		year++;
    818 	}
    819 
    820 	/*
    821 	 * Erase months, and set crib number.  The crib number is used
    822 	 * later to determine if the month to be displayed is here or
    823 	 * should be built on the fly with the generic routine
    824 	 */
    825 	memmove(scal, empty, MAXDAYS * sizeof(int));
    826 	scal[MAXDAYS] = month + year * 12;
    827 	memmove(jcal, empty, MAXDAYS * sizeof(int));
    828 	jcal[MAXDAYS] = month + year * 12;
    829 
    830 	/*
    831 	 * It doesn't matter what the actual month is when figuring
    832 	 * out if this is a leap year or not, just so long as February
    833 	 * gets the right number of days in it.
    834 	 */
    835 	mdays = days_in_month[g_leap_year(year, 3, 1)][month];
    836 
    837 	/*
    838 	 * Bounce back to the first "row" in the day array, and fill
    839 	 * in any days that actually occur.
    840 	 */
    841 	for (*diw %= 7; (*date - *done) <= mdays; (*date)++, (*diy)++) {
    842 		/*
    843 		 * "date" doesn't get reset by the caller across calls
    844 		 * to this routine, so we can actually tell that we're
    845 		 * looking at April the 41st.  Much easier than trying
    846 		 * to calculate the absolute julian day for a given
    847 		 * date and then checking that.
    848 		 */
    849 		if (*date < reform->date ||
    850 		    *date >= reform->date + reform->missing_days) {
    851 			scal[*diw] = *date - *done;
    852 			jcal[*diw] = *diy;
    853 			(*diw)++;
    854 		}
    855 	}
    856 	*done += mdays;
    857 }
    858 
    859 int
    860 getnum(const char *p)
    861 {
    862 	long result;
    863 	char *ep;
    864 
    865 	errno = 0;
    866 	result = strtoul(p, &ep, 10);
    867 	if (p[0] == '\0' || *ep != '\0')
    868 		goto error;
    869 	if (errno == ERANGE && result == ULONG_MAX)
    870 		goto error;
    871 	if (result > INT_MAX)
    872 		goto error;
    873 
    874 	return (int)result;
    875 
    876 error:
    877 	errx(1, "bad number: %s", p);
    878 	/*NOTREACHED*/
    879 }
    880 
    881 void
    882 init_hilite(void)
    883 {
    884 	static char control[128];
    885 	char cap[1024];
    886 	char *tc;
    887 
    888 	hilite++;
    889 
    890 	if (!isatty(fileno(stdout)))
    891 		return;
    892 
    893 	tc = getenv("TERM");
    894 	if (tc == NULL)
    895 		tc = "dumb";
    896 	if (tgetent(&cap[0], tc) != 1)
    897 		return;
    898 
    899 	tc = &control[0];
    900 	if ((md = tgetstr(hilite > 1 ? "mr" : "md", &tc)))
    901 		*tc++ = '\0';
    902 	if ((me = tgetstr("me", &tc)))
    903 		*tc++ = '\0';
    904 	if (me == NULL || md == NULL)
    905 		md = me = NULL;
    906 }
    907 
    908 void
    909 usage(void)
    910 {
    911 
    912 	(void)fprintf(stderr,
    913 	    "usage: cal [-hjry3] [-d day-of-week] [-B before] [-A after] "
    914 	    "[-R reform-spec]\n           [[month] year]\n");
    915 	exit(1);
    916 }
    917