//#include <unistd.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/soundcard.h>
#include <sys/time.h>

#include"libmodplug/modplug.h"

ModPlugFile *daMod;
void *tb;
int audio_fd, mixer_fd;
#define	AUDIO_BUFFER_SIZE	8192

int My_open_audio()
{
	if ((audio_fd=open("/dev/dsp", O_WRONLY, 0))==-1)//O_RDWR
	{
		if ((audio_fd=open("/dev/audio", O_WRONLY, 0))==-1)//O_RDWR
		{
			perror("/dev/audio | /dev/dsp");
			return 1;
		}
	}
	// reset DSP
	ioctl(audio_fd, SNDCTL_DSP_RESET, 0);
	//set DSP format
	int daFormat = AFMT_S16_NE;
	if( ioctl(audio_fd, SNDCTL_DSP_SETFMT, &daFormat))
	{
		perror("SNDCTL_DSP_SETFMT");
		return 1;
	}
	if( daFormat != AFMT_S16_NE )
	{
		printf("bad audio format\n");
		return 1;
	}
	int daChann = 2;
	if( ioctl( audio_fd, SNDCTL_DSP_CHANNELS, &daChann) == -1 )
	{
		perror("SNDCTL_DSP_CHANNELS");
		return 1;
	}
	if( daChann != 2)
	{
		printf("can't play in stereo :(\n");
		return 1;
	}
	int daSpeed = 44100;
	if(ioctl(audio_fd, SNDCTL_DSP_SPEED, &daSpeed) == -1 )
	{
		perror("SNDCTL_DSP_SPEED");
		return 1;
	}
	if( daSpeed != 44100 )
	{
		printf("can't play at 44100 Hz :(\n");
		return 1;
	}
//	------------ MIXER ------------
/*
	if ((mixer_fd=open("/dev/mixer", O_WRONLY, 0))==-1)//O_RDWR
	{
		if ((mixer_fd=open("/dev/mixer0", O_WRONLY, 0))==-1)//O_RDWR
		{
			if ((mixer_fd=open("/dev/mixer1", O_WRONLY, 0))==-1)//O_RDWR
			{
				perror("/dev/dsp");
				printf("no mixer on this system :(\n");
			}
		}
	}
	int vol = 10;
	if(ioctl(mixer_fd, SOUND_MIXER_WRITE_OGAIN, &vol) == -1)
	{
		printf("could not set volume...\n");
	}

	close(mixer_fd);
*/
 	return 0;
}

void My_close_audio()
{
	close(audio_fd);
}

void My_childThread()
{
  if(  !My_open_audio() )
  {
	while(ModPlug_Read(daMod, tb, AUDIO_BUFFER_SIZE) )
	{
		write(audio_fd, tb, AUDIO_BUFFER_SIZE);
	}
	My_close_audio();
  }
  else printf("Can't init sound :(\n");
}

void My_init_sound(void *soundBuff, int soundFileSize)
{
  ModPlug_Settings Sett;
  daMod = ModPlug_Load( soundBuff, soundFileSize );

  tb = (void*) new char[AUDIO_BUFFER_SIZE];
  ModPlug_GetSettings(&Sett);
  Sett.mFlags = MODPLUG_ENABLE_NOISE_REDUCTION | MODPLUG_ENABLE_OVERSAMPLING;
  Sett.mResamplingMode = MODPLUG_RESAMPLE_LINEAR;
  ModPlug_SetSettings(&Sett);
}

void My_release_sound()
{
  ModPlug_Unload(daMod);
}
