/* This function calculates two N(0,1) deviates, 
   saves one and returns the other.  The next time 
   it is called it simply returns the saved one 
   and the cycle is repeated next time the 
   function is called.  Thus it is NOT suitable 
   in some contexts... */
#include <math.h>

double rnorm(long *seed)
{
  double rand1(long *seed);  /* A U[0,1] generator */
  static int flag=0;        /* A flag for whether to calculate new */
			    /* deviates or return a saved one (0=new, */
			    /* 1=saved) */
  static float saved;       /* The value of the saved deviate */
  double fac,rsq,v1,v2;

  /*  if(*seed $<$ 0) flag=0;*/
  if (flag == 0) {           /* If we must generate new deviates */
    do {
      v1=2.0*rand1(seed)-1.0;    /* Generate two numbers in $[-1,1]$ */
      v2=2.0*rand1(seed)-1.0;
      rsq=v1*v1+v2*v2;
    } while (rsq >= 1.0 || rsq == 0.0); /* If they're within 1 of */
					/* (0,0) keep them.  */
					/* Otherwise try again. */
    fac=sqrt(-2.0*log(rsq)/rsq);   /* Now use Box-Muller to get two */
    saved=v1*fac;                  /* N(0,1) deviates.  Save one and */
    flag=1;return v2*fac;          /* return the other. */
  }

  else {                     /* Else we have one saved */
    flag=0;                          /* Unset the flag and */
    return saved;                    /* return the saved value */
  }
}
