#include <stdio.h>
#include <stdlib.h>

#include "global.h"
#include "r_random.h"

/* this is the seed size in bytes for the random number generator */
static const int NUMBYTES = 256;

/* make sure the first thing you do before using this is call RandInit() */
static R_RANDOM_STRUCT randStruct;

/* seed the random number generator */
void RandInit(void) {
  uchar buf[NUMBYTES];

  printf("Generating seed...\n");
  /* get the seed from the videocamera */
  getRandomSeed(buf, NUMBYTES, "do_capture");
  printf("Seeding done.\n");

  R_RandomInit(&randStruct);
  R_RandomUpdate(&randStruct, buf, NUMBYTES);
}

int main(int argc, char * argv[]) {
  FILE * fp;
  
  const int BUF_SIZE = 100;
  uchar buf[BUF_SIZE];

  /* where to write the random data generated (in binary format) */
  const char * file_name = "./rand_data"; 

  /* how many random bytes to generate */
  /* the default number set here is the one recommended by the diehard
     battery of statistical tests */
  int N = 4 * 2867200;

  RandInit();

  if (argc > 2) {
    fprintf(stderr, "Usage: %s [num_bytes_to_generate]\n", argv[0]);
    return (-1);
  }

  if (argc == 2) {
    N = atoi(argv[1]);
    if (N <= 0) {
      fprintf(stderr, "Number of bytes must be positive.\n");
      return (-1);
    }
    if (N % BUF_SIZE) {
      fprintf(stderr, "Number of bytes must be multiple of %d.\n", BUF_SIZE);
      return (-1);      
    }
  }

  if ((fp = fopen(file_name, "wb")) == NULL) {
    fprintf(stderr, "Error opening %s.\n", file_name);
    return -1;
  }
  
  printf("Generating %d random bytes in file %s.\n", N, file_name);

  for(int i = 0; i < N / BUF_SIZE; i++) { 
    R_GenerateBytes (buf, BUF_SIZE, &randStruct);
    if (fwrite(buf, 1, BUF_SIZE, fp) != BUF_SIZE) {
      fprintf(stderr, "Error writing to %s.\n", file_name);
      return -1;
    }
  }
  
  R_RandomFinal(&randStruct);  /* clean up when done */
  fclose(fp);
  printf("Job done!\n");
  return 0; 
}

