#include "menu.h"
#include "main.h"
#include "pad.h"
#include "ed_host_int.h"
#include "ed_pad_int.h"
#include "ed_slave_int.h"

#include "PSoCAPI.h"    // PSoC API definitions for all User Modules

signed char menu(const char *menuname1, const char **menu, 
				 signed char selected)
{
	unsigned char i;
	unsigned char menuitems;
	unsigned char b;
		
	menuitems=0;
	while (menu[menuitems][0]!=0)
		menuitems++;
			
	pad_LcdClear();
		
	redraw:
	
	pad_LcdPrintC(0x00, 0x08, 'D', menuname1);

	for (i=0;i<menuitems;i+=2)
		{
		if (i==selected)
			pad_LcdPrintC(0x04, 24+i*4, 'b', menu[i]);
		else
			pad_LcdPrintC(0x04, 24+i*4, 'B', menu[i]);
		
		if (i+1==menuitems)
			break;
		
		if (i+1==selected)
			pad_LcdPrintC(0x40, 24+i*4, 'b', menu[i+1]);
		else
			pad_LcdPrintC(0x40, 24+i*4, 'B', menu[i+1]);
		}
	
	while(1)
		{
		b=pad_gets();
	
		if ((b&PAD_MOVEMASK)==PAD_UP && selected>1) //up
			{
			selected-=2;
			if (selected<0)
				selected=menuitems-1;
			goto redraw;
			}
		if ((b&PAD_MOVEMASK)==PAD_DOWN && selected<(menuitems-2)) //down
			{
			selected+=2;
			if (selected>(menuitems-1))
				selected=0;
				
			goto redraw;
			}
		
		if ((b&PAD_MOVEMASK)==PAD_LEFT && (selected&1)==1) //left
			{
			selected-=1;
			if (selected<0)
				selected=menuitems-1;
			goto redraw;	
			}

		if ((b&PAD_MOVEMASK)==PAD_RIGHT && (selected&1)==0) //right
			{
			selected+=1;
			if (selected>(menuitems-1))
				selected=0;
			goto redraw;	
			}
			
		if (b&(PAD_STICK|PAD_MENU))
			{
			return selected;
			}
		if (b&(PAD_STOP))
			{
			return -1;
			}
		}
	return 0;
}

