#include "layers.h"

int move() {

  int i,j;
  double xtmp,ytmp,ztmp,dx,dy,dz,ddx,ddy,ddz;
  double NHfac,vscal;
  double v,maxv;
  double adLxh = 2.0 / Lx;
  double adLyh = 2.0 / Ly;
  double adLzh = 2.0 / Lz;
  double dtqdm = deltat * deltat / m;
  double Ekinsoll;

  Ekinsoll = 0.001 * 0.5 * (double)Ndegfree * Rgas * Tsoll;

  if(NHT) {
    NHfac = 1.0 / (1.0 + NHzeta * deltat * 0.5);
  } else   NHfac = 1.0;

  maxv = 5.0*sqrt(3.0*0.001*Rgas*Tsoll/m);

  Ekin = 0.0;

  for(i=0;i<nsites;i++) {

    xtmp = xo[i] + (2.0 * (x[i] - xo[i]) + fx[i] * dtqdm) * NHfac;
    ytmp = yo[i] + (2.0 * (y[i] - yo[i]) + fy[i] * dtqdm) * NHfac;
    ztmp = zo[i] + (2.0 * (z[i] - zo[i]) + fz[i] * dtqdm) * NHfac;

    dx = xtmp-x[i];
    dy = ytmp-y[i];
    dz = ztmp-z[i];

    Ekin += dx*dx+dy*dy+dz*dz;

    ddx = Lx * (int)(xtmp * adLxh);
    ddy = Ly * (int)(ytmp * adLyh);
    ddz = Lz * (int)(ztmp * adLzh);

    xtmp -= ddx;
    ytmp -= ddy;
    ztmp -= ddz;

    xo[i] = x[i]-ddx;
    yo[i] = y[i]-ddy;
    zo[i] = z[i]-ddz;

    x[i] = xtmp;
    y[i] = ytmp;
    z[i] = ztmp;

    if(VELDIS) {
      v = sqrt((x[i]-xo[i])*(x[i]-xo[i])+(y[i]-yo[i])*(y[i]-yo[i])+
               (z[i]-zo[i])*(z[i]-zo[i]))/0.001;
      if(v<maxv) {
        j = (int)(100.0*(v/maxv));
        if(j<100) vdist[j]++;
      }
    }

  }

  if(KINSTA) {

    Ekin = 0.5*m*Ekin/deltat/deltat;
    vscal = sqrt(Ekinsoll/Ekin);
    Ekin = 0.0;

    for(i=0;i<nsites;i++) {    

      dx = x[i] - xo[i];
      dy = y[i] - yo[i];
      dz = z[i] - zo[i];
      xo[i] = x[i] - vscal * dx;
      yo[i] = y[i] - vscal * dy;
      zo[i] = z[i] - vscal * dz;
      dx = x[i]-xo[i];
      dy = y[i]-yo[i];
      dz = z[i]-zo[i];

      Ekin += dx*dx+dy*dy+dz*dz;

    }

  }

  Ekin = 0.5*m*Ekin/deltat/deltat;

  if(NHT) {
    NHzetaold = NHzeta;
    NHzeta = (Ekin/Ekinsoll-1.0)*(deltat/NHtau/NHtau)+NHzetaold;
  }

  return(1);
}
