#include "library.h"

#undef HTONS

//#include "tapdev.h"

//static const struct uip_eth_addr ethaddr = {{0x00,0x00,0xe2,0x58,0xb6,0x6b}};  

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

#ifndef NULL
#define NULL (void *)0
#endif 

static unsigned short start, current;

#define RT_CLOCK_SECOND 3

static unsigned short rt_ticks(void)
{
  extern unsigned short ticks;
  return ticks;
}  
   

   
void web(){
  
    u8_t i, arptimer;

    /* Let the tapdev network device driver read an entire IP packet
       into the uip_buf. If it returns > 0, there is a packet in the
       uip_buf buffer. */
  
    set_pos(0x0);
    uip_len = cs8900a_poll();
  
    
    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();
	   //tapdev_send();
	  cs8900a_send();
	}
      } 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) {	
	  //tapdev_send();
	  cs8900a_send();
	} 
      }
    } else {
      /* The poll function returned 0, so no packet was
	 received. Instead we check if there is time that we do the
	 periodic processing. */
      current = rt_ticks();
      
      if((u16_t)(current - start) >= (u16_t)RT_CLOCK_SECOND / 2) {
	start = current;
	for(i = 0; i < UIP_CONNS; i++) {
	  uip_periodic(i);
	  /* 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();
	     //tapdev_send();
	    cs8900a_send();
	  }
	}


#if UIP_UDP
	for(i = 0; i < UIP_UDP_CONNS; i++) {
	  uip_udp_periodic(i);
	  /* 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();
	    //tapdev_send();
	    cs8900a_send();
	    
	  }
	}
#endif /* UIP_UDP */
      
	/* Call the ARP timer function every 10 seconds. */
	if(++arptimer == 20) {	
	  uip_arp_timer();
	  arptimer = 0;
	}
      	
      }    
    }    
  }


