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