//================================================== file = count2exp.c =====
//=  Program to convert arrivals per minute into exponential interarrivals  =
//===========================================================================
//=  Notes:                                                                 =
//=    1) Input from input file "in.dat" to stdin (see example below)       =
//=        * Comments are bounded by "&" characters at the beginning and    =
//=          end of the comment block                                       =
//=    2) Assumes that counts are for 1 minute intervals                    =
//=    3) Output is to stdout                                               =
//=-------------------------------------------------------------------------=
//= Example "in.dat" file:                                                  =
//=                                                                         =
//=   & Here are counts for 3 minutes &                                     =
//=   2                                                                     =
//=   3                                                                     =
//=   1                                                                     =
//=-------------------------------------------------------------------------=
//= Example output (for above "in.dat")                                     =
//=                                                                         =
//=   & --------------------------------------- count2exp.c ----- &         =
//=   5.879006                                                              =
//=   1.014231                                                              =
//=   0.093412                                                              =
//=   0.259823                                                              =
//=   0.209890                                                              =
//=   1.518870                                                              =
//=   & --------------------------------------------------------- &         =
//=-------------------------------------------------------------------------=
//=  Build: bcc32 count2exp.c, cl count2exp.c                               =
//=-------------------------------------------------------------------------=
//=  Execute: count2exp < in.dat                                            =
//=-------------------------------------------------------------------------=
//=  Author: Ken Christensen                                                =
//=          University of South Florida                                    =
//=          Web: http://www.csee.usf.edu/~christen                         =
//=          Email: christen@csee.usf.edu                                   =
//=-------------------------------------------------------------------------=
//=  History: KJC (05/26/13) - Genesis (from interval.c)                    =
//===========================================================================
//----- Include files -------------------------------------------------------
#include <stdio.h>                 // Needed for printf() and feof()
#include <stdlib.h>                // Needed for exit() and atof()
#include <string.h>                // Needed for strcmp()
#include <math.h>                  // Needed for log()

//----- Defines -------------------------------------------------------------
#define MAX_SIZE     2000000       // Max size of time series data array

//----- Globals -------------------------------------------------------------
double     X[MAX_SIZE];            // Time series read from "in.dat"
long int   N;                      // Number of values in X[]

//----- Prototypes ----------------------------------------------------------
void   load_X_array(void);         // Load X array
double exponential(double x);      // Returns an exponential random variable
double rand_val(int seed);         // Jain's RNG

//===========================================================================
//=  Main program                                                           =
//===========================================================================
void main(void)
{
  int  i, j;                       // Loop counters

  // Seed the RNG
  rand_val(1);

  // Load the series X
  printf("& --------------------------------------- count2exp.c ----- & \n");
  load_X_array();

  // Generate exponential interarrival times for each minute interval
  for (i=0; i<N; i++)
    for (j=0; j<((int) X[i]); j++)
      printf("%f \n", exponential(60.0 / X[i]));

  printf("& --------------------------------------------------------- & \n");
}

//===========================================================================
//=  Function to load X array from stdin and determine N                    =
//===========================================================================
void load_X_array(void)
{
  char      temp_string[1024];     // Temporary string variable

  // Read all values into X
  N = 0;
  while(1)
  {
    scanf("%s", temp_string);
    if (feof(stdin)) goto end;

    // This handles a comment bounded by "&" symbols
    while (strcmp(temp_string, "&") == 0)
    {
      do
      {
        scanf("%s", temp_string);
        if (feof(stdin)) goto end;
      } while (strcmp(temp_string, "&") != 0);
      scanf("%s", temp_string);
      if (feof(stdin)) goto end;
    }

    // Enter value in array and increment array index
    X[N] = atof(temp_string);
    N++;

    // Check if MAX_SIZE data values exceeded
    if (N >= MAX_SIZE)
    {
      printf("*** ERROR - greater than %ld data values \n", MAX_SIZE);
      exit(1);
    }
  }

  // End-of-file escape
  end:

  return;
}

//===========================================================================
//=  Function to generate exponentially distributed random variables        =
//=    - Input:  Mean value of distribution                                 =
//=    - Output: Returns with exponentially distributed random variable     =
//===========================================================================
double exponential(double x)
{
  double z;                     // Uniform random number (0 < z < 1)
  double exp_value;             // Computed exponential value to be returned

  // Pull a uniform random number (0 < z < 1)
  do
  {
    z = rand_val(0);
  }
  while ((z == 0) || (z == 1));

  // Compute exponential random variable using inversion method
  exp_value = -x * log(z);

  return(exp_value);
}

//=========================================================================
//= Multiplicative LCG for generating uniform(0.0, 1.0) random numbers    =
//=   - x_n = 7^5*x_(n-1)mod(2^31 - 1)                                    =
//=   - With x seeded to 1 the 10000th x value should be 1043618065       =
//=   - From R. Jain, "The Art of Computer Systems Performance Analysis," =
//=     John Wiley & Sons, 1991. (Page 443, Figure 26.2)                  =
//=========================================================================
double rand_val(int seed)
{
  const long  a =      16807;  // Multiplier
  const long  m = 2147483647;  // Modulus
  const long  q =     127773;  // m div a
  const long  r =       2836;  // m mod a
  static long x;               // Random int value
  long        x_div_q;         // x divided by q
  long        x_mod_q;         // x modulo q
  long        x_new;           // New x value

  // Set the seed if argument is non-zero and then return zero
  if (seed > 0)
  {
    x = seed;
    return(0.0);
  }

  // RNG using integer arithmetic
  x_div_q = x / q;
  x_mod_q = x % q;
  x_new = (a * x_mod_q) - (r * x_div_q);
  if (x_new > 0)
    x = x_new;
  else
    x = x_new + m;

  // Return a random value between 0.0 and 1.0
  return((double) x / m);
}
