/************************************************************/
/*                                                          */
/*  The header file of packet definition                    */
/*  For CS 145 (Fall 2003) Lab 2                            */
/*  Author: Xiaoliang (David) Wei                           */
/*  Date:   Nov 07, 2002                                    */
/*                                                          */
/************************************************************/


#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/time.h>
#include <unistd.h>

/*
Packet Format:
0-3 Bytes: Length of the packet (in bytes)
4-7 Bytes: Sequence Number (per packet)
8-11 Bytes: file (in packet)
12- Bytes: Data
*/
typedef struct header
{
	u_int32_t len;
	u_int32_t seq;
	u_int32_t tt_seq;
};

#define packet_header(x) (struct header *)x
//Translate "a pointer to a packet" to "a pointer to the header of a packet".

#define HEADER_SIZE (sizeof (struct header))

#define S 15000 //maximum packet size

class Packet 
{
	public:
	int size;
//the size of the packet (including header), when size==0, the packet is invalid.

	char buf[S+1];
//the buffer to store this packet
	
	public:
	Packet();			//Create an empty packet, possibly for pure ack
	Packet(FILE* pktfile);
	//The packet is stored in the file. read the packet from the file.

	Packet(char* newbuf, int len); 
	//parse the buf and translate into packet format
	//len: number of bytes to be copied from the buffer. This should be equal to the packet size
	Packet(FILE* infile, int maxlen); 
	//read from file and create the packet
	//maxlen: maximum packet size of the system
	
	struct header * getHeaderPtr() {return (struct header*)buf;}
				//return the header of the packet
	char* getDataPtr() {char* tmp=buf; tmp+=HEADER_SIZE; return tmp;};
	int getDataLen() {return getHeaderPtr()->len-HEADER_SIZE;}
	int isValid() {return size>0; } 
	void print(); //print the packet
	void output(FILE* outfile); //save the packet to a file
	void send_to_file(char prefix); //send a packet to the "network" simulated by a file
	
	void set_total_length(u_int32_t tt_seq)	{getHeaderPtr()->tt_seq=tt_seq;}
	// set the length of the file (in packet) in the header.
private:
	void parse(int len); //parse a packet
};



