#include <stdio.h>
#include <stdlib.h>
#include "reseau.h"

#define SOURCE 42
#define DESTINATION 26
#define FEMISSION  "flux2.dat"
#define FRECEPTION "flux1.dat"

int main(void)
/* Programme principal */
{
  int AS,AD,numero,trame_attendue=0;
  char aux;

  ttampon TamponReception;
  ttrame Trame;

  fprintf(stderr,"Initialisation du protocole 4\n");
  initialise_couche_physique(FEMISSION, FRECEPTION);
  initialise_couche_reseau(SOURCE, DESTINATION);

  while(1)
  {
    attendre(SIGRECU);
    prendre_de_la_couche_physique(&Trame);
    recuperer_donnees(Trame, &TamponReception,&numero, &AS, &AD);
    fprintf(stderr,"Trame %d recue : %s\n",numero,TamponReception.info);
    if (numero!=trame_attendue) fprintf(stderr,"Trame non attendue (%d) !\n",trame_attendue);
    else {
      envoyer_vers_couche_reseau(TamponReception, AS, AD);
      if ((rand() % 20)==0)
      {
        strcpy(TamponReception.info,"N");
        fprintf(stderr,"Envoi de RNR !\nAppuyez sur entree pour continuer\n");
        construire_trame(numero, AD, AS, TamponReception, &Trame);
        envoyer_vers_couche_physique(Trame);
	fflush(stdin);
        scanf("%c",&aux);
      }
      strcpy(TamponReception.info,"R");
      construire_trame(numero, AD, AS, TamponReception, &Trame);
      fprintf(stderr,"Acquitement %d envoye\n",numero);
      envoyer_vers_couche_physique(Trame);
      trame_attendue=(trame_attendue+1)%MAXTAILLEFENETRE;
    }
  }
}