/*********************************************************
* Module Name: UDP Echo client source 
*
* File Name:    UDPEchoClient2.c
*
* Summary:
*  This file contains the client portion of a client/server
*         UDP-based performance tool.
*
*  Note:  Any code following FAILURE CHECK
*         can eventually be removed.....
*
*  Note:  Allocates a single large network buffer (called echoBuffer)
*         that is used for sending and receiving
*         The user param for messageSize can range [MESSAGEMIN, MESSAGEMAX]
*         The network buffer size is defined by MAX_DATA_BUFFER 
*         which is large enough to hold at least the max allowed messageSize 
*         plus the size of the largest msg hdr (defined as MAX_MSG_HDR).
*         In other words, the messageSize param is DATA only...it does not
*         include msg hdr bytes.
*
*         The design assumes that all possible modes share at least the
*         first two head fields:   SeqNumber (4 octets) and mode (2 octets)
*         Change $A6 extends this to include msgType (2 octets), 
*         and timeSentSeconds (4 octets) and timeSentUSeconds (4 octets)
*  
* Revisions:
*
* $A0:  2/19/2017  
*         -Version 1.2
*         -iteration delay arguement interpreted as number of microseconds
*         -added debug level param (optional)
*         -reused socket except for when errors occur
*
* $A1:   2/28/17
* $A2 : 9/7/2017  Version 1.3
* $A3 : 9/27/2017 V1.4 - add CBR mode
* $A4 : 11/9/2017 V1.6 - preparing for mode 2 - window mode
* $A5 : 11/26/2017  -  added windowed mode
* $A6 : 12/3/2017  V1.7 interim mode 2 solution  
*          To get to RTT MODE code, search 'RTT MODE CODE', 'CBR MODE CODE',  'WINDOW MODE CODE' 
*          To get to the entry to the RTT.dat file,  search for 'OUT RTT MODE' 'OUT CBR MODE'  'OUT WINDOW MODE'
* $A7:  12/10/2017 - changed all references ECHOMAX to MAX_DATA_BUFFER 
* $A8 : 12/10/2017 - V1.8
*
* TODOS:
*   -change to uint16_t and uint32_t 
*   -finish the monitors
*   -mode 0- verify one way latency. Also very RTT is same with using the in MSG timestamp
*   -mode 0 - change so the server obtains one way latency samples and shows avg session latency at termination
*             Change so the server updates the timestamp on the reply with the time it sends. THe client can
*               then calculate the one way (server to client) and the RTT.
*   -mode 2 with maxW beween two machines with an RTT 50ms, msg size:1000 bytes. Throughput should be: 0.150 Mbps.
*   -mode 2 - check that one msg in flight has a timeout active....             
*   -mode 1- add adaptive delay to overcome the nanosleep inaccuracy
*   -mode 2 - fix setting non zero number of iterations.  Right now, it's not exact as there is an 
*               inner loop that might send a window of packets....
*             For mode 2, redefine it as the desired  number of RTT periods ,  0 is forever.
*   -mode 2 - to add accurate RTO-  compute RTO - something like RTO=2* (avg of last two RTT samples)
*             implement tiemout by using asynch I/O on the recvfrom or using select instead of recvfrom. 
*             Either way allows the timeout to be the precise RTO value
*********************************************************/
#include "UDPEcho.h"

void clientCNTCCode(); //handler for CNT-C signal
void CatchAlarm(int ignored);  //handler for alarm signal
void exitProcessing(double curTime, int reasonCode);



//$A6
int getWindow(unsigned int cwnd, int maxW);
int updateState(double curTime, int opCode, unsigned int RxSeqNumber);
int getStateInfo(double curTime, int opCode);
void initMonitor(double curTime);
int  updateMonitor(double curTime);
int showSlidingWindowState(double curTime);


//For mode 2
//These are the opcodes used in either updateState or getStateInfo
//The results of processing an ACK, decisionMade reflects what was done 
//based on one of these values
#define  NEXT_EXPECTED_ACK_EVENT 1
#define  NEW_ACK_EVENT 2
#define  RECOVERY_ACK_EVENT 3
#define  DUPLICATE_ACK_EVENT 4
#define  UNEXPECTED_ACK_EVENT 5
#define  TIMEOUT_EVENT  6
#define  OLD_ACK_ERROR_EVENT 7
#define  ERROR_EVENT 8
#define  UNKNOWN_DECISION 9

#define  SENT_MSG 10

#define  GET_WINDOW 11 
#define  GET_LEFT_EDGE 12
#define  GET_RIGHT_EDGE 13
#define  GET_SEND_NEXT  14
#define  GET_NUMBER_IN_FLIGHT 15
#define  GET_NUMBER_CAN_SEND 16
#define  GET_RECOVERY_STATE 17


#define  UNKNOWN_OPCODE -1


//To deal with ERROR RECOVERY, we implement a
// state machine.
// Current state maintained  in errorRecoveryState
//
// if errorRecoveryState > 0, loss has occurred and we
// are at some stage of the recovery

//Each define reflects a state (with a few execptions)
#define  NO_ERROR_RECOVERY 0


#define  LOSS_DETECTED  1
#define  ERROR_RECOVERY_STATE 2
#define  ERROR_RECOVERY_COMPLETE 3
#define  ERROR_RECOVERY_UNEXPECTED_STATE 4
#define NULL_SEQ_NUMBER 0

//Misc. global variables
int sock = -1;                         /* Socket descriptor */
int bStop = 1;                         /* 1 to stop main while loop */
FILE *newFile = NULL;
double startTime = 0.0; 
double endTime = 0.0;   //Set at program termination (exit routine)

//Global program params
char *serverIP = NULL;                   /* IP address of server */
unsigned short serverPort;        /* Echo server port */
unsigned int targetSendRate = 0;
unsigned short mode = RTT_MODE;

//amount of actual application data in the msg 
int dataSize = -1;              

//amount of application data PLUS the number octets in the application header.
int messageSize = -1;  

int nIterations = -1;
unsigned int debugFlag = 129;
unsigned int debugLevel = 1;
unsigned int createDataFileFlag = 0;


unsigned int cwnd=1;  //congestion window
unsigned int currentWindow=1;       //latest window as of the last call to getWindow
int maxW = -1;

//only applicable for mode 2
int errorRecoveryState =  NO_ERROR_RECOVERY;
unsigned int recoveryLeftEdge  = NULL_SEQ_NUMBER;
unsigned int recoveryRightEdge = NULL_SEQ_NUMBER;
unsigned int numberOfErrorRecoveries = 0; 

unsigned int numberOfNEWACKs = 0;
unsigned int numberOfRECOVERYACKs = 0;
unsigned int numberOfERRORACKs = 0;
unsigned int numberOfDUPACKs = 0;
unsigned int numberOfOLDACKs  = 0;

//numberOfNEWACKs++;
//numberOfRECOVERYACKs++;
//numberOfERRORACKs++;
//numberOfDUPACKs++;
//numberOfOLDACKs++;

unsigned int sequenceNumberTimed = NULL_SEQ_NUMBER;

//What is this used for ..... and how to deal with it during recoveries ??
unsigned int largestSeqSent = 0; //at sendto, =max(seqNumber,largestSeqSent)

//might not need these...
unsigned int largestAckRxed = 0; //at recvfrom,set if the RxSeqnumber just recved is larger
unsigned int lastSeqNumberSent = 0; //the msg seq number sent most recently - possibly not ack'ed 
unsigned int lastRxSeqNumberRxed = 0; //the last RxSeqNumber received in an ack 


//Related to sliding  window state

unsigned int leftEdge=1;            //lowest seq number not yet ack'ed
                                    //same as lastSeqNumberAcked+1
unsigned int rightEdge=1;          //highest seq number not yet ack'ed
                                   //same as largestSeqSent
unsigned int snd_next=1;            //seq number to send next.  After sending a window,this
                                    //should be rightEdge+1


//Counters to track aggregate count of events 
unsigned int numberOfTimeOuts=0;
unsigned int numberOfTrials=0;  /*counts total  number of attempts */
unsigned int numberOfSocketsUsed = 0;
unsigned int numberLost=0;
long long totalBytesSent =0;	
unsigned int totalSends=0;  // total number of calls to sendto 
unsigned int totalMsgsSent=0;  //that appear to be successful...although might not be ACKEd
unsigned int totalReceivedMsgs = 0;

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



//For the Statistics...

//RTT as a long
long avgPing = 0.0; /* final mean */
long totalPing = 0.0;
unsigned int numberRTTSamples = 0;

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


//Only for mode 2
//For the monitoring  (in seconds)
#define MONITOR_INTERVAL 60 
double firstMonIntervalTime = -1;
double lastMonIntervalTime = -1;
unsigned int numberOfIntervals = 0; //represents number of completed intervals

unsigned int monByteCount = 0;
unsigned int monLossCount = 0;
double  RTTSampleCount = 0.0;
unsigned int numberRTTIntervalSamples = 0; //within an interval, the number of samples

unsigned int numberIntervalSamples = 0; //within an interval, the number of samples
unsigned int lastMonitorThroughputSample=0;
double  lastMonitorLossRateSample=0;
double  lastMonitorRTTSample=0;

unsigned int monitorThroughputSum=0;
double  monitorLossRateSum =0;
double  monitorRTTSum=0;



void myUsage(char *myName, int paramCount, char *myVersion)
{

  printf("Usage: %s V%s): [Server IP] [Server Port] [Message Size (bytes)] [# of iterations] [Debug Flag (default : 129)]   \n",  
         myName,myVersion);
  printf("\t\t[mode 0 ECHO MODE] [iteration delay (usecs)] \n");
  printf("\t\t[mode 1 CBR MODE ] [target send rate (bps)] \n");
  printf("\t\t[mode 2 WINDOW  MODE] [max Window (number packets), 0 implies infinite size] \n");

}


