/******************************************************************************
$Id$

TextMMS: an ncurses audio player for Linux
Copyright (C) 2003 Ben Hoskings <benhoskings@users.sourceforge.net>

This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place, Suite 330, Boston, MA 02111-1307 USA
******************************************************************************/

#include "rand.h"
#include "debug.h"


static int   istart = sizeof(int) - 1;
static FILE *fp_rand = NULL;

state_t rand_open()
{
    if (fp_rand == NULL)
    {
        fp_rand = fopen("/dev/urandom", "r");
        
        if (fp_rand != NULL)
        {
            return OK;
        }
        else
        {
            error("rand_open(): fopen() failed!\n");
            return ERR_FILE;
        }
    }
    else
    {
        error("rand_open(): rand FILE already open!\n");
        return ERR_OPEN;
    }
}

state_t rand_close()
{
    if (fp_rand != NULL)
    {
        if (fclose(fp_rand) == 0)
        {
            return OK;
        }
        else
        {
            error("rand_close(): fclose() failed!\n");
            return ERR_FILE;
        }
    }
    else
    {
        error("rand_close(): rand FILE not opened!\n");
        return ERR_CLOSE;
    }
}

int rand_get()
{
    int val = 0,
        i;
    
    if (fp_rand != NULL)
    {
        /* we combine enough 8-bit values */
        for (i = istart; i >= 0; i--)
        {
            /* truncate the random value to 8 bits before adding it */
            val += (fgetc(fp_rand) & 0xff) << (i * 8);
        }
        
        /* clear the MSB to make the value positive (0 <= val <= RAND_MAXVAL) */
        val &= RAND_MAXVAL;
    }
    else
    {
        error("rand_get(): f_rand not opened!\n");
        val = -1;
    }
    
    return val;
}

