File:  [LON-CAPA] / capa / capa51 / pProj / capaUnit.c
Revision 1.9: download - view: text, annotated - select for diffs
Thu Sep 14 20:25:12 2000 UTC (23 years, 9 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- comment updates

    1: /* functions to handle the unit parser/comparison engine
    2:    Copyright (C) 1992-2000 Michigan State University
    3: 
    4:    The CAPA system is free software; you can redistribute it and/or
    5:    modify it under the terms of the GNU General Public License as
    6:    published by the Free Software Foundation; either version 2 of the
    7:    License, or (at your option) any later version.
    8: 
    9:    The CAPA system is distributed in the hope that it will be useful,
   10:    but WITHOUT ANY WARRANTY; without even the implied warranty of
   11:    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   12:    General Public License for more details.
   13: 
   14:    You should have received a copy of the GNU General Public
   15:    License along with the CAPA system; see the file COPYING.  If not,
   16:    write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
   17:    Boston, MA 02111-1307, USA.
   18: 
   19:    As a special exception, you have permission to link this program
   20:    with the TtH/TtM library and distribute executables, as long as you
   21:    follow the requirements of the GNU GPL in regard to all of the
   22:    software in the executable aside from TtH/TtM.
   23: */
   24: 
   25: /* =||>|===================== capaUnit.c   =====================|<||= */
   26: /*   created by Isaac Tsai   1997                                    */
   27: /*   by Isaac Tsai 1997, 1998, 1999                      */
   28: /* =||>|========================================================|<||= */
   29: #include <stdio.h>        /* fopen()  */
   30: #include <stdlib.h>
   31: #include <ctype.h>        /* isalnum()   */
   32: #include <string.h>
   33: #include <math.h>
   34: #include <float.h>
   35: 
   36: #include "capaParser.h"
   37: 
   38: int      PrefixTbl[QUARTER_K];
   39: int      BaseUnitcnt;
   40: double   CScale[BASEUNIT_LIMIT];
   41: double   CExp[BASEUNIT_LIMIT];
   42: char     CSymb[BASEUNIT_LIMIT][SYMBOL_MAXLEN];
   43: Unit_t  *UnitTree_p;
   44: double   MinSquared;
   45: Unit_t  *MinSquaredUnit_p;
   46: Unit_t  *InqueryUnit_p;
   47: double  *TmpAexp, *TmpBexp;
   48: Unit_t  *EquivUnit[BASEUNIT_LIMIT];
   49: double   MinValue[BASEUNIT_LIMIT];
   50: int      EquivUnitCnt;
   51: char     Sbuf[ONE_K_SIZE];
   52: int      Sidx;
   53: Unit_t  *Pstack[ONE_K_SIZE];
   54: int      Ptopidx;
   55: int      gUnitError;
   56: 
   57: FILE    *ufp;
   58: 
   59: /* ==================================================================== */
   60: void c_ignorewhite(FILE *f) /* ignore white spaces from a file stream */
   61: {
   62:   register int c;
   63:   register int ok;
   64:  
   65:   ok = 0;
   66:   do {
   67:     do {  c = getc(f);
   68:     } while ( isspace(c) );
   69:     ungetc(c,f);
   70:     if (c == '#') {
   71:       while (getc(f) != '\n');
   72:     } else ok = 1;
   73:   } while( ! ok);
   74: }
   75: 
   76: int c_getint(FILE *f)  /* returns an integer from the file stream */
   77: {
   78:     int c;
   79:     int value;
   80:  
   81:     c_ignorewhite(f);
   82:     c = fgetc(f);
   83:     if (!isdigit(c)) {
   84:         fprintf(stderr,"Error: Expected digit, got %c\n", c);
   85:         exit(-1);
   86:     }
   87:     ungetc(c,f);
   88:     fscanf(f,"%d", &value);
   89:     return(value);
   90: }
   91: int c_getsec_range(FILE *f,int *low,int *high)
   92: {
   93:     int c;
   94:     int tmp, result;
   95:  
   96:     c_ignorewhite(f);
   97:     c = fgetc(f);
   98:     if( c == '[' ) { /* specify a range of sections */
   99:       do {  c = getc(f); } while ( isspace(c) );
  100:       if (!isdigit(c)) {
  101:         fprintf(stderr,"Error in section range format, expecting a number.\n");
  102:         result = -1;
  103:         return (result);
  104:       }
  105:       ungetc(c,f);
  106:       fscanf(f,"%d", low);
  107:       do {  c = getc(f); } while ( isspace(c) );
  108:       if( c == ',' ) {
  109:         do {  c = getc(f); } while ( isspace(c) );
  110:         if (!isdigit(c)) {
  111:           fprintf(stderr,"Error in section range format, expecting a number.\n");
  112:           result = -1;
  113:           return (result);
  114:         }
  115:         ungetc(c,f);
  116:         fscanf(f,"%d", high);
  117:         do {  c = getc(f); } while ( isspace(c) );
  118:         if( c == ']' ) {
  119:           if( *high < *low ) {
  120:             tmp= *high; *high = *low; *low =tmp;
  121:           }
  122:           if(*low <=0) {
  123:             *low = 1;
  124:           }
  125:           if(*high <=0) {
  126:             *high =1;
  127:           }
  128:           /* printf("Section range=>[%d,%d]\n",*low,*high); */
  129:           result = 2;
  130:         }
  131:       } else { /* no , specified */
  132:         result = -1;
  133:         return (result);
  134:       }
  135:     } else { /* specify a section only */
  136:       if (!isdigit(c)) {
  137:         fprintf(stderr,"Error: Expected digit, got %c\n", c);
  138:         result = -1;
  139:         return (result);
  140:       }
  141:       ungetc(c,f);
  142:       fscanf(f,"%d", low);
  143:       result = 1;
  144:     }
  145:     return (result);
  146: }
  147: 
  148: double c_getdouble(FILE *f)
  149: {
  150:     int c;
  151:     double value;
  152:  
  153:     c_ignorewhite(f);
  154:     c = fgetc(f);
  155:     if (!isdigit(c)) {
  156:         fprintf(stderr,"Error: Expected digit, got %c\n", c);
  157:         exit(-1);
  158:     }
  159:     ungetc(c,f);
  160:     fscanf(f,"%lf", &value);
  161:     return(value);
  162: }
  163: 
  164: /*   read until encountered an unrecognizable char */
  165: /*      space, #, anything other than alphanum, {}-^_ */
  166: char *c_getword(FILE *f) 
  167: {
  168:   register int c;
  169:   register int idx;
  170:   char     tmp_string[ONE_K];
  171:   char     *new_string;
  172: 
  173:   idx = 0;
  174:   c_ignorewhite(f);
  175:     do {  c = getc(f);
  176:       tmp_string[idx] = c;
  177:       idx++;
  178:     } while (isalnum(c) || c == '{' || c == '}' || c == '-' || 
  179:              c == '^'   || c == '_' );
  180:     ungetc(c,f); idx--;
  181:     tmp_string[idx] = 0;
  182:     new_string = (char *)malloc( (idx+1)*sizeof(char) );
  183:     strncpy(new_string,tmp_string, (idx+1) );
  184:   
  185:   return (new_string);
  186: }
  187: /*   read until encountered a newline, # */
  188: char *c_getstring(FILE *f) 
  189: {
  190:   register int c;
  191:   register int idx;
  192:   char     tmp_string[1024];
  193:   char     *new_string;
  194: 
  195:   idx = 0;
  196:   c_ignorewhite(f);
  197:     do {  c = getc(f);
  198:       tmp_string[idx] = c;
  199:       idx++;
  200:     } while (isalnum(c) || c == '{' || c == '}' || c == '-' || 
  201:              c == '^'   || c == ' ' || c == ',' || c == ';' ||
  202:              c == '.'   || c == '(' || c == ')' || c == '=' ||
  203:              c == '+'   || c == '*' || c == '/' );
  204:     ungetc(c,f); idx--;
  205:     tmp_string[idx] = 0;
  206:     c = tmp_string[idx-1];
  207:     while( c == ' ') {   /* get rid of trailing white space */
  208:        idx--;
  209:        c = tmp_string[idx-1];
  210:     }
  211:     tmp_string[idx] = 0;
  212:     new_string = (char *)malloc( (idx+1)*sizeof(char) );
  213:     strncpy(new_string,tmp_string, (idx+1) );
  214:   
  215:   return (new_string);
  216: }
  217: char *c_getcomment(FILE *f) 
  218: {
  219:   register int c;
  220:   register int idx;
  221:   char     tmp_string[ONE_K];
  222:   char     *new_string;
  223: 
  224:   idx = 0;
  225:   while (getc(f) != '#');
  226:   while ((c = getc(f)) == ' ');  ungetc(c,f);
  227:     do {  c = getc(f);
  228:       tmp_string[idx] = c;
  229:       idx++;
  230:     } while ( isprint(c) );
  231: /*
  232:     } while (isalnum(c) || c == '{' || c == '}' || c == '-' || 
  233:              c == '^'   || c == ' ' || c == ',' || c == ';' ||
  234:              c == '.'   || c == '(' || c == ')' || c == '=' );
  235: */
  236:     ungetc(c,f); idx--;
  237:     tmp_string[idx] = 0;
  238:     c = tmp_string[idx-1];
  239:     while( c == ' ') {   /* get rid of trailing white space */
  240:        idx--;
  241:        c = tmp_string[idx-1];
  242:     }
  243:     tmp_string[idx] = 0;
  244:     new_string = (char *)malloc( (idx+1)*sizeof(char) );
  245:     strncpy(new_string,tmp_string, (idx+1) );
  246:   
  247:   return (new_string);
  248: }
  249: void  c_moveto_unit(FILE *f)
  250: {
  251:   register int c;
  252:   register int ok;
  253:  
  254:   ok = 0;
  255:   do {
  256:     do {  c = getc(f);
  257:     } while (c != '<' );
  258:     c = getc(f);
  259:     if (c == '<') {
  260:       ungetc(c,f); ungetc(c,f); ok=1;
  261:     }
  262:   } while( ! ok);
  263: }
  264: 
  265: int  c_gettype(FILE *f)
  266: {
  267:   register int c;
  268:   register int idx;
  269:   char     tmp_string[ONE_K];
  270:   char     new_string[ONE_K];
  271:   
  272:   idx = 0;
  273: PRESTART:
  274:   c_ignorewhite(f);
  275:   while ((c=getc(f)) != '<') { if ( (char)c==(char)EOF ) return U_UNKNOWN; }
  276:   c = getc(f);
  277:   if( c == '<' ) {
  278:     c_ignorewhite(f);
  279: PREEND:
  280:     do {  c = getc(f);
  281:       tmp_string[idx] = toupper(c);
  282:       idx++;
  283:     } while ( c != '>' );
  284:     c = getc(f); 
  285:     if( c == '>' ) {
  286:       idx--;
  287:       tmp_string[idx] = 0;
  288:       c = tmp_string[idx-1];
  289:       while( c == ' ') {   /* get rid of trailing white space */
  290:         idx--;
  291:         c = tmp_string[idx-1];
  292:       }
  293:       tmp_string[idx] = 0;
  294:       strncpy(new_string,tmp_string, (idx+1) );
  295:     } else {
  296:       ungetc(c,f);
  297:       goto PREEND;
  298:     }
  299:   } else {
  300:     goto PRESTART;
  301:   }
  302:   if( !strcmp(new_string,"BASE UNIT") ) {
  303:     return (U_BASE);
  304:   }  
  305:   if( strcmp(new_string, "DERIVED UNIT") == 0 ) {
  306:     return (U_DERIVED);
  307:   }
  308:   if( strcmp(new_string, "PREFIX") == 0 ) {
  309:     return (U_PREFIX);
  310:   }
  311:   if( strcmp(new_string, "CONSTANTS") == 0 ) {
  312:     return (U_CONSTANT);
  313:   }
  314:   if( strcasecmp(new_string, "DEFAULTS") == 0 ) {
  315:     return (U_DEFAULT);
  316:   }
  317:   return (U_UNKNOWN);
  318:   
  319: }
  320: 
  321: /* =================================================================== */
  322: /* =================================================================== */
  323: /* returns: 0 success */
  324: /*          1 the first units string u1_str could not be reduce to a valid unit */
  325: /*          2 the second units string could not be reduced to a valid unit */
  326: int
  327: u_convert_unit(char *u1_str,char *u2_str,double *ratio)
  328: {
  329:   Unit_t   *ap, *bp;
  330:   int       result=0;
  331:   
  332:   while( isspace(*u1_str) )  u1_str++;
  333:   while( isspace(*u2_str) )  u2_str++;
  334:   bp = parse_unit_expr(u2_str);
  335:   Ptopidx=0;
  336:   postwalk_utree(bp);
  337:   if( Ptopidx == 1 ) {
  338:     simplify_unit(Pstack[Ptopidx]);
  339:     bp = Pstack[Ptopidx];
  340:     /* print_unit_t(bp); */
  341:     ap = parse_unit_expr(u1_str);
  342:     Ptopidx=0;
  343:     postwalk_utree(ap);
  344:     if( Ptopidx == 1 ) {
  345:       simplify_unit(Pstack[Ptopidx]);
  346:       /* print_unit_t(Pstack[Ptopidx]); */
  347:       if( (Pstack[Ptopidx]->u_count != 0) ||
  348:           (Pstack[Ptopidx]->u_count == bp->u_count) ) { /* has unit */
  349:         *ratio = units_ratio(Pstack[Ptopidx], bp);
  350:       } else {
  351:         result = 1;
  352:       }
  353:     }
  354:     free_utree(ap);
  355:   } else {
  356:     result = 2;
  357:   }
  358:   free_utree(bp);
  359:   return (result);
  360: }
  361: 
  362: /* =================================================================== */
  363: 
  364: 
  365: 
  366: Unit_t *
  367: u_find_symb (char *name, Unit_t *t, int *result) 
  368: {
  369:   
  370:   if (t == NULL)  return t;
  371: 
  372:   for (;;) {
  373:     if ( comp_unit_symb(name,t->u_symbol) < 0 ) {
  374:       if (t->u_left == NULL)  {
  375:         /* printf("L not found\n"); */
  376:         *result = 0;
  377:         break;
  378:       }
  379:       t = t->u_left;
  380:     } else if ( comp_unit_symb(name,t->u_symbol) > 0 ) {
  381:       if (t->u_right == NULL) {
  382:         /* printf("R not found\n"); */
  383:         *result = 0;
  384:         break;
  385:       }
  386:       t = t->u_right;
  387:     } else {
  388:      *result = 1;
  389:       break;
  390:     }
  391:   }
  392:   return t;
  393: }
  394: /* ------------------------------------------------------------- */
  395: /*   use the input unit_t's element list to locate the min squared */
  396: /*   error fit of the unit tree        */
  397: /*   report either exact fit or approx */
  398: 
  399: void
  400: u_find_name(Unit_t *t)
  401: {
  402:   int      ii;
  403:   Unit_E  *eu_p;
  404:   
  405:   MinSquared = FLT_MAX;
  406:   EquivUnitCnt=0;
  407:   InqueryUnit_p = t;
  408:   /* printf("INQ[[%s,%s,%d]]\n", U_SYMB(t), U_NAME(t),U_COUNT(t)); */
  409:   TmpAexp = (double *)capa_malloc(BaseUnitcnt,sizeof(double));
  410:   TmpBexp = (double *)capa_malloc(BaseUnitcnt,sizeof(double));
  411:   for(ii=0;ii<BaseUnitcnt;ii++) {
  412:      TmpAexp[ii] = 0.0;
  413:   }
  414:   if( t->u_count > 0 ) {
  415:     for(eu_p = t->u_list; eu_p; eu_p = eu_p->ue_nextp) {
  416:       TmpAexp[eu_p->ue_index] = eu_p->ue_exp;
  417:       /* printf("(%d)^(%g) ",eu_p->ue_index,TmpAexp[eu_p->ue_exp]); */
  418:     }
  419:     /* printf("\n"); */
  420:   }
  421:   inorder_diff(UnitTree_p);
  422:   /*capa_mfree((char *)TmpAexp); capa_mfree((char *)TmpBexp);*/
  423:   
  424: }
  425: 
  426: void
  427: print_matches(Unit_t *t)
  428: {
  429:   double   scale, factor;
  430:   Unit_t  *tmp_p;
  431:   int      ii;
  432:   
  433:   scale = t->u_scale;
  434:   if( MinSquared == 0.0 ) {  /* exact match */
  435:     if( EquivUnitCnt > 0 ) {
  436:       printf(" Entered unit is equivalent to:\n");
  437:       for(ii=0;ii<EquivUnitCnt;ii++) {
  438:         tmp_p = EquivUnit[ii];
  439:         if( MinSquared ==  MinValue[ii] ) {
  440:           if( tmp_p->u_type == U_BASE ) {    /* if there is a base unit */
  441:             MinSquaredUnit_p = tmp_p;
  442:           }
  443:           factor = scale / tmp_p->u_scale;
  444:           printf(" <<%g %s>>", factor,U_SYMB(tmp_p));
  445:         }
  446:       }
  447:       printf("\n");
  448:       
  449:     }
  450:   } else {  /* no exact match */
  451:     if( EquivUnitCnt > 0 ) {
  452:       printf(" Entered unit is approximated by:\n");
  453:       for(ii=0;ii<EquivUnitCnt;ii++) {
  454:         tmp_p = EquivUnit[ii];
  455:         if( MinSquared ==  MinValue[ii] ) {
  456:           printf(" <<%s>> ", U_SYMB(tmp_p) );
  457:         }
  458:       }
  459:       printf("\n");
  460:     }
  461:   }
  462: }
  463: 
  464: /* ------------------------------------ */
  465: double
  466: u_squared_diff(Unit_t  *a, Unit_t *b)
  467: {
  468:   double   result;
  469:   double   squared_diff = 0.0;
  470:   int      ii;
  471:   Unit_E  *eu_p;
  472:   
  473:   
  474:   for(ii=0;ii<BaseUnitcnt;ii++) {
  475:     TmpAexp[ii] = 0.0;
  476:     TmpBexp[ii] = 0.0;
  477:   }
  478:   if( a->u_count > 0 ) {
  479:     for(eu_p= a->u_list; eu_p; eu_p = eu_p->ue_nextp) {
  480:       TmpAexp[eu_p->ue_index] = eu_p->ue_exp;
  481:     }
  482:   }
  483:   if( b->u_count > 0 ) {
  484:     for(eu_p= b->u_list; eu_p; eu_p = eu_p->ue_nextp) {
  485:       TmpBexp[eu_p->ue_index] = eu_p->ue_exp;
  486:       /* printf("Exp[%d]=%g ",ii,TmpBexp[ii]); */
  487:     }
  488:     /* printf("\n"); */
  489:   }
  490:   for(ii=0;ii<BaseUnitcnt;ii++) {
  491:     result = TmpAexp[ii] - TmpBexp[ii];
  492:     squared_diff = squared_diff + result*result;
  493:   }
  494:   
  495:   return (squared_diff);
  496: }
  497: 
  498: double
  499: u_sq_diff(Unit_t *b)
  500: {
  501:   double   result;
  502:   double   squared_diff = 0.0;
  503:   int      ii;
  504:   Unit_E  *eu_p;
  505:   
  506:   
  507:   for(ii=0;ii<BaseUnitcnt;ii++) {
  508:     TmpBexp[ii] = 0.0;
  509:   }
  510:   if( b->u_count > 0 ) {
  511:     for(eu_p= b->u_list; eu_p; eu_p = eu_p->ue_nextp) {
  512:       TmpBexp[eu_p->ue_index] = eu_p->ue_exp;
  513:       /* printf("Exp[%d]=%g ",ii,TmpBexp[ii]); */
  514:     }
  515:     /* printf("\n"); */
  516:   } else if( b->u_type == U_BASE  ) {
  517:     TmpBexp[b->u_index] = 1.0;
  518:   }
  519:   for(ii=0;ii<BaseUnitcnt;ii++) {
  520:     result = TmpAexp[ii] - TmpBexp[ii];
  521:     squared_diff = squared_diff + result*result;
  522:   }
  523:   
  524:   return (squared_diff);
  525: 
  526: }
  527: /* ------------------------------------ */
  528: 
  529: int
  530: inorder_diff(node_p) Unit_t  *node_p;
  531: {
  532:   int      result;
  533:   double   sq_diff=0.0;
  534:   
  535:   if( node_p == NULL )  return (1);
  536:   
  537:   result = inorder_diff(U_LEFT(node_p));
  538:   if( result ) {
  539:      sq_diff = u_sq_diff(node_p);
  540:      /*
  541:      printf("DIFF [%s,%s,%d] - [%s,%s,%d] = %g\n", 
  542:       U_SYMB(InqueryUnit_p), U_NAME(InqueryUnit_p),U_COUNT(InqueryUnit_p),
  543:       U_SYMB(node_p), U_NAME(node_p),U_COUNT(node_p),sq_diff);
  544:      */
  545:      if( MinSquared > sq_diff) {
  546:        MinSquaredUnit_p = node_p;
  547:        MinSquared = sq_diff;
  548:      } else if ( MinSquared == sq_diff) {
  549:        EquivUnit[EquivUnitCnt] = node_p;
  550:        MinValue[EquivUnitCnt] = sq_diff;
  551:        EquivUnitCnt++;
  552:      }
  553:   }
  554:   result = inorder_diff(U_RIGHT(node_p));
  555:   
  556:   return (result);
  557: }
  558: 
  559: 
  560: int
  561: alphaorder_utree(node_p) Unit_t  *node_p;
  562: {
  563:   int  result;
  564:   
  565:   if( node_p == NULL )  return (1);
  566:   
  567:   result = alphaorder_utree(U_LEFT(node_p));
  568:   if( result ) printf(" (%s,%s)\n", U_SYMB(node_p), U_NAME(node_p) );
  569:   result = alphaorder_utree(U_RIGHT(node_p));
  570:   
  571:   return (result);
  572: }
  573: 
  574: int
  575: w_alphaorder_utree(node_p) Unit_t  *node_p;
  576: {
  577:   int  result;
  578:   
  579:   if( node_p == NULL )  return (1);
  580:   
  581:   result = alphaorder_utree(U_LEFT(node_p));
  582:   if( result ) { 
  583:      printf(" (%s,%s)\n", U_SYMB(node_p), U_NAME(node_p) );
  584:   }
  585:   result = alphaorder_utree(U_RIGHT(node_p));
  586:   
  587:   return (result);
  588: }
  589: 
  590: /* --------------------------------------------------------------------- */
  591: void
  592: print_unit_tree(int mode)
  593: {
  594:   if( mode == 1 ) {
  595:     alphaorder_utree(UnitTree_p);
  596:   } else {
  597:     w_alphaorder_utree(UnitTree_p);
  598:   }
  599: }
  600: 
  601: 
  602: int
  603: preorder_utree(node_p) Unit_t  *node_p;
  604: {
  605:   int  result;
  606:   
  607:   if( node_p == NULL )  return (1);
  608:   printf("Preorder=[[%s,%s,%d]]\n", U_SYMB(node_p), U_NAME(node_p),U_COUNT(node_p));
  609:   result = preorder_utree(U_LEFT(node_p));
  610:   if( result ) result = preorder_utree(U_RIGHT(node_p));
  611:   return (result);
  612: }
  613: int
  614: inorder_utree(node_p) Unit_t  *node_p;
  615: {
  616:   int  result;
  617:   
  618:   if( node_p == NULL )  return (1);
  619:   
  620:   result = inorder_utree(U_LEFT(node_p));
  621:   if( result ) printf("INorder=[[%s,%s,%d]]\n", 
  622:     U_SYMB(node_p), U_NAME(node_p),U_COUNT(node_p));
  623:   result = inorder_utree(U_RIGHT(node_p));
  624:   
  625:   return (result);
  626: }
  627: int
  628: postorder_utree(node_p) Unit_t  *node_p;
  629: {
  630:   int  result;
  631:   
  632:   if( node_p == NULL )  return (1);
  633:   
  634:   result = postorder_utree(U_LEFT(node_p));
  635:   if( result ) result = postorder_utree(U_RIGHT(node_p));
  636:   if( result ) {
  637:     switch(U_TYPE(node_p)) {
  638:       case U_DERIVED:   print_unit_t(node_p);
  639:             break;
  640:       case U_CONSTANT:  printf("(%g)",U_SCALE(node_p));
  641:             break;
  642:       case U_OP_POWER:  printf("^");
  643:             break;
  644:       case U_OP_TIMES:  printf("*");
  645:             break;
  646:       case U_OP_PLUS:   printf("+");
  647:             break;
  648:       case U_OP_MINUS:  printf("-");
  649:             break;
  650:       case U_OP_DIVIDE: printf("/");
  651:             break;
  652:       default:          printf("()");
  653:             break;  
  654:     }
  655:   }
  656:   return (result);
  657: }
  658: 
  659: /* returns 1 on okay, 2 on error*/
  660: int
  661: postwalk_utree(Unit_t  *n_p)
  662: {
  663:   int  result;
  664:   
  665:   if( n_p == NULL )  return (1);
  666:   
  667:   result = postwalk_utree(U_LEFT(n_p));
  668:   if (result !=2) {
  669:     if( result ) result = postwalk_utree(U_RIGHT(n_p));
  670:     if (result !=2) {
  671:       if( result ) {
  672: 	switch(U_TYPE(n_p)) {
  673: 	case U_DERIVED:   Ptopidx++; Pstack[Ptopidx] = n_p;  /* push into stack */
  674: 	  break;
  675: 	case U_CONSTANT:  Ptopidx++; Pstack[Ptopidx] = n_p;  /* push into stack */
  676: 	  break;
  677: 	case U_UNKNOWN:   result=2; 
  678: 	  /*push into stack anyway, try to parse rest of tree */
  679: 	  break;
  680: 	case U_OP_POWER:  printf("^"); result=2;
  681: 	  break;
  682: 	case U_OP_TIMES:  process_op(U_OP_TIMES);        /* process operator */
  683: 	  break;
  684: 	case U_OP_PLUS:   printf("+"); result=2;
  685: 	  break;
  686: 	case U_OP_MINUS:  printf("-"); result=2;
  687: 	  break;
  688: 	case U_OP_DIVIDE: process_op(U_OP_DIVIDE);       /* process operator */
  689: 	  break;
  690: 	default:          printf("()"); result=2;
  691: 	  break;  
  692: 	}
  693:       }
  694:     }
  695:   }
  696:   return (result);
  697: }
  698: 
  699: void
  700: process_op(int op)
  701: {
  702:   Unit_t  *ap, *bp;
  703:   double   exp_scale;
  704:   int      no_error=1;
  705:   
  706:   bp = Pstack[Ptopidx--]; 
  707:   ap = Pstack[Ptopidx--]; 
  708:   
  709:   switch(op) {
  710:     case U_OP_TIMES:  exp_scale = 1.0;  break;
  711:     case U_OP_DIVIDE: exp_scale = -1.0; break;
  712:     case U_OP_PLUS:   
  713:     case U_OP_MINUS:  no_error = u_pm_op(ap,bp,op);
  714:                       if(no_error) {
  715:                         Ptopidx++;
  716:                         Pstack[Ptopidx] = ap;
  717:                       }
  718:                       break;
  719:     default:          no_error=0; 
  720:                       printf("No such op on the parse tree!\n");
  721:           break;
  722:   }
  723:   if(no_error) {
  724:     u_copy_unit(ap, bp, exp_scale);
  725:     Ptopidx++;
  726:     Pstack[Ptopidx] = ap;
  727:   }
  728: }
  729: 
  730: void
  731: process_utree(Unit_t *t)
  732: {
  733:   Ptopidx=0;
  734:   postwalk_utree(t);
  735:   if( Ptopidx == 1 ) {
  736:     /* printf("Correctly parsed!\n"); */
  737:     printf("Unit:%s\n",Sbuf);
  738:     simplify_unit(Pstack[Ptopidx]);
  739:     Pstack[Ptopidx]->u_symbol[0]='\0';
  740:     /*sprintf(Pstack[Ptopidx]->u_symbol,"");*/
  741:     print_unit_t(Pstack[Ptopidx]);
  742:     u_find_name(Pstack[Ptopidx]);
  743:     print_matches(Pstack[Ptopidx]);
  744:     free_utree(t);
  745:   }
  746: }
  747: 
  748: /* ============================================================== */
  749: /*  called from capaCommon.c */
  750: /*                      */
  751: /*  UNIT_FAIL           */
  752: /*  NO_UNIT             */
  753: /*  result: UNIT_OK correct   */
  754: /*                            */
  755: /* -------------------------------------------------------------- */
  756: int  check_correct_unit(char *u_symb,Unit_t *t,double *scale)
  757: {
  758:   Unit_t   *ap;
  759:   int       result=UNIT_OK;
  760: 
  761: #ifdef UNIT_DBUG
  762:    if ((ufp=fopen("unit.DBUG","a"))==NULL) { fprintf(stderr,"Error: can't open login debug\n"); return UNIT_FAIL; }
  763: #endif 
  764: 
  765:   while( isspace(*u_symb) )  u_symb++; 
  766:   /* <= change this to search from the end of string */
  767:   /* or to get rid of all the white spaces */
  768: 
  769: 
  770:   ap = parse_unit_expr(u_symb);
  771:   Ptopidx=0;
  772: 
  773:   if (postwalk_utree(ap)==1) {
  774: #ifdef UNIT_DBUG
  775:     fprintf(ufp,"Ptopidx %d\n",Ptopidx);
  776: #endif
  777:     if( Ptopidx == 1 ) {
  778:       simplify_unit(Pstack[Ptopidx]);
  779:       
  780:       if( (Pstack[Ptopidx]->u_count != 0) ||
  781: 	  (Pstack[Ptopidx]->u_count == t->u_count) ) { /* has unit */
  782: 	*scale = units_ratio(Pstack[Ptopidx], t);
  783: 	if( *scale == 0.0 ) {
  784: 	  result = UNIT_FAIL;
  785: 	}
  786: 	free_utree(ap);
  787:       } else {
  788: 	result = UNIT_FAIL;
  789:       }
  790:     } else { /* invalid unit representation */
  791:       result = UNIT_FAIL;
  792:     }
  793:   } else {
  794:     result = UNIT_FAIL;
  795:   }
  796: #ifdef UNIT_DBUG
  797:   fclose(ufp);
  798: #endif 
  799:   return (result);
  800: }
  801: 
  802: /* ============================================================= */
  803: int
  804: free_units()
  805: {
  806:   free_utree(UnitTree_p);
  807:   UnitTree_p=NULL;
  808:   return 0;
  809: }
  810: 
  811: int
  812: free_utree(Unit_t  *t)
  813: {
  814:   int  result=1;
  815:   
  816:   if( t == NULL )  return (1);
  817:   u_postfree(t);
  818:   t=NULL;
  819:   
  820:   return (result);
  821: }
  822: 
  823: 
  824: int
  825: u_postfree(Unit_t  *t)
  826: {
  827:   int  result;
  828:   
  829:   if( t == NULL )  return (1);
  830:   
  831:   result = u_postfree(U_LEFT(t));
  832:   if( result ) result = u_postfree(U_RIGHT(t));
  833:   if( result ) {
  834:     if( t->u_comment ) {
  835:       capa_mfree((char *)t->u_comment);
  836:     }
  837:     freelist_unit_e(t->u_list);
  838:     capa_mfree((char *)t);
  839:   }
  840:   return (result);
  841: }
  842: 
  843: 
  844: void
  845: print_unit_t(Unit_t *t) 
  846: {
  847:   Unit_E  *ue_p;
  848: 
  849:   /* printf("  Unit::[%s,%d]= %g * ", t->u_symbol,t->u_count,t->u_scale); */
  850:   printf("  Unit::[%s] = %g * ", t->u_symbol, t->u_scale);
  851:   for(ue_p=t->u_list; ue_p ; ue_p = ue_p->ue_nextp) {
  852:     /*
  853:     printf("<%s,%d,%g,%g> ",ue_p->ue_symbol,ue_p->ue_index,ue_p->ue_scale,ue_p->ue_exp);
  854:     */
  855:     printf("(%g*%s^%g) ",ue_p->ue_scale,ue_p->ue_symbol,ue_p->ue_exp);
  856:   }
  857:   printf("\n");
  858: 
  859: }
  860: /*  ----------------------------------------------------------- */
  861: /*  copy the Unit_E linked list from b_p->u_list to a_p->u_list */
  862: /*   create some Unit_E nodes in a_p->u_list if needed and      */
  863: /*   leave b_p->u_list intact                                   */
  864: /*   a_p->u_scale is multiplied by pow(b_p->u_scale,exp_scale)  */
  865: /*  ----------------------------------------------------------- */
  866: void
  867: u_copy_unit(Unit_t *a_p, Unit_t *b_p, double exp_scale) 
  868: {
  869:   Unit_E  *oe_p, *ne_p, *last_p;
  870:   int      ii;
  871:   double   scale;
  872:   
  873:   if( a_p->u_count > 0 ) {
  874:     for(last_p = a_p->u_list; last_p->ue_nextp; last_p = last_p->ue_nextp) {  }
  875:   } else {
  876:     a_p->u_list = last_p = NULL;
  877:   }
  878:   if( b_p->u_count > 0 ) {
  879:     oe_p = b_p->u_list;
  880:     for(ii=0;ii<b_p->u_count;ii++) {
  881:       ne_p = (Unit_E *) capa_malloc(1, sizeof(Unit_E)); /* *** */
  882:       ne_p->ue_scale = oe_p->ue_scale;
  883:       ne_p->ue_exp   = oe_p->ue_exp * exp_scale;
  884:       ne_p->ue_index = oe_p->ue_index;
  885:       strcpy(ne_p->ue_symbol, oe_p->ue_symbol);
  886:       oe_p = oe_p->ue_nextp;
  887:       if( last_p == NULL ) {
  888:         a_p->u_list = ne_p;
  889:       } else {
  890:         last_p->ue_nextp = ne_p;
  891:       }
  892:       last_p = ne_p;
  893:       a_p->u_count++;
  894:     }
  895:     scale = pow(b_p->u_scale, exp_scale);
  896:     a_p->u_scale = a_p->u_scale * scale;
  897:     /* printf("Found scale=%g=%g\n",a_p->u_scale,b_p->u_scale); */
  898:   } else {  
  899:     if( b_p->u_type == U_BASE ) { 
  900:       /* *b_p is a base unit, so create a one element unit */
  901:       ne_p = (Unit_E *) capa_malloc(1, sizeof(Unit_E));   /* *** */
  902:       ne_p->ue_scale = b_p->u_scale;
  903:       ne_p->ue_exp   = exp_scale;
  904:       ne_p->ue_index = b_p->u_index;
  905:       strcpy(ne_p->ue_symbol, b_p->u_symbol);
  906:       if( last_p == NULL ) {
  907:         a_p->u_list = ne_p;
  908:       } else {
  909:         last_p->ue_nextp = ne_p;
  910:       }
  911:       last_p = ne_p;
  912:       a_p->u_count++;
  913:     } else if( b_p->u_type == U_DERIVED) {
  914:       /* derived units but without any units elements (scalar) */
  915:       /* do nothing, ignore this units  WE REALLY MEAN THIS DON'T DO THE NEXT LINE!*/
  916:       /*a_p->u_count++;*/
  917:     } else if( b_p->u_type == U_CONSTANT ) {
  918:       scale = pow(b_p->u_scale, exp_scale);
  919:       a_p->u_scale = a_p->u_scale * scale;
  920:     } else {
  921:       printf("This node has no u_e list and Type unknown\n");
  922:     }
  923:   }
  924: }
  925: int
  926: u_pm_op(Unit_t *a_p, Unit_t *b_p, int op)
  927: {
  928:   int    result=0;
  929:   
  930:   if( a_p->u_count > 0 || b_p->u_count > 0 ) {
  931:      printf(" cannot add or sub units at this moment\n");
  932:      return  result;
  933:   }
  934:   if( op == U_OP_PLUS ) {
  935:     a_p->u_scale = a_p->u_scale + b_p->u_scale;
  936:   } else {
  937:     a_p->u_scale = a_p->u_scale - b_p->u_scale;
  938:   }
  939:   return 1;
  940: }
  941: 
  942: int
  943: u_parsepower(char *unit_str)
  944: {
  945:   int   exp, ii;
  946:   char  *ch_p, exp_str[16];
  947: 
  948:   ch_p = unit_str;
  949:   while( isspace(*ch_p) ) { ch_p++; }
  950:   ii=0;
  951:   while( isdigit(*ch_p) ) {
  952:     ch_p++;
  953:   }
  954:   while( isspace(*ch_p) ) { ch_p++; }
  955:   if( *ch_p == '^' ) {
  956:     ch_p++;
  957:   }
  958:   while( isspace(*ch_p) ) { ch_p++; }
  959:   if( *ch_p == '{' ) {
  960:     ch_p++;
  961:   }
  962:   while( isspace(*ch_p) ) { ch_p++; }
  963:   ii=0;
  964:   while( isdigit(*ch_p) || *ch_p == '-' || *ch_p == '+' ) {
  965:     exp_str[ii++] = *ch_p;
  966:     ch_p++;
  967:   }
  968:   exp_str[ii]=0;
  969:   sscanf(exp_str,"%d", &exp);
  970:   return (exp);
  971: }
  972: 
  973: /* ------------------------------------------- */
  974: /* scan a number of the form indicated below from the input buffer */
  975: /* 1.234^{2.3} */
  976: /*  1e */
  977: double
  978: s_scan_number(char *buf, int idx, int *r_idx)
  979: {
  980:   double   num; 
  981:   float    exp; 
  982:   double   result;
  983:   int      ii=0;
  984:   char     num_str[QUARTER_K];
  985:   
  986:   num_str[ii]=0;
  987:   
  988:   if( buf[idx] == '-' ) {
  989:     num_str[ii++] = '-';
  990:     idx++;
  991:   }
  992:   while( isdigit(buf[idx]) || buf[idx] == '.' ) { 
  993:       num_str[ii++] = buf[idx];
  994:       idx++;
  995:   }
  996:   if( buf[idx] == 'E' || buf[idx] == 'e' ) {
  997:     if( buf[idx+1] == '-' || isdigit(buf[idx+1]) ) {
  998:       num_str[ii++] = buf[idx++];
  999:       num_str[ii++] = buf[idx++];
 1000:       while( isdigit(buf[idx]) ) {
 1001:         num_str[ii++] = buf[idx];
 1002:         idx++;
 1003:       }
 1004:     }
 1005:   }
 1006:   num_str[ii] = 0; /* terminate the str */
 1007:   sscanf(num_str,"%lg", &num);
 1008:   /* printf("Scan number %s got %g\n",num_str, num); fflush(stdout); */
 1009:   result = num;
 1010:   if( buf[idx] == '^' ) {
 1011:     idx++;
 1012:     while( isspace(buf[idx]) ) { idx++; }
 1013:     if( buf[idx] == '{' ) {  /* need to scan for a matching right bracket */
 1014:         idx++;
 1015:     }
 1016:     while( isspace(buf[idx]) ) { idx++; }
 1017:     num_str[0]=0;
 1018:     if( isdigit(buf[idx]) || buf[idx] == '+' || buf[idx] == '-' )  {
 1019:        ii=0;
 1020:        while( isdigit(buf[idx]) || buf[idx] == '.' || buf[idx] == '+' || buf[idx] == '-' ) {
 1021:          num_str[ii++] = buf[idx];
 1022:          idx++;
 1023:        }
 1024:        num_str[ii]=0;
 1025:     }
 1026:     while( isspace(buf[idx]) ) { idx++; }
 1027:     if( buf[idx] == '}' ) {
 1028:       idx++;
 1029:     }
 1030:     sscanf(num_str,"%f", &exp);
 1031:     /* printf("Scan exp number %s got %g\n",num_str, exp); fflush(stdout); */
 1032:     
 1033:     result = pow(num, (double)exp);
 1034:     /* printf("{%d^%d}=%g\n",num, exp,result); */
 1035:   }
 1036:   *r_idx = idx;
 1037:   return (result);
 1038: }
 1039: 
 1040: 
 1041: double
 1042: s_scan_symbol(char *buf,char *symb_p,int idx, int *r_idx)
 1043: {
 1044:   char     num_str[QUARTER_K];
 1045:   int      ii=0;
 1046:   double   r_exp=1.0;
 1047:   
 1048:   symb_p[0]=0;
 1049:   while( isalnum(buf[idx]) || buf[idx] == '_' ) {
 1050:     symb_p[ii++] = buf[idx];
 1051:     idx++;
 1052:   }
 1053:   symb_p[ii]=0;
 1054:   
 1055:   if( buf[idx] == '^' ) {  /* look for either left bracket or a number */
 1056:     idx++;
 1057:     while( isspace(buf[idx]) ) { idx++; } 
 1058:     if( buf[idx] == '{' ) {  /* need to scan for a matching right bracket */
 1059:       idx++;
 1060:     }
 1061:     while( isspace(buf[idx]) ) { idx++; }
 1062:     if( isdigit(buf[idx]) || buf[idx] == '.' || buf[idx] == '+' || buf[idx] == '-'  )  {
 1063:       ii=0; num_str[ii] = 0;
 1064:       while( isdigit(buf[idx]) || buf[idx] == '.' || buf[idx] == '+' || buf[idx] == '-' ) {
 1065:         num_str[ii++] = buf[idx];
 1066:         idx++;
 1067:       }
 1068:       num_str[ii]=0;
 1069:     }
 1070:     while( isspace(buf[idx]) ) { idx++; }
 1071:     if( buf[idx] == '}' ) {
 1072:       idx++;
 1073:     }
 1074:     sscanf(num_str,"%lg", &r_exp);  /* power could be of type float */
 1075:     /* printf("[scan symb with power %s ^ %lg] ",symb_p, r_exp); fflush(stdout);  */
 1076:   }
 1077:   *r_idx = idx;
 1078:   return (r_exp);
 1079: }
 1080: 
 1081: /*  return: err_code    0    parsed ok */
 1082: /*                      1    symbol is of length 1, not found in the tree */
 1083: /*                      2    symbol not found in the tree  */
 1084: /*                      3    symbol parsed as prefix symb, but symb not found */
 1085: /*                      4    symbol length is 0 or negative */
 1086: int
 1087: s_process_symb(char *symb_str,Unit_t  *cu_p,double exp)
 1088: {
 1089:   int      len;
 1090:   Unit_t  *au_p;
 1091:   int      c_result;
 1092:   int      ii;
 1093:   char     tmp_str[ANSWER_STRING_LENG];
 1094:   int      err_code = 0;
 1095:   double   d_exp;
 1096:   
 1097:   len = strlen(symb_str);
 1098:   if( len > 0 ) {
 1099:     au_p = u_find_symb(symb_str, UnitTree_p, &c_result);
 1100:     if( c_result == 1 ) {  /* if found, copy the definition over */
 1101:       u_copy_unit(cu_p, au_p, exp);
 1102:     } else {
 1103:       if( len > 1 ) {
 1104:         if( PrefixTbl[ (int)symb_str[0] ] != 0 ) {  /* prefix is defined */
 1105:           for(ii=1;ii<len;ii++) {
 1106:              tmp_str[ii-1] = symb_str[ii];
 1107:           }
 1108:           tmp_str[len-1]=0;
 1109:           au_p = u_find_symb(tmp_str, UnitTree_p, &c_result);
 1110:           if( c_result == 1 ) {
 1111:               /* printf("[%s] ", tmp_str); */
 1112:             u_copy_unit(cu_p, au_p, exp);
 1113:             d_exp = (double)PrefixTbl[ (int)symb_str[0] ] * exp;
 1114:             cu_p->u_scale = cu_p->u_scale * pow((double)10.0,d_exp);
 1115:           } else { /* unit *tmp_str not found */
 1116:             /*printf("The unit: %s, not defined\n",tmp_str);*/
 1117:             err_code = 3;
 1118:           }
 1119:         } else {
 1120:           /*printf("<<%s>>", symb_str);*/
 1121:           err_code = 2;
 1122:         }
 1123:       } else {/* len == 1 */
 1124: 	/*printf("The unit: %s, not defined\n",symb_str);*/
 1125:         err_code = 1;
 1126:       }
 1127:     }
 1128:   } else {
 1129:     err_code = 4;
 1130:   }
 1131:   return (err_code);
 1132: }
 1133: 
 1134: Unit_t *
 1135: u_parse_unit(char *unit_str)
 1136: {
 1137:   char      *ch;
 1138:   char       symb_str[QUARTER_K];
 1139:   int        idx;
 1140:   double     exp_sign;
 1141:   int        s_result;
 1142:   int        not_done;
 1143:   double     s_number,  offset;
 1144:   double     tmp_scale, symb_exp, exp;
 1145:   Unit_t    *cu_p;
 1146: 
 1147:   gUnitError=0;
 1148:   ch   = unit_str;
 1149:   cu_p = (Unit_t *) capa_malloc(1, sizeof(Unit_t)); /* *** */
 1150:   cu_p->u_scale = 1.0;
 1151:   idx = 0;  not_done = 1;
 1152:   exp_sign = 1.0; exp = 1;
 1153:   symb_str[0] = 0;
 1154: 
 1155:   while( isspace(*ch) ) { ch++; }    /* trim leading white spaces */
 1156:   /* fprintf(stdout,"PARSE |%s|\n", unit_str); */
 1157:   while( not_done ) {
 1158:     if( isdigit(ch[idx]) || ch[idx] == '-' ) {  /* rule 1: number */
 1159:        s_number = s_scan_number(ch,idx,&idx);
 1160:        
 1161:        tmp_scale = pow(s_number,exp_sign);
 1162:        /* printf("S=%g,Power(%g,%d)=%g\n", 
 1163:           cu_p->u_scale, s_number,exp_sign, tmp_scale);
 1164:        */
 1165:        cu_p->u_scale = cu_p->u_scale * tmp_scale;
 1166:        
 1167:        /* printf("[Scale %g=%g^%g] ",tmp_scale,s_number,exp_sign); */
 1168:        while( isspace(ch[idx]) ) { idx++; }
 1169:     } else {
 1170:       if( isalpha(ch[idx]) ) { /* rule 2: unit_symbol ^ exp */
 1171: 	symb_str[0] = 0;
 1172: 	symb_exp = s_scan_symbol(ch,symb_str,idx,&idx);
 1173: 	exp = (double)exp_sign * symb_exp;
 1174: 	/* printf("[scanned %s ^ (%g * %g)] ", symb_str,symb_exp,exp_sign); fflush(stdout); */
 1175: 	s_result = s_process_symb(symb_str,cu_p,exp);
 1176: 	if( s_result > 0 ) {
 1177: 	  /* printf("Error processing symbol [%s]\n", symb_str); */
 1178: 	  gUnitError = 1;
 1179: 	}
 1180: 	while( isspace(ch[idx]) ) { idx++; }
 1181:       } else {
 1182: 	if( ch[idx] == '*' || ch[idx] == '/' ) {
 1183: 	  if( ch[idx] == '/' ) { /* printf("[/] "); */ exp_sign = -1.0; }
 1184: 	  idx++;
 1185: 	  while( isspace(ch[idx]) ) { idx++; }
 1186: 	} else {
 1187: 	  if( ch[idx] == '+' || ch[idx] == '-' ) {
 1188: 	    idx++;
 1189: 	    while( isspace(ch[idx]) ) { idx++; }
 1190: 	    offset = s_scan_number(ch,idx,&idx);
 1191: 	    /* printf("[Offset %g] ",offset); */
 1192: 	  } else {
 1193: 	    if( ch[idx] == 0 ) {  /* end of input string */
 1194: 	      not_done = 0;
 1195: 	      /* printf("\n"); */
 1196: 	    } else {
 1197: 	      /* garbage in unit string */
 1198: 	      gUnitError = 1;
 1199: 	      not_done=0;
 1200: 	    }
 1201: 	  }
 1202: 	}
 1203:       }
 1204:     }
 1205:   }
 1206:   simplify_unit(cu_p);
 1207:   return (cu_p);
 1208: 
 1209: }
 1210: 
 1211: void
 1212: u_getunit(FILE *f)
 1213: {
 1214:   register int  unit_type;
 1215:   register int  c;
 1216:   int      power, result;
 1217:   char   *name_p, *symbol_p, *comment_p, *unit_p;
 1218:   
 1219:   BaseUnitcnt = 0;
 1220:   free_utree(UnitTree_p);
 1221:   UnitTree_p = NULL;
 1222:   c_moveto_unit(f);  /* move the file position to << */
 1223:   do {
 1224:     c_ignorewhite(f);
 1225:     c = getc(f); ungetc(c,f);
 1226:     if( c == '<' ) {
 1227:       unit_type = c_gettype(f);
 1228:     }
 1229:     if( c != EOF ) {
 1230:       switch(unit_type) {
 1231:         case U_BASE:
 1232:                name_p    = c_getword(f);    symbol_p = c_getword(f); 
 1233:                comment_p = c_getcomment(f);
 1234:                /*
 1235:                printf("B Unit: N=%s,S=%s,C=%s\n",name_p,symbol_p,comment_p);
 1236:                */
 1237:                result = u_insert_baseunit(name_p,symbol_p,comment_p);
 1238:                if( result == 1 ) {
 1239:                  printf("The entry %s is duplicated\n",symbol_p);
 1240:                }
 1241:                free(name_p); free(symbol_p); free(comment_p);
 1242:                break;
 1243:         case U_DERIVED:
 1244:                name_p    = c_getword(f);    symbol_p = c_getword(f);
 1245:                unit_p    = c_getstring(f);  comment_p = c_getcomment(f);
 1246:                /*
 1247:                printf("D Unit: N=%s,S=%s,C=%s,U=%s\n",
 1248:                        name_p,symbol_p,comment_p,unit_p);
 1249:                */
 1250:                result = u_insert_derived(name_p,symbol_p,comment_p,unit_p);
 1251:                if( result == 1 ) {
 1252:                  printf("The entry %s is duplicated\n",symbol_p);
 1253:                }
 1254:                /* preorder_utree(UnitTree_p); */ 
 1255:                free(name_p); free(symbol_p); free(comment_p); free(unit_p);
 1256:                break;
 1257:         case U_PREFIX:
 1258:                name_p    = c_getword(f);    symbol_p = c_getword(f);
 1259:                unit_p    = c_getstring(f);
 1260:                /*
 1261:                printf("Prefix: N=%s,S=%s,U=%s\n",
 1262:                        name_p,symbol_p,unit_p);
 1263:                */
 1264:                power = u_parsepower(unit_p);
 1265:                PrefixTbl[ (int)(*symbol_p) ] = power;
 1266:                /* printf("    P[%c]=%d\n",*symbol_p,power);  */
 1267:                free(name_p); free(symbol_p); free(unit_p);
 1268:                break;
 1269:         case U_CONSTANT:
 1270:                symbol_p = c_getword(f);  unit_p    = c_getstring(f);
 1271:                comment_p = c_getcomment(f);
 1272:                /*
 1273:                printf("Const.: S=%s,C=%s,U=%s\n",
 1274:                        symbol_p,comment_p,unit_p);
 1275:                */
 1276:                break;
 1277:         case U_UNKNOWN:
 1278:                /* printf("Unknown\n"); */
 1279:                break;
 1280:       }
 1281:     }
 1282:   } while ( c != EOF );
 1283: 
 1284: }
 1285: 
 1286: /* ----------------------------------------------------------------- */
 1287: /* comparing unit symbol names should be case sensitive */
 1288: int
 1289: comp_unit_symb(a, b) char *a; char *b;
 1290: {
 1291:   return strncmp(a,b,SYMBOL_MAXLEN);
 1292: }
 1293: 
 1294: 
 1295: Unit_t *
 1296: u_splay (char *name, Unit_t *t) 
 1297: {
 1298:   Unit_t     N;
 1299:   Unit_t    *l, *r, *y;
 1300: 
 1301:   if (t == NULL)  return t;
 1302:   N.u_left  = (Unit_t *)NULL;
 1303:   N.u_right = (Unit_t *)NULL;
 1304:   l = r = &N;
 1305: 
 1306:   for (;;) {
 1307:     if ( comp_unit_symb(name,t->u_symbol) < 0 ) {
 1308:       if (t->u_left == NULL)  break;
 1309:       if ( comp_unit_symb(name, (t->u_left)->u_symbol ) < 0 ) {
 1310:         y = t->u_left; t->u_left = y->u_right; y->u_right = t; t = y;
 1311:         if (t->u_left == NULL) break;
 1312:       }
 1313:       r->u_left = t; r = t; t = t->u_left;
 1314:     } else if ( comp_unit_symb(name,t->u_symbol) > 0 ) {
 1315:         if (t->u_right == NULL) break;
 1316:         if ( comp_unit_symb(name, (t->u_right)->u_symbol ) > 0 ) {
 1317:           y = t->u_right; t->u_right = y->u_left; y->u_left = t; t = y;
 1318:           if (t->u_right == NULL) break;
 1319:         }
 1320:         l->u_right = t; l = t; t = t->u_right;
 1321:     } else {
 1322:       break;
 1323:     }
 1324:   }
 1325:   l->u_right = t->u_left; r->u_left = t->u_right; t->u_left = N.u_right;
 1326:   t->u_right = N.u_left;
 1327:   return t;
 1328: }
 1329: 
 1330: 
 1331: 
 1332: /* returns: 0  correctly inserted */
 1333: /*          -1 error */
 1334: /*          1  duplicate entry    */
 1335: 
 1336: int
 1337: u_insert_baseunit(n_p,s_p,c_p) char  *n_p, *s_p, *c_p;
 1338: {
 1339:   Unit_t   *new_p, *t;
 1340:   int       len;
 1341:  
 1342:   new_p = (Unit_t *) capa_malloc(1, sizeof(Unit_t)); /* *** */
 1343:   if (new_p == NULL) {
 1344:       printf("Ran out of space\n");
 1345:       return(-1);
 1346:   }
 1347:   strcpy(new_p->u_symbol, s_p);
 1348:   strcpy(new_p->u_name, n_p);
 1349:   len = strlen(c_p);
 1350:   new_p->u_comment = (char *) capa_malloc((len+1), sizeof(char)); /* *** */
 1351:   strcpy(new_p->u_comment,c_p);
 1352:   BaseUnitcnt++;
 1353:   new_p->u_index  = BaseUnitcnt;
 1354:   new_p->u_type   = U_BASE;
 1355:   new_p->u_scale  = 1.0;
 1356:   new_p->u_offset = 0.0;
 1357:   new_p->u_count  = 0;
 1358:   new_p->u_list   = NULL;
 1359:  
 1360:   if (UnitTree_p == NULL) {  /* a new unit tree */
 1361:       UnitTree_p = new_p;
 1362:       return (0);
 1363:   }
 1364:   t = u_splay(s_p, UnitTree_p);
 1365:   if ( comp_unit_symb(s_p,t->u_symbol) < 0 ) {
 1366:         new_p->u_left = t->u_left; new_p->u_right = t;
 1367:         t->u_left = NULL;
 1368:         /* Splay_cnt++;  */
 1369:         UnitTree_p = new_p;
 1370:         return (0);
 1371:   } else if ( comp_unit_symb(s_p,t->u_symbol) > 0 ) {
 1372:         new_p->u_right = t->u_right; new_p->u_left = t;
 1373:         t->u_right = NULL;
 1374:         /* Splay_cnt++; */
 1375:         UnitTree_p = new_p;
 1376:         return (0);
 1377:   } else {    /* name and t->u_symbol is the same, which means found it */
 1378:         capa_mfree( (char *)new_p );
 1379:         UnitTree_p = t;
 1380:         return (1);
 1381:   }
 1382: }
 1383: 
 1384: 
 1385: int
 1386: u_insert_derived(n_p,s_p,c_p,u_p)char  *n_p, *s_p, *c_p, *u_p;
 1387: {
 1388:   Unit_t  *new_p, *t;
 1389:   int      c_result, len;
 1390:   
 1391:   /* inorder_utree(UnitTree_p); */
 1392:   t = u_splay(s_p, UnitTree_p);
 1393:   UnitTree_p = t;
 1394:   c_result = comp_unit_symb(s_p,t->u_symbol);
 1395:   if ( c_result == 0 ) {
 1396:     UnitTree_p = t;
 1397:     return (1);
 1398:   }
 1399:   
 1400:   /* prepare a new Unit_t */
 1401:   new_p = u_parse_unit(u_p);
 1402:   strcpy(new_p->u_symbol,s_p);
 1403:   strcpy(new_p->u_name, n_p);
 1404:   new_p->u_type = U_DERIVED;
 1405:   len = strlen(c_p);
 1406:   new_p->u_comment = (char *) capa_malloc((len+1), sizeof(char)); /* *** */
 1407:   strcpy(new_p->u_comment,c_p);
 1408:   
 1409:   simplify_unit(new_p);
 1410:   /*
 1411:   printf("Derived Unit:%s\n",new_p->u_name);
 1412:   print_unit_t(new_p); 
 1413:   */
 1414:   if (c_result < 0 ) {
 1415:     new_p->u_left = t->u_left; new_p->u_right = t;
 1416:     t->u_left = NULL;
 1417:   } else {  /* c_result > 0 */
 1418:     new_p->u_right = t->u_right; new_p->u_left = t;
 1419:     t->u_right = NULL;
 1420:   }
 1421:   UnitTree_p = new_p;
 1422:   
 1423:   return (0);
 1424:   
 1425: }
 1426: 
 1427: void
 1428: freelist_unit_e(Unit_E *ue_p) 
 1429: {
 1430:   Unit_E  *curr_p, *next_p;
 1431:   
 1432:   if( ue_p != NULL ) {
 1433:     next_p = ue_p->ue_nextp;
 1434:     curr_p = ue_p;
 1435:     if( next_p == NULL ) {
 1436:       capa_mfree((char *)curr_p);
 1437:     } else {
 1438:       for( curr_p = ue_p; next_p; curr_p = next_p, next_p = next_p->ue_nextp) {
 1439:         capa_mfree((char *)curr_p);
 1440:       }
 1441:       capa_mfree((char *)curr_p);
 1442:     }
 1443:   }
 1444: }
 1445: void
 1446: simplify_unit(u_p) Unit_t *u_p;
 1447: {
 1448:   Unit_E   *eu_p, *prev_p;
 1449:   int       ii, idx;
 1450:   
 1451:   /* walk through u_list and replace those u_index = -1 with */
 1452:   /* a linked list of basic unit. */
 1453:   /* u_msort_main() the whole u_list */
 1454:   /* combine those units with same u_index */
 1455:   for(ii=0;ii<BaseUnitcnt;ii++) {
 1456:     CScale[ii] = 0.0;
 1457:     CExp[ii] = 0.0;
 1458:   }
 1459:   /*
 1460:   printf("Before Simplify:: \n");
 1461:   print_unit_t(u_p);
 1462:   */
 1463:   if( u_p->u_count > 0 ) {
 1464:     
 1465:     for(eu_p=u_p->u_list; eu_p; eu_p = eu_p->ue_nextp) {
 1466:       idx = eu_p->ue_index;
 1467:       if( CScale[idx] == 0.0 ) {
 1468:         CScale[idx] = 1.0;
 1469:         strcpy(CSymb[idx],eu_p->ue_symbol);
 1470:       }
 1471:       CScale[idx] = CScale[idx] * eu_p->ue_scale;
 1472:       CExp[idx] = CExp[idx] + eu_p->ue_exp;
 1473:     }
 1474:     /* debugging 
 1475:     for(ii=0;ii<BaseUnitcnt;ii++) {
 1476:       if( CScale[ii] != 0.0 ) {
 1477:         printf("(%d)%s,S=%g,E=%g\n",ii,CSymb[ii],CScale[ii], CExp[ii]);
 1478:       }
 1479:       if( CExp[ii] == 0.0 ) {
 1480:         printf("(%d)%s,S=%g,Exp=%g\n",ii,CSymb[ii],CScale[ii], CExp[ii]);
 1481:       }
 1482:     }
 1483:     */
 1484:     freelist_unit_e(u_p->u_list);
 1485:     prev_p = u_p->u_list = NULL;
 1486:     u_p->u_count = 0;
 1487:     for(ii=0;ii<BaseUnitcnt;ii++) {
 1488:       if( CScale[ii] != 0.0 && CExp[ii] != 0) {
 1489:         eu_p = (Unit_E *)capa_malloc(1,sizeof(Unit_E)); /* ***************** */
 1490:         eu_p->ue_scale = 1.0;
 1491:         eu_p->ue_exp = CExp[ii];
 1492:         eu_p->ue_index = ii;
 1493:         strcpy(eu_p->ue_symbol,CSymb[ii]);
 1494:         if( prev_p == NULL) {
 1495:           u_p->u_list = prev_p = eu_p;
 1496:         } else {
 1497:           prev_p->ue_nextp = eu_p;
 1498:           prev_p = eu_p;
 1499:         }
 1500:         u_p->u_count++;
 1501:       }
 1502:     }
 1503:   }
 1504:   /* 
 1505:   printf("After Simplify:: \n");
 1506:   print_unit_t(u_p);
 1507:   */
 1508: }
 1509: 
 1510: /* before comparing two units, make sure they are of  basic form */
 1511: /* compares if two units are equal */
 1512: /* equality returns 1 */
 1513: 
 1514: int  is_units_equal(Unit_t *u1_p, Unit_t *u2_p)
 1515: {
 1516:   int      result=1;
 1517:   Unit_E  *a_p, *b_p;
 1518:   
 1519:   if( (u1_p->u_count == u2_p->u_count) && 
 1520:       (u1_p->u_scale == u2_p->u_scale) ) {
 1521:     for(a_p=u1_p->u_list, b_p=u2_p->u_list;
 1522:         a_p; a_p=a_p->ue_nextp, b_p=b_p->ue_nextp) {
 1523:       if(a_p->ue_index != b_p->ue_index ||
 1524:          a_p->ue_scale != b_p->ue_scale ||
 1525:          a_p->ue_exp   != b_p->ue_exp ) {
 1526:         result=0;
 1527:         break;
 1528:       }
 1529:     }
 1530:   } else {
 1531:     result=0;
 1532:   }
 1533:   return (result);
 1534: }
 1535: /*     input : both are the simplest units */
 1536: /*     result: 0.0 means they are not of euquvalent units */
 1537: /*             the ratio of u1 / u2   */
 1538: double  units_ratio(Unit_t *u1_p, Unit_t *u2_p)
 1539: {
 1540:   double   ratio=1.0;
 1541:   Unit_E  *a_p, *b_p;
 1542:   
 1543:   if( (u1_p->u_count == u2_p->u_count) ) {
 1544:     for(a_p=u1_p->u_list, b_p=u2_p->u_list;
 1545:         a_p; a_p=a_p->ue_nextp, b_p=b_p->ue_nextp) {
 1546:       if(a_p->ue_index != b_p->ue_index ||
 1547:          a_p->ue_scale != b_p->ue_scale ||
 1548:          a_p->ue_exp   != b_p->ue_exp ) {
 1549:         ratio=0.0;
 1550:         break;
 1551:       }
 1552:     }
 1553:   } else {
 1554:     ratio=0.0;
 1555:   }
 1556:   if( (ratio != 0.0) && (u2_p->u_scale != 0.0 )  ) {
 1557:     ratio = u1_p->u_scale / u2_p->u_scale;
 1558:   }
 1559:   return (ratio);
 1560: }
 1561: 
 1562: /* ------------- The Grammar of Units Parser --------------------
 1563: 
 1564:   scan_unit_expr()  -->  scan_basic_block()
 1565:                     -->  scan_basic_block() '+' scan_basic_block() 
 1566:                     -->  scan_basic_block() '-' scan_basic_block()
 1567:  
 1568:   scan_num_expr()   -->  scan_num_block()
 1569:                     -->  scan_num_block() '+' scan_num_block()
 1570:                     -->  scan_num_block() '-' scan_num_block()
 1571:                     
 1572:   scan_basic_block()-->  scan_basic_term()
 1573:                     -->  scan_basic_term()  '*' scan_basic_term()
 1574:                     -->  scan_basic_term()  ' ' scan_basic_term()
 1575:                     -->  scan_basic_term()  '/' scan_basic_term()
 1576: 
 1577:   scan_num_block()  -->  scan_num_term()
 1578:                     -->  scan_num_term()  '*' scan_num_term()
 1579:                     -->  scan_num_term()  ' ' scan_num_term()
 1580:                     -->  scan_num_term()  '/' scan_num_term()
 1581:   
 1582:   
 1583:   scan_basic_term() -->  scan_unit_item()          
 1584:                     -->  scan_num_item()
 1585:                     -->  '(' scan_basic_block() ')'
 1586:                     -->  '{' scan_basic_block() '}'
 1587: 
 1588:   scan_num_term()   -->  scan_num_item()<sp>*
 1589:                     --> '-' scan_num_item()<sp>*
 1590:                     --> '(' scan_num_expr() ')'
 1591:                     --> '{' scan_num_expr() '}'
 1592: 
 1593:   scan_unit_item()  -->  UNIT<sp>*
 1594:                     -->  UNIT<sp>*  '^' <sp>* scan_num_term()
 1595:                     
 1596:   scan_num_item()   -->  FLOAT<sp>*
 1597:                     -->  FLOAT<sp>* '^' <sp>* scan_num_term()
 1598:   
 1599:   scan_FLOAT()      -->  [0-9]+([eE][+-]?[0-9]+)*
 1600:   
 1601:   p_new_unit()      -->  [a-Z]+[a-Z0-9_]*
 1602:   
 1603:   -----------------------------------------
 1604:   U.expr  := B.block
 1605:            | B.block '+' B.block
 1606:            | B.block '-' B.block
 1607:            
 1608:   N.expr  := N.block 
 1609:            | N.block '+' N.block
 1610:            | N.block '-' N.block
 1611:  
 1612:  To allow for operations like (J/N)^2 or {N/m}^2 (N/J)^3 
 1613:  
 1614:  
 1615:   B.block := B.term
 1616:            | B.term ' ' B.term
 1617:            | B.term '*' B.term
 1618:            | B.term '/' B.term
 1619:            
 1620:   N.block := N.term 
 1621:            | N.term ' ' N.term
 1622:            | N.term '*' N.term
 1623:            | N.term '/' N.term
 1624:            
 1625:   B.term  := U.item
 1626:            | N.item
 1627:            | '(' B.block ')'
 1628:            | '{' B.block '}'
 1629:            
 1630:            | '(' B.block ')' ^ N.term
 1631:            | '{' B.block '}' ^ N.term
 1632:            
 1633:   N.term  := N.item
 1634:            | '-' N.item
 1635:            | '(' N.expr ')'
 1636:            | '{' N.expr '}'
 1637:            
 1638:   U.item  := UNIT
 1639:            | UNIT '^' N.term
 1640:            
 1641:   N.item  := FLOAT
 1642:            | FLOAT '^' N.term
 1643:            
 1644:   UNIT    := [a-Z]+[a-Z0-9_]*
 1645:   
 1646:   FLOAT   := [0-9]+([eE][+-]?[0-9]+)*
 1647:   
 1648:  ------------------------------------------------------------------- */
 1649:  
 1650: Unit_t *
 1651: p_new_op(Unit_t *left_p, int op, Unit_t *right_p)
 1652: {
 1653:   Unit_t  *new_p;
 1654:   
 1655:   new_p = (Unit_t *) capa_malloc(1, sizeof(Unit_t));
 1656:   if (new_p == NULL) {
 1657:       printf("Ran out of space\n");
 1658:       return(NULL);
 1659:   }
 1660:   new_p->u_left   = left_p;
 1661:   new_p->u_right  = right_p;
 1662:   new_p->u_scale  = 0.0;
 1663:   new_p->u_type   = op;
 1664:   new_p->u_offset = 0.0;
 1665:   new_p->u_count  = 0;
 1666:   new_p->u_list   = NULL;
 1667:   
 1668:   return (new_p);
 1669: }
 1670: 
 1671: Unit_t *
 1672: p_new_num(Unit_t *left_p, double num, Unit_t *right_p)
 1673: {
 1674:   Unit_t  *new_p;
 1675:   
 1676:   new_p = (Unit_t *) capa_malloc(1, sizeof(Unit_t));
 1677:   if (new_p == NULL) {
 1678:       printf("Ran out of space\n");
 1679:       return(NULL);
 1680:   }
 1681:   
 1682:   new_p->u_left   = left_p;
 1683:   new_p->u_right  = right_p;
 1684:   new_p->u_scale  = num;
 1685:   new_p->u_type   = U_CONSTANT;
 1686:   new_p->u_offset = 0.0;
 1687:   new_p->u_count  = 0;
 1688:   new_p->u_list   = NULL;
 1689:   
 1690:   return (new_p);
 1691: }
 1692: 
 1693: Unit_t *
 1694: p_new_unit(Unit_t *left_p, Unit_t *right_p)
 1695: {
 1696:   char     symb_str[ANSWER_STRING_LENG];
 1697:   int      ii=0;
 1698:   int      len;
 1699:   Unit_t  *au_p, *cu_p;
 1700:   int      c_result;
 1701:   char     tmp_str[ANSWER_STRING_LENG];
 1702:   int      err_code = 0;
 1703:   double   d_exp;
 1704:   
 1705:   symb_str[ii]=0;
 1706:   while( isspace(Sbuf[Sidx]) ) { Sidx++; }
 1707:   while( isalnum(Sbuf[Sidx]) || Sbuf[Sidx] == '_' ) {
 1708:     symb_str[ii++] = Sbuf[Sidx];
 1709:     Sidx++;
 1710:   }
 1711:   symb_str[ii]=0;
 1712:   /* printf("<U %s>", symb_str); */
 1713:   cu_p = (Unit_t *) capa_malloc(1, sizeof(Unit_t));
 1714:   strcpy(cu_p->u_symbol,symb_str);
 1715:   cu_p->u_left   = left_p;
 1716:   cu_p->u_right  = right_p;
 1717:   cu_p->u_scale  = 1.0;
 1718:   cu_p->u_type   = U_DERIVED;
 1719:   cu_p->u_offset = 0.0;
 1720:   cu_p->u_count  = 0;
 1721:   cu_p->u_list   = NULL;
 1722:   
 1723:   len = strlen(symb_str);
 1724:   if( len > 0 ) {
 1725:     au_p = u_find_symb(symb_str, UnitTree_p, &c_result);
 1726:     if( c_result == 1 ) {  /* if found, copy the definition over */
 1727:       u_copy_unit(cu_p, au_p, 1);
 1728:     } else {
 1729:       if( len > 1 ) {
 1730:         if( PrefixTbl[ (int)symb_str[0] ] != 0 ) {  /* prefix is defined */
 1731:           for(ii=1;ii<len;ii++) {
 1732:              tmp_str[ii-1] = symb_str[ii];
 1733:           }
 1734:           tmp_str[len-1]=0;
 1735:           au_p = u_find_symb(tmp_str, UnitTree_p, &c_result);
 1736:           if( c_result == 1 ) {
 1737:               /* printf("[%s] ", tmp_str); */
 1738:             u_copy_unit(cu_p, au_p, 1);
 1739:             d_exp = (double)PrefixTbl[ (int)symb_str[0] ];
 1740:             cu_p->u_scale = cu_p->u_scale * pow((double)10.0,d_exp);
 1741:           } else { /* unit *tmp_str not found */
 1742:             /* printf(" not found\n"); */
 1743:             err_code = 3;
 1744: 	    cu_p->u_type   = U_UNKNOWN;
 1745:           }
 1746:         } else { /* symb_str is not in <prefix><units> form */
 1747:           /* printf("<<%s>>", symb_str); */
 1748:           err_code = 2;
 1749: 	  cu_p->u_type   = U_UNKNOWN;
 1750:         }
 1751:       } else {/* len == 1 */
 1752:         /* printf(" not found in symbol tree \n"); */
 1753:         err_code = 1;
 1754: 	cu_p->u_type   = U_UNKNOWN;
 1755:       }
 1756:     }
 1757:   } else { /* why would we have a length less than zero symb_str ? */
 1758:     err_code = 4;
 1759:   }
 1760:   
 1761:   return (cu_p);
 1762: }
 1763: 
 1764: int  s_peeknext_op()
 1765: {
 1766:   char  *ch;
 1767:   int    sp=0;
 1768:   
 1769:   ch = (char *)&Sbuf[Sidx];
 1770:   while( isspace(*ch) ) { ch++; sp=1; }
 1771:   if( (*ch == '*')  || (*ch == '/') || (*ch == '+')  || (*ch == '-') || (*ch == '^')) {
 1772:     return (*ch);
 1773:   }
 1774:   /* what if space is the last thing on the line?*/
 1775:   if( sp && (*ch != '\0')) return '*';
 1776:   return (*ch);
 1777: }
 1778: 
 1779: int  s_getnext_op()
 1780: {
 1781:   char  *ch;
 1782:   int    inc = 0, sp=0;
 1783:   
 1784:   
 1785:   /* printf("\n((op"); print_remains(); printf("\n");  */
 1786:   ch = (char *)&Sbuf[Sidx];
 1787:   while( isspace(*ch) ) { ch++; inc++; sp=1; }
 1788:   Sidx = Sidx + inc;
 1789:   if( (*ch == '*')  || (*ch == '/') || (*ch == '+')  || (*ch == '-') || (*ch == '^') ) {
 1790:     Sidx++;
 1791:     /* print_remains();  printf(" op))"); printf("\n"); */
 1792:     return (*ch);
 1793:   }
 1794:   /* print_remains();  printf(" op))"); printf("\n"); */
 1795:   /* what if space is the last thing on the line?*/
 1796:   if( sp  && (*ch != '\0')) return '*';
 1797:   return (*ch);
 1798: }
 1799: 
 1800: int
 1801: s_getnext()
 1802: {
 1803:   char  ch;
 1804:   
 1805:   ch = Sbuf[Sidx];
 1806:   Sidx++;
 1807:   return (ch);
 1808: }
 1809: 
 1810: int
 1811: s_peeknext()
 1812: {
 1813:   char  ch;
 1814:   
 1815:   ch = Sbuf[Sidx];
 1816:   return (ch);
 1817: }
 1818: 
 1819: int
 1820: s_peeknextNW()  /* peek into the next non-whitespaces character */
 1821: {
 1822:   char  *ch;
 1823: 
 1824:   ch = (char *)&Sbuf[Sidx];
 1825:   while( isspace(*ch) ) { ch++; }
 1826:   return (*ch);
 1827: }
 1828: 
 1829: int
 1830: s_getnextNW()  /* get the next non-whitespaces character */
 1831: {
 1832:   char  *ch;
 1833: 
 1834:   ch = (char *)&Sbuf[Sidx]; Sidx++;
 1835:   while( isspace(*ch) ) { ch++; Sidx++; }
 1836:   return (*ch);
 1837: }
 1838: /* peek into the next non-whitespaces character 
 1839:    which should be either a multiply or division */
 1840: int
 1841: s_peekMDWS()  
 1842: {
 1843:   char  *ch;
 1844:   int    sp=0;
 1845:   
 1846:   ch = (char *)&Sbuf[Sidx];
 1847:   while( isspace(*ch) ) { ch++; sp=1;}
 1848:   if( (*ch == '*')  || (*ch == '/') ) {
 1849:     return (*ch);
 1850:   }
 1851:   if( sp ) return ' ';
 1852:   ch = (char *)&Sbuf[Sidx];
 1853:   while( isspace(*ch) ) { ch++; }
 1854:   return (*ch);
 1855: }
 1856: 
 1857: int
 1858: s_getnextMDWS()
 1859: {
 1860:   char  *ch;
 1861:   int    inc=0, sp=0;
 1862:   
 1863:   ch = (char *)&Sbuf[Sidx]; Sidx++;
 1864:   while( isspace(*ch) ) { ch++; inc++; sp=1; }
 1865:   Sidx += inc;
 1866:   if( (*ch == '*')  || (*ch == '/') ) {
 1867:     return (*ch);
 1868:   }
 1869:   if( sp ) return ' ';
 1870:   return (*ch);
 1871: }
 1872: 
 1873: double
 1874: scan_FLOAT()
 1875: {
 1876:   double   num; 
 1877:   int      ii=0, len;
 1878:   char     num_str[QUARTER_K];
 1879:   
 1880:   num_str[ii]=0;
 1881:   while( isspace(Sbuf[Sidx]) ) { Sidx++; }
 1882:   if( Sbuf[Sidx] == '-' ) {
 1883:     num_str[ii++] = Sbuf[Sidx++];
 1884:   }
 1885:   while( isdigit(Sbuf[Sidx]) || Sbuf[Sidx] == '.' ) {
 1886:       num_str[ii++] = Sbuf[Sidx++];
 1887:   }
 1888:   if( Sbuf[Sidx] == 'E' || Sbuf[Sidx] == 'e' ) {
 1889:     if( Sbuf[Sidx+1] == '-' || isdigit(Sbuf[Sidx+1]) ) {
 1890:       num_str[ii++] = Sbuf[Sidx++];
 1891:       num_str[ii++] = Sbuf[Sidx++];
 1892:       while( isdigit(Sbuf[Sidx]) ) {
 1893:         num_str[ii++] = Sbuf[Sidx++];
 1894:       }
 1895:     }
 1896:   }
 1897:   num_str[ii] = 0; /* terminate the str */
 1898:   len = strlen(num_str);
 1899:   if(len > 0 ) {
 1900:     sscanf(num_str,"%lg", &num);
 1901:     /* printf("<N %s %g>",num_str,num); fflush(stdout);  print_remains(); */
 1902:   } else {
 1903:     num = 1.0;
 1904:   }
 1905:   return (num);
 1906: }
 1907: /* -----------------------------------------------
 1908:   N.item  := FLOAT
 1909:            | FLOAT '^' N.term
 1910:    ----------------------------------------------- */
 1911: Unit_t  *
 1912: scan_num_item()
 1913: {
 1914:   Unit_t  *node_p, *exp_p;
 1915:   double   num_const;
 1916:   char     ch;
 1917:   
 1918:   num_const = scan_FLOAT();
 1919:   node_p = p_new_num(NULL, num_const, NULL);
 1920:   ch = s_peeknext_op();
 1921:   if( ch == '^' ) {
 1922:     ch = s_getnext_op();
 1923:     
 1924:     exp_p = scan_num_term();
 1925:     num_const = node_p->u_scale;
 1926:     if( node_p->u_scale > 0.0 ) {
 1927:       num_const = pow(node_p->u_scale,exp_p->u_scale);
 1928:     }
 1929:     node_p->u_scale = num_const;
 1930:     capa_mfree((char *)exp_p);
 1931:   }
 1932:   return node_p;
 1933: }
 1934: 
 1935: /* -----------------------------------------------
 1936:   U.item  := UNIT
 1937:            | UNIT '^' N.term
 1938:    ----------------------------------------------- */
 1939:    
 1940: Unit_t *
 1941: scan_unit_item()
 1942: {
 1943:   Unit_t   *node_p, *exp_p;
 1944:   char      ch;
 1945:   double   num_const;
 1946:   Unit_E   *oe_p;
 1947:   
 1948:   node_p = p_new_unit(NULL,NULL);
 1949:   ch = s_peeknext_op();
 1950:   if( ch == '^' ) {
 1951:     ch = s_getnext_op();
 1952:     exp_p = scan_num_term();
 1953:     num_const = exp_p->u_scale;
 1954:     if( node_p->u_count > 0 ) {
 1955:       oe_p = node_p->u_list;
 1956:       for(oe_p = node_p->u_list; oe_p; oe_p = oe_p->ue_nextp ) {
 1957:         oe_p->ue_exp   = oe_p->ue_exp * num_const;
 1958:       }
 1959:     }
 1960:     num_const = node_p->u_scale;
 1961:     if( node_p->u_scale > 0.0 ) {
 1962:       num_const = pow(node_p->u_scale,exp_p->u_scale);
 1963:     }
 1964:     node_p->u_scale = num_const;
 1965:     capa_mfree((char *)exp_p);
 1966:   }
 1967:   return node_p;
 1968: }
 1969: 
 1970: void distribute_exp(Unit_t* node_p,Unit_t* exp_p) 
 1971: {
 1972:   Unit_E* oe_p;
 1973:   double num_const;
 1974:   num_const = exp_p->u_scale;  /* should we check if num_const too large or small ? */
 1975:   if( node_p->u_count > 0 ) {
 1976:     oe_p = node_p->u_list;
 1977:     for(oe_p = node_p->u_list; oe_p; oe_p = oe_p->ue_nextp ) {
 1978:       oe_p->ue_exp   = oe_p->ue_exp * num_const;
 1979:     }
 1980:   }
 1981:   num_const = node_p->u_scale;
 1982:   if( node_p->u_scale > 0.0 ) {  /* what if u_scale <= 0.0 ? */
 1983:     num_const = pow(node_p->u_scale,exp_p->u_scale);
 1984:   }
 1985:   node_p->u_scale = num_const;
 1986:   if (node_p->u_left) distribute_exp(node_p->u_left,exp_p);
 1987:   if (node_p->u_right) distribute_exp(node_p->u_right,exp_p);
 1988: }
 1989: 
 1990: /* ---------------------------------------------------------------
 1991:    B.term  := U.item
 1992:            | N.item
 1993:            | '(' B.block ')'
 1994:            | '{' B.block '}'
 1995:            
 1996:            | '(' B.block ')' '^' N.term  <== July 6 1998
 1997:            | '{' B.block '}' '^' N.term
 1998:            
 1999:    --------------------------------------------------------------- */
 2000: Unit_t *
 2001: scan_basic_term()
 2002: {
 2003:   Unit_t   *node_p, *exp_p;
 2004:   int       ch, nch;
 2005:   
 2006:   ch = s_peeknextNW();
 2007:   if( ch == '(' || ch == '{' ) {
 2008:     ch = s_getnextNW();  /* get rid of '(' or '{' */
 2009:     node_p = scan_basic_block();
 2010:     nch = s_peeknextNW();
 2011:     if( nch == ')' || nch == '}' ) {  /* should be either ')' or '}' */
 2012:       if( ((ch == '(' ) && (nch == ')' )) ||
 2013:           ((ch == '{' ) && (nch == '}' )) ) { /* matching left paren with right paren */
 2014:           
 2015:            
 2016:       } else {
 2017:         /* printf(" WARN: %c matched by %c\n", ch, nch); */
 2018:       }
 2019:       nch = s_getnextNW();
 2020:       /* ====== Added Jul 6, 1998 ====> */
 2021:       ch = s_peeknext_op();
 2022:       if( ch == '^' ) {
 2023:         ch = s_getnext_op();  /* get rid of '^' char */
 2024:         exp_p = scan_num_term();
 2025: 	distribute_exp(node_p,exp_p);
 2026:         capa_mfree((char *)exp_p);
 2027:       } 
 2028:       /* <== added Jul 6, 1998 == */
 2029:     } else {
 2030:       /* printf(" WARN: %c is not matched by %c\n", ch, nch); */
 2031:     }
 2032:   } else if( ch >= '0' && ch <= '9' ) {
 2033:     node_p = scan_num_item();
 2034:   } else { /* assume a unit symbol */
 2035:     /* printf("<B.term>"); print_remains(); */
 2036:     node_p = scan_unit_item();
 2037:     /* print_remains(); */
 2038:   }
 2039:   return node_p;
 2040: }
 2041: /* --------------------------------------------------
 2042:    N.term  := N.item
 2043:            | '-' N.item
 2044:            | '(' N.expr ')'
 2045:            | '{' N.expr '}'
 2046:  -------------------------------------------------- */
 2047: Unit_t *
 2048: scan_num_term()
 2049: {
 2050:   Unit_t   *node_p;
 2051:   char      ch, nch;
 2052: 
 2053:   ch = s_peeknextNW();
 2054:   if( ch == '(' || ch == '{' ) {
 2055:     ch = s_getnextNW();
 2056:     node_p = scan_num_expr();
 2057:     nch = s_peeknextNW();
 2058:     if( nch == ')' || nch == '}' ) {  /* should be either ')' or '}' */
 2059:       if( ((ch == '(' ) && (nch == ')' )) ||
 2060:           ((ch == '{' ) && (nch == '}' )) ) { 
 2061:         
 2062:       } else {
 2063:         /* printf(" WARN: %c matched by %c\n", ch, nch); */
 2064:       }
 2065:       nch = s_getnextNW();
 2066:     } else {
 2067:       /* printf(" WARN: %c is not matched by %c\n", ch, ch); */
 2068:     }
 2069:   } else if( ch == '-' ) {
 2070:     ch = s_getnextNW();
 2071:     node_p = scan_num_item();
 2072:     node_p->u_scale = (-1)*node_p->u_scale;
 2073:   } else {
 2074:     if( isdigit(ch) ) {
 2075:        node_p = scan_num_item();
 2076:     } else { /* something other than a number */
 2077:        /*
 2078:           printf(" ERROR: expect a number: ");
 2079:           print_remains();
 2080:        */
 2081:        node_p = p_new_num(NULL, 0.0, NULL); /* make the unknown item */
 2082:     }
 2083:   }
 2084:   return node_p;
 2085: }
 2086: 
 2087: /* --------------------------------------------------
 2088:    B.block := B.term
 2089:            | B.term ' ' B.term
 2090:            | B.term '*' B.term
 2091:            | B.term '/' B.term
 2092:    -------------------------------------------------- */
 2093: Unit_t  *
 2094: scan_basic_block()
 2095: {
 2096:   Unit_t   *node_p;
 2097:   char      ch;
 2098:   int       op;
 2099:   
 2100:   /* printf("<B.block>(before B.term)"); print_remains(); */
 2101:   node_p = scan_basic_term();
 2102:   ch = s_peeknext_op();
 2103:   while ( ch == '*' || ch == '/' ) {
 2104:     op = ( ch == '/' ? U_OP_DIVIDE : U_OP_TIMES);
 2105:     ch = s_getnext_op();
 2106:     /* printf("<B.block>(/ *)"); print_remains();  */
 2107:     node_p = p_new_op(node_p,op,scan_basic_term());
 2108:     ch = s_peeknext_op();
 2109:   }
 2110:   return node_p;
 2111: }
 2112: /* --------------------------------------------------
 2113:    N.block := N.term 
 2114:            | N.term ' ' N.term
 2115:            | N.term '*' N.term
 2116:            | N.term '/' N.term
 2117:    -------------------------------------------------- */
 2118: Unit_t  *
 2119: scan_num_block()
 2120: {
 2121:   Unit_t   *node_p, *opand_p;
 2122:   char      ch;
 2123:   double    result;
 2124:   
 2125:   node_p = scan_num_term();
 2126:   ch = s_peeknext_op();
 2127:   while ( ch == '*' || ch == '/' ) {
 2128:     s_getnext_op();
 2129:     opand_p = scan_num_term();
 2130:     if( ch == '*' ) {
 2131:       result = node_p->u_scale * opand_p->u_scale;
 2132:     } else {
 2133:       result = node_p->u_scale / opand_p->u_scale;
 2134:     }
 2135:     node_p->u_scale = result;
 2136:     capa_mfree((char *)opand_p);
 2137:     ch = s_peeknext_op();
 2138:   }
 2139:   return node_p;
 2140: }
 2141: 
 2142: /* ---------------------------------------
 2143:    U.expr  := B.block
 2144:            | B.block '+' B.block
 2145:            | B.block '-' B.block
 2146:    --------------------------------------- */
 2147: Unit_t  *
 2148: scan_unit_expr()
 2149: {
 2150:   Unit_t   *node_p;
 2151:   char      ch;
 2152:   int       op;
 2153:   
 2154:   /* printf("<U.expr>"); print_remains();  */
 2155:   node_p = scan_basic_block();
 2156:   ch = s_peeknext_op();
 2157:   while ( ch == '+' || ch == '-' ) {
 2158:     op = ( ch == '+' ? U_OP_PLUS : U_OP_MINUS);
 2159:     ch = s_getnext_op();
 2160:     /* printf("<U.expr>(+-)"); print_remains(); */
 2161:     node_p = p_new_op(node_p,op,scan_basic_block());
 2162:     ch = s_peeknext_op();
 2163:   }
 2164:   return node_p;
 2165: }
 2166: /* -----------------------------------------
 2167:    N.expr  := N.block 
 2168:            | N.block '+' N.block
 2169:            | N.block '-' N.block
 2170:    ----------------------------------------- */
 2171: Unit_t  *
 2172: scan_num_expr()
 2173: {
 2174:   Unit_t   *node_p, *opand_p;
 2175:   char      ch;
 2176:   double    result;
 2177:   
 2178:   node_p = scan_num_block();
 2179:   ch = s_peeknext_op();
 2180:   while ( ch == '+' || ch == '-' ) {
 2181:     ch = s_getnext_op();
 2182:     opand_p = scan_num_block();
 2183:     if( ch == '+' ) {
 2184:       result = node_p->u_scale + opand_p->u_scale;
 2185:     } else {
 2186:       result = node_p->u_scale - opand_p->u_scale;
 2187:     }
 2188:     node_p->u_scale = result;
 2189:     capa_mfree((char *)opand_p);
 2190:     ch = s_peeknext_op();
 2191:   }
 2192:   return node_p;
 2193: }
 2194: 
 2195: /* ----------------------------------------------------------------------- */
 2196: /* <--  This is the major entry point to parse an units expression ------> */
 2197: Unit_t  *
 2198: parse_unit_expr(char *symb_str)
 2199: {
 2200:   Unit_t   *root_p;
 2201:   int       len;
 2202:   
 2203:   len = strlen(symb_str);
 2204:   strcpy(Sbuf,symb_str);  /* copy it into the global Sbuf */
 2205:   Sidx=0;
 2206:   root_p = scan_unit_expr();
 2207:   if(Sidx < len-1 ) {
 2208:     /* printf(" WARN: NOT PARSED:");  print_remains(); */
 2209:   }
 2210:   return (root_p);
 2211: 
 2212: }
 2213: 
 2214: void
 2215: print_remains()
 2216: {
 2217:   int       len, ii;
 2218:   
 2219:   len = strlen(Sbuf);
 2220:   printf("[[");
 2221:   for(ii=Sidx;ii<len;ii++) {
 2222:       printf("%c",Sbuf[ii]);
 2223:   }
 2224:   printf("]]");
 2225:   
 2226: }
 2227: 
 2228: 
 2229: 
 2230: /* =================================================================== */

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>