#include "xparameters.h"	/* EDK generated parameters */
#include "led2_ip.h"
#include <stdio.h>
#include "xbasic_types.h"
#include "xscugic.h"
#include "axi_max11100_adc.h"
//#include "axi_interrupt.h"

#define INTC_DEVICE_ID		XPAR_SCUGIC_SINGLE_DEVICE_ID
#define INTC_DEVICE_INT_ID	91

int SetUpInterruptSystem(XScuGic *XScuGicInstancePtr);

XScuGic InterruptController; /* Instance of the Interrupt Controller */
static XScuGic_Config *GicConfig;/* The configuration parameters of the controller */
void Intr_Handler(void * CallBackRef);

int main(void)
{
	int Status;

	GicConfig = XScuGic_LookupConfig(INTC_DEVICE_ID);
	if (NULL == GicConfig) {
		return XST_FAILURE;
	}

	Status = XScuGic_CfgInitialize(&InterruptController, GicConfig,
						GicConfig->CpuBaseAddress);
	if (Status != XST_SUCCESS) {
		return XST_FAILURE;
	}

	/*
	 * Perform a self-test to ensure that the hardware was built
	 * correctly
	 */
	Status = XScuGic_SelfTest(&InterruptController);
	if (Status != XST_SUCCESS) {
		return XST_FAILURE;
	}

	/*
	 * Setup the Interrupt System
	 */
	Status = SetUpInterruptSystem(&InterruptController);
	if (Status != XST_SUCCESS) {
		return XST_FAILURE;
	}

	/*
	 * Connect a device driver handler that will be called when an
	 * interrupt for the device occurs, the device driver handler performs
	 * the specific interrupt processing for the device
	 */
	Status = XScuGic_Connect(&InterruptController, INTC_DEVICE_INT_ID,
			   (Xil_ExceptionHandler)Intr_Handler,
			   (void *)&InterruptController);
	if (Status != XST_SUCCESS) {
			return XST_FAILURE;
		}

	/*
	 * Enable the interrupt for the device and then cause (simulate) an
	 * interrupt so the handlers will be called
	 */
	//XScuGic_Enable(&InterruptController, INTC_DEVICE_INT_ID);

	/*Status = XScuGic_SoftwareIntr(&InterruptController, INTC_DEVICE_INT_ID, XSCUGIC_SPI_CPU0_MASK);
	if (Status != XST_SUCCESS) {
		return XST_FAILURE;
	}*/

	u32 temp;
	LED2_IP_mWriteReg(XPAR_LED2_IP_0_BASEADDR, 1, 0xAC);
	temp = LED2_IP_mReadReg(XPAR_LED2_IP_0_BASEADDR,1);
	printf("%X",temp);

	u32 r, v;

	while(1)
	AXI_MAX11100_ADC_mWriteReg(XPAR_AXI_MAX11100_ADC_0_BASEADDR,r,v);

	/*LED2_IP_mWriteReg(XPAR_LED2_IP_0_BASEADDR, 0, 0xAB);
	LED2_IP_mWriteReg(XPAR_LED2_IP_0_BASEADDR, 0, 0xAB);
	LED2_IP_mWriteReg(XPAR_LED2_IP_0_BASEADDR, 0, 0xAB);*/

	while(1)
	{
	}

	return 0;
}

int SetUpInterruptSystem(XScuGic *XScuGicInstancePtr)
{

	/*
	 * Connect the interrupt controller interrupt handler to the hardware
	 * interrupt handling logic in the ARM processor.
	 */
	Xil_ExceptionRegisterHandler(XIL_EXCEPTION_ID_INT,
			(Xil_ExceptionHandler) XScuGic_InterruptHandler,
			XScuGicInstancePtr);

	/*
	 * Enable interrupts in the ARM
	 */
	Xil_ExceptionEnable();

	return XST_SUCCESS;
}

void Intr_Handler(void * CallBackRef)
{
	printf("User logic interrupt! \n\r");
}
