#include <io.h>
#include <system.h>
#include <stdio.h>
//write data
#define IOWR_DATA(base, offset, data) \
		IOWR_16DIRECT(base, (offset) * 2, data)
//read data
#define IORD_DATA(base, offset) \
		IORD_16DIRECT(base, (offset) * 2)

#define RD_SYNC 0
#define RD_start 1
#define WR_start 2
#define WR_readselects 3
#define RD_leftclick 0
#define RD_rightclick 1
#define RD_dx 2
#define RD_dy 3


int main()
{
	alt_u8 blank = 0;

	//bottom right corner of pixel dump
	alt_u16 xcoordinate = 0;
	alt_u16 ycoordinate = 0;


	alt_8 deltaX;
	alt_8 deltaY;

	IOWR_DATA(VGA_BASE, WR_readselects, 1);

	for(;;){

		//while(!blank){
			//read from address 0 for vsync/blank status
			blank = IORD_DATA(VGA_BASE, RD_SYNC);
			//read from address 1 for x position of sample
			deltaX = IORD_DATA(GPIO_BASE, RD_dx);
			//read from address 2 for y position of sample
			deltaY = IORD_DATA(GPIO_BASE, RD_dy);




		//}
		//reset
		if(IORD_DATA(GPIO_BASE, RD_rightclick)==0){
			xcoordinate = 0;
			ycoordinate = 0;
			continue;
		}else if(IORD_DATA(GPIO_BASE, RD_leftclick)==0){


			alt_32 xcoordinate_temp=xcoordinate-deltaX;
			alt_32 ycoordinate_temp=ycoordinate+deltaY;
			printf("%d\n",ycoordinate_temp);
			//Boundary conditions
			if(xcoordinate_temp<0 || ycoordinate_temp<0 || xcoordinate_temp>240 || ycoordinate_temp>240){
				continue;
			}else{
				xcoordinate-=deltaX;
				ycoordinate+=deltaY;
				//xcoordinate_temp=xcoordinate;
				//ycoordinate_temp=ycoordinate;
			}
			alt_u16 start_RAM = ycoordinate-1*xcoordinate*256;
			//write back new position
			IOWR_DATA(GPIO_BASE, WR_start, 550);

			//printf("%d\n",ycoordinate-1*xcoordinate*256);
		}
	}
}
