#include <stdio.h>
#include <stdlib.h>
#include <pcap.h>
#include "packman.h"
#include "proto_util.h"
#include "las_pcap_recv.h"
#include "las_pack_send.h"

extern struct base			**cell;

extern u_int16_t			noh;

extern struct header_hash_table		**head_hash;

extern struct pack_vect			*packs2bsnt;

extern u_int8_t				verbose;

extern FILE				*output_file;

extern int				sockd;

int do_the_game(int state){
  struct send 	*snd;
  struct wait 	*wt;
  struct recv 	*rcv;
  struct shell	*sh;

  if(verbose){
    fprintf(output_file,"State %s : ",cell[state]->state_name);
    fflush(output_file);
  }
  switch(cell[state]->action){
    case SEND_PACKET:
	finish_pack(state);
	snd = (struct send *)cell[state]->arg;
	if(verbose){
          fprintf(output_file,"Sending pack #%d... ",snd->packet_id);
	  fflush(output_file);
	  send_it(snd->pack,snd->psize/8);
	  fprintf(output_file,"sent.\n");
	}else
	  send_it(snd->pack,snd->psize/8);
	break;
    case RECV_PACKET:
        rcv = (struct recv *)cell[state]->arg;
	if(verbose){
	  fprintf(output_file,"Waiting for a packet...");
	  fflush(output_file);
	  cell[state]->next = packet_receiver(head_hash,noh,rcv);
          fprintf(output_file,"\n");
	}else
	  cell[state]->next = packet_receiver(head_hash,noh,rcv);
	break;
    case SHELL:
        sh = (struct shell *)cell[state]->arg;
	if(verbose)
	  fprintf(output_file,"Running \"%s\"...\n",sh->command);
	system(sh->command);
	break;
    case WAIT:
	wt = (struct wait *)cell[state]->arg;
	if(verbose){
          fprintf(output_file,"Waiting... %u micro seconds",wt->usec);
	  fflush(output_file);
	  usleep(wt->usec);
	  fprintf(output_file,"\n");
	}else
	  usleep(wt->usec);
	break;
    case FINISH:
	if(sockd >= 0)
	  close(sockd);
        if(verbose)
	  fprintf(output_file,"Game over, man!!\n");
	break;
    default:
	if(verbose)
	  fprintf(output_file,"This was not supposed to show up!\n");
	return -4;
  }
  return cell[state]->next;
}

int lets_play(state)
int state;
{
  int next = state;
 
  while(next >= 0){
    next = do_the_game(next);
  }
}
