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: head/usr.bin/units/units.c 264475 2014-04-14 21:09:47Z eadler $
30 #include "pathnames.h"
33 #define UNITSFILE _PATH_UNITSLIB
37 #define MAXPREFIXES 100
39 #define MAXSUBUNITS 500
41 #define PRIMITIVECHAR '!'
43 static const char *powerstring = "^";
48 } unittable[MAXUNITS];
51 char *numerator[MAXSUBUNITS];
52 char *denominator[MAXSUBUNITS];
61 } prefixtable[MAXPREFIXES];
64 static char NULLUNIT[] = "";
73 static int prefixcount;
74 static bool verbose = false;
75 static const char * havestr;
76 static const char * wantstr;
78 static int addsubunit(char *product[], char *toadd);
79 static int addunit(struct unittype *theunit, const char *toadd, int flip, int quantity);
80 static void cancelunit(struct unittype * theunit);
81 static int compare(const void *item1, const void *item2);
82 static int compareproducts(char **one, char **two);
83 static int compareunits(struct unittype * first, struct unittype * second);
84 static int completereduce(struct unittype * unit);
85 static char *dupstr(const char *str);
86 static void initializeunit(struct unittype * theunit);
87 static char *lookupunit(const char *unit);
88 static void readunits(const char *userfile);
89 static int reduceproduct(struct unittype * theunit, int flip);
90 static int reduceunit(struct unittype * theunit);
91 static void showanswer(struct unittype * have, struct unittype * want);
92 static void showunit(struct unittype * theunit);
93 static void sortunit(struct unittype * theunit);
94 static void usage(void);
95 static void zeroerror(void);
97 static const char* promptstr = "";
99 static const char * prompt(EditLine *e __unused) {
104 dupstr(const char *str)
116 readunits(const char *userfile)
119 char line[512], *lineptr;
126 unitfile = fopen(userfile, "rt");
128 errx(1, "unable to open units file '%s'", userfile);
131 unitfile = fopen(UNITSFILE, "rt");
136 env = getenv("PATH");
138 direc = strtok(env, SEPARATOR);
140 snprintf(filename, sizeof(filename),
141 "%s/%s", direc, UNITSFILE);
142 unitfile = fopen(filename, "rt");
145 direc = strtok(NULL, SEPARATOR);
149 errx(1, "can't find units file '%s'", UNITSFILE);
152 while (!feof(unitfile)) {
153 if (!fgets(line, sizeof(line), unitfile))
159 lineptr += strspn(lineptr, " \n\t");
160 len = strcspn(lineptr, " \n\t");
162 if (!strlen(lineptr))
164 if (lineptr[strlen(lineptr) - 1] == '-') { /* it's a prefix */
165 if (prefixcount == MAXPREFIXES) {
166 warnx("memory for prefixes exceeded in line %d", linenum);
169 lineptr[strlen(lineptr) - 1] = 0;
170 prefixtable[prefixcount].prefixname = dupstr(lineptr);
171 for (i = 0; i < prefixcount; i++)
172 if (!strcmp(prefixtable[i].prefixname, lineptr)) {
173 warnx("redefinition of prefix '%s' on line %d ignored",
178 lineptr += strspn(lineptr, " \n\t");
179 len = strcspn(lineptr, "\n\t");
181 warnx("unexpected end of prefix on line %d",
186 prefixtable[prefixcount++].prefixval = dupstr(lineptr);
188 else { /* it's not a prefix */
189 if (unitcount == MAXUNITS) {
190 warnx("memory for units exceeded in line %d", linenum);
193 unittable[unitcount].uname = dupstr(lineptr);
194 for (i = 0; i < unitcount; i++)
195 if (!strcmp(unittable[i].uname, lineptr)) {
196 warnx("redefinition of unit '%s' on line %d ignored",
201 lineptr += strspn(lineptr, " \n\t");
202 if (!strlen(lineptr)) {
203 warnx("unexpected end of unit on line %d",
207 len = strcspn(lineptr, "\n\t");
209 unittable[unitcount++].uval = dupstr(lineptr);
216 initializeunit(struct unittype * theunit)
218 theunit->numerator[0] = theunit->denominator[0] = NULL;
219 theunit->factor = 1.0;
220 theunit->offset = 0.0;
221 theunit->quantity = 0;
226 addsubunit(char *product[], char *toadd)
230 for (ptr = product; *ptr && *ptr != NULLUNIT; ptr++);
231 if (ptr >= product + MAXSUBUNITS) {
232 warnx("memory overflow in unit reduction");
237 *ptr = dupstr(toadd);
243 showunit(struct unittype * theunit)
249 printf("%.8g", theunit->factor);
251 printf("&%.8g", theunit->offset);
252 for (ptr = theunit->numerator; *ptr; ptr++) {
253 if (ptr > theunit->numerator && **ptr &&
254 !strcmp(*ptr, *(ptr - 1)))
258 printf("%s%d", powerstring, counter);
265 printf("%s%d", powerstring, counter);
268 for (ptr = theunit->denominator; *ptr; ptr++) {
269 if (ptr > theunit->denominator && **ptr &&
270 !strcmp(*ptr, *(ptr - 1)))
274 printf("%s%d", powerstring, counter);
285 printf("%s%d", powerstring, counter);
293 warnx("unit reduces to zero");
297 Adds the specified string to the unit.
298 Flip is 0 for adding normally, 1 for adding reciprocal.
299 Quantity is 1 if this is a quantity to be converted rather than a pure unit.
301 Returns 0 for successful addition, nonzero on error.
305 addunit(struct unittype * theunit, const char *toadd, int flip, int quantity)
307 char *scratch, *savescr;
309 char *divider, *slash, *offset;
315 savescr = scratch = dupstr(toadd);
316 for (slash = scratch + 1; *slash; slash++)
318 (tolower(*(slash - 1)) != 'e' ||
319 !strchr(".0123456789", *(slash + 1))))
321 slash = strchr(scratch, '/');
326 item = strtok(scratch, " *\t\n/");
328 if (strchr("0123456789.", *item)) { /* item is a number */
329 double num, offsetnum;
332 theunit->quantity = 1;
334 offset = strchr(item, '&');
337 offsetnum = atof(offset+1);
341 divider = strchr(item, '|');
349 if (doingtop ^ flip) {
350 theunit->factor *= num;
351 theunit->offset *= num;
353 theunit->factor /= num;
354 theunit->offset /= num;
356 num = atof(divider + 1);
361 if (doingtop ^ flip) {
362 theunit->factor /= num;
363 theunit->offset /= num;
365 theunit->factor *= num;
366 theunit->offset *= num;
375 if (doingtop ^ flip) {
376 theunit->factor *= num;
377 theunit->offset *= num;
379 theunit->factor /= num;
380 theunit->offset /= num;
384 theunit->offset += offsetnum;
386 else { /* item is not a number */
389 if (strchr("23456789",
390 item[strlen(item) - 1])) {
391 repeat = item[strlen(item) - 1] - '0';
392 item[strlen(item) - 1] = 0;
394 for (; repeat; repeat--)
395 if (addsubunit(doingtop ^ flip ? theunit->numerator : theunit->denominator, item))
398 item = strtok(NULL, " *\t/\n");
406 } while (doingtop >= 0);
413 compare(const void *item1, const void *item2)
415 return strcmp(*(const char * const *)item1, *(const char * const *)item2);
420 sortunit(struct unittype * theunit)
425 for (count = 0, ptr = theunit->numerator; *ptr; ptr++, count++);
426 qsort(theunit->numerator, count, sizeof(char *), compare);
427 for (count = 0, ptr = theunit->denominator; *ptr; ptr++, count++);
428 qsort(theunit->denominator, count, sizeof(char *), compare);
433 cancelunit(struct unittype * theunit)
438 den = theunit->denominator;
439 num = theunit->numerator;
441 while (*num && *den) {
442 comp = strcmp(*den, *num);
444 /* if (*den!=NULLUNIT) free(*den);
445 if (*num!=NULLUNIT) free(*num);*/
460 Looks up the definition for the specified unit.
461 Returns a pointer to the definition or a null pointer
462 if the specified unit does not appear in the units table.
465 static char buffer[100]; /* buffer for lookupunit answers with
469 lookupunit(const char *unit)
474 for (i = 0; i < unitcount; i++) {
475 if (!strcmp(unittable[i].uname, unit))
476 return unittable[i].uval;
479 if (unit[strlen(unit) - 1] == '^') {
481 copy[strlen(copy) - 1] = 0;
482 for (i = 0; i < unitcount; i++) {
483 if (!strcmp(unittable[i].uname, copy)) {
484 strlcpy(buffer, copy, sizeof(buffer));
491 if (unit[strlen(unit) - 1] == 's') {
493 copy[strlen(copy) - 1] = 0;
494 for (i = 0; i < unitcount; i++) {
495 if (!strcmp(unittable[i].uname, copy)) {
496 strlcpy(buffer, copy, sizeof(buffer));
501 if (copy[strlen(copy) - 1] == 'e') {
502 copy[strlen(copy) - 1] = 0;
503 for (i = 0; i < unitcount; i++) {
504 if (!strcmp(unittable[i].uname, copy)) {
505 strlcpy(buffer, copy, sizeof(buffer));
513 for (i = 0; i < prefixcount; i++) {
514 size_t len = strlen(prefixtable[i].prefixname);
515 if (!strncmp(prefixtable[i].prefixname, unit, len)) {
516 if (!strlen(unit + len) || lookupunit(unit + len)) {
517 snprintf(buffer, sizeof(buffer), "%s %s",
518 prefixtable[i].prefixval, unit + len);
529 reduces a product of symbolic units to primitive units.
530 The three low bits are used to return flags:
532 bit 0 (1) set on if reductions were performed without error.
533 bit 1 (2) set on if no reductions are performed.
534 bit 2 (4) set on if an unknown unit is discovered.
541 reduceproduct(struct unittype * theunit, int flip)
546 int didsomething = 2;
549 product = theunit->denominator;
551 product = theunit->numerator;
553 for (; *product; product++) {
556 if (!strlen(*product))
558 toadd = lookupunit(*product);
560 printf("unknown unit '%s'\n", *product);
563 if (strchr(toadd, PRIMITIVECHAR))
566 if (*product != NULLUNIT) {
570 if (addunit(theunit, toadd, flip, 0))
579 Reduces numerator and denominator of the specified unit.
580 Returns 0 on success, or 1 on unknown unit error.
584 reduceunit(struct unittype * theunit)
590 ret = reduceproduct(theunit, 0) | reduceproduct(theunit, 1);
599 compareproducts(char **one, char **two)
601 while (*one || *two) {
602 if (!*one && *two != NULLUNIT)
604 if (!*two && *one != NULLUNIT)
606 if (*one == NULLUNIT)
608 else if (*two == NULLUNIT)
610 else if (strcmp(*one, *two))
619 /* Return zero if units are compatible, nonzero otherwise */
622 compareunits(struct unittype * first, struct unittype * second)
625 compareproducts(first->numerator, second->numerator) ||
626 compareproducts(first->denominator, second->denominator);
631 completereduce(struct unittype * unit)
633 if (reduceunit(unit))
641 showanswer(struct unittype * have, struct unittype * want)
645 if (compareunits(have, want)) {
646 printf("conformability error\n");
648 printf("\t%s = ", havestr);
653 printf("\t%s = ", wantstr);
658 else if (have->offset != want->offset) {
660 printf("WARNING: conversion of non-proportional quantities.\n");
663 (have->factor + have->offset-want->offset)/want->factor);
665 printf("\t (-> x*%.8g %+.8g)\n\t (<- y*%.8g %+.8g)\n",
666 have->factor / want->factor,
667 (have->offset-want->offset)/want->factor,
668 want->factor / have->factor,
669 (want->offset - have->offset)/have->factor);
673 ans = have->factor / want->factor;
675 printf("\t%s = %.8g * %s\n", havestr, ans, wantstr);
677 printf("\t* %.8g\n", ans);
680 printf("\t%s = (1 / %.8g) * %s\n", havestr, 1/ans, wantstr);
682 printf("\t/ %.8g\n", 1/ans);
691 "usage: units [-f unitsfile] [-UVq] [from-unit to-unit]\n");
697 main(int argc, char **argv)
700 struct unittype have, want;
711 while ((optchar = getopt(argc, argv, "f:qvUV")) != -1) {
715 if (strlen(optarg) == 0)
727 fprintf(stderr, "FreeBSD units\n");
730 if (access(UNITSFILE, F_OK) == 0)
731 printf("%s\n", UNITSFILE);
733 printf("Units data file not found");
744 inhistory = history_init();
745 el = el_init(argv[0], stdin, stdout, stderr);
746 el_set(el, EL_PROMPT, &prompt);
747 el_set(el, EL_EDITOR, "emacs");
748 el_set(el, EL_SIGNAL, 1);
749 el_set(el, EL_HIST, history, inhistory);
751 history(inhistory, &ev, H_SETSIZE, 800);
753 err(1, "Could not initialize history");
755 if (optind == argc - 2) {
756 havestr = argv[optind];
757 wantstr = argv[optind + 1];
758 initializeunit(&have);
759 addunit(&have, havestr, 0, 1);
760 completereduce(&have);
761 initializeunit(&want);
762 addunit(&want, wantstr, 0, 1);
763 completereduce(&want);
764 showanswer(&have, &want);
768 printf("%d units, %d prefixes\n", unitcount,
772 initializeunit(&have);
774 promptstr = "You have: ";
775 havestr = el_gets(el, &inputsz);
779 history(inhistory, &ev, H_ENTER,
781 } while (addunit(&have, havestr, 0, 1) ||
782 completereduce(&have));
784 initializeunit(&want);
786 promptstr = "You want: ";
787 wantstr = el_gets(el, &inputsz);
791 history(inhistory, &ev, H_ENTER,
793 } while (addunit(&want, wantstr, 0, 1) ||
794 completereduce(&want));
795 showanswer(&have, &want);
799 history_end(inhistory);