#include "layers.h"

int forces() {

  int i,j;
  double sqdr,rsqdr,rdr6;
  double dx,dy,dz;
  double dEdr,Etmp;
  double sqcutoff = cutoff*cutoff;
  double adLxh = 2.0 / Lx;
  double adLyh = 2.0 / Ly;
  double adLzh = 2.0 / Lz;
  double sig6 = pow(sigma,6.0);
  double sig12 = pow(sigma,12.0);
  double A = 4.0*epsilon*sig12;
  double B = 4.0*epsilon*sig6;
  double dA = 48.0*epsilon*sig12;
  double dB = 24.0*epsilon*sig6;
  double dE, dV;

  Evdw = 0.0;
  Vvdw = 0.0;

  if(SHIFT) {
    dE = - EshiftpIA;
    dV = - VshiftpIA;
  } else {
    dE = 0.0;
    dV = 0.0;
  }

  for(i=0;i<nsites;i++) {
    fx[i] = 0.0;
    fy[i] = 0.0;
    fz[i] = 0.0;
  }

  for(i=0;i<nsites-1;i++) {
    for(j=i+1;j<nsites;j++) {

      dx = x[j]-x[i];
      dy = y[j]-y[i];
      dz = z[j]-z[i];
      dx -= Lx * (int)(dx * adLxh);
      dy -= Ly * (int)(dy * adLyh);
      dz -= Lz * (int)(dz * adLzh);

      sqdr = dx*dx+dy*dy+dz*dz;

      if(sqdr<sqcutoff) {

          rsqdr =  1.0/sqdr;
          rdr6  =  rsqdr*rsqdr*rsqdr;
          Etmp  =  A * rdr6 * rdr6 - B * rdr6 + dE;

	  //  if(Etmp>10.0) printf("%d, forces: U(%d-%d) = %le, nsites = %d\n",currentstep,i,j,Etmp,nsites);

          Evdw += Etmp;
          dEdr  = -dA * rdr6 * rdr6 * rsqdr + dB *rdr6 * rsqdr;
          Vvdw -=  dEdr * sqdr + dV;

          fx[i] += dEdr * dx;
          fy[i] += dEdr * dy;
          fz[i] += dEdr * dz;
          fx[j] -= dEdr * dx;
          fy[j] -= dEdr * dy;
          fz[j] -= dEdr * dz;
      }
    }
  }

  if(LRC) { 
    Evdw += Elrc*(double)(nsites*nsites);
    Vvdw += Vlrc*(double)(nsites*nsites);
  }


  return(1);
}
