/* File: packet.c */

/*
 *********************************************************************
   ALTERNATING BIT AND GO-BACK-N NETWORK EMULATOR

   Revised version of code by J.F. Kurose

   From the companion website for 
   _Computer Networking: A Top-Down Approach Featuring the Internet_
   by J.F. Kurose and K. W. Ross
   (c) 2001 by Addison Wesley Longman

   Based on document at <URL:http://occawlonline.pearsoned.com/
   bookbind/pubbooks/kurose-ross1/chapter4/custom12/deluxe-content.html>
   (as of 02 July 2002)
 *********************************************************************
*/

#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include "payload.h"
#include "packet.h"

struct pkt {
     int seqnum;
     int acknum;
     int checksum;
     char payload[PAYLOAD_SZ];
};


/* create a packet */
packet_t 
new_pkt(void) {
  packet_t P;

  if (NULL != (P = malloc(sizeof(struct pkt)))) {
    init_pkt(P);
  }

  return P;
} /* new_pkt() */


/* destroy a packet */
void
dispose_pkt(packet_t P) {
  free(P);
} /* dispose_pkt() */


void
init_pkt(packet_t P) {
  P->seqnum = P->acknum = P->checksum = -1;
  P->payload[0] = '\0';
} /* init_pkt() */


/* display a packet */
int
print_pkt (FILE *   where,
           char *   before, 
           packet_t P,
           char *   after) {
  return
    fprintf(where, "%s seq: %d, ack: %d, check: %d, data: %s%s",
            before, P->seqnum, P->acknum, P->checksum, P->payload, after);
} /* print_pkt() */



/* put data into a packet */
void
set_pkt_data (packet_t P,
              int      seq_num,
              int      ack_num,
              int      checksum,
              char *   data) {
  P->seqnum   = seq_num;
  P->acknum   = ack_num;
  P->checksum = checksum;
  (void)strncpy(P->payload, data, PAYLOAD_SZ - 1);
} /* set_pkt_data() */



 /*
   copy the data from one packet into another 
   NB: this does not make a new packet (use new_pkt() for that)
 */
void
copy_pkt (packet_t dst,   /* clone    */
          packet_t src) { /* original */
/*
  dst->seqnum   = src->seqnum;
  dst->acknum   = src->acknum;
  dst->checksum = src->checksum;
  (void)strcpy(dst->payload, src->payload);
 */
 memcpy(dst,src,sizeof(struct pkt));
} /* copy_pkt() */


/* get a copy of the packet's payload */
char *
pkt_data (packet_t P) {
  return P->payload;
} /* pkt_data() */


/* get a copy of the packet's sequence number */
int
pkt_seq (packet_t P) {
  return P->seqnum;
} /* pkt_seq() */


/* get a copy of the packet's ACK number */
int
pkt_ack (packet_t P) {
  return P->acknum;
} /* pkt_ack() */


/* get a copy of the packet's checksum value */
int
pkt_check (packet_t P) {
  return P->checksum;
} /* pkt_check() */

/* get the size of the packet structure */
int
pkt_size(){
  return (sizeof(struct pkt));
}

/* EOF (packet.c) */
