/* sndsine writes a sound file containing a sine wave */
/* cc -O -DLINUX io.o headers.o audio.o lispcall.o sound.o -o sndsine sndsine.c -lm */
/* sndsine test.snd */

#if defined(HAVE_CONFIG_H)
  #include "config.h"
#endif

#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#if (defined(NEXT) || (defined(HAVE_LIBC_H) && (!defined(HAVE_UNISTD_H))))
  #include <libc.h>
#else
  #include <unistd.h>
  #include <string.h>
#endif
#include <errno.h>

#include "sndlib.h"

#if MACOS
  #include <console.h>
#endif

#define BUFFER_SIZE 4096

int main(int argc, char *argv[])
{
  int fd,i,k,frames;
  float phase,incr;
  int *obuf[1];
#if MACOS
  argc = ccommand(&argv);
#endif
  if (argc == 1) {printf("usage: sndsine outfile\n"); exit(0);}
  initialize_sndlib();
  fd = open_sound_output(argv[1],22050,1,snd_16_linear,NeXT_sound_file,"created by sndsine");
  if (fd != -1)
    {
      frames = 22050;
      phase = 0.0;
      incr = 2*PI*440.0/22050.0;
      obuf[0] = (int *)CALLOC(BUFFER_SIZE,sizeof(int));
      k=0;
      for (i=0;i<frames;i++)
	{
	  obuf[0][k] = (int)(3276.8 * sin(phase)); /* amp = .1 */
	  phase += incr;
	  k++;
	  if (k == BUFFER_SIZE)
	    {
	      write_sound(fd,0,BUFFER_SIZE-1,1,obuf);
	      k=0;
	    }
	}
      if (k>0) write_sound(fd,0,k-1,1,obuf);
      close_sound_output(fd,22050*c_snd_datum_size(snd_16_linear));
      FREE(obuf[0]);
    }
  return(0);
}
