#include <ADuCM360.h>
#include <hal/timer.h>
#include <list>

#include <cstdarg>

using namespace std;

list<unsigned int> beep_l;

void buzzer_open(void)
{
	pADI_GP2->GPCON = (pADI_GP2->GPCON & ~GP2CON_CON2_MSK) | GP2CON_CON2_GPIO;

	GP2OCE_OCE2_BBA = false;

	GP2SET_SET2_BBA = true;

	GP2OEN_OEN2_BBA = true;

	GP2PUL_PUL2_BBA = true;
}

int static beep_loop(int argc, char *argv[])
{
	timer t;

	if (!beep_l.empty())
	{
		t.time = beep_l.front();
		beep_l.pop_front();

		t.timer_app.fun = beep_loop;
		t.timer_app.argc = 0;
		t.timer_app.argv = new char*;

		GP2TGL_TGL2_BBA = 0x1;

		update_timer(t);
	}
	else
	{
		t.timer_app.fun = beep_loop;
		t.timer_app.argc = 0;

		delete_timer(t);
		GP2SET_SET2_BBA = 0x1; //stop
	}
}

void _beep(int time, ...)
{
	GP2SET_SET2_BBA = 0x1; //stop

	beep_l.clear();

	timer t;
	t.timer_app.fun = beep_loop;
	t.timer_app.argc = 0;

	delete_timer(t);

	va_list ap;
	va_start(ap, time);

	for (int i = time; i > 0; i = va_arg(ap, int))
	{
		beep_l.push_back(i);
	}

	va_end(ap);

	beep_loop(0, nullptr); //start
}
