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",
176 lineptr
+= strspn(lineptr
, " \n\t");
177 len
= strcspn(lineptr
, "\n\t");
179 warnx("unexpected end of prefix on line %d",
184 prefixtable
[prefixcount
++].prefixval
= dupstr(lineptr
);
186 else { /* it's not a prefix */
187 if (unitcount
== MAXUNITS
) {
188 warnx("memory for units exceeded in line %d", linenum
);
191 unittable
[unitcount
].uname
= dupstr(lineptr
);
192 for (i
= 0; i
< unitcount
; i
++)
193 if (!strcmp(unittable
[i
].uname
, lineptr
))
194 warnx("redefinition of unit '%s' on line %d ignored",
197 lineptr
+= strspn(lineptr
, " \n\t");
198 if (!strlen(lineptr
)) {
199 warnx("unexpected end of unit on line %d",
203 len
= strcspn(lineptr
, "\n\t");
205 unittable
[unitcount
++].uval
= dupstr(lineptr
);
212 initializeunit(struct unittype
* theunit
)
214 theunit
->numerator
[0] = theunit
->denominator
[0] = NULL
;
215 theunit
->factor
= 1.0;
216 theunit
->offset
= 0.0;
217 theunit
->quantity
= 0;
222 addsubunit(char *product
[], char *toadd
)
226 for (ptr
= product
; *ptr
&& *ptr
!= NULLUNIT
; ptr
++);
227 if (ptr
>= product
+ MAXSUBUNITS
) {
228 warnx("memory overflow in unit reduction");
233 *ptr
= dupstr(toadd
);
239 showunit(struct unittype
* theunit
)
245 printf("%.8g", theunit
->factor
);
247 printf("&%.8g", theunit
->offset
);
248 for (ptr
= theunit
->numerator
; *ptr
; ptr
++) {
249 if (ptr
> theunit
->numerator
&& **ptr
&&
250 !strcmp(*ptr
, *(ptr
- 1)))
254 printf("%s%d", powerstring
, counter
);
261 printf("%s%d", powerstring
, counter
);
264 for (ptr
= theunit
->denominator
; *ptr
; ptr
++) {
265 if (ptr
> theunit
->denominator
&& **ptr
&&
266 !strcmp(*ptr
, *(ptr
- 1)))
270 printf("%s%d", powerstring
, counter
);
281 printf("%s%d", powerstring
, counter
);
289 warnx("unit reduces to zero");
293 Adds the specified string to the unit.
294 Flip is 0 for adding normally, 1 for adding reciprocal.
295 Quantity is 1 if this is a quantity to be converted rather than a pure unit.
297 Returns 0 for successful addition, nonzero on error.
301 addunit(struct unittype
* theunit
, const char *toadd
, int flip
, int quantity
)
303 char *scratch
, *savescr
;
305 char *divider
, *slash
, *offset
;
311 savescr
= scratch
= dupstr(toadd
);
312 for (slash
= scratch
+ 1; *slash
; slash
++)
314 (tolower(*(slash
- 1)) != 'e' ||
315 !strchr(".0123456789", *(slash
+ 1))))
317 slash
= strchr(scratch
, '/');
322 item
= strtok(scratch
, " *\t\n/");
324 if (strchr("0123456789.", *item
)) { /* item is a number */
325 double num
, offsetnum
;
328 theunit
->quantity
= 1;
330 offset
= strchr(item
, '&');
333 offsetnum
= atof(offset
+1);
337 divider
= strchr(item
, '|');
345 if (doingtop
^ flip
) {
346 theunit
->factor
*= num
;
347 theunit
->offset
*= num
;
349 theunit
->factor
/= num
;
350 theunit
->offset
/= num
;
352 num
= atof(divider
+ 1);
357 if (doingtop
^ flip
) {
358 theunit
->factor
/= num
;
359 theunit
->offset
/= num
;
361 theunit
->factor
*= num
;
362 theunit
->offset
*= num
;
371 if (doingtop
^ flip
) {
372 theunit
->factor
*= num
;
373 theunit
->offset
*= num
;
375 theunit
->factor
/= num
;
376 theunit
->offset
/= num
;
380 theunit
->offset
+= offsetnum
;
382 else { /* item is not a number */
385 if (strchr("23456789",
386 item
[strlen(item
) - 1])) {
387 repeat
= item
[strlen(item
) - 1] - '0';
388 item
[strlen(item
) - 1] = 0;
390 for (; repeat
; repeat
--)
391 if (addsubunit(doingtop
^ flip
? theunit
->numerator
: theunit
->denominator
, item
))
394 item
= strtok(NULL
, " *\t/\n");
402 } while (doingtop
>= 0);
409 compare(const void *item1
, const void *item2
)
411 return strcmp(*(const char * const *)item1
, *(const char * const *)item2
);
416 sortunit(struct unittype
* theunit
)
421 for (count
= 0, ptr
= theunit
->numerator
; *ptr
; ptr
++, count
++);
422 qsort(theunit
->numerator
, count
, sizeof(char *), compare
);
423 for (count
= 0, ptr
= theunit
->denominator
; *ptr
; ptr
++, count
++);
424 qsort(theunit
->denominator
, count
, sizeof(char *), compare
);
429 cancelunit(struct unittype
* theunit
)
434 den
= theunit
->denominator
;
435 num
= theunit
->numerator
;
437 while (*num
&& *den
) {
438 comp
= strcmp(*den
, *num
);
440 /* if (*den!=NULLUNIT) free(*den);
441 if (*num!=NULLUNIT) free(*num);*/
456 Looks up the definition for the specified unit.
457 Returns a pointer to the definition or a null pointer
458 if the specified unit does not appear in the units table.
461 static char buffer
[100]; /* buffer for lookupunit answers with
465 lookupunit(const char *unit
)
470 for (i
= 0; i
< unitcount
; i
++) {
471 if (!strcmp(unittable
[i
].uname
, unit
))
472 return unittable
[i
].uval
;
475 if (unit
[strlen(unit
) - 1] == '^') {
477 copy
[strlen(copy
) - 1] = 0;
478 for (i
= 0; i
< unitcount
; i
++) {
479 if (!strcmp(unittable
[i
].uname
, copy
)) {
480 strlcpy(buffer
, copy
, sizeof(buffer
));
487 if (unit
[strlen(unit
) - 1] == 's') {
489 copy
[strlen(copy
) - 1] = 0;
490 for (i
= 0; i
< unitcount
; i
++) {
491 if (!strcmp(unittable
[i
].uname
, copy
)) {
492 strlcpy(buffer
, copy
, sizeof(buffer
));
497 if (copy
[strlen(copy
) - 1] == 'e') {
498 copy
[strlen(copy
) - 1] = 0;
499 for (i
= 0; i
< unitcount
; i
++) {
500 if (!strcmp(unittable
[i
].uname
, copy
)) {
501 strlcpy(buffer
, copy
, sizeof(buffer
));
509 for (i
= 0; i
< prefixcount
; i
++) {
510 size_t len
= strlen(prefixtable
[i
].prefixname
);
511 if (!strncmp(prefixtable
[i
].prefixname
, unit
, len
)) {
512 if (!strlen(unit
+ len
) || lookupunit(unit
+ len
)) {
513 snprintf(buffer
, sizeof(buffer
), "%s %s",
514 prefixtable
[i
].prefixval
, unit
+ len
);
525 reduces a product of symbolic units to primitive units.
526 The three low bits are used to return flags:
528 bit 0 (1) set on if reductions were performed without error.
529 bit 1 (2) set on if no reductions are performed.
530 bit 2 (4) set on if an unknown unit is discovered.
537 reduceproduct(struct unittype
* theunit
, int flip
)
542 int didsomething
= 2;
545 product
= theunit
->denominator
;
547 product
= theunit
->numerator
;
549 for (; *product
; product
++) {
552 if (!strlen(*product
))
554 toadd
= lookupunit(*product
);
556 printf("unknown unit '%s'\n", *product
);
559 if (strchr(toadd
, PRIMITIVECHAR
))
562 if (*product
!= NULLUNIT
) {
566 if (addunit(theunit
, toadd
, flip
, 0))
575 Reduces numerator and denominator of the specified unit.
576 Returns 0 on success, or 1 on unknown unit error.
580 reduceunit(struct unittype
* theunit
)
586 ret
= reduceproduct(theunit
, 0) | reduceproduct(theunit
, 1);
595 compareproducts(char **one
, char **two
)
597 while (*one
|| *two
) {
598 if (!*one
&& *two
!= NULLUNIT
)
600 if (!*two
&& *one
!= NULLUNIT
)
602 if (*one
== NULLUNIT
)
604 else if (*two
== NULLUNIT
)
606 else if (strcmp(*one
, *two
))
615 /* Return zero if units are compatible, nonzero otherwise */
618 compareunits(struct unittype
* first
, struct unittype
* second
)
621 compareproducts(first
->numerator
, second
->numerator
) ||
622 compareproducts(first
->denominator
, second
->denominator
);
627 completereduce(struct unittype
* unit
)
629 if (reduceunit(unit
))
637 showanswer(struct unittype
* have
, struct unittype
* want
)
641 if (compareunits(have
, want
)) {
642 printf("conformability error\n");
644 printf("\t%s = ", havestr
);
649 printf("\t%s = ", wantstr
);
654 else if (have
->offset
!= want
->offset
) {
656 printf("WARNING: conversion of non-proportional quantities.\n");
659 (have
->factor
+ have
->offset
-want
->offset
)/want
->factor
);
661 printf("\t (-> x*%.8g %+.8g)\n\t (<- y*%.8g %+.8g)\n",
662 have
->factor
/ want
->factor
,
663 (have
->offset
-want
->offset
)/want
->factor
,
664 want
->factor
/ have
->factor
,
665 (want
->offset
- have
->offset
)/have
->factor
);
669 ans
= have
->factor
/ want
->factor
;
671 printf("\t%s = %.8g * %s\n", havestr
, ans
, wantstr
);
673 printf("\t* %.8g\n", ans
);
676 printf("\t%s = (1 / %.8g) * %s\n", havestr
, 1/ans
, wantstr
);
678 printf("\t/ %.8g\n", 1/ans
);
687 "usage: units [-f unitsfile] [-UVq] [from-unit to-unit]\n");
693 main(int argc
, char **argv
)
696 struct unittype have
, want
;
707 while ((optchar
= getopt(argc
, argv
, "f:qvUV")) != -1) {
711 if (strlen(optarg
) == 0)
723 fprintf(stderr
, "FreeBSD units\n");
726 if (access(UNITSFILE
, F_OK
) == 0)
727 printf("%s\n", UNITSFILE
);
729 printf("Units data file not found");
740 inhistory
= history_init();
741 el
= el_init(argv
[0], stdin
, stdout
, stderr
);
742 el_set(el
, EL_PROMPT
, &prompt
);
743 el_set(el
, EL_EDITOR
, "emacs");
744 el_set(el
, EL_SIGNAL
, 1);
745 el_set(el
, EL_HIST
, history
, inhistory
);
747 history(inhistory
, &ev
, H_SETSIZE
, 800);
749 err(1, "Could not initialize history");
751 if (optind
== argc
- 2) {
752 havestr
= argv
[optind
];
753 wantstr
= argv
[optind
+ 1];
754 initializeunit(&have
);
755 addunit(&have
, havestr
, 0, 1);
756 completereduce(&have
);
757 initializeunit(&want
);
758 addunit(&want
, wantstr
, 0, 1);
759 completereduce(&want
);
760 showanswer(&have
, &want
);
764 printf("%d units, %d prefixes\n", unitcount
,
768 initializeunit(&have
);
770 promptstr
= "You have: ";
771 havestr
= el_gets(el
, &inputsz
);
775 history(inhistory
, &ev
, H_ENTER
,
777 } while (addunit(&have
, havestr
, 0, 1) ||
778 completereduce(&have
));
780 initializeunit(&want
);
782 promptstr
= "You want: ";
783 wantstr
= el_gets(el
, &inputsz
);
787 history(inhistory
, &ev
, H_ENTER
,
789 } while (addunit(&want
, wantstr
, 0, 1) ||
790 completereduce(&want
));
791 showanswer(&have
, &want
);
795 history_end(inhistory
);