#include <sys/ioctl.h>
#include <portos/soundcard.h>
#include <portos/monitor.h>

int SoundCtrl ( int fd, int code, int value ) {
	return ioctl(fd, code, &value);
}

int openMicro(){
	int result= open("/dev/audio/mic",0);
	if (result != -1) {
	      /* Set 8000Hz mono sampling */
	      SoundCtrl(result, SNDCTL_DSP_STEREO, 0);
	      SoundCtrl(result, SNDCTL_DSP_SPEED, 8000);
	}
	return result;
}

void copyMicro( int indes, int outdes) {
	char buffer[0x1000];
	int  command;

	int mypid = getpid();                      /* boost priority */
	int oldPrio = moniGetprio(mypid);
	moniSetprio(mypid,oldPrio+0x100);

	/* Read microphone until we receive a (suspend) command */

	while ( ioctl(0,FIONREAD, &command)!=-1 && command == 0) {
	      int amount = read(indes, &buffer, sizeof(buffer));
	      write (outdes, &buffer, amount);
	}
	moniSetprio(mypid,oldPrio);             /* unboost */
}


int main( int argc, char **argv) {
	char command;
	int microphone;

	while(1) {
		command='q';
		read(0,&command,1);
		switch(command) {

		  case 'r':     /* Record */
		  case 'R':
			microphone = openMicro();
			if (microphone<0) return 1;
			copyMicro(microphone,1);
			close(microphone);
			break;

		  case 's':     /* Suspend */
		  case 'S':
			/* no action required */
			break;

		  case 'q':
		  case 'Q':
		  default:     /* Quit, broken pipe */
			return(1);
		}
	}
}
