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

/********************************************************/
/***	    COS 496     Assignment #2                 ***/
/***   posed by Perry Cook   this solution by PRC     ***/
/***   writes sound out so you can hear the pendulum  ***/
/********************************************************/
#define DELTA_T 0.01
#define THETA_INITIAL 0.1
#define EXACT 1

/********************************************************/
/*****			 Main			    *****/
/********************************************************/

/********  NeXT Soundfile Header Struct   *******/
struct headerform {
    char pref[4];
    long hdr_length;
    long file_length;
    long mode;
    long samp_rate;
    long num_channels;
    char comment[1024];
};

void main(int argc, char *argv[]) {
    int i, j, k;
    double mass, length, theta, d_theta, d_d_theta, constant;
    double last_theta, freq, max_theta, max_d_theta;
    FILE *soundFile;
    short soundOut;
    struct headerform hdr = {".snd",28,0,3,22050,1,"HI"};

    soundFile = fopen("temp.snd", "wb");    
    fwrite(&hdr,4,7,soundFile);

	length = 0.8;
	constant = - 9.8 / length;

	    theta = THETA_INITIAL;
	    
	    freq = 0.0;
	    max_theta = 0.0;
	    max_d_theta = 0.0;
	    
	    printf("l=%f, th=%f, freq=", length,  theta);

	    d_theta = 0;
	    d_d_theta = 0;
	    
	    for (k=0;k < (int) (1000.0 / DELTA_T);k++)   {

		if (EXACT)	
		    d_d_theta = constant * sin(theta);
		else
		    d_d_theta = constant * theta;
		
		d_theta = d_theta + (DELTA_T * d_d_theta);
		last_theta = theta;
		theta = theta + (DELTA_T * d_theta);
		
		if ((last_theta * theta) < 0.0) freq += 1;
		if (theta > max_theta) max_theta = theta;
		if (d_theta > max_d_theta) max_d_theta = d_theta;

		soundOut = (short) (theta * 15000.0 / THETA_INITIAL);
		fwrite(&soundOut, 2, 1, soundFile);
		
	    }

	    freq = freq * DELTA_T / 1000 / 2;

	    printf("freq=%f, max_theta=%f, max_vel=%f\n", freq, max_theta, max_d_theta); 
	
      fclose(soundFile);
   exit(0);
}