Home | History | Annotate | Line # | Download | only in time
zic.c revision 1.38
      1 /*	$NetBSD: zic.c,v 1.38 2013/03/06 18:19:07 christos Exp $	*/
      2 /*
      3 ** This file is in the public domain, so clarified as of
      4 ** 2006-07-17 by Arthur David Olson.
      5 */
      6 
      7 #if HAVE_NBTOOL_CONFIG_H
      8 #include "nbtool_config.h"
      9 #endif
     10 
     11 #include <sys/cdefs.h>
     12 #ifndef lint
     13 __RCSID("$NetBSD: zic.c,v 1.38 2013/03/06 18:19:07 christos Exp $");
     14 #endif /* !defined lint */
     15 
     16 #include "version.h"
     17 #include "private.h"
     18 #include "locale.h"
     19 #include "tzfile.h"
     20 
     21 #define	ZIC_VERSION	'2'
     22 
     23 typedef intmax_t	zic_t;
     24 #define TIME_T_BITS_IN_FILE	64
     25 static const zic_t min_time = INTMAX_MIN;
     26 static const zic_t max_time = INTMAX_MAX;
     27 
     28 
     29 #ifndef ZIC_MAX_ABBR_LEN_WO_WARN
     30 #define ZIC_MAX_ABBR_LEN_WO_WARN	6
     31 #endif /* !defined ZIC_MAX_ABBR_LEN_WO_WARN */
     32 
     33 #if HAVE_SYS_STAT_H
     34 #include "sys/stat.h"
     35 #endif
     36 #ifdef S_IRUSR
     37 #define MKDIR_UMASK (S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH)
     38 #else
     39 #define MKDIR_UMASK 0755
     40 #endif
     41 
     42 #include "unistd.h"
     43 
     44 /*
     45 ** On some ancient hosts, predicates like `isspace(C)' are defined
     46 ** only if isascii(C) || C == EOF. Modern hosts obey the C Standard,
     47 ** which says they are defined only if C == ((unsigned char) C) || C == EOF.
     48 ** Neither the C Standard nor Posix require that `isascii' exist.
     49 ** For portability, we check both ancient and modern requirements.
     50 ** If isascii is not defined, the isascii check succeeds trivially.
     51 */
     52 #include "ctype.h"
     53 #ifndef isascii
     54 #define isascii(x) 1
     55 #endif
     56 
     57 #define end(cp)	(strchr((cp), '\0'))
     58 
     59 struct rule {
     60 	const char *	r_filename;
     61 	int		r_linenum;
     62 	const char *	r_name;
     63 
     64 	int		r_loyear;	/* for example, 1986 */
     65 	int		r_hiyear;	/* for example, 1986 */
     66 	const char *	r_yrtype;
     67 	int		r_lowasnum;
     68 	int		r_hiwasnum;
     69 
     70 	int		r_month;	/* 0..11 */
     71 
     72 	int		r_dycode;	/* see below */
     73 	int		r_dayofmonth;
     74 	int		r_wday;
     75 
     76 	zic_t		r_tod;		/* time from midnight */
     77 	int		r_todisstd;	/* above is standard time if TRUE */
     78 					/* or wall clock time if FALSE */
     79 	int		r_todisgmt;	/* above is GMT if TRUE */
     80 					/* or local time if FALSE */
     81 	zic_t		r_stdoff;	/* offset from standard time */
     82 	const char *	r_abbrvar;	/* variable part of abbreviation */
     83 
     84 	int		r_todo;		/* a rule to do (used in outzone) */
     85 	zic_t		r_temp;		/* used in outzone */
     86 };
     87 
     88 /*
     89 **	r_dycode		r_dayofmonth	r_wday
     90 */
     91 
     92 #define DC_DOM		0	/* 1..31 */	/* unused */
     93 #define DC_DOWGEQ	1	/* 1..31 */	/* 0..6 (Sun..Sat) */
     94 #define DC_DOWLEQ	2	/* 1..31 */	/* 0..6 (Sun..Sat) */
     95 
     96 struct zone {
     97 	const char *	z_filename;
     98 	int		z_linenum;
     99 
    100 	const char *	z_name;
    101 	zic_t		z_gmtoff;
    102 	const char *	z_rule;
    103 	const char *	z_format;
    104 
    105 	zic_t		z_stdoff;
    106 
    107 	struct rule *	z_rules;
    108 	int		z_nrules;
    109 
    110 	struct rule	z_untilrule;
    111 	zic_t		z_untiltime;
    112 };
    113 
    114 extern int	getopt(int argc, char * const argv[],
    115 			const char * options);
    116 extern int	link(const char * fromname, const char * toname);
    117 extern char *	optarg;
    118 extern int	optind;
    119 
    120 static void	addtt(zic_t starttime, int type);
    121 static int	addtype(zic_t gmtoff, const char * abbr, int isdst,
    122 				int ttisstd, int ttisgmt);
    123 static void	leapadd(zic_t t, int positive, int rolling, int count);
    124 static void	adjleap(void);
    125 static void	associate(void);
    126 static void	dolink(const char * fromfield, const char * tofield);
    127 static zic_t	eitol(int i);
    128 static char **	getfields(char * buf);
    129 static zic_t	gethms(const char * string, const char * errstrng,
    130 			int signable);
    131 static void	infile(const char * filename);
    132 static void	inleap(char ** fields, int nfields);
    133 static void	inlink(char ** fields, int nfields);
    134 static void	inrule(char ** fields, int nfields);
    135 static int	inzcont(char ** fields, int nfields);
    136 static int	inzone(char ** fields, int nfields);
    137 static int	inzsub(char ** fields, int nfields, int iscont);
    138 static int	itsdir(const char * name);
    139 static int	lowerit(int c);
    140 int		main(int, char **);
    141 static int	mkdirs(char * filename);
    142 static void	newabbr(const char * abbr);
    143 static zic_t	oadd(zic_t t1, zic_t t2);
    144 static void	outzone(const struct zone * zp, int ntzones);
    145 static int	rcomp(const void * leftp, const void * rightp);
    146 static zic_t	rpytime(const struct rule * rp, int wantedy);
    147 static void	rulesub(struct rule * rp,
    148 			const char * loyearp, const char * hiyearp,
    149 			const char * typep, const char * monthp,
    150 			const char * dayp, const char * timep);
    151 static zic_t	tadd(zic_t t1, zic_t t2);
    152 static int	yearistype(int year, const char * type);
    153 static int	atcomp(const void *avp, const void *bvp);
    154 static void	updateminmax(int x);
    155 
    156 static int		charcnt;
    157 static int		errors;
    158 static const char *	filename;
    159 static int		leapcnt;
    160 static int		leapseen;
    161 static int		leapminyear;
    162 static int		leapmaxyear;
    163 static int		linenum;
    164 static size_t		max_abbrvar_len;
    165 static size_t		max_format_len;
    166 static int		max_year;
    167 static int		min_year;
    168 static int		noise;
    169 static const char *	rfilename;
    170 static int		rlinenum;
    171 static const char *	progname;
    172 static int		timecnt;
    173 static int		typecnt;
    174 
    175 /*
    176 ** Line codes.
    177 */
    178 
    179 #define LC_RULE		0
    180 #define LC_ZONE		1
    181 #define LC_LINK		2
    182 #define LC_LEAP		3
    183 
    184 /*
    185 ** Which fields are which on a Zone line.
    186 */
    187 
    188 #define ZF_NAME		1
    189 #define ZF_GMTOFF	2
    190 #define ZF_RULE		3
    191 #define ZF_FORMAT	4
    192 #define ZF_TILYEAR	5
    193 #define ZF_TILMONTH	6
    194 #define ZF_TILDAY	7
    195 #define ZF_TILTIME	8
    196 #define ZONE_MINFIELDS	5
    197 #define ZONE_MAXFIELDS	9
    198 
    199 /*
    200 ** Which fields are which on a Zone continuation line.
    201 */
    202 
    203 #define ZFC_GMTOFF	0
    204 #define ZFC_RULE	1
    205 #define ZFC_FORMAT	2
    206 #define ZFC_TILYEAR	3
    207 #define ZFC_TILMONTH	4
    208 #define ZFC_TILDAY	5
    209 #define ZFC_TILTIME	6
    210 #define ZONEC_MINFIELDS	3
    211 #define ZONEC_MAXFIELDS	7
    212 
    213 /*
    214 ** Which files are which on a Rule line.
    215 */
    216 
    217 #define RF_NAME		1
    218 #define RF_LOYEAR	2
    219 #define RF_HIYEAR	3
    220 #define RF_COMMAND	4
    221 #define RF_MONTH	5
    222 #define RF_DAY		6
    223 #define RF_TOD		7
    224 #define RF_STDOFF	8
    225 #define RF_ABBRVAR	9
    226 #define RULE_FIELDS	10
    227 
    228 /*
    229 ** Which fields are which on a Link line.
    230 */
    231 
    232 #define LF_FROM		1
    233 #define LF_TO		2
    234 #define LINK_FIELDS	3
    235 
    236 /*
    237 ** Which fields are which on a Leap line.
    238 */
    239 
    240 #define LP_YEAR		1
    241 #define LP_MONTH	2
    242 #define LP_DAY		3
    243 #define LP_TIME		4
    244 #define LP_CORR		5
    245 #define LP_ROLL		6
    246 #define LEAP_FIELDS	7
    247 
    248 /*
    249 ** Year synonyms.
    250 */
    251 
    252 #define YR_MINIMUM	0
    253 #define YR_MAXIMUM	1
    254 #define YR_ONLY		2
    255 
    256 static struct rule *	rules;
    257 static int		nrules;	/* number of rules */
    258 
    259 static struct zone *	zones;
    260 static int		nzones;	/* number of zones */
    261 
    262 struct link {
    263 	const char *	l_filename;
    264 	int		l_linenum;
    265 	const char *	l_from;
    266 	const char *	l_to;
    267 };
    268 
    269 static struct link *	links;
    270 static int		nlinks;
    271 
    272 struct lookup {
    273 	const char *	l_word;
    274 	const int	l_value;
    275 };
    276 
    277 static struct lookup const *	byword(const char * string,
    278 					const struct lookup * lp);
    279 
    280 static struct lookup const	line_codes[] = {
    281 	{ "Rule",	LC_RULE },
    282 	{ "Zone",	LC_ZONE },
    283 	{ "Link",	LC_LINK },
    284 	{ "Leap",	LC_LEAP },
    285 	{ NULL,		0}
    286 };
    287 
    288 static struct lookup const	mon_names[] = {
    289 	{ "January",	TM_JANUARY },
    290 	{ "February",	TM_FEBRUARY },
    291 	{ "March",	TM_MARCH },
    292 	{ "April",	TM_APRIL },
    293 	{ "May",	TM_MAY },
    294 	{ "June",	TM_JUNE },
    295 	{ "July",	TM_JULY },
    296 	{ "August",	TM_AUGUST },
    297 	{ "September",	TM_SEPTEMBER },
    298 	{ "October",	TM_OCTOBER },
    299 	{ "November",	TM_NOVEMBER },
    300 	{ "December",	TM_DECEMBER },
    301 	{ NULL,		0 }
    302 };
    303 
    304 static struct lookup const	wday_names[] = {
    305 	{ "Sunday",	TM_SUNDAY },
    306 	{ "Monday",	TM_MONDAY },
    307 	{ "Tuesday",	TM_TUESDAY },
    308 	{ "Wednesday",	TM_WEDNESDAY },
    309 	{ "Thursday",	TM_THURSDAY },
    310 	{ "Friday",	TM_FRIDAY },
    311 	{ "Saturday",	TM_SATURDAY },
    312 	{ NULL,		0 }
    313 };
    314 
    315 static struct lookup const	lasts[] = {
    316 	{ "last-Sunday",	TM_SUNDAY },
    317 	{ "last-Monday",	TM_MONDAY },
    318 	{ "last-Tuesday",	TM_TUESDAY },
    319 	{ "last-Wednesday",	TM_WEDNESDAY },
    320 	{ "last-Thursday",	TM_THURSDAY },
    321 	{ "last-Friday",	TM_FRIDAY },
    322 	{ "last-Saturday",	TM_SATURDAY },
    323 	{ NULL,			0 }
    324 };
    325 
    326 static struct lookup const	begin_years[] = {
    327 	{ "minimum",	YR_MINIMUM },
    328 	{ "maximum",	YR_MAXIMUM },
    329 	{ NULL,		0 }
    330 };
    331 
    332 static struct lookup const	end_years[] = {
    333 	{ "minimum",	YR_MINIMUM },
    334 	{ "maximum",	YR_MAXIMUM },
    335 	{ "only",	YR_ONLY },
    336 	{ NULL,		0 }
    337 };
    338 
    339 static struct lookup const	leap_types[] = {
    340 	{ "Rolling",	TRUE },
    341 	{ "Stationary",	FALSE },
    342 	{ NULL,		0 }
    343 };
    344 
    345 static const int	len_months[2][MONSPERYEAR] = {
    346 	{ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
    347 	{ 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
    348 };
    349 
    350 static const int	len_years[2] = {
    351 	DAYSPERNYEAR, DAYSPERLYEAR
    352 };
    353 
    354 static struct attype {
    355 	zic_t		at;
    356 	unsigned char	type;
    357 }			attypes[TZ_MAX_TIMES];
    358 static zic_t		gmtoffs[TZ_MAX_TYPES];
    359 static char		isdsts[TZ_MAX_TYPES];
    360 static unsigned char	abbrinds[TZ_MAX_TYPES];
    361 static char		ttisstds[TZ_MAX_TYPES];
    362 static char		ttisgmts[TZ_MAX_TYPES];
    363 static char		chars[TZ_MAX_CHARS];
    364 static zic_t		trans[TZ_MAX_LEAPS];
    365 static zic_t		corr[TZ_MAX_LEAPS];
    366 static char		roll[TZ_MAX_LEAPS];
    367 
    368 /*
    369 ** Memory allocation.
    370 */
    371 
    372 static __pure void *
    373 memcheck(void *const ptr)
    374 {
    375 	if (ptr == NULL) {
    376 		const char *e = strerror(errno);
    377 
    378 		(void) fprintf(stderr, _("%s: Memory exhausted: %s\n"),
    379 			progname, e);
    380 		exit(EXIT_FAILURE);
    381 	}
    382 	return ptr;
    383 }
    384 
    385 #define emalloc(size)		memcheck(malloc(size))
    386 #define erealloc(ptr, size)	memcheck(realloc((ptr), (size)))
    387 #define ecpyalloc(ptr)		memcheck(icpyalloc(ptr))
    388 #define ecatalloc(oldp, newp)	memcheck(icatalloc((oldp), (newp)))
    389 
    390 /*
    391 ** Error handling.
    392 */
    393 
    394 static void
    395 eats(const char *const name, const int num, const char *const rname,
    396     const int rnum)
    397 {
    398 	filename = name;
    399 	linenum = num;
    400 	rfilename = rname;
    401 	rlinenum = rnum;
    402 }
    403 
    404 static void
    405 eat(const char *const name, const int num)
    406 {
    407 	eats(name, num, NULL, -1);
    408 }
    409 
    410 static void
    411 error(const char *const string)
    412 {
    413 	/*
    414 	** Match the format of "cc" to allow sh users to
    415 	**	zic ... 2>&1 | error -t "*" -v
    416 	** on BSD systems.
    417 	*/
    418 	(void) fprintf(stderr, _("\"%s\", line %d: %s"),
    419 		filename, linenum, string);
    420 	if (rfilename != NULL)
    421 		(void) fprintf(stderr, _(" (rule from \"%s\", line %d)"),
    422 			rfilename, rlinenum);
    423 	(void) fprintf(stderr, "\n");
    424 	++errors;
    425 }
    426 
    427 static void
    428 warning(const char *const string)
    429 {
    430 	char *	cp;
    431 
    432 	cp = ecpyalloc(_("warning: "));
    433 	cp = ecatalloc(cp, string);
    434 	error(cp);
    435 	free(cp);
    436 	--errors;
    437 }
    438 
    439 __dead static void
    440 usage(FILE *stream, int status)
    441 {
    442 	(void) fprintf(stream, _("%s: usage is %s \
    443 [ --version ] [ --help ] [ -v ] [ -l localtime ] [ -p posixrules ] \\\n\
    444 \t[ -d directory ] [ -L leapseconds ] [ -y yearistype ] [ filename ... ]\n\
    445 \n\
    446 Report bugs to %s.\n"),
    447 		       progname, progname, REPORT_BUGS_TO);
    448 	exit(status);
    449 }
    450 
    451 static const char *	psxrules;
    452 static const char *	lcltime;
    453 static const char *	directory;
    454 static const char *	leapsec;
    455 static const char *	yitcommand;
    456 
    457 int
    458 main(int argc, char *argv[])
    459 {
    460 	int	i;
    461 	int	j;
    462 	int	c;
    463 
    464 #ifdef _POSIX_VERSION
    465 	(void) umask(umask(S_IWGRP | S_IWOTH) | (S_IWGRP | S_IWOTH));
    466 #endif /* defined _POSIX_VERSION */
    467 #if HAVE_GETTEXT - 0
    468 	(void) setlocale(LC_MESSAGES, "");
    469 #ifdef TZ_DOMAINDIR
    470 	(void) bindtextdomain(TZ_DOMAIN, TZ_DOMAINDIR);
    471 #endif /* defined TEXTDOMAINDIR */
    472 	(void) textdomain(TZ_DOMAIN);
    473 #endif /* HAVE_GETTEXT */
    474 	progname = argv[0];
    475 	if (TYPE_BIT(zic_t) < 64) {
    476 		(void) fprintf(stderr, "%s: %s\n", progname,
    477 			_("wild compilation-time specification of zic_t"));
    478 		exit(EXIT_FAILURE);
    479 	}
    480 	for (i = 1; i < argc; ++i)
    481 		if (strcmp(argv[i], "--version") == 0) {
    482 			(void) printf("zic %s%s\n", PKGVERSION, TZVERSION);
    483 			exit(EXIT_SUCCESS);
    484 		} else if (strcmp(argv[i], "--help") == 0) {
    485 			usage(stdout, EXIT_SUCCESS);
    486 		}
    487 	while ((c = getopt(argc, argv, "d:l:p:L:vsy:")) != EOF && c != -1)
    488 		switch (c) {
    489 			default:
    490 				usage(stderr, EXIT_FAILURE);
    491 			case 'd':
    492 				if (directory == NULL)
    493 					directory = optarg;
    494 				else {
    495 					(void) fprintf(stderr,
    496 _("%s: More than one -d option specified\n"),
    497 						progname);
    498 					exit(EXIT_FAILURE);
    499 				}
    500 				break;
    501 			case 'l':
    502 				if (lcltime == NULL)
    503 					lcltime = optarg;
    504 				else {
    505 					(void) fprintf(stderr,
    506 _("%s: More than one -l option specified\n"),
    507 						progname);
    508 					exit(EXIT_FAILURE);
    509 				}
    510 				break;
    511 			case 'p':
    512 				if (psxrules == NULL)
    513 					psxrules = optarg;
    514 				else {
    515 					(void) fprintf(stderr,
    516 _("%s: More than one -p option specified\n"),
    517 						progname);
    518 					exit(EXIT_FAILURE);
    519 				}
    520 				break;
    521 			case 'y':
    522 				if (yitcommand == NULL)
    523 					yitcommand = optarg;
    524 				else {
    525 					(void) fprintf(stderr,
    526 _("%s: More than one -y option specified\n"),
    527 						progname);
    528 					exit(EXIT_FAILURE);
    529 				}
    530 				break;
    531 			case 'L':
    532 				if (leapsec == NULL)
    533 					leapsec = optarg;
    534 				else {
    535 					(void) fprintf(stderr,
    536 _("%s: More than one -L option specified\n"),
    537 						progname);
    538 					exit(EXIT_FAILURE);
    539 				}
    540 				break;
    541 			case 'v':
    542 				noise = TRUE;
    543 				break;
    544 			case 's':
    545 				(void) printf("%s: -s ignored\n", progname);
    546 				break;
    547 		}
    548 	if (optind == argc - 1 && strcmp(argv[optind], "=") == 0)
    549 		usage(stderr, EXIT_FAILURE);	/* usage message by request */
    550 	if (directory == NULL)
    551 		directory = TZDIR;
    552 	if (yitcommand == NULL)
    553 		yitcommand = "yearistype";
    554 
    555 	if (optind < argc && leapsec != NULL) {
    556 		infile(leapsec);
    557 		adjleap();
    558 	}
    559 
    560 	for (i = optind; i < argc; ++i)
    561 		infile(argv[i]);
    562 	if (errors)
    563 		exit(EXIT_FAILURE);
    564 	associate();
    565 	for (i = 0; i < nzones; i = j) {
    566 		/*
    567 		** Find the next non-continuation zone entry.
    568 		*/
    569 		for (j = i + 1; j < nzones && zones[j].z_name == NULL; ++j)
    570 			continue;
    571 		outzone(&zones[i], j - i);
    572 	}
    573 	/*
    574 	** Make links.
    575 	*/
    576 	for (i = 0; i < nlinks; ++i) {
    577 		eat(links[i].l_filename, links[i].l_linenum);
    578 		dolink(links[i].l_from, links[i].l_to);
    579 		if (noise)
    580 			for (j = 0; j < nlinks; ++j)
    581 				if (strcmp(links[i].l_to,
    582 					links[j].l_from) == 0)
    583 						warning(_("link to link"));
    584 	}
    585 	if (lcltime != NULL) {
    586 		eat("command line", 1);
    587 		dolink(lcltime, TZDEFAULT);
    588 	}
    589 	if (psxrules != NULL) {
    590 		eat("command line", 1);
    591 		dolink(psxrules, TZDEFRULES);
    592 	}
    593 	return (errors == 0) ? EXIT_SUCCESS : EXIT_FAILURE;
    594 }
    595 
    596 static void
    597 dolink(const char *const fromfield, const char *const tofield)
    598 {
    599 	char *	fromname;
    600 	char *	toname;
    601 
    602 	if (fromfield[0] == '/')
    603 		fromname = ecpyalloc(fromfield);
    604 	else {
    605 		fromname = ecpyalloc(directory);
    606 		fromname = ecatalloc(fromname, "/");
    607 		fromname = ecatalloc(fromname, fromfield);
    608 	}
    609 	if (tofield[0] == '/')
    610 		toname = ecpyalloc(tofield);
    611 	else {
    612 		toname = ecpyalloc(directory);
    613 		toname = ecatalloc(toname, "/");
    614 		toname = ecatalloc(toname, tofield);
    615 	}
    616 	/*
    617 	** We get to be careful here since
    618 	** there's a fair chance of root running us.
    619 	*/
    620 	if (!itsdir(toname))
    621 		(void) remove(toname);
    622 	if (link(fromname, toname) != 0) {
    623 		int	result;
    624 
    625 		if (mkdirs(toname) != 0)
    626 			exit(EXIT_FAILURE);
    627 
    628 		result = link(fromname, toname);
    629 #if HAVE_SYMLINK
    630 		if (result != 0 &&
    631 			access(fromname, F_OK) == 0 &&
    632 			!itsdir(fromname)) {
    633 				const char *s = tofield;
    634 				char * symlinkcontents = NULL;
    635 
    636 				while ((s = strchr(s+1, '/')) != NULL)
    637 					symlinkcontents =
    638 						ecatalloc(symlinkcontents,
    639 						"../");
    640 				symlinkcontents =
    641 					ecatalloc(symlinkcontents,
    642 					fromname);
    643 				result = symlink(symlinkcontents,
    644 					toname);
    645 				if (result == 0)
    646 warning(_("hard link failed, symbolic link used"));
    647 				free(symlinkcontents);
    648 		}
    649 #endif /* HAVE_SYMLINK */
    650 		if (result != 0) {
    651 			const char *e = strerror(errno);
    652 
    653 			(void) fprintf(stderr,
    654 				_("%s: Can't link from %s to %s: %s\n"),
    655 				progname, fromname, toname, e);
    656 			exit(EXIT_FAILURE);
    657 		}
    658 	}
    659 	free(fromname);
    660 	free(toname);
    661 }
    662 
    663 static int
    664 itsdir(const char *const name)
    665 {
    666 	char *	myname;
    667 	int	accres;
    668 
    669 	myname = ecpyalloc(name);
    670 	myname = ecatalloc(myname, "/.");
    671 	accres = access(myname, F_OK);
    672 	free(myname);
    673 	return accres == 0;
    674 }
    675 
    676 /*
    677 ** Associate sets of rules with zones.
    678 */
    679 
    680 /*
    681 ** Sort by rule name.
    682 */
    683 
    684 static int
    685 rcomp(const void *cp1, const void *cp2)
    686 {
    687 	return strcmp(((const struct rule *) cp1)->r_name,
    688 		((const struct rule *) cp2)->r_name);
    689 }
    690 
    691 static void
    692 associate(void)
    693 {
    694 	struct zone *	zp;
    695 	struct rule *	rp;
    696 	int		base, out;
    697 	int		i, j;
    698 
    699 	if (nrules != 0) {
    700 		(void) qsort(rules, (size_t)nrules, sizeof *rules, rcomp);
    701 		for (i = 0; i < nrules - 1; ++i) {
    702 			if (strcmp(rules[i].r_name,
    703 				rules[i + 1].r_name) != 0)
    704 					continue;
    705 			if (strcmp(rules[i].r_filename,
    706 				rules[i + 1].r_filename) == 0)
    707 					continue;
    708 			eat(rules[i].r_filename, rules[i].r_linenum);
    709 			warning(_("same rule name in multiple files"));
    710 			eat(rules[i + 1].r_filename, rules[i + 1].r_linenum);
    711 			warning(_("same rule name in multiple files"));
    712 			for (j = i + 2; j < nrules; ++j) {
    713 				if (strcmp(rules[i].r_name,
    714 					rules[j].r_name) != 0)
    715 						break;
    716 				if (strcmp(rules[i].r_filename,
    717 					rules[j].r_filename) == 0)
    718 						continue;
    719 				if (strcmp(rules[i + 1].r_filename,
    720 					rules[j].r_filename) == 0)
    721 						continue;
    722 				break;
    723 			}
    724 			i = j - 1;
    725 		}
    726 	}
    727 	for (i = 0; i < nzones; ++i) {
    728 		zp = &zones[i];
    729 		zp->z_rules = NULL;
    730 		zp->z_nrules = 0;
    731 	}
    732 	for (base = 0; base < nrules; base = out) {
    733 		rp = &rules[base];
    734 		for (out = base + 1; out < nrules; ++out)
    735 			if (strcmp(rp->r_name, rules[out].r_name) != 0)
    736 				break;
    737 		for (i = 0; i < nzones; ++i) {
    738 			zp = &zones[i];
    739 			if (strcmp(zp->z_rule, rp->r_name) != 0)
    740 				continue;
    741 			zp->z_rules = rp;
    742 			zp->z_nrules = out - base;
    743 		}
    744 	}
    745 	for (i = 0; i < nzones; ++i) {
    746 		zp = &zones[i];
    747 		if (zp->z_nrules == 0) {
    748 			/*
    749 			** Maybe we have a local standard time offset.
    750 			*/
    751 			eat(zp->z_filename, zp->z_linenum);
    752 			zp->z_stdoff = gethms(zp->z_rule, _("unruly zone"),
    753 				TRUE);
    754 			/*
    755 			** Note, though, that if there's no rule,
    756 			** a '%s' in the format is a bad thing.
    757 			*/
    758 			if (strchr(zp->z_format, '%') != 0)
    759 				error(_("%s in ruleless zone"));
    760 		}
    761 	}
    762 	if (errors)
    763 		exit(EXIT_FAILURE);
    764 }
    765 
    766 static void
    767 infile(const char *name)
    768 {
    769 	FILE *			fp;
    770 	char **		fields;
    771 	char *			cp;
    772 	const struct lookup *	lp;
    773 	int			nfields;
    774 	int			wantcont;
    775 	int			num;
    776 	char				buf[BUFSIZ];
    777 
    778 	if (strcmp(name, "-") == 0) {
    779 		name = _("standard input");
    780 		fp = stdin;
    781 	} else if ((fp = fopen(name, "r")) == NULL) {
    782 		const char *e = strerror(errno);
    783 
    784 		(void) fprintf(stderr, _("%s: Can't open %s: %s\n"),
    785 			progname, name, e);
    786 		exit(EXIT_FAILURE);
    787 	}
    788 	wantcont = FALSE;
    789 	for (num = 1; ; ++num) {
    790 		eat(name, num);
    791 		if (fgets(buf, (int) sizeof buf, fp) != buf)
    792 			break;
    793 		cp = strchr(buf, '\n');
    794 		if (cp == NULL) {
    795 			error(_("line too zic_t"));
    796 			exit(EXIT_FAILURE);
    797 		}
    798 		*cp = '\0';
    799 		fields = getfields(buf);
    800 		nfields = 0;
    801 		while (fields[nfields] != NULL) {
    802 			static char	nada;
    803 
    804 			if (strcmp(fields[nfields], "-") == 0)
    805 				fields[nfields] = &nada;
    806 			++nfields;
    807 		}
    808 		if (nfields == 0) {
    809 			/* nothing to do */
    810 		} else if (wantcont) {
    811 			wantcont = inzcont(fields, nfields);
    812 		} else {
    813 			lp = byword(fields[0], line_codes);
    814 			if (lp == NULL)
    815 				error(_("input line of unknown type"));
    816 			else switch ((int) (lp->l_value)) {
    817 				case LC_RULE:
    818 					inrule(fields, nfields);
    819 					wantcont = FALSE;
    820 					break;
    821 				case LC_ZONE:
    822 					wantcont = inzone(fields, nfields);
    823 					break;
    824 				case LC_LINK:
    825 					inlink(fields, nfields);
    826 					wantcont = FALSE;
    827 					break;
    828 				case LC_LEAP:
    829 					if (name != leapsec)
    830 						(void) fprintf(stderr,
    831 _("%s: Leap line in non leap seconds file %s\n"),
    832 							progname, name);
    833 					else	inleap(fields, nfields);
    834 					wantcont = FALSE;
    835 					break;
    836 				default:	/* "cannot happen" */
    837 					(void) fprintf(stderr,
    838 _("%s: panic: Invalid l_value %d\n"),
    839 						progname, lp->l_value);
    840 					exit(EXIT_FAILURE);
    841 			}
    842 		}
    843 		free(fields);
    844 	}
    845 	if (ferror(fp)) {
    846 		(void) fprintf(stderr, _("%s: Error reading %s\n"),
    847 			progname, filename);
    848 		exit(EXIT_FAILURE);
    849 	}
    850 	if (fp != stdin && fclose(fp)) {
    851 		const char *e = strerror(errno);
    852 
    853 		(void) fprintf(stderr, _("%s: Error closing %s: %s\n"),
    854 			progname, filename, e);
    855 		exit(EXIT_FAILURE);
    856 	}
    857 	if (wantcont)
    858 		error(_("expected continuation line not found"));
    859 }
    860 
    861 /*
    862 ** Convert a string of one of the forms
    863 **	h	-h	hh:mm	-hh:mm	hh:mm:ss	-hh:mm:ss
    864 ** into a number of seconds.
    865 ** A null string maps to zero.
    866 ** Call error with errstring and return zero on errors.
    867 */
    868 
    869 static zic_t
    870 gethms(const char *string, const char *const errstring, const int signable)
    871 {
    872 	long 	lhh;
    873 	zic_t	hh;
    874 	int	mm, ss, sign;
    875 
    876 	if (string == NULL || *string == '\0')
    877 		return 0;
    878 	if (!signable)
    879 		sign = 1;
    880 	else if (*string == '-') {
    881 		sign = -1;
    882 		++string;
    883 	} else	sign = 1;
    884 	if (sscanf(string, scheck(string, "%ld"), &lhh) == 1)
    885 		mm = ss = 0;
    886 	else if (sscanf(string, scheck(string, "%ld:%d"), &lhh, &mm) == 2)
    887 		ss = 0;
    888 	else if (sscanf(string, scheck(string, "%ld:%d:%d"),
    889 		&lhh, &mm, &ss) != 3) {
    890 			error(errstring);
    891 			return 0;
    892 	}
    893 	hh = lhh;
    894 	if (hh < 0 ||
    895 		mm < 0 || mm >= MINSPERHOUR ||
    896 		ss < 0 || ss > SECSPERMIN) {
    897 			error(errstring);
    898 			return 0;
    899 	}
    900 	if (LONG_MAX / SECSPERHOUR < hh) {
    901 		error(_("time overflow"));
    902 		return 0;
    903 	}
    904 	if (noise && hh == HOURSPERDAY && mm == 0 && ss == 0)
    905 		warning(_("24:00 not handled by pre-1998 versions of zic"));
    906 	if (noise && (hh > HOURSPERDAY ||
    907 		(hh == HOURSPERDAY && (mm != 0 || ss != 0))))
    908 warning(_("values over 24 hours not handled by pre-2007 versions of zic"));
    909 	return oadd(eitol(sign) * hh * eitol(SECSPERHOUR),
    910 		    eitol(sign) * (eitol(mm) * eitol(SECSPERMIN) + eitol(ss)));
    911 }
    912 
    913 static void
    914 inrule(char **const fields, const int nfields)
    915 {
    916 	static struct rule	r;
    917 
    918 	if (nfields != RULE_FIELDS) {
    919 		error(_("wrong number of fields on Rule line"));
    920 		return;
    921 	}
    922 	if (*fields[RF_NAME] == '\0') {
    923 		error(_("nameless rule"));
    924 		return;
    925 	}
    926 	r.r_filename = filename;
    927 	r.r_linenum = linenum;
    928 	r.r_stdoff = gethms(fields[RF_STDOFF], _("invalid saved time"), TRUE);
    929 	rulesub(&r, fields[RF_LOYEAR], fields[RF_HIYEAR], fields[RF_COMMAND],
    930 		fields[RF_MONTH], fields[RF_DAY], fields[RF_TOD]);
    931 	r.r_name = ecpyalloc(fields[RF_NAME]);
    932 	r.r_abbrvar = ecpyalloc(fields[RF_ABBRVAR]);
    933 	if (max_abbrvar_len < strlen(r.r_abbrvar))
    934 		max_abbrvar_len = strlen(r.r_abbrvar);
    935 	rules = erealloc(rules, (nrules + 1) * sizeof *rules);
    936 	rules[nrules++] = r;
    937 }
    938 
    939 static int
    940 inzone(char **const fields, const int nfields)
    941 {
    942 	int	i;
    943 	static char *	buf;
    944 
    945 	if (nfields < ZONE_MINFIELDS || nfields > ZONE_MAXFIELDS) {
    946 		error(_("wrong number of fields on Zone line"));
    947 		return FALSE;
    948 	}
    949 	if (strcmp(fields[ZF_NAME], TZDEFAULT) == 0 && lcltime != NULL) {
    950 		buf = erealloc(buf, 132 + strlen(TZDEFAULT));
    951 		(void)sprintf(buf,	/* XXX: sprintf is safe */
    952 _("\"Zone %s\" line and -l option are mutually exclusive"),
    953 			TZDEFAULT);
    954 		error(buf);
    955 		return FALSE;
    956 	}
    957 	if (strcmp(fields[ZF_NAME], TZDEFRULES) == 0 && psxrules != NULL) {
    958 		buf = erealloc(buf, 132 + strlen(TZDEFRULES));
    959 		(void)sprintf(buf,	/* XXX: sprintf is safe */
    960 _("\"Zone %s\" line and -p option are mutually exclusive"),
    961 			TZDEFRULES);
    962 		error(buf);
    963 		return FALSE;
    964 	}
    965 	for (i = 0; i < nzones; ++i)
    966 		if (zones[i].z_name != NULL &&
    967 			strcmp(zones[i].z_name, fields[ZF_NAME]) == 0) {
    968 				buf = erealloc(buf, 132 +
    969 					strlen(fields[ZF_NAME]) +
    970 					strlen(zones[i].z_filename));
    971 				(void)sprintf(buf,	/* XXX: sprintf is safe */
    972 _("duplicate zone name %s (file \"%s\", line %d)"),
    973 					fields[ZF_NAME],
    974 					zones[i].z_filename,
    975 					zones[i].z_linenum);
    976 				error(buf);
    977 				return FALSE;
    978 		}
    979 	return inzsub(fields, nfields, FALSE);
    980 }
    981 
    982 static int
    983 inzcont(char **const fields, const int nfields)
    984 {
    985 	if (nfields < ZONEC_MINFIELDS || nfields > ZONEC_MAXFIELDS) {
    986 		error(_("wrong number of fields on Zone continuation line"));
    987 		return FALSE;
    988 	}
    989 	return inzsub(fields, nfields, TRUE);
    990 }
    991 
    992 static int
    993 inzsub(char **const fields, const int nfields, const int iscont)
    994 {
    995 	char *		cp;
    996 	static struct zone	z;
    997 	int		i_gmtoff, i_rule, i_format;
    998 	int		i_untilyear, i_untilmonth;
    999 	int		i_untilday, i_untiltime;
   1000 	int		hasuntil;
   1001 
   1002 	if (iscont) {
   1003 		i_gmtoff = ZFC_GMTOFF;
   1004 		i_rule = ZFC_RULE;
   1005 		i_format = ZFC_FORMAT;
   1006 		i_untilyear = ZFC_TILYEAR;
   1007 		i_untilmonth = ZFC_TILMONTH;
   1008 		i_untilday = ZFC_TILDAY;
   1009 		i_untiltime = ZFC_TILTIME;
   1010 		z.z_name = NULL;
   1011 	} else {
   1012 		i_gmtoff = ZF_GMTOFF;
   1013 		i_rule = ZF_RULE;
   1014 		i_format = ZF_FORMAT;
   1015 		i_untilyear = ZF_TILYEAR;
   1016 		i_untilmonth = ZF_TILMONTH;
   1017 		i_untilday = ZF_TILDAY;
   1018 		i_untiltime = ZF_TILTIME;
   1019 		z.z_name = ecpyalloc(fields[ZF_NAME]);
   1020 	}
   1021 	z.z_filename = filename;
   1022 	z.z_linenum = linenum;
   1023 	z.z_gmtoff = gethms(fields[i_gmtoff], _("invalid UTC offset"), TRUE);
   1024 	if ((cp = strchr(fields[i_format], '%')) != 0) {
   1025 		if (*++cp != 's' || strchr(cp, '%') != 0) {
   1026 			error(_("invalid abbreviation format"));
   1027 			return FALSE;
   1028 		}
   1029 	}
   1030 	z.z_rule = ecpyalloc(fields[i_rule]);
   1031 	z.z_format = ecpyalloc(fields[i_format]);
   1032 	if (max_format_len < strlen(z.z_format))
   1033 		max_format_len = strlen(z.z_format);
   1034 	hasuntil = nfields > i_untilyear;
   1035 	if (hasuntil) {
   1036 		z.z_untilrule.r_filename = filename;
   1037 		z.z_untilrule.r_linenum = linenum;
   1038 		rulesub(&z.z_untilrule,
   1039 			fields[i_untilyear],
   1040 			"only",
   1041 			"",
   1042 			(nfields > i_untilmonth) ?
   1043 			fields[i_untilmonth] : "Jan",
   1044 			(nfields > i_untilday) ? fields[i_untilday] : "1",
   1045 			(nfields > i_untiltime) ? fields[i_untiltime] : "0");
   1046 		z.z_untiltime = rpytime(&z.z_untilrule,
   1047 			z.z_untilrule.r_loyear);
   1048 		if (iscont && nzones > 0 &&
   1049 			z.z_untiltime > min_time &&
   1050 			z.z_untiltime < max_time &&
   1051 			zones[nzones - 1].z_untiltime > min_time &&
   1052 			zones[nzones - 1].z_untiltime < max_time &&
   1053 			zones[nzones - 1].z_untiltime >= z.z_untiltime) {
   1054 				error(_(
   1055 "Zone continuation line end time is not after end time of previous line"
   1056 					));
   1057 				return FALSE;
   1058 		}
   1059 	}
   1060 	zones = erealloc(zones, (nzones + 1) * sizeof *zones);
   1061 	zones[nzones++] = z;
   1062 	/*
   1063 	** If there was an UNTIL field on this line,
   1064 	** there's more information about the zone on the next line.
   1065 	*/
   1066 	return hasuntil;
   1067 }
   1068 
   1069 static void
   1070 inleap(char **const fields, const int nfields)
   1071 {
   1072 	const char *		cp;
   1073 	const struct lookup *	lp;
   1074 	int			i, j;
   1075 	int				year, month, day;
   1076 	zic_t				dayoff, tod;
   1077 	zic_t				t;
   1078 
   1079 	if (nfields != LEAP_FIELDS) {
   1080 		error(_("wrong number of fields on Leap line"));
   1081 		return;
   1082 	}
   1083 	dayoff = 0;
   1084 	cp = fields[LP_YEAR];
   1085 	if (sscanf(cp, scheck(cp, "%d"), &year) != 1) {
   1086 		/*
   1087 		** Leapin' Lizards!
   1088 		*/
   1089 		error(_("invalid leaping year"));
   1090 		return;
   1091 	}
   1092 	if (!leapseen || leapmaxyear < year)
   1093 		leapmaxyear = year;
   1094 	if (!leapseen || leapminyear > year)
   1095 		leapminyear = year;
   1096 	leapseen = TRUE;
   1097 	j = EPOCH_YEAR;
   1098 	while (j != year) {
   1099 		if (year > j) {
   1100 			i = len_years[isleap(j)];
   1101 			++j;
   1102 		} else {
   1103 			--j;
   1104 			i = -len_years[isleap(j)];
   1105 		}
   1106 		dayoff = oadd(dayoff, eitol(i));
   1107 	}
   1108 	if ((lp = byword(fields[LP_MONTH], mon_names)) == NULL) {
   1109 		error(_("invalid month name"));
   1110 		return;
   1111 	}
   1112 	month = lp->l_value;
   1113 	j = TM_JANUARY;
   1114 	while (j != month) {
   1115 		i = len_months[isleap(year)][j];
   1116 		dayoff = oadd(dayoff, eitol(i));
   1117 		++j;
   1118 	}
   1119 	cp = fields[LP_DAY];
   1120 	if (sscanf(cp, scheck(cp, "%d"), &day) != 1 ||
   1121 		day <= 0 || day > len_months[isleap(year)][month]) {
   1122 			error(_("invalid day of month"));
   1123 			return;
   1124 	}
   1125 	dayoff = oadd(dayoff, eitol(day - 1));
   1126 	if (dayoff < 0 && !TYPE_SIGNED(zic_t)) {
   1127 		error(_("time before zero"));
   1128 		return;
   1129 	}
   1130 	if (dayoff < min_time / SECSPERDAY) {
   1131 		error(_("time too small"));
   1132 		return;
   1133 	}
   1134 	if (dayoff > max_time / SECSPERDAY) {
   1135 		error(_("time too large"));
   1136 		return;
   1137 	}
   1138 	t = (zic_t) dayoff * SECSPERDAY;
   1139 	tod = gethms(fields[LP_TIME], _("invalid time of day"), FALSE);
   1140 	cp = fields[LP_CORR];
   1141 	{
   1142 		int	positive;
   1143 		int		count;
   1144 
   1145 		if (strcmp(cp, "") == 0) { /* infile() turns "-" into "" */
   1146 			positive = FALSE;
   1147 			count = 1;
   1148 		} else if (strcmp(cp, "--") == 0) {
   1149 			positive = FALSE;
   1150 			count = 2;
   1151 		} else if (strcmp(cp, "+") == 0) {
   1152 			positive = TRUE;
   1153 			count = 1;
   1154 		} else if (strcmp(cp, "++") == 0) {
   1155 			positive = TRUE;
   1156 			count = 2;
   1157 		} else {
   1158 			error(_("illegal CORRECTION field on Leap line"));
   1159 			return;
   1160 		}
   1161 		if ((lp = byword(fields[LP_ROLL], leap_types)) == NULL) {
   1162 			error(_(
   1163 				"illegal Rolling/Stationary field on Leap line"
   1164 				));
   1165 			return;
   1166 		}
   1167 		leapadd(tadd(t, tod), positive, lp->l_value, count);
   1168 	}
   1169 }
   1170 
   1171 static void
   1172 inlink(char **const fields, const int nfields)
   1173 {
   1174 	struct link	l;
   1175 
   1176 	if (nfields != LINK_FIELDS) {
   1177 		error(_("wrong number of fields on Link line"));
   1178 		return;
   1179 	}
   1180 	if (*fields[LF_FROM] == '\0') {
   1181 		error(_("blank FROM field on Link line"));
   1182 		return;
   1183 	}
   1184 	if (*fields[LF_TO] == '\0') {
   1185 		error(_("blank TO field on Link line"));
   1186 		return;
   1187 	}
   1188 	l.l_filename = filename;
   1189 	l.l_linenum = linenum;
   1190 	l.l_from = ecpyalloc(fields[LF_FROM]);
   1191 	l.l_to = ecpyalloc(fields[LF_TO]);
   1192 	links = erealloc(links, (nlinks + 1) * sizeof *links);
   1193 	links[nlinks++] = l;
   1194 }
   1195 
   1196 static void
   1197 rulesub(struct rule *const rp, const char *const loyearp,
   1198     const char *const hiyearp, const char *const typep,
   1199     const char *const monthp, const char *const dayp, const char *const timep)
   1200 {
   1201 	const struct lookup *	lp;
   1202 	const char *		cp;
   1203 	char *			dp;
   1204 	char *			ep;
   1205 
   1206 	if ((lp = byword(monthp, mon_names)) == NULL) {
   1207 		error(_("invalid month name"));
   1208 		return;
   1209 	}
   1210 	rp->r_month = lp->l_value;
   1211 	rp->r_todisstd = FALSE;
   1212 	rp->r_todisgmt = FALSE;
   1213 	dp = ecpyalloc(timep);
   1214 	if (*dp != '\0') {
   1215 		ep = dp + strlen(dp) - 1;
   1216 		switch (lowerit(*ep)) {
   1217 			case 's':	/* Standard */
   1218 				rp->r_todisstd = TRUE;
   1219 				rp->r_todisgmt = FALSE;
   1220 				*ep = '\0';
   1221 				break;
   1222 			case 'w':	/* Wall */
   1223 				rp->r_todisstd = FALSE;
   1224 				rp->r_todisgmt = FALSE;
   1225 				*ep = '\0';
   1226 				break;
   1227 			case 'g':	/* Greenwich */
   1228 			case 'u':	/* Universal */
   1229 			case 'z':	/* Zulu */
   1230 				rp->r_todisstd = TRUE;
   1231 				rp->r_todisgmt = TRUE;
   1232 				*ep = '\0';
   1233 				break;
   1234 		}
   1235 	}
   1236 	rp->r_tod = gethms(dp, _("invalid time of day"), FALSE);
   1237 	free(dp);
   1238 	/*
   1239 	** Year work.
   1240 	*/
   1241 	cp = loyearp;
   1242 	lp = byword(cp, begin_years);
   1243 	rp->r_lowasnum = lp == NULL;
   1244 	if (!rp->r_lowasnum) switch ((int) lp->l_value) {
   1245 		case YR_MINIMUM:
   1246 			rp->r_loyear = INT_MIN;
   1247 			break;
   1248 		case YR_MAXIMUM:
   1249 			rp->r_loyear = INT_MAX;
   1250 			break;
   1251 		default:	/* "cannot happen" */
   1252 			(void) fprintf(stderr,
   1253 				_("%s: panic: Invalid l_value %d\n"),
   1254 				progname, lp->l_value);
   1255 			exit(EXIT_FAILURE);
   1256 	} else if (sscanf(cp, scheck(cp, "%d"), &rp->r_loyear) != 1) {
   1257 		error(_("invalid starting year"));
   1258 		return;
   1259 	}
   1260 	cp = hiyearp;
   1261 	lp = byword(cp, end_years);
   1262 	rp->r_hiwasnum = lp == NULL;
   1263 	if (!rp->r_hiwasnum) switch ((int) lp->l_value) {
   1264 		case YR_MINIMUM:
   1265 			rp->r_hiyear = INT_MIN;
   1266 			break;
   1267 		case YR_MAXIMUM:
   1268 			rp->r_hiyear = INT_MAX;
   1269 			break;
   1270 		case YR_ONLY:
   1271 			rp->r_hiyear = rp->r_loyear;
   1272 			break;
   1273 		default:	/* "cannot happen" */
   1274 			(void) fprintf(stderr,
   1275 				_("%s: panic: Invalid l_value %d\n"),
   1276 				progname, lp->l_value);
   1277 			exit(EXIT_FAILURE);
   1278 	} else if (sscanf(cp, scheck(cp, "%d"), &rp->r_hiyear) != 1) {
   1279 		error(_("invalid ending year"));
   1280 		return;
   1281 	}
   1282 	if (rp->r_loyear > rp->r_hiyear) {
   1283 		error(_("starting year greater than ending year"));
   1284 		return;
   1285 	}
   1286 	if (*typep == '\0')
   1287 		rp->r_yrtype = NULL;
   1288 	else {
   1289 		if (rp->r_loyear == rp->r_hiyear) {
   1290 			error(_("typed single year"));
   1291 			return;
   1292 		}
   1293 		rp->r_yrtype = ecpyalloc(typep);
   1294 	}
   1295 	/*
   1296 	** Day work.
   1297 	** Accept things such as:
   1298 	**	1
   1299 	**	last-Sunday
   1300 	**	Sun<=20
   1301 	**	Sun>=7
   1302 	*/
   1303 	dp = ecpyalloc(dayp);
   1304 	if ((lp = byword(dp, lasts)) != NULL) {
   1305 		rp->r_dycode = DC_DOWLEQ;
   1306 		rp->r_wday = lp->l_value;
   1307 		rp->r_dayofmonth = len_months[1][rp->r_month];
   1308 	} else {
   1309 		if ((ep = strchr(dp, '<')) != 0)
   1310 			rp->r_dycode = DC_DOWLEQ;
   1311 		else if ((ep = strchr(dp, '>')) != 0)
   1312 			rp->r_dycode = DC_DOWGEQ;
   1313 		else {
   1314 			ep = dp;
   1315 			rp->r_dycode = DC_DOM;
   1316 		}
   1317 		if (rp->r_dycode != DC_DOM) {
   1318 			*ep++ = 0;
   1319 			if (*ep++ != '=') {
   1320 				error(_("invalid day of month"));
   1321 				free(dp);
   1322 				return;
   1323 			}
   1324 			if ((lp = byword(dp, wday_names)) == NULL) {
   1325 				error(_("invalid weekday name"));
   1326 				free(dp);
   1327 				return;
   1328 			}
   1329 			rp->r_wday = lp->l_value;
   1330 		}
   1331 		if (sscanf(ep, scheck(ep, "%d"), &rp->r_dayofmonth) != 1 ||
   1332 			rp->r_dayofmonth <= 0 ||
   1333 			(rp->r_dayofmonth > len_months[1][rp->r_month])) {
   1334 				error(_("invalid day of month"));
   1335 				free(dp);
   1336 				return;
   1337 		}
   1338 	}
   1339 	free(dp);
   1340 }
   1341 
   1342 static void
   1343 convert(const zic_t val, char *const buf)
   1344 {
   1345 	int	i;
   1346 	int	shift;
   1347 	unsigned char *const b = (unsigned char *) buf;
   1348 
   1349 	for (i = 0, shift = 24; i < 4; ++i, shift -= 8)
   1350 		b[i] = val >> shift;
   1351 }
   1352 
   1353 static void
   1354 convert64(const zic_t val, char *const buf)
   1355 {
   1356 	int	i;
   1357 	int	shift;
   1358 	unsigned char *const b = (unsigned char *) buf;
   1359 
   1360 	for (i = 0, shift = 56; i < 8; ++i, shift -= 8)
   1361 		b[i] = val >> shift;
   1362 }
   1363 
   1364 static void
   1365 puttzcode(const zic_t val, FILE *const fp)
   1366 {
   1367 	char	buf[4];
   1368 
   1369 	convert(val, buf);
   1370 	(void) fwrite(buf, sizeof buf, (size_t) 1, fp);
   1371 }
   1372 
   1373 static void
   1374 puttzcode64(const zic_t val, FILE *const fp)
   1375 {
   1376 	char	buf[8];
   1377 
   1378 	convert64(val, buf);
   1379 	(void) fwrite(buf, sizeof buf, (size_t) 1, fp);
   1380 }
   1381 
   1382 static int
   1383 atcomp(const void *avp, const void *bvp)
   1384 {
   1385 	const zic_t	a = ((const struct attype *) avp)->at;
   1386 	const zic_t	b = ((const struct attype *) bvp)->at;
   1387 
   1388 	return (a < b) ? -1 : (a > b);
   1389 }
   1390 
   1391 static int
   1392 is32(const zic_t x)
   1393 {
   1394 	return INT32_MIN <= x && x <= INT32_MAX;
   1395 }
   1396 
   1397 static void
   1398 writezone(const char *const name, const char *const string)
   1399 {
   1400 	FILE *			fp;
   1401 	int			i, j;
   1402 	int			leapcnt32, leapi32;
   1403 	int			timecnt32, timei32;
   1404 	int			pass;
   1405 	static char *			fullname;
   1406 	static const struct tzhead	tzh0;
   1407 	static struct tzhead		tzh;
   1408 	zic_t				ats[TZ_MAX_TIMES];
   1409 	unsigned char			types[TZ_MAX_TIMES];
   1410 
   1411 	/*
   1412 	** Sort.
   1413 	*/
   1414 	if (timecnt > 1)
   1415 		(void) qsort(attypes, (size_t) timecnt, sizeof *attypes,
   1416 		    atcomp);
   1417 	/*
   1418 	** Optimize.
   1419 	*/
   1420 	{
   1421 		int	fromi;
   1422 		int	toi;
   1423 
   1424 		toi = 0;
   1425 		fromi = 0;
   1426 		while (fromi < timecnt && attypes[fromi].at < min_time)
   1427 			++fromi;
   1428 		if (isdsts[0] == 0)
   1429 			while (fromi < timecnt && attypes[fromi].type == 0)
   1430 				++fromi;	/* handled by default rule */
   1431 		for ( ; fromi < timecnt; ++fromi) {
   1432 			if (toi != 0 && ((attypes[fromi].at +
   1433 				gmtoffs[attypes[toi - 1].type]) <=
   1434 				(attypes[toi - 1].at + gmtoffs[toi == 1 ? 0
   1435 				: attypes[toi - 2].type]))) {
   1436 					attypes[toi - 1].type =
   1437 						attypes[fromi].type;
   1438 					continue;
   1439 			}
   1440 			if (toi == 0 ||
   1441 				attypes[toi - 1].type != attypes[fromi].type)
   1442 					attypes[toi++] = attypes[fromi];
   1443 		}
   1444 		timecnt = toi;
   1445 	}
   1446 	/*
   1447 	** Transfer.
   1448 	*/
   1449 	for (i = 0; i < timecnt; ++i) {
   1450 		ats[i] = attypes[i].at;
   1451 		types[i] = attypes[i].type;
   1452 	}
   1453 	/*
   1454 	** Correct for leap seconds.
   1455 	*/
   1456 	for (i = 0; i < timecnt; ++i) {
   1457 		j = leapcnt;
   1458 		while (--j >= 0)
   1459 			if (ats[i] > trans[j] - corr[j]) {
   1460 				ats[i] = tadd(ats[i], corr[j]);
   1461 				break;
   1462 			}
   1463 	}
   1464 	/*
   1465 	** Figure out 32-bit-limited starts and counts.
   1466 	*/
   1467 	timecnt32 = timecnt;
   1468 	timei32 = 0;
   1469 	leapcnt32 = leapcnt;
   1470 	leapi32 = 0;
   1471 	while (timecnt32 > 0 && !is32(ats[timecnt32 - 1]))
   1472 		--timecnt32;
   1473 	while (timecnt32 > 0 && !is32(ats[timei32])) {
   1474 		--timecnt32;
   1475 		++timei32;
   1476 	}
   1477 	while (leapcnt32 > 0 && !is32(trans[leapcnt32 - 1]))
   1478 		--leapcnt32;
   1479 	while (leapcnt32 > 0 && !is32(trans[leapi32])) {
   1480 		--leapcnt32;
   1481 		++leapi32;
   1482 	}
   1483 	fullname = erealloc(fullname,
   1484 	    strlen(directory) + 1 + strlen(name) + 1);
   1485 	(void) sprintf(fullname, "%s/%s", directory, name);	/* XXX: sprintf is safe */
   1486 	/*
   1487 	** Remove old file, if any, to snap links.
   1488 	*/
   1489 	if (!itsdir(fullname) && remove(fullname) != 0 && errno != ENOENT) {
   1490 		const char *e = strerror(errno);
   1491 
   1492 		(void) fprintf(stderr, _("%s: Can't remove %s: %s\n"),
   1493 			progname, fullname, e);
   1494 		exit(EXIT_FAILURE);
   1495 	}
   1496 	if ((fp = fopen(fullname, "wb")) == NULL) {
   1497 		if (mkdirs(fullname) != 0)
   1498 			exit(EXIT_FAILURE);
   1499 		if ((fp = fopen(fullname, "wb")) == NULL) {
   1500 			const char *e = strerror(errno);
   1501 
   1502 			(void) fprintf(stderr, _("%s: Can't create %s: %s\n"),
   1503 				progname, fullname, e);
   1504 			exit(EXIT_FAILURE);
   1505 		}
   1506 	}
   1507 	for (pass = 1; pass <= 2; ++pass) {
   1508 		int	thistimei, thistimecnt;
   1509 		int	thisleapi, thisleapcnt;
   1510 		int	thistimelim, thisleaplim;
   1511 		int		writetype[TZ_MAX_TIMES];
   1512 		int		typemap[TZ_MAX_TYPES];
   1513 		int	thistypecnt;
   1514 		char		thischars[TZ_MAX_CHARS];
   1515 		char		thischarcnt;
   1516 		int 		indmap[TZ_MAX_CHARS];
   1517 
   1518 		if (pass == 1) {
   1519 			thistimei = timei32;
   1520 			thistimecnt = timecnt32;
   1521 			thisleapi = leapi32;
   1522 			thisleapcnt = leapcnt32;
   1523 		} else {
   1524 			thistimei = 0;
   1525 			thistimecnt = timecnt;
   1526 			thisleapi = 0;
   1527 			thisleapcnt = leapcnt;
   1528 		}
   1529 		thistimelim = thistimei + thistimecnt;
   1530 		thisleaplim = thisleapi + thisleapcnt;
   1531 		for (i = 0; i < typecnt; ++i)
   1532 			writetype[i] = thistimecnt == timecnt;
   1533 		if (thistimecnt == 0) {
   1534 			/*
   1535 			** No transition times fall in the current
   1536 			** (32- or 64-bit) window.
   1537 			*/
   1538 			if (typecnt != 0)
   1539 				writetype[typecnt - 1] = TRUE;
   1540 		} else {
   1541 			for (i = thistimei - 1; i < thistimelim; ++i)
   1542 				if (i >= 0)
   1543 					writetype[types[i]] = TRUE;
   1544 			/*
   1545 			** For America/Godthab and Antarctica/Palmer
   1546 			*/
   1547 			if (thistimei == 0)
   1548 				writetype[0] = TRUE;
   1549 		}
   1550 #ifndef LEAVE_SOME_PRE_2011_SYSTEMS_IN_THE_LURCH
   1551 		/*
   1552 		** For some pre-2011 systems: if the last-to-be-written
   1553 		** standard (or daylight) type has an offset different from the
   1554 		** most recently used offset,
   1555 		** append an (unused) copy of the most recently used type
   1556 		** (to help get global "altzone" and "timezone" variables
   1557 		** set correctly).
   1558 		*/
   1559 		{
   1560 			int	mrudst, mrustd, hidst, histd, type;
   1561 
   1562 			hidst = histd = mrudst = mrustd = -1;
   1563 			for (i = thistimei; i < thistimelim; ++i)
   1564 				if (isdsts[types[i]])
   1565 					mrudst = types[i];
   1566 				else	mrustd = types[i];
   1567 			for (i = 0; i < typecnt; ++i)
   1568 				if (writetype[i]) {
   1569 					if (isdsts[i])
   1570 						hidst = i;
   1571 					else	histd = i;
   1572 				}
   1573 			if (hidst >= 0 && mrudst >= 0 && hidst != mrudst &&
   1574 				gmtoffs[hidst] != gmtoffs[mrudst]) {
   1575 					isdsts[mrudst] = -1;
   1576 					type = addtype(gmtoffs[mrudst],
   1577 						&chars[abbrinds[mrudst]],
   1578 						TRUE,
   1579 						ttisstds[mrudst],
   1580 						ttisgmts[mrudst]);
   1581 					isdsts[mrudst] = TRUE;
   1582 					writetype[type] = TRUE;
   1583 			}
   1584 			if (histd >= 0 && mrustd >= 0 && histd != mrustd &&
   1585 				gmtoffs[histd] != gmtoffs[mrustd]) {
   1586 					isdsts[mrustd] = -1;
   1587 					type = addtype(gmtoffs[mrustd],
   1588 						&chars[abbrinds[mrustd]],
   1589 						FALSE,
   1590 						ttisstds[mrustd],
   1591 						ttisgmts[mrustd]);
   1592 					isdsts[mrustd] = FALSE;
   1593 					writetype[type] = TRUE;
   1594 			}
   1595 		}
   1596 #endif /* !defined LEAVE_SOME_PRE_2011_SYSTEMS_IN_THE_LURCH */
   1597 		thistypecnt = 0;
   1598 		for (i = 0; i < typecnt; ++i)
   1599 			typemap[i] = writetype[i] ?  thistypecnt++ : -1;
   1600 		for (i = 0; i < (int)(sizeof indmap / sizeof indmap[0]); ++i)
   1601 			indmap[i] = -1;
   1602 		thischarcnt = 0;
   1603 		for (i = 0; i < typecnt; ++i) {
   1604 			char *	thisabbr;
   1605 
   1606 			if (!writetype[i])
   1607 				continue;
   1608 			if (indmap[abbrinds[i]] >= 0)
   1609 				continue;
   1610 			thisabbr = &chars[abbrinds[i]];
   1611 			for (j = 0; j < thischarcnt; ++j)
   1612 				if (strcmp(&thischars[j], thisabbr) == 0)
   1613 					break;
   1614 			if (j == thischarcnt) {
   1615 				(void) strcpy(&thischars[(int) thischarcnt],
   1616 					thisabbr);
   1617 				thischarcnt += strlen(thisabbr) + 1;
   1618 			}
   1619 			indmap[abbrinds[i]] = j;
   1620 		}
   1621 #define DO(field)	(void) fwrite(tzh.field, \
   1622 				sizeof tzh.field, (size_t) 1, fp)
   1623 		tzh = tzh0;
   1624 		(void) strncpy(tzh.tzh_magic, TZ_MAGIC, sizeof tzh.tzh_magic);
   1625 		tzh.tzh_version[0] = ZIC_VERSION;
   1626 		convert(eitol(thistypecnt), tzh.tzh_ttisgmtcnt);
   1627 		convert(eitol(thistypecnt), tzh.tzh_ttisstdcnt);
   1628 		convert(eitol(thisleapcnt), tzh.tzh_leapcnt);
   1629 		convert(eitol(thistimecnt), tzh.tzh_timecnt);
   1630 		convert(eitol(thistypecnt), tzh.tzh_typecnt);
   1631 		convert(eitol(thischarcnt), tzh.tzh_charcnt);
   1632 		DO(tzh_magic);
   1633 		DO(tzh_version);
   1634 		DO(tzh_reserved);
   1635 		DO(tzh_ttisgmtcnt);
   1636 		DO(tzh_ttisstdcnt);
   1637 		DO(tzh_leapcnt);
   1638 		DO(tzh_timecnt);
   1639 		DO(tzh_typecnt);
   1640 		DO(tzh_charcnt);
   1641 #undef DO
   1642 		for (i = thistimei; i < thistimelim; ++i)
   1643 			if (pass == 1)
   1644 				puttzcode(ats[i], fp);
   1645 			else	puttzcode64(ats[i], fp);
   1646 		for (i = thistimei; i < thistimelim; ++i) {
   1647 			unsigned char	uc;
   1648 
   1649 			uc = typemap[types[i]];
   1650 			(void) fwrite(&uc, sizeof uc, (size_t) 1, fp);
   1651 		}
   1652 		for (i = 0; i < typecnt; ++i)
   1653 			if (writetype[i]) {
   1654 				puttzcode(gmtoffs[i], fp);
   1655 				(void) putc(isdsts[i], fp);
   1656 				(void) putc((unsigned char) indmap[abbrinds[i]], fp);
   1657 			}
   1658 		if (thischarcnt != 0)
   1659 			(void) fwrite(thischars, sizeof thischars[0],
   1660 				(size_t) thischarcnt, fp);
   1661 		for (i = thisleapi; i < thisleaplim; ++i) {
   1662 			zic_t	todo;
   1663 
   1664 			if (roll[i]) {
   1665 				if (timecnt == 0 || trans[i] < ats[0]) {
   1666 					j = 0;
   1667 					while (isdsts[j])
   1668 						if (++j >= typecnt) {
   1669 							j = 0;
   1670 							break;
   1671 						}
   1672 				} else {
   1673 					j = 1;
   1674 					while (j < timecnt &&
   1675 						trans[i] >= ats[j])
   1676 							++j;
   1677 					j = types[j - 1];
   1678 				}
   1679 				todo = tadd(trans[i], -gmtoffs[j]);
   1680 			} else	todo = trans[i];
   1681 			if (pass == 1)
   1682 				puttzcode((zic_t) todo, fp);
   1683 			else	puttzcode64(todo, fp);
   1684 			puttzcode(corr[i], fp);
   1685 		}
   1686 		for (i = 0; i < typecnt; ++i)
   1687 			if (writetype[i])
   1688 				(void) putc(ttisstds[i], fp);
   1689 		for (i = 0; i < typecnt; ++i)
   1690 			if (writetype[i])
   1691 				(void) putc(ttisgmts[i], fp);
   1692 	}
   1693 	(void) fprintf(fp, "\n%s\n", string);
   1694 	if (ferror(fp) || fclose(fp)) {
   1695 		(void) fprintf(stderr, _("%s: Error writing %s\n"),
   1696 			progname, fullname);
   1697 		exit(EXIT_FAILURE);
   1698 	}
   1699 }
   1700 
   1701 static void
   1702 doabbr(char *const abbr, const int abbrlen, const char *const format,
   1703     const char *const letters, const int isdst, const int doquotes)
   1704 {
   1705 	char *	cp;
   1706 	char *	slashp;
   1707 	int	len;
   1708 
   1709 	slashp = strchr(format, '/');
   1710 	if (slashp == NULL) {
   1711 		if (letters == NULL)
   1712 			(void) strlcpy(abbr, format, abbrlen);
   1713 		else	(void) snprintf(abbr, abbrlen, format, letters);
   1714 	} else if (isdst) {
   1715 		(void) strlcpy(abbr, slashp + 1, abbrlen);
   1716 	} else {
   1717 		if (slashp > format)
   1718 			(void) strncpy(abbr, format, (size_t)(slashp - format));
   1719 		abbr[slashp - format] = '\0';
   1720 	}
   1721 	if (!doquotes)
   1722 		return;
   1723 	for (cp = abbr; *cp != '\0'; ++cp)
   1724 		if (strchr("ABCDEFGHIJKLMNOPQRSTUVWXYZ", *cp) == NULL &&
   1725 			strchr("abcdefghijklmnopqrstuvwxyz", *cp) == NULL)
   1726 				break;
   1727 	len = strlen(abbr);
   1728 	if (len > 0 && *cp == '\0')
   1729 		return;
   1730 	abbr[len + 2] = '\0';
   1731 	abbr[len + 1] = '>';
   1732 	for ( ; len > 0; --len)
   1733 		abbr[len] = abbr[len - 1];
   1734 	abbr[0] = '<';
   1735 }
   1736 
   1737 static void
   1738 updateminmax(const int x)
   1739 {
   1740 	if (min_year > x)
   1741 		min_year = x;
   1742 	if (max_year < x)
   1743 		max_year = x;
   1744 }
   1745 
   1746 static int
   1747 stringoffset(char *result, zic_t offset)
   1748 {
   1749 	int	hours;
   1750 	int	minutes;
   1751 	int	seconds;
   1752 
   1753 	result[0] = '\0';
   1754 	if (offset < 0) {
   1755 		(void) strcpy(result, "-");
   1756 		offset = -offset;
   1757 	}
   1758 	seconds = offset % SECSPERMIN;
   1759 	offset /= SECSPERMIN;
   1760 	minutes = offset % MINSPERHOUR;
   1761 	offset /= MINSPERHOUR;
   1762 	hours = offset;
   1763 	if (hours > HOURSPERDAY) {
   1764 		result[0] = '\0';
   1765 		return -1;
   1766 	}
   1767 	(void) sprintf(end(result), "%d", hours);
   1768 	if (minutes != 0 || seconds != 0) {
   1769 		(void) sprintf(end(result), ":%02d", minutes);
   1770 		if (seconds != 0)
   1771 			(void) sprintf(end(result), ":%02d", seconds);
   1772 	}
   1773 	return 0;
   1774 }
   1775 
   1776 static int
   1777 stringrule(char *result, const struct rule *const rp, const zic_t dstoff,
   1778     const zic_t gmtoff)
   1779 {
   1780 	zic_t	tod;
   1781 
   1782 	result = end(result);
   1783 	if (rp->r_dycode == DC_DOM) {
   1784 		int	month, total;
   1785 
   1786 		if (rp->r_dayofmonth == 29 && rp->r_month == TM_FEBRUARY)
   1787 			return -1;
   1788 		total = 0;
   1789 		for (month = 0; month < rp->r_month; ++month)
   1790 			total += len_months[0][month];
   1791 		(void) sprintf(result, "J%d", total + rp->r_dayofmonth);
   1792 	} else {
   1793 		int	week;
   1794 
   1795 		if (rp->r_dycode == DC_DOWGEQ) {
   1796 			if ((rp->r_dayofmonth % DAYSPERWEEK) != 1)
   1797 				return -1;
   1798 			week = 1 + rp->r_dayofmonth / DAYSPERWEEK;
   1799 		} else if (rp->r_dycode == DC_DOWLEQ) {
   1800 			if (rp->r_dayofmonth == len_months[1][rp->r_month])
   1801 				week = 5;
   1802 			else {
   1803 				if ((rp->r_dayofmonth % DAYSPERWEEK) != 0)
   1804 					return -1;
   1805 				week = rp->r_dayofmonth / DAYSPERWEEK;
   1806 			}
   1807 		} else	return -1;	/* "cannot happen" */
   1808 		(void) sprintf(result, "M%d.%d.%d",
   1809 			rp->r_month + 1, week, rp->r_wday);
   1810 	}
   1811 	tod = rp->r_tod;
   1812 	if (rp->r_todisgmt)
   1813 		tod += gmtoff;
   1814 	if (rp->r_todisstd && rp->r_stdoff == 0)
   1815 		tod += dstoff;
   1816 	if (tod < 0) {
   1817 		result[0] = '\0';
   1818 		return -1;
   1819 	}
   1820 	if (tod != 2 * SECSPERMIN * MINSPERHOUR) {
   1821 		(void) strcat(result, "/");
   1822 		if (stringoffset(end(result), tod) != 0)
   1823 			return -1;
   1824 	}
   1825 	return 0;
   1826 }
   1827 
   1828 static void
   1829 stringzone(char *result, const int resultlen, const struct zone *const zpfirst,
   1830     const int zonecount)
   1831 {
   1832 	const struct zone *	zp;
   1833 	struct rule *		rp;
   1834 	struct rule *		stdrp;
   1835 	struct rule *		dstrp;
   1836 	int			i;
   1837 	const char *		abbrvar;
   1838 
   1839 	result[0] = '\0';
   1840 	zp = zpfirst + zonecount - 1;
   1841 	stdrp = dstrp = NULL;
   1842 	for (i = 0; i < zp->z_nrules; ++i) {
   1843 		rp = &zp->z_rules[i];
   1844 		if (rp->r_hiwasnum || rp->r_hiyear != INT_MAX)
   1845 			continue;
   1846 		if (rp->r_yrtype != NULL)
   1847 			continue;
   1848 		if (rp->r_stdoff == 0) {
   1849 			if (stdrp == NULL)
   1850 				stdrp = rp;
   1851 			else	return;
   1852 		} else {
   1853 			if (dstrp == NULL)
   1854 				dstrp = rp;
   1855 			else	return;
   1856 		}
   1857 	}
   1858 	if (stdrp == NULL && dstrp == NULL) {
   1859 		/*
   1860 		** There are no rules running through "max".
   1861 		** Let's find the latest rule.
   1862 		*/
   1863 		for (i = 0; i < zp->z_nrules; ++i) {
   1864 			rp = &zp->z_rules[i];
   1865 			if (stdrp == NULL || rp->r_hiyear > stdrp->r_hiyear ||
   1866 				(rp->r_hiyear == stdrp->r_hiyear &&
   1867 				(rp->r_month > stdrp->r_month ||
   1868 				(rp->r_month == stdrp->r_month &&
   1869 				rp->r_dayofmonth > stdrp->r_dayofmonth))))
   1870 					stdrp = rp;
   1871 		}
   1872 		if (stdrp != NULL && stdrp->r_stdoff != 0)
   1873 			return;	/* We end up in DST (a POSIX no-no). */
   1874 		/*
   1875 		** Horrid special case: if year is 2037,
   1876 		** presume this is a zone handled on a year-by-year basis;
   1877 		** do not try to apply a rule to the zone.
   1878 		*/
   1879 		if (stdrp != NULL && stdrp->r_hiyear == 2037)
   1880 			return;
   1881 	}
   1882 	if (stdrp == NULL && (zp->z_nrules != 0 || zp->z_stdoff != 0))
   1883 		return;
   1884 	abbrvar = (stdrp == NULL) ? "" : stdrp->r_abbrvar;
   1885 	doabbr(result, resultlen, zp->z_format, abbrvar, FALSE, TRUE);
   1886 	if (stringoffset(end(result), -zp->z_gmtoff) != 0) {
   1887 		result[0] = '\0';
   1888 		return;
   1889 	}
   1890 	if (dstrp == NULL)
   1891 		return;
   1892 	doabbr(end(result), resultlen - strlen(result),
   1893 		zp->z_format, dstrp->r_abbrvar, TRUE, TRUE);
   1894 	if (dstrp->r_stdoff != SECSPERMIN * MINSPERHOUR)
   1895 		if (stringoffset(end(result),
   1896 			-(zp->z_gmtoff + dstrp->r_stdoff)) != 0) {
   1897 				result[0] = '\0';
   1898 				return;
   1899 		}
   1900 	(void) strcat(result, ",");
   1901 	if (stringrule(result, dstrp, dstrp->r_stdoff, zp->z_gmtoff) != 0) {
   1902 		result[0] = '\0';
   1903 		return;
   1904 	}
   1905 	(void) strcat(result, ",");
   1906 	if (stringrule(result, stdrp, dstrp->r_stdoff, zp->z_gmtoff) != 0) {
   1907 		result[0] = '\0';
   1908 		return;
   1909 	}
   1910 }
   1911 
   1912 static void
   1913 outzone(const struct zone *const zpfirst, const int zonecount)
   1914 {
   1915 	const struct zone *	zp;
   1916 	struct rule *		rp;
   1917 	int			i, j;
   1918 	int			usestart, useuntil;
   1919 	zic_t			starttime, untiltime;
   1920 	zic_t			gmtoff;
   1921 	zic_t			stdoff;
   1922 	int			year;
   1923 	zic_t			startoff;
   1924 	int			startttisstd;
   1925 	int			startttisgmt;
   1926 	int			type;
   1927 	char *			startbuf;
   1928 	char *			ab;
   1929 	char *			envvar;
   1930 	size_t			max_abbr_len;
   1931 	size_t			max_envvar_len;
   1932 	int			prodstic; /* all rules are min to max */
   1933 
   1934 	max_abbr_len = 2 + max_format_len + max_abbrvar_len;
   1935 	max_envvar_len = 2 * max_abbr_len + 5 * 9;
   1936 	startbuf = emalloc(max_abbr_len + 1);
   1937 	ab = emalloc(max_abbr_len + 1);
   1938 	envvar = emalloc(max_envvar_len + 1);
   1939 	INITIALIZE(untiltime);
   1940 	INITIALIZE(starttime);
   1941 	/*
   1942 	** Now. . .finally. . .generate some useful data!
   1943 	*/
   1944 	timecnt = 0;
   1945 	typecnt = 0;
   1946 	charcnt = 0;
   1947 	prodstic = zonecount == 1;
   1948 	/*
   1949 	** Thanks to Earl Chew
   1950 	** for noting the need to unconditionally initialize startttisstd.
   1951 	*/
   1952 	startttisstd = FALSE;
   1953 	startttisgmt = FALSE;
   1954 	min_year = max_year = EPOCH_YEAR;
   1955 	if (leapseen) {
   1956 		updateminmax(leapminyear);
   1957 		updateminmax(leapmaxyear + (leapmaxyear < INT_MAX));
   1958 	}
   1959 	for (i = 0; i < zonecount; ++i) {
   1960 		zp = &zpfirst[i];
   1961 		if (i < zonecount - 1)
   1962 			updateminmax(zp->z_untilrule.r_loyear);
   1963 		for (j = 0; j < zp->z_nrules; ++j) {
   1964 			rp = &zp->z_rules[j];
   1965 			if (rp->r_lowasnum)
   1966 				updateminmax(rp->r_loyear);
   1967 			if (rp->r_hiwasnum)
   1968 				updateminmax(rp->r_hiyear);
   1969 		}
   1970 	}
   1971 	/*
   1972 	** Generate lots of data if a rule can't cover all future times.
   1973 	*/
   1974 	stringzone(envvar, max_envvar_len+1, zpfirst, zonecount);
   1975 	if (noise && envvar[0] == '\0') {
   1976 		char *	wp;
   1977 
   1978 		wp = ecpyalloc(_("no POSIX environment variable for zone"));
   1979 		wp = ecatalloc(wp, " ");
   1980 		wp = ecatalloc(wp, zpfirst->z_name);
   1981 		warning(wp);
   1982 		free(wp);
   1983 	}
   1984 	if (envvar[0] == '\0') {
   1985 		if (min_year >= INT_MIN + YEARSPERREPEAT)
   1986 			min_year -= YEARSPERREPEAT;
   1987 		else	min_year = INT_MIN;
   1988 		if (max_year <= INT_MAX - YEARSPERREPEAT)
   1989 			max_year += YEARSPERREPEAT;
   1990 		else	max_year = INT_MAX;
   1991 		/*
   1992 		** Regardless of any of the above,
   1993 		** for a "proDSTic" zone which specifies that its rules
   1994 		** always have and always will be in effect,
   1995 		** we only need one cycle to define the zone.
   1996 		*/
   1997 		if (prodstic) {
   1998 			min_year = 1900;
   1999 			max_year = min_year + YEARSPERREPEAT;
   2000 		}
   2001 	}
   2002 	/*
   2003 	** For the benefit of older systems,
   2004 	** generate data from 1900 through 2037.
   2005 	*/
   2006 	if (min_year > 1900)
   2007 		min_year = 1900;
   2008 	if (max_year < 2037)
   2009 		max_year = 2037;
   2010 	for (i = 0; i < zonecount; ++i) {
   2011 		/*
   2012 		** A guess that may well be corrected later.
   2013 		*/
   2014 		stdoff = 0;
   2015 		zp = &zpfirst[i];
   2016 		usestart = i > 0 && (zp - 1)->z_untiltime > min_time;
   2017 		useuntil = i < (zonecount - 1);
   2018 		if (useuntil && zp->z_untiltime <= min_time)
   2019 			continue;
   2020 		gmtoff = zp->z_gmtoff;
   2021 		eat(zp->z_filename, zp->z_linenum);
   2022 		*startbuf = '\0';
   2023 		startoff = zp->z_gmtoff;
   2024 		if (zp->z_nrules == 0) {
   2025 			stdoff = zp->z_stdoff;
   2026 			doabbr(startbuf, max_abbr_len + 1, zp->z_format,
   2027 			        NULL, stdoff != 0, FALSE);
   2028 			type = addtype(oadd(zp->z_gmtoff, stdoff),
   2029 				startbuf, stdoff != 0, startttisstd,
   2030 				startttisgmt);
   2031 			if (usestart) {
   2032 				addtt(starttime, type);
   2033 				usestart = FALSE;
   2034 			} else if (stdoff != 0)
   2035 				addtt(min_time, type);
   2036 		} else for (year = min_year; year <= max_year; ++year) {
   2037 			if (useuntil && year > zp->z_untilrule.r_hiyear)
   2038 				break;
   2039 			/*
   2040 			** Mark which rules to do in the current year.
   2041 			** For those to do, calculate rpytime(rp, year);
   2042 			*/
   2043 			for (j = 0; j < zp->z_nrules; ++j) {
   2044 				rp = &zp->z_rules[j];
   2045 				eats(zp->z_filename, zp->z_linenum,
   2046 					rp->r_filename, rp->r_linenum);
   2047 				rp->r_todo = year >= rp->r_loyear &&
   2048 						year <= rp->r_hiyear &&
   2049 						yearistype(year, rp->r_yrtype);
   2050 				if (rp->r_todo)
   2051 					rp->r_temp = rpytime(rp, year);
   2052 			}
   2053 			for ( ; ; ) {
   2054 				int	k;
   2055 				zic_t	jtime, ktime;
   2056 				zic_t	offset;
   2057 
   2058 				INITIALIZE(ktime);
   2059 				if (useuntil) {
   2060 					/*
   2061 					** Turn untiltime into UTC
   2062 					** assuming the current gmtoff and
   2063 					** stdoff values.
   2064 					*/
   2065 					untiltime = zp->z_untiltime;
   2066 					if (!zp->z_untilrule.r_todisgmt)
   2067 						untiltime = tadd(untiltime,
   2068 							-gmtoff);
   2069 					if (!zp->z_untilrule.r_todisstd)
   2070 						untiltime = tadd(untiltime,
   2071 							-stdoff);
   2072 				}
   2073 				/*
   2074 				** Find the rule (of those to do, if any)
   2075 				** that takes effect earliest in the year.
   2076 				*/
   2077 				k = -1;
   2078 				for (j = 0; j < zp->z_nrules; ++j) {
   2079 					rp = &zp->z_rules[j];
   2080 					if (!rp->r_todo)
   2081 						continue;
   2082 					eats(zp->z_filename, zp->z_linenum,
   2083 						rp->r_filename, rp->r_linenum);
   2084 					offset = rp->r_todisgmt ? 0 : gmtoff;
   2085 					if (!rp->r_todisstd)
   2086 						offset = oadd(offset, stdoff);
   2087 					jtime = rp->r_temp;
   2088 					if (jtime == min_time ||
   2089 						jtime == max_time)
   2090 							continue;
   2091 					jtime = tadd(jtime, -offset);
   2092 					if (k < 0 || jtime < ktime) {
   2093 						k = j;
   2094 						ktime = jtime;
   2095 					}
   2096 				}
   2097 				if (k < 0)
   2098 					break;	/* go on to next year */
   2099 				rp = &zp->z_rules[k];
   2100 				rp->r_todo = FALSE;
   2101 				if (useuntil && ktime >= untiltime)
   2102 					break;
   2103 				stdoff = rp->r_stdoff;
   2104 				if (usestart && ktime == starttime)
   2105 					usestart = FALSE;
   2106 				if (usestart) {
   2107 					if (ktime < starttime) {
   2108 						startoff = oadd(zp->z_gmtoff,
   2109 							stdoff);
   2110 						doabbr(startbuf,
   2111 							max_abbr_len + 1,
   2112 							zp->z_format,
   2113 							rp->r_abbrvar,
   2114 							rp->r_stdoff != 0,
   2115 							FALSE);
   2116 						continue;
   2117 					}
   2118 					if (*startbuf == '\0' &&
   2119 						startoff == oadd(zp->z_gmtoff,
   2120 						stdoff)) {
   2121 							doabbr(startbuf,
   2122 								max_abbr_len + 1,
   2123 								zp->z_format,
   2124 								rp->r_abbrvar,
   2125 								rp->r_stdoff !=
   2126 								0,
   2127 								FALSE);
   2128 					}
   2129 				}
   2130 				eats(zp->z_filename, zp->z_linenum,
   2131 					rp->r_filename, rp->r_linenum);
   2132 				doabbr(ab, max_abbr_len+1, zp->z_format, rp->r_abbrvar,
   2133 					rp->r_stdoff != 0, FALSE);
   2134 				offset = oadd(zp->z_gmtoff, rp->r_stdoff);
   2135 				type = addtype(offset, ab, rp->r_stdoff != 0,
   2136 					rp->r_todisstd, rp->r_todisgmt);
   2137 				addtt(ktime, type);
   2138 			}
   2139 		}
   2140 		if (usestart) {
   2141 			if (*startbuf == '\0' &&
   2142 				zp->z_format != NULL &&
   2143 				strchr(zp->z_format, '%') == NULL &&
   2144 				strchr(zp->z_format, '/') == NULL)
   2145 					(void)strncpy(startbuf, zp->z_format,
   2146 					    max_abbr_len + 1 - 1);
   2147 			eat(zp->z_filename, zp->z_linenum);
   2148 			if (*startbuf == '\0')
   2149 error(_("can't determine time zone abbreviation to use just after until time"));
   2150 			else	addtt(starttime,
   2151 					addtype(startoff, startbuf,
   2152 						startoff != zp->z_gmtoff,
   2153 						startttisstd,
   2154 						startttisgmt));
   2155 		}
   2156 		/*
   2157 		** Now we may get to set starttime for the next zone line.
   2158 		*/
   2159 		if (useuntil) {
   2160 			startttisstd = zp->z_untilrule.r_todisstd;
   2161 			startttisgmt = zp->z_untilrule.r_todisgmt;
   2162 			starttime = zp->z_untiltime;
   2163 			if (!startttisstd)
   2164 				starttime = tadd(starttime, -stdoff);
   2165 			if (!startttisgmt)
   2166 				starttime = tadd(starttime, -gmtoff);
   2167 		}
   2168 	}
   2169 	writezone(zpfirst->z_name, envvar);
   2170 	free(startbuf);
   2171 	free(ab);
   2172 	free(envvar);
   2173 }
   2174 
   2175 static void
   2176 addtt(const zic_t starttime, int type)
   2177 {
   2178 	if (starttime <= min_time ||
   2179 		(timecnt == 1 && attypes[0].at < min_time)) {
   2180 		gmtoffs[0] = gmtoffs[type];
   2181 		isdsts[0] = isdsts[type];
   2182 		ttisstds[0] = ttisstds[type];
   2183 		ttisgmts[0] = ttisgmts[type];
   2184 		if (abbrinds[type] != 0)
   2185 			(void) strcpy(chars, &chars[abbrinds[type]]);
   2186 		abbrinds[0] = 0;
   2187 		charcnt = strlen(chars) + 1;
   2188 		typecnt = 1;
   2189 		timecnt = 0;
   2190 		type = 0;
   2191 	}
   2192 	if (timecnt >= TZ_MAX_TIMES) {
   2193 		error(_("too many transitions?!"));
   2194 		exit(EXIT_FAILURE);
   2195 	}
   2196 	attypes[timecnt].at = starttime;
   2197 	attypes[timecnt].type = type;
   2198 	++timecnt;
   2199 }
   2200 
   2201 static int
   2202 addtype(const zic_t gmtoff, const char *const abbr, const int isdst,
   2203     const int ttisstd, const int ttisgmt)
   2204 {
   2205 	int	i, j;
   2206 
   2207 	if (isdst != TRUE && isdst != FALSE) {
   2208 		error(_("internal error - addtype called with bad isdst"));
   2209 		exit(EXIT_FAILURE);
   2210 	}
   2211 	if (ttisstd != TRUE && ttisstd != FALSE) {
   2212 		error(_("internal error - addtype called with bad ttisstd"));
   2213 		exit(EXIT_FAILURE);
   2214 	}
   2215 	if (ttisgmt != TRUE && ttisgmt != FALSE) {
   2216 		error(_("internal error - addtype called with bad ttisgmt"));
   2217 		exit(EXIT_FAILURE);
   2218 	}
   2219 	/*
   2220 	** See if there's already an entry for this zone type.
   2221 	** If so, just return its index.
   2222 	*/
   2223 	for (i = 0; i < typecnt; ++i) {
   2224 		if (gmtoff == gmtoffs[i] && isdst == isdsts[i] &&
   2225 			strcmp(abbr, &chars[abbrinds[i]]) == 0 &&
   2226 			ttisstd == ttisstds[i] &&
   2227 			ttisgmt == ttisgmts[i])
   2228 				return i;
   2229 	}
   2230 	/*
   2231 	** There isn't one; add a new one, unless there are already too
   2232 	** many.
   2233 	*/
   2234 	if (typecnt >= TZ_MAX_TYPES) {
   2235 		error(_("too many local time types"));
   2236 		exit(EXIT_FAILURE);
   2237 	}
   2238 	if (! (-1L - 2147483647L <= gmtoff && gmtoff <= 2147483647L)) {
   2239 		error(_("UTC offset out of range"));
   2240 		exit(EXIT_FAILURE);
   2241 	}
   2242 	gmtoffs[i] = gmtoff;
   2243 	isdsts[i] = isdst;
   2244 	ttisstds[i] = ttisstd;
   2245 	ttisgmts[i] = ttisgmt;
   2246 
   2247 	for (j = 0; j < charcnt; ++j)
   2248 		if (strcmp(&chars[j], abbr) == 0)
   2249 			break;
   2250 	if (j == charcnt)
   2251 		newabbr(abbr);
   2252 	abbrinds[i] = j;
   2253 	++typecnt;
   2254 	return i;
   2255 }
   2256 
   2257 static void
   2258 leapadd(const zic_t t, const int positive, const int rolling, int count)
   2259 {
   2260 	int	i, j;
   2261 
   2262 	if (leapcnt + (positive ? count : 1) > TZ_MAX_LEAPS) {
   2263 		error(_("too many leap seconds"));
   2264 		exit(EXIT_FAILURE);
   2265 	}
   2266 	for (i = 0; i < leapcnt; ++i)
   2267 		if (t <= trans[i]) {
   2268 			if (t == trans[i]) {
   2269 				error(_("repeated leap second moment"));
   2270 				exit(EXIT_FAILURE);
   2271 			}
   2272 			break;
   2273 		}
   2274 	do {
   2275 		for (j = leapcnt; j > i; --j) {
   2276 			trans[j] = trans[j - 1];
   2277 			corr[j] = corr[j - 1];
   2278 			roll[j] = roll[j - 1];
   2279 		}
   2280 		trans[i] = t;
   2281 		corr[i] = positive ? 1L : eitol(-count);
   2282 		roll[i] = rolling;
   2283 		++leapcnt;
   2284 	} while (positive && --count != 0);
   2285 }
   2286 
   2287 static void
   2288 adjleap(void)
   2289 {
   2290 	int	i;
   2291 	zic_t	last = 0;
   2292 
   2293 	/*
   2294 	** propagate leap seconds forward
   2295 	*/
   2296 	for (i = 0; i < leapcnt; ++i) {
   2297 		trans[i] = tadd(trans[i], last);
   2298 		last = corr[i] += last;
   2299 	}
   2300 }
   2301 
   2302 static int
   2303 yearistype(const int year, const char *const type)
   2304 {
   2305 	static char *	buf;
   2306 	int		result;
   2307 
   2308 	if (type == NULL || *type == '\0')
   2309 		return TRUE;
   2310 	buf = erealloc(buf, 132 + strlen(yitcommand) + strlen(type));
   2311 	(void)sprintf(buf, "%s %d %s", yitcommand, year, type); /* XXX: sprintf is safe */
   2312 	result = system(buf);
   2313 	if (WIFEXITED(result)) switch (WEXITSTATUS(result)) {
   2314 		case 0:
   2315 			return TRUE;
   2316 		case 1:
   2317 			return FALSE;
   2318 	}
   2319 	error(_("Wild result from command execution"));
   2320 	(void) fprintf(stderr, _("%s: command was '%s', result was %d\n"),
   2321 		progname, buf, result);
   2322 	for ( ; ; )
   2323 		exit(EXIT_FAILURE);
   2324 }
   2325 
   2326 static int
   2327 lowerit(int a)
   2328 {
   2329 	a = (unsigned char) a;
   2330 	return (isascii(a) && isupper(a)) ? tolower(a) : a;
   2331 }
   2332 
   2333 /* case-insensitive equality */
   2334 static __pure int
   2335 ciequal(const char *ap, const char *bp)
   2336 {
   2337 	while (lowerit(*ap) == lowerit(*bp++))
   2338 		if (*ap++ == '\0')
   2339 			return TRUE;
   2340 	return FALSE;
   2341 }
   2342 
   2343 static __pure int
   2344 itsabbr(const char *abbr, const char *word)
   2345 {
   2346 	if (lowerit(*abbr) != lowerit(*word))
   2347 		return FALSE;
   2348 	++word;
   2349 	while (*++abbr != '\0')
   2350 		do {
   2351 			if (*word == '\0')
   2352 				return FALSE;
   2353 		} while (lowerit(*word++) != lowerit(*abbr));
   2354 	return TRUE;
   2355 }
   2356 
   2357 static __pure const struct lookup *
   2358 byword(const char *const word, const struct lookup *const table)
   2359 {
   2360 	const struct lookup *	foundlp;
   2361 	const struct lookup *	lp;
   2362 
   2363 	if (word == NULL || table == NULL)
   2364 		return NULL;
   2365 	/*
   2366 	** Look for exact match.
   2367 	*/
   2368 	for (lp = table; lp->l_word != NULL; ++lp)
   2369 		if (ciequal(word, lp->l_word))
   2370 			return lp;
   2371 	/*
   2372 	** Look for inexact match.
   2373 	*/
   2374 	foundlp = NULL;
   2375 	for (lp = table; lp->l_word != NULL; ++lp)
   2376 		if (itsabbr(word, lp->l_word)) {
   2377 			if (foundlp == NULL)
   2378 				foundlp = lp;
   2379 			else	return NULL;	/* multiple inexact matches */
   2380 		}
   2381 	return foundlp;
   2382 }
   2383 
   2384 static char **
   2385 getfields(char *cp)
   2386 {
   2387 	char *	dp;
   2388 	char **	array;
   2389 	int	nsubs;
   2390 
   2391 	if (cp == NULL)
   2392 		return NULL;
   2393 	array = emalloc((strlen(cp) + 1) * sizeof *array);
   2394 	nsubs = 0;
   2395 	for ( ; ; ) {
   2396 		while (isascii((unsigned char) *cp) &&
   2397 			isspace((unsigned char) *cp))
   2398 				++cp;
   2399 		if (*cp == '\0' || *cp == '#')
   2400 			break;
   2401 		array[nsubs++] = dp = cp;
   2402 		do {
   2403 			if ((*dp = *cp++) != '"')
   2404 				++dp;
   2405 			else while ((*dp = *cp++) != '"')
   2406 				if (*dp != '\0')
   2407 					++dp;
   2408 				else {
   2409 					error(_(
   2410 						"Odd number of quotation marks"
   2411 						));
   2412 					exit(1);
   2413 				}
   2414 		} while (*cp != '\0' && *cp != '#' &&
   2415 			(!isascii(*cp) || !isspace((unsigned char) *cp)));
   2416 		if (isascii(*cp) && isspace((unsigned char) *cp))
   2417 			++cp;
   2418 		*dp = '\0';
   2419 	}
   2420 	array[nsubs] = NULL;
   2421 	return array;
   2422 }
   2423 
   2424 static __pure zic_t
   2425 oadd(const zic_t t1, const zic_t t2)
   2426 {
   2427 	if (t1 < 0 ? t2 < LONG_MIN - t1 : LONG_MAX - t1 < t2) {
   2428 		error(_("time overflow"));
   2429 		exit(EXIT_FAILURE);
   2430 	}
   2431 	return t1 + t2;
   2432 }
   2433 
   2434 static zic_t
   2435 tadd(const zic_t t1, const zic_t t2)
   2436 {
   2437 	if (t1 == max_time && t2 > 0)
   2438 		return max_time;
   2439 	if (t1 == min_time && t2 < 0)
   2440 		return min_time;
   2441 	if (t1 < 0 ? t2 < min_time - t1 : max_time - t1 < t2) {
   2442 		error(_("time overflow"));
   2443 		exit(EXIT_FAILURE);
   2444 	}
   2445 	return t1 + t2;
   2446 }
   2447 
   2448 /*
   2449 ** Given a rule, and a year, compute the date - in seconds since January 1,
   2450 ** 1970, 00:00 LOCAL time - in that year that the rule refers to.
   2451 */
   2452 
   2453 static zic_t
   2454 rpytime(const struct rule *const rp, const int wantedy)
   2455 {
   2456 	int	y, m, i;
   2457 	zic_t	dayoff;			/* with a nod to Margaret O. */
   2458 	zic_t	t;
   2459 
   2460 	if (wantedy == INT_MIN)
   2461 		return min_time;
   2462 	if (wantedy == INT_MAX)
   2463 		return max_time;
   2464 	dayoff = 0;
   2465 	m = TM_JANUARY;
   2466 	y = EPOCH_YEAR;
   2467 	while (wantedy != y) {
   2468 		if (wantedy > y) {
   2469 			i = len_years[isleap(y)];
   2470 			++y;
   2471 		} else {
   2472 			--y;
   2473 			i = -len_years[isleap(y)];
   2474 		}
   2475 		dayoff = oadd(dayoff, eitol(i));
   2476 	}
   2477 	while (m != rp->r_month) {
   2478 		i = len_months[isleap(y)][m];
   2479 		dayoff = oadd(dayoff, eitol(i));
   2480 		++m;
   2481 	}
   2482 	i = rp->r_dayofmonth;
   2483 	if (m == TM_FEBRUARY && i == 29 && !isleap(y)) {
   2484 		if (rp->r_dycode == DC_DOWLEQ)
   2485 			--i;
   2486 		else {
   2487 			error(_("use of 2/29 in non leap-year"));
   2488 			exit(EXIT_FAILURE);
   2489 		}
   2490 	}
   2491 	--i;
   2492 	dayoff = oadd(dayoff, eitol(i));
   2493 	if (rp->r_dycode == DC_DOWGEQ || rp->r_dycode == DC_DOWLEQ) {
   2494 		zic_t	wday;
   2495 
   2496 #define LDAYSPERWEEK	((zic_t) DAYSPERWEEK)
   2497 		wday = eitol(EPOCH_WDAY);
   2498 		/*
   2499 		** Don't trust mod of negative numbers.
   2500 		*/
   2501 		if (dayoff >= 0)
   2502 			wday = (wday + dayoff) % LDAYSPERWEEK;
   2503 		else {
   2504 			wday -= ((-dayoff) % LDAYSPERWEEK);
   2505 			if (wday < 0)
   2506 				wday += LDAYSPERWEEK;
   2507 		}
   2508 		while (wday != eitol(rp->r_wday))
   2509 			if (rp->r_dycode == DC_DOWGEQ) {
   2510 				dayoff = oadd(dayoff, (zic_t) 1);
   2511 				if (++wday >= LDAYSPERWEEK)
   2512 					wday = 0;
   2513 				++i;
   2514 			} else {
   2515 				dayoff = oadd(dayoff, (zic_t) -1);
   2516 				if (--wday < 0)
   2517 					wday = LDAYSPERWEEK - 1;
   2518 				--i;
   2519 			}
   2520 		if (i < 0 || i >= len_months[isleap(y)][m]) {
   2521 			if (noise)
   2522 				warning(_("rule goes past start/end of month--\
   2523 will not work with pre-2004 versions of zic"));
   2524 		}
   2525 	}
   2526 	if (dayoff < min_time / SECSPERDAY)
   2527 		return min_time;
   2528 	if (dayoff > max_time / SECSPERDAY)
   2529 		return max_time;
   2530 	t = (zic_t) dayoff * SECSPERDAY;
   2531 	return tadd(t, rp->r_tod);
   2532 }
   2533 
   2534 static void
   2535 newabbr(const char *const string)
   2536 {
   2537 	int	i;
   2538 
   2539 	if (strcmp(string, GRANDPARENTED) != 0) {
   2540 		const char *	cp;
   2541 		const char *	mp;
   2542 
   2543 		/*
   2544 		** Want one to ZIC_MAX_ABBR_LEN_WO_WARN alphabetics
   2545 		** optionally followed by a + or - and a number from 1 to 14.
   2546 		*/
   2547 		cp = string;
   2548 		mp = NULL;
   2549 		while (isascii((unsigned char) *cp) &&
   2550 			isalpha((unsigned char) *cp))
   2551 				++cp;
   2552 		if (cp - string == 0)
   2553 mp = _("time zone abbreviation lacks alphabetic at start");
   2554 		if (noise && cp - string < 3)
   2555 mp = _("time zone abbreviation has fewer than 3 alphabetics");
   2556 		if (cp - string > ZIC_MAX_ABBR_LEN_WO_WARN)
   2557 mp = _("time zone abbreviation has too many alphabetics");
   2558 		if (mp == NULL && (*cp == '+' || *cp == '-')) {
   2559 			++cp;
   2560 			if (isascii((unsigned char) *cp) &&
   2561 				isdigit((unsigned char) *cp))
   2562 					if (*cp++ == '1' &&
   2563 						*cp >= '0' && *cp <= '4')
   2564 							++cp;
   2565 		}
   2566 		if (*cp != '\0')
   2567 mp = _("time zone abbreviation differs from POSIX standard");
   2568 		if (mp != NULL) {
   2569 			char *wp = ecpyalloc(mp);
   2570 			wp = ecatalloc(wp, " (");
   2571 			wp = ecatalloc(wp, string);
   2572 			wp = ecatalloc(wp, ")");
   2573 			warning(wp);
   2574 			free(wp);
   2575 		}
   2576 	}
   2577 	i = strlen(string) + 1;
   2578 	if (charcnt + i > TZ_MAX_CHARS) {
   2579 		error(_("too many, or too zic_t, time zone abbreviations"));
   2580 		exit(EXIT_FAILURE);
   2581 	}
   2582 	(void)strncpy(&chars[charcnt], string, sizeof(chars) - charcnt - 1);
   2583 	charcnt += eitol(i);
   2584 }
   2585 
   2586 static int
   2587 mkdirs(char *argname)
   2588 {
   2589 	char *	name;
   2590 	char *	cp;
   2591 
   2592 	if (argname == NULL || *argname == '\0')
   2593 		return 0;
   2594 	cp = name = ecpyalloc(argname);
   2595 	while ((cp = strchr(cp + 1, '/')) != 0) {
   2596 		*cp = '\0';
   2597 #ifndef __NetBSD__
   2598 		/*
   2599 		** DOS drive specifier?
   2600 		*/
   2601 		if (isalpha((unsigned char) name[0]) &&
   2602 			name[1] == ':' && name[2] == '\0') {
   2603 				*cp = '/';
   2604 				continue;
   2605 		}
   2606 #endif /* !defined __NetBSD__ */
   2607 		if (!itsdir(name)) {
   2608 			/*
   2609 			** It doesn't seem to exist, so we try to create it.
   2610 			** Creation may fail because of the directory being
   2611 			** created by some other multiprocessor, so we get
   2612 			** to do extra checking.
   2613 			*/
   2614 			if (mkdir(name, MKDIR_UMASK) != 0) {
   2615 				const char *e = strerror(errno);
   2616 
   2617 				if (errno != EEXIST || !itsdir(name)) {
   2618 					(void) fprintf(stderr,
   2619 _("%s: Can't create directory %s: %s\n"),
   2620 						progname, name, e);
   2621 					free(name);
   2622 					return -1;
   2623 				}
   2624 			}
   2625 		}
   2626 		*cp = '/';
   2627 	}
   2628 	free(name);
   2629 	return 0;
   2630 }
   2631 
   2632 static zic_t
   2633 eitol(const int i)
   2634 {
   2635 	zic_t	l;
   2636 
   2637 	l = i;
   2638 	if ((i < 0 && l >= 0) || (i == 0 && l != 0) || (i > 0 && l <= 0)) {
   2639 		(void) fprintf(stderr,
   2640 			_("%s: %d did not sign extend correctly\n"),
   2641 			progname, i);
   2642 		exit(EXIT_FAILURE);
   2643 	}
   2644 	return l;
   2645 }
   2646 
   2647 /*
   2648 ** UNIX was a registered trademark of The Open Group in 2003.
   2649 */
   2650