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;
79 static int addsubunit(char *product[], char *toadd);
80 static int addunit(struct unittype *theunit, const char *toadd, int flip, int quantity);
81 static void cancelunit(struct unittype * theunit);
82 static int compare(const void *item1, const void *item2);
83 static int compareproducts(char **one, char **two);
84 static int compareunits(struct unittype * first, struct unittype * second);
85 static int completereduce(struct unittype * unit);
86 static char *dupstr(const char *str);
87 static void initializeunit(struct unittype * theunit);
88 static char *lookupunit(const char *unit);
89 static void readunits(const char *userfile);
90 static int reduceproduct(struct unittype * theunit, int flip);
91 static int reduceunit(struct unittype * theunit);
92 static void showanswer(struct unittype * have, struct unittype * want);
93 static void showunit(struct unittype * theunit);
94 static void sortunit(struct unittype * theunit);
95 static void usage(void);
96 static void zeroerror(void);
98 static const char* promptstr = "";
100 static const char * prompt(EditLine *e __unused) {
105 dupstr(const char *str)
109 ret = malloc(strlen(str) + 1);
111 errx(3, "memory allocation error");
118 readunits(const char *userfile)
121 char line[512], *lineptr;
128 unitfile = fopen(userfile, "rt");
130 errx(1, "unable to open units file '%s'", userfile);
133 unitfile = fopen(UNITSFILE, "rt");
138 env = getenv("PATH");
140 direc = strtok(env, SEPARATOR);
142 snprintf(filename, sizeof(filename),
143 "%s/%s", direc, UNITSFILE);
144 unitfile = fopen(filename, "rt");
147 direc = strtok(NULL, SEPARATOR);
151 errx(1, "can't find units file '%s'", UNITSFILE);
154 while (!feof(unitfile)) {
155 if (!fgets(line, sizeof(line), unitfile))
161 lineptr += strspn(lineptr, " \n\t");
162 len = strcspn(lineptr, " \n\t");
164 if (!strlen(lineptr))
166 if (lineptr[strlen(lineptr) - 1] == '-') { /* it's a prefix */
167 if (prefixcount == MAXPREFIXES) {
168 warnx("memory for prefixes exceeded in line %d", linenum);
171 lineptr[strlen(lineptr) - 1] = 0;
172 prefixtable[prefixcount].prefixname = dupstr(lineptr);
173 for (i = 0; i < prefixcount; i++)
174 if (!strcmp(prefixtable[i].prefixname, lineptr)) {
175 warnx("redefinition of prefix '%s' on line %d ignored",
180 lineptr += strspn(lineptr, " \n\t");
181 len = strcspn(lineptr, "\n\t");
183 warnx("unexpected end of prefix on line %d",
188 prefixtable[prefixcount++].prefixval = dupstr(lineptr);
190 else { /* it's not a prefix */
191 if (unitcount == MAXUNITS) {
192 warnx("memory for units exceeded in line %d", linenum);
195 unittable[unitcount].uname = dupstr(lineptr);
196 for (i = 0; i < unitcount; i++)
197 if (!strcmp(unittable[i].uname, lineptr)) {
198 warnx("redefinition of unit '%s' on line %d ignored",
203 lineptr += strspn(lineptr, " \n\t");
204 if (!strlen(lineptr)) {
205 warnx("unexpected end of unit on line %d",
209 len = strcspn(lineptr, "\n\t");
211 unittable[unitcount++].uval = dupstr(lineptr);
218 initializeunit(struct unittype * theunit)
220 theunit->numerator[0] = theunit->denominator[0] = NULL;
221 theunit->factor = 1.0;
222 theunit->offset = 0.0;
223 theunit->quantity = 0;
228 addsubunit(char *product[], char *toadd)
232 for (ptr = product; *ptr && *ptr != NULLUNIT; ptr++);
233 if (ptr >= product + MAXSUBUNITS) {
234 warnx("memory overflow in unit reduction");
239 *ptr = dupstr(toadd);
245 showunit(struct unittype * theunit)
251 printf("%.8g", theunit->factor);
253 printf("&%.8g", theunit->offset);
254 for (ptr = theunit->numerator; *ptr; ptr++) {
255 if (ptr > theunit->numerator && **ptr &&
256 !strcmp(*ptr, *(ptr - 1)))
260 printf("%s%d", powerstring, counter);
267 printf("%s%d", powerstring, counter);
270 for (ptr = theunit->denominator; *ptr; ptr++) {
271 if (ptr > theunit->denominator && **ptr &&
272 !strcmp(*ptr, *(ptr - 1)))
276 printf("%s%d", powerstring, counter);
287 printf("%s%d", powerstring, counter);
295 warnx("unit reduces to zero");
299 Adds the specified string to the unit.
300 Flip is 0 for adding normally, 1 for adding reciprocal.
301 Quantity is 1 if this is a quantity to be converted rather than a pure unit.
303 Returns 0 for successful addition, nonzero on error.
307 addunit(struct unittype * theunit, const char *toadd, int flip, int quantity)
309 char *scratch, *savescr;
311 char *divider, *slash, *offset;
317 savescr = scratch = dupstr(toadd);
318 for (slash = scratch + 1; *slash; slash++)
320 (tolower(*(slash - 1)) != 'e' ||
321 !strchr(".0123456789", *(slash + 1))))
323 slash = strchr(scratch, '/');
328 item = strtok(scratch, " *\t\n/");
330 if (strchr("0123456789.", *item)) { /* item is a number */
331 double num, offsetnum;
334 theunit->quantity = 1;
336 offset = strchr(item, '&');
339 offsetnum = atof(offset+1);
343 divider = strchr(item, '|');
351 if (doingtop ^ flip) {
352 theunit->factor *= num;
353 theunit->offset *= num;
355 theunit->factor /= num;
356 theunit->offset /= num;
358 num = atof(divider + 1);
363 if (doingtop ^ flip) {
364 theunit->factor /= num;
365 theunit->offset /= num;
367 theunit->factor *= num;
368 theunit->offset *= num;
377 if (doingtop ^ flip) {
378 theunit->factor *= num;
379 theunit->offset *= num;
381 theunit->factor /= num;
382 theunit->offset /= num;
386 theunit->offset += offsetnum;
388 else { /* item is not a number */
391 if (strchr("23456789",
392 item[strlen(item) - 1])) {
393 repeat = item[strlen(item) - 1] - '0';
394 item[strlen(item) - 1] = 0;
396 for (; repeat; repeat--)
397 if (addsubunit(doingtop ^ flip ? theunit->numerator : theunit->denominator, item))
400 item = strtok(NULL, " *\t/\n");
408 } while (doingtop >= 0);
415 compare(const void *item1, const void *item2)
417 return strcmp(*(const char * const *)item1, *(const char * const *)item2);
422 sortunit(struct unittype * theunit)
427 for (count = 0, ptr = theunit->numerator; *ptr; ptr++, count++);
428 qsort(theunit->numerator, count, sizeof(char *), compare);
429 for (count = 0, ptr = theunit->denominator; *ptr; ptr++, count++);
430 qsort(theunit->denominator, count, sizeof(char *), compare);
435 cancelunit(struct unittype * theunit)
440 den = theunit->denominator;
441 num = theunit->numerator;
443 while (*num && *den) {
444 comp = strcmp(*den, *num);
446 /* if (*den!=NULLUNIT) free(*den);
447 if (*num!=NULLUNIT) free(*num);*/
462 Looks up the definition for the specified unit.
463 Returns a pointer to the definition or a null pointer
464 if the specified unit does not appear in the units table.
467 static char buffer[100]; /* buffer for lookupunit answers with
471 lookupunit(const char *unit)
476 for (i = 0; i < unitcount; i++) {
477 if (!strcmp(unittable[i].uname, unit))
478 return unittable[i].uval;
481 if (unit[strlen(unit) - 1] == '^') {
483 copy[strlen(copy) - 1] = 0;
484 for (i = 0; i < unitcount; i++) {
485 if (!strcmp(unittable[i].uname, copy)) {
486 strlcpy(buffer, copy, sizeof(buffer));
493 if (unit[strlen(unit) - 1] == 's') {
495 copy[strlen(copy) - 1] = 0;
496 for (i = 0; i < unitcount; i++) {
497 if (!strcmp(unittable[i].uname, copy)) {
498 strlcpy(buffer, copy, sizeof(buffer));
503 if (copy[strlen(copy) - 1] == 'e') {
504 copy[strlen(copy) - 1] = 0;
505 for (i = 0; i < unitcount; i++) {
506 if (!strcmp(unittable[i].uname, copy)) {
507 strlcpy(buffer, copy, sizeof(buffer));
515 for (i = 0; i < prefixcount; i++) {
516 size_t len = strlen(prefixtable[i].prefixname);
517 if (!strncmp(prefixtable[i].prefixname, unit, len)) {
518 if (!strlen(unit + len) || lookupunit(unit + len)) {
519 snprintf(buffer, sizeof(buffer), "%s %s",
520 prefixtable[i].prefixval, unit + len);
531 reduces a product of symbolic units to primitive units.
532 The three low bits are used to return flags:
534 bit 0 (1) set on if reductions were performed without error.
535 bit 1 (2) set on if no reductions are performed.
536 bit 2 (4) set on if an unknown unit is discovered.
543 reduceproduct(struct unittype * theunit, int flip)
548 int didsomething = 2;
551 product = theunit->denominator;
553 product = theunit->numerator;
555 for (; *product; product++) {
558 if (!strlen(*product))
560 toadd = lookupunit(*product);
562 printf("unknown unit '%s'\n", *product);
565 if (strchr(toadd, PRIMITIVECHAR))
568 if (*product != NULLUNIT) {
572 if (addunit(theunit, toadd, flip, 0))
581 Reduces numerator and denominator of the specified unit.
582 Returns 0 on success, or 1 on unknown unit error.
586 reduceunit(struct unittype * theunit)
592 ret = reduceproduct(theunit, 0) | reduceproduct(theunit, 1);
601 compareproducts(char **one, char **two)
603 while (*one || *two) {
604 if (!*one && *two != NULLUNIT)
606 if (!*two && *one != NULLUNIT)
608 if (*one == NULLUNIT)
610 else if (*two == NULLUNIT)
612 else if (strcmp(*one, *two))
621 /* Return zero if units are compatible, nonzero otherwise */
624 compareunits(struct unittype * first, struct unittype * second)
627 compareproducts(first->numerator, second->numerator) ||
628 compareproducts(first->denominator, second->denominator);
633 completereduce(struct unittype * unit)
635 if (reduceunit(unit))
643 showanswer(struct unittype * have, struct unittype * want)
647 if (compareunits(have, want)) {
648 printf("conformability error\n");
650 printf("\t%s = ", havestr);
655 printf("\t%s = ", wantstr);
660 else if (have->offset != want->offset) {
662 printf("WARNING: conversion of non-proportional quantities.\n");
665 (have->factor + have->offset-want->offset)/want->factor);
667 printf("\t (-> x*%.8g %+.8g)\n\t (<- y*%.8g %+.8g)\n",
668 have->factor / want->factor,
669 (have->offset-want->offset)/want->factor,
670 want->factor / have->factor,
671 (want->offset - have->offset)/have->factor);
675 ans = have->factor / want->factor;
677 printf("\t%s = %.8g * %s\n", havestr, ans, wantstr);
679 printf("\t* %.8g\n", ans);
682 printf("\t%s = (1 / %.8g) * %s\n", havestr, 1/ans, wantstr);
684 printf("\t/ %.8g\n", 1/ans);
693 "usage: units [-f unitsfile] [-UVq] [from-unit to-unit]\n");
699 main(int argc, char **argv)
702 struct unittype have, want;
713 while ((optchar = getopt(argc, argv, "fqvUV:")) != -1) {
717 if (strlen(optarg) == 0)
729 if (access(UNITSFILE, F_OK) == 0)
730 printf("%s\n", UNITSFILE);
732 printf("Units data file not found");
736 fprintf(stderr, "FreeBSD units\n");
747 inhistory = history_init();
748 el = el_init(argv[0], stdin, stdout, stderr);
749 el_set(el, EL_PROMPT, &prompt);
750 el_set(el, EL_EDITOR, "emacs");
751 el_set(el, EL_SIGNAL, 1);
752 el_set(el, EL_HIST, history, inhistory);
754 history(inhistory, &ev, H_SETSIZE, 800);
756 err(1, "Could not initalize history");
758 if (optind == argc - 2) {
759 havestr = argv[optind];
760 wantstr = argv[optind + 1];
761 initializeunit(&have);
762 addunit(&have, havestr, 0, 1);
763 completereduce(&have);
764 initializeunit(&want);
765 addunit(&want, wantstr, 0, 1);
766 completereduce(&want);
767 showanswer(&have, &want);
771 printf("%d units, %d prefixes\n", unitcount,
775 initializeunit(&have);
777 promptstr = "You have: ";
778 havestr = el_gets(el, &inputsz);
782 history(inhistory, &ev, H_ENTER,
784 } while (addunit(&have, havestr, 0, 1) ||
785 completereduce(&have));
787 initializeunit(&want);
789 promptstr = "You want: ";
790 wantstr = el_gets(el, &inputsz);
794 history(inhistory, &ev, H_ENTER,
796 } while (addunit(&want, wantstr, 0, 1) ||
797 completereduce(&want));
798 showanswer(&have, &want);
802 history_end(inhistory);