#include "dspspy.h"
//#include <SDL.h>

void main() {
	
	FILE *mic;
	FILE *thr;
	char data[2];
	int val;
	int thresh;
	void *bufp;
	bufp=data;
	
	if (!(mic=fopen("/dev/dsp","rb"))) {
		cout << "Something is Wrong ....."<< endl;
		cout << "Error Could not open Sound device /dev/dsp" <<endl;
		exit(0);
	}
	
	cout << "_____MICTUNE 1.1.0 for dspspy_____" <<endl;
	cout << endl;
	cout << "    Coded by Richard Svensson" <<endl;
	cout << "      this software is GPL" <<endl;
	cout << "__________________________________"<<endl;
	cout << endl;
	cout << "This will calibrate the threshold for the" <<endl;
	cout << "curent microphone level."<<endl;
	cout << "Please be as quiet as you can. But make sure" <<endl;
	cout << "the microphone is ON."<<endl;
	cout << "Please wait.." <<endl;
		
	data=" ";
	fread(bufp,1,1,mic);	
	val =abs((int)data[0]);	
	thresh=val;
		
		
	for (int i=0;i<=50000;i++) {
		data=" ";
		fread(bufp,1,1,mic);	
		val =abs((int)data[0]);	
		if (val<thresh) {
			thresh=val;
			cout << "Threshold lowred to " <<thresh<<endl;
		}
	}
	fclose(mic);
	
	cout << "Calibration complete" <<endl;
	cout << "Threshold is " <<thresh<<endl;
	
	if (!(thr=fopen("dspspy.thr","w"))) {
		cout << "Something is Wrong ....."<< endl;
		cout << "Error could not open dspspy.tr" <<endl;
		cout << "Make sure that dspspy is not running" <<endl;
		exit(0);
	}
	bufp=&thresh;
	fwrite(bufp,1,1,thr);
	fclose(thr);
}