#include "dspspy.h"

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

/*
	if ( SDL_Init(SDL_INIT_VIDEO) < 0 ) {
		fprintf(stderr, "Unable to init SDL: %s\n", SDL_GetError());
	exit(1);
	}
	atexit(SDL_Quit);

   SDL_Surface *screen;
	screen = SDL_SetVideoMode(320, 240, 16, SDL_SWSURFACE);
	if ( screen == NULL ) {
		fprintf(stderr, "Unable to set 320x240 video: %s\n", SDL_GetError());
		exit(1);
	}
*/

	char recfile[9];
   char data[2];
   FILE *mic;
	FILE *rec;
   FILE *thr;
   void *bufp;
	bufp=data;
	int val;
	int x=0;
	int y=0;
 	int r,g,b;
	int recnr=0;
	int thresh=0;
	bool sound;

	if (!(mic=fopen("/dev/dsp","r"))) {
		cout << "Something is Wrong ....."<< endl;
		cout << "Error Could not open Sound device /dev/dsp" <<endl;
		exit(0);
	}
		
	if (!(thr=fopen("dspspy.thr","r"))) {
		cout << "Something is Wrong ....."<< endl;
		cout << "Could not open dspspy.thr" <<endl;
		cout << "Please run mictune first" <<endl;
		exit(0);
	}
	
	data=" ";
	fread(bufp,1,1,thr);	
	thresh =(int)data[0];
	fclose(thr);	
	
	cout << "_______DSPSPY__V 1.1.2_____" <<endl;
	cout << endl;
	cout << " Coded By Richard Svensson"<<endl;
	cout << "   this Software is GPL "<<endl;
	cout << "___________________________"<<endl;
	cout << " Using threshold "<<thresh<<endl;

	for (;;) {
/*		x++;if (x>=320) {
			x=0;
			r=rand()%255;
			g=rand()%255;
			b=rand()%255;
		}*/
      	
		data=" ";
		fread(bufp,1,1,mic);	
		val =(int)data[0];

		y=230-abs(val);
		if (abs(val) <thresh) {
			recnr++;
			cout <<"SOUND detected"<<endl;
			cout <<"Recording Sound to ds" <<recnr <<".rec" <<endl;
			recfile="ds--.rec";
			recfile[2]=((int)(recnr/10))+48;
			recfile[3]=(recnr%10)+48;
			cout <<recfile<<endl;
			if (!(rec=fopen(recfile,"w"))) {
				cout << "Something is Wrong ....."<< endl;
				cout << "Error could not open ds"<<recnr<<".rec" <<endl;
			}				
			sound=true;
			while (sound==true) {
				sound=false;
				for (int i=0;i<=10000;i++) {
					data=" ";
					fread(bufp,1,1,mic);	
					val =(int)data[0];
					fwrite(bufp,1,1,rec);
					if (abs(val)<thresh){ sound=true;};
				}
			}
			cout <<"Stoped recording" <<endl;
			fclose(rec);
		}		
//		DrawPixel(screen,x,y,r,g,b);	
	}
}	