

#include <stdio.h>
#include <ctype.h> // serve per toupper ()
#include <string.h>

typedef struct {
  char  cognome [40];
  char  nome [40];
  char  matricola [20];
} t_studente;

#define QUEUE_SIZE  10

typedef struct {
  int   head, tail, n;
  t_studente data [QUEUE_SIZE];
} t_queue;

t_queue init_queue (void)
{
  t_queue new_queue;
  new_queue.head = new_queue.tail = new_queue.n = 0;
  return new_queue;
}

int is_queue_full (t_queue q)
{
  return q.n == QUEUE_SIZE;
}

int is_queue_empty (t_queue q)
{
  return q.n == 0;
}

void in (t_queue * q, t_studente elem)
{
  q->data [q->tail] = elem;
  q->tail = (q->tail + 1) % QUEUE_SIZE;
  q->n++;
}

t_studente out (t_queue * q)
{
  t_studente tmp;
  tmp = q->data [q->head];
  q->head = (q->head + 1) % QUEUE_SIZE;
  q->n--;
  return tmp;
}

int check_studente (t_queue q, t_studente s)
{
  int i, index;
  index = q.head;
  for (i = 0;i < q.n;i++) {
	 if (strcmp (s.matricola, q.data [index].matricola) == 0)
		return 1;
	 index = (index + 1) % QUEUE_SIZE;
  }
  return 0;
}

int main (int argc, char * argv[])
{
  t_queue myqueues[3];
  int i, choice;
  for (i = 0;i < 3;i++)
	 myqueues [i] = init_queue ();
  do {
	 printf ("0. Fine\n");
	 printf ("1. Nuovo studente in coda\n");
	 printf ("2. Prossimo studente da servire\n");
	 scanf ("%d", &choice);
	 switch (choice) {
		case 1:
		  t_studente s;
		  char primo_carattere;
		  int coda_selezionata;
		  printf ("Inserisci il cognome:");
		  scanf ("%s", s.cognome);
		  printf ("Inserisci il nome:");
		  scanf ("%s", s.nome);
		  printf ("Inserisci la matricola:");
		  scanf ("%s", s.matricola);
                             
		  coda_selezionata = 0;
		  for (i = 1; i < 3;i++) {
			 if (myqueues [i].n < myqueues [coda_selezionata].n)
				coda_selezionata = i;
		  }

		  if (is_queue_full (myqueues [coda_selezionata]) == 1)
			 printf ("Coda piena!\n");
		  else {
			 if (check_studente (myqueues [coda_selezionata], s) == 0) {
				in (& myqueues [coda_selezionata], s);
				printf ("Sei in coda allo sportello n.%d\n",
						  coda_selezionata+1);
				printf ("Davanti a te ci sono %d studenti\n",
							myqueues [coda_selezionata].n - 1);
			 }
			 else
            printf ("Studente gia' presente in coda.\n");
		  }
		  break;
		case 2:
		  int num_sportello;
		  printf ("Inserisci il numero di sportello:");
		  scanf ("%d", &num_sportello);
		  num_sportello --;
		  if (is_queue_empty (myqueues [num_sportello]) == 1)
			 printf ("Nessuno studente in coda\n");
		  else {
          t_studente prox_s;
			 prox_s = out (& myqueues [num_sportello]);
			 printf ("Cognome   : %s\n", prox_s.cognome);
			 printf ("Nome      : %s\n", prox_s.nome);
			 printf ("Matricola : %s\n", prox_s.matricola);
			 printf ("La fila contiene ancora %d studenti\n",
                  myqueues [num_sportello].n);
		  }
		  break;
	 }
  } while (choice != 0);
}
