#include <conf.h>

#include <stdio.h>
#include <stdlib.h>
#include <x_types.h>
#include <sys/types.h>
#ifdef  HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#ifdef  HAVE_SYS_TIME_H
#ifdef  TIME_WITH_SYS_TIME
#include <time.h>
#endif
#endif
#include <unistd.h>


Real64
drandom()
{
  static Uns8	initialized = 0;
  Int32		the_seed;

  if(! initialized){

    the_seed = (Int32) (time(NULL) * getpid());

#ifdef	HAVE_GETTIMEOFDAY
    {
	struct timeval	tv;

	gettimeofday(&tv, NULL);

	the_seed *= (tv.tv_sec * 1000 + tv.tv_usec / 1000
			+ (tv.tv_usec % 1000) * 100000000);
    }
#endif

#ifdef	HAVE_DRAND48
    srand48((long int) the_seed);
#else
#ifdef	HAVE_RAND
    srand((unsigned int) the_seed);
#endif
#endif

    initialized = 1;
  }

#ifdef	HAVE_DRAND48
    return((Real64)  drand48());
#else
#ifdef	HAVE_RAND
    return((Real64) rand() / (Real64) (RAND_MAX));
#endif
#endif

#if !defined(HAVE_DRAND48) && !defined(HAVE_RAND)
#error	"No random function found."
#endif
}


Real64
Real64_precision()
{
  static Int16	prec_calculated = 0;
  Real64		d, q;
  static Real64		p;

  if(prec_calculated)
    return(p);

  d = 1.0;
  q = 2.0;

  while(q != 1.0){
    while(1.0 + d != 1.0){
	p = d;
	d /= q;
    }
    d = p;
    q = 1.0 + ((q - 1.0) / 2.0);
  }

  prec_calculated = 1;

  return(p);
}


double
r_int(double d)
{
  int	r;

  r = (d > 0.0 ? (int) (d + 0.5) : - (int) (-d + 0.5));

  return((double) r);
}

int
is_nan(float f)
{
  char	*u;

  u = (char *) (&f);

  if((u[3] & 127) == 127 && (u[2] & 128) == 128 &&
	((u[2] & 127) != 0 || u[1] != 0 || u[0] != 0))
    return(1);

  return(0);
}

/************ end of $RCSfile$ ******************/
