#ifndef SIM_HPP
#define SIM_HPP

#include <gsl/gsl_rng.h>
#include <complex>
#include <math.h>

#include "latlib/neigh.h"

class sim : public o815::sim {
public:
  struct siteconf {
    complex<double> phi;
  };
  sim(o815 *_O815);
  siteconf* conf;
  unsigned int LSIZE2;
  double M;
  double m;
  neigh *nb;

private:
  void _makeSweep();
  void _newParas();
  gsl_rng* rangsl;
  void updatePhi (const int& x);
  static double magnYOfR (const double& r);
};

double sim::magnYOfR (const double& r) 
{
  return sqrt( -std::log(1-r) );
}

sim::sim(o815 *_O815) : o815::sim( _O815, 
				   sizeof(siteconf)*
				   (_O815->comargs.lsize[0]*_O815->comargs.lsize[1]) ) {
  conf = (siteconf*)confMem;

  rangsl = gsl_rng_alloc(gsl_rng_ranlxs0);
  gsl_rng_set(rangsl, time(NULL));

  LSIZE2 = _O815->comargs.lsize[0] * _O815->comargs.lsize[1];

  nb = new neigh(2, _O815->comargs.lsize[0], _O815->comargs.lsize[1]);
}

void sim::updatePhi (const int& x) 
{
  complex<double> V=0;
  complex<double> Y;

  for (int nu=0; nu<4; nu++)
    V += conf[ (*nb)[x*4+nu] ].phi;

  Y = sqrt(M) * conf[x].phi - V / sqrt(M);

#if defined(ALGORITHM_AHBMHB) || defined(ALGORITHM_AHBMOR) || defined(ALGORITHM_AHBM0)
  Y = polar( abs(Y), gsl_rng_uniform(rangsl) * 2*M_PI );
#elif defined(ALGORITHM_AORMHB) || defined(ALGORITHM_AORMOR) || defined(ALGORITHM_AORM0)
  const double V2diff = pow(real(V), 2) - pow(imag(V), 2);
  const double Vprod = real(V)*imag(V);
  Y = complex<double> ( + real(Y) * V2diff + 2 * imag(Y) * Vprod,
			- imag(Y) * V2diff + 2 * real(Y) * Vprod ) / norm(V);
#endif
  
#if defined(ALGORITHM_AHBMHB) || defined(ALGORITHM_AORMHB) || defined(ALGORITHM_A0MHB)
  Y = polar( magnYOfR( gsl_rng_uniform(rangsl) ), arg(Y) );
#elif defined(ALGORITHM_AHBMOR) || defined(ALGORITHM_AORMOR) || defined(ALGORITHM_A0MOR)
  Y = polar( magnYOfR( exp( -norm(Y) ) ), arg(Y) );
#endif

  conf[x].phi = Y / sqrt(M) + V / M;
}

void sim::_makeSweep() {  
  for (int ichecker=0; ichecker<2; ichecker++)
    for (int it=0; it<O815->comargs.lsize[0]; it++)
      for (int iy=(it+ichecker)%2; iy<O815->comargs.lsize[1]; iy+=2)
	updatePhi( it*O815->comargs.lsize[1] + iy );
}

void sim::_newParas() {
  m = (*O815->paraQ)["mass"];
  M = pow( (*O815->paraQ)["mass"], 2 ) + 4;
  *log << "SIM: Resetting fields." << endl << flush;

  for (int ix=0; ix<LSIZE2; ix++)
    conf[ix].phi = polar( 1., gsl_rng_uniform(rangsl) * 2*M_PI );
}

#endif
