#include <stdio.h>

int main() {
  double t, x, v, a, w2, A, e;
  double dt, dt2;
  int i, n;
  FILE *dat, *gp;
  
  A = 1;
  w2 = 1;
  dt = 0.1;
  dt2=dt*dt;
  n = 1000;
  dat = fopen("HarmonicOscillator.dat", "w");

  // initial conditions
  x = A;
  v = 0;
  a = -w2*x;
  t = 0;
  for (i=0; i< n; i++) {
    x += v*dt + 0.5*a*dt2;
    v += 0.5*a*dt;
    a = -w2*x;
    v += 0.5*a*dt;
    e = v*v+w2*x*x;    
    t += dt;
    fprintf(dat, "%f %f %f %f\n", t, x, v, e);
  }
  fclose(dat);
  gp = popen("gnuplot", "w");
  fprintf(gp, "plot 'HarmonicOscillator.dat' u 1:4 w l\n");
  fflush(gp);
  getchar();
  fclose(gp);
  return(0);
}