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