#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <linux/signal.h>

int child=0;
pid_t pid;
int goon;
int waiting;

void sig_term(int n)
{
	goon=0;
	waiting=1;
        signal(SIGUSR1,sig_term);
}

int main(int argc, char* argv[])
{
  int device;
  FILE* dev_dsp;
  FILE* sound;
    int what[2];

  if (!fork()) {  /* Son process */  
    pid=getppid();
    if ((device=open("/dev/beep",O_RDONLY))<0) {
      fprintf(stderr,"Could not open device /dev/beep\n");
      signal(pid,SIGKILL);
      exit(1);
    }
    what[0]=1;
    while(what[0]!=((('!'*256+'f')*256+'f')*256+'o')) {
      read(device,(char*)what,8);
      kill(pid,SIGUSR1);
    }
    kill(pid,SIGKILL);
  }
  else { /* Father process */
    signal(SIGUSR1,sig_term);
    waiting=0;
    while(1) { 
      if (!waiting) {
        wait(NULL);
      }
      waiting=0;
      if (!(dev_dsp=fopen("/dev/audio","w"))) {
        fprintf(stderr,"Could not open device /dev/audio\n");
        continue;
      }

      sound=fopen(argv[1],"r");
      if (!sound) {
        fprintf(stderr,"Could not open sound file %s\n",argv[1]);
        fclose(dev_dsp);
	continue;
      }
      goon=1;
      while (goon && (!feof(sound))) {
        putc(getc(sound),dev_dsp);
      }
      fclose(dev_dsp);
      fclose(sound);
    }
  }
}