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

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


enum {
    MAXPOINTS= 50000,    /* Maximum No. of points in array */
    RESOLUTION= 1000      /* No of "slots" in which we divide [0,1] */
};

#define OUTFILE "chaos2.out"

int main()
{
    float xpts[MAXPOINTS], ypts[MAXPOINTS];  
       /* Arrays which will hold our points to plot */
     /* NOTE: Defining a very large array and then only filling part of it
     is inefficient but it's the only way to do this using the language
     features I'd taught you up to this point - it's also far easier
     than the alternatives */
    int tot_points; /* No. of points to plot */
    float x,lambda; /* See question for equation */
    float z[RESOLUTION];  /* Array representing [0,1] for a particular lambda*/
    int zval;   /* Used to map [0, 1] back to 0-> RESOLUTION */
    int i,j;
    tot_points= 0;
    for (i= 0; i < RESOLUTION; i++) {
        /* This maps a number from 0->RESOLUTION-1 to a number from 0.5 1.0 */
        lambda= 0.75+ (0.25*(float)i / (RESOLUTION-1));
        /* Blank out the z array */
        for (j= 0; j < RESOLUTION; j++) {
            z[j]= 0;
        }
        x= 0.3456;  /* Initialise x */
        /* Don't plot the first 50 x values */
        for (j= 0; j < 50; j++) {
            x= 4*lambda*x*(1.0 - x);
        }
        for (j= 50; j < 150; j++) {
            x= 4*lambda*x*(1.0 - x);
            /* Map back to 0-> RESOLUTION -1 - check range just in case */
            zval= (int) (x* (RESOLUTION-1));
            if (zval >= RESOLUTION)
                zval= RESOLUTION-1;
            if (z[zval] == 0) {
                z[zval]= 1;
                xpts[tot_points]= lambda;
                ypts[tot_points]= x;
                tot_points++;
                if (tot_points == MAXPOINTS) {
                    printf ("Too many points to plot\n");
                    return -1;
                }
            }
        }
        
    }
    write_2d_array (OUTFILE, tot_points, xpts, ypts);
    return 0;
}


void write_2d_array (char filename [], int no_points, float xaxis[], 
   float yaxis[])
/* Writes an EXCELL 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);
    }

    for (i= 0; i < no_points; i++) {
        fprintf (fptr, "%f %f\n", xaxis[i], yaxis[i]);   
    }
    fclose(fptr);
}


