#include <alsa/asoundlib.h>
#include <linux/soundcard.h>
#include <stdio.h>
#include "co.h"

#define RATE 22000
#define CHANNEL 1
	unsigned int pcm; //is that an error code or the device id?
	unsigned int rate = RATE;
	int seconds = 3;
	snd_pcm_t * pcm_handle;
	snd_pcm_hw_params_t * params;
	snd_pcm_uframes_t frames;
snd_rawmidi_t * midiout;
const char * portname = "hw:1,0";
int mode = SND_RAWMIDI_SYNC;

char* device = "/dev/snd/seq";
const unsigned char devnum = 0;
unsigned char packet[4] = {SEQ_MIDIPUTC,0,0,0};
int fd;
void ABegin(){
	fd = open(device,O_WRONLY);
	if (fd < 0) Prnt("OSS ! err",20,10,RED);

	pcm = snd_rawmidi_open(NULL,&midiout,portname,mode);
	//pcm = snd_pcm_open(&pcm_handle, "default",SND_PCM_STREAM_PLAYBACK,0);
	if(pcm < 0) Prnt("BEET err", 0,20,RED);

	/*
	snd_pcm_hw_params_alloca(&params);

	snd_pcm_hw_params_any(pcm_handle, params);

	pcm = snd_pcm_hw_params_set_access(pcm_handle, params, 
				           SND_PCM_ACCESS_MMAP_NONINTERLEAVED);
	if (pcm < 0) Prnt("BEET err2", 0,21,RED);
	pcm = snd_pcm_hw_params_set_format(pcm_handle, params, 
					   SND_PCM_FORMAT_U8);
	if (pcm < 0) Prnt("BEET err3", 0,22,RED);
	pcm = snd_pcm_hw_params_set_rate_near(pcm_handle, params,&rate, 0);
	if (pcm < 0) Prnt("BEET err5", 0,24,RED);

	pcm = snd_pcm_hw_params(pcm_handle, params);
	if (pcm < 0) Prnt("BEET err6", 0,25,RED);

	Prnt(snd_pcm_name(pcm_handle),20,21,CYAN);
	Prnt(snd_pcm_state_name(snd_pcm_state(pcm_handle)),20,22,CYAN);

	snd_pcm_hw_params_get_rate(params,&rate,0);	
	snd_pcm_hw_params_get_period_size(params,&frames,0);
	snd_pcm_hw_params_get_period_time(params,&frames,NULL);
	*/
	

}

void AEnd(){
	close(fd);
	snd_rawmidi_close(midiout);
	//snd_pcm_drain(pcm_handle);
	//snd_pcm_close(pcm_handle);
	Prnt("BEET end", 20,24,CYAN);

}

void Bt(){
	Prnt("BEET ???",20,20,CYAN);

	packet[1] = 0x90;
	write(fd,packet,sizeof(packet));
	packet[1] = 0x60;
	write(fd,packet,sizeof(packet));
	packet[1] = 127;
	write(fd,packet,sizeof(packet));


	char * buff = malloc(frames*2);
	for (int i=0;i<frames;i++){
		if((i/220)%2==1) buff[i] = 0;
		else buff[i] = 128;
	}
	Prnt("generated",20,25,CYAN);
	for (int i=(seconds*1000000)/rate; i>0; i-- ){
	
	char noteon[3] = {0x90,60,100};

	pcm = snd_rawmidi_write(midiout, noteon,3);

	//pcm = snd_pcm_writen(pcm_handle,buff, frames);
	if (pcm != -EPIPE) {
		//snd_pcm_prepare(pcm_handle);
		Prnt("played",0,26,GREEN);
	}
	else{
		Prnt("BEET err7",0,26,RED);
	}

	}
	free(buff);
}


