/*------------------------------------------------------------------------------
 src/lib/dj/rand.cxx
 
 Copyright (c) 2004-2006 Darby Johnston.
 All rights reserved.
 Use is subject to license terms.
------------------------------------------------------------------------------*/

#include "djMath.h"
#include <sys/time.h>
#include <stdlib.h>
#include <math.h>

namespace dj {

static double _rand() { return ::rand() / double(RAND_MAX); }
#define _RANDOM_INT(in, rand) \
  int((rand) * (((in) - 1) + (((in) < 0) ? -almostOne : almostOne)))
static int _rand(int in) { return _RANDOM_INT(in, _rand()); }

int rand(int in) { return _rand(in); }
int rand(int min, int max)
{
  if (min < max) return min + _rand(max - min + 1);
  else return max + _rand(min - max + 1);
}

double rand() { return _rand(); }

double rand(double in) { return _rand() * in; }
double rand(double min, double max) { return min + _rand() * (max - min); }

void randSeed(int in)
{
  if (in <= 0) {

    // Seed with the current time.
    //
    struct timeval time;
    gettimeofday(&time, 0);
    srand(time.tv_usec);

  } else {
  
    srand(in);
  }
}

}
