/*
 * Copyright (c) 2004, Anthony Roberts
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following
 * disclaimer in the documentation and/or other materials provided
 * with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */



#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <string.h>
#include "arger.h"
#include "random.h"

extern char *myname;

/* initializes the rand48 generator from the source file */
int init_rand48 (char *source_file) {
  int in;
  union {
    long int num;
    char buff[RANDOM_STATESIZE];
    unsigned short seed[RANDOM_STATESIZE / sizeof(unsigned short)];
  } state; 

  in = open(source_file, O_RDONLY, MODE_DONTCARE);

  if (in < 0) {
    fprintf(stderr, "%s: could not open \"%s\".\n", myname, source_file);
    exit(1);
  }

  if (read(in, state.buff, RANDOM_STATESIZE) != RANDOM_STATESIZE) {
    fprintf(stderr, "%s: could not read from \"%s\".\n",
	    myname, source_file);
    close(in);
    return 1;
  }

  close(in);

  srand48(state.num);
  return 0;
}

/* initializes the rand48 generator from stdin */
int init_rand48_stdin () {
  union {
    long int num;
    char buff[RANDOM_STATESIZE];
    unsigned short seed[RANDOM_STATESIZE / sizeof(unsigned short)];
  } state; 

  if (read(STDIN, state.buff, RANDOM_STATESIZE) != RANDOM_STATESIZE) {
    fprintf(stderr, "%s: could not read from stdin.\n", myname);
    return 1;
  }

  if (isatty(STDIN)) {
    while (!feof(stdin)) {
      getchar();
    }
  }

  srand48(state.num);
  return 0;
}

