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

void write_2d_array (char [], int, double [], double []);
/* A function which outputs maple style files to plot an array */


const int POINTS= 500;    /* No. of points in array */

const double PI 3.141599;
#define SINFILE "sin.out"       /* Various files for output */
#define SINCOSFILE "sincos.out"
#define SINSINFILE "sinsin.out"

int main()
{
    double x[POINTS], y[POINTS];  /* Arrays which will hold our points to plot */
    double angle;  /* An angle in radians - used to calculate sin and cos */
    int i;
    
    
    /* Write the first function - a sin wave */
    for (i= 0; i < POINTS; i++) {
        x[i]= i*2.0*PI/ POINTS;   /* This will do one cycle of the sin */
        y[i]= sin (x[i]);
    }
    write_2d_array (SINFILE, POINTS, x, y);
    /* The second is a sin versus a cos wave */
    for (i= 0; i < POINTS; i++) {
        angle= i*2.0 *PI / POINTS;
        x[i]= sin(angle);
        y[i]= cos(angle);
    }
    write_2d_array (SINCOSFILE, POINTS, x, y);
    /* The final plot is a sin versuts a sine with 1.5 times the frequency
    offset by 30 degrees */
    for (i= 0; i < POINTS; i++) {
        angle= i*8.0 * PI / POINTS;  /* 4 cycles of the sin wave */
        x[i]= sin(angle);
        y[i]= sin(PI/6+angle*1.5);  /* 30 degrees + 1.5 times frequency */
    }
    write_2d_array (SINSINFILE, POINTS, x, y);
    return 0;
}



void write_2d_array (char filename [], int no_points, double xaxis[], 
   double yaxis[])
/* Writes a maple style output of a variable for plotting */
{
    FILE *fptr;
    int i;
    fptr= fopen (filename, "w");
    if (fptr == NULL) {
        fprintf (stderr, "Unable to open \"%s\" to write\n", filename);
        exit (-1);
    }
    fprintf (fptr, "p:=[\n");
    for (i= 0; i < no_points; i++) {
        fprintf (fptr, "[%f,%f]", xaxis[i], yaxis[i]);
        if (i < no_points-1)
            fprintf (fptr,",");  /* All but last line need comma */
        fprintf (fptr, "\n");
        
    }
    fprintf (fptr,"];\n");
    fclose(fptr);
}

