#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/soundcard.h>
#include <math.h>


#define TEST_CHANNELS 6
char DEVICE[50];

#define PI2 (3.14159265358*2)

static float incr = PI2 * 440 / 48000;

short
get_sample ()
{
  static float phase = 0;
  static int s_out = 0;
  short dta;
  short limit;

  phase += incr;
  s_out++;

  if (s_out > 1024)
    {
      //incr+=((rand()&32767)-16384)*(0.001/32767);     
      s_out = 0;
    }

  while (phase >= PI2)
    phase -= PI2;

  dta = (short) ((sin (phase) + 0.000000001) * 16384);

  limit = ((rand () & 1023) + 16384 - 1023);
  if (dta > limit)
    dta = limit;
  else if (dta < -limit)
    dta = -limit;
  return dta;
}

int samples_out = 0;
int pulses = 0;

short
get_analognoise ()
{
  return (rand () & 127) + (rand () & 127) + (rand () & 127) +
    (rand () & 127) + (rand () & 127) + (rand () & 127) + (rand () & 127) +
    (rand () & 127);

}

short
get_pulse ()
{
  samples_out++;
  if (samples_out > 26000)
    {
      pulses++;
      samples_out = 0;
    }

  if (samples_out > 10000)
    return get_sample () + get_analognoise ();
  else
    return get_analognoise ();
}

int
main (int argc, char **argv)
{
  short dta[1024];
  int t, channels, arg, fd, k;
  FILE *fdz;
  int i=0, j;

//  for (i = 0; i < 48; i++)
    {
      sprintf (DEVICE, "/dev/dsp_multich");
      printf ("testing %s\n", DEVICE);
      fdz = fopen (DEVICE, "wb");
      if (!fdz)
	{
	  printf ("Unable to open device\n");
	  return -1;
	}

      fd = fileno (fdz);

      arg = 0x0002000F;
      if (ioctl (fd, SNDCTL_DSP_SETFRAGMENT, &arg) == -1)
	perror ("SNDCTL_DSP_SETFRAGMENT");


      arg = AFMT_S16_LE;
      if (ioctl (fd, SNDCTL_DSP_SETFMT, &arg) == -1)
	perror ("SNDCTL_DSP_SETFMT");
      fprintf (stderr, "Format %s\n", (arg == 16) ? "stereo" : "mono");

      arg = TEST_CHANNELS;
      if (ioctl (fd, SNDCTL_DSP_CHANNELS, &arg) == -1)
	perror ("SNDCTL_DSP_CHANNELS");
      if (arg == 1)
	arg = 2;
      if (ioctl (fd, SNDCTL_DSP_CHANNELS, &arg) == -1)
	perror ("SNDCTL_DSP_CHANNELS");
      channels = arg;

      fprintf (stderr, "Channels %d\n", arg);

      arg = 48000;
      if (ioctl (fd, SNDCTL_DSP_SPEED, &arg) == -1)
	perror ("SNDCTL_DSP_SPEED");


      j = 0;
      while (j < 2)
	{
	  for (t = 0; t < channels; t++)
	    {
	      printf ("playing chan = %d\n", t + 1);
	      samples_out = 0;
	      pulses = 0;
	      while (pulses != (t + 1))
		{
		  for (k = 0; k < channels; k++)
		    {
		      if (k == t)
			dta[k] = get_pulse ();
		      else
			dta[k] = 0;

		    }
		  fwrite (dta, 2, channels, fdz);
		}
	    }
	  j++;
	}
      fclose (fdz);
    }
  return 0;
}
