#include "layers.h"

double  gauss_rand(void) {

  double        v1, v2, r, fac;

  if(set == 0) {

    do {
      v1 = 2.0*((double)rand()/RAND_MAX)-1.0;
      v2 = 2.0*((double)rand()/RAND_MAX)-1.0;
      r = v1*v1 + v2*v2;
    } while(r > 1.0 || r == 0.0);

    fac = sqrt(-2.0 * log(r) / r);
    gset = v1 * fac;
/*
  printf("fac = %le\n",fac);
  printf("r = %le\n",r);
  printf("v2fac = %le\n",v2*fac);
*/
    set = 1;
    return(v2*fac);

  } else {

    set = 0;
    return(gset);

  }
}

void merr(char* str) {

  fprintf(stderr,"%s\n",str);
  exit(1);

}

int checkcoords(void) {

  int i;

  for(i=0;i<nsites;i++) 
    if(fabs(x[i])>Lx*0.5 || fabs(y[i])>Ly*0.5 || fabs(z[i])>Lz*0.5 )
       merr("At least one particle is outside the box");

  return(1);
}

int checkvel(void) {

  int i;
  double t;

  for(i=0;i<nsites;i++) {
    t = ((x[i]-xo[i])*(x[i]-xo[i])+(y[i]-yo[i])*(y[i]-yo[i])+
        (z[i]-zo[i])*(z[i]-zo[i])/deltat/deltat*0.5*m)/Rgas*2.0/3.0;
    if(t>10000.0) {
      fprintf(stderr, "T(%d) = %le\n", i,t);
      merr("Input is too hot");
    }
  }

  return(1);
}

void write_time(clock_t t0,clock_t t1) {

  double ttot = ((double)(t1-t0))/CLOCKS_PER_SEC;
  time_t t;
  t = time(NULL);

  fprintf(output,"# Simulation ended at %s", ctime(&t));
  fprintf(output,"# total CPU time: %12d seconds\n",(int)ttot);
}

