/*
*
* This is the DMA RX interrupt handler function
*
* It gets the interrupt status from the hardware, acknowledges it, and if any
* error happens, it resets the hardware. Otherwise, if a completion interrupt
* presents, then it calls the callback function.
*
* @param	Callback is a pointer to RX channel of the DMA engine.
*
* @return	None.
*
* @note		None.
*
******************************************************************************/
static void RxIntrHandler(void *Callback)
{
	XAxiDma *AxiDmaPtr = (XAxiDma *) Callback;

	XAxiDma_BdRing *RxRingPtr = XAxiDma_GetRxIndexRing(AxiDmaPtr, 0);

	u32 IrqStatus;
	int TimeOut;


	/* Read pending interrupts */
	IrqStatus = XAxiDma_BdRingGetIrq(RxRingPtr);

	/* Acknowledge pending interrupts */
	XAxiDma_BdRingAckIrq(RxRingPtr, IrqStatus);

	/*
	 * If no interrupt is asserted, we do not do anything
	 */
	if (!(IrqStatus & XAXIDMA_IRQ_ALL_MASK)) {
		return;
	}

	/*
	 * If error interrupt is asserted, raise error flag, reset the
	 * hardware to recover from the error, and return with no further
	 * processing.
	 */
	if ((IrqStatus & XAXIDMA_IRQ_ERROR_MASK)) {

		Error = 1;

		/* Reset could fail and hang
		 * NEED a way to handle this or do not call it??
		 */
		XAxiDma_Reset(&AxiDma);

		TimeOut = RESET_TIMEOUT_COUNTER;

		while (TimeOut) {
			if(XAxiDma_ResetIsDone(&AxiDma)) {
				break;
			}

			TimeOut -= 1;
		}

		return;
	}

	/*
	 * If completion interrupt is asserted, call RX call back function
	 * to handle the processed BDs and then raise the according flag.
	 */
	if ((IrqStatus & (XAXIDMA_IRQ_DELAY_MASK | XAXIDMA_IRQ_IOC_MASK))) {
		RxCallBack(AxiDmaPtr);
	}
}
/*
*
* This is the DMA TX Interrupt handler function.
*
* It gets the interrupt status from the hardware, acknowledges it, and if any
* error happens, it resets the hardware. Otherwise, if a completion interrupt
* is present, then sets the TxDone.flag
*
* @param	Callback is a pointer to TX channel of the DMA engine.
*
* @return	None.
*
* @note		None.
*
******************************************************************************/
static void TxIntrHandler(void *Callback)
{

	u32 IrqStatus;
	int TimeOut;
	XAxiDma *AxiDmaInst = (XAxiDma *)Callback;

	/* Read pending interrupts */
	IrqStatus = XAxiDma_IntrGetIrq(AxiDmaInst, XAXIDMA_DMA_TO_DEVICE);

	/* Acknowledge pending interrupts */


	XAxiDma_IntrAckIrq(AxiDmaInst, IrqStatus, XAXIDMA_DMA_TO_DEVICE);

	/*
	 * If no interrupt is asserted, we do not do anything
	 */
	if (!(IrqStatus & XAXIDMA_IRQ_ALL_MASK)) {

		return;
	}

	/*
	 * If error interrupt is asserted, raise error flag, reset the
	 * hardware to recover from the error, and return with no further
	 * processing.
	 */
	if ((IrqStatus & XAXIDMA_IRQ_ERROR_MASK)) {

		Error = 1;

		/*
		 * Reset should never fail for transmit channel
		 */
		XAxiDma_Reset(AxiDmaInst);

		TimeOut = RESET_TIMEOUT_COUNTER;

		while (TimeOut) {
			if (XAxiDma_ResetIsDone(AxiDmaInst)) {
				break;
			}

			TimeOut -= 1;
		}

		return;
	}

	/*
	 * If Completion interrupt is asserted, then set the TxDone flag
	 */
	if ((IrqStatus & XAXIDMA_IRQ_IOC_MASK)) {

		TxDone = 1;
	}
}
/*
*
* This is the DMA TX Interrupt handler function.
*
* It gets the interrupt status from the hardware, acknowledges it, and if any
* error happens, it resets the hardware. Otherwise, if a completion interrupt
* presents, then it calls the callback function.
*
* @param	Callback is a pointer to TX channel of the DMA engine.
*
* @return	None.
*
* @note		None.
*
******************************************************************************/
static void TxIntrHandler(void *Callback)
{
	XAxiDma_BdRing *TxRingPtr = (XAxiDma_BdRing *) Callback;
	u32 IrqStatus;
	int TimeOut;

	/* Read pending interrupts */
	IrqStatus = XAxiDma_BdRingGetIrq(TxRingPtr);

	/* Acknowledge pending interrupts */
	XAxiDma_BdRingAckIrq(TxRingPtr, IrqStatus);

	/* If no interrupt is asserted, we do not do anything
	 */
	if (!(IrqStatus & XAXIDMA_IRQ_ALL_MASK)) {

		return;
	}

	/*
	 * If error interrupt is asserted, raise error flag, reset the
	 * hardware to recover from the error, and return with no further
	 * processing.
	 */
	if ((IrqStatus & XAXIDMA_IRQ_ERROR_MASK)) {

		XAxiDma_BdRingDumpRegs(TxRingPtr);

		Error = 1;

		/*
		 * Reset should never fail for transmit channel
		 */
		XAxiDma_Reset(&AxiDma);

		TimeOut = RESET_TIMEOUT_COUNTER;

		while (TimeOut) {
			if (XAxiDma_ResetIsDone(&AxiDma)) {
				break;
			}

			TimeOut -= 1;
		}

		return;
	}

	/*
	 * If Transmit done interrupt is asserted, call TX call back function
	 * to handle the processed BDs and raise the according flag
	 */
	if ((IrqStatus & (XAXIDMA_IRQ_DELAY_MASK | XAXIDMA_IRQ_IOC_MASK))) {
		TxCallBack(TxRingPtr);
	}
}
int main()
{

    static XIntc intc;

    Xil_ICacheEnable();
    Xil_DCacheEnable();

    xil_printf("Testing UART output.\r\n");

    // Camera DMA Configuration
    XAxiDma_Config *dmaconf = XAxiDma_LookupConfig(XPAR_AXI_DMA_0_DEVICE_ID);
    XAxiDma dma;
    XAxiDma_CfgInitialize(&dma, dmaconf);
    XAxiDma_Resume(&dma);
    XAxiDma_Reset(&dma);
    while(!XAxiDma_ResetIsDone(&dma));

    // Initialize Video
    InitVideo();

    // Example camera DMA read
    // Note - transfer MUST be 4096B
    // Data format is 20-bit pixel number (stored in a 32 bit integer) followed by 16-bit RGB values
    // This will not work until you implement camera_stream.v.
    // (or at least, until you have it barely working)
    //int resdde = XAxiDma_SimpleTransfer(&dma, (u32)((unsigned char*)&camera), 4096, XAXIDMA_DEVICE_TO_DMA);
    //while(XAxiDma_Busy(&dma,XAXIDMA_DEVICE_TO_DMA));


    int Status;
    XEmacLite *EmacLiteInstPtr = &EmacLiteInstance;
    u32 PhyAddress = 0;
    RecvFrameLength = 0;
    XEmacLite_Config *ConfigPtr;

    /*
     * Initialize the EmacLite device.
     */
    ConfigPtr = XEmacLite_LookupConfig(XPAR_ETHERNET_LITE_DEVICE_ID);
    if (ConfigPtr == NULL) {
        return XST_FAILURE;
    }
    Status = XEmacLite_CfgInitialize(EmacLiteInstPtr,
                    ConfigPtr,
                    ConfigPtr->BaseAddress);
    if (Status != XST_SUCCESS) {
        return XST_FAILURE;
    }

    /*
     * Set the MAC address.
     */
    XEmacLite_SetMacAddress(EmacLiteInstPtr, LocalAddress);

    /*
     * Empty any existing receive frames.
     */
    XEmacLite_FlushReceive(EmacLiteInstPtr);

    /*
     * Check if there is a TX buffer available, if there isn't it is an
     * error.
     */
    if (XEmacLite_TxBufferAvailable(EmacLiteInstPtr) != TRUE) {
        return XST_FAILURE;
    }

    /*
     * Reset the receive frame length to zero.
     */
    RecvFrameLength = 0;

    // Example program that sends packets and changes the color of an on-screen box upon receiving a packet.
    unsigned char c = 0;
    unsigned char r=0xFF, g=0x0, b=0x0;

    while(1) {
        c++;
        if(XEmacLite_IsTxDone(ConfigPtr->BaseAddress)) {
            Status = EmacLiteSendFrame(EmacLiteInstPtr, EMACLITE_TEST_FRAME_SIZE);
            if (Status != XST_SUCCESS) {
                if (XEmacLite_IsMdioConfigured(EmacLiteInstPtr)) {
                    return XST_FAILURE;
                }
            }
        }
        else {
            RecvFrameLength = XEmacLite_Recv(EmacLiteInstPtr, (u8 *)RxFrame);
            if (RecvFrameLength > 0) {
            	xil_printf("Received a packet!\r\n");
                unsigned char oldr = r;
                r=g;
                g=b;
                b=oldr;
            }
            // Example of writing data to the screen
            int x, y;
            for (x = 0; x < 20; x++)
                for (y = 0; y < 20; y++)
                    if (t[y*20 + x]) {
                        fptr[y*640*4 + x*4] = b;
                        fptr[y*640*4 + x*4 + 1] = g;
                        fptr[y*640*4 + x*4 + 2] = r;
                    }
        }
    }

    Xil_DCacheDisable();
    Xil_ICacheDisable();

    return 0;
}