/*********************************************************
*
* Module Name: UDP Echo server 
*
* File Name:    UDPEchoServer.c	
*
* Summary:
*  This file contains the echo server code
*  The server loops forever, receives a message and echoe's it back to the client.
*
* Parameters:
*    port :   the port to use.  Port 7 is used by default.
*    debugFlag: contains two pieces of information.
*               -To log samples in an output file
*               -The debugLevel which controls how much info is displayed
*
*               To log samples, set the 8th bit of the debugFlag. E.g., 128.
*               The debugLevel is set by anding the debugFlag with 0x7f                
*       
*               By default, this is 129 which sets debugLevel to 1 and creates samples file.
* 
*    0:  serious error messages only
*    1:  adds start msg and final results  and warnings
*    2:  shows iteration results
*    3:  debug information
*
*    Example:  Value 129 sets debugLevel to 1 and creates samples file
*
* Revisions:
*  $A0 : 2-20-2017 Version 1.2 
*  $A1 : 9/7/2017  Version 1.3
*  $A2 : 928/2017  V 1.4 - added CBR mode
*
*********************************************************/
#include "UDPEcho.h"
#include "sessionManager.h"

void CNTCCode();
void CatchAlarm(int ignored);
void exitProcessing(double curTime);

int sock = -1;                         /* Socket descriptor */
int bStop = 1;;
FILE *newFile = NULL;
double startTime = 0.0;

//remove
unsigned int largestSeqRecv = 0;
unsigned int receivedCount = 0;

unsigned int numberRTTSamples = 0;
unsigned int numberOfSocketsUsed = 0;
unsigned int numberOutOfOrder=0;

long avgPing = 0.0; /* final mean */
long totalPing = 0.0;

double curRTT = 0.0;
double sumOfCurRTT = 0.0;
double meanCurRTT = 0.0; /* final mean */
double smoothedRTT = 0.0;

unsigned int debugLevel = 1;
unsigned int createDataFileFlag = 0;
unsigned int errorCount = 0;  /* each loop iteration, any/all errors increment */

unsigned int debugFlagMask =  0x00000080;

void myUsage(char *myName, int paramCount, char *myVersion)
{
  printf("Usage(V%s,%d): %s [port] [debugFlag] \n", myVersion,paramCount,myName);
}



int main(int argc, char *argv[])
{
    struct sockaddr_in echoServAddr; /* Local address */
    struct sockaddr_in echoClntAddr; /* Client address */
    unsigned int cliAddrLen;         /* Length of incoming message */

    char echoBuffer[ECHOMAX];        /* Buffer for echo string */
    unsigned short echoServPort;     /* Server port */
    int recvMsgSize;                 /* Size of received message */
    char dataFile[] = "EchoServer.dat";
    unsigned int debugFlag = 129;
    unsigned int loopCount = 0;
    unsigned int errorCount = 0;


    unsigned int RxSeqNumber = 0;
    int *RxSeqNumberPtr = (int *)echoBuffer;
//$A2
    unsigned short RxMode = 0;
    unsigned short *RxModePtr = (unsigned short *)&echoBuffer[4];
    session *mySession = NULL;

    int rc = 0;
    double curTime = 0.0;

    bStop = 0;
    startTime = timestamp();
    curTime = startTime;

    if (argc < 2)         /* Test for correct number of parameters */
    {
      myUsage(argv[0],argc, Version);
      exit(1);
    }

    signal (SIGINT, CNTCCode);

    echoServPort = atoi(argv[1]);  /* First arg:  local port */

    if (argc == 3) {        /* see if debug level set ... */
      debugFlag = atoi(argv[2]);
      debugLevel = (debugFlag & 0x0000007f); 
    }

    if (debugFlag && debugFlagMask)
      createDataFileFlag = 1;
    else 
      createDataFileFlag = 0;

    if (debugLevel > 0) {
      printf("UDPEchoServer(#args:%d): port:%d  debugLevel:%d debugFlag:%d createFlag:%d \n",
          argc,echoServPort, debugLevel, debugFlag, createDataFileFlag);
    }

    if (createDataFileFlag == 1 ) {
      newFile = fopen(dataFile, "w");
      if ((newFile ) == NULL) {
        printf("UDPEchoClient(%s): HARD ERROR failed fopen of file %s,  errno:%d \n", 
             argv[0],dataFile,errno);
        exit(1);
      }
    }

    /* Create socket for sending/receiving datagrams */
    if ((sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0){
      errorCount++;
      printf("UDPEchoServer(%f): HARD ERROR : Failure on socket call errorCount:%d  errno:%d \n", 
              curTime,errorCount,  errno);
      exit(1);
    }

    /* Construct local address structure */
    memset(&echoServAddr, 0, sizeof(echoServAddr));   /* Zero out structure */
    echoServAddr.sin_family = AF_INET;                /* Internet address family */
    echoServAddr.sin_addr.s_addr = htonl(INADDR_ANY); /* Any incoming interface */
    echoServAddr.sin_port = htons(echoServPort);      /* Local port */

    rc = bind(sock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr));
    /* Bind to the local address */
    if (rc < 0) {
      errorCount++;
      printf("UDPEchoServer(%f): HARD ERROR : bind to port %d error, errorCount:%d  errno:%d \n", 
           curTime,echoServPort,errorCount,  errno);
      exit(1);
    }
  
    while ( bStop != 1) 
    {
      loopCount++;
      curTime = timestamp();
      /* Set the size of the in-out parameter */
      cliAddrLen = sizeof(echoClntAddr);

      /* Block until receive message from a client */
      recvMsgSize = recvfrom(sock, echoBuffer, ECHOMAX, 0, (struct sockaddr *) &echoClntAddr, &cliAddrLen);
      if (recvMsgSize < 0)
      {
        errorCount++;
        printf("UDPEchoServer(%f)(%d) HARD ERROR : error recvfrom  errorCount%d  errno:%d \n", 
              curTime,loopCount, errorCount,  errno);
        if (createDataFileFlag == 1 ) {
            fprintf(newFile,"UDPEchoServer(%f)(%d) HARD ERROR : error recvfrom  errorCount%d  errno:%d \n", 
              curTime,loopCount, errorCount,  errno);
        }
        continue;
      }
      //Check if Session already exists
      mySession = findSession(echoClntAddr.sin_addr, echoClntAddr.sin_port);

      if(mySession == NULL) // If not added already, create a session
      {
        mySession = createSession(echoClntAddr.sin_addr, echoClntAddr.sin_port);
      }


      //Tracks total number received from any client
      receivedCount++;

      RxSeqNumber = (unsigned int)ntohl( (unsigned int)(*RxSeqNumberPtr) );
      //two cases, arrival is a 'new' segment  
      if (mySession->largestSeqNumRxed  < RxSeqNumber)
        mySession->largestSeqNumRxed = RxSeqNumber;

      //the arrival is an 'old' segment 
      if (mySession->largestSeqNumRxed >= RxSeqNumber)
        mySession->outOfOrderArrivals++;


      mySession->lastSeqNumRxed = RxSeqNumber;

      RxMode = (unsigned short )ntohs( (unsigned short )(*RxModePtr));
      mySession->mode = RxMode;

      //Update session info 
      gettimeofday(&(mySession->lastRxTime), NULL);
      mySession->messagesReceived++;
      mySession->bytesReceived += recvMsgSize;

      mySession->messagesLost = mySession->largestSeqNumRxed - mySession->messagesReceived;


      if (debugLevel > 2) {
        printf("UDPEchoServer(%f):(%d,%d),rxed %d bytes, RxSeqNumber:%d Rxmode:%d errorCount:%d #sessions:%d \n",
            curTime,loopCount,receivedCount, recvMsgSize, RxSeqNumber, RxMode,errorCount, getNumberSessions());
        displaySession(mySession,FALSE);
      }


      /* Send received datagram back to the client */
      rc = sendto(sock, echoBuffer, recvMsgSize, 0,  (struct sockaddr *) &echoClntAddr, sizeof(echoClntAddr));

      if ( rc != recvMsgSize) 
      {
          errorCount++;
          printf("UDPEchoServer(%f):(%d) HARD ERROR : error sending %d bytes to client %s, errorCount%d, rc:%d  errno:%d \n", 
              curTime,loopCount,recvMsgSize, inet_ntoa(echoClntAddr.sin_addr), errorCount, rc,  errno);
          if (createDataFileFlag == 1 ) {
            fprintf(newFile,"UDPEchoServer(%f):(%d) HARD ERROR : error sending %d bytes to client %s, errorCount%d  rc:%d, errno:%d \n", 
              curTime,loopCount,recvMsgSize, inet_ntoa(echoClntAddr.sin_addr), errorCount, rc,  errno);
          }
          continue;
      }

      if (debugLevel > 1) {
        printf("UDPEchoServer(%f):(%d,%d), ECHOED  %d bytes, SeqNumber:%d sessionLargestSeqNumber/total:%d %d  RxMode:%d errorCount:%d #sessions:%d \n",
            curTime,loopCount,receivedCount,recvMsgSize, RxSeqNumber, mySession->largestSeqNumRxed, mySession->messagesReceived, RxMode, errorCount, getNumberSessions());
      }
      if (createDataFileFlag == 1 ) {
        fprintf(newFile,"%f %d %d %d %d %d %d %d\n",
               curTime,RxSeqNumber,recvMsgSize, RxMode, mySession->largestSeqNumRxed, mySession->messagesReceived,errorCount, getNumberSessions());
      }
    }
    //If we get here, we are supposed to end....
    printf("UDPEchoServer:(%f)(%d,%d) WARNING:  Ending Loop  \n", curTime,loopCount,receivedCount);
    //exitProcessing(curTime);
    exit(0);
}


void CNTCCode() {

  bStop = 1;
  exitProcessing(timestamp());
  exit(0);
}


void exitProcessing(double curTime) 
{

  double endTime = 0.0;
  double  duration = 0.0;

  endTime = curTime;
  duration = endTime - startTime;
  if (sock != -1) 
    close(sock);
  sock = -1;

  if (debugLevel >0) {
    printf("UDPEcho2Server: %f  receivedCount:%d, numberSessions:%d  \n",
       duration, receivedCount, getNumberSessions());
  }

  displayAllSessions(FALSE);

  if (newFile != NULL) {
    fflush(newFile);
    fclose(newFile);
  }
}





