2 * units.c Copyright (c) 1993 by Adrian Mariano (adrian@cam.cornell.edu)
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. The name of the author may not be used to endorse or promote products
10 * derived from this software without specific prior written permission.
11 * Disclaimer: This software is provided by the author "as is". The author
12 * shall not be liable for any damages caused in any way by this software.
14 * I would appreciate (though I do not require) receiving a copy of any
15 * improvements you might make to this program.
17 * $FreeBSD: src/usr.bin/units/units.c,v 1.6.2.2 2001/03/04 09:22:35 kris Exp $
18 * $DragonFly: src/usr.bin/units/units.c,v 1.2 2003/06/17 04:29:33 dillon Exp $
28 #include "pathnames.h"
33 #define UNITSFILE _PATH_UNITSLIB
37 #define MAXPREFIXES 100
39 #define MAXSUBUNITS 500
41 #define PRIMITIVECHAR '!'
43 const char *powerstring = "^";
48 } unittable[MAXUNITS];
51 char *numerator[MAXSUBUNITS];
52 char *denominator[MAXSUBUNITS];
59 } prefixtable[MAXPREFIXES];
75 dupstr(const char *str)
79 ret = malloc(strlen(str) + 1);
81 errx(3, "memory allocation error");
88 readunits(const char *userfile)
91 char line[512], *lineptr;
98 unitfile = fopen(userfile, "rt");
100 errx(1, "unable to open units file '%s'", userfile);
103 unitfile = fopen(UNITSFILE, "rt");
108 env = getenv("PATH");
110 direc = strtok(env, SEPARATOR);
112 snprintf(filename, sizeof(filename),
113 "%s/%s", direc, UNITSFILE);
114 unitfile = fopen(filename, "rt");
117 direc = strtok(NULL, SEPARATOR);
121 errx(1, "can't find units file '%s'", UNITSFILE);
124 while (!feof(unitfile)) {
125 if (!fgets(line, sizeof(line), unitfile))
131 lineptr += strspn(lineptr, " \n\t");
132 len = strcspn(lineptr, " \n\t");
134 if (!strlen(lineptr))
136 if (lineptr[strlen(lineptr) - 1] == '-') { /* it's a prefix */
137 if (prefixcount == MAXPREFIXES) {
138 warnx("memory for prefixes exceeded in line %d", linenum);
141 lineptr[strlen(lineptr) - 1] = 0;
142 prefixtable[prefixcount].prefixname = dupstr(lineptr);
143 for (i = 0; i < prefixcount; i++)
144 if (!strcmp(prefixtable[i].prefixname, lineptr)) {
145 warnx("redefinition of prefix '%s' on line %d ignored",
150 lineptr += strspn(lineptr, " \n\t");
151 len = strcspn(lineptr, "\n\t");
153 warnx("unexpected end of prefix on line %d",
158 prefixtable[prefixcount++].prefixval = dupstr(lineptr);
160 else { /* it's not a prefix */
161 if (unitcount == MAXUNITS) {
162 warnx("memory for units exceeded in line %d", linenum);
165 unittable[unitcount].uname = dupstr(lineptr);
166 for (i = 0; i < unitcount; i++)
167 if (!strcmp(unittable[i].uname, lineptr)) {
168 warnx("redefinition of unit '%s' on line %d ignored",
173 lineptr += strspn(lineptr, " \n\t");
174 if (!strlen(lineptr)) {
175 warnx("unexpected end of unit on line %d",
179 len = strcspn(lineptr, "\n\t");
181 unittable[unitcount++].uval = dupstr(lineptr);
188 initializeunit(struct unittype * theunit)
190 theunit->factor = 1.0;
191 theunit->numerator[0] = theunit->denominator[0] = NULL;
196 addsubunit(char *product[], char *toadd)
200 for (ptr = product; *ptr && *ptr != NULLUNIT; ptr++);
201 if (ptr >= product + MAXSUBUNITS) {
202 warnx("memory overflow in unit reduction");
207 *ptr = dupstr(toadd);
213 showunit(struct unittype * theunit)
219 printf("\t%.8g", theunit->factor);
220 for (ptr = theunit->numerator; *ptr; ptr++) {
221 if (ptr > theunit->numerator && **ptr &&
222 !strcmp(*ptr, *(ptr - 1)))
226 printf("%s%d", powerstring, counter);
233 printf("%s%d", powerstring, counter);
236 for (ptr = theunit->denominator; *ptr; ptr++) {
237 if (ptr > theunit->denominator && **ptr &&
238 !strcmp(*ptr, *(ptr - 1)))
242 printf("%s%d", powerstring, counter);
253 printf("%s%d", powerstring, counter);
261 warnx("unit reduces to zero");
265 Adds the specified string to the unit.
266 Flip is 0 for adding normally, 1 for adding reciprocal.
268 Returns 0 for successful addition, nonzero on error.
272 addunit(struct unittype * theunit, char *toadd, int flip)
274 char *scratch, *savescr;
276 char *divider, *slash;
282 savescr = scratch = dupstr(toadd);
283 for (slash = scratch + 1; *slash; slash++)
285 (tolower(*(slash - 1)) != 'e' ||
286 !strchr(".0123456789", *(slash + 1))))
288 slash = strchr(scratch, '/');
293 item = strtok(scratch, " *\t\n/");
295 if (strchr("0123456789.", *item)) { /* item is a number */
298 divider = strchr(item, '|');
307 theunit->factor *= num;
309 theunit->factor /= num;
310 num = atof(divider + 1);
316 theunit->factor /= num;
318 theunit->factor *= num;
327 theunit->factor *= num;
329 theunit->factor /= num;
333 else { /* item is not a number */
336 if (strchr("23456789",
337 item[strlen(item) - 1])) {
338 repeat = item[strlen(item) - 1] - '0';
339 item[strlen(item) - 1] = 0;
341 for (; repeat; repeat--)
342 if (addsubunit(doingtop ^ flip ? theunit->numerator : theunit->denominator, item))
345 item = strtok(NULL, " *\t/\n");
353 } while (doingtop >= 0);
360 compare(const void *item1, const void *item2)
362 return strcmp(*(const char **) item1, *(const char **) item2);
367 sortunit(struct unittype * theunit)
372 for (count = 0, ptr = theunit->numerator; *ptr; ptr++, count++);
373 qsort(theunit->numerator, count, sizeof(char *), compare);
374 for (count = 0, ptr = theunit->denominator; *ptr; ptr++, count++);
375 qsort(theunit->denominator, count, sizeof(char *), compare);
380 cancelunit(struct unittype * theunit)
385 den = theunit->denominator;
386 num = theunit->numerator;
388 while (*num && *den) {
389 comp = strcmp(*den, *num);
391 /* if (*den!=NULLUNIT) free(*den);
392 if (*num!=NULLUNIT) free(*num);*/
407 Looks up the definition for the specified unit.
408 Returns a pointer to the definition or a null pointer
409 if the specified unit does not appear in the units table.
412 static char buffer[100]; /* buffer for lookupunit answers with
416 lookupunit(const char *unit)
421 for (i = 0; i < unitcount; i++) {
422 if (!strcmp(unittable[i].uname, unit))
423 return unittable[i].uval;
426 if (unit[strlen(unit) - 1] == '^') {
428 copy[strlen(copy) - 1] = 0;
429 for (i = 0; i < unitcount; i++) {
430 if (!strcmp(unittable[i].uname, copy)) {
431 strlcpy(buffer, copy, sizeof(buffer));
438 if (unit[strlen(unit) - 1] == 's') {
440 copy[strlen(copy) - 1] = 0;
441 for (i = 0; i < unitcount; i++) {
442 if (!strcmp(unittable[i].uname, copy)) {
443 strlcpy(buffer, copy, sizeof(buffer));
448 if (copy[strlen(copy) - 1] == 'e') {
449 copy[strlen(copy) - 1] = 0;
450 for (i = 0; i < unitcount; i++) {
451 if (!strcmp(unittable[i].uname, copy)) {
452 strlcpy(buffer, copy, sizeof(buffer));
460 for (i = 0; i < prefixcount; i++) {
461 size_t len = strlen(prefixtable[i].prefixname);
462 if (!strncmp(prefixtable[i].prefixname, unit, len)) {
463 if (!strlen(unit + len) || lookupunit(unit + len)) {
464 snprintf(buffer, sizeof(buffer), "%s %s",
465 prefixtable[i].prefixval, unit + len);
476 reduces a product of symbolic units to primitive units.
477 The three low bits are used to return flags:
479 bit 0 (1) set on if reductions were performed without error.
480 bit 1 (2) set on if no reductions are performed.
481 bit 2 (4) set on if an unknown unit is discovered.
488 reduceproduct(struct unittype * theunit, int flip)
493 int didsomething = 2;
496 product = theunit->denominator;
498 product = theunit->numerator;
500 for (; *product; product++) {
503 if (!strlen(*product))
505 toadd = lookupunit(*product);
507 printf("unknown unit '%s'\n", *product);
510 if (strchr(toadd, PRIMITIVECHAR))
513 if (*product != NULLUNIT) {
517 if (addunit(theunit, toadd, flip))
526 Reduces numerator and denominator of the specified unit.
527 Returns 0 on success, or 1 on unknown unit error.
531 reduceunit(struct unittype * theunit)
537 ret = reduceproduct(theunit, 0) | reduceproduct(theunit, 1);
546 compareproducts(char **one, char **two)
548 while (*one || *two) {
549 if (!*one && *two != NULLUNIT)
551 if (!*two && *one != NULLUNIT)
553 if (*one == NULLUNIT)
555 else if (*two == NULLUNIT)
557 else if (strcmp(*one, *two))
566 /* Return zero if units are compatible, nonzero otherwise */
569 compareunits(struct unittype * first, struct unittype * second)
572 compareproducts(first->numerator, second->numerator) ||
573 compareproducts(first->denominator, second->denominator);
578 completereduce(struct unittype * unit)
580 if (reduceunit(unit))
589 showanswer(struct unittype * have, struct unittype * want)
591 if (compareunits(have, want)) {
592 printf("conformability error\n");
597 printf("\t* %.8g\n\t/ %.8g\n", have->factor / want->factor,
598 want->factor / have->factor);
606 "usage: units [-f unitsfile] [-q] [-v] [from-unit to-unit]\n");
612 main(int argc, char **argv)
615 struct unittype have, want;
616 char havestr[81], wantstr[81];
621 while ((optchar = getopt(argc, argv, "vqf:")) != -1) {
630 fprintf(stderr, "\n units version %s Copyright (c) 1993 by Adrian Mariano\n",
632 fprintf(stderr, " This program may be freely distributed\n");
640 if (optind != argc - 2 && optind != argc)
645 if (optind == argc - 2) {
646 strlcpy(havestr, argv[optind], sizeof(havestr));
647 strlcpy(wantstr, argv[optind + 1], sizeof(wantstr));
648 initializeunit(&have);
649 addunit(&have, havestr, 0);
650 completereduce(&have);
651 initializeunit(&want);
652 addunit(&want, wantstr, 0);
653 completereduce(&want);
654 showanswer(&have, &want);
658 printf("%d units, %d prefixes\n", unitcount,
662 initializeunit(&have);
664 printf("You have: ");
665 if (!fgets(havestr, sizeof(havestr), stdin)) {
670 } while (addunit(&have, havestr, 0) ||
671 completereduce(&have));
673 initializeunit(&want);
675 printf("You want: ");
676 if (!fgets(wantstr, sizeof(wantstr), stdin)) {
681 } while (addunit(&want, wantstr, 0) ||
682 completereduce(&want));
683 showanswer(&have, &want);