#include <ctype.h>
#include <exec/types.h>
#include "mp.h"
extern int debug;
/*************************************************************
* Round a positive integer to the "simplest" number in [val..limit]
*/

#define lsdig(x)  (((x) >= 10) ? (x)-((x)/10)*10 : (x))

iround(val,dir,limit)
int val, dir;
float limit;

{
   int tmpval;

   switch (dir) {
      case UP:
         tmpval = lsdig(val);
         tmpval = ( (tmpval) ? (val+10-tmpval) : val );
         if (tmpval > limit) return(val);
         if (val <= 10) return(tmpval);
         val = iround(tmpval/10,dir,limit/10);
         return(val*10);
      case DOWN:
         tmpval = val-lsdig(val);
         if (tmpval < limit) return(val);
         if (val <= 10) return(tmpval);
         val = iround(tmpval/10,dir,limit/10);
         return(val*10);
   }   
   return(val);
}


/*************************************************************
* Round an FFP to the "simplest" number in [val..limit]
*/

#define FLARGE 1.0e18

FFP fround(ffpval, dir, ffplimit)
FFP ffpval, ffplimit;
int dir;
{
   FFP val, limit, fact=1.;
   
   val = ffpval;   
   limit = ffplimit;   

   if (debug) printf("fround: val=%f, dir=%d, limit=%f\n",ffpval,dir,ffplimit);
   if (abs(val) < 1.e-4) return((FFP)0.);
   if (val < 0.) {
      val *= -1.; limit *= -1.; fact = -1.;
      dir = (dir==UP ? DOWN : UP);
   }
   
   while (val < 1.e5) {val*=10.; limit*=10.; fact*=10.;}
   while (val > 1.e6) {val*=0.1; limit*=0.1; fact*=0.1;}
   if ((int)val) {
      val = (FFP) iround( (int)val, dir, limit);
      if (debug) printf("fround: returning %f\n",val/fact);
      val /= fact;
      return(val);
   }
   else {
      if (debug) printf("fround: returning 0.0\n");
      return(0.0);
   }
}


/***************************************************************************/
char *getwrd(bp)
char **bp;
{
   char *retval;
   
   while (**bp == ' ') (*bp)++;
   retval = *bp;
   while (**bp && (**bp != ' ') ) (*bp)++;
   return(retval);
}


/***************************************************************************/
numeric(cp)
char *cp;
{
   int rv = FALSE;
   char c;
   
   while(*(cp) == ' ') cp++;

   while (c = *(cp++)) {
      if (isdigit(c)||(toupper(c)=='E')||(c=='-')||(c=='+')||(c=='.'))
         rv = TRUE;
      else if ( c==' ')
         return(rv);
      else
         return(FALSE);
   }
   return(rv);
}


/***************************************************************************/
same(a,b,len)
char *a, *b;
int len;
{
   char i=0;
   
   while(*a && *b) {
      if (toupper(*a) != toupper(*b)) return(FALSE);
      a++; b++; i++;
      if (i==len) return(TRUE);
   }
   return(i==len);
}

/***************************************************************************/
void trch(oldch,newch,buf)
char oldch, newch, *buf;
{
   while (*buf) {
      if (*buf == oldch) *buf = newch;
      buf++;
   }
}

