ab631576a9f9e7436b3afb09621d639fdff50a36
[oweals/busybox.git] / coreutils / cal.c
1 /*
2  * Calendar implementation for busybox
3  *
4  * Copyright (C) 2001 by Steven J. Merrifield <steve@labyrinth.net.au>
5  *
6  * See original copyright at the end of this file
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16  * General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21  *
22 */
23        
24
25 #include <sys/types.h>
26 #include <ctype.h>
27 #include <err.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <time.h>
32 #include <unistd.h>
33
34 #include "busybox.h"
35
36 #ifdef CONFIG_LOCALE_SUPPORT
37 #include <locale.h>
38 #endif
39
40 #define THURSDAY                4               /* for reformation */
41 #define SATURDAY                6               /* 1 Jan 1 was a Saturday */
42
43 #define FIRST_MISSING_DAY       639787          /* 3 Sep 1752 */
44 #define NUMBER_MISSING_DAYS     11              /* 11 day correction */
45
46 #define MAXDAYS                 42              /* max slots in a month array */
47 #define SPACE                   -1              /* used in day array */
48
49 static int days_in_month[2][13] = {
50         {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
51         {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
52 };
53
54 int sep1752[MAXDAYS] = {
55         SPACE,  SPACE,  1,      2,      14,     15,     16,
56         17,     18,     19,     20,     21,     22,     23,
57         24,     25,     26,     27,     28,     29,     30,
58         SPACE,  SPACE,  SPACE,  SPACE,  SPACE,  SPACE,  SPACE,
59         SPACE,  SPACE,  SPACE,  SPACE,  SPACE,  SPACE,  SPACE,
60         SPACE,  SPACE,  SPACE,  SPACE,  SPACE,  SPACE,  SPACE,
61 }, j_sep1752[MAXDAYS] = {
62         SPACE,  SPACE,  245,    246,    258,    259,    260,
63         261,    262,    263,    264,    265,    266,    267,
64         268,    269,    270,    271,    272,    273,    274,
65         SPACE,  SPACE,  SPACE,  SPACE,  SPACE,  SPACE,  SPACE,
66         SPACE,  SPACE,  SPACE,  SPACE,  SPACE,  SPACE,  SPACE,
67         SPACE,  SPACE,  SPACE,  SPACE,  SPACE,  SPACE,  SPACE,
68 }, empty[MAXDAYS] = {
69         SPACE,  SPACE,  SPACE,  SPACE,  SPACE,  SPACE,  SPACE,
70         SPACE,  SPACE,  SPACE,  SPACE,  SPACE,  SPACE,  SPACE,
71         SPACE,  SPACE,  SPACE,  SPACE,  SPACE,  SPACE,  SPACE,
72         SPACE,  SPACE,  SPACE,  SPACE,  SPACE,  SPACE,  SPACE,
73         SPACE,  SPACE,  SPACE,  SPACE,  SPACE,  SPACE,  SPACE,
74         SPACE,  SPACE,  SPACE,  SPACE,  SPACE,  SPACE,  SPACE,
75 };
76
77 char *month_names[12];
78
79 char day_headings[] = "                    ";
80 char j_day_headings[] = "                           ";
81
82 /* leap year -- account for gregorian reformation in 1752 */
83 #define leap_year(yr) \
84         ((yr) <= 1752 ? !((yr) % 4) : \
85         (!((yr) % 4) && ((yr) % 100)) || !((yr) % 400))
86
87 /* number of centuries since 1700, not inclusive */
88 #define centuries_since_1700(yr) \
89         ((yr) > 1700 ? (yr) / 100 - 17 : 0)
90
91 /* number of centuries since 1700 whose modulo of 400 is 0 */
92 #define quad_centuries_since_1700(yr) \
93         ((yr) > 1600 ? ((yr) - 1600) / 400 : 0)
94
95 /* number of leap years between year 1 and this year, not inclusive */
96 #define leap_years_since_year_1(yr) \
97         ((yr) / 4 - centuries_since_1700(yr) + quad_centuries_since_1700(yr))
98
99 int julian;
100 void ascii_day __P((char *, int));
101 void center __P((char *, int, int));
102 void day_array __P((int, int, int *));
103 int day_in_week __P((int, int, int));
104 int day_in_year __P((int, int, int));
105 void j_yearly __P((int));
106 void monthly __P((int, int));
107 void trim_trailing_spaces __P((char *));
108 void yearly __P((int));
109
110 int cal_main(int argc, char **argv)
111 {
112         struct tm *local_time;
113         static struct tm zero_tm;
114         time_t now;
115         int ch, month, year, yflag, i;
116         char buf[40];
117
118 #ifdef CONFIG_LOCALE_SUPPORT
119         setlocale(LC_TIME, "");
120 #endif
121
122         yflag = 0;
123         while ((ch = getopt(argc, argv, "jy")) != -1)
124                 switch(ch) {
125                 case 'j':
126                         julian = 1;
127                         break;
128                 case 'y':
129                         yflag = 1;
130                         break;
131                 default:
132                         show_usage();
133                 }
134         argc -= optind;
135         argv += optind;
136
137         month = 0;
138         switch(argc) {
139         case 2:
140                 if ((month = atoi(*argv++)) < 1 || month > 12)
141                         error_msg_and_die("Illegal month value: use 1-12");
142                 /* FALLTHROUGH */
143         case 1:
144                 if ((year = atoi(*argv)) < 1 || year > 9999)
145                         error_msg_and_die("Illegal year value: use 1-9999");
146                 break;
147         case 0:
148                 time(&now);
149                 local_time = localtime(&now);
150                 year = local_time->tm_year + 1900;
151                 if (!yflag)
152                         month = local_time->tm_mon + 1;
153                 break;
154         default:
155                 show_usage();
156         }
157
158         for (i = 0; i < 12; i++) {
159                 zero_tm.tm_mon = i;
160                 strftime(buf, sizeof(buf), "%B", &zero_tm);
161                 month_names[i] = xstrdup(buf);
162         }
163         for (i = 0; i < 7; i++) {
164                 zero_tm.tm_wday = i;
165                 strftime(buf, sizeof(buf), "%a", &zero_tm);
166                 strncpy(day_headings + i * 3, buf, 2);
167                 strncpy(j_day_headings + i * 4 + 1, buf, 2);
168         }
169
170         if (month)
171                 monthly(month, year);
172         else if (julian)
173                 j_yearly(year);
174         else
175                 yearly(year);
176         exit(0);
177 }
178
179 #define DAY_LEN         3               /* 3 spaces per day */
180 #define J_DAY_LEN       4               /* 4 spaces per day */
181 #define WEEK_LEN        20              /* 7 * 3 - one space at the end */
182 #define J_WEEK_LEN      27              /* 7 * 4 - one space at the end */
183 #define HEAD_SEP        2               /* spaces between day headings */
184 #define J_HEAD_SEP      2
185
186 void monthly(int month, int year)
187 {
188         int col, row, len, days[MAXDAYS];
189         char *p, lineout[30];
190
191         day_array(month, year, days);
192         len = sprintf(lineout, "%s %d", month_names[month - 1], year);
193         printf("%*s%s\n%s\n",
194             ((julian ? J_WEEK_LEN : WEEK_LEN) - len) / 2, "",
195             lineout, julian ? j_day_headings : day_headings);
196         for (row = 0; row < 6; row++) {
197                 for (col = 0, p = lineout; col < 7; col++,
198                     p += julian ? J_DAY_LEN : DAY_LEN)
199                         ascii_day(p, days[row * 7 + col]);
200                 *p = '\0';
201                 trim_trailing_spaces(lineout);
202                 printf("%s\n", lineout);
203         }
204 }
205
206 void j_yearly(int year)
207 {
208         int col, *dp, i, month, row, which_cal;
209         int days[12][MAXDAYS];
210         char *p, lineout[80];
211
212         sprintf(lineout, "%d", year);
213         center(lineout, J_WEEK_LEN * 2 + J_HEAD_SEP, 0);
214         printf("\n\n");
215         for (i = 0; i < 12; i++)
216                 day_array(i + 1, year, days[i]);
217         memset(lineout, ' ', sizeof(lineout) - 1);
218         lineout[sizeof(lineout) - 1] = '\0';
219         for (month = 0; month < 12; month += 2) {
220                 center(month_names[month], J_WEEK_LEN, J_HEAD_SEP);
221                 center(month_names[month + 1], J_WEEK_LEN, 0);
222                 printf("\n%s%*s%s\n", j_day_headings, J_HEAD_SEP, "",
223                     j_day_headings);
224                 for (row = 0; row < 6; row++) {
225                         for (which_cal = 0; which_cal < 2; which_cal++) {
226                                 p = lineout + which_cal * (J_WEEK_LEN + 2);
227                                 dp = &days[month + which_cal][row * 7];
228                                 for (col = 0; col < 7; col++, p += J_DAY_LEN)
229                                         ascii_day(p, *dp++);
230                         }
231                         *p = '\0';
232                         trim_trailing_spaces(lineout);
233                         printf("%s\n", lineout);
234                 }
235         }
236         printf("\n");
237 }
238
239 void yearly(int year)
240 {
241         int col, *dp, i, month, row, which_cal;
242         int days[12][MAXDAYS];
243         char *p, lineout[80];
244
245         sprintf(lineout, "%d", year);
246         center(lineout, WEEK_LEN * 3 + HEAD_SEP * 2, 0);
247         printf("\n\n");
248         for (i = 0; i < 12; i++)
249                 day_array(i + 1, year, days[i]);
250         memset(lineout, ' ', sizeof(lineout) - 1);
251         lineout[sizeof(lineout) - 1] = '\0';
252         for (month = 0; month < 12; month += 3) {
253                 center(month_names[month], WEEK_LEN, HEAD_SEP);
254                 center(month_names[month + 1], WEEK_LEN, HEAD_SEP);
255                 center(month_names[month + 2], WEEK_LEN, 0);
256                 printf("\n%s%*s%s%*s%s\n", day_headings, HEAD_SEP,
257                     "", day_headings, HEAD_SEP, "", day_headings);
258                 for (row = 0; row < 6; row++) {
259                         for (which_cal = 0; which_cal < 3; which_cal++) {
260                                 p = lineout + which_cal * (WEEK_LEN + 2);
261                                 dp = &days[month + which_cal][row * 7];
262                                 for (col = 0; col < 7; col++, p += DAY_LEN)
263                                         ascii_day(p, *dp++);
264                         }
265                         *p = '\0';
266                         trim_trailing_spaces(lineout);
267                         printf("%s\n", lineout);
268                 }
269         }
270         printf("\n");
271 }
272
273 /*
274  * day_array --
275  *      Fill in an array of 42 integers with a calendar.  Assume for a moment
276  *      that you took the (maximum) 6 rows in a calendar and stretched them
277  *      out end to end.  You would have 42 numbers or spaces.  This routine
278  *      builds that array for any month from Jan. 1 through Dec. 9999.
279  */
280 void day_array(int month, int year, int *days)
281 {
282         int day, dw, dm;
283
284         if ((month == 9) && (year == 1752)) {
285                 memmove(days,
286                         julian ? j_sep1752 : sep1752, MAXDAYS * sizeof(int));
287                 return;
288         }
289         memmove(days, empty, MAXDAYS * sizeof(int));
290         dm = days_in_month[leap_year(year)][month];
291         dw = day_in_week(1, month, year);
292         day = julian ? day_in_year(1, month, year) : 1;
293         while (dm--)
294                 days[dw++] = day++;
295 }
296
297 /*
298  * day_in_year --
299  *      return the 1 based day number within the year
300  */
301 int day_in_year(int day, int month, int year)
302 {
303         int i, leap;
304
305         leap = leap_year(year);
306         for (i = 1; i < month; i++)
307                 day += days_in_month[leap][i];
308         return (day);
309 }
310
311 /*
312  * day_in_week
313  *      return the 0 based day number for any date from 1 Jan. 1 to
314  *      31 Dec. 9999.  Assumes the Gregorian reformation eliminates
315  *      3 Sep. 1752 through 13 Sep. 1752.  Returns Thursday for all
316  *      missing days.
317  */
318 int day_in_week(int day, int month, int year)
319 {
320         long temp;
321
322         temp = (long)(year - 1) * 365 + leap_years_since_year_1(year - 1)
323             + day_in_year(day, month, year);
324         if (temp < FIRST_MISSING_DAY)
325                 return ((temp - 1 + SATURDAY) % 7);
326         if (temp >= (FIRST_MISSING_DAY + NUMBER_MISSING_DAYS))
327                 return (((temp - 1 + SATURDAY) - NUMBER_MISSING_DAYS) % 7);
328         return (THURSDAY);
329 }
330
331 void ascii_day(char *p, int day)
332 {
333         int display, val;
334         static char *aday[] = {
335                 "",
336                 " 1", " 2", " 3", " 4", " 5", " 6", " 7",
337                 " 8", " 9", "10", "11", "12", "13", "14",
338                 "15", "16", "17", "18", "19", "20", "21",
339                 "22", "23", "24", "25", "26", "27", "28",
340                 "29", "30", "31",
341         };
342
343         if (day == SPACE) {
344                 memset(p, ' ', julian ? J_DAY_LEN : DAY_LEN);
345                 return;
346         }
347         if (julian) {
348                 if ((val = day / 100) != 0) {
349                         day %= 100;
350                         *p++ = val + '0';
351                         display = 1;
352                 } else {
353                         *p++ = ' ';
354                         display = 0;
355                 }
356                 val = day / 10;
357                 if (val || display)
358                         *p++ = val + '0';
359                 else
360                         *p++ = ' ';
361                 *p++ = day % 10 + '0';
362         } else {
363                 *p++ = aday[day][0];
364                 *p++ = aday[day][1];
365         }
366         *p = ' ';
367 }
368
369 void trim_trailing_spaces(char *s)
370 {
371         char *p;
372
373         for (p = s; *p; ++p)
374                 continue;
375         while (p > s && (--p, isspace(*p)))
376                 continue;
377         if (p > s)
378                 ++p;
379         *p = '\0';
380 }
381
382 void center(char *str, int len, int separate)
383 {
384
385         len -= strlen(str);
386         printf("%*s%s%*s", len / 2, "", str, len / 2 + len % 2, "");
387         if (separate)
388                 printf("%*s", separate, "");
389 }
390
391
392 /*
393  * Copyright (c) 1989, 1993, 1994
394  *      The Regents of the University of California.  All rights reserved.
395  *
396  * This code is derived from software contributed to Berkeley by
397  * Kim Letkeman.
398  *
399  * Redistribution and use in source and binary forms, with or without
400  * modification, are permitted provided that the following conditions
401  * are met:
402  * 1. Redistributions of source code must retain the above copyright
403  *    notice, this list of conditions and the following disclaimer.
404  * 2. Redistributions in binary form must reproduce the above copyright
405  *    notice, this list of conditions and the following disclaimer in the
406  *    documentation and/or other materials provided with the distribution.
407  * 3. Neither the name of the University nor the names of its contributors
408  *    may be used to endorse or promote products derived from this software
409  *    without specific prior written permission.
410  *
411  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
412  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
413  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
414  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
415  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
416  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
417  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
418  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
419  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
420  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
421  * SUCH DAMAGE.
422  */
423
424