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


/*
Command Line format:
sender <filename> <packetsize>

*/


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

#include "udpfile.h"


FILE *infile; //Input file. 

u_int32_t packetSize;
u_int32_t fileSize=0;
u_int32_t ind=0;
u_int32_t dataSize;

int main (int argc,char *argv[])
{
	if (argc!=3)
	{
		printf("Error: Format of this command should be: sender <filename> <packetsize>\n");
		return 1;
	}
	packetSize=atoi(argv[2]);
	if (packetSize<=HEADER_SIZE)
	{
		printf("Error: The packet size is too small for encoding. This program requires at least %d bytes for packet size\n",HEADER_SIZE+1);
		return 1;
	}
	dataSize=packetSize-HEADER_SIZE;
	
	printf("Working on file %s with packet size %d, data size: %d\n",argv[1],packetSize,dataSize);
	
	//read the source file
	infile=fopen(argv[1],"r");
	if (infile==NULL)
	{
		printf("Erorr when reading file!\n");
		return 1;
	}


	//Calculate the size of the file in packet	
	int byte_count=0;
	//number of bytes in the current packet, if byte_count>=dataSize, we need one more packet
	while (!feof(infile))
	{
		char a;
		fscanf(infile,"%c",&a);
		byte_count++;
		if (byte_count>=dataSize)
		{
			//create one packet
			fileSize++;
			byte_count=0;
		}
	}
	fclose(infile);

	//consider the leftover as one packet
	if (byte_count>0) fileSize++;

	

	//split the file into packet
	infile=fopen(argv[1],"r");

	u_int32_t ind=0;
	//ind is the index of the current packet. 

	while (!feof(infile))
	{ 
		ind++;
		Packet* p=new Packet(infile, packetSize);	//create a packet from file
		p->set_total_length(fileSize);
		p->getHeaderPtr()->seq=ind;			//assign a seq #
		p->send_to_file('P');				//output the packet to filesystem
		delete p;
	};
	fclose(infile);
};


