#include "archinc.h"
#include "eventq.h"
#include "zarlink.h"
#include "zl_event.h"

#include "uip/uip.h"
#include "uip/uip_arp.h"

#define BUF ((struct uip_eth_hdr *)&uip_buf[0])

#ifdef CONFIG_INCLUDE_ZARLINK

#include <stdio.h>
#include <stdlib.h>

static void handleFrameRxEvent(void);

static void handleFrameRxEvent(void)
{
  uip_len = zarlinkEthFrameRead();

    if(uip_len > 0) {
      /* A packet is present in the packet buffer. We call the
	 appropriate ARP functions depending on what kind of packet we
	 have received. If the packet is an IP packet, we should call
	 uip_input() as well. */
      if(BUF->type == htons(UIP_ETHTYPE_IP)) {
	uip_arp_ipin();
	uip_input();
	/* If the above function invocation resulted in data that
	   should be sent out on the network, the global variable
	   uip_len is set to a value > 0. */
	if(uip_len > 0) {
	  uip_arp_out();
	  zarlinkEthFrameWrite();
	}
      } else if(BUF->type == htons(UIP_ETHTYPE_ARP)) {
	uip_arp_arpin();
	/* If the above function invocation resulted in data that
	   should be sent out on the network, the global variable
	   uip_len is set to a value > 0. */	
	if(uip_len > 0) {	
	  zarlinkEthFrameWrite();
	}
      }
    }

  zarlinkEventUnmaskIrq(INT_CPU_FRAME);
}

int zarlinkRxFrameInit(void)
{
  eventqRegisterHandler(SWITCH_FRAME_RX, handleFrameRxEvent);
  return 0;
}

#endif

