% This function calculates the potential energy, kinetic energy and the total energy.
function totenergy(t, N, xn, pn, m, Lo2, eta, Q, Tset, s, a, pressure, estar, kB, rstar,energy_cutoff, totEnergyFile);

deltaR = zeros(1,3);
L = zeros(1,3);

for i = 1:3 L(1,i) = 2.*Lo2(1,i); end;
volume = L(1,1)*L(1,2)*L(1,3);
energy = 0;
potenergy = 0;

for i = 1:N
  for j = i+1:N
    for k = 1:3
      deltaR(1,k) = xn(i,k)-xn(j,k);
      if (deltaR(1,k) > Lo2(1,k)) deltaR(1,k) = deltaR(1,k)-L(1,k); end;
      if (deltaR(1,k) < (-1.*Lo2(1,k))) deltaR(1,k) = deltaR(1,k) + L(1,k); end;
    end;
  
    if ((deltaR(1,1) < a) && (deltaR(1,2) < a) && (deltaR(1,3) < a)) r = partsep(deltaR);
    else r = 10*a; 
    end;

    LJE = LJEnergy(r, energy_cutoff);
    if (r<a) potenergy = potenergy + LJE; end;
  end;
end;

KE = KEnergy(pn,m,N);
energy = potenergy + KE;
Tmeas = 2*KE/(3*(N-1));
Nose = potenergy + KE + eta*eta*N*Q + 3.*N*Tset*s;

%Printing the data out to file.
fprintf(totEnergyFile, '%d\t %g\t %g\t %g\t %g\t %g\n', t, potenergy, KE, energy, Tmeas*estar/kB, Tset*estar/kB);
