#include <sys/stat.h>
#include <string.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <fcntl.h>
#include <math.h>

#define SAMPLE_RATE 44100
#define TIME 1 //seconds
#define SAMPLE_SIZE 32 // 32 bits float
#define PI 3.141592653

int main(int argc, char ** argv){

   char filename[10];
   strcpy(filename, "output.wav");

   FILE *fp = fopen(filename,"wb+");

   fwrite("RIFF", 1, 4, fp);
   int size = SAMPLE_RATE * TIME * SAMPLE_SIZE / 8; // 44100 * 10 seconds * 4 bytes per sample
   fwrite(&size, 1, sizeof(size), fp);
   fwrite("WAVE", 1, 4, fp);

   fwrite("fmt ", 1, 4, fp);
   int flag = 16; // chunk size
   fwrite(&flag, 1, 4, fp);
   flag = 0x0003; // compression code
   fwrite(&flag, 1, 2, fp);
   flag = 1; // number of channels
   fwrite(&flag, 1, 2, fp);
   flag = SAMPLE_RATE; // sample rate
   fwrite(&flag, 1, 4, fp);
   flag = SAMPLE_RATE * SAMPLE_SIZE / 8; // bytes per second
   fwrite(&flag, 1, 4, fp);
   flag = SAMPLE_SIZE / 8; // block align
   fwrite(&flag, 1, 2, fp);
   flag = SAMPLE_SIZE; // significant bits per sample
   fwrite(&flag, 1, 2, fp);

   fwrite("data", 1, 4, fp);
   fwrite(&size, 1, 4, fp);

   float buffer[SAMPLE_RATE * TIME];
   float freq = 440.0f;
   float step = 2.0f * PI / ((float)SAMPLE_RATE / freq);
   printf("Step: %f\n", step);

   int i = 0;
   for(i = 0 ; i < SAMPLE_RATE * TIME; i++){
	buffer[i] = sin((float)i * step);
   }

   fwrite(buffer, 1, size, fp);
   fclose(fp);

}
