xref: /netbsd/usr.bin/cal/cal.c (revision c4a72b64)
1 /*	$NetBSD: cal.c,v 1.14 2002/10/25 20:06:56 yamt 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. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *	This product includes software developed by the University of
21  *	California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  */
38 
39 #include <sys/cdefs.h>
40 #ifndef lint
41 __COPYRIGHT("@(#) Copyright (c) 1989, 1993, 1994\n\
42 	The Regents of the University of California.  All rights reserved.\n");
43 #endif /* not lint */
44 
45 #ifndef lint
46 #if 0
47 static char sccsid[] = "@(#)cal.c	8.4 (Berkeley) 4/2/94";
48 #else
49 __RCSID("$NetBSD: cal.c,v 1.14 2002/10/25 20:06:56 yamt Exp $");
50 #endif
51 #endif /* not lint */
52 
53 #include <sys/types.h>
54 
55 #include <ctype.h>
56 #include <err.h>
57 #include <errno.h>
58 #include <limits.h>
59 #include <stdio.h>
60 #include <stdlib.h>
61 #include <string.h>
62 #include <time.h>
63 #include <tzfile.h>
64 #include <unistd.h>
65 
66 #define	THURSDAY		4		/* for reformation */
67 #define	SATURDAY 		6		/* 1 Jan 1 was a Saturday */
68 
69 #define	FIRST_MISSING_DAY 	639799		/* 3 Sep 1752 */
70 #define	NUMBER_MISSING_DAYS 	11		/* 11 day correction */
71 
72 #define	MAXDAYS			42		/* max slots in a month array */
73 #define	SPACE			-1		/* used in day array */
74 
75 static int days_in_month[2][13] = {
76 	{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
77 	{0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
78 };
79 
80 int sep1752[MAXDAYS] = {
81 	SPACE,	SPACE,	1,	2,	14,	15,	16,
82 	17,	18,	19,	20,	21,	22,	23,
83 	24,	25,	26,	27,	28,	29,	30,
84 	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,
85 	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,
86 	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,
87 }, j_sep1752[MAXDAYS] = {
88 	SPACE,	SPACE,	245,	246,	258,	259,	260,
89 	261,	262,	263,	264,	265,	266,	267,
90 	268,	269,	270,	271,	272,	273,	274,
91 	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,
92 	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,
93 	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,
94 }, empty[MAXDAYS] = {
95 	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,
96 	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,
97 	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,
98 	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,
99 	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,
100 	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,
101 };
102 
103 char *month_names[12] = {
104 	"January", "February", "March", "April", "May", "June",
105 	"July", "August", "September", "October", "November", "December",
106 };
107 
108 char *day_headings = " S  M Tu  W Th  F  S";
109 char *j_day_headings = "  S   M  Tu   W  Th   F   S";
110 
111 /* leap year -- account for gregorian reformation in 1752 */
112 #define	leap_year(yr) \
113 	((yr) <= 1752 ? !((yr) % 4) : \
114 	(!((yr) % 4) && ((yr) % 100)) || !((yr) % 400))
115 
116 /* number of centuries since 1700, not inclusive */
117 #define	centuries_since_1700(yr) \
118 	((yr) > 1700 ? (yr) / 100 - 17 : 0)
119 
120 /* number of centuries since 1700 whose modulo of 400 is 0 */
121 #define	quad_centuries_since_1700(yr) \
122 	((yr) > 1600 ? ((yr) - 1600) / 400 : 0)
123 
124 /* number of leap years between year 1 and this year, not inclusive */
125 #define	leap_years_since_year_1(yr) \
126 	((yr) / 4 - centuries_since_1700(yr) + quad_centuries_since_1700(yr))
127 
128 int julian;
129 
130 int	getnum(const char *);
131 void	ascii_day(char *, int);
132 void	center(char *, int, int);
133 void	day_array(int, int, int *);
134 int	day_in_week(int, int, int);
135 int	day_in_year(int, int, int);
136 void	monthrange(int, int, int, int, int);
137 int	main(int, char **);
138 void	trim_trailing_spaces(char *);
139 void	usage(void);
140 
141 int
142 main(int argc, char **argv)
143 {
144 	struct tm *local_time;
145 	time_t now;
146 	int ch, month, year, yflag;
147 	int before, after;
148 	int yearly = 0;
149 
150 	before = after = 0;
151 	yflag = year = 0;
152 	while ((ch = getopt(argc, argv, "A:B:jy3")) != -1) {
153 		switch (ch) {
154 		case 'A':
155 			after = getnum(optarg);
156 			break;
157 		case 'B':
158 			before = getnum(optarg);
159 			break;
160 		case 'j':
161 			julian = 1;
162 			break;
163 		case 'y':
164 			yflag = 1;
165 			break;
166 		case '3':
167 			before = after = 1;
168 			break;
169 		case '?':
170 		default:
171 			usage();
172 			/* NOTREACHED */
173 		}
174 	}
175 
176 	argc -= optind;
177 	argv += optind;
178 
179 	month = 0;
180 	switch (argc) {
181 	case 2:
182 		if ((month = atoi(*argv++)) < 1 || month > 12)
183 			errx(1, "illegal month value: use 1-12");
184 		/* FALLTHROUGH */
185 	case 1:
186 		if ((year = atoi(*argv)) < 1 || year > 9999)
187 			errx(1, "illegal year value: use 1-9999");
188 		break;
189 	case 0:
190 		(void)time(&now);
191 		local_time = localtime(&now);
192 		year = local_time->tm_year + TM_YEAR_BASE;
193 		if (!yflag)
194 			month = local_time->tm_mon + 1;
195 		break;
196 	default:
197 		usage();
198 	}
199 
200 	if (!month) {
201 		/* yearly */
202 		month = 1;
203 		before = 0;
204 		after = 11;
205 		yearly = 1;
206 	}
207 
208 	monthrange(month, year, before, after, yearly);
209 
210 	exit(0);
211 }
212 
213 #define	DAY_LEN		3		/* 3 spaces per day */
214 #define	J_DAY_LEN	4		/* 4 spaces per day */
215 #define	WEEK_LEN	20		/* 7 * 3 - one space at the end */
216 #define	J_WEEK_LEN	27		/* 7 * 4 - one space at the end */
217 #define	HEAD_SEP	2		/* spaces between day headings */
218 #define	J_HEAD_SEP	2
219 #define	MONTH_PER_ROW	3		/* how many monthes in a row */
220 #define	J_MONTH_PER_ROW	2
221 
222 void
223 monthrange(int month, int year, int before, int after, int yearly)
224 {
225 	int startmonth, startyear;
226 	int endmonth, endyear;
227 	int i, row;
228 	int days[3][MAXDAYS];
229 	char lineout[80];
230 	int inayear;
231 	int newyear;
232 	int day_len, week_len, head_sep;
233 	int month_per_row;
234 	int skip;
235 
236 	if (julian) {
237 		day_len = J_DAY_LEN;
238 		week_len = J_WEEK_LEN;
239 		head_sep = J_HEAD_SEP;
240 		month_per_row = J_MONTH_PER_ROW;
241 	}
242 	else {
243 		day_len = DAY_LEN;
244 		week_len = WEEK_LEN;
245 		head_sep = HEAD_SEP;
246 		month_per_row = MONTH_PER_ROW;
247 	}
248 
249 	month--;
250 
251 	startyear = year - (before + 12 - 1 - month) / 12;
252 	startmonth = 12 - 1 - ((before + 12 - 1 - month) % 12);
253 	endyear = year + (month + after) / 12;
254 	endmonth = (month + after) % 12;
255 
256 	if (startyear < 0 || endyear > 9999) {
257 		errx(1, "year should be in 1-9999\n");
258 	}
259 
260 	year = startyear;
261 	month = startmonth;
262 	inayear = newyear = (year != endyear || yearly);
263 	if (inayear) {
264 		skip = month % month_per_row;
265 		month -= skip;
266 	}
267 	else {
268 		skip = 0;
269 	}
270 
271 	do {
272 		if (newyear) {
273 			(void)snprintf(lineout, sizeof(lineout), "%d", year);
274 			center(lineout, week_len * month_per_row +
275 			    head_sep * (month_per_row - 1), 0);
276 			(void)printf("\n\n");
277 			newyear = 0;
278 		}
279 
280 		for (i = 0; i < skip; i++)
281 			center("", week_len, head_sep);
282 
283 		for (; i < month_per_row; i++) {
284 			int sep;
285 
286 			if (year == endyear && month + i > endmonth)
287 				break;
288 
289 			sep = (i == month_per_row - 1) ? 0 : head_sep;
290 			day_array(month + i + 1, year, days[i]);
291 			if (inayear) {
292 				center(month_names[month + i], week_len, sep);
293 			}
294 			else {
295 				snprintf(lineout, sizeof(lineout), "%s %d",
296 				    month_names[month + i], year);
297 				center(lineout, week_len, sep);
298 			}
299 		}
300 		printf("\n");
301 
302 		for (i = 0; i < skip; i++)
303 			center("", week_len, head_sep);
304 
305 		for (; i < month_per_row; i++) {
306 			int sep;
307 
308 			if (year == endyear && month + i > endmonth)
309 				break;
310 
311 			sep = (i == month_per_row - 1) ? 0 : head_sep;
312 			printf("%s%*s",
313 			    (julian) ? j_day_headings : day_headings, sep, "");
314 		}
315 		printf("\n");
316 
317 		memset(lineout, ' ', sizeof(lineout));
318 		for (row = 0; row < 6; row++) {
319 			char *p;
320 			for (i = 0; i < skip; i++) {
321 				p = lineout + i * (week_len + 2);
322 				memset(p, ' ', week_len);
323 			}
324 			for (; i < month_per_row; i++) {
325 				int col, *dp;
326 
327 				if (year == endyear && month + i > endmonth)
328 					break;
329 
330 				p = lineout + i * (week_len + 2);
331 				dp = &days[i][row * 7];
332 				for (col = 0; col < 7; col++, p += day_len)
333 					ascii_day(p, *dp++);
334 			}
335 			*p = '\0';
336 			trim_trailing_spaces(lineout);
337 			(void)printf("%s\n", lineout);
338 		}
339 
340 		skip = 0;
341 		month += month_per_row;
342 		if (month >= 12) {
343 			month -= 12;
344 			year++;
345 			newyear = 1;
346 		}
347 	} while (year < endyear || (year == endyear && month <= endmonth));
348 }
349 
350 /*
351  * day_array --
352  *	Fill in an array of 42 integers with a calendar.  Assume for a moment
353  *	that you took the (maximum) 6 rows in a calendar and stretched them
354  *	out end to end.  You would have 42 numbers or spaces.  This routine
355  *	builds that array for any month from Jan. 1 through Dec. 9999.
356  */
357 void
358 day_array(int month, int year, int *days)
359 {
360 	int day, dw, dm;
361 
362 	if (month == 9 && year == 1752) {
363 		memmove(days,
364 			julian ? j_sep1752 : sep1752, MAXDAYS * sizeof(int));
365 		return;
366 	}
367 	memmove(days, empty, MAXDAYS * sizeof(int));
368 	dm = days_in_month[leap_year(year)][month];
369 	dw = day_in_week(1, month, year);
370 	day = julian ? day_in_year(1, month, year) : 1;
371 	while (dm--)
372 		days[dw++] = day++;
373 }
374 
375 /*
376  * day_in_year --
377  *	return the 1 based day number within the year
378  */
379 int
380 day_in_year(int day, int month, int year)
381 {
382 	int i, leap;
383 
384 	leap = leap_year(year);
385 	for (i = 1; i < month; i++)
386 		day += days_in_month[leap][i];
387 	return (day);
388 }
389 
390 /*
391  * day_in_week
392  *	return the 0 based day number for any date from 1 Jan. 1 to
393  *	31 Dec. 9999.  Assumes the Gregorian reformation eliminates
394  *	3 Sep. 1752 through 13 Sep. 1752.  Returns Thursday for all
395  *	missing days.
396  */
397 int
398 day_in_week(int day, int month, int year)
399 {
400 	long temp;
401 
402 	temp = (long)(year - 1) * 365 + leap_years_since_year_1(year - 1)
403 	    + day_in_year(day, month, year);
404 	if (temp < FIRST_MISSING_DAY)
405 		return ((temp - 1 + SATURDAY) % 7);
406 	if (temp >= (FIRST_MISSING_DAY + NUMBER_MISSING_DAYS))
407 		return (((temp - 1 + SATURDAY) - NUMBER_MISSING_DAYS) % 7);
408 	return (THURSDAY);
409 }
410 
411 void
412 ascii_day(char *p, int day)
413 {
414 	int display, val;
415 	static char *aday[] = {
416 		"",
417 		" 1", " 2", " 3", " 4", " 5", " 6", " 7",
418 		" 8", " 9", "10", "11", "12", "13", "14",
419 		"15", "16", "17", "18", "19", "20", "21",
420 		"22", "23", "24", "25", "26", "27", "28",
421 		"29", "30", "31",
422 	};
423 
424 	if (day == SPACE) {
425 		memset(p, ' ', julian ? J_DAY_LEN : DAY_LEN);
426 		return;
427 	}
428 	if (julian) {
429 		if ((val = day / 100) != 0) {
430 			day %= 100;
431 			*p++ = val + '0';
432 			display = 1;
433 		} else {
434 			*p++ = ' ';
435 			display = 0;
436 		}
437 		val = day / 10;
438 		if (val || display)
439 			*p++ = val + '0';
440 		else
441 			*p++ = ' ';
442 		*p++ = day % 10 + '0';
443 	} else {
444 		*p++ = aday[day][0];
445 		*p++ = aday[day][1];
446 	}
447 	*p = ' ';
448 }
449 
450 void
451 trim_trailing_spaces(char *s)
452 {
453 	char *p;
454 
455 	for (p = s; *p; ++p)
456 		continue;
457 	while (p > s && isspace((unsigned char)*--p))
458 		continue;
459 	if (p > s)
460 		++p;
461 	*p = '\0';
462 }
463 
464 void
465 center(char *str, int len, int separate)
466 {
467 
468 	len -= strlen(str);
469 	(void)printf("%*s%s%*s", len / 2, "", str, len / 2 + len % 2, "");
470 	if (separate)
471 		(void)printf("%*s", separate, "");
472 }
473 
474 int
475 getnum(const char *p)
476 {
477 	long result;
478 	char *ep;
479 
480 	errno = 0;
481 	result = strtoul(p, &ep, 10);
482 	if (p[0] == '\0' || *ep != '\0')
483 		goto error;
484 	if (errno == ERANGE && result == ULONG_MAX)
485 		goto error;
486 	if (result > INT_MAX)
487 		goto error;
488 
489 	return (int)result;
490 
491 error:
492 	errx(1, "bad number: %s", p);
493 	/*NOTREACHED*/
494 }
495 
496 void
497 usage(void)
498 {
499 
500 	(void)fprintf(stderr,
501 	    "usage: cal [-jy3] [-B before] [-A after] [[month] year]\n");
502 	exit(1);
503 }
504