]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.bin/ncal/ncal.c
Merge through 204723 plus changes to usr.sbin to move to the Makefile.arch setup
[FreeBSD/FreeBSD.git] / usr.bin / ncal / ncal.c
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
28 static const char rcsid[] =
29   "$FreeBSD$";
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 #include <wctype.h>
45 #include <term.h>
46 #undef lines                    /* term.h defines this */
47
48 /* Width of one month with backward compatibility and in regular mode*/
49 #define MONTH_WIDTH_B_J 27
50 #define MONTH_WIDTH_B 20
51
52 #define MONTH_WIDTH_R_J 24
53 #define MONTH_WIDTH_R 18
54
55 #define MAX_WIDTH 64
56
57 typedef struct date date;
58
59 struct monthlines {
60         wchar_t name[MAX_WIDTH + 1];
61         char lines[7][MAX_WIDTH + 1];
62         char weeks[MAX_WIDTH + 1];
63         unsigned int linelen[7];
64 };
65
66 struct weekdays {
67         wchar_t names[7][4];
68 };
69
70 /* The switches from Julian to Gregorian in some countries */
71 static struct djswitch {
72         const char *cc; /* Country code according to ISO 3166 */
73         const char *nm; /* Name of country */
74         date dt;        /* Last day of Julian calendar */
75 } switches[] = {
76         {"AL", "Albania",       {1912, 11, 30}},
77         {"AT", "Austria",       {1583, 10,  5}},
78         {"AU", "Australia",     {1752,  9,  2}},
79         {"BE", "Belgium",       {1582, 12, 14}},
80         {"BG", "Bulgaria",      {1916,  3, 18}},
81         {"CA", "Canada",        {1752,  9,  2}},
82         {"CH", "Switzerland",   {1655,  2, 28}},
83         {"CN", "China",         {1911, 12, 18}},
84         {"CZ", "Czech Republic",{1584,  1,  6}},
85         {"DE", "Germany",       {1700,  2, 18}},
86         {"DK", "Denmark",       {1700,  2, 18}},
87         {"ES", "Spain",         {1582, 10,  4}},
88         {"FI", "Finland",       {1753,  2, 17}},
89         {"FR", "France",        {1582, 12,  9}},
90         {"GB", "United Kingdom",{1752,  9,  2}},
91         {"GR", "Greece",        {1924,  3,  9}},
92         {"HU", "Hungary",       {1587, 10, 21}},
93         {"IS", "Iceland",       {1700, 11, 16}},
94         {"IT", "Italy",         {1582, 10,  4}},
95         {"JP", "Japan",         {1918, 12, 18}},
96         {"LI", "Lithuania",     {1918,  2,  1}},
97         {"LN", "Latin",         {9999, 05, 31}},
98         {"LU", "Luxembourg",    {1582, 12, 14}},
99         {"LV", "Latvia",        {1918,  2,  1}},
100         {"NL", "Netherlands",   {1582, 12, 14}},
101         {"NO", "Norway",        {1700,  2, 18}},
102         {"PL", "Poland",        {1582, 10,  4}},
103         {"PT", "Portugal",      {1582, 10,  4}},
104         {"RO", "Romania",       {1919,  3, 31}},
105         {"RU", "Russia",        {1918,  1, 31}},
106         {"SI", "Slovenia",      {1919,  3,  4}},
107         {"SW", "Sweden",        {1753,  2, 17}},
108         {"TR", "Turkey",        {1926, 12, 18}},
109         {"US", "United States", {1752,  9,  2}},
110         {"YU", "Yugoslavia",    {1919,  3,  4}}
111 };
112
113 struct djswitch *dftswitch =
114     switches + sizeof(switches) / sizeof(struct djswitch) - 2;
115     /* default switch (should be "US") */
116
117 /* Table used to print day of month and week numbers */
118 char daystr[] = "     1  2  3  4  5  6  7  8  9 10 11 12 13 14 15"
119                 " 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31"
120                 " 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47"
121                 " 48 49 50 51 52 53";
122
123 /* Table used to print day of year and week numbers */
124 char jdaystr[] = "       1   2   3   4   5   6   7   8   9"
125                  "  10  11  12  13  14  15  16  17  18  19"
126                  "  20  21  22  23  24  25  26  27  28  29"
127                  "  30  31  32  33  34  35  36  37  38  39"
128                  "  40  41  42  43  44  45  46  47  48  49"
129                  "  50  51  52  53  54  55  56  57  58  59"
130                  "  60  61  62  63  64  65  66  67  68  69"
131                  "  70  71  72  73  74  75  76  77  78  79"
132                  "  80  81  82  83  84  85  86  87  88  89"
133                  "  90  91  92  93  94  95  96  97  98  99"
134                  " 100 101 102 103 104 105 106 107 108 109"
135                  " 110 111 112 113 114 115 116 117 118 119"
136                  " 120 121 122 123 124 125 126 127 128 129"
137                  " 130 131 132 133 134 135 136 137 138 139"
138                  " 140 141 142 143 144 145 146 147 148 149"
139                  " 150 151 152 153 154 155 156 157 158 159"
140                  " 160 161 162 163 164 165 166 167 168 169"
141                  " 170 171 172 173 174 175 176 177 178 179"
142                  " 180 181 182 183 184 185 186 187 188 189"
143                  " 190 191 192 193 194 195 196 197 198 199"
144                  " 200 201 202 203 204 205 206 207 208 209"
145                  " 210 211 212 213 214 215 216 217 218 219"
146                  " 220 221 222 223 224 225 226 227 228 229"
147                  " 230 231 232 233 234 235 236 237 238 239"
148                  " 240 241 242 243 244 245 246 247 248 249"
149                  " 250 251 252 253 254 255 256 257 258 259"
150                  " 260 261 262 263 264 265 266 267 268 269"
151                  " 270 271 272 273 274 275 276 277 278 279"
152                  " 280 281 282 283 284 285 286 287 288 289"
153                  " 290 291 292 293 294 295 296 297 298 299"
154                  " 300 301 302 303 304 305 306 307 308 309"
155                  " 310 311 312 313 314 315 316 317 318 319"
156                  " 320 321 322 323 324 325 326 327 328 329"
157                  " 330 331 332 333 334 335 336 337 338 339"
158                  " 340 341 342 343 344 345 346 347 348 349"
159                  " 350 351 352 353 354 355 356 357 358 359"
160                  " 360 361 362 363 364 365 366";
161
162 int     flag_weeks;             /* user wants number of week */
163 int     nswitch;                /* user defined switch date */
164 int     nswitchb;               /* switch date for backward compatibility */
165 const char      *term_so, *term_se;
166 int     today;
167
168 char    *center(char *s, char *t, int w);
169 wchar_t *wcenter(wchar_t *s, wchar_t *t, int w);
170 void    mkmonthr(int year, int month, int jd_flag, struct monthlines * monthl);
171 void    mkmonthb(int year, int month, int jd_flag, struct monthlines * monthl);
172 void    mkweekdays(struct weekdays * wds);
173 int     parsemonth(const char *s, int *m, int *y);
174 void    printcc(void);
175 void    printeaster(int year, int julian, int orthodox);
176 int     firstday(int y, int m);
177 date    *sdater(int ndays, struct date * d);
178 date    *sdateb(int ndays, struct date * d);
179 int     sndaysr(struct date * d);
180 int     sndaysb(struct date * d);
181 static void     usage(void);
182 void    monthranger(int year, int jd_flag, int m, int before, int after);
183 void    monthrangeb(int year, int jd_flag, int m, int before, int after);
184
185 int
186 main(int argc, char *argv[])
187 {
188         struct  djswitch *p, *q;        /* to search user defined switch date */
189         date    never = {10000, 1, 1};  /* outside valid range of dates */
190         date    ukswitch = {1752, 9, 2};/* switch date for Great Britain */
191         date    dt;
192         int     ch;                     /* holds the option character */
193         int     m = 0;                  /* month */
194         int     y = 0;                  /* year */
195         int     flag_backward = 0;      /* user called cal--backward compat. */
196         int     flag_hole_year = 0;     /* user wants the whole year */
197         int     flag_julian_cal = 0;    /* user wants Julian Calendar */
198         int     flag_julian_day = 0;    /* user wants the Julian day
199                                          * numbers */
200         int     flag_orthodox = 0;      /* use wants Orthodox easter */
201         int     flag_easter = 0;        /* use wants easter date */
202         char    *cp;                    /* character pointer */
203         char    *flag_month = NULL;     /* requested month as string */
204         char    *flag_highlightdate = NULL;
205         int     before, after;
206         const char    *locale;          /* locale to get country code */
207         char tbuf[1024], cbuf[512], *b;
208
209         /* On how to highlight on this terminal */
210         term_se = term_so = NULL;
211         if (isatty(STDOUT_FILENO) && tgetent(tbuf, NULL) == 1) {
212                 b = cbuf;
213                 term_so = tgetstr("so", &b);
214                 term_se = tgetstr("se", &b);
215         }
216
217         /*
218          * Use locale to determine the country code,
219          * and use the country code to determine the default
220          * switchdate and date format from the switches table.
221          */
222         if (setlocale(LC_ALL, "") == NULL)
223                 warn("setlocale");
224         locale = setlocale(LC_TIME, NULL);
225         if (locale == NULL ||
226             strcmp(locale, "C") == 0 ||
227             strcmp(locale, "POSIX") == 0 ||
228             strcmp(locale, "ASCII") == 0 ||
229             strcmp(locale, "US-ASCII") == 0)
230                 locale = "_US";
231         q = switches + sizeof(switches) / sizeof(struct djswitch);
232         for (p = switches; p != q; p++)
233                 if ((cp = strstr(locale, p->cc)) != NULL && *(cp - 1) == '_')
234                         break;
235         if (p == q) {
236                 nswitch = ndaysj(&dftswitch->dt);
237         } else {
238                 nswitch = ndaysj(&p->dt);
239                 dftswitch = p;
240         }
241
242
243         /*
244          * Get the filename portion of argv[0] and set flag_backward if
245          * this program is called "cal".
246          */
247         cp = strrchr(argv[0], '/');
248         cp = (cp == NULL) ? argv[0] : cp + 1;
249         if (strcmp("cal", cp) == 0)
250                 flag_backward = 1;
251
252         /* Set the switch date to United Kingdom if backwards compatible */
253         if (flag_backward)
254                 nswitchb = ndaysj(&ukswitch);
255
256         before = after = -1;
257
258         while ((ch = getopt(argc, argv, "A:B:3Jbd:ehjm:ops:wy")) != -1)
259                 switch (ch) {
260                 case '3':
261                         before = after = 1;
262                         break;
263                 case 'A':
264                         after = strtol(optarg, NULL, 10);
265                         if (after < 0)
266                                 errx(1, "Argument to -A must be positive");
267                         break;
268                 case 'B':
269                         before = strtol(optarg, NULL, 10);
270                         if (before < 0)
271                                 errx(1, "Argument to -B must be positive");
272                         break;
273                 case 'J':
274                         if (flag_backward)
275                                 usage();
276                         nswitch = ndaysj(&never);
277                         flag_julian_cal = 1;
278                         break;
279                 case 'b':
280                         flag_backward = 1;
281                         break;
282                 case 'd':
283                         flag_highlightdate = optarg;
284                         break;
285                 case 'h':
286                         term_so = term_se = NULL;
287                         break;
288                 case 'e':
289                         if (flag_backward)
290                                 usage();
291                         flag_easter = 1;
292                         break;
293                 case 'j':
294                         flag_julian_day = 1;
295                         break;
296                 case 'm':
297                         flag_month = optarg;
298                         break;
299                 case 'o':
300                         if (flag_backward)
301                                 usage();
302                         flag_orthodox = 1;
303                         flag_easter = 1;
304                         break;
305                 case 'p':
306                         if (flag_backward)
307                                 usage();
308                         printcc();
309                         return (0);
310                         break;
311                 case 's':
312                         if (flag_backward)
313                                 usage();
314                         q = switches +
315                             sizeof(switches) / sizeof(struct djswitch);
316                         for (p = switches;
317                              p != q && strcmp(p->cc, optarg) != 0; p++)
318                                 ;
319                         if (p == q)
320                                 errx(EX_USAGE,
321                                     "%s: invalid country code", optarg);
322                         nswitch = ndaysj(&(p->dt));
323                         break;
324                 case 'w':
325                         if (flag_backward)
326                                 usage();
327                         flag_weeks = 1;
328                         break;
329                 case 'y':
330                         flag_hole_year = 1;
331                         break;
332                 default:
333                         usage();
334                 }
335
336         argc -= optind;
337         argv += optind;
338
339         switch (argc) {
340         case 2:
341                 if (flag_easter)
342                         usage();
343                 flag_month = *argv++;
344                 /* FALLTHROUGH */
345         case 1:
346                 y = atoi(*argv++);
347                 if (y < 1 || y > 9999)
348                         errx(EX_USAGE, "year %d not in range 1..9999", y);
349                 before = 0;
350                 after = 11;
351                 m = 1;
352                 break;
353         case 0:
354                 {
355                         time_t t;
356                         struct tm *tm;
357
358                         t = time(NULL);
359                         tm = localtime(&t);
360                         y = tm->tm_year + 1900;
361                         m = tm->tm_mon + 1;
362                         if (before == -1)
363                                 before = 0;
364                         if (after == -1)
365                                 after = 0;
366                 }
367                 break;
368         default:
369                 usage();
370         }
371
372         if (flag_month != NULL) {
373                 if (parsemonth(flag_month, &m, &y)) {
374                         errx(EX_USAGE,
375                             "%s is neither a month number (1..12) nor a name",
376                             flag_month);
377                 }
378         }
379
380         if (flag_highlightdate != NULL) {
381                 dt.y = strtol(flag_highlightdate, NULL, 10);
382                 dt.m = strtol(flag_highlightdate + 5, NULL, 10);
383                 dt.d = strtol(flag_highlightdate + 8, NULL, 10);
384         } else {
385                 time_t t;
386                 struct tm *tm1;
387
388                 t = time(NULL);
389                 tm1 = localtime(&t);
390                 dt.y = tm1->tm_year + 1900;
391                 dt.m = tm1->tm_mon + 1;
392                 dt.d = tm1->tm_mday;
393         }
394         today = sndaysb(&dt);
395
396         if (flag_easter)
397                 printeaster(y, flag_julian_cal, flag_orthodox);
398         else
399                 if (flag_backward)
400                         monthrangeb(y, flag_julian_day, m, before, after);
401                 else
402                         monthranger(y, flag_julian_day, m, before, after);
403         return (0);
404 }
405
406 static void
407 usage(void)
408 {
409
410         fputs(
411             "usage: cal [-hjy] [[month] year]\n"
412             "       cal [-hj] [-m month] [year]\n"
413             "       ncal [-hJjpwy] [-s country_code] [[month] year]\n"
414             "       ncal [-hJeo] [year]\n"
415             "for debug the highlighting: [-b] [-d yyyy-mm-dd]\n",
416             stderr);
417         exit(EX_USAGE);
418 }
419
420 /* print the assumed switches for all countries */
421 void
422 printcc(void)
423 {
424         struct djswitch *p;
425         int n;  /* number of lines to print */
426         int m;  /* offset from left to right table entry on the same line */
427
428 #define FSTR "%c%s %-15s%4d-%02d-%02d"
429 #define DFLT(p) ((p) == dftswitch ? '*' : ' ')
430 #define FSTRARG(p) DFLT(p), (p)->cc, (p)->nm, (p)->dt.y, (p)->dt.m, (p)->dt.d
431
432         n = sizeof(switches) / sizeof(struct djswitch);
433         m = (n + 1) / 2;
434         n /= 2;
435         for (p = switches; p != switches + n; p++)
436                 printf(FSTR"     "FSTR"\n", FSTRARG(p), FSTRARG(p+m));
437         if (m != n)
438                 printf(FSTR"\n", FSTRARG(p));
439 }
440
441 /* print the date of easter sunday */
442 void
443 printeaster(int y, int julian, int orthodox)
444 {
445         date    dt;
446         struct tm tm;
447         char    buf[MAX_WIDTH];
448         static int d_first = -1;
449
450         if (d_first < 0)
451                 d_first = (*nl_langinfo(D_MD_ORDER) == 'd');
452         /* force orthodox easter for years before 1583 */
453         if (y < 1583)
454                 orthodox = 1;
455
456         if (orthodox)
457                 if (julian)
458                         easteroj(y, &dt);
459                 else
460                         easterog(y, &dt);
461         else
462                 easterg(y, &dt);
463
464         memset(&tm, 0, sizeof(tm));
465         tm.tm_year = dt.y - 1900;
466         tm.tm_mon  = dt.m - 1;
467         tm.tm_mday = dt.d;
468         strftime(buf, sizeof(buf), d_first ? "%e %B %Y" : "%B %e %Y",  &tm);
469         printf("%s\n", buf);
470 }
471
472 #define MW(mw, ms, ml) \
473         strlen(ms) > (ml) ? (mw) + 9 : (mw)
474 #define DECREASEMONTH(m, y)             \
475                 if (--m == 0) {         \
476                         m = 12;         \
477                         y--;            \
478                 }
479 #define INCREASEMONTH(m, y)             \
480                 if (++(m) == 13) {      \
481                         (m) = 1;        \
482                         (y)++;          \
483                 }
484 #define M2Y(m)  ((m) / 12)
485 #define M2M(m)  (1 + (m) % 12) 
486
487 void
488 monthrangeb(int y, int jd_flag, int m, int before, int after)
489 {
490         struct monthlines year[12];
491         struct weekdays wds;
492         char    s[MAX_WIDTH], t[MAX_WIDTH];
493         wchar_t ws[MAX_WIDTH], ws1[MAX_WIDTH];
494         const char      *wdss;
495         int     i, j;
496         int     mpl;
497         int     mw;
498         int     m1, m2;
499         int     printyearheader;
500         int     prevyear = -1;
501
502         mpl = jd_flag ? 2 : 3;
503         mw = jd_flag ? MONTH_WIDTH_B_J : MONTH_WIDTH_B;
504         wdss = (mpl == 2) ? " " : "";
505
506         while (before != 0) {
507                 DECREASEMONTH(m, y);
508                 before--;
509                 after++;
510         }
511         m1 = y * 12 + m - 1;
512         m2 = m1 + after;
513
514         mkweekdays(&wds);
515
516         /*
517          * The year header is printed when there are more than 'mpl' months
518          * and if the first month is a multitude of 'mpl'.
519          * If not, it will print the year behind every month.
520          */
521         printyearheader = (after >= mpl - 1) && (M2M(m1) - 1) % mpl == 0;
522
523         m = m1;
524         while (m <= m2) {
525                 int count = 0;
526                 for (i = 0; i != mpl && m + i <= m2; i++) {
527                         mkmonthb(M2Y(m + i), M2M(m + i) - 1, jd_flag, year + i);
528                         count++;
529                 }
530
531                 /* Empty line between two rows of months */
532                 if (m != m1)
533                         printf("\n");
534
535                 /* Year at the top */
536                 if (printyearheader && M2Y(m) != prevyear) {
537                         sprintf(s, "%d", M2Y(m));
538                         printf("%s\n", center(t, s, mpl * mw));
539                         prevyear = M2Y(m);
540                 }
541
542                 /* Month names */
543                 for (i = 0; i < count; i++)
544                         if (printyearheader)
545                                 wprintf(L"%-*ls  ",
546                                     mw, wcenter(ws, year[i].name, mw));
547                         else {
548                                 swprintf(ws, sizeof(ws), L"%-ls %d",
549                                     year[i].name, M2Y(m + i));
550                                 wprintf(L"%-*ls  ", mw, wcenter(ws1, ws, mw));
551                         }
552                 printf("\n");
553
554                 /* Day of the week names */
555                 for (i = 0; i < count; i++) {
556                         wprintf(L"%s%ls%s%ls%s%ls%s%ls%s%ls%s%ls%s%ls ",
557                                 wdss, wds.names[6], wdss, wds.names[0],
558                                 wdss, wds.names[1], wdss, wds.names[2],
559                                 wdss, wds.names[3], wdss, wds.names[4],
560                                 wdss, wds.names[5]);
561                 }
562                 printf("\n");
563
564                 for (i = 0; i != 6; i++) {
565                         for (j = 0; j < count; j++)
566                                 printf("%-*s  ", mw, year[j].lines[i]+1);
567                         printf("\n");
568                 }
569
570                 m += mpl;
571         }
572 }
573
574 void
575 monthranger(int y, int jd_flag, int m, int before, int after)
576 {
577         struct monthlines year[12];
578         struct weekdays wds;
579         char    s[MAX_WIDTH], t[MAX_WIDTH];
580         int     i, j;
581         int     mpl;
582         int     mw;
583         int     m1, m2;
584         int     prevyear = -1;
585         int     printyearheader;
586
587         mpl = jd_flag ? 3 : 4;
588         mw = jd_flag ? MONTH_WIDTH_R_J : MONTH_WIDTH_R;
589
590         while (before != 0) {
591                 DECREASEMONTH(m, y);
592                 before--;
593                 after++;
594         }
595         m1 = y * 12 + m - 1;
596         m2 = m1 + after;
597
598         mkweekdays(&wds);
599
600         /*
601          * The year header is printed when there are more than 'mpl' months
602          * and if the first month is a multitude of 'mpl'.
603          * If not, it will print the year behind every month.
604          */
605         printyearheader = (after >= mpl - 1) && (M2M(m1) - 1) % mpl == 0;
606
607         m = m1;
608         while (m <= m2) {
609                 int count = 0;
610                 for (i = 0; i != mpl && m + i <= m2; i++) {
611                         mkmonthr(M2Y(m + i), M2M(m + i) - 1, jd_flag, year + i);
612                         count++;
613                 }
614
615                 /* Empty line between two rows of months */
616                 if (m != m1)
617                         printf("\n");
618
619                 /* Year at the top */
620                 if (printyearheader && M2Y(m) != prevyear) {
621                         sprintf(s, "%d", M2Y(m));
622                         printf("%s\n", center(t, s, mpl * mw));
623                         prevyear = M2Y(m);
624                 }
625
626                 /* Month names */
627                 wprintf(L"    ");
628                 for (i = 0; i < count; i++)
629                         if (printyearheader)
630                                 wprintf(L"%-*ls", mw, year[i].name);
631                         else
632                                 wprintf(L"%-ls %-*d", year[i].name,
633                                     mw - wcslen(year[i].name) - 1, M2Y(m + i));
634                 printf("\n");
635
636                 for (i = 0; i != 7; i++) {
637                         /* Week day */
638                         wprintf(L"%.2ls", wds.names[i]);
639
640                         /* Full months */
641                         for (j = 0; j < count; j++)
642                                 printf("%-*s",
643                                     MW(mw, year[j].lines[i],
644                                         year[j].linelen[i]), year[j].lines[i]);
645                         printf("\n");
646                 }
647
648                 if (flag_weeks) {
649                         printf("  ");
650                         for (i = 0; i < count; i++)
651                                 printf("%-*s", mw, year[i].weeks);
652                         printf("\n");
653                 }
654
655                 m += mpl;
656         }
657         return;
658 }
659
660 void
661 mkmonthr(int y, int m, int jd_flag, struct monthlines *mlines)
662 {
663
664         struct tm tm;           /* for strftime printing local names of
665                                  * months */
666         date    dt;             /* handy date */
667         int     dw;             /* width of numbers */
668         int     first;          /* first day of month */
669         int     firstm;         /* first day of first week of month */
670         int     i, j, k, l;     /* just indices */
671         int     last;           /* the first day of next month */
672         int     jan1 = 0;       /* the first day of this year */
673         char   *ds;             /* pointer to day strings (daystr or
674                                  * jdaystr) */
675
676         /* Set name of month. */
677         memset(&tm, 0, sizeof(tm));
678         tm.tm_mon = m;
679         wcsftime(mlines->name, sizeof(mlines->name) / sizeof(mlines->name[0]),
680                  L"%OB", &tm);
681         mlines->name[0] = towupper(mlines->name[0]);
682
683         /*
684          * Set first and last to the day number of the first day of this
685          * month and the first day of next month respectively. Set jan1 to
686          * the day number of the first day of this year.
687          */
688         first = firstday(y, m + 1);
689         if (m == 11)
690                 last = firstday(y + 1, 1);
691         else
692                 last = firstday(y, m + 2);
693
694         if (jd_flag)
695                 jan1 = firstday(y, 1);
696
697         /*
698          * Set firstm to the day number of monday of the first week of
699          * this month. (This might be in the last month)
700          */
701         firstm = first - weekday(first);
702
703         /* Set ds (daystring) and dw (daywidth) according to the jd_flag */
704         if (jd_flag) {
705                 ds = jdaystr;
706                 dw = 4;
707         } else {
708                 ds = daystr;
709                 dw = 3;
710         }
711
712         /*
713          * Fill the lines with day of month or day of year (julian day)
714          * line index: i, each line is one weekday. column index: j, each
715          * column is one day number. print column index: k.
716          */
717         for (i = 0; i != 7; i++) {
718                 l = 0;
719                 for (j = firstm + i, k = 0; j < last; j += 7, k += dw) {
720                         if (j == today &&
721                             (term_so != NULL && term_se != NULL)) {
722                                 l = strlen(term_so);
723                                 if (jd_flag)
724                                         dt.d = j - jan1 + 1;
725                                 else
726                                         sdateb(j, &dt);
727                                 /* separator */
728                                 mlines->lines[i][k] = ' ';
729                                 /* the actual text */
730                                 memcpy(mlines->lines[i] + k + l,
731                                     ds + dt.d * dw, dw);
732                                 /* highlight on */
733                                 memcpy(mlines->lines[i] + k + 1, term_so, l);
734                                 /* highlight off */
735                                 memcpy(mlines->lines[i] + k + l + dw, term_se,
736                                     strlen(term_se));
737                                 l = strlen(term_se) + strlen(term_so);
738                                 continue;
739                         }
740                         if (j >= first) {
741                                 if (jd_flag)
742                                         dt.d = j - jan1 + 1;
743                                 else
744                                         sdater(j, &dt);
745                                 memcpy(mlines->lines[i] + k + l,
746                                        ds + dt.d * dw, dw);
747                         } else
748                                 memcpy(mlines->lines[i] + k + l, "    ", dw);
749                 }
750                 mlines->lines[i][k + l] = '\0';
751                 mlines->linelen[i] = k;
752         }
753
754         /* fill the weeknumbers */
755         if (flag_weeks) {
756                 for (j = firstm, k = 0; j < last;  k += dw, j += 7)
757                         if (j <= nswitch)
758                                 memset(mlines->weeks + k, ' ', dw);
759                         else
760                                 memcpy(mlines->weeks + k,
761                                     ds + week(j, &i)*dw, dw);
762                 mlines->weeks[k] = '\0';
763         }
764 }
765
766 void
767 mkmonthb(int y, int m, int jd_flag, struct monthlines *mlines)
768 {
769
770         struct tm tm;           /* for strftime printing local names of
771                                  * months */
772         date    dt;             /* handy date */
773         int     dw;             /* width of numbers */
774         int     first;          /* first day of month */
775         int     firsts;         /* sunday of first week of month */
776         int     i, j, k, l;     /* just indices */
777         int     jan1 = 0;       /* the first day of this year */
778         int     last;           /* the first day of next month */
779         char   *ds;             /* pointer to day strings (daystr or
780                                  * jdaystr) */
781
782         /* Set ds (daystring) and dw (daywidth) according to the jd_flag */
783         if (jd_flag) {
784                 ds = jdaystr;
785                 dw = 4;
786         } else {
787                 ds = daystr;
788                 dw = 3;
789         }
790
791         /* Set name of month centered */
792         memset(&tm, 0, sizeof(tm));
793         tm.tm_mon = m;
794         wcsftime(mlines->name, sizeof(mlines->name) / sizeof(mlines->name[0]),
795                  L"%OB", &tm);
796         mlines->name[0] = towupper(mlines->name[0]);
797
798         /*
799          * Set first and last to the day number of the first day of this
800          * month and the first day of next month respectively. Set jan1 to
801          * the day number of Jan 1st of this year.
802          */
803         dt.y = y;
804         dt.m = m + 1;
805         dt.d = 1;
806         first = sndaysb(&dt);
807         if (m == 11) {
808                 dt.y = y + 1;
809                 dt.m = 1;
810                 dt.d = 1;
811         } else {
812                 dt.y = y;
813                 dt.m = m + 2;
814                 dt.d = 1;
815         }
816         last = sndaysb(&dt);
817
818         if (jd_flag) {
819                 dt.y = y;
820                 dt.m = 1;
821                 dt.d = 1;
822                 jan1 = sndaysb(&dt);
823         }
824
825         /*
826          * Set firsts to the day number of sunday of the first week of
827          * this month. (This might be in the last month)
828          */
829         firsts = first - (weekday(first)+1) % 7;
830
831         /*
832          * Fill the lines with day of month or day of year (Julian day)
833          * line index: i, each line is one week. column index: j, each
834          * column is one day number. print column index: k.
835          */
836         for (i = 0; i != 6; i++) {
837                 l = 0;
838                 for (j = firsts + 7 * i, k = 0; j < last && k != dw * 7;
839                     j++, k += dw) { 
840                         if (j == today &&
841                             (term_so != NULL && term_se != NULL)) {
842                                 l = strlen(term_so);
843                                 if (jd_flag)
844                                         dt.d = j - jan1 + 1;
845                                 else
846                                         sdateb(j, &dt);
847                                 /* separator */
848                                 mlines->lines[i][k] = ' ';
849                                 /* the actual text */
850                                 memcpy(mlines->lines[i] + k + l,
851                                     ds + dt.d * dw, dw);
852                                 /* highlight on */
853                                 memcpy(mlines->lines[i] + k + 1, term_so, l);
854                                 /* highlight off */
855                                 memcpy(mlines->lines[i] + k + l + dw, term_se,
856                                     strlen(term_se));
857                                 l = strlen(term_se) + strlen(term_so);
858                                 continue;
859                         }
860                         if (j >= first) {
861                                 if (jd_flag)
862                                         dt.d = j - jan1 + 1;
863                                 else
864                                         sdateb(j, &dt);
865                                 memcpy(mlines->lines[i] + k + l,
866                                        ds + dt.d * dw, dw);
867                         } else
868                                 memcpy(mlines->lines[i] + k + l, "    ", dw);
869                 }
870                 if (k == 0)
871                         mlines->lines[i][1] = '\0';
872                 else
873                         mlines->lines[i][k + l] = '\0';
874         }
875 }
876
877 /* Put the local names of weekdays into the wds */
878 void
879 mkweekdays(struct weekdays *wds)
880 {
881         int i, len, width = 0;
882         struct tm tm;
883         wchar_t buf[20];
884
885         memset(&tm, 0, sizeof(tm));
886
887         for (i = 0; i != 7; i++) {
888                 tm.tm_wday = (i+1) % 7;
889                 wcsftime(buf, sizeof(buf), L"%a", &tm);
890                 for (len = 2; len > 0; --len) {
891                         if ((width = wcswidth(buf, len)) <= 2)
892                                 break;
893                 }
894                 wmemset(wds->names[i], L'\0', 4);
895                 if (width == 1)
896                         wds->names[i][0] = L' ';
897                 wcsncat(wds->names[i], buf, len);
898                 wcsncat(wds->names[i], L" ", 1);
899         }
900 }
901
902 /*
903  * Compute the day number of the first
904  * existing date after the first day in month.
905  * (the first day in month and even the month might not exist!)
906  */
907 int
908 firstday(int y, int m)
909 {
910         date dt;
911         int nd;
912
913         dt.y = y;
914         dt.m = m;
915         dt.d = 1;
916         nd = sndaysr(&dt);
917         for (;;) {
918                 sdater(nd, &dt);
919                 if ((dt.m >= m && dt.y == y) || dt.y > y)
920                         return (nd);
921                 else
922                         nd++;
923         }
924         /* NEVER REACHED */
925 }
926
927 /*
928  * Compute the number of days from date, obey the local switch from
929  * Julian to Gregorian if specified by the user.
930  */
931 int
932 sndaysr(struct date *d)
933 {
934
935         if (nswitch != 0)
936                 if (nswitch < ndaysj(d))
937                         return (ndaysg(d));
938                 else
939                         return (ndaysj(d));
940         else
941                 return ndaysg(d);
942 }
943
944 /*
945  * Compute the number of days from date, obey the switch from
946  * Julian to Gregorian as used by UK and her colonies.
947  */
948 int
949 sndaysb(struct date *d)
950 {
951
952         if (nswitchb < ndaysj(d))
953                 return (ndaysg(d));
954         else
955                 return (ndaysj(d));
956 }
957
958 /* Inverse of sndays */
959 struct date *
960 sdater(int nd, struct date *d)
961 {
962
963         if (nswitch < nd)
964                 return (gdate(nd, d));
965         else
966                 return (jdate(nd, d));
967 }
968
969 /* Inverse of sndaysb */
970 struct date *
971 sdateb(int nd, struct date *d)
972 {
973
974         if (nswitchb < nd)
975                 return (gdate(nd, d));
976         else
977                 return (jdate(nd, d));
978 }
979
980 /* Center string t in string s of length w by putting enough leading blanks */
981 char *
982 center(char *s, char *t, int w)
983 {
984         char blanks[MAX_WIDTH];
985
986         memset(blanks, ' ', sizeof(blanks));
987         sprintf(s, "%.*s%s", (int)(w - strlen(t)) / 2, blanks, t);
988         return (s);
989 }
990
991 /* Center string t in string s of length w by putting enough leading blanks */
992 wchar_t *
993 wcenter(wchar_t *s, wchar_t *t, int w)
994 {
995         char blanks[MAX_WIDTH];
996
997         memset(blanks, ' ', sizeof(blanks));
998         swprintf(s, MAX_WIDTH, L"%.*s%ls", (int)(w - wcslen(t)) / 2, blanks, t);
999         return (s);
1000 }
1001
1002 int
1003 parsemonth(const char *s, int *m, int *y)
1004 {
1005         int nm, ny;
1006         char *cp;
1007         struct tm tm;
1008
1009         nm = (int)strtol(s, &cp, 10);
1010         if (cp != s) {
1011                 ny = *y;
1012                 if (*cp == '\0') {
1013                         ;       /* no special action */
1014                 } else if (*cp == 'f' || *cp == 'F') {
1015                         if (nm <= *m)
1016                                 ny++;
1017                 } else if (*cp == 'p' || *cp == 'P') {
1018                         if (nm >= *m)
1019                                 ny--;
1020                 } else
1021                         return (1);
1022                 if (nm < 1 || nm > 12)
1023                         return 1;
1024                 *m = nm;
1025                 *y = ny;
1026                 return (0);
1027         }
1028         if (strptime(s, "%B", &tm) != NULL || strptime(s, "%b", &tm) != NULL) {
1029                 *m = tm.tm_mon + 1;
1030                 return (0);
1031         }
1032         return (1);
1033 }