/*************************************************************
*
* Function: Main program for  UDPEcho client
*           
* inputs: 
*  char *  serverIP = IPV4 server name of dotted quad address 
*  unsigned int  serverPort = server's port 
*  unsigned int messageSize = amount of data added to each data msg
*  unsigned int iterations  : number of iterations....0 implies forever
*  unsigned int debugFlag :  
*  unsigned int mode:  RTT (ECHO),  CBR, or WINDOW modes
*             [mode 0] [<Iteration Delay (usecs)>] 
*             [mode 1] [targetSendRate]
*             [mode 2] [Window Mode]
*
*    debugFlag: contains two pieces of information.
*               -The debugLevel which controls how much info is displayed
*               -If the 8th bit of debugFlag parameter set, then
*                    createDataFlag is set true. This creates an output file
*                    that logs samples.
*    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
*
* outputs:  
*
*
*  Summary of the client:
*
*   -INIT: declare and init variables 
*          SETUP buffer and buffer ptrs
*   -SOCKET: create the socket
*   -Main loop -   details depend on modes 0,1,2
*
***************************************************************/
int main(int argc, char *argv[])
{
//INIT
  struct sockaddr_in serverAddress; /* Echo server address */
  struct sockaddr_in clientAddress; /* Source address of echo */ 
  unsigned int clientAddressSize = 0;   /* In-out of address size for recvfrom() */

  char *echoString;                /* Ptr to the send bufer */
  char echoBuffer[MAX_DATA_BUFFER];      /* Buffer for sending and receiving   */
  int echoStringLen = -1;               /* Length of msg to send */
  int recvMsgSize  = -1;               /* Length of received response */
  struct hostent *thehost;	     /* Hostent from gethostbyname() */

  //At least 64 bits 
  long long delay = 1000000;	     /* Iteration delay in microseconds */
  double iterationDelay = 1.0;	     /* Iteration delay in seconds */

  char dataFile[] = "Client.dat";
  double curTime = timestamp();


  //Used to compute the RTT
  struct timeval *theTime1;
  struct timeval *theTime2;
  struct timeval TV1, TV2;
  long usec1, usec2, curPing;

  //Needed for the alarm timer
  struct sigaction myaction;

  //Maintains the next seq number to use
  unsigned int seqNumber = 1;
  unsigned int *SeqNumberPtr = NULL;

  //Holds the seq number of a received message
  unsigned int RxSeqNumber = 0;
  unsigned short   RxMode =  RTT_MODE;
  unsigned short   msgType = DATAMSG;
  unsigned int   sendTimeSeconds = 0;
  unsigned int   sendTimeUSeconds  = 0;
  unsigned short msgSize = 0;
  unsigned short dataSize = 0;
  double   RxMsgSendTime = 0;
  double oneWayLatencySample=0;


  //Used when we pull the RxSequence Number from a received MSG
  //currently, this is pointing to the same loation as SeqNumberPtr
  unsigned int *RxSeqNumberPtr = NULL;
  unsigned short *modePtr = NULL;
  unsigned short *MsgTypePtr = (unsigned short *)&echoBuffer[6];
  unsigned int *TimeSentSecondsPtr = (unsigned int *)&echoBuffer[8];
  unsigned int *TimeSentUSecondsPtr = (unsigned int *)&echoBuffer[12];
  unsigned short *MsgSizePtr = (unsigned short *)&echoBuffer[16];
  unsigned short *dataSizePtr = (unsigned short *)&echoBuffer[18];

  unsigned int allowedToSend = 0; //indicates number of msgs to send
                                //  =  currentWindow - numberinFlight

  //Mode 2, once an ACK arrives, after we call updateState, this is 
  //set to indicate what was done
  int decisionMade = 0;


  int rc  = SUCCESS;  //we attempt to maintain this to SUCCESS or FAILURE as the program runs
  int loopFlag = 1;
  //for testing....can eventually remove
  int tmpA=-1;
  int tmpB=-1;

  theTime1 = &TV1;
  theTime2 = &TV2;

  //Initialize values
  totalPing =0;
  bStop = 0;

  unsigned int debugFlagMask =  0x00000080;

  if ((argc <= 3 || argc > 8))    
  {
    myUsage(argv[0],argc, Version);
    exit(EXIT_FAILURE);
  }

  signal (SIGINT, clientCNTCCode);

  serverIP = argv[1];           /* First arg: server IP address (dotted quad) */
  serverPort = atoi(argv[2]);   /* Second arg: server port */
  //messageSize param is just number of dta octets
  dataSize = atoi(argv[3]);
  messageSize = dataSize + DATAMsgHdrSize;

  if (messageSize > MESSAGEMAX) {
    dataSize = messageSize - MESSAGEMAX-DATAMsgHdrSize;
    messageSize = dataSize + DATAMsgHdrSize;
  }
  nIterations = atoi(argv[4]);
  debugFlag = atoi(argv[5]);
  debugLevel = (debugFlag & 0x0000007f); 
  mode = atoi(argv[6]);
  if (argc == 8) {
    switch(mode) {
      case RTT_MODE:
        //value is in microseconds
        //if 0, then we send with no delay
        delay = atoll(argv[7]);
        if (debugLevel > 1) {
          if (delay == 0)
            printf("UDPEchoClient: WARNING: sending with no delay ????  \n");
        }
                
      break;

      case CBR_MODE:
        targetSendRate = atoi(argv[7]);
        //FAILURE CHECK
        if ((targetSendRate == 0) || (targetSendRate > MAX_SENDING_RATE)){
          printf("UDPEchoClient:(%f) HARD ERROR: targetSendRate: %d and MAX: %d)  \n",
                 curTime, targetSendRate, MAX_SENDING_RATE);
          exit(EXIT_FAILURE);
        }
      break;

      case WINDOW_MODE:
        maxW = atoi(argv[7]);
        //if 0, then assume it's infinit
        //FAILURE CHECK
        if  (maxW < 0) { 
          printf("UDPEchoClient: HARD ERROR :    maxW : %d  \n",maxW);
          exit(EXIT_FAILURE);
        }
      break;

      default:
        printf("UDPEchoClient: HARD ERROR bad mode param %d \n", mode);
        myUsage(argv[0],argc, Version);
        exit(EXIT_FAILURE);
    }
  } else {
    delay = 1000000;
    targetSendRate = 2000000;
    maxW = 100;
  }

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

  if (debugLevel > 0) {
      printf("UDPEchoClient(#args:%d): mode:%d dataSize:%d, messageSize:%d,  debugLevel:%d create data file:%d\n",
          argc,mode, dataSize, messageSize,  debugLevel,createDataFileFlag);
  }

  //For both modes, we can just do this once.  
  //Place the iterationDelay in units of seconds
  if ( mode == RTT_MODE) {
    iterationDelay = ((double)delay)/1000000;/* Iteration delay in seconds */
  } else if ( mode == CBR_MODE) {
    if (targetSendRate > 0) {
      iterationDelay =  (((double)messageSize)*8) / (double)targetSendRate;
    } else {
      printf("UDPEchoClient(%s): HARD ERROR BAD targetSendRate? %d \n", argv[0],targetSendRate);
      exit(EXIT_FAILURE);
    }
  } else if (mode == WINDOW_MODE) {
    //Set to something large....as a safe guard ??
    iterationDelay =  (((double)messageSize)*8) / (double)MAX_SENDING_RATE;
  } else { 
    printf("UDPEchoClient(%s): HARD ERROR BAD MODE ?? %d \n", argv[0],mode);
    exit(EXIT_FAILURE);
  }
 
  if (debugLevel > 1) {
    printf("UDPEchoClient(#args:%d):server:%s, port:%d,  msgSize:%d, iteration:%d, mode(%d):   ",
      argc, serverIP,serverPort, messageSize, nIterations, mode );
    if (mode ==  RTT_MODE)
      printf(" RTT_MODE delay:%d microseconds, iterationDelay:%f \n", (int) delay, iterationDelay);
    if (mode ==  CBR_MODE)
      printf(" CBR_MODE targetRate:%d bps,  iterationDelay:%f \n", targetSendRate, iterationDelay);
    if (mode ==  WINDOW_MODE)
      printf(" WINDOW_MODE maxW:%d messages, iterationDelay:%f \n", maxW, iterationDelay);

  }
  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(EXIT_FAILURE);
    }

    switch(mode) {

      case RTT_MODE:
        fprintf(newFile,"curTime,mode, curRTT, smoothedRTT, RxSeqNumber,  \n");
        fprintf(newFile,"          largestSeqSent, numberOfTimeOuts,numberLost, errorCount\n");
        break;

      case CBR_MODE:
        break;

      case WINDOW_MODE:
#if 0
        fprintf(newFile,"curTime, mode, inet_ntoa(clientAddress.sin_addr),ntohs(clientAddress.sin_port) \n");
        fprintf(newFile,"          RxSeqNumber, decisionMade, curRTT, cwnd, currentWindow,  \n");
        fprintf(newFile,"             largestSeqSent,leftEdge, rightEdge,snd_next, \n");
        fprintf(newFile,"                lastMonitorThroughputSample, lastMonitorLossRateSample, lastMonitorRTTSample \n");
#endif
        fprintf(newFile,"curTime nIter RecoveryState Decision RxSeqNumber, curRTT, cwnd, currentWindow,  \n");
        fprintf(newFile,"          #inFlight #canSend  largestSeqSent,leftEdge, rightEdge,snd_next seqnumberTimed \n");
        break;

      default:
          printf("UDPEchoClient: HARD ERROR bad mode param %d \n", mode);
          myUsage(argv[0],argc, Version);
          exit(EXIT_FAILURE);

      }
  }

  if (debugLevel > 0) {
      printf("UDPEchoClient(%s): IP:port:%s:%d #params:%d  %lld  %f %d %d %d %d %d %d \n", 
        argv[0],  serverIP, serverPort, argc,
        delay, iterationDelay, messageSize, dataSize, nIterations, debugFlag, mode, targetSendRate);
  }

  myaction.sa_handler = CatchAlarm;
  if (sigfillset(&myaction.sa_mask) < 0){
    printf("UDPEchoClient(%s): HARD ERROR sigfillset failed:  errno:%d \n", 
             argv[0],errno);
    exit(EXIT_FAILURE);
  }

  myaction.sa_flags = 0;

  if (sigaction(SIGALRM, &myaction, 0) < 0)  {
    printf("UDPEchoClient(%s): HARD ERROR sigaction failed:  errno:%d \n", 
             argv[0],errno);
    exit(EXIT_FAILURE);
  }



//SETUP POINTERS:  setup  all the pointers that are required ....
// The client uses a single network buffer for both
//  sending and receiving. 

  bzero(echoBuffer,(size_t)sizeof(echoBuffer));
  echoStringLen = messageSize;
  echoString = (char *) echoBuffer;

  //Next lines setup both ptrs to same location since we use a single buffer for send and rx
  //This points so sender can update seqNumber
  SeqNumberPtr = (unsigned int *)echoBuffer;
  //This points to rx buffer so client can obtain the RxSeqNumber 
  RxSeqNumberPtr = (unsigned int *)echoBuffer;

  if (debugLevel > 2) {
    printf("UDPEchoClient: Setup pointers...sizeof echoBuffer:%d, defined size:%d, messageSize:%d \n",
         (int) sizeof(echoBuffer), MAX_DATA_BUFFER, echoStringLen);
  }

//For the sender
  modePtr =  (unsigned short *)&echoString[sizeof(seqNumber)];
//Just need to do this 1 time since we reuse the echoString buffer
  *modePtr =  htons(mode);

  MsgTypePtr = (unsigned short *)&echoBuffer[6];
  *MsgTypePtr = htons(DATAMSG);

  TimeSentSecondsPtr = (unsigned int *)&echoBuffer[8];
  TimeSentUSecondsPtr = (unsigned int *)&echoBuffer[12];

  MsgSizePtr = (unsigned short *)&echoBuffer[16];
  dataSizePtr = (unsigned short *)&echoBuffer[18];

//Note, these values will never change..for mode 0 and 1.
  *MsgSizePtr = htons(messageSize);
  *dataSizePtr = htons(dataSize);
//FOr mode 2,  the above is correct for a Data msg.
//              For an ACK msg, the dataSize set to 0, 
//               and the MsgSize  ACKMsgSize 



  /* Construct the server address structure */
  memset(&serverAddress, 0, sizeof(serverAddress));    /* Zero out structure */
  serverAddress.sin_family = AF_INET;                 /* Internet addr family */
  serverAddress.sin_addr.s_addr = (in_addr_t)inet_addr(serverIP);  /* Server IP address */
    
    /* If user gave a dotted decimal address, we need to resolve it  */
  if (serverAddress.sin_addr.s_addr == -1) {
      thehost = gethostbyname(serverIP);
      serverAddress.sin_addr.s_addr = *((unsigned long *) thehost->h_addr_list[0]);
  }
    
  serverAddress.sin_port   = htons(serverPort);     /* Server port */


//SOCKET
  /* Create a datagram/UDP socket */
  if ((sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
      DieWithError("socket() failed");
  } else 
      numberOfSocketsUsed++;
  
  nIterations--;

  
  //  RTT MODE CODE
  if (mode == RTT_MODE) {

    while ( (loopFlag>0) && (bStop != 1)) 
    {

    if (nIterations > 0) { 
      nIterations--;
      loopFlag = 1;
    } 
    else if (nIterations == 0) 
      loopFlag = 0;
    else 
      loopFlag = 1;

    if (errorCount > ERROR_LIMIT) {
        if (debugLevel > 1) {
          printf("UDPEchoClient:(%f): WARNING :  errorCount %d, hit ERROR_LIMIT \n ",
                 curTime,errorCount);
        }
        errorCount = 0;
        //try to reset things.....
        /* Create a datagram/UDP socket */
        if (sock != -1) 
          close(sock);
        sock = -1;
        if ((sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
          printf("UDPEchoClient:(%f): HARD ERROR errorCount %d, socket reset failed, errno:%d \n ",
                 curTime,errorCount,errno);
          exit(EXIT_FAILURE);
        } else 
          numberOfSocketsUsed++;
    }
    numberOfTrials++;


    if ( seqNumber > largestSeqSent)
         largestSeqSent= seqNumber;

    //update seq number in the msg in network byte order
    *SeqNumberPtr = (unsigned int)htonl(seqNumber++); 
    //$A3
    //update the mode...actually just need to do this once as it never changes 
    //*modePtr =  htons(mode);

    if (debugLevel > 2) {
      printf("UDPEchoClient: iteration:%d, sending seq and mode: %d %d  \n", numberOfTrials, largestSeqSent, mode);
    }

    //
    gettimeofday(theTime1, NULL);
    curTime = convertTimeval(theTime1);
    *TimeSentSecondsPtr = (unsigned int)htonl(theTime1->tv_sec);
    *TimeSentUSecondsPtr = (unsigned int)htonl(theTime1->tv_usec);
    if (startTime  == 0.0 ) 
        startTime = curTime;

      if (debugLevel > 2) {
         printf("UDPEchoClient(%f:%d): Sending seqNum:%d (%d bytes) to the server: %s, next seq#timed:%d \n", 
             curTime,nIterations,seqNumber - 1, echoStringLen,serverIP, outOfOrderArrivals);
      }

      //SEND in RTT_MODE
      totalSends++;  // total number of calls to sendto 
      rc =sendto(sock, echoString, echoStringLen, 0, (struct sockaddr *)&serverAddress, sizeof(serverAddress));
      if (rc < 0) 
      {
          errorCount++;
          printf("UDPEchoClient:(%f) HARD error: send error (tried %d bytes), errorCount:%d, errno:%d \n",
               curTime,echoStringLen,errorCount,errno);
          //force next iteration of loop
          continue; 
      } 
      else 
      {
        if (rc != echoStringLen) {
          printf("UDPEchoClient(%f,%d):RTT_MODE: HARD ERROR sendto: expected:%d, rc:%d \n", 
             curTime,nIterations, echoStringLen, rc);
          exit(EXIT_FAILURE);
        } 
        //Else the send succeeded
        totalMsgsSent++;
        totalBytesSent += (long long)rc;
        if (debugLevel > 2) {
          printf("UDPEchoClient: Sent completed, rc = %d \n",rc);
        }

        clientAddressSize = sizeof(clientAddress);
        alarm(TIMEOUT);    //set the timeout 

        /* Recv a response RTT_MODE , client address/port will be filled in on return */
        recvMsgSize = recvfrom(sock, echoBuffer, MAX_DATA_BUFFER, 0, (struct sockaddr *) &clientAddress, &clientAddressSize);
        alarm(0);            //clear the timeout 

        if (recvMsgSize < 0) 
        {
          //Handle error conditions....errno is the global that is set by the system
          //to reflect the specific error
          if (errno == EINTR) 
          { 
            numberOfTimeOuts++; 
            if (debugLevel > 1) {
              printf("UDPEchoClient:(%f) WARNING :Received Timeout !! #TOs:%d errorCount:%d  \n",
                   curTime,numberOfTimeOuts,errorCount);
            }
            //force next iteration of loop
            continue; 
          } else {
            errorCount++;
            if (debugLevel > 1) {
              printf("UDPEchoClient:(%f) WARNING : Rx error errorCount:%d, errno:%d  \n",
                   curTime,errorCount,errno);
            }
            //force next iteration of loop
            continue; 
          }
        } 
        else 
        {
          if (recvMsgSize != echoStringLen) 
          {
            printf("UDPEchoClient:(%f):  HARD ERROR  Rx'ed (%d) less than expected %d)  errorCount:%d  \n",
                   curTime,recvMsgSize, echoStringLen,errorCount);
            exit(EXIT_FAILURE);
          }
        } 


        //If we get here, either no error or we aren't worried about an error....move forward:
        if (debugLevel > 2) {
          printf("UDPEchoClient:(%f): Received %d bytes from  %s \n", curTime, recvMsgSize, serverIP);
        }


        gettimeofday(theTime2, NULL);
        curTime = convertTimeval(theTime2);
        //gettimeofday(&receivedTime, NULL);
        //curTime = convertTimeval(&receivedTime);
        totalReceivedMsgs++;

      //we know we received a valid echo data frame
      RxSeqNumber = (unsigned int)ntohl( (unsigned int)(*RxSeqNumberPtr) );
      RxMode = (unsigned short )ntohs( (unsigned short )(*modePtr));
      msgType = ntohs(*MsgTypePtr);
      msgSize = ntohs(*MsgSizePtr);
      dataSize = ntohs(*dataSizePtr);
      sendTimeSeconds = ntohl(*TimeSentSecondsPtr);
      sendTimeUSeconds = ntohl(*TimeSentUSecondsPtr);

      RxMsgSendTime =  ((double)sendTimeSeconds + ((double)sendTimeUSeconds / 1000000));
      oneWayLatencySample= curTime - RxMsgSendTime;
 
      if (debugLevel > 2) {
          printf("UDPEchoClient(%f,%d) :Received ACK RxSeqNumber:%d  (RecvMsgSize:%d): msgSize:%d dataSize:%d \n",
              curTime,nIterations, RxSeqNumber, recvMsgSize, msgSize, dataSize);
          printf("UDPEchoClient(%f):DataMsg: RxMsgSendTime:%f,  latency:%3.6f \n",
              curTime, RxMsgSendTime, oneWayLatencySample);
      }



        if (debugLevel > 2) {
          printf("UDPEchoClient: RxSeqNumber: %d , and outOfOrderArrivals:%d, errorCount:%d \n",
              RxSeqNumber,outOfOrderArrivals,errorCount);
        }


        //Three possibilities between actual SeqN and expected: less than, equal, GT
        // Norm is they are equal.  GT is not possible. LT  would be a false 
        if (RxSeqNumber > largestSeqSent) {
            printf("UDPEchoClient2:(%f): HARD ERROR:  RxSeqNumber:%d largestSeqSent:%d  \n",
              curTime,  RxSeqNumber, largestSeqSent);
            exit(EXIT_FAILURE);
        }

        //the arrival is an 'old' ACK
        if (RxSeqNumber< largestSeqSent) {
          outOfOrderArrivals++;
        } 


        //Warning: the following are longs and not doubles....
        usec2 = (theTime2->tv_sec) * 1000000 + (theTime2->tv_usec);
        usec1 = (theTime1->tv_sec) * 1000000 + (theTime1->tv_usec);
        curPing = (usec2 - usec1);
        totalPing += curPing;

        curRTT = ((double)curPing) / 1000000;
        smoothedRTT  = 0.5 * smoothedRTT + 0.5*curRTT;
        sumOfCurRTT += curRTT;
        numberRTTSamples++;

        numberLost = numberOfTrials - numberRTTSamples;


        if (debugLevel > 1) {
          printf("%f %d  %3.9f %3.9f %d %d %d %d %d\n", 
               curTime,mode, curRTT, smoothedRTT, RxSeqNumber, largestSeqSent, numberOfTimeOuts,numberLost, errorCount);
        }
        // OUT RTT MODE
        if (createDataFileFlag == 1 ) {
          fprintf(newFile,"%f %d  %3.9f  %3.9f %d %d %d %d %d\n", 
               curTime,mode, curRTT, smoothedRTT, RxSeqNumber, largestSeqSent, numberOfTimeOuts,numberLost, errorCount);
        }

      }

      //Delay the correct amount of time
      rc = myDelay(iterationDelay);
      if (rc == FAILURE){
        printf("UDPEchoClient2:(%f): HARD ERROR:  myDelay returned an error ??? %d  \n", curTime, rc);
        exit(EXIT_FAILURE);
      }

    }  //end while
  } else if (mode == CBR_MODE) {
    //  CBR MODE CODE

    while ( (loopFlag>0) && (bStop != 1)) 
    {
      if (nIterations > 0) { 
        nIterations--;
        loopFlag = 1;
      } 
      else if (nIterations == 0) 
        loopFlag = 0;
      else 
        loopFlag = 1;

      numberOfTrials++;

      if ( seqNumber > largestSeqSent)
         largestSeqSent= seqNumber;

      //update seq number in the msg in network byte order
      *SeqNumberPtr = (unsigned int)htonl(seqNumber++); 

      gettimeofday(theTime1, NULL);
      curTime = convertTimeval(theTime1);
      *TimeSentSecondsPtr = (unsigned int)htonl(theTime1->tv_sec);
      *TimeSentUSecondsPtr = (unsigned int)htonl(theTime1->tv_usec);
      if (startTime  == 0.0 ) 
        startTime = curTime;

      if (debugLevel > 2) {
        printf("UDPEchoClient(%f:%d):sending seq and mode: %d %d  \n", 
             curTime,numberOfTrials, largestSeqSent, mode);
      }

      totalSends++;  // total number of calls to sendto 
      //SEND in CBR_MODE
      rc =sendto(sock, echoString, echoStringLen, 0, (struct sockaddr *)&serverAddress, sizeof(serverAddress));
      if (rc < 0) 
      {
          errorCount++;
          printf("UDPEchoClient:(%f) HARD error: : send error (tried %d bytes), errno:%d \n",curTime,echoStringLen,errno);
          continue; 
      } 
      else if (rc != echoStringLen) {
        printf("UDPEchoClient(%f,%d):CBR_MODE: HARD ERROR sendto: expected:%d, rc:%d \n", 
             curTime,nIterations, echoStringLen, rc);
        exit(EXIT_FAILURE);
      } 
      //else, all going ok....
      totalBytesSent += (long long)rc;
      totalMsgsSent++;

      rc = myDelay(iterationDelay);
      // OUT CBR MODE
      // TODO:  adapt iterationDelay
      // Add monitor to create CBR.dat 

    }  //end while 


  } else if (mode == WINDOW_MODE) {
    // WINDOW MODE CODE

    //FAILURE CHECK
    if (seqNumber != 1) { 
      printf("UDPEchoClient2:(%f):WINDOW MODE:  HARD ERROR: first seqNum %d not 1 ??", curTime,seqNumber);
      exit(EXIT_FAILURE);
    }

    gettimeofday(theTime1, NULL);
    curTime = convertTimeval(theTime1);
    if (startTime  == 0.0 ) 
        startTime = curTime;


    initMonitor(curTime);  
    while ( (loopFlag>0) && (bStop != 1)) 
    {

      if (nIterations > 0) { 
        nIterations--;
        loopFlag = 1;
      } 
      else if (nIterations == 0) {
        loopFlag = 0;
        break;
      }
      else 
        loopFlag = 1;

      numberOfTrials++;
      if ( seqNumber > largestSeqSent)
         largestSeqSent= seqNumber;

      currentWindow = getStateInfo(curTime,GET_WINDOW);
      allowedToSend = getStateInfo(curTime,GET_NUMBER_CAN_SEND);
      if (debugLevel > 2) {
        printf("UDPEchoClient:WINDOW(%f,%d,%d):about to send %d messages, first seqnumber: %d,currentW:%d  \n", 
               curTime, errorRecoveryState, numberOfTrials,allowedToSend, seqNumber, currentWindow);
      }

      if (allowedToSend == 0) {
        if (debugLevel > 1) {
          printf("UDPEchoClient:WINDOW(%f,%d,%d): WARNING sending:%d, largestSeqSent:%d, currentWindow:%d BUT not allowed to Send \n ", 
           curTime, errorRecoveryState, numberOfTrials,seqNumber, largestSeqSent, currentWindow );
        }
      }
      else   
      {

        if (debugLevel > 2) {
          printf("UDPEchoClient:WINDOW(%f,%d,%d): About to send %d messages, start seqN:%d, cwnd:%d currentW:%d \n",
           curTime, errorRecoveryState, numberOfTrials,allowedToSend, seqNumber, cwnd, currentWindow);
        }
        //testing
        tmpA = allowedToSend;
        tmpB=0;
        while (allowedToSend--) 
        {
          //sends whatever we can based on current sliding window state.
          //Once done, we will then recv more ACKs 
          tmpB++;
          if (seqNumber > largestSeqSent)
            largestSeqSent = seqNumber;

          lastSeqNumberSent =  seqNumber;
      
          *SeqNumberPtr = (unsigned int)htonl(seqNumber++); 

          gettimeofday(theTime1, NULL);
          curTime = convertTimeval(theTime1);
          *TimeSentSecondsPtr = (unsigned int)htonl(theTime1->tv_sec);
          *TimeSentUSecondsPtr = (unsigned int)htonl(theTime1->tv_usec);

          if (debugLevel > 2) {
           printf("UDPEchoClient:WINDOW(%f,%d):Sending:%d, startingseqNumber:%d, RxSeqNumber:%d,  W:%d, allowedToSend:%d, seqnumbeingTimed:%d \n", 
               curTime, numberOfTrials,lastSeqNumberSent, getStateInfo(curTime,GET_SEND_NEXT),
               RxSeqNumber, currentWindow, allowedToSend,sequenceNumberTimed);
          }


          //loop for allowedToSend times, send msgs with seqnumber updated each msg
          //SEND in WINDOW_MODE
          totalSends++;  // total number of calls to sendto 
          rc =sendto(sock, echoString, echoStringLen, 0, (struct sockaddr *)&serverAddress, sizeof(serverAddress));
          if (rc < 0) 
          {
            errorCount++;
            printf("UDPEchoClient:WINDOW(%f) HARD error: : send error (tried %d bytes), errno:%d \n",curTime,echoStringLen,errno);
            //force next iteration of loop
            continue; 
          } 
          else 
          {
            if (rc != echoStringLen) {
              printf("UDPEchoClient(%f,%d):WINDOW_MODE: HARD ERROR sendto: expected:%d, rc:%d \n", 
                curTime,nIterations, echoStringLen, rc);
              exit(EXIT_FAILURE);
            } 
           
            //Else the send succeeded
            totalMsgsSent++;
            totalBytesSent += (long long)rc;
            monByteCount += rc;
            numberIntervalSamples++;  //within an interval, the number of samples
            if (debugLevel > 2) {
              printf("UDPEchoClientWINDOW: Sent %d completed, rc = %d, \n",lastSeqNumberSent,rc);
            }

            clientAddressSize = sizeof(clientAddress);

            //this will update leftEdge, rightEdge, snd_next
            //and note this could be a retransmit!!
            currentWindow = updateState(curTime, SENT_MSG, lastSeqNumberSent);
            //  make sure to id the msg being timed
            //  once we get an ack that ack's this msg, 
            //   that code sets this back to NULL.
            //  This ensures we maintain a single timed transmission
            if (sequenceNumberTimed == NULL_SEQ_NUMBER) { 
              sequenceNumberTimed = lastSeqNumberSent;
              alarm(TIMEOUT);    //set the timeout 
              if (debugLevel > 2) {
                printf("UDPEchoClientWINDOW:(%f) Will SET ALARM this sequenceNumber: %d  \n",curTime,sequenceNumberTimed);
              }
            }

          }
        }
        //FAILURE CHECK
        if (tmpA != tmpB) {
          printf("UDPEchoClient:WINDOW(%f,%d): HARD ERROR  allowedToSend(tmpA):%d, actual(tmpB):%d seqNumber:%d largestSeqSent:%d, currentWindow:%d  \n ", 
           curTime, numberOfTrials, tmpA,tmpB, seqNumber, largestSeqSent, currentWindow );
          exit(EXIT_FAILURE);
        }
      }

      //So we just sent as much data permitted by the window.
      /* Recv a response in WINDOW_MODE, client address/port will be filled in on return */
      recvMsgSize = recvfrom(sock, echoBuffer, MAX_DATA_BUFFER, 0, (struct sockaddr *) &clientAddress, &clientAddressSize);
      //Note....clear the alarm ONLY if this ACK is for the MSG beging timed

      if (recvMsgSize < 0) 
      {
          //Handle error conditions....errno is the global that is set by the system
          //to reflect the specific error
          if (errno == EINTR) 
          { 
            numberOfTimeOuts++; 
            monLossCount++; 
            currentWindow = updateState(curTime, TIMEOUT_EVENT, sequenceNumberTimed);
            if (debugLevel > 1) {
              printf("UDPEchoClient:WINDOW(%f) WARNING :Received Timeout !! #TOs:%d errorCount:%d, currentWindow:%d, seqNumberTimed:%d  \n",
                   curTime,numberOfTimeOuts,errorCount,currentWindow, sequenceNumberTimed); 
            }
            alarm(0);            //clear the timeout 
            continue; 
          } else {
            errorCount++;
            alarm(0);            //clear the timeout 
            if (debugLevel > 0) {
              printf("UDPEchoClient:WINDOW(%f) WARNING : recvFrom:%d,  errorCount:%d, errno:%d  \n",
                   curTime,recvMsgSize, errorCount,errno);
            }
            continue; 
          }
      } else 
      {
        if (recvMsgSize != ACKMsgSize)
        {
            errorCount++;
            if (debugLevel > 1) {
              printf("UDPEchoClient:WINDOW(%f) WARNING : Rx'ed (%d) less than expected %d)  errorCount:%d  \n",
                   curTime,recvMsgSize, ACKMsgSize,errorCount);
            }
            continue; 
        }


          //If we get here, either no error or we aren't worried about an error....move forward:
        //we know we received a valid echo data frame
        RxSeqNumber = (unsigned int)ntohl( (unsigned int)(*RxSeqNumberPtr) );
        RxMode = (unsigned short )ntohs( (unsigned short )(*modePtr));
        msgType = ntohs(*MsgTypePtr);
        msgSize = ntohs(*MsgSizePtr);
        dataSize = ntohs(*dataSizePtr);
        sendTimeSeconds = ntohl(*TimeSentSecondsPtr);
        sendTimeUSeconds = ntohl(*TimeSentUSecondsPtr);

        RxMsgSendTime =  ((double)sendTimeSeconds + ((double)sendTimeUSeconds / 1000000));
        oneWayLatencySample= curTime - RxMsgSendTime;
 
        if (debugLevel > 1) {
          printf("UDPEchoClient(%f,%d) :Received Echo ACK RxSeqNumber:%d  (RecvMsgSize:%d): msgSize:%d dataSize:%d \n",
              curTime,nIterations, RxSeqNumber, recvMsgSize, msgSize, dataSize);
          printf("UDPEchoClient(%f):DataMsg: RxMsgSendTime:%f,  latency:%3.6f \n",
              curTime, RxMsgSendTime, oneWayLatencySample);
        }


        if (debugLevel > 2) {
          printf("UDPEchoClient:WINDOW(%f): Received %d bytes from  %s \n", curTime, recvMsgSize, serverIP);
        }

        gettimeofday(theTime2, NULL);
        curTime = convertTimeval(theTime2);
        totalReceivedMsgs++;

        RxSeqNumber = (unsigned int)ntohl( (unsigned int)(*RxSeqNumberPtr) );
        lastRxSeqNumberRxed = RxSeqNumber;
        if (RxSeqNumber > largestAckRxed) {
           largestAckRxed = RxSeqNumber;
        }
        else {  
          printf("UDPEchoClient2:(%f): HARD ERROR:  RxSeqNumber: %d less than largestAckedRxed:%d,  lastRxSeqNumberRxed:%d \n", 
               curTime, RxSeqNumber, largestAckRxed, lastRxSeqNumberRxed);
            exit(EXIT_FAILURE);
        }

          if (sequenceNumberTimed != NULL_SEQ_NUMBER) { 
            if (RxSeqNumber >  sequenceNumberTimed) {
              alarm(0);
              if (debugLevel > 2) {
                printf("UDPEchoClient:WINDOW(%f): STOP ALARM  RxSeqNumber:%d > sequenceNumberTimed:%d  \n", 
                       curTime, RxSeqNumber,sequenceNumberTimed);
              }
              sequenceNumberTimed = NULL_SEQ_NUMBER;
              //NOTE:  Restart an alarm ?? 
              // what if there are more packets in flight ?
            }
          }
 
          {
          decisionMade = UNKNOWN_DECISION;
          rc  = FAILURE;
          if (debugLevel > 2) {
            printf("UDPEchoClient:WINDOW(%f:%d: %d):BEGIN: RxSeqNumber:%d leftEdge:%d, rightEdge:%d, snd_next:%d (largestS:%d,timed:%d) \n",
             curTime,nIterations,errorRecoveryState,RxSeqNumber,leftEdge,rightEdge,snd_next,largestSeqSent,sequenceNumberTimed);
          }

          //leftEdge = lastSeqNumberSent;
          //The following determines if the RxSeqNumber is NEW ACK , DUP , or other
          //Rules:
          //       snd_next must be = rightEdge+1 before processing the ACK
          // NEW ACK 
          //       if RxSeqNumber is > leftEdge and < rightEdge+1
          // RECOVERY ACK
          //     if (errorRecoverState >0) && 
          //       if RxSeqNumber is > recoveryLeftEdge && <= recoveryRightEdge
          // DUP ACK if RxSeqNumber is == left edge
          // OLD ACK if RxSeqNumber is < leftEdge....just ignore
          // ERROR :  if Rx SeqNumber >= snd_next    
          //            or.... if Rx Seq Number  > rightEdge+1

         
          if ((RxSeqNumber > leftEdge)  && (RxSeqNumber <= (rightEdge+1)))  
          {
            if (debugLevel > 2) {
              printf("UDPEchoClient:WINDOW(%f:%d:%d):  RxSeqNumber:%d leftEdge:%d, rightEdge:%d, snd_next:%d (largestS:%d,timed:%d) \n",
                curTime,nIterations,errorRecoveryState,RxSeqNumber,leftEdge,rightEdge,snd_next,largestSeqSent,sequenceNumberTimed);
            }
            // Normal and good case .... this is a NEW ACK....or a RECOVERY_ACK !!!
            currentWindow= updateState(curTime, NEW_ACK_EVENT, RxSeqNumber);
            if (errorRecoveryState == NO_ERROR_RECOVERY) {
              decisionMade = NEW_ACK_EVENT;
              numberOfNEWACKs++;
            } else {
              decisionMade = RECOVERY_ACK_EVENT;
              numberOfRECOVERYACKs++;
            }
            rc  = SUCCESS;

            if (debugLevel > 2) {
              printf("UDPEchoClient:WINDOW(%f): NEW ACK  Received seqNumber:%d, leftEdge:%d, rightEdge:%d, snd_next:%d (largestS:%d,timed:%d) \n",
                curTime,RxSeqNumber,leftEdge,rightEdge,snd_next,largestSeqSent,sequenceNumberTimed);
            }

          } else if  (RxSeqNumber == leftEdge) {
            //Case of a  dup
            numberOfDUPACKs++;
            currentWindow= updateState(curTime, DUPLICATE_ACK_EVENT, RxSeqNumber);
            decisionMade = DUPLICATE_ACK_EVENT;
            rc  = SUCCESS;
            if (debugLevel > 2) {
              printf("UDPEchoClient:WINDOW(%f): DUP ACK  Received seqNumber:%d, leftEdge:%d, rightEdge:%d, snd_next:%d (largestS:%d,timed:%d) \n",
                curTime,RxSeqNumber,leftEdge,rightEdge,snd_next,largestSeqSent,sequenceNumberTimed);
            }
          } else if (RxSeqNumber < leftEdge) {
            //Old ACK .... probably can happen and we don't care ....
            numberOfOLDACKs++;
            decisionMade =  OLD_ACK_ERROR_EVENT;
            rc  = SUCCESS;
            if (debugLevel > 2) {
              printf("UDPEchoClient:WINDOW(%f): Received seqNumber:%d, leftEdge:%d, rightEdge:%d, snd_next:%d (largestS:%d,timed:%d \n",
                curTime, RxSeqNumber,leftEdge,rightEdge,snd_next,largestSeqSent,sequenceNumberTimed);
            }
          } else if  ( (RxSeqNumber > snd_next) || (RxSeqNumber > (rightEdge+1))) {
            //An error 
            numberOfERRORACKs++;
            decisionMade =  ERROR_EVENT;
            rc  = FAILURE;
            if (debugLevel > 2) {
              printf("UDPEchoClient:WINDOW(%f): ERROR_EVENT:  RxSeqNumber:%d, leftEdge:%d, rightEdge:%d, snd_next:%d (largestS:%d,timed:%d) \n",
                curTime, RxSeqNumber,leftEdge,rightEdge,snd_next,largestSeqSent,sequenceNumberTimed);
            }
          } else {
            rc  = FAILURE;
            printf("UDPEchoClient:WINDOW(%f:%d): ERROR??  Unknown state/decision  RxseqNumber:%d, leftEdge:%d, rightEdge:%d, snd_next:%d (largestS:%d,timed:%d) \n",
                curTime,nIterations, RxSeqNumber,leftEdge,rightEdge,snd_next,largestSeqSent,sequenceNumberTimed);
          }
          if (debugLevel > 2) {
            printf("UDPEchoClient:WINDOW(%f:%d):END:decision:%d, RxSeqNumber:%d leftEdge:%d, rightEdge:%d, snd_next:%d (largestS:%d,timed:%d) \n",
              curTime,nIterations,decisionMade,RxSeqNumber,leftEdge,rightEdge,snd_next,largestSeqSent,sequenceNumberTimed);
          }

          if (rc == FAILURE) {
            printf("UDPEchoClient:WINDOW(%f:%d):FAILURE:decision:%d, RxSeqNumber:%d leftEdge:%d, rightEdge:%d, snd_next:%d (largestS:%d,timed:%d) \n",
              curTime,nIterations,decisionMade,RxSeqNumber,leftEdge,rightEdge,snd_next,largestSeqSent,sequenceNumberTimed);
            exit(EXIT_FAILURE);
          }
          }

          //Warning: the following are longs and not doubles....
          usec2 = (theTime2->tv_sec) * 1000000 + (theTime2->tv_usec);
          usec1 = (theTime1->tv_sec) * 1000000 + (theTime1->tv_usec);
          curPing = (usec2 - usec1);
          totalPing += curPing;

          curRTT = ((double)curPing) / 1000000;
          RTTSampleCount+=curRTT;
          numberRTTIntervalSamples++;

          smoothedRTT  = 0.5 * smoothedRTT + 0.5*curRTT;
          sumOfCurRTT += curRTT;
          numberRTTSamples++;
 
          numberLost = numberOfTrials - numberRTTSamples;

          if (debugLevel > 2) {
            printf("UDPEchoClient2:WINDOW(%f): curRTT:%f, smoothRTT:%f currPing:%ld  RxSeqNumber:%d #TOs:%d #Lost:%d, #Errors:%d \n",
                curTime,curRTT, smoothedRTT, curPing, RxSeqNumber, numberOfTimeOuts,numberLost, errorCount);
          }

          if (debugLevel > 2) {
            printf("UDPEchoClient2:WINDOW(%f):  %d %3.6f %d %d %d %3.6f %d %d %d %d %d\n", 
               curTime,mode,curRTT, cwnd, currentWindow, RxSeqNumber, 
               smoothedRTT, RxSeqNumber, largestSeqSent, numberOfTimeOuts,numberLost, errorCount);
          }
          //currently, show this each ACK received
          // WINDOW SAMPLES
          //  Under development...
          //rc  =  updateMonitor(curTime);
          rc = SUCCESS;
          if (rc == SUCCESS) {

            if (debugLevel > 1) {
              printf("STATE:%f %d %d %d %d %f %d %d %d %d %d %d %d %d %d \n",
                 curTime, nIterations, errorRecoveryState, decisionMade, RxSeqNumber, curRTT,  cwnd, currentWindow, 
                 getStateInfo(curTime,GET_NUMBER_IN_FLIGHT),
                 getStateInfo(curTime,GET_NUMBER_CAN_SEND),
                 largestSeqSent,leftEdge, rightEdge,snd_next, sequenceNumberTimed);
            }
            // OUT WINDOW MODE
            if (createDataFileFlag == 1 ) {
              fprintf(newFile,"%f %d %d %d %d %f %d %d %d %d %d %d %d %d %d \n",
                 curTime, nIterations, errorRecoveryState, decisionMade, RxSeqNumber, curRTT,  cwnd, currentWindow, 
                 getStateInfo(curTime,GET_NUMBER_IN_FLIGHT),
                 getStateInfo(curTime,GET_NUMBER_CAN_SEND),
                 largestSeqSent,leftEdge, rightEdge,snd_next, sequenceNumberTimed);
            }
#if 0
            if (createDataFileFlag == 1 ) {
              fprintf(newFile,"%f %d %s %d %d %d %f %d %d %d %d %d %d %d %2.4f %3.6f\n",
                 curTime, mode, inet_ntoa(clientAddress.sin_addr),ntohs(clientAddress.sin_port),
                 RxSeqNumber, decisionMade, curRTT, cwnd, currentWindow, largestSeqSent,leftEdge, rightEdge,snd_next,
                lastMonitorThroughputSample, lastMonitorLossRateSample, lastMonitorRTTSample);
            }
#endif 
          }

      }

      //Delay the correct amount of time
      rc = myDelay(iterationDelay);
      if (rc == ERROR){
          printf("UDPEchoClient2:WINDOW(%f): HARD ERROR:  myDelay returned an error ???   \n", curTime);
          exit(EXIT_FAILURE);
      }
    }  //end while
  } else {
    printf("UDPEchoClient:(%f): HARD ERROR: Bad mode :  %d \n", curTime, mode);
    exit(EXIT_FAILURE);
  }

  //If we get here, we've ended because iterations finished
  if (debugLevel > 2) {
       printf("UDPEchoClient2: Finished %d iterations \n", nIterations);
              
  }
  if (rc == SUCCESS){
    exitProcessing(timestamp(),MAIN_SUCCESS_EXIT);
    exit(EXIT_SUCCESS);
  }
  else{ 
    exitProcessing(timestamp(),MAIN_ERROR_EXIT);
    exit(EXIT_FAILURE);
  }

}


void CatchAlarm(int ignored) 
{ 

  if (debugLevel > 2) {
    printf("UDPEchoClient2:CatchAlarm:(signal:%d): #iterations:%d,  #timeouts:%d \n", 
          ignored, numberOfTrials,numberOfTimeOuts);
  }

}

/***********************************************************
* Function: void clientCNTCCode() 
*
* Explanation: the programs SIG-INT signal handler.
*
* inputs: passed the IP and port of the client 
*
* outputs:
*    
* notes: 
*
***********************************************************/
void clientCNTCCode() 
{

  bStop = 1;
  if (debugLevel > 2) {
    printf("UDPEchoClient2:CNTC: #iterations:%d,  #timeouts:%d \n", 
           numberOfTrials,numberOfTimeOuts);
  }
  exitProcessing(timestamp(), CNTC_EXIT);
  exit(EXIT_SUCCESS);
}


/***********************************************************
* Function: void exitProcessing(double curTime, int reasonCode) 
*
* Explanation:  This is called when the program it to terminate. 
*  It computes final statistics and printf out results.
*
* inputs: passed the curTime
*     reasonCode: indicates who calls and why ...
*         MAIN_SUCCESS_EXIT : main program exits with no errors
*         MAIN_ERROR_EXIT 2: main program exits in error
*         CNTC_EXIT 3 :    signal handler called to terminate program
*
* outputs:
*    
* notes: 
*  It is assumed that the caller will issue the exit
*
***********************************************************/
void exitProcessing(double curTime, int reasonCode) 
{
  double duration = 0;
  double actualSendRate = 0;
  double avgLoss = 0.0;
  double avgLoss1 = 0.0;
  double avgLoss2 = 0.0;

  endTime = curTime;
  duration = endTime - startTime;

  if (sock != -1) 
    close(sock);

  sock = -1;
  numberLost = numberOfTrials - numberRTTSamples;

  if (duration > 0.0)
    actualSendRate = ((double )totalBytesSent)*8 / duration;

  if (numberRTTSamples != 0) {
    avgPing = (totalPing/numberRTTSamples);
    meanCurRTT = (sumOfCurRTT/numberRTTSamples);
  }
  if (numberOfTrials != 0) 
    avgLoss = (((double)numberOfTimeOuts*100)/numberOfTrials);

  if (mode == RTT_MODE) {
    if (debugLevel > 0) {
      printf("UDPEcho2Client:exitProcessing(Duration:%f,%d):RTT_MODE:  numberOfTrials:%d, numberRTTSamples:%d, numberLoss:%d, numberOfTOs:%d \n",
         duration,reasonCode, numberOfTrials, numberRTTSamples,numberLost, numberOfTimeOuts); 

      printf("UDPEcho2Client:exitProcessing(Duration:%f):RTT_MODE: Sent:%d avgRTT:%3.6f smoothedRTT:%3.6f, avgLoss:%2.4f, actualSendRate:%9.0f\n",
             duration,numberOfTrials, meanCurRTT, smoothedRTT, avgLoss, actualSendRate);
    }
  } else if ( mode == CBR_MODE) {
    if (debugLevel > 0) {
        printf("UDPEcho2Client:exitProcessing:(Duration:%f,%d):CBR_MODE: Sent:%d TotalBytes:%lld actualSendRate:%9.0f\n",
             duration,reasonCode,numberOfTrials, totalBytesSent, actualSendRate);
    }
  } else if ( mode == WINDOW_MODE) {
   
    unsigned int avgThroughput = 0;
    double avgLossRate=0.0; 
    double avgRTT=0.0;
    if (numberOfIntervals > 0) {
     avgThroughput =  monitorThroughputSum/ numberOfIntervals;
     avgLossRate = monitorLossRateSum/numberOfIntervals; 
     avgRTT =  monitorRTTSum/numberRTTIntervalSamples;
    }

    if (debugLevel > 0) {
      printf("UDPEcho2Client:exitProcessing(Duration:%f:%d):WINDOW_MODE(%d): Sent:%d Received:%d numberLost:%d numberRTTSamples:%d, avgRTT:%f actualSendRate:%9.0f\n",
             duration,reasonCode,numberOfTrials, totalMsgsSent, totalReceivedMsgs, numberLost, numberRTTSamples, meanCurRTT, actualSendRate);
      printf("      NumberOfMonitorIntervals:%d (#RTTsamples:%d), avgThroughput:%d, avgLossRate:%2.4f, avgRTT:%3.6f \n",
           numberOfIntervals, numberRTTIntervalSamples, avgThroughput,avgLossRate, avgRTT);
    }

  } else {
    if (debugLevel > 0) {
        printf("UDPEcho2Client:exitProcessing(%f:%d): BAD MODE ?? %d SentMsgs:%d TotalBytes:%lld actualSendRate:%9.0f\n",
             duration, reasonCode, mode, numberOfTrials, totalBytesSent, actualSendRate);
    }
  }

  if (debugLevel > 2) {
    printf("UDPEcho2Client:exitProcessing(%f:%s:%d) attempts/samples/#Lost/#TOs/NumberNewSockets: :%d:%d:%d:%d:%d #errors:%d \n", 
       duration,serverIP,reasonCode,numberOfTrials,numberRTTSamples,numberLost, outOfOrderArrivals,numberOfSocketsUsed,errorCount);
  }

  if (newFile != NULL) {
    printf("UDPEcho2Client:exitProcessing(%f:%s:%d) fflush and close file \n",
       duration,serverIP,reasonCode);
    fflush(newFile);
    fclose(newFile);
  }
}

/*************************************************************
*
* Function: int getStateInfo(int opCode)
* 
* Explanation:   This routine routines the information
*                specified by the opcode based on 
*                current state.  No state updates are made.
*
* inputs: 
*  double curTime : current time
*  int  opCode :  : the information that is requested 
n
* outputs:
*  Success is 0 or greater which represents the value of the 
*         requested data. 
*          Or, a FAILURE (-1) is returned on error. 
*
*  Assumed that:
*      snd_next is the seq number to send next if the window allows
*      currentWindow, leftEdge, rightEdge are all correct
************************************************************/
int getStateInfo(double curTime, int opCode)
{
  int rc=FAILURE; 


  switch(opCode) {

    case GET_WINDOW:
      rc = currentWindow;
      break;

    case GET_LEFT_EDGE:
        rc = leftEdge;
      break;

    case GET_RIGHT_EDGE:
        rc = rightEdge;            
      break;

    case GET_SEND_NEXT:
        rc = snd_next;
      break;

    case GET_NUMBER_IN_FLIGHT:
        if (snd_next > rightEdge) {
          //in this case, should be a full window
          rc= ((rightEdge+1) - leftEdge);
          if (rc != currentWindow) {
            //FAILURE CHECK
            //if this is true.....something is wrong
            printf("UDPEchoClient:(%f)getStateInfo:GET_NUMBER_IN_FLIGHT: HARD ERROR: not full window?? snd_next:%d, rightEdge:%d, leftEdge:%d, rc:%d, currentWindow:%d \n",
                 curTime,snd_next, rightEdge, leftEdge,rc,currentWindow);
            exit(EXIT_FAILURE);
          }
        }
        else 
          rc= snd_next -leftEdge ;

        if (rc < 0) {
          //FAILURE CHECK
          //if this is true.....something is wrong
          printf("UDPEchoClient:(%f)getStateInfo:GET_NUMBER_IN_FLIGHT: HARD ERROR: snd_next:%d, rightEdge:%d, leftEdge:%d, rc:%d \n",
                 curTime,snd_next, rightEdge, leftEdge,rc);
          exit(EXIT_FAILURE);
        }
      break;

    case GET_NUMBER_CAN_SEND:
        //note....assumes current left/right edge and snd_next
        // Will NOT slide window forward if that is possible
        // if snd_next points to rightEdge+1, then can 't send any
        if (snd_next > rightEdge)
          rc = 0;
        else { 
          rc = rightEdge - snd_next + 1;
        }
        if (rc < 0) {
          //FAILURE CHECK
          //if this is true.....something is wrong
          printf("UDPEchoClient:(%f)getStateInfo:GET_NUMBER_CAN_SEND:  HARD ERROR: snd_next:%d, rightEdge:%d, leftEdge:%d, rc:%d \n",
                 curTime,snd_next, rightEdge, leftEdge,rc);
          exit(EXIT_FAILURE);
        }
      break;

    case GET_RECOVERY_STATE: 
        rc = errorRecoveryState;
      break;

    case UNKNOWN_OPCODE:
        if (debugLevel > 1) {
          printf("UDPEchoClient:(%f)getStateInfo:  WARNING :opCode: UNKNOWN_OPCODE %d  \n",
                 curTime,opCode);
        }
        rc = FAILURE;
      break;

    default:
        if (debugLevel > 1) {
        printf("UDPEchoClient:(%f)getStateInfo:  WARNING :opCode: hit default?? %d \n",
                 curTime, opCode);
        }
        rc = FAILURE;
  }


  if (rc == FAILURE) 
     printf("UDPEchoClient:getStateInfo(%f): FAILED??  opCode:%d, rc:%d \n",
                 curTime, opCode, rc);

  if (debugLevel > 2) {
     printf("UDPEchoClient:getStateInfo(%f): SUCCEEDED opCode:%d, rc : %d \n",
                 curTime, opCode, rc);
  }

  return rc;

}

/*************************************************************
*
* Function: int updateState(double curTime, int opCode, unsigned int seqNumber))
* 
* Explanation:   This routine updates state based on 
*                 the opCode and RxSeqNumber.  
*                It returns the updated currentWindow.
*
*                This routine hides the differences in behaviors during ERROR_RECOVERY
*           
* inputs: 
*  double curTime : current time
*  int  opCode :   Event that is to be considered 
*  unsigned int seqNumber - the SeqNumber that might be associated with the opCode.
*                     For opCodes that are not triggered by an ACK arrival, the RxSeqNumber
*                     is set to 0.
n
* outputs:
*  returns the updated window.   
*             Or a FAILURE.
*
*  Notes:   All state variables are updated, including the currentWindow.  
************************************************************/
int updateState(double curTime, int opCode, unsigned int SeqNumberP)
{
int rc=SUCCESS;

//Used to convey how many data segments are being ACKed (might not be appropriate for all cases below)
int msgsAcked = 0;

  currentWindow  = getWindow(cwnd, maxW);
  if (debugLevel > 2) {
    printf("UDPEchoClient:updateState(%f:%d): ENTRY opCode:%d  RxSeqNumber:%d, cwnd:%d, left:%d, right:%d,snd_next:%d  \n",
            curTime, errorRecoveryState, opCode, SeqNumberP, cwnd,leftEdge,rightEdge,snd_next);
  }

  switch(opCode) {

    case NEW_ACK_EVENT:
      if (debugLevel > 2) {
          printf("UDPEchoClient:updateState(%f:%d):NEW ACK: ENTRY: RxSeqNumber:%d  cwnd:%d, left:%d, right:%d,snd_next:%d  \n",
                 curTime, errorRecoveryState, SeqNumberP, cwnd,leftEdge,rightEdge,snd_next);
      }
      if (errorRecoveryState == NO_ERROR_RECOVERY) {
         //a new ack arrived....if it acks > 1 msg, its a cumulative ACK
         msgsAcked = SeqNumberP -leftEdge;
         if (msgsAcked <= 0) {
          printf("UDPEchoClient:updateState(%f:%d):NEW ACK:  HARD ERROR: RxSeqNumber:%d  # Msgs acked :%d  \n",
                 curTime, errorRecoveryState, SeqNumberP, msgsAcked);
          exit(EXIT_FAILURE);
         }
         leftEdge+=msgsAcked;

         //grow the window
         cwnd++;       
         currentWindow  = getWindow(cwnd, maxW);
         rightEdge = leftEdge + (currentWindow-1);
      } else {
         //we got either a NEW ACK or a Recovery ACK while in recovery...
         msgsAcked = SeqNumberP -leftEdge;
         if (msgsAcked <= 0) {
           printf("UDPEchoClient:updateState(%f:%d):NEW ACK:  HARD ERROR: RxSeqNumber:%d  # Msgs acked :%d  \n",
                 curTime, errorRecoveryState, SeqNumberP, msgsAcked);
           exit(EXIT_FAILURE);
         }
         leftEdge+=msgsAcked;
         currentWindow  = getWindow(cwnd, maxW);
         rightEdge = leftEdge + (currentWindow-1);

         if ( (SeqNumberP > recoveryLeftEdge) && (SeqNumberP <  recoveryRightEdge) ) {
           errorRecoveryState = ERROR_RECOVERY_STATE;
         } else if (SeqNumberP == recoveryRightEdge) {
           errorRecoveryState = ERROR_RECOVERY_COMPLETE;
         } else if (SeqNumberP > recoveryRightEdge) {
            //then a true NEW ACK and this completes recovery
           errorRecoveryState = NO_ERROR_RECOVERY;
           recoveryLeftEdge  = NULL_SEQ_NUMBER;
           recoveryRightEdge = NULL_SEQ_NUMBER;
           cwnd++;       
           currentWindow  = getWindow(cwnd, maxW);
           rightEdge = leftEdge + (currentWindow-1);
         }

      }
      if (debugLevel > 2) {
          printf("UDPEchoClient:updateState(%f:%d):NEW ACK: RxSeqNumber:%d  # Msgs acked :%d, cwnd:%d, left:%d, right:%d,snd_next:%d  \n",
                 curTime, errorRecoveryState, SeqNumberP, msgsAcked,cwnd,leftEdge,rightEdge,snd_next);
      }
      break;


    case DUPLICATE_ACK_EVENT:
      if (errorRecoveryState == NO_ERROR_RECOVERY) {
          //we enter RECOVERY state, recording the sequence numbers
          //in flight. A Go-Back-N recover requires the entire
          //block (usually a partial window ) to be retransmitted
          errorRecoveryState = LOSS_DETECTED;
          numberOfErrorRecoveries++;
          recoveryLeftEdge  = leftEdge;
          recoveryRightEdge  = rightEdge;

          //so we reset the snd_next ptr
          snd_next =  leftEdge; 
 
          
          //Let's shrink the window....
          cwnd=1;
          currentWindow = getWindow(cwnd, maxW);
          //leftEdge  stays the same
          //RightEdge moves to leftEdge...
          rightEdge = leftEdge;

          if (debugLevel > 2) {
            printf("UDPEchoClient:WINDOW(%f:%d): FIRST DUP, move to RECOVERY_DETECTED firstSeqNumr:%d, lastSeqNum:%d, snd_next:%d\n",
              curTime, errorRecoveryState, recoveryLeftEdge, recoveryRightEdge,snd_next);
          }
      } else { 

         //we got another dup..... 
         msgsAcked = SeqNumberP -leftEdge;
         if (msgsAcked <= 0) {
           printf("UDPEchoClient:updateState(%f:%d):NEW ACK:  HARD ERROR: RxSeqNumber:%d  # Msgs acked :%d  \n",
                 curTime, errorRecoveryState, SeqNumberP, msgsAcked);
           exit(EXIT_FAILURE);
         }
         leftEdge+=msgsAcked;
         currentWindow  = getWindow(cwnd, maxW);
         rightEdge = leftEdge + (currentWindow-1);

         if ( (SeqNumberP > recoveryLeftEdge) && (SeqNumberP <  recoveryRightEdge) ) {
           errorRecoveryState = ERROR_RECOVERY_STATE;
         } else if (SeqNumberP == recoveryRightEdge) {
           errorRecoveryState = ERROR_RECOVERY_COMPLETE;
         } else if (SeqNumberP > recoveryRightEdge) {
            //then a true NEW ACK and this completes recovery
           errorRecoveryState = NO_ERROR_RECOVERY;
           recoveryLeftEdge  = NULL_SEQ_NUMBER;
           recoveryRightEdge = NULL_SEQ_NUMBER;
           cwnd++;       
           currentWindow  = getWindow(cwnd, maxW);
           rightEdge = leftEdge + (currentWindow-1);
         } 

         if (SeqNumberP <= recoveryRightEdge) 
         {
            errorRecoveryState = ERROR_RECOVERY_STATE;
         } else {
            //Something strange has happened....
            errorRecoveryState = ERROR_RECOVERY_UNEXPECTED_STATE;
            printf("UDPEchoClient:updateState(%f:%d): WARNING: DUP :%d, not in range recoveryLeftEdge:%d, recoveryRightEdge:%d  \n",
                 curTime, errorRecoveryState,SeqNumberP, recoveryLeftEdge,  recoveryRightEdge);
            exit(EXIT_FAILURE);
          }
        }
            
        if (debugLevel > 2) {
          printf("UDPEchoClient:updateState(%f:%d):DUP ACK: RxSeqNumber:%d  # Msgs acked :%d, cwnd:%d, left:%d, right:%d,snd_next:%d  \n",
                 curTime,errorRecoveryState, SeqNumberP, msgsAcked,cwnd,leftEdge,rightEdge,snd_next);
        }
      break;

    case UNEXPECTED_ACK_EVENT:
        if (errorRecoveryState != NO_ERROR_RECOVERY) {
          printf("UDPEchoClient:(%f)updateState:UNEXPECTED_ACK: and NOT in RECOVERY?  rxed: %d, currentWindow:%d, leftEdge:%d, rightEdge:%d , send_nxt:%d\n",
                 curTime,SeqNumberP, currentWindow, leftEdge, rightEdge, snd_next);
        } else {
          printf("UDPEchoClient:(%f)updateState:UNEXPECTED_ACK: and NOT in RECOVERY?  rxed: %d, currentWindow:%d, leftEdge:%d, rightEdge:%d , send_nxt:%d\n",
                 curTime,SeqNumberP, currentWindow, leftEdge, rightEdge, snd_next);
        }
        exit(EXIT_FAILURE);
        //rc=FAILURE;
      break;

    case SENT_MSG:
      if (errorRecoveryState == NO_ERROR_RECOVERY) {
        //leftEdge does not change
        //rightEdge does not change....
        //snd_next is seq number to be sent Next
        snd_next=SeqNumberP+1;
        currentWindow  = getWindow(cwnd, maxW);
        if (debugLevel > 2) {
          printf("UDPEchoClient:(%f)updateState:SENT_MSG:seqNumber:%d leftEdge:%d, rightEdge:%d, snd_next:%d \n",
                 curTime,SeqNumberP, leftEdge, rightEdge,snd_next);
        }
      } else if (errorRecoveryState == LOSS_DETECTED) {
        if ((SeqNumberP >= recoveryLeftEdge) && (SeqNumberP <= recoveryRightEdge)) 
            errorRecoveryState = ERROR_RECOVERY_STATE;
      }
      if (debugLevel > 2) {
        printf("UDPEchoClient:(%f:%d)updateState:SENT_MSG:seqNumber:%d leftEdge:%d, rightEdge:%d, snd_next:%d \n",
                 curTime,errorRecoveryState,SeqNumberP, leftEdge, rightEdge,snd_next);
      }
      break;

    case TIMEOUT_EVENT:
       if (errorRecoveryState == NO_ERROR_RECOVERY) {
          //we enter RECOVERY state, recording the sequence numbers
          //in flight. A Go-Back-N recover requires the entire
          //block (usually a partial window ) to be retransmitted
          errorRecoveryState = LOSS_DETECTED;
          numberOfErrorRecoveries++;
          recoveryLeftEdge  = leftEdge;
          recoveryRightEdge  = rightEdge;
          snd_next = SeqNumberP;  //so we reset the snd_next ptr
 
          
          //Let's shrink the window....
          cwnd=1;
          currentWindow = getWindow(cwnd, maxW);
          //leftEdge  stays the same
          //RightEdge moves to leftEdge 
          rightEdge = leftEdge;

      } else if (errorRecoveryState == LOSS_DETECTED) {
        if ((SeqNumberP >= recoveryLeftEdge) && (SeqNumberP <= recoveryRightEdge)) 
            errorRecoveryState = ERROR_RECOVERY_STATE;
      }
      if (debugLevel > 2) {
        printf("UDPEchoClient:(%f:%d)updateState:TIMEOUT_EVENT:seqNumber:%d leftEdge:%d, rightEdge:%d, snd_next:%d \n",
                 curTime,errorRecoveryState,SeqNumberP, leftEdge, rightEdge,snd_next);
      }
      break;

    case UNKNOWN_OPCODE:
        printf("UDPEchoClient:(%f:%d)updateState: HARD ERROR :opCode: UNKNOWN_OPCODE %d  \n",
                 curTime,errorRecoveryState,opCode);
        exit(EXIT_FAILURE);
        //rc=FAILURE;
      break;

    default:
        printf("UDPEchoClient:(%f:%d)updateState: HARD ERROR :opCode: default ??  %d  \n",
                 curTime,errorRecoveryState,opCode);
        exit(EXIT_FAILURE);
        //rc=FAILURE;
  }

  if (rc == FAILURE) {
    if (debugLevel > 1) {
       printf("UDPEchoClient:updateState(%f:%d): WARNING  FAILED??  opCode:%d, cwnd:%d, currentWindow:%d \n",
                 curTime, errorRecoveryState, opCode, cwnd, currentWindow);
    }
  }
  else { 
    rc = currentWindow;
    if (debugLevel > 1) {
      printf("UDPEchoClient:updateState(%f:%d): SUCCEEDED opCode:%d, cwnd:%d, currentWindow:%d  rc : %d \n",
                 curTime, errorRecoveryState, opCode, cwnd, currentWindow,rc);
    }
  }

  return rc;
}


/*************************************************************
*
* Function: int getWindow(unsigned int cwnd, int maxW)
* 
* Explanation:   This routine returns the Window based on
*                the two parameters.   
*                Global state is NOT updated by this routine.
*
*           
* inputs: 
*     unsigned int cwnd
*     int maxW : the configured maxW.  If -1, an error.
*                if 0, we assume it means infinite, 
*                else its a valid maxW   
*
* outputs:
*  Returns the min(cwnd,maxW) or FAILURe if one of these input params
*         appears to not be valid.
*
************************************************************/
int getWindow(unsigned int cwndP, int maxWP)
{

int rc = FAILURE;

  if ((maxWP < 0) || (cwndP == 0)) {
    printf("UDPEchoClient:getWindow: HARD ERROR cwndP:%d, maxWP:%d, returned rc:%d \n", cwndP,maxWP,rc);
  }
  else { 
    if (maxWP == 0) 
      rc = cwndP;
    else {
      if (cwndP > maxWP)
        rc = maxWP;
      else
        rc = cwndP;
    }
  }

  if (debugLevel > 2) {
    printf("UDPEchoClient:getWindow: cwnd:%d, maxW:%d, returned window rc:%d \n", cwndP,maxWP,rc);
  }

  return rc; 
}

/*************************************************************
*
* Function: void initMonitor(double curTime)
* 
* Explanation:  inits all variables used for the interval monitor.
*
* inputs: none
*           
* outputs:
*     updates the monitor state variables - initalizes.
*
************************************************************/
void initMonitor(double curTime)
{

  firstMonIntervalTime = curTime;
  lastMonIntervalTime = curTime;
  monByteCount = 0;
  monLossCount = 0;
  numberOfIntervals = 0;


  RTTSampleCount = 0.0;
  numberRTTIntervalSamples = 0; //within an interval, the number of samples
  lastMonitorRTTSample=0;
  monitorRTTSum=0;

  numberIntervalSamples = 0;
  lastMonitorThroughputSample=0;
  monitorThroughputSum = 0;
  lastMonitorLossRateSample=0.0;
  monitorLossRateSum = 0.0;
}

/*************************************************************
*
* Function: int  updateMonitor(double curTime)
* 
* Explanation: called to update monitor state 
*              This routine assumes the per interval counters
*              are updated by the caller....
* inputs: 
*   double curTime :            
*
* outputs:
*   returns a SUCCESS if the interval measures have been updated. 
*   returns a FAILURE if the interval measures HAVE not been
*            updated because the interval period has not yet expired
*
***********************************************/
int updateMonitor(double curTime)
{
  int rc = FAILURE;
  double timeSinceLastInterval = curTime - lastMonIntervalTime;
  int tmpInt = 0;
  double tmpDouble = 0.0;


  if (timeSinceLastInterval > MONITOR_INTERVAL) {
    rc = SUCCESS;
    numberOfIntervals++;
    if (numberIntervalSamples == 0) {
      lastMonitorThroughputSample = 0;
      lastMonitorLossRateSample  = 0.0;
      lastMonitorRTTSample=0;
    }
    else {
      if (timeSinceLastInterval > 0)   
        tmpInt = (monByteCount * 8) /  timeSinceLastInterval;

      tmpDouble =  (double) monLossCount / (double)numberIntervalSamples;

      lastMonitorThroughputSample = tmpInt;
      lastMonitorLossRateSample  = tmpDouble;


      //now update the monitor rtt 
      if (numberRTTIntervalSamples > 0) {
         lastMonitorRTTSample = RTTSampleCount / numberRTTIntervalSamples;
      } else  
          lastMonitorRTTSample=0;
    } 

    monitorThroughputSum+=lastMonitorThroughputSample;
    monitorLossRateSum +=lastMonitorLossRateSample;
    monitorRTTSum+=lastMonitorRTTSample;

    if (debugLevel > 2) {
      printf("UDPEchoClient:updateMonitor:(%f): UPDATE!! NumberSamples%d, ByteCount:%d, lossCount:%d throughput:%d avgLoss:%f avgRTT:%f \n",
           curTime,numberIntervalSamples, monByteCount,monLossCount,
          lastMonitorThroughputSample,lastMonitorLossRateSample, lastMonitorRTTSample);
    }

    numberIntervalSamples = 0;
    monByteCount = 0;
    monLossCount = 0;
    RTTSampleCount = 0.0;
    numberRTTIntervalSamples = 0; //within an interval, the number of samples
    lastMonIntervalTime=curTime;
  } else {
    rc = FAILURE;
  } 
  

  if (debugLevel > 2) {
 
   if (rc == SUCCESS) {
    printf("UDPEchoClient:updateMonitor:(%f:%d): MONITOR UPDATE:  avgThroughput:%d, avgLoss:%f, avgRTT:%f\n",
           curTime, numberIntervalSamples, 
            lastMonitorThroughputSample, lastMonitorLossRateSample, lastMonitorRTTSample);
    }
    else {
     printf("UDPEchoClient:updateMonitor:(%f,%d):NO UPDATE, time since last Interval:%f \n",
           curTime,numberIntervalSamples,timeSinceLastInterval);
    }
  }


  return rc;
}

/*************************************************************
*
* Function: int  showSlidingWindowState(double curTime)
* 
* Explanation: called to printf a summary of window state 
*
* inputs: 
*   double curTime :            
*
* outputs:
*   returns a SUCCESS if the interval measures have been updated. 
*   returns a FAILURE if the interval measures HAVE not been
*            updated because the interval period has not yet expired
*
***********************************************/
int showSlidingWindowState(double curTime)
{
  int rc = SUCCESS;

   printf("%f currentWindow:%d, cwnd:%d,  leftEdge:%d, rightEdge:%d, snd_next:%d \n",
                curTime,currentWindow,cwnd, leftEdge,rightEdge,snd_next);
  return rc;
}

