#include <stdio.h>
#include <math.h>

int main() {
  double t, x, v, a, w2, A, e;
  double dt, dt2;
  int i, n;
  double gamma;// dumping in units of m
  double F, Omega;
  double K;
  int trans;
  FILE *dat, *gp;
  
  A = 1;
  w2 = 1;
  dt = 0.1;
  dt2=dt*dt;
  n = 10000;
  trans = 9000;
  F = 1;
  Omega = 1.;
  dat = fopen("ForcedDumpedHarmonicOscillator.dat", "w");

  // initial conditions
  x = A;
  v = 0;
  a = -w2*x;
  t = 0;
  gamma = 0.1;
  for (i=0; i< n; i++) {
    x += v*dt + 0.5*a*dt2;
    v += 0.5*a*dt;
    K = F * sin(Omega * t);
    a = -w2*x - gamma * v + K;
    v += 0.5*a*dt;
    e = v*v+w2*x*x;    
    t += dt;
    if (i>trans) {
      fprintf(dat, "%f %f %f %f\n", t, x, v, K );
    }
  }
  fclose(dat);
  gp = popen("gnuplot", "w");
  fprintf(gp, "set multiplot layout 1,2\n");
  fprintf(gp, "plot 'ForcedDumpedHarmonicOscillator.dat' u 1:2 t 'response' w l, ");
  fprintf(gp, "'' u 1:4 t 'driv e' w l\n");
  fprintf(gp, "plot 'ForcedDumpedHarmonicOscillator.dat' u 2:4 w l\n ");
  fflush(gp);
  getchar();
  fclose(gp);
  return(0);
}