/* nag_rand_skip_ahead_power2 (g05kkc) Example Program.
 *
 * Copyright 2014 Numerical Algorithms Group.
 *
 * Mark 23, 2011.
 */

#include <stdio.h>
#include <nag.h>
#include <nag_stdlib.h>
#include <nagg05.h>

#define LSEED 1

int main(void)
{
  /* Scalars */
  Integer exit_status = 0;
  Integer lstate, n, nv, subid, i;
  /* Arrays */
  Integer seed[LSEED];
  Integer *state = 0;
  double *x = 0;
  char cgenid[40];
  /* Nag types */
  Nag_BaseRNG genid;
  NagError fail;

  /* Initialise the error structure */
  INIT_FAIL(fail);

  printf("nag_rand_skip_ahead_power2 (g05kkc) Example Program Results\n\n");

  /* Skip heading in data file */
  scanf("%*[^\n] ");

  /* Read in the base generator information and seed */
  scanf("%39s%"NAG_IFMT "%"NAG_IFMT "%*[^\n] ",cgenid,&subid,&seed[0]);
  genid = (Nag_BaseRNG) nag_enum_name_to_value(cgenid);

  /* Query to get the require length of state array */
  lstate = -1;
  nag_rand_init_repeatable(genid, subid, seed, LSEED, state, &lstate, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_rand_init_repeatable (g05kfc).\n%s\n", fail.message);
    exit_status = 1;
    goto END;
  }
  
  /* Allocate state */
  if (!(state = NAG_ALLOC((lstate), Integer)))
    {
      printf("Allocation failure\n");
      exit_status = -1;
      goto END;
    }

  /* Initialize the generator to a repeatable sequence */
  nag_rand_init_repeatable(genid, subid, seed, LSEED, state, &lstate, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_rand_init_repeatable (g05kfc).\n%s\n", fail.message);
    exit_status = 2;
    goto END;
  }

  /* Read in the skip ahead and sample size */
  scanf("%"NAG_IFMT "%"NAG_IFMT "%*[^\n] ",&n,&nv);
  if (!(x = NAG_ALLOC((nv), double)))
    {
      printf("Allocation failure\n");
      exit_status = -2;
      goto END;
    }

  /* Advance the sequence 2**n places */
  nag_rand_skip_ahead_power2(n, state, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_rand_skip_ahead_power2 (g05kkc).\n%s\n",
            fail.message);
    exit_status = 3;
    goto END;
  }

  /* Generate NV variates from a uniform distribution */
  nag_rand_basic(nv, state, x, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_rand_basic (g05sac).\n%s\n", fail.message);
    exit_status = 4;
    goto END;
  }

  /* Display the variates */
  for (i = 0; i < nv; i++) printf("%10.4f\n", x[i]);
  printf("\n");

 END:
  NAG_FREE(x);
  NAG_FREE(state);
  return exit_status;
}