/* Integer Version 2.0, RD, 21.1.93	irandom.c	*/

#include "iint.h"
#include "imem.h"
#include <LiDIA/random.h>
/* #include "random.h" */
#include <stdlib.h>
#include "timing.h"

#define NO_RANDOM_BITS 31

static DigitType 
Prandom()
 /* return  random DigitType */
{
    unsigned int x;
    static BOOLEAN init = FALSE;
    int i;
    DigitType ran;

    if (!init)
    {
	init = TRUE;
	x = timeseed();
	srandom(x);
    }

    ran = random();
    i = NO_RANDOM_BITS;
    while (i < BitsPerDigit)
    {
	ran = (ran << NO_RANDOM_BITS) | random();
	i += NO_RANDOM_BITS;
    }
    return ran;
}				/* Prandom */

void 
IasrandomI(a, b)
    Integer *a;
    const Integer *b;
/* waehle a zufaellig mit 0<=|a|<|b|, a->sign=b->sign.
   a und b muessen verschieden sein. */
{
    register int i;
    register DigitType *pa;
    register int nl;
    nl = b->length;
    if (nl > a->maxlength)
    {
	delDigitVec(a->vec, a->maxlength);
	a->maxlength = nl;
	a->vec = newDigitVec(&a->maxlength);
    }
    pa = a->vec;
    pa[nl - 1] = Prandom() % (b->vec[nl - 1]);
    for (i = nl - 2; i >= 0; i--)
	pa[i] = Prandom();
    i = nl;
    while (!pa[i - 1] && i > 0)
	i--;
    a->length = i;
    if (i)
	a->sign = b->sign;
    else
	a->sign = PLUS;
}				/* IasrandomI */
