
#include <stdio.h>

/* Program to calculate the path of a bouncing ball and make a maple plot of it */

const int SERIES_LEN= 1000;
const double END_TIME= 10;

/* Acceleration due to gravity - negative since it is downwards - defined as a global const though we could use a #define if we wished*/

const double g = -9.8;

void plot_2d_graph (char [], double [], double [], int);
/* Plot a 2d graph of two series */

int main (int argc, char *argv[])
{
    double heights[SERIES_LEN];  /* height of ball*/
    double times[SERIES_LEN];    /* time series*/
    double dt;                  /* Time step to use */
    double vel= 0;              /* Velocity of ball - initially 0*/
    double height= 10;          /* Initial height - 10m */
    double coeff= 0.9;          /* Coefficient of restitution - 0.9 */
    double time= 0;             /* Current simulation time */
    int i;           

    dt= (double) END_TIME/ (double) SERIES_LEN;
    /* Fill the series with points related to the bouncing ball*/
    for (i= 0; i < SERIES_LEN; i++) {
        heights[i]= height;
        times[i]= time;
        vel+= g * dt;
        height+= vel *dt;
        time+= dt;
          /* If we are below the "ground" and moving down then we "bounce" */
        if (height < 0 && vel < 0)
             vel = - coeff * vel;
    }
    plot_2d_graph ("bounce.dat",times, heights, SERIES_LEN);
}


void plot_2d_graph (char filename [], double xseries[], double yseries[], 
    int len)

/* Function prints two series of doubles in x,y to a file in Maple format */
{
    FILE *fptr;
    int i;
    
    /* Try to open the file */
    fptr= fopen (filename, "w");
    if (fptr == NULL) {
        fprintf (stderr, "Unable to open file \"%s\"\n", filename);
        return;
    }
    /* Print out the file */
    fprintf (fptr, "p:=[\n");
    for (i= 0; i < len; i++) {
        fprintf (fptr, "[%f,%f]",xseries[i],yseries[i]);
        if (i != len - 1)    /* Omit the comma on the last line */
             fprintf (fptr,",");
        fprintf (fptr, "\n");
    }
    fprintf (fptr, "]:\n");
    fclose (fptr);
}

