#include "socket.h"
#include <avr/io.h>
#include <util/delay.h>
#include <stdio.h>
#include "var.h"
#include "serial.h"


void send_packet(uint8_t p){
    /* for each byte in the packet, send the appropriate character
     * sequence
     */
    
   switch(p) {
      /* if it's the same code as an END character, we send a
       * special two character code so as not to make the
       * receiver think we sent an END
       */
      case END:
          send_serial(ESC);
          send_serial(ESC_END);
          break;

          /* if it's the same code as an ESC character,
           * we send a special two character code so as not
           * to make the receiver think we sent an ESC
           */
          case ESC:
          send_serial(ESC);
          send_serial(ESC_ESC);
          break;
          /* otherwise, we just send the character
           */
          default:
          send_serial(p);
      }
}

// GET SLIP
int receive_packet()
{
   /* RECV_PACKET: receives a packet into the buffer located at "p".
    *      If more than len bytes are received, the packet will
    *      be truncated.
    *      Returns the number of bytes stored in the buffer.
    */
   uint8_t c;
   /* sit in a loop reading bytes until we put together
    * a whole packet.
    * Make sure not to copy them into the packet if we
    * run out of room.
    */
		while(1)
		{
           // get a character to process
           c = get_serial();

           // handle bytestuffing if necessary
           switch(c) {

           /* if it's an END character then we're done with
            * the packet
            */
           case END:

                   return -1;

           /* if it's the same code as an ESC character, wait
            * and get another character and then figure out
            * what to store in the packet based on that.
            */
           case ESC:
                   c = get_serial();

                   /* if "c" is not one of these two, then we
                    * have a protocol violation.  The best bet
                    * seems to be to leave the byte alone and
                    * just stuff it into the packet
                    */
                   switch(c) {
                   case ESC_END:
                           c = END;
                           return c;
                   case ESC_ESC:
                           c = ESC;
                           return c;
                   }
			default:
					return c;
                           
                   
           }
		}
}

void stock_packet(uint8_t * tab_rec, int len){
	  int c=0x00;

		int i=0;
		get_serial();
		do
		{
			c = receive_packet();
			if(c!=-1)
				tab_rec[i] = c;
			i++;
		}
		while(c !=-1 && i<len);
}