Home | History | Annotate | Line # | Download | only in units
units.c revision 1.24
      1  1.24       wiz /*	$NetBSD: units.c,v 1.24 2013/01/06 00:19:13 wiz Exp $	*/
      2   1.6   thorpej 
      3   1.1       cgd /*
      4   1.1       cgd  * units.c   Copyright (c) 1993 by Adrian Mariano (adrian (at) cam.cornell.edu)
      5   1.1       cgd  *
      6   1.1       cgd  * Redistribution and use in source and binary forms, with or without
      7   1.1       cgd  * modification, are permitted provided that the following conditions
      8   1.1       cgd  * are met:
      9   1.1       cgd  * 1. Redistributions of source code must retain the above copyright
     10   1.1       cgd  *    notice, this list of conditions and the following disclaimer.
     11   1.1       cgd  * 2. The name of the author may not be used to endorse or promote products
     12   1.2       jtc  *    derived from this software without specific prior written permission.
     13   1.1       cgd  * Disclaimer:  This software is provided by the author "as is".  The author
     14   1.1       cgd  * shall not be liable for any damages caused in any way by this software.
     15   1.1       cgd  *
     16   1.1       cgd  * I would appreciate (though I do not require) receiving a copy of any
     17   1.1       cgd  * improvements you might make to this program.
     18   1.1       cgd  */
     19   1.1       cgd 
     20   1.3       jtc #include <ctype.h>
     21   1.7     lukem #include <err.h>
     22  1.21       apb #include <float.h>
     23   1.1       cgd #include <stdio.h>
     24   1.1       cgd #include <string.h>
     25   1.1       cgd #include <stdlib.h>
     26   1.8     perry #include <unistd.h>
     27   1.1       cgd 
     28   1.1       cgd #include "pathnames.h"
     29   1.1       cgd 
     30   1.1       cgd #define VERSION "1.0"
     31   1.1       cgd 
     32   1.1       cgd #ifndef UNITSFILE
     33   1.1       cgd #define UNITSFILE _PATH_UNITSLIB
     34   1.1       cgd #endif
     35   1.1       cgd 
     36   1.1       cgd #define MAXUNITS 1000
     37   1.1       cgd #define MAXPREFIXES 50
     38   1.1       cgd 
     39   1.1       cgd #define MAXSUBUNITS 500
     40   1.1       cgd 
     41   1.1       cgd #define PRIMITIVECHAR '!'
     42   1.1       cgd 
     43  1.21       apb static int precision = 8;		/* for printf with "%.*g" format */
     44  1.21       apb 
     45  1.21       apb static const char *errprefix = NULL;	/* if not NULL, then prepend this
     46  1.21       apb 					 * to error messages and send them to
     47  1.21       apb 					 * stdout instead of stderr.
     48  1.21       apb 					 */
     49  1.21       apb 
     50  1.17     joerg static const char *powerstring = "^";
     51   1.1       cgd 
     52  1.17     joerg static struct {
     53  1.16     lukem 	const char *uname;
     54  1.16     lukem 	const char *uval;
     55   1.1       cgd }      unittable[MAXUNITS];
     56   1.1       cgd 
     57   1.1       cgd struct unittype {
     58  1.16     lukem 	const char *numerator[MAXSUBUNITS];
     59  1.16     lukem 	const char *denominator[MAXSUBUNITS];
     60   1.1       cgd 	double factor;
     61   1.1       cgd };
     62   1.1       cgd 
     63   1.1       cgd struct {
     64  1.16     lukem 	const char *prefixname;
     65  1.16     lukem 	const char *prefixval;
     66   1.1       cgd }      prefixtable[MAXPREFIXES];
     67   1.1       cgd 
     68   1.1       cgd 
     69  1.17     joerg static const char *NULLUNIT = "";
     70   1.1       cgd 
     71  1.17     joerg static int unitcount;
     72  1.17     joerg static int prefixcount;
     73   1.1       cgd 
     74   1.7     lukem 
     75  1.17     joerg static int	addsubunit(const char *[], const char *);
     76  1.17     joerg static int	addunit(struct unittype *, const char *, int);
     77  1.17     joerg static void	cancelunit(struct unittype *);
     78  1.17     joerg static int	compare(const void *, const void *);
     79  1.17     joerg static int	compareproducts(const char **, const char **);
     80  1.17     joerg static int	compareunits(struct unittype *, struct unittype *);
     81  1.17     joerg static int	compareunitsreciprocal(struct unittype *, struct unittype *);
     82  1.17     joerg static int	completereduce(struct unittype *);
     83  1.17     joerg static void	initializeunit(struct unittype *);
     84  1.17     joerg static void	readerror(int);
     85  1.17     joerg static void	readunits(const char *);
     86  1.17     joerg static int	reduceproduct(struct unittype *, int);
     87  1.17     joerg static int	reduceunit(struct unittype *);
     88  1.17     joerg static void	showanswer(struct unittype *, struct unittype *);
     89  1.17     joerg static void	showunit(struct unittype *);
     90  1.17     joerg static void	sortunit(struct unittype *);
     91  1.17     joerg __dead static void	usage(void);
     92  1.17     joerg static void	zeroerror(void);
     93  1.17     joerg static char   *dupstr(const char *);
     94  1.17     joerg static const char *lookupunit(const char *);
     95   1.7     lukem 
     96  1.17     joerg static char *
     97  1.16     lukem dupstr(const char *str)
     98   1.1       cgd {
     99   1.1       cgd 	char *ret;
    100   1.1       cgd 
    101  1.12    itojun 	ret = strdup(str);
    102   1.7     lukem 	if (!ret)
    103   1.7     lukem 		err(3, "Memory allocation error");
    104   1.1       cgd 	return (ret);
    105   1.1       cgd }
    106   1.1       cgd 
    107   1.1       cgd 
    108  1.17     joerg static void
    109  1.21       apb mywarnx(const char *fmt, ...)
    110  1.21       apb {
    111  1.21       apb 	va_list args;
    112  1.21       apb 
    113  1.21       apb 	va_start(args, fmt);
    114  1.21       apb 	if (errprefix) {
    115  1.21       apb 		/* warn to stdout, with errprefix prepended */
    116  1.21       apb 		printf("%s", errprefix);
    117  1.21       apb 		vprintf(fmt, args);
    118  1.21       apb 		printf("%s", "\n");
    119  1.21       apb 	} else {
    120  1.21       apb 		/* warn to stderr */
    121  1.21       apb 		vwarnx(fmt, args);
    122  1.21       apb 	}
    123  1.21       apb 	va_end(args);
    124  1.21       apb }
    125  1.21       apb 
    126  1.21       apb static void
    127   1.1       cgd readerror(int linenum)
    128   1.1       cgd {
    129  1.21       apb 	mywarnx("Error in units file '%s' line %d", UNITSFILE, linenum);
    130   1.1       cgd }
    131   1.1       cgd 
    132   1.1       cgd 
    133  1.17     joerg static void
    134  1.16     lukem readunits(const char *userfile)
    135   1.1       cgd {
    136   1.1       cgd 	FILE *unitfile;
    137   1.1       cgd 	char line[80], *lineptr;
    138  1.20       apb 	int len, linenum, i, isdup;
    139   1.1       cgd 
    140   1.1       cgd 	unitcount = 0;
    141   1.1       cgd 	linenum = 0;
    142   1.1       cgd 
    143   1.1       cgd 	if (userfile) {
    144   1.1       cgd 		unitfile = fopen(userfile, "rt");
    145   1.7     lukem 		if (!unitfile)
    146   1.7     lukem 			err(1, "Unable to open units file '%s'", userfile);
    147   1.1       cgd 	}
    148   1.1       cgd 	else {
    149   1.1       cgd 		unitfile = fopen(UNITSFILE, "rt");
    150   1.1       cgd 		if (!unitfile) {
    151   1.1       cgd 			char *direc, *env;
    152   1.1       cgd 			char filename[1000];
    153   1.1       cgd 			char separator[2];
    154   1.1       cgd 
    155   1.1       cgd 			env = getenv("PATH");
    156   1.1       cgd 			if (env) {
    157   1.1       cgd 				if (strchr(env, ';'))
    158  1.12    itojun 					strlcpy(separator, ";",
    159  1.12    itojun 					    sizeof(separator));
    160   1.1       cgd 				else
    161  1.12    itojun 					strlcpy(separator, ":",
    162  1.12    itojun 					    sizeof(separator));
    163   1.1       cgd 				direc = strtok(env, separator);
    164   1.1       cgd 				while (direc) {
    165  1.12    itojun 					strlcpy(filename, "", sizeof(filename));
    166  1.12    itojun 					strlcat(filename, direc,
    167  1.12    itojun 					    sizeof(filename));
    168  1.12    itojun 					strlcat(filename, "/",
    169  1.12    itojun 					    sizeof(filename));
    170  1.12    itojun 					strlcat(filename, UNITSFILE,
    171  1.12    itojun 					    sizeof(filename));
    172   1.1       cgd 					unitfile = fopen(filename, "rt");
    173   1.1       cgd 					if (unitfile)
    174   1.1       cgd 						break;
    175   1.1       cgd 					direc = strtok(NULL, separator);
    176   1.1       cgd 				}
    177   1.1       cgd 			}
    178   1.7     lukem 			if (!unitfile)
    179   1.7     lukem 				errx(1, "Can't find units file '%s'",
    180   1.1       cgd 				    UNITSFILE);
    181   1.1       cgd 		}
    182   1.1       cgd 	}
    183   1.1       cgd 	while (!feof(unitfile)) {
    184   1.1       cgd 		if (!fgets(line, 79, unitfile))
    185   1.1       cgd 			break;
    186   1.1       cgd 		linenum++;
    187   1.1       cgd 		lineptr = line;
    188   1.1       cgd 		if (*lineptr == '/')
    189   1.1       cgd 			continue;
    190   1.1       cgd 		lineptr += strspn(lineptr, " \n\t");
    191   1.1       cgd 		len = strcspn(lineptr, " \n\t");
    192   1.1       cgd 		lineptr[len] = 0;
    193   1.1       cgd 		if (!strlen(lineptr))
    194   1.1       cgd 			continue;
    195   1.1       cgd 		if (lineptr[strlen(lineptr) - 1] == '-') { /* it's a prefix */
    196   1.1       cgd 			if (prefixcount == MAXPREFIXES) {
    197  1.21       apb 				mywarnx(
    198  1.21       apb 			"Memory for prefixes exceeded in line %d",
    199  1.21       apb 					linenum);
    200   1.1       cgd 				continue;
    201   1.1       cgd 			}
    202   1.1       cgd 			lineptr[strlen(lineptr) - 1] = 0;
    203  1.20       apb 			for (isdup = 0, i = 0; i < prefixcount; i++) {
    204  1.20       apb 				if (!strcmp(prefixtable[i].prefixname,
    205  1.20       apb 				    lineptr)) {
    206  1.20       apb 					isdup = 1;
    207  1.20       apb 					break;
    208  1.20       apb 				}
    209  1.20       apb 			}
    210  1.20       apb 			if (isdup) {
    211  1.21       apb 				mywarnx(
    212  1.20       apb 			"Redefinition of prefix '%s' on line %d ignored",
    213  1.20       apb 				    lineptr, linenum);
    214  1.20       apb 				continue;
    215  1.20       apb 			}
    216   1.1       cgd 			prefixtable[prefixcount].prefixname = dupstr(lineptr);
    217   1.1       cgd 			lineptr += len + 1;
    218   1.1       cgd 			if (!strlen(lineptr)) {
    219   1.1       cgd 				readerror(linenum);
    220   1.1       cgd 				continue;
    221   1.1       cgd 			}
    222   1.1       cgd 			lineptr += strspn(lineptr, " \n\t");
    223   1.1       cgd 			len = strcspn(lineptr, "\n\t");
    224   1.1       cgd 			lineptr[len] = 0;
    225   1.1       cgd 			prefixtable[prefixcount++].prefixval = dupstr(lineptr);
    226   1.1       cgd 		}
    227   1.1       cgd 		else {		/* it's not a prefix */
    228   1.1       cgd 			if (unitcount == MAXUNITS) {
    229  1.21       apb 				mywarnx("Memory for units exceeded in line %d",
    230   1.1       cgd 				    linenum);
    231   1.1       cgd 				continue;
    232   1.1       cgd 			}
    233  1.20       apb 			for (isdup = 0, i = 0; i < unitcount; i++) {
    234   1.1       cgd 				if (!strcmp(unittable[i].uname, lineptr)) {
    235  1.20       apb 					isdup = 1;
    236  1.20       apb 					break;
    237  1.20       apb 				}
    238  1.20       apb 			}
    239  1.20       apb 			if (isdup) {
    240  1.21       apb 				mywarnx(
    241   1.7     lukem 				"Redefinition of unit '%s' on line %d ignored",
    242  1.20       apb 				    lineptr, linenum);
    243  1.20       apb 				continue;
    244  1.20       apb 			}
    245  1.20       apb 			unittable[unitcount].uname = dupstr(lineptr);
    246   1.1       cgd 			lineptr += len + 1;
    247   1.1       cgd 			lineptr += strspn(lineptr, " \n\t");
    248   1.1       cgd 			if (!strlen(lineptr)) {
    249   1.1       cgd 				readerror(linenum);
    250   1.1       cgd 				continue;
    251   1.1       cgd 			}
    252   1.1       cgd 			len = strcspn(lineptr, "\n\t");
    253   1.1       cgd 			lineptr[len] = 0;
    254   1.1       cgd 			unittable[unitcount++].uval = dupstr(lineptr);
    255   1.1       cgd 		}
    256   1.1       cgd 	}
    257   1.1       cgd 	fclose(unitfile);
    258   1.1       cgd }
    259   1.1       cgd 
    260  1.17     joerg static void
    261   1.1       cgd initializeunit(struct unittype * theunit)
    262   1.1       cgd {
    263   1.1       cgd 	theunit->factor = 1.0;
    264   1.1       cgd 	theunit->numerator[0] = theunit->denominator[0] = NULL;
    265   1.1       cgd }
    266   1.1       cgd 
    267  1.17     joerg static int
    268  1.16     lukem addsubunit(const char *product[], const char *toadd)
    269   1.1       cgd {
    270  1.16     lukem 	const char **ptr;
    271   1.1       cgd 
    272   1.1       cgd 	for (ptr = product; *ptr && *ptr != NULLUNIT; ptr++);
    273   1.1       cgd 	if (ptr >= product + MAXSUBUNITS) {
    274  1.21       apb 		mywarnx("Memory overflow in unit reduction");
    275   1.1       cgd 		return 1;
    276   1.1       cgd 	}
    277   1.1       cgd 	if (!*ptr)
    278   1.1       cgd 		*(ptr + 1) = 0;
    279   1.1       cgd 	*ptr = dupstr(toadd);
    280   1.1       cgd 	return 0;
    281   1.1       cgd }
    282   1.1       cgd 
    283  1.17     joerg static void
    284   1.1       cgd showunit(struct unittype * theunit)
    285   1.1       cgd {
    286  1.16     lukem 	const char **ptr;
    287   1.1       cgd 	int printedslash;
    288   1.1       cgd 	int counter = 1;
    289   1.1       cgd 
    290  1.21       apb 	printf("\t%.*g", precision, theunit->factor);
    291   1.1       cgd 	for (ptr = theunit->numerator; *ptr; ptr++) {
    292   1.1       cgd 		if (ptr > theunit->numerator && **ptr &&
    293   1.1       cgd 		    !strcmp(*ptr, *(ptr - 1)))
    294   1.1       cgd 			counter++;
    295   1.1       cgd 		else {
    296   1.1       cgd 			if (counter > 1)
    297   1.1       cgd 				printf("%s%d", powerstring, counter);
    298   1.1       cgd 			if (**ptr)
    299   1.1       cgd 				printf(" %s", *ptr);
    300   1.1       cgd 			counter = 1;
    301   1.1       cgd 		}
    302   1.1       cgd 	}
    303   1.1       cgd 	if (counter > 1)
    304   1.1       cgd 		printf("%s%d", powerstring, counter);
    305   1.1       cgd 	counter = 1;
    306   1.1       cgd 	printedslash = 0;
    307   1.1       cgd 	for (ptr = theunit->denominator; *ptr; ptr++) {
    308   1.1       cgd 		if (ptr > theunit->denominator && **ptr &&
    309   1.1       cgd 		    !strcmp(*ptr, *(ptr - 1)))
    310   1.1       cgd 			counter++;
    311   1.1       cgd 		else {
    312   1.1       cgd 			if (counter > 1)
    313   1.1       cgd 				printf("%s%d", powerstring, counter);
    314   1.1       cgd 			if (**ptr) {
    315   1.1       cgd 				if (!printedslash)
    316   1.1       cgd 					printf(" /");
    317   1.1       cgd 				printedslash = 1;
    318   1.1       cgd 				printf(" %s", *ptr);
    319   1.1       cgd 			}
    320   1.1       cgd 			counter = 1;
    321   1.1       cgd 		}
    322   1.1       cgd 	}
    323   1.1       cgd 	if (counter > 1)
    324   1.1       cgd 		printf("%s%d", powerstring, counter);
    325   1.1       cgd 	printf("\n");
    326   1.1       cgd }
    327   1.1       cgd 
    328  1.17     joerg static void
    329  1.18      matt zeroerror(void)
    330   1.1       cgd {
    331  1.21       apb 	mywarnx("Unit reduces to zero");
    332   1.1       cgd }
    333   1.1       cgd 
    334   1.1       cgd /*
    335   1.1       cgd    Adds the specified string to the unit.
    336   1.1       cgd    Flip is 0 for adding normally, 1 for adding reciprocal.
    337   1.1       cgd 
    338   1.1       cgd    Returns 0 for successful addition, nonzero on error.
    339   1.1       cgd */
    340   1.1       cgd 
    341  1.17     joerg static int
    342  1.16     lukem addunit(struct unittype * theunit, const char *toadd, int flip)
    343   1.1       cgd {
    344   1.1       cgd 	char *scratch, *savescr;
    345   1.1       cgd 	char *item;
    346   1.3       jtc 	char *divider, *slash;
    347   1.1       cgd 	int doingtop;
    348   1.1       cgd 
    349   1.1       cgd 	savescr = scratch = dupstr(toadd);
    350   1.1       cgd 	for (slash = scratch + 1; *slash; slash++)
    351   1.1       cgd 		if (*slash == '-' &&
    352  1.14       dsl 		    (tolower((unsigned char)*(slash - 1)) != 'e' ||
    353   1.1       cgd 		    !strchr(".0123456789", *(slash + 1))))
    354   1.1       cgd 			*slash = ' ';
    355   1.1       cgd 	slash = strchr(scratch, '/');
    356   1.1       cgd 	if (slash)
    357   1.1       cgd 		*slash = 0;
    358   1.1       cgd 	doingtop = 1;
    359   1.1       cgd 	do {
    360   1.1       cgd 		item = strtok(scratch, " *\t\n/");
    361   1.1       cgd 		while (item) {
    362  1.19       apb 			if (strchr("0123456789.", *item)) {
    363  1.19       apb 				/* item starts with a number */
    364  1.19       apb 				char *endptr;
    365   1.1       cgd 				double num;
    366   1.1       cgd 
    367   1.1       cgd 				divider = strchr(item, '|');
    368   1.1       cgd 				if (divider) {
    369   1.1       cgd 					*divider = 0;
    370  1.19       apb 					num = strtod(item, &endptr);
    371   1.1       cgd 					if (!num) {
    372   1.1       cgd 						zeroerror();
    373   1.1       cgd 						return 1;
    374   1.1       cgd 					}
    375  1.19       apb 					if (endptr != divider) {
    376  1.19       apb 						/* "6foo|2" is an error */
    377  1.21       apb 						mywarnx("Junk before '|'");
    378  1.19       apb 						return 1;
    379  1.19       apb 					}
    380   1.1       cgd 					if (doingtop ^ flip)
    381   1.1       cgd 						theunit->factor *= num;
    382   1.1       cgd 					else
    383   1.1       cgd 						theunit->factor /= num;
    384  1.19       apb 					num = strtod(divider + 1, &endptr);
    385   1.1       cgd 					if (!num) {
    386   1.1       cgd 						zeroerror();
    387   1.1       cgd 						return 1;
    388   1.1       cgd 					}
    389   1.1       cgd 					if (doingtop ^ flip)
    390   1.1       cgd 						theunit->factor /= num;
    391   1.1       cgd 					else
    392   1.1       cgd 						theunit->factor *= num;
    393  1.19       apb 					if (*endptr) {
    394  1.19       apb 						/* "6|2foo" is like "6|2 foo" */
    395  1.19       apb 						item = endptr;
    396  1.19       apb 						continue;
    397  1.19       apb 					}
    398   1.1       cgd 				}
    399   1.1       cgd 				else {
    400  1.19       apb 					num = strtod(item, &endptr);
    401   1.1       cgd 					if (!num) {
    402   1.1       cgd 						zeroerror();
    403   1.1       cgd 						return 1;
    404   1.1       cgd 					}
    405   1.1       cgd 					if (doingtop ^ flip)
    406   1.1       cgd 						theunit->factor *= num;
    407   1.1       cgd 					else
    408   1.1       cgd 						theunit->factor /= num;
    409  1.19       apb 					if (*endptr) {
    410  1.19       apb 						/* "3foo" is like "3 foo" */
    411  1.19       apb 						item = endptr;
    412  1.19       apb 						continue;
    413  1.19       apb 					}
    414   1.1       cgd 				}
    415   1.1       cgd 			}
    416   1.1       cgd 			else {	/* item is not a number */
    417   1.1       cgd 				int repeat = 1;
    418   1.1       cgd 
    419   1.1       cgd 				if (strchr("23456789",
    420   1.1       cgd 				    item[strlen(item) - 1])) {
    421   1.1       cgd 					repeat = item[strlen(item) - 1] - '0';
    422   1.1       cgd 					item[strlen(item) - 1] = 0;
    423   1.1       cgd 				}
    424   1.1       cgd 				for (; repeat; repeat--)
    425   1.1       cgd 					if (addsubunit(doingtop ^ flip ? theunit->numerator : theunit->denominator, item))
    426   1.1       cgd 						return 1;
    427   1.1       cgd 			}
    428   1.1       cgd 			item = strtok(NULL, " *\t/\n");
    429   1.1       cgd 		}
    430   1.1       cgd 		doingtop--;
    431   1.1       cgd 		if (slash) {
    432   1.1       cgd 			scratch = slash + 1;
    433   1.1       cgd 		}
    434   1.1       cgd 		else
    435   1.1       cgd 			doingtop--;
    436   1.1       cgd 	} while (doingtop >= 0);
    437   1.1       cgd 	free(savescr);
    438   1.1       cgd 	return 0;
    439   1.1       cgd }
    440   1.1       cgd 
    441  1.17     joerg static int
    442   1.1       cgd compare(const void *item1, const void *item2)
    443   1.1       cgd {
    444  1.16     lukem 	return strcmp(*(const char * const *) item1,
    445  1.16     lukem 		      *(const char * const *) item2);
    446   1.1       cgd }
    447   1.1       cgd 
    448  1.17     joerg static void
    449   1.1       cgd sortunit(struct unittype * theunit)
    450   1.1       cgd {
    451  1.16     lukem 	const char **ptr;
    452   1.1       cgd 	int count;
    453   1.1       cgd 
    454   1.1       cgd 	for (count = 0, ptr = theunit->numerator; *ptr; ptr++, count++);
    455   1.1       cgd 	qsort(theunit->numerator, count, sizeof(char *), compare);
    456   1.1       cgd 	for (count = 0, ptr = theunit->denominator; *ptr; ptr++, count++);
    457   1.1       cgd 	qsort(theunit->denominator, count, sizeof(char *), compare);
    458   1.1       cgd }
    459   1.1       cgd 
    460  1.17     joerg static void
    461   1.1       cgd cancelunit(struct unittype * theunit)
    462   1.1       cgd {
    463  1.16     lukem 	const char **den, **num;
    464   1.1       cgd 	int comp;
    465   1.1       cgd 
    466   1.1       cgd 	den = theunit->denominator;
    467   1.1       cgd 	num = theunit->numerator;
    468   1.1       cgd 
    469   1.1       cgd 	while (*num && *den) {
    470   1.1       cgd 		comp = strcmp(*den, *num);
    471   1.1       cgd 		if (!comp) {
    472   1.1       cgd /*      if (*den!=NULLUNIT) free(*den);
    473   1.1       cgd       if (*num!=NULLUNIT) free(*num);*/
    474   1.1       cgd 			*den++ = NULLUNIT;
    475   1.1       cgd 			*num++ = NULLUNIT;
    476   1.1       cgd 		}
    477   1.1       cgd 		else if (comp < 0)
    478   1.1       cgd 			den++;
    479   1.1       cgd 		else
    480   1.1       cgd 			num++;
    481   1.1       cgd 	}
    482   1.1       cgd }
    483   1.1       cgd 
    484   1.1       cgd 
    485   1.1       cgd 
    486   1.1       cgd 
    487   1.1       cgd /*
    488   1.1       cgd    Looks up the definition for the specified unit.
    489   1.1       cgd    Returns a pointer to the definition or a null pointer
    490   1.1       cgd    if the specified unit does not appear in the units table.
    491   1.1       cgd */
    492   1.1       cgd 
    493   1.1       cgd static char buffer[100];	/* buffer for lookupunit answers with
    494   1.1       cgd 				   prefixes */
    495   1.1       cgd 
    496  1.17     joerg static const char *
    497  1.16     lukem lookupunit(const char *unit)
    498   1.1       cgd {
    499   1.1       cgd 	int i;
    500   1.1       cgd 	char *copy;
    501   1.1       cgd 
    502   1.1       cgd 	for (i = 0; i < unitcount; i++) {
    503   1.1       cgd 		if (!strcmp(unittable[i].uname, unit))
    504   1.1       cgd 			return unittable[i].uval;
    505   1.1       cgd 	}
    506   1.1       cgd 
    507   1.1       cgd 	if (unit[strlen(unit) - 1] == '^') {
    508   1.1       cgd 		copy = dupstr(unit);
    509   1.1       cgd 		copy[strlen(copy) - 1] = 0;
    510   1.1       cgd 		for (i = 0; i < unitcount; i++) {
    511   1.1       cgd 			if (!strcmp(unittable[i].uname, copy)) {
    512  1.12    itojun 				strlcpy(buffer, copy, sizeof(buffer));
    513   1.1       cgd 				free(copy);
    514   1.1       cgd 				return buffer;
    515   1.1       cgd 			}
    516   1.1       cgd 		}
    517   1.1       cgd 		free(copy);
    518   1.1       cgd 	}
    519   1.1       cgd 	if (unit[strlen(unit) - 1] == 's') {
    520   1.1       cgd 		copy = dupstr(unit);
    521   1.1       cgd 		copy[strlen(copy) - 1] = 0;
    522   1.1       cgd 		for (i = 0; i < unitcount; i++) {
    523   1.1       cgd 			if (!strcmp(unittable[i].uname, copy)) {
    524  1.12    itojun 				strlcpy(buffer, copy, sizeof(buffer));
    525   1.1       cgd 				free(copy);
    526   1.1       cgd 				return buffer;
    527   1.1       cgd 			}
    528   1.1       cgd 		}
    529   1.1       cgd 		if (copy[strlen(copy) - 1] == 'e') {
    530   1.1       cgd 			copy[strlen(copy) - 1] = 0;
    531   1.1       cgd 			for (i = 0; i < unitcount; i++) {
    532   1.1       cgd 				if (!strcmp(unittable[i].uname, copy)) {
    533  1.12    itojun 					strlcpy(buffer, copy, sizeof(buffer));
    534   1.1       cgd 					free(copy);
    535   1.1       cgd 					return buffer;
    536   1.1       cgd 				}
    537   1.1       cgd 			}
    538   1.1       cgd 		}
    539   1.1       cgd 		free(copy);
    540   1.1       cgd 	}
    541   1.1       cgd 	for (i = 0; i < prefixcount; i++) {
    542   1.1       cgd 		if (!strncmp(prefixtable[i].prefixname, unit,
    543   1.1       cgd 			strlen(prefixtable[i].prefixname))) {
    544   1.1       cgd 			unit += strlen(prefixtable[i].prefixname);
    545   1.1       cgd 			if (!strlen(unit) || lookupunit(unit)) {
    546  1.12    itojun 				strlcpy(buffer, prefixtable[i].prefixval,
    547  1.12    itojun 				    sizeof(buffer));
    548  1.12    itojun 				strlcat(buffer, " ", sizeof(buffer));
    549  1.12    itojun 				strlcat(buffer, unit, sizeof(buffer));
    550   1.1       cgd 				return buffer;
    551   1.1       cgd 			}
    552   1.1       cgd 		}
    553   1.1       cgd 	}
    554   1.1       cgd 	return 0;
    555   1.1       cgd }
    556   1.1       cgd 
    557   1.1       cgd 
    558   1.1       cgd 
    559   1.1       cgd /*
    560   1.1       cgd    reduces a product of symbolic units to primitive units.
    561   1.1       cgd    The three low bits are used to return flags:
    562   1.1       cgd 
    563   1.1       cgd      bit 0 (1) set on if reductions were performed without error.
    564   1.1       cgd      bit 1 (2) set on if no reductions are performed.
    565   1.1       cgd      bit 2 (4) set on if an unknown unit is discovered.
    566   1.1       cgd */
    567   1.1       cgd 
    568   1.1       cgd 
    569   1.1       cgd #define ERROR 4
    570   1.1       cgd 
    571  1.17     joerg static int
    572   1.1       cgd reduceproduct(struct unittype * theunit, int flip)
    573   1.1       cgd {
    574   1.1       cgd 
    575  1.16     lukem 	const char *toadd;
    576  1.16     lukem 	const char **product;
    577   1.1       cgd 	int didsomething = 2;
    578   1.1       cgd 
    579   1.1       cgd 	if (flip)
    580   1.1       cgd 		product = theunit->denominator;
    581   1.1       cgd 	else
    582   1.1       cgd 		product = theunit->numerator;
    583   1.1       cgd 
    584   1.1       cgd 	for (; *product; product++) {
    585   1.1       cgd 
    586   1.1       cgd 		for (;;) {
    587   1.1       cgd 			if (!strlen(*product))
    588   1.1       cgd 				break;
    589   1.1       cgd 			toadd = lookupunit(*product);
    590   1.1       cgd 			if (!toadd) {
    591  1.21       apb 				mywarnx("Unknown unit '%s'", *product);
    592   1.1       cgd 				return ERROR;
    593   1.1       cgd 			}
    594   1.1       cgd 			if (strchr(toadd, PRIMITIVECHAR))
    595   1.1       cgd 				break;
    596   1.1       cgd 			didsomething = 1;
    597   1.1       cgd 			if (*product != NULLUNIT) {
    598  1.16     lukem 				free(__UNCONST(*product));
    599   1.1       cgd 				*product = NULLUNIT;
    600   1.1       cgd 			}
    601   1.1       cgd 			if (addunit(theunit, toadd, flip))
    602   1.1       cgd 				return ERROR;
    603   1.1       cgd 		}
    604   1.1       cgd 	}
    605   1.1       cgd 	return didsomething;
    606   1.1       cgd }
    607   1.1       cgd 
    608   1.1       cgd 
    609   1.1       cgd /*
    610   1.1       cgd    Reduces numerator and denominator of the specified unit.
    611   1.1       cgd    Returns 0 on success, or 1 on unknown unit error.
    612   1.1       cgd */
    613   1.1       cgd 
    614  1.17     joerg static int
    615   1.1       cgd reduceunit(struct unittype * theunit)
    616   1.1       cgd {
    617   1.1       cgd 	int ret;
    618   1.1       cgd 
    619   1.1       cgd 	ret = 1;
    620   1.1       cgd 	while (ret & 1) {
    621   1.1       cgd 		ret = reduceproduct(theunit, 0) | reduceproduct(theunit, 1);
    622   1.1       cgd 		if (ret & 4)
    623   1.1       cgd 			return 1;
    624   1.1       cgd 	}
    625   1.1       cgd 	return 0;
    626   1.1       cgd }
    627   1.1       cgd 
    628  1.17     joerg static int
    629  1.16     lukem compareproducts(const char **one, const char **two)
    630   1.1       cgd {
    631   1.1       cgd 	while (*one || *two) {
    632   1.1       cgd 		if (!*one && *two != NULLUNIT)
    633   1.1       cgd 			return 1;
    634   1.1       cgd 		if (!*two && *one != NULLUNIT)
    635   1.1       cgd 			return 1;
    636   1.1       cgd 		if (*one == NULLUNIT)
    637   1.1       cgd 			one++;
    638   1.1       cgd 		else if (*two == NULLUNIT)
    639   1.1       cgd 			two++;
    640  1.15  christos 		else if (*one && *two && strcmp(*one, *two))
    641   1.1       cgd 			return 1;
    642   1.1       cgd 		else
    643   1.1       cgd 			one++, two++;
    644   1.1       cgd 	}
    645   1.1       cgd 	return 0;
    646   1.1       cgd }
    647   1.1       cgd 
    648   1.1       cgd 
    649   1.1       cgd /* Return zero if units are compatible, nonzero otherwise */
    650   1.1       cgd 
    651  1.17     joerg static int
    652   1.1       cgd compareunits(struct unittype * first, struct unittype * second)
    653   1.1       cgd {
    654   1.1       cgd 	return
    655   1.1       cgd 	compareproducts(first->numerator, second->numerator) ||
    656   1.1       cgd 	compareproducts(first->denominator, second->denominator);
    657   1.1       cgd }
    658   1.1       cgd 
    659  1.17     joerg static int
    660  1.13   mycroft compareunitsreciprocal(struct unittype * first, struct unittype * second)
    661  1.13   mycroft {
    662  1.13   mycroft 	return
    663  1.13   mycroft 	compareproducts(first->numerator, second->denominator) ||
    664  1.13   mycroft 	compareproducts(first->denominator, second->numerator);
    665  1.13   mycroft }
    666  1.13   mycroft 
    667   1.1       cgd 
    668  1.17     joerg static int
    669   1.1       cgd completereduce(struct unittype * unit)
    670   1.1       cgd {
    671   1.1       cgd 	if (reduceunit(unit))
    672   1.1       cgd 		return 1;
    673   1.1       cgd 	sortunit(unit);
    674   1.1       cgd 	cancelunit(unit);
    675   1.1       cgd 	return 0;
    676   1.1       cgd }
    677   1.1       cgd 
    678   1.1       cgd 
    679  1.17     joerg static void
    680   1.1       cgd showanswer(struct unittype * have, struct unittype * want)
    681   1.1       cgd {
    682   1.1       cgd 	if (compareunits(have, want)) {
    683  1.13   mycroft 		if (compareunitsreciprocal(have, want)) {
    684  1.13   mycroft 			printf("conformability error\n");
    685  1.13   mycroft 			showunit(have);
    686  1.13   mycroft 			showunit(want);
    687  1.13   mycroft 		} else {
    688  1.13   mycroft 			printf("\treciprocal conversion\n");
    689  1.21       apb 			printf("\t* %.*g\n\t/ %.*g\n",
    690  1.21       apb 			    precision, 1 / (have->factor * want->factor),
    691  1.21       apb 			    precision, want->factor * have->factor);
    692  1.13   mycroft 		}
    693   1.1       cgd 	}
    694   1.1       cgd 	else
    695  1.21       apb 		printf("\t* %.*g\n\t/ %.*g\n",
    696  1.21       apb 		    precision, have->factor / want->factor,
    697  1.21       apb 		    precision, want->factor / have->factor);
    698   1.1       cgd }
    699   1.1       cgd 
    700  1.21       apb static int
    701  1.21       apb listunits(int expand)
    702  1.21       apb {
    703  1.21       apb 	struct unittype theunit;
    704  1.21       apb 	const char *thename;
    705  1.21       apb 	const char *thedefn;
    706  1.21       apb 	int errors = 0;
    707  1.21       apb 	int i;
    708  1.21       apb 	int printexpansion;
    709  1.21       apb 
    710  1.21       apb 	/*
    711  1.21       apb 	 * send error and warning messages to stdout,
    712  1.21       apb 	 * and make them look like comments.
    713  1.21       apb 	 */
    714  1.21       apb 	errprefix = "/ ";
    715  1.21       apb 
    716  1.21       apb #if 0 /* debug */
    717  1.21       apb 	printf("/ expand=%d precision=%d unitcount=%d prefixcount=%d\n",
    718  1.21       apb 	    expand, precision, unitcount, prefixcount);
    719  1.21       apb #endif
    720  1.21       apb 
    721  1.21       apb 	/* 1. Dump all primitive units, e.g. "m !a!", "kg !b!", ... */
    722  1.21       apb 	printf("/ Primitive units\n");
    723  1.21       apb 	for (i = 0; i < unitcount; i++) {
    724  1.21       apb 		thename = unittable[i].uname;
    725  1.21       apb 		thedefn = unittable[i].uval;
    726  1.21       apb 		if (thedefn[0] == PRIMITIVECHAR) {
    727  1.21       apb 			printf("%s\t%s\n", thename, thedefn);
    728  1.21       apb 		}
    729  1.21       apb 	}
    730  1.21       apb 
    731  1.21       apb 	/* 2. Dump all prefixes, e.g. "yotta- 1e24", "zetta- 1e21", ... */
    732  1.21       apb 	printf("/ Prefixes\n");
    733  1.21       apb 	for (i = 0; i < prefixcount; i++) {
    734  1.21       apb 		printexpansion = expand;
    735  1.21       apb 		thename = prefixtable[i].prefixname;
    736  1.21       apb 		thedefn = prefixtable[i].prefixval;
    737  1.21       apb 		if (expand) {
    738  1.21       apb 			/*
    739  1.21       apb 			 * prefix names are sometimes identical to unit
    740  1.21       apb 			 * names, so we have to expand thedefn instead of
    741  1.21       apb 			 * expanding thename.
    742  1.21       apb 			 */
    743  1.21       apb 			initializeunit(&theunit);
    744  1.21       apb 			if (addunit(&theunit, thedefn, 0) != 0
    745  1.21       apb 			    || completereduce(&theunit) != 0) {
    746  1.21       apb 				errors++;
    747  1.21       apb 				printexpansion = 0;
    748  1.21       apb 				mywarnx("Error in prefix '%s-'", thename);
    749  1.21       apb 			}
    750  1.21       apb 		}
    751  1.21       apb 		if (printexpansion) {
    752  1.21       apb 			printf("%s-", thename);
    753  1.21       apb 			showunit(&theunit);
    754  1.21       apb 		} else
    755  1.21       apb 			printf("%s-\t%s\n", thename, thedefn);
    756  1.21       apb 	}
    757  1.21       apb 
    758  1.21       apb 	/* 3. Dump all other units. */
    759  1.21       apb 	printf("/ Other units\n");
    760  1.21       apb 	for (i = 0; i < unitcount; i++) {
    761  1.21       apb 		printexpansion = expand;
    762  1.21       apb 		thename = unittable[i].uname;
    763  1.21       apb 		thedefn = unittable[i].uval;
    764  1.21       apb 		if (thedefn[0] == PRIMITIVECHAR)
    765  1.21       apb 			continue;
    766  1.21       apb 		if (expand) {
    767  1.21       apb 			/*
    768  1.21       apb 			 * expand thename, not thedefn, so that
    769  1.21       apb 			 * we can catch errors in the name itself.
    770  1.21       apb 			 * e.g. a name that contains a hyphen
    771  1.22       apb 			 * will be interpreted as multiplication.
    772  1.21       apb 			 */
    773  1.21       apb 			initializeunit(&theunit);
    774  1.23       apb 			if (addunit(&theunit, thename, 0) != 0
    775  1.21       apb 			    || completereduce(&theunit) != 0) {
    776  1.21       apb 				errors++;
    777  1.21       apb 				printexpansion = 0;
    778  1.21       apb 				mywarnx("Error in unit '%s'", thename);
    779  1.21       apb 			}
    780  1.21       apb 		}
    781  1.21       apb 		if (printexpansion) {
    782  1.21       apb 			printf("%s", thename);
    783  1.21       apb 			showunit(&theunit);
    784  1.21       apb 		} else
    785  1.21       apb 			printf("%s\t%s\n", thename, thedefn);
    786  1.21       apb 	}
    787  1.21       apb 
    788  1.21       apb 	if (errors)
    789  1.21       apb 		mywarnx("Definitions with errors: %d", errors);
    790  1.21       apb 	return (errors ? 1 : 0);
    791  1.21       apb }
    792   1.1       cgd 
    793  1.17     joerg static void
    794  1.17     joerg usage(void)
    795   1.1       cgd {
    796   1.7     lukem 	fprintf(stderr,
    797  1.24       wiz 	    "\nunits [-Llqv] [-f filename] [[count] from-unit to-unit]\n");
    798   1.1       cgd 	fprintf(stderr, "\n    -f specify units file\n");
    799  1.24       wiz 	fprintf(stderr, "    -L list units in standardized base units\n");
    800  1.24       wiz 	fprintf(stderr, "    -l list units\n");
    801  1.10    atatat 	fprintf(stderr, "    -q suppress prompting (quiet)\n");
    802   1.1       cgd 	fprintf(stderr, "    -v print version number\n");
    803   1.1       cgd 	exit(3);
    804   1.1       cgd }
    805   1.1       cgd 
    806   1.4       jtc int
    807   1.1       cgd main(int argc, char **argv)
    808   1.1       cgd {
    809   1.1       cgd 
    810   1.1       cgd 	struct unittype have, want;
    811   1.1       cgd 	char havestr[81], wantstr[81];
    812   1.5      mark 	int optchar;
    813  1.16     lukem 	const char *userfile = 0;
    814  1.21       apb 	int list = 0, listexpand = 0;
    815   1.1       cgd 	int quiet = 0;
    816   1.1       cgd 
    817  1.21       apb 	while ((optchar = getopt(argc, argv, "lLvqf:")) != -1) {
    818   1.1       cgd 		switch (optchar) {
    819  1.21       apb 		case 'l':
    820  1.21       apb 			list = 1;
    821  1.21       apb 			break;
    822  1.21       apb 		case 'L':
    823  1.21       apb 			list = 1;
    824  1.21       apb 			listexpand = 1;
    825  1.21       apb 			precision = DBL_DIG;
    826  1.21       apb 			break;
    827   1.1       cgd 		case 'f':
    828   1.1       cgd 			userfile = optarg;
    829   1.1       cgd 			break;
    830   1.1       cgd 		case 'q':
    831   1.1       cgd 			quiet = 1;
    832   1.1       cgd 			break;
    833   1.1       cgd 		case 'v':
    834   1.1       cgd 			fprintf(stderr, "\n  units version %s  Copyright (c) 1993 by Adrian Mariano\n",
    835   1.1       cgd 			    VERSION);
    836   1.1       cgd 			fprintf(stderr, "                    This program may be freely distributed\n");
    837   1.1       cgd 			usage();
    838   1.1       cgd 		default:
    839   1.1       cgd 			usage();
    840   1.1       cgd 			break;
    841   1.1       cgd 		}
    842   1.1       cgd 	}
    843   1.1       cgd 
    844  1.10    atatat 	argc -= optind;
    845  1.10    atatat 	argv += optind;
    846  1.10    atatat 
    847  1.21       apb 	if ((argc != 3 && argc != 2 && argc != 0)
    848  1.21       apb 	    || (list && argc != 0))
    849   1.1       cgd 		usage();
    850   1.1       cgd 
    851  1.21       apb 	if (list)
    852  1.21       apb 		errprefix = "/ ";	/* set this before reading the file */
    853  1.21       apb 
    854   1.1       cgd 	readunits(userfile);
    855   1.1       cgd 
    856  1.21       apb 	if (list)
    857  1.21       apb 		return listunits(listexpand);
    858  1.21       apb 
    859  1.10    atatat 	if (argc == 3) {
    860  1.12    itojun 		strlcpy(havestr, argv[0], sizeof(havestr));
    861  1.12    itojun 		strlcat(havestr, " ", sizeof(havestr));
    862  1.12    itojun 		strlcat(havestr, argv[1], sizeof(havestr));
    863  1.10    atatat 		argc--;
    864  1.10    atatat 		argv++;
    865  1.10    atatat 		argv[0] = havestr;
    866  1.10    atatat 	}
    867  1.10    atatat 
    868  1.10    atatat 	if (argc == 2) {
    869  1.12    itojun 		strlcpy(havestr, argv[0], sizeof(havestr));
    870  1.12    itojun 		strlcpy(wantstr, argv[1], sizeof(wantstr));
    871   1.1       cgd 		initializeunit(&have);
    872   1.1       cgd 		addunit(&have, havestr, 0);
    873   1.1       cgd 		completereduce(&have);
    874   1.1       cgd 		initializeunit(&want);
    875   1.1       cgd 		addunit(&want, wantstr, 0);
    876   1.1       cgd 		completereduce(&want);
    877   1.1       cgd 		showanswer(&have, &want);
    878   1.1       cgd 	}
    879   1.1       cgd 	else {
    880   1.1       cgd 		if (!quiet)
    881   1.1       cgd 			printf("%d units, %d prefixes\n\n", unitcount,
    882   1.1       cgd 			    prefixcount);
    883   1.1       cgd 		for (;;) {
    884   1.1       cgd 			do {
    885   1.1       cgd 				initializeunit(&have);
    886   1.1       cgd 				if (!quiet)
    887   1.1       cgd 					printf("You have: ");
    888   1.1       cgd 				if (!fgets(havestr, 80, stdin)) {
    889  1.11  kristerw 					if (!quiet)
    890  1.11  kristerw 						putchar('\n');
    891   1.1       cgd 					exit(0);
    892   1.1       cgd 				}
    893   1.1       cgd 			} while (addunit(&have, havestr, 0) ||
    894   1.1       cgd 			    completereduce(&have));
    895   1.1       cgd 			do {
    896   1.1       cgd 				initializeunit(&want);
    897   1.1       cgd 				if (!quiet)
    898   1.1       cgd 					printf("You want: ");
    899   1.1       cgd 				if (!fgets(wantstr, 80, stdin)) {
    900   1.1       cgd 					if (!quiet)
    901   1.1       cgd 						putchar('\n');
    902   1.1       cgd 					exit(0);
    903   1.1       cgd 				}
    904   1.1       cgd 			} while (addunit(&want, wantstr, 0) ||
    905   1.1       cgd 			    completereduce(&want));
    906   1.1       cgd 			showanswer(&have, &want);
    907   1.1       cgd 		}
    908   1.1       cgd 	}
    909   1.7     lukem 	return (0);
    910   1.1       cgd }
    911