/* sndrecord records a sound */

#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

#ifdef BEOS
  #define CHANNELS 2
#else
  #define CHANNELS 1
#endif

#ifdef NEXT
  #define BUFFER_SIZE 1024
  #define READS 1
  typedef char indata;
  #define FILE_TYPE NeXT_sound_file
  #define DATA_TYPE snd_8_mulaw
  #define SAMPLING_RATE 8000
#else
  #define BUFFER_SIZE 4096
  #define READS 10
  typedef short indata;
  #ifdef WINDOZE
    #define FILE_TYPE RIFF_sound_file
    #define DATA_TYPE snd_8_unsigned
    #define SAMPLING_RATE 22050
  #else
    #if HAVE_OSS
      #define FILE_TYPE RIFF_sound_file
      #define DATA_TYPE snd_16_linear_little_endian
      #define SAMPLING_RATE 22050
    #else
      #define FILE_TYPE AIFF_sound_file
      #define DATA_TYPE snd_16_linear
      #define SAMPLING_RATE 44100
    #endif
  #endif
#endif

int main(int argc, char *argv[])
{
  int fd,afd,i,err,bytes_per_sample,bytes_per_read;
  float mic_gain[1];
  indata *ibuf;
#if MACOS
  argc = ccommand(&argv);
#endif
  if (argc == 1) {printf("usage: sndrecord outfile\n"); exit(0);}
  afd = -1;
  initialize_sndlib();
  /* make sure the microphone is on */
  mic_gain[0] = 1.0;
  write_audio_state(MICROPHONE_DEVICE,AMP_FIELD,0,mic_gain);
  if (CHANNELS == 2) write_audio_state(MICROPHONE_DEVICE,AMP_FIELD,1,mic_gain);
  /* open the output sound file */
  bytes_per_sample = c_snd_datum_size(DATA_TYPE);
  bytes_per_read = BUFFER_SIZE * bytes_per_sample;
  fd = open_sound_output(argv[1],SAMPLING_RATE,CHANNELS,DATA_TYPE,FILE_TYPE,"created by sndrecord");
  if (fd != -1)
    {
      /* prepare and open the microphone input line */
      ibuf = (indata *)CALLOC(BUFFER_SIZE,sizeof(indata));
      afd = open_audio_input(MICROPHONE_DEVICE,SAMPLING_RATE,CHANNELS,DATA_TYPE,bytes_per_read);
      if (afd != -1)
	{
	  for (i=0;i<READS;i++)
	    {
	      err = read_audio(afd,(char *)ibuf,bytes_per_read);
	      if (err != NO_ERROR) {fprintf(stderr,audio_error_name(audio_error())); break;}
	      write(fd,(char *)ibuf,bytes_per_read);
	    }
	  close_audio(afd);
	}
      else 
	fprintf(stderr,audio_error_name(audio_error()));
      close_sound_output(fd,bytes_per_read * READS);
      FREE(ibuf);
    }
  else
    fprintf(stderr,"%s: %s ",argv[1],strerror(errno));
  return(0);
}
