1/*-
2 * Copyright (c) 1997 Wolfgang Helbig
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24 * SUCH DAMAGE.
25 */
26
27#ifndef lint
28static const char rcsid[] =
29  "$FreeBSD: src/usr.bin/ncal/ncal.c,v 1.19 2004/11/23 22:57:17 wollman Exp $";
30#endif /* not lint */
31
32#include <calendar.h>
33#include <ctype.h>
34#include <err.h>
35#include <langinfo.h>
36#include <locale.h>
37#include <stdio.h>
38#include <stdlib.h>
39#include <string.h>
40#include <sysexits.h>
41#include <time.h>
42#include <unistd.h>
43#include <wchar.h>
44
45/* Width of one month with backward compatibility */
46#define MONTH_WIDTH_B_J 27
47#define MONTH_WIDTH_B 20
48
49#define MONTH_WIDTH_J 24
50#define MONTH_WIDTH 18
51
52#define MAX_WIDTH 28
53
54typedef struct date date;
55
56struct monthlines {
57	char name[MAX_WIDTH + 1];
58	char lines[7][MAX_WIDTH + 1];
59	char weeks[MAX_WIDTH + 1];
60};
61
62struct weekdays {
63	char *names[7];
64};
65
66/* The switches from Julian to Gregorian in some countries */
67static struct djswitch {
68	const char *cc;	/* Country code according to ISO 3166 */
69	const char *nm;	/* Name of country */
70	date dt;	/* Last day of Julian calendar */
71} switches[] = {
72	{"AL", "Albania",       {1912, 11, 30}},
73	{"AT", "Austria",       {1583, 10,  5}},
74	{"AU", "Australia",     {1752,  9,  2}},
75	{"BE", "Belgium",       {1582, 12, 14}},
76	{"BG", "Bulgaria",      {1916,  3, 18}},
77	{"CA", "Canada",        {1752,  9,  2}},
78	{"CH", "Switzerland",   {1655,  2, 28}},
79	{"CN", "China",         {1911, 12, 18}},
80	{"CZ", "Czech Republic",{1584,  1,  6}},
81	{"DE", "Germany",       {1700,  2, 18}},
82	{"DK", "Denmark",       {1700,  2, 18}},
83	{"ES", "Spain",         {1582, 10,  4}},
84	{"FI", "Finland",       {1753,  2, 17}},
85	{"FR", "France",        {1582, 12,  9}},
86	{"GB", "United Kingdom",{1752,  9,  2}},
87	{"GR", "Greece",        {1924,  3,  9}},
88	{"HU", "Hungary",       {1587, 10, 21}},
89	{"IS", "Iceland",       {1700, 11, 16}},
90	{"IT", "Italy",         {1582, 10,  4}},
91	{"JP", "Japan",         {1918, 12, 18}},
92	{"LI", "Lithuania",     {1918,  2,  1}},
93	{"LN", "Latin",         {9999, 05, 31}},
94	{"LU", "Luxembourg",    {1582, 12, 14}},
95	{"LV", "Latvia",        {1918,  2,  1}},
96	{"NL", "Netherlands",   {1582, 12, 14}},
97	{"NO", "Norway",        {1700,  2, 18}},
98	{"PL", "Poland",        {1582, 10,  4}},
99	{"PT", "Portugal",      {1582, 10,  4}},
100	{"RO", "Romania",       {1919,  3, 31}},
101	{"RU", "Russia",        {1918,  1, 31}},
102	{"SI", "Slovenia",      {1919,  3,  4}},
103	{"SW", "Sweden",        {1753,  2, 17}},
104	{"TR", "Turkey",        {1926, 12, 18}},
105	{"US", "United States", {1752,  9,  2}},
106	{"YU", "Yugoslavia",    {1919,  3,  4}}
107};
108
109struct djswitch *dftswitch =
110    switches + sizeof(switches) / sizeof(struct djswitch) - 2;
111    /* default switch (should be "US") */
112
113/* Table used to print day of month and week numbers */
114char daystr[] = "     1  2  3  4  5  6  7  8  9 10 11 12 13 14 15"
115		" 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31"
116		" 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47"
117		" 48 49 50 51 52 53";
118
119/* Table used to print day of year and week numbers */
120char jdaystr[] = "       1   2   3   4   5   6   7   8   9"
121		 "  10  11  12  13  14  15  16  17  18  19"
122		 "  20  21  22  23  24  25  26  27  28  29"
123		 "  30  31  32  33  34  35  36  37  38  39"
124		 "  40  41  42  43  44  45  46  47  48  49"
125		 "  50  51  52  53  54  55  56  57  58  59"
126		 "  60  61  62  63  64  65  66  67  68  69"
127		 "  70  71  72  73  74  75  76  77  78  79"
128		 "  80  81  82  83  84  85  86  87  88  89"
129		 "  90  91  92  93  94  95  96  97  98  99"
130		 " 100 101 102 103 104 105 106 107 108 109"
131		 " 110 111 112 113 114 115 116 117 118 119"
132		 " 120 121 122 123 124 125 126 127 128 129"
133		 " 130 131 132 133 134 135 136 137 138 139"
134		 " 140 141 142 143 144 145 146 147 148 149"
135		 " 150 151 152 153 154 155 156 157 158 159"
136		 " 160 161 162 163 164 165 166 167 168 169"
137		 " 170 171 172 173 174 175 176 177 178 179"
138		 " 180 181 182 183 184 185 186 187 188 189"
139		 " 190 191 192 193 194 195 196 197 198 199"
140		 " 200 201 202 203 204 205 206 207 208 209"
141		 " 210 211 212 213 214 215 216 217 218 219"
142		 " 220 221 222 223 224 225 226 227 228 229"
143		 " 230 231 232 233 234 235 236 237 238 239"
144		 " 240 241 242 243 244 245 246 247 248 249"
145		 " 250 251 252 253 254 255 256 257 258 259"
146		 " 260 261 262 263 264 265 266 267 268 269"
147		 " 270 271 272 273 274 275 276 277 278 279"
148		 " 280 281 282 283 284 285 286 287 288 289"
149		 " 290 291 292 293 294 295 296 297 298 299"
150		 " 300 301 302 303 304 305 306 307 308 309"
151		 " 310 311 312 313 314 315 316 317 318 319"
152		 " 320 321 322 323 324 325 326 327 328 329"
153		 " 330 331 332 333 334 335 336 337 338 339"
154		 " 340 341 342 343 344 345 346 347 348 349"
155		 " 350 351 352 353 354 355 356 357 358 359"
156		 " 360 361 362 363 364 365 366";
157
158int     flag_weeks;		/* user wants number of week */
159int     nswitch;		/* user defined switch date */
160int	nswitchb;		/* switch date for backward compatibility */
161
162char   *center(char *s, char *t, int w, int r);
163char   *leftjustify(char *s, char *t, int w);
164void	mkmonth(int year, int month, int jd_flag, struct monthlines * monthl);
165void    mkmonthb(int year, int month, int jd_flag, struct monthlines * monthl);
166void    mkweekdays(struct weekdays * wds);
167int     parsemonth(const char *s);
168void    printcc(void);
169void    printeaster(int year, int julian, int orthodox);
170void    printmonth(int year, int month, int jd_flag);
171void    printmonthb(int year, int month, int jd_flag);
172void    printyear(int year, int jd_flag);
173void    printyearb(int year, int jd_flag);
174int	firstday(int y, int m);
175date   *sdate(int ndays, struct date * d);
176date   *sdateb(int ndays, struct date * d);
177int     sndays(struct date * d);
178int     sndaysb(struct date * d);
179static void usage(void);
180int     weekdayb(int nd);
181
182int
183main(int argc, char *argv[])
184{
185	struct  djswitch *p, *q;	/* to search user defined switch date */
186	date	never = {10000, 1, 1};	/* outside valid range of dates */
187	date	ukswitch = {1752, 9, 2};/* switch date for Great Britain */
188	int     ch;			/* holds the option character */
189	int     m = 0;			/* month */
190	int	y = 0;			/* year */
191	int     flag_backward = 0;	/* user called cal--backward compat. */
192	int     flag_hole_year = 0;	/* user wants the whole year */
193	int	flag_julian_cal = 0;	/* user wants Julian Calendar */
194	int     flag_julian_day = 0;	/* user wants the Julian day
195					 * numbers */
196	int	flag_orthodox = 0;	/* use wants Orthodox easter */
197	int	flag_easter = 0;	/* use wants easter date */
198	char	*cp;			/* character pointer */
199	char	*flag_month = NULL;	/* requested month as string */
200	const char    *locale;		/* locale to get country code */
201
202	/*
203	 * Use locale to determine the country code,
204	 * and use the country code to determine the default
205	 * switchdate and date format from the switches table.
206	 */
207	if (setlocale(LC_ALL, "") == NULL)
208		warn("setlocale");
209	locale = setlocale(LC_TIME, NULL);
210	if (locale == NULL ||
211	    strcmp(locale, "C") == 0 ||
212	    strcmp(locale, "POSIX") == 0 ||
213	    strcmp(locale, "ASCII") == 0 ||
214	    strcmp(locale, "US-ASCII") == 0)
215		locale = "_US";
216	q = switches + sizeof(switches) / sizeof(struct djswitch);
217	for (p = switches; p != q; p++)
218		if ((cp = strstr(locale, p->cc)) != NULL && *(cp - 1) == '_')
219			break;
220	if (p == q) {
221		nswitch = ndaysj(&dftswitch->dt);
222	} else {
223		nswitch = ndaysj(&p->dt);
224		dftswitch = p;
225	}
226
227
228	/*
229	 * Get the filename portion of argv[0] and set flag_backward if
230	 * this program is called "cal".
231	 */
232	cp = strrchr(argv[0], '/');
233	cp = (cp == NULL) ? argv[0] : cp + 1;
234	if (strcmp("cal", cp) == 0)
235		flag_backward = 1;
236
237	/* Set the switch date to United Kingdom if backwards compatible */
238	if (flag_backward)
239		nswitchb = ndaysj(&ukswitch);
240
241	while ((ch = getopt(argc, argv, "Jejm:ops:wy")) != -1)
242		switch (ch) {
243		case 'J':
244			if (flag_backward)
245				usage();
246			nswitch = ndaysj(&never);
247			flag_julian_cal = 1;
248			break;
249		case 'e':
250			if (flag_backward)
251				usage();
252			flag_easter = 1;
253			break;
254		case 'j':
255			flag_julian_day = 1;
256			break;
257		case 'm':
258			flag_month = optarg;
259			break;
260		case 'o':
261			if (flag_backward)
262				usage();
263			flag_orthodox = 1;
264			flag_easter = 1;
265			break;
266		case 'p':
267			if (flag_backward)
268				usage();
269			printcc();
270			return (0);
271			break;
272		case 's':
273			if (flag_backward)
274				usage();
275			q = switches +
276			    sizeof(switches) / sizeof(struct djswitch);
277			for (p = switches;
278			     p != q && strcmp(p->cc, optarg) != 0; p++)
279				;
280			if (p == q)
281				errx(EX_USAGE,
282				    "%s: invalid country code", optarg);
283			nswitch = ndaysj(&(p->dt));
284			break;
285		case 'w':
286			if (flag_backward)
287				usage();
288			flag_weeks = 1;
289			break;
290		case 'y':
291			flag_hole_year = 1;
292			break;
293		default:
294			usage();
295		}
296
297	argc -= optind;
298	argv += optind;
299
300	switch (argc) {
301	case 2:
302		if (flag_easter)
303			usage();
304		flag_month = *argv++;
305		/* FALLTHROUGH */
306	case 1:
307		y = atoi(*argv++);
308		if (y < 1 || y > 9999)
309			errx(EX_USAGE, "year %d not in range 1..9999", y);
310		break;
311	case 0:
312		{
313			time_t t;
314			struct tm *tm;
315
316			t = time(NULL);
317			tm = localtime(&t);
318			y = tm->tm_year + 1900;
319			m = tm->tm_mon + 1;
320		}
321		break;
322	default:
323		usage();
324	}
325
326	if (flag_month != NULL) {
327		m = parsemonth(flag_month);
328		if (m < 1 || m > 12)
329			errx(EX_USAGE,
330			    "%s is neither a month number (1..12) nor a name",
331			    flag_month);
332	}
333
334	if (flag_easter)
335		printeaster(y, flag_julian_cal, flag_orthodox);
336	else if (argc == 1 || flag_hole_year)
337		if (flag_backward)
338			printyearb(y, flag_julian_day);
339		else
340			printyear(y, flag_julian_day);
341	else
342		if (flag_backward)
343			printmonthb(y, m, flag_julian_day);
344		else
345			printmonth(y, m, flag_julian_day);
346
347	return (0);
348}
349
350static void
351usage(void)
352{
353
354	fputs(
355	    "usage: cal [-jy] [[month] year]\n"
356	    "       cal [-j] [-m month] [year]\n"
357	    "       ncal [-Jjpwy] [-s country_code] [[month] year]\n"
358	    "       ncal [-Jeo] [year]\n", stderr);
359	exit(EX_USAGE);
360}
361
362/* print the assumed switches for all countries */
363void
364printcc(void)
365{
366	struct djswitch *p;
367	int n;	/* number of lines to print */
368	int m;	/* offset from left to right table entry on the same line */
369
370#define FSTR "%c%s %-15s%4d-%02d-%02d"
371#define DFLT(p) ((p) == dftswitch ? '*' : ' ')
372#define FSTRARG(p) DFLT(p), (p)->cc, (p)->nm, (p)->dt.y, (p)->dt.m, (p)->dt.d
373
374	n = sizeof(switches) / sizeof(struct djswitch);
375	m = (n + 1) / 2;
376	n /= 2;
377	for (p = switches; p != switches + n; p++)
378		printf(FSTR"     "FSTR"\n", FSTRARG(p), FSTRARG(p+m));
379	if (m != n)
380		printf(FSTR"\n", FSTRARG(p));
381}
382
383/* print the date of easter sunday */
384void
385printeaster(int y, int julian, int orthodox)
386{
387	date    dt;
388	struct tm tm;
389	char    buf[80];
390	static int d_first = -1;
391
392	if (d_first < 0)
393		d_first = (*nl_langinfo(D_MD_ORDER) == 'd');
394	/* force orthodox easter for years before 1583 */
395	if (y < 1583)
396		orthodox = 1;
397
398	if (orthodox)
399		if (julian)
400			easteroj(y, &dt);
401		else
402			easterog(y, &dt);
403	else
404		easterg(y, &dt);
405
406	memset(&tm, 0, sizeof(tm));
407	tm.tm_year = dt.y - 1900;
408	tm.tm_mon  = dt.m - 1;
409	tm.tm_mday = dt.d;
410	strftime(buf, sizeof(buf), d_first ? "%e %B %Y" : "%B %e %Y",  &tm);
411	printf("%s\n", buf);
412}
413
414void
415printmonth(int y, int m, int jd_flag)
416{
417	struct monthlines month;
418	struct weekdays wds;
419	int i;
420
421	mkmonth(y, m - 1, jd_flag, &month);
422	mkweekdays(&wds);
423	printf("    %s %d\n", month.name, y);
424	for (i = 0; i != 7; i++) {
425		printf("%s%s\n", wds.names[i], month.lines[i]);
426		free(wds.names[i]);
427	}
428	if (flag_weeks)
429		printf("  %s\n", month.weeks);
430}
431
432void
433printmonthb(int y, int m, int jd_flag)
434{
435	struct monthlines month;
436	struct weekdays wds;
437	char s[MAX_WIDTH], t[MAX_WIDTH];
438	int i;
439	int mw;
440
441	mkmonthb(y, m - 1, jd_flag, &month);
442	mkweekdays(&wds);
443
444	mw = jd_flag ? MONTH_WIDTH_B_J : MONTH_WIDTH_B;
445
446	sprintf(s, "%s %d", month.name, y);
447	printf("%s\n", center(t, s, mw, 0));
448
449	if (jd_flag)
450		printf(" %s  %s  %s  %s  %s  %s  %s\n", wds.names[6],
451			wds.names[0], wds.names[1], wds.names[2], wds.names[3],
452			wds.names[4], wds.names[5]);
453	else
454		printf("%s %s %s %s %s %s %s\n", wds.names[6], wds.names[0],
455			wds.names[1], wds.names[2], wds.names[3],
456			wds.names[4], wds.names[5]);
457
458	for (i = 0; i != 7; i++)
459		free(wds.names[i]);
460	for (i = 0; i != 6; i++)
461		printf("%s\n", month.lines[i]+1);
462}
463
464void
465printyear(int y, int jd_flag)
466{
467	struct monthlines year[12];
468	struct weekdays wds;
469	char    s[80], t[80];
470	int     i, j;
471	int     mpl;
472	int     mw;
473
474	for (i = 0; i != 12; i++)
475		mkmonth(y, i, jd_flag, year + i);
476	mkweekdays(&wds);
477	mpl = jd_flag ? 3 : 4;
478	mw = jd_flag ? MONTH_WIDTH_J : MONTH_WIDTH;
479
480	sprintf(s, "%d", y);
481	printf("%s\n", center(t, s, mpl * mw, 0));
482
483	for (j = 0; j != 12; j += mpl) {
484		char a[80], b[80], c[80];
485		printf("    %s%s",
486		    leftjustify(a, year[j].name, mw),
487		    leftjustify(b, year[j + 1].name, mw));
488		if (mpl == 3)
489			printf("%s\n", year[j + 2].name);
490		else
491			printf("%s%s\n",
492			    leftjustify(a, year[j + 2].name, mw),
493			    year[j + 3].name);
494		for (i = 0; i != 7; i++) {
495			printf("%s%s%s",
496			    wds.names[i],
497			    leftjustify(a, year[j].lines[i], mw),
498			    leftjustify(b, year[j + 1].lines[i], mw));
499			if (mpl == 3)
500				printf("%s\n", year[j + 2].lines[i]);
501			else
502				printf("%s%s\n",
503			    	    leftjustify(a, year[j + 2].lines[i], mw),
504			    	    year[j + 3].lines[i]);
505		}
506		if (flag_weeks) {
507			if (mpl == 3)
508				printf("  %s%s%s\n",
509				    leftjustify(a, year[j].weeks, mw),
510				    leftjustify(b, year[j + 1].weeks, mw),
511				    year[j + 2].weeks);
512			else
513				printf("  %s%s%s%s\n",
514				    leftjustify(a, year[j].weeks, mw),
515				    leftjustify(b, year[j + 1].weeks, mw),
516				    leftjustify(c, year[j + 2].weeks, mw),
517				    year[j + 3].weeks);
518		}
519	}
520	for (i = 0; i != 7; i++)
521		free(wds.names[i]);
522}
523
524void
525printyearb(int y, int jd_flag)
526{
527	struct monthlines year[12];
528	struct weekdays wds;
529	char	s[80], t[80];
530	int     i, j;
531	int     mpl;
532	int     mw;
533
534	for (i = 0; i != 12; i++)
535		mkmonthb(y, i, jd_flag, year + i);
536	mkweekdays(&wds);
537	mpl = jd_flag ? 2 : 3;
538	mw = jd_flag ? MONTH_WIDTH_B_J : MONTH_WIDTH_B;
539
540	sprintf(s, "%d", y);
541	printf("%s\n\n", center(t, s, mw * mpl + mpl, 0));
542
543	for (j = 0; j != 12; j += mpl) {
544		printf("%s  ", center(s, year[j].name, mw, 1));
545		if (mpl == 2)
546			printf("%s\n", center(s, year[j + 1].name, mw, 0));
547		else
548			printf("%s  %s\n",
549			    center(s, year[j + 1].name, mw, 1),
550			    center(t, year[j + 2].name, mw, 0));
551
552		if (mpl == 2)
553			printf(" %s  %s  %s  %s  %s  %s  %s  "
554			       " %s  %s  %s  %s  %s  %s  %s\n",
555				wds.names[6], wds.names[0], wds.names[1],
556				wds.names[2], wds.names[3], wds.names[4],
557				wds.names[5],
558				wds.names[6], wds.names[0], wds.names[1],
559				wds.names[2], wds.names[3], wds.names[4],
560				wds.names[5]);
561		else
562			printf("%s %s %s %s %s %s %s  "
563				"%s %s %s %s %s %s %s  "
564				"%s %s %s %s %s %s %s\n",
565				wds.names[6], wds.names[0], wds.names[1],
566				wds.names[2], wds.names[3], wds.names[4],
567				wds.names[5],
568				wds.names[6], wds.names[0], wds.names[1],
569				wds.names[2], wds.names[3], wds.names[4],
570				wds.names[5],
571				wds.names[6], wds.names[0], wds.names[1],
572				wds.names[2], wds.names[3], wds.names[4],
573				wds.names[5]);
574		for (i = 0; i != 6; i++) {
575			if (mpl == 2)
576				printf("%-*s  %s\n",
577			    mw, year[j].lines[i]+1,
578			    year[j + 1].lines[i]+1);
579			else
580				printf("%-*s  %-*s  %s\n",
581			    mw, year[j].lines[i]+1,
582			    mw, year[j + 1].lines[i]+1,
583			    year[j + 2].lines[i]+1);
584
585		}
586	}
587	for (i = 0; i != 7; i++)
588		free(wds.names[i]);
589}
590
591void
592mkmonth(int y, int m, int jd_flag, struct monthlines *mlines)
593{
594
595	struct tm tm;		/* for strftime printing local names of
596				 * months */
597	date    dt;		/* handy date */
598	int     dw;		/* width of numbers */
599	int     first;		/* first day of month */
600	int     firstm;		/* first day of first week of month */
601	int     i, j, k;	/* just indices */
602	int     last;		/* the first day of next month */
603	int     jan1 = 0;	/* the first day of this year */
604	char   *ds;		/* pointer to day strings (daystr or
605				 * jdaystr) */
606	wchar_t *wcs;
607	int len;
608
609	/* Set name of month. */
610	memset(&tm, 0, sizeof(tm));
611	tm.tm_mon = m;
612	strftime(mlines->name, sizeof(mlines->name), "%B", &tm);
613
614	len = mbstowcs(NULL, mlines->name, 0);
615	wcs = calloc(len + 1, sizeof(wchar_t));
616	mbstowcs(wcs, mlines->name, len);
617	wcs[0] = towupper(wcs[0]);
618	wcstombs(mlines->name, wcs, sizeof(mlines->name));
619	free(wcs);
620
621	/*
622	 * Set first and last to the day number of the first day of this
623	 * month and the first day of next month respectively. Set jan1 to
624	 * the day number of the first day of this year.
625	 */
626	first = firstday(y, m + 1);
627	if (m == 11)
628		last = firstday(y + 1, 1);
629	else
630		last = firstday(y, m + 2);
631
632	if (jd_flag)
633		jan1 = firstday(y, 1);
634
635	/*
636	 * Set firstm to the day number of monday of the first week of
637	 * this month. (This might be in the last month)
638	 */
639	firstm = first - weekday(first);
640
641	/* Set ds (daystring) and dw (daywidth) according to the jd_flag */
642	if (jd_flag) {
643		ds = jdaystr;
644		dw = 4;
645	} else {
646		ds = daystr;
647		dw = 3;
648	}
649
650	/*
651	 * Fill the lines with day of month or day of year (julian day)
652	 * line index: i, each line is one weekday. column index: j, each
653	 * column is one day number. print column index: k.
654	 */
655	for (i = 0; i != 7; i++) {
656		for (j = firstm + i, k = 0; j < last; j += 7, k += dw)
657			if (j >= first) {
658				if (jd_flag)
659					dt.d = j - jan1 + 1;
660				else
661					sdate(j, &dt);
662				memcpy(mlines->lines[i] + k,
663				       ds + dt.d * dw, dw);
664			} else
665				memcpy(mlines->lines[i] + k, "    ", dw);
666		mlines->lines[i][k] = '\0';
667
668	}
669
670	/* fill the weeknumbers */
671	if (flag_weeks) {
672		for (j = firstm, k = 0; j < last;  k += dw, j += 7)
673			if (j <= nswitch)
674				memset(mlines->weeks + k, ' ', dw);
675			else
676				memcpy(mlines->weeks + k,
677				    ds + week(j, &i)*dw, dw);
678		mlines->weeks[k] = '\0';
679	}
680}
681
682void
683mkmonthb(int y, int m, int jd_flag, struct monthlines *mlines)
684{
685
686	struct tm tm;		/* for strftime printing local names of
687				 * months */
688	date    dt;		/* handy date */
689	int     dw;		/* width of numbers */
690	int     first;		/* first day of month */
691	int     firsts;		/* sunday of first week of month */
692	int     i, j, k;	/* just indices */
693	int     jan1 = 0;	/* the first day of this year */
694	int     last;		/* the first day of next month */
695	char   *ds;		/* pointer to day strings (daystr or
696				 * jdaystr) */
697
698	/* Set ds (daystring) and dw (daywidth) according to the jd_flag */
699	if (jd_flag) {
700		ds = jdaystr;
701		dw = 4;
702	} else {
703		ds = daystr;
704		dw = 3;
705	}
706
707	/* Set name of month centered */
708	memset(&tm, 0, sizeof(tm));
709	tm.tm_mon = m;
710	strftime(mlines->name, sizeof(mlines->name), "%B", &tm);
711
712        wchar_t ws[MAX_WIDTH+1];
713        size_t len = mbstowcs(ws, mlines->name, MAX_WIDTH);
714        if (len != -1) {
715                ws[0] = towupper(ws[0]);
716                (void)wcstombs(mlines->name, ws, sizeof(mlines->name));
717        }
718
719	/*
720	 * Set first and last to the day number of the first day of this
721	 * month and the first day of next month respectively. Set jan1 to
722	 * the day number of Jan 1st of this year.
723	 */
724	dt.y = y;
725	dt.m = m + 1;
726	dt.d = 1;
727	first = sndaysb(&dt);
728	if (m == 11) {
729		dt.y = y + 1;
730		dt.m = 1;
731		dt.d = 1;
732	} else {
733		dt.y = y;
734		dt.m = m + 2;
735		dt.d = 1;
736	}
737	last = sndaysb(&dt);
738
739	if (jd_flag) {
740		dt.y = y;
741		dt.m = 1;
742		dt.d = 1;
743		jan1 = sndaysb(&dt);
744	}
745
746	/*
747	 * Set firsts to the day number of sunday of the first week of
748	 * this month. (This might be in the last month)
749	 */
750	firsts = first - (weekday(first)+1) % 7;
751
752	/*
753	 * Fill the lines with day of month or day of year (Julian day)
754	 * line index: i, each line is one week. column index: j, each
755	 * column is one day number. print column index: k.
756	 */
757	for (i = 0; i != 6; i++) {
758		for (j = firsts + 7 * i, k = 0; j < last && k != dw * 7;
759		     j++, k += dw)
760			if (j >= first) {
761				if (jd_flag)
762					dt.d = j - jan1 + 1;
763				else
764					sdateb(j, &dt);
765				memcpy(mlines->lines[i] + k,
766				       ds + dt.d * dw, dw);
767			} else
768				memcpy(mlines->lines[i] + k, "    ", dw);
769		if (k == 0)
770			mlines->lines[i][1] = '\0';
771		else
772			mlines->lines[i][k] = '\0';
773	}
774}
775
776/* Put the local names of weekdays into the wds */
777void
778mkweekdays(struct weekdays *wds)
779{
780	int i, len;
781	struct tm tm;
782	char buf[20];
783	int j, col;
784	wchar_t *wcs;
785
786	memset(&tm, 0, sizeof(tm));
787
788	for (i = 0; i != 7; i++) {
789		tm.tm_wday = (i+1) % 7;
790		strftime(buf, sizeof(buf), "%a", &tm);
791
792		len = mbstowcs(NULL, buf, 0);
793		wcs = calloc(len + 1, sizeof(wchar_t));
794		mbstowcs(wcs, buf, len);
795		for (j = 0; j < len; j++)
796			if (wcswidth(wcs, j + 1) >= 2)
797				break;
798		wcs[j + 1] = 0;
799
800		col = wcswidth(wcs, j + 1);
801		len = wcstombs(NULL, wcs, 0);
802		wds->names[i] = calloc(len + 2 - col + 1, sizeof(char));
803		wcstombs(wds->names[i], wcs, len);
804		free(wcs);
805		if (col < 2)
806			strcat(wds->names[i], " ");
807	}
808}
809
810/*
811 * Compute the day number of the first
812 * existing date after the first day in month.
813 * (the first day in month and even the month might not exist!)
814 */
815int
816firstday(int y, int m)
817{
818	date dt;
819	int nd;
820
821	dt.y = y;
822	dt.m = m;
823	dt.d = 1;
824	nd = sndays(&dt);
825	for (;;) {
826		sdate(nd, &dt);
827		if ((dt.m >= m && dt.y == y) || dt.y > y)
828			return (nd);
829		else
830			nd++;
831	}
832	/* NEVER REACHED */
833}
834
835/*
836 * Compute the number of days from date, obey the local switch from
837 * Julian to Gregorian if specified by the user.
838 */
839int
840sndays(struct date *d)
841{
842
843	if (nswitch != 0)
844		if (nswitch < ndaysj(d))
845			return (ndaysg(d));
846		else
847			return (ndaysj(d));
848	else
849		return ndaysg(d);
850}
851
852/*
853 * Compute the number of days from date, obey the switch from
854 * Julian to Gregorian as used by UK and her colonies.
855 */
856int
857sndaysb(struct date *d)
858{
859
860	if (nswitchb < ndaysj(d))
861		return (ndaysg(d));
862	else
863		return (ndaysj(d));
864}
865
866/* Inverse of sndays */
867struct date *
868sdate(int nd, struct date *d)
869{
870
871	if (nswitch < nd)
872		return (gdate(nd, d));
873	else
874		return (jdate(nd, d));
875}
876
877/* Inverse of sndaysb */
878struct date *
879sdateb(int nd, struct date *d)
880{
881
882	if (nswitchb < nd)
883		return (gdate(nd, d));
884	else
885		return (jdate(nd, d));
886}
887
888/* Returns the number of display columns for the string */
889int
890displaywidth(char* s)
891{
892	wchar_t *wcs;
893	int res;
894	int len = mbstowcs(NULL, s, 0);
895	wcs = calloc(len + 1, sizeof(wchar_t));
896	mbstowcs(wcs, s, len);
897        res = wcswidth(wcs, len);
898	free(wcs);
899	return res;
900}
901
902/* Center string t in string s of length w by putting enough leading blanks */
903/* if r is true, also print spaces on the right side */
904char *
905center(char *s, char *t, int w, int r)
906{
907	char blanks[80];
908
909	memset(blanks, ' ', sizeof(blanks));
910
911	int width = displaywidth(t);
912	int leading = (w - width) / 2;
913	int trailing = r ? (w - width - leading) : 0;
914	sprintf(s, "%.*s%s%.*s", leading, blanks, t, trailing, blanks);
915	return (s);
916}
917
918char*
919leftjustify(char *s, char *t, int w)
920{
921	char blanks[80];
922
923	memset(blanks, ' ', sizeof(blanks));
924
925	int width = displaywidth(t);
926	int trailing = (w - width);
927	sprintf(s, "%s%.*s", t, trailing, blanks);
928	return (s);
929}
930
931int
932parsemonth(const char *s)
933{
934	int v;
935	char *cp;
936	struct tm tm;
937
938	v = (int)strtol(s, &cp, 10);
939	if (cp != s)
940		return (v);
941	if (strptime(s, "%B", &tm) != NULL)
942		return (tm.tm_mon + 1);
943	if (strptime(s, "%b", &tm) != NULL)
944		return (tm.tm_mon + 1);
945	return (0);
946}
947