/**********************************************************
 * tcp - upd echo client program 
 *
 * This program is the client side of a udp/tcp echo program.
 *   For TCP, the program sends a CHUNKSIZE and then  
 *     attempts to receive the chunk.
*    For both UDP and TCP, a new socket is created EVERY iteration.
 *
 * Invocation:
 *   ./client blade33.cs.clemson.edu 5000 3 100000 1 0
 *    server:
 *    port:
 *    iteration delay
 *    message size
 *    protocol:  0:UDP,   1:TCP
 *    iterations:  0 infinite, ...
 *
 * Notes:
 *  -modify the Makefile to add -DDEBUG option or uncomment below
 *
 * Revisions
 *
 **************************************************************/
#include "echo.h"
#include "math.h"
static int Sent;
static int Lost;
static double Avg;
static double Thruput;

//uncomment this to turn on printf's
//#define DEBUG 0 
//#define XDEBUG 0 

void signal_handler();
double getTime();
void createAddress( struct sockaddr_in *addr, char* name, char* port);
int createSocket(int protocol);
void print_stats();
void doTCP(int sock,char *sendbuf,char *recvbuf, unsigned int len, struct sockaddr_in *destAddr);
   
int main(int argc, char *argv[])
{
    int sock;                        /* Socket descriptor */
    struct sockaddr_in echoServAddr; /* Echo server address */
    struct sockaddr_in fromAddr;     /* Source address of echo */
    unsigned int fromSize;           /* In-out of address size for recvfrom() */
    int iters;
    
    int bufferLen;
    int delay,protocol;
    int *seqPtr;
    char *buffer;
    char *recvbuffer;
    struct sigaction sig;
    struct hostent *thehost;
    
    if (argc < 6)    /* Test for correct number of arguments */
    {
        fprintf(stderr,"Usage: %s server port delay size protocol iterations\n", argv[0]);
        fprintf(stderr,"  delay : the iteration delay\n");
        fprintf(stderr,"  size:  the amount of data sent each iteration \n");
        fprintf(stderr,"  protocol : 0 is UDP,  1 is tcp \n");
        fprintf(stderr,"  iterations : if not specified, iterations will be forever\n");
        exit(1);
    }
	
    /* setup signals */
    memset(&sig,0,sizeof(sig));
    sig.sa_handler = signal_handler;
    sigaction (SIGINT,  &sig, NULL);
    sigaction (SIGALRM, &sig, NULL);
	
    bufferLen = atoi(argv[4]);
    delay = atoi(argv[3]);
    protocol = atoi(argv[5]);
    if (argc > 6) 
      iters = atoi(argv[6]);  
    else 
      iters = 0; 
    /* Construct the server address structure */
    memset (&echoServAddr, 0, sizeof (echoServAddr));
    echoServAddr.sin_family = AF_INET;
    echoServAddr.sin_addr.s_addr = inet_addr (argv[1]);
  
    /* If user gave a name ip, we need to resolve it  */
    if (echoServAddr.sin_addr.s_addr == -1) {
        thehost = gethostbyname (argv[1]);
        echoServAddr.sin_addr.s_addr =
            *((unsigned long *) thehost->h_addr_list[0]);
    }

    echoServAddr.sin_port = htons (atoi(argv[2]));

    /* setup buffer and stats */
    buffer = (char*)malloc(bufferLen);
    recvbuffer = (char*)malloc(bufferLen);
    if(buffer == NULL || recvbuffer == NULL) 
      DieWithError("Message Size too Large");

    seqPtr = (int *)buffer;
	*seqPtr = 0;
    Sent = Lost = Avg = 0;	
    Thruput = 0;

    while (1) {
#ifdef DEBUG
        printf("Parent: Start with protocol of %d \n",protocol);
#endif
        sock = createSocket(protocol);
        int dropped=0; 
        int *recvPtr = (int *)recvbuffer;
        double time = getTime();
		 
        *seqPtr = (htonl(++Sent));

        if(protocol == 0) {

#ifdef DEBUG
            printf("Parent: send message of size %d \n",bufferLen);
#endif
            if (sendto(sock,buffer, bufferLen, 0, (struct sockaddr *)
                   &echoServAddr, sizeof(echoServAddr)) != bufferLen)
                    DieWithError("sendto() diff bytes expected");

            fromSize = sizeof(fromAddr);
            alarm(UDP_TIMEOUT);
            if (recvfrom(sock, recvbuffer, bufferLen, 0,
                         (struct sockaddr *) &fromAddr,&fromSize) < 0) {
                if(errno == EINTR)
                    dropped = 1;
                else
                    DieWithError("recvfrom() failed");
            }
        
        } else {
            doTCP(sock,buffer, recvbuffer,bufferLen,&echoServAddr);
        }
        
        if(!dropped) {
            time = getTime() - time;	
            Avg = (((Sent - Lost - 1)*Avg) + time)/(Sent - Lost);
            if(ntohl((int)*seqPtr) != ntohl((int)*recvPtr))
                printf("recvPtr mismatch");
            printf("%s ", protocol ? "tcp":"udp");
            Thruput = (bufferLen * 8) / time;
            printf("echo: %3i, time(ms): %.2f,  thruput(bps):%d\n",
                   ntohl((int)*seqPtr),time*1000, (int)Thruput);
        } else {
            Lost++;
        }
        alarm(0);
        close(sock);
        sleep(delay);
        if(iters)
            if(iters == (Sent + Lost)) 
                print_stats();
	}
    exit(0);
}

void signal_handler(int sig) {
	switch(sig) {
		case SIGINT:
			print_stats();
            break;
		case SIGALRM:
			break;
	}
}

void print_stats() {
    printf("\nSENT: %d LOST: %d LOSS RATE: %.2f AVG: %.2fms\n",
       Sent,Lost,(((double)Lost)/((double)Sent))*100,Avg*1000);
    exit(0);
}
double getTime()
{
	struct timeval curTime;
	(void) gettimeofday (&curTime, (struct timezone *) NULL);
	return (((((double) curTime.tv_sec) * 1000000.0) 
             + (double) curTime.tv_usec) / 1000000.0); 
}

  
int createSocket(int protocol) {
    int sockfd;
    if (protocol == 0) {
#ifdef DEBUG
     printf("Socket: Create UDP socket \n");
#endif
      sockfd = socket(PF_INET,SOCK_DGRAM,IPPROTO_UDP);
    }
    else
      sockfd = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);

    if (sockfd < 0)
        DieWithError("socket() failed");

    return sockfd;
}

void createAddress( struct sockaddr_in *addr, char* name, char* port) {
    
    memset(addr, 0, sizeof(*addr));   
    addr->sin_family = AF_INET;               
    addr->sin_addr.s_addr = inet_addr(name);
	
    if (addr->sin_addr.s_addr == -1)
	{
        struct hostent *thehost = gethostbyname(name);
        addr->sin_addr.s_addr = *((unsigned long *) thehost->h_addr_list[0]);
    }

   addr->sin_port = htons(atoi(port));


} 


void doTCP(int sock, char *sendBuffer, char *rxBuffer, unsigned int len, struct sockaddr_in *destAddr) 
{
    int rc=0;
    int chunkSize = CHUNKSIZE;
    int totalSent = 0;
    int totalBytesRcvd = 0;
    int totalRcvd = 0;
    int bytesRcvd = 0;


#ifdef DEBUG
    printf("doTCP: connecting ... \n");
#endif
    if(connect(sock, (struct sockaddr *)destAddr, sizeof(*destAddr)) < 0) 
            DieWithError("connect() error");
    

#ifdef DEBUG 
    printf("doTCP: connected (len=%d) \n",len);
#endif

    /* Send the string to the server */
    int sendCount = len;
 
    while (sendCount > 0) {
      if (sendCount < chunkSize)
       chunkSize = sendCount;
       int chunkSendCount = chunkSize;
       while (chunkSendCount > 0) {
        rc = send(sock, sendBuffer+totalSent, chunkSize, 0);
        if (rc < 0)
          DieWithError("send() error ....");
        chunkSendCount -= rc;
        totalSent +=rc;
        sendCount = sendCount - rc;
       }
      if (rc < 0)
        DieWithError("send() error ....");
#ifdef XDEBUG
      printf("doTCP: sent %d bytes, totalSent =%d, total sendCount:%d,  totalBytesRcvd:%d, chunkSize:%d \n",
               rc,totalSent,sendCount,totalBytesRcvd,chunkSize);
#endif

      /* Receive the same chunk back from the server */
#ifdef XDEBUG
      printf("Sent data ... now Rx \n");
#endif
      totalBytesRcvd = 0;
      alarm(TCP_TIMEOUT);
      while (totalBytesRcvd < chunkSize)
      {
        if ((bytesRcvd = recv(sock, rxBuffer+totalRcvd, chunkSize, 0)) <= 0)
            DieWithError("recv() failed or connection closed prematurely");
        totalBytesRcvd += bytesRcvd;   /* Keep tally of total bytes for THIS Recv */
        totalRcvd += bytesRcvd;   /* Keep tally of total bytes */
#ifdef XDEBUG
        printf("Rx %d bytes, totalRxed:%d\n",bytesRcvd,totalBytesRcvd);
#endif
      }
      alarm(0);
  }
#ifdef DEBUG
  printf("doTCP: FINISHED: totalSent: %d, totalRxed:%d\n",totalSent,totalRcvd);
#endif
}



