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

#define eps 1.0e-16
#define N 100
#define kp 40
#define kc 250
#define F0 5
#define v0 0.01
#define vf 0.04
#define m 1
#define dt 0.001
#define Nsteps 200000
#define to_plot 10

double sign(double num) {
  
  double s=1.0;

  if ( num<0 )
    s=-1.0;

  return s;

}

double get_vnext(double vnow, double Fl, double Fb) {

  double vnext, Fftr, vtr, Ff = 0.0;

  if ( fabs(vnow) < eps ) {
   if ( fabs(Fb+Fl) < F0 )
     vnext = 0.0;
   else {
     Ff=-F0*sign(Fb+Fl);
     vnext=(dt/m)*(Fb+Fl+Ff)+vnow;
   }
  }

  else {
    Fftr = -F0*sign(vnow)/(1+fabs(vnow/vf));
    vtr = (dt/m)*(Fb+Fl+Fftr)+vnow;
    if ( vtr*vnow < 0.0 )
      vnext = 0.0;
    else {
      vnext = vtr;
    }
  }

  return vnext;

}

main() {
  
  int i,n;
  double Fl, Fb;
  double xnow[N], xnext[N], vnow[N], vnext[N];
  FILE *fid;
  
  /* Initialize xnow to random numbers */
  srand(time(0));
  for (n=0;n<N;n++) { 
    xnow[n]=( (0.1*rand())/RAND_MAX-0.5 )*0.01;
    vnow[n]=0.0; 
  }
  /* Open the file */
  fid=fopen("position","w");    
  for (n=0;n<Nsteps;n++) {
    
    /* Two ends -- free boundary conditions */
    /* Leftmost block */
    Fl = kp*(v0*n*dt-xnow[0]);
    Fb = kc*(xnow[1]-xnow[0]);
    vnext[0] = get_vnext(vnow[0],Fl,Fb);
    xnext[0] = dt*vnow[0]+xnow[0];
    
    /* Rightmost block */
    Fl = kp*(v0*n*dt-xnow[N-1]);
    Fb = kc*(xnow[N-2]-xnow[N-1]);
    vnext[N-1] = get_vnext(vnow[N-1],Fl,Fb);
    xnext[N-1] = dt*vnow[N-1]+xnow[N-1];

    for (i=1;i<N-1;i++) {

      Fl = kp*(v0*n*dt-xnow[i]);
      Fb = kc*(xnow[i+1]+xnow[i-1]-2*xnow[i]);
      vnext[i] = get_vnext(vnow[i],Fl,Fb);
      xnext[i] = dt*vnow[i]+xnow[i];

      
    }
    
    fprintf(fid,"%lf\n",xnow[to_plot]);


    /* Propagate */
    for (i=0;i<N;i++) {
      xnow[i]=xnext[i];
      vnow[i]=vnext[i];
    }      
  }
  fclose(fid);
}



