/* 
   This file is part of Practical Distributed Processing
   Copyright (C) 2006-2007 Phillip J. Brooke and Richard F. Paige
*/

#include "netstr.h"
#include "ngcommon.h"
#include "ngcommon2.h"
#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <unistd.h>

/* We have a linked list of tiles that we handle. */
typedef struct tile_node {
  int               x;
  int               y;
  struct tile_node *next;
} tnode;

/* Head of the linked list. */
tnode *thead = NULL;

/* List of neighbouring map servers.  We also store them by tile. */
msnode *nmshead = NULL; 
msnode* tiles[N_TILES][N_TILES];

/* Our TCP and UDP sockets and address info. */
int st;
int su;
int sta;
struct sockaddr_in at;
struct sockaddr_in au;
struct sockaddr_in ata;

/* An address for the admin server. */
struct sockaddr_in admin_a;

/* Flag indicating that a shutdown is desired. */
int terminate = 0;

/* Subprogram prototypes. */
void open_ports(void);
void get_admin_address(void);
void fill_local_address(void);
void register_with_admin(void);
void wait_for_tiles(void);
void running(void);
void *periodic_move(void *param);
void send_p(char *buffer, int xt, int yt, int xtp, int ytp);
void send_pn(char *buffer, int xt, int yt, int xtp, int ytp);
int from_other(struct sockaddr_in *a);
int handle_tile(int xt, int yt);

/* Main function and subprograms. */

int main (int argc, char *argv[]) {
  pthread_attr_t      attr;
  pthread_mutexattr_t mattr;
  pthread_t           threadid; 

  printf("Map server starting, protocol version %d...\n", PROTOCOL_VERSION);
  read_command_line(argc, argv);
  if (!secret_keyword) {
    printf("Need secret keyword supplying with `-s'!\n");
    exit(EXIT_FAILURE);
  }
  if (!admin_host) {
    printf("Need admin server name supplying with `-a'!\n");
    exit(EXIT_FAILURE);
  }
  get_admin_address();
  open_ports();
  register_with_admin();
  if (!terminate) {
    wait_for_tiles();
    /* Create mutex. */
    pthread_mutexattr_init(&mattr);
    pthread_mutexattr_settype(&mattr, PTHREAD_MUTEX_RECURSIVE); 
    if (pthread_mutex_init(&pmutex, &mattr) < 0) 
    {
        perror("pthread_mutex_init failed");
        exit(EXIT_FAILURE);
    }
    /* Start a thread that periodically moves players and shots. */
    pthread_attr_init(&attr);
    /* We never want to collect any values for this -- it's entirely
       the thread's problem. */
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
    pthread_create(&threadid, &attr, periodic_move, NULL);
    /* Start the main cycle. */
    running();
  }
  printf("Map server shutting down.\n");
  exit(EXIT_SUCCESS);
}

void open_ports(void) {
  int                on              = 1;

  /* Create a UDP socket. */
  if ((su = socket(PF_INET, SOCK_DGRAM, 0)) < 0) {
    perror("Could not create UDP socket");
    exit(EXIT_FAILURE);
  }

  if (setsockopt(su, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
    {
      perror("Problem setting UDP socket option");
      exit(EXIT_FAILURE);
    }

  au.sin_family = AF_INET;
  au.sin_addr.s_addr = INADDR_ANY;
  au.sin_port = 0;

  if (bind(su, (struct sockaddr *) &au, sizeof(au)) != 0)
    {
      perror("Could not bind UDP socket");
      exit(EXIT_FAILURE);
    }

  /* Create a TCP socket to listen to the admin server. */
  if ((st = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
      perror("Could not create TCP socket");
      exit(EXIT_FAILURE);
    }

  if (setsockopt(st, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
    {
      perror("Problem setting TCP socket option");
      exit(EXIT_FAILURE);
    }

  at.sin_family = AF_INET;
  at.sin_addr.s_addr = INADDR_ANY;
  at.sin_port = 0;

  if (bind(st, (struct sockaddr *) &at, sizeof(at)) != 0)
    {
      perror("Could not bind TCP socket");
      exit(EXIT_FAILURE);
    }

  if (listen(st, 5) != 0)
    {
      perror("Problem listening on TCP socket");
      exit(EXIT_FAILURE);
    }
  /* Create a TCP socket to talk to the admin server. */
  if ((sta = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
      perror("Could not create TCP socket");
      exit(EXIT_FAILURE);
    }

  if (setsockopt(sta, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
    {
      perror("Problem setting TCP socket option");
      exit(EXIT_FAILURE);
    }

  ata.sin_family = AF_INET;
  ata.sin_addr.s_addr = admin_a.sin_addr.s_addr;
  ata.sin_port = htons(ADMIN_PORT);

  if (connect(sta, (struct sockaddr *) &ata, sizeof(ata)) != 0)
    {
      perror("Could not connect to admin server");
      exit(EXIT_FAILURE);
    }

  /* The map server can be chatty.  What ports did we get? */
  fill_local_address();
  printf("Opened TCP port %d and UDP port %d.\n",
	 ntohs(at.sin_port), 
	 ntohs(au.sin_port));
}

void fill_local_address(void) {
  socklen_t          sockaddr_in_len;

  /* What have we actually ended up with? */
  sockaddr_in_len = sizeof(struct sockaddr_in);
  getsockname(st, (struct sockaddr *) &at, &sockaddr_in_len);
  getsockname(su, (struct sockaddr *) &au, &sockaddr_in_len);
}

void get_admin_address(void) {
  struct hostent *   admin_h;

  /* Sort out the admin server address. */
  if ((admin_h = gethostbyname(admin_host)) == NULL)
    { 
      perror("Could not get host details.");
      exit(EXIT_FAILURE);
    }   

  admin_a.sin_family = AF_INET;
  memcpy(&admin_a.sin_addr.s_addr, admin_h->h_addr, admin_h->h_length);
  admin_a.sin_port = htons(ADMIN_PORT);

  printf("Got admin server IP address %s, port %d.\n",
	 inet_ntoa(admin_a.sin_addr), ntohs(admin_a.sin_port));
}

void register_with_admin(void) {
  char *             buffer          = malloc(BUFFER_SIZE);
  char *             reply1          = malloc(BUFFER_SIZE);
  char *             reply2          = malloc(BUFFER_SIZE);
  char *             token;
  int                nonce;

  /* Wait for a message.  We know what it should be.... */
  snprintf(reply1, BUFFER_SIZE, PROTOCOL_LN " STARTUP");
  if (NSrecv(sta, buffer, BUFFER_SIZE, 0) <= 0) {
    perror("Problem with recv, dropping connection");
    terminate = 1;
  }
  if (!terminate) {
    if (strncmp(reply1, buffer, strlen(reply1))) {
      printf("Unexpected string from admin server.\n");
      terminate = 1;
    }
  }
  /* Send our REGISTER MAP SERVER and our ports. */
  if (!terminate) {
    snprintf(buffer, BUFFER_SIZE, 
	     "REGISTER MAP SERVER\nUDP-PORT %d TCP-PORT %d",
	     ntohs(au.sin_port), ntohs(at.sin_port));
    if (send(sta, buffer, strlen(buffer), 0) < 0) {
      perror("Warning!  problem with send.");
      terminate = 1;
    }
  }
  /* Wait for nonce. */
  if (!terminate) {
    if (NSrecv(sta, buffer, BUFFER_SIZE, 0) <= 0) {
      perror("Problem with recv, dropping connection");
      terminate = 1;
    }
  }
  if (!terminate) {
    if (sscanf(buffer, "CHALLENGE %d", &nonce) != 1) {
      printf("Didn't receive nonce...\n");
      terminate = 1;
    }
  }
  /* Construct our reply. */
  if (!terminate) {
    token = make_token("REGISTER", nonce);
    snprintf(buffer, BUFFER_SIZE, 
	     "RESPONSE %s",
	     token);
    if (send(sta, buffer, strlen(buffer), 0) < 0) {
      perror("Warning!  problem with send.");
      terminate = 1;
    }
    free(token);
  }
  /* Wait for accept/reject. */
  /* There are only two likely replies.  ACCEPT or REJECT.  Construct
     both and see what we get back. */
  snprintf(reply1, BUFFER_SIZE, "ACCEPT MAP SERVER");
  snprintf(reply2, BUFFER_SIZE, "REJECT MAP SERVER");
  if (!terminate) {
    if (NSrecv(sta, buffer, BUFFER_SIZE, 0) <= 0) {
      perror("Problem with recv, dropping connection");
      terminate = 1;
    }
    if (!strncmp(buffer, reply1, strlen(reply1))) {
      /* Accept! */
      printf("Map server registration accepted.\n");
    } else if (!strncmp(buffer, reply2, strlen(reply1))) {
      /* Reject.... */
      printf("Map server registration rejected.\n");
      terminate = 1;
    } else {
      /* Eh?! */
      printf("Unexpected message from admin server.\n");
      terminate = 1;
    }
  }

  free(buffer);
  free(reply1);
  free(reply2);
  /* Don't need this socket anymore. */
  close(sta);
}

void wait_for_tiles(void) {
  char *             buffer                 = malloc(BUFFER_SIZE);
  char *             ok                     = malloc(BUFFER_SIZE);
  char *             reply                  = malloc(BUFFER_SIZE);
  int                drop;
  int                exit_flag              = 0;
  int                i,j;
  int                s;
  socklen_t          sockaddr_in_len;
  struct sockaddr_in a;
  tnode *            tcurr;

  /* Init neighbours. */
  for (i=0; i<N_TILES; i++) {
    for (j=0; j<N_TILES; j++) {
      tiles[i][j] = NULL;
    }
  }
  /* Our TCP port is open.  Block on accept.  Keep going round this
     until we're told that we're done. */
  snprintf(ok, BUFFER_SIZE, "OK");
  sockaddr_in_len = sizeof(struct sockaddr_in);
  while (!exit_flag) {
    drop = 0;
    s = accept(st, (struct sockaddr *) &a, &sockaddr_in_len);
    /* Send a message as given in the book. */
    snprintf(buffer, BUFFER_SIZE, PROTOCOL_LN "\nMAP");
    if (send(s, buffer, strlen(buffer), 0) < 0) {
      perror("Problem with send of initial message");
      exit(EXIT_FAILURE);
    }
    /* Wait for a message.  We know what it should be.... */
    snprintf(reply, BUFFER_SIZE, PROTOCOL_LN " ADMIN TILES");
    if (NSrecv(s, buffer, BUFFER_SIZE, 0) <= 0) {
      perror("Problem with recv, dropping connection");
      drop = 1;
    }
    if (!drop) {
      if (strncmp(reply, buffer, strlen(buffer))) {
	printf("Bogus token, dropping connection.\n");
	drop = 1;
      }
    }
    if (!drop) {
      /* Say OK. */
      if (send(s, ok, strlen(ok), 0) < 0) {
	perror("Problem with send");
	drop = 1;
      }
    }
    if (!drop) {
      /* Loop with each tile. */
      /* We terminate the loop when we see `DONE'. */
      snprintf(reply, BUFFER_SIZE, "DONE");
      while (!exit_flag) {
	if (NSrecv(s, buffer, BUFFER_SIZE, 0) <= 0) {
	  perror("Problem with recv for tile assignment, die");
	  exit(EXIT_FAILURE);
	}
	/* Sort out buffer. */
	if (!strncmp(reply, buffer, strlen(reply))) {
	  printf("Accepted tile assignments.\n");
	  exit_flag = 1;
	} else {
	  tcurr = malloc(sizeof(tnode));
	  tcurr->next = thead;
	  if (sscanf(buffer, "TILE\nXT %d\nYT %d", 
		     &(tcurr->x), &(tcurr->y)) == 2) {
	    if (check_tile(&(tcurr->x), &(tcurr->y))) {
	      thead = tcurr;
	    } else {
	      free(tcurr);
	    }
	  } else {
	    printf("Couldn't parse message `%s', expected tile assignment.\n",
		   buffer);
	    free(tcurr);
	  }
	  /* Send OK. */
	  if (send(s, ok, strlen(ok), 0) < 0) {
	    perror("Problem with send (ignored)");
	  }
	} /* if done */
      } /* while */
    }
    close(s);
  } /* while */
  free(ok);
  free(reply);
  close(st);
  /* Now need to request all neighbours. */
  tcurr = thead;
  while (tcurr) {
    snprintf(buffer, BUFFER_SIZE,
		 PROTOCOL_LN "\nNEIGHBOURS %d %d",
		 tcurr->x, tcurr->y);
    if (sendto(su, buffer, strlen(buffer), 0,
		      (struct sockaddr *) &(admin_a),
		      sizeof(admin_a)) <0) {
      perror("Problem sending neighbour request");
    }
    tcurr = tcurr->next;
  }
  free(buffer);
}

void running(void) {
  char              *buffer          = malloc(BUFFER_SIZE);
  char              *m_host          = malloc(BUFFER_SIZE);
  char              *p_host          = malloc(BUFFER_SIZE);
  char              *username        = malloc(BUFFER_SIZE);
  float              xi, yi;
  float              txi, tyi;
  int                add_nms;
  int                exit_flag = 0;
  int                m_port;
  int                p_port;
  int                xt, yt;
  int                xtp, ytp;
  int                txt, tyt;
  msnode *           nmscurr;
  pnode *            pcurr;
  snode *            scurr;
  socklen_t          sockaddr_in_len;
  struct hostent *   h;
  struct sockaddr_in a;

  sockaddr_in_len = sizeof(struct sockaddr_in);
  while (!exit_flag) {
    /* Listen only on our UDP socket forever. */
    if (NSrecvfrom(su, buffer, BUFFER_SIZE, 0,
		   (struct sockaddr *) &a, &sockaddr_in_len) <= 0) {
      /* Ignore it. */
      printf("Ignoring broken message from %s:%d.\n",
	     inet_ntoa(a.sin_addr), ntohs(a.sin_port));
    } else if (!from_other(&a)) {
      printf("Ignoring message from %s:%d (not client, admin or neighbour).\n",
	     inet_ntoa(a.sin_addr), ntohs(a.sin_port));
    } else {
      /* Handle a UDP message. */
      /* So what messages can the map server's UDP port accept? */
      /* From the admin server... */
      /* NEW PLAYER */
      if (sscanf(buffer, PROTOCOL_LN "\nNEW PLAYER %" Xstr(SHORT_BUFFER) "s %d %d %f %f %" Xstr(BUFFER_SIZE) "s %d", 
		 username, &xt, &yt, &xi, &yi, p_host, &p_port) == 7) {
	if (check_tile(&xt, &yt) && check_inner(&xi, &yi)) {
	  pthread_mutex_lock(&pmutex);
	  pcurr = add_player(username, xt, yt, xi, yi, xt, yt, xi, yi, p_host, p_port);
	  /* Send PLAYER UP back to the admin server... */
	  snprintf(buffer, BUFFER_SIZE,
		   PROTOCOL_LN "\nPLAYER UP %s",
		   pcurr->name);
	  if (sendto(su, buffer, strlen(buffer), 0, 
		     (struct sockaddr *) &(admin_a), 
		     sizeof(admin_a)) < 0) {
	    perror("Problem sending shutdown ack to admin server");
	  }
	  printf("Accepted player %s.\n", pcurr->name);
	  /* Need to tell player and neighbouring servers about this
	     player.  Generate a PLAYER MOVE message to their start
	     point. */
	  snprintf(buffer, BUFFER_SIZE,
		   PROTOCOL_LN "\nPLAYER MOVE %s %d %d %d %d %f %f",
		   pcurr->name, 
		   pcurr->xt, pcurr->yt,
		   pcurr->xt, pcurr->yt,
		   pcurr->xi, pcurr->yi);
	  pcurr->last_move = 0;
	  pthread_mutex_unlock(&pmutex);
	  send_pn(buffer, xt, yt, -1, -1);
	} else {
	  printf("Rejected coordinates in NEW PLAYER.\n");
	}
      }
      /* HANDLER */
      else if (sscanf(buffer, PROTOCOL_LN "\nHANDLER %d %d %" Xstr(SHORT_BUFFER) "s %d",
		      &xt, &yt, m_host, &m_port) == 4) {
	if (check_tile(&xt, &yt)) {
	  /* If we've seen any before, only add this if it's new.
	     Don't add entries if we know we handle this tile. */
	  if (handle_tile(xt, yt)) {
	    add_nms = 0;
	  } else if (nmshead == NULL) {
	    add_nms = 1;
	  } else {
	    add_nms = 1;
	    nmscurr = nmshead;
	    while (nmscurr && add_nms) {
	      if ((!strcmp(m_host, inet_ntoa(nmscurr->udp.sin_addr)))
		  && (m_port == ntohs(nmscurr->udp.sin_port))) {
		tiles[xt][yt] = nmscurr;
		add_nms = 0;
	      }
	      nmscurr = nmscurr->next;
	    }
	  }
	  if (add_nms) {
	    if ((h = gethostbyname(m_host)) == NULL)
	      { 
		perror("Could not get host details.");
		exit(EXIT_FAILURE);
	      }
	    nmscurr = malloc(sizeof(msnode));
	    nmscurr->udp.sin_family = AF_INET;
	    memcpy(&(nmscurr->udp.sin_addr.s_addr), h->h_addr, h->h_length);
	    nmscurr->udp.sin_port = htons(m_port);
	    nmscurr->next = nmshead;
	    nmshead = nmscurr;
	    tiles[xt][yt] = nmscurr;
	  }
	} else {
	  printf("Rejected coordinates in HANDLER.\n");
	}
      }
      /* SHUTDOWN */
      else if (!strcmp(buffer, PROTOCOL_LN "\nSHUTDOWN")) {
	printf("Shutting down map server...\n");
	exit_flag = 1;
	/* Loop round our list of players. */
	snprintf(buffer, BUFFER_SIZE,
		   PROTOCOL_LN "\nSHUTDOWN");
	send_p(buffer, -1, -1, -1, -1);
	/* Send shutdown ack */
	snprintf(buffer, BUFFER_SIZE,
		 PROTOCOL_LN "\nSHUTDOWN ACK");
	if (sendto(su, buffer, strlen(buffer), 0, 
		   (struct sockaddr *) &(admin_a), 
		   sizeof(admin_a)) < 0) {
	  perror("Problem sending shutdown ack to admin server");
	}
	
      } 
      /* From the players...  */
      /* MOVE */
      else if (sscanf(buffer, PROTOCOL_LN "\nMOVE %" Xstr(SHORT_BUFFER) "s %d %d %f %f",
		      username, &xt, &yt, &xi, &yi) == 5) {
	if (check_tile(&xt, &yt) && check_inner(&xi, &yi)) {
	  /* Update the destination position. */
	  pthread_mutex_lock(&pmutex);
	  pcurr = match_player(username);
	  if (pcurr) {
	    pcurr->txt = xt;
	    pcurr->tyt = yt;
	    pcurr->txi = xi;
	    pcurr->tyi = yi;
	  }
	  pthread_mutex_unlock(&pmutex);
	} else {
	  printf("Rejected coordinates in MOVE.\n");
	}
      } 
      /* FIRE */
      else if (sscanf(buffer, PROTOCOL_LN "\nFIRE %" Xstr(SHORT_BUFFER) "s %d %d %f %f",
		      username, &xt, &yt, &xi, &yi) == 5) {
	if (check_tile(&xt, &yt) && check_inner(&xi, &yi)) {
	  pthread_mutex_lock(&pmutex);
	  pcurr = match_player(username);
	  if (pcurr) {
	    add_shot(strdup(username), 
		     pcurr->xt, pcurr->yt, pcurr->xi, pcurr->yi,
		     xt, yt, xi, yi);
	  }
	  pthread_mutex_unlock(&pmutex);
	} else {
	  printf("Rejected coordinates in FIRE.\n");
	}
      } 
      /* QUIT */
      else if (sscanf(buffer, PROTOCOL_LN "\nQUIT %" Xstr(SHORT_BUFFER) "s",
		      username) == 1) {
	pthread_mutex_lock(&pmutex);
	pcurr = match_player(username);
	if (pcurr) {
	  /* Tell the admin server, players and neighbours that this
	     player has gone. */
	  snprintf(buffer, BUFFER_SIZE, 
		   PROTOCOL_LN "\nREMOVE PLAYER %s %d %d",
		   username, pcurr->xt, pcurr->yt);
	  if (sendto(su, buffer, strlen(buffer), 0, 
		     (struct sockaddr *) &admin_a, 
		     sizeof(admin_a)) < 0) {
	    perror("Warning!  problem with sendto.  Continuing anyway.");
	  }
	  send_pn(buffer, -1, -1, -1, -1);
	  /* Remove from our list. */
	  delete_player(pcurr); 
	  printf("Player %s has quit.\n", username);
	}
	pthread_mutex_unlock(&pmutex);
      } 
      /* From other map servers... */
      /* PLAYER MOVE */
      else if (sscanf(buffer, PROTOCOL_LN "\nPLAYER MOVE %" Xstr(SHORT_BUFFER) "s %d %d %d %d %f %f",
		      username, &xtp, &ytp, &xt, &yt, &xi, &yi) == 7) {
	if (check_tile(&xtp, &ytp) && check_tile(&xt, &yt) && check_inner(&xi, &yi)) {
	  /* Tell our players. */
	  send_p(buffer, xt, yt, xtp, ytp);
	} else {
	  printf("Rejected coordinates in PLAYER MOVE.\n");
	}
      } 
      /* SHOT */
      else if (sscanf(buffer, PROTOCOL_LN "\nSHOT %" Xstr(SHORT_BUFFER) "s %d %d %d %d %f %f",
		      username, &xtp, &ytp, &xt, &yt, &xi, &yi) == 7) {
	if (check_tile(&xtp, &ytp) && check_tile(&xt, &yt) && check_inner(&xi, &yi)) {	
	  /* Tell our players. */
	  send_p(buffer, xt, yt, xtp, ytp);
	} else {
	  printf("Rejected coordinates in PLAYER MOVE.\n");
	}
      } 
      /* SEND PLAYER */
      else if (sscanf(buffer, PROTOCOL_LN "\nSEND PLAYER %" Xstr(SHORT_BUFFER) "s %d %d %f %f %d %d %f %f %s %d",
		      username, &xt, &yt, &xi, &yi, &txt, &tyt, &txi, &tyi, p_host, &p_port) == 11) {
	if (check_tile(&xt, &yt)  && check_inner(&xi, &yi) && check_tile(&txt, &tyt)  && check_inner(&txi, &tyi)) {
	  /* If we already have this player, delete it and add again. */
	  pthread_mutex_lock(&pmutex);
	  pcurr = match_player(username);
	  if (pcurr) {
	    delete_player(pcurr);
	  }
	  add_player(username, xt, yt, xi, yi, txt, tyt, txi, tyi, p_host, p_port);
	  pthread_mutex_unlock(&pmutex);
	  /* Send ACCEPT. */
	  snprintf(buffer, BUFFER_SIZE, 
		   PROTOCOL_LN "\nACCEPT PLAYER %s",
		   username);
	  if (sendto(su, buffer, strlen(buffer), 0, 
		     (struct sockaddr *) &a, 
		     sizeof(a)) < 0) {
	    perror("Warning!  problem with sendto (accept player -> map).  Continuing anyway.");
	  }
	  printf("Accepted player %s from another map server.\n", username);
	} else {
	  printf("Rejected coordinates in SEND PLAYER.\n");
	}
      } 
      /* SEND SHOT */
      else if (sscanf(buffer, PROTOCOL_LN "\nSEND SHOT %" Xstr(SHORT_BUFFER) "s %d %d %f %f %d %d %f %f",
		      username, &xt, &yt, &xi, &yi, &txt, &tyt, &txi, &tyi) == 9) {
	if (check_tile(&xt, &yt)  && check_inner(&xi, &yi) && check_tile(&txt, &tyt)  && check_inner(&txi, &tyi)) {
	  /* If we already have this shot, delete it and add again. */
	  pthread_mutex_lock(&pmutex);
	  scurr = match_shot(username);
	  if (scurr) {
	    delete_shot(scurr);
	  }
	  add_shot(username, xt, yt, xi, yi, txt, tyt, txi, tyi);
	  pthread_mutex_unlock(&pmutex);
	  /* Send ACCEPT. */
	  snprintf(buffer, BUFFER_SIZE, 
		   PROTOCOL_LN "\nACCEPT SHOT %s",
		   username);
	  if (sendto(su, buffer, strlen(buffer), 0, 
		     (struct sockaddr *) &a, 
		     sizeof(a)) < 0) {
	    perror("Warning!  problem with sendto (accept shot -> map).  Continuing anyway.");
	  }
	  printf("Accepted shot from player %s from another map server.\n", username);
	} else {
	  printf("Rejected coordinates in SEND SHOT.\n");
	}
      } 
      /* ACCEPT PLAYER */
      else if (sscanf(buffer, PROTOCOL_LN "\nACCEPT PLAYER %" Xstr(SHORT_BUFFER) "s",
		      username) == 1) {
	/* If it's one of ours, remove it. */
	pcurr = match_player(username);
	if (pcurr) {
	  delete_player(pcurr);
	  printf("Player %s is now handled by another map server.\n", username);
	}
      } 
      /* ACCEPT SHOT */
      else if (sscanf(buffer, PROTOCOL_LN "\nACCEPT SHOT %" Xstr(SHORT_BUFFER) "s",
		      username) == 1) {
	/* If it's one of ours, remove it. */
	scurr = match_shot(username);
	if (scurr) {
	  delete_shot(scurr);
	  printf("Shot from player %s is now handled by another map server.\n", username);
	}
      } 
      /* REMOVE PLAYER */
      else if (sscanf(buffer, PROTOCOL_LN "\nREMOVE PLAYER %" Xstr(SHORT_BUFFER) "s %d %d",
		      username, &xt, &yt) == 3) {
	if (check_tile(&xt, &yt)) {
	  /* Tell our players. */
	  send_p(buffer, xt, yt, -1, -1);
	  /* Remove the player. */
	  if ((pcurr = match_player(username))) {
	    delete_player(pcurr);
	  }
	  /* Remove their shots as well. */
	  if ((scurr = match_shot(username))) {
	    delete_shot(scurr);
	  }
	} else {
	  printf("Rejected coordinates in REMOVE PLAYER.\n");
	}
      } 
      /* REMOVE SHOT */
      else if (sscanf(buffer, PROTOCOL_LN "\nREMOVE SHOT %" Xstr(SHORT_BUFFER) "s %d %d",
		      username, &xt, &yt) == 3) {
	if (check_tile(&xt, &yt)) {
	  /* Tell our players. */
	  send_p(buffer, xt, yt, -1, -1);
	  /* Remove the shot. */
	  if ((scurr = match_shot(username))) {
	    delete_shot(scurr);
	  }
	} else {
	  printf("Rejected coordinates in REMOVE SHOT.\n");
	}
      } 
      /* PLAYER DIED */
      else if (sscanf(buffer, PROTOCOL_LN "\nPLAYER DIED %" Xstr(SHORT_BUFFER) "s %d %d",
		      username, &xt, &yt) == 3) {
	if (check_tile(&xt, &yt)) {
	  /* Tell our players. */
	  send_p(buffer, xt, yt, -1, -1);
	} else {
	  printf("Rejected coordinates in PLAYER DIED.\n");
	}
      } 
      /* No match? */
      else {
	printf("Ignoring unmatched message from %s:%d.\n",
	       inet_ntoa(a.sin_addr), ntohs(a.sin_port));
	printf("  Message: `%s'\n", buffer);
      }
    }
  }
}

void *periodic_move(void *param) {
  char            *buffer      = malloc(BUFFER_SIZE);
  float            xd, yd, d;
  float            xr0, yr0;
  float            xr1, yr1;
  float            xr2, yr2;
  float            ps,ss;
  float            scale;
  float            nxi, nyi;
  int              bang;
  int              nxt, nyt;
  pnode           *pcurr;
  pnode           *pnext;
  snode           *scurr;
  snode           *snext;
  struct timespec  ts;

  /* This runs in a separate thread.  Every period, we wake up
     and move all mobile players and shots. */
  /* The distance players and shots can travel each time slice.  Note
     that we are not dead-reckoning here.  It takes time to do each
     calculation, so everything will move slightly slowly. */
  ps = PLAYERSPEED * (float) MOVEPERIOD / 1000000000.0;
  ss = SHOTSPEED * (float) MOVEPERIOD / 1000000000.0;
  /* Time-slice set up. */
  ts.tv_sec = 0;
  ts.tv_nsec = MOVEPERIOD;
  while (1) {
    /* Lock the mutex. */
    pthread_mutex_lock(&pmutex);
    /* For each player... */
    pcurr = phead;
    while (pcurr) {
      /* Move player. */
      xr0 = to_real(pcurr->xt, pcurr->xi);
      yr0 = to_real(pcurr->yt, pcurr->yi);
      xr1 = to_real(pcurr->txt, pcurr->txi);
      yr1 = to_real(pcurr->tyt, pcurr->tyi);
      xd = get_dir(xr0, xr1);
      yd = get_dir(yr0, yr1);
      d = distance(xd, yd);
      if (d > EPSILON) {
	if (d > ps) {
	  /* Too far this slice.  Reduce it to the maximum. */
	  scale = ps / d;
	  xd = xd * scale;
	  yd = yd * scale;
	}
	/* Do the move. */
	xr2 = xr0 + xd;
	yr2 = yr0 + yd;
	/* Check bounds. */
	if (xr2 < 0.0) { xr2 = xr2 + (float) (N_TILES * TILE_LENGTH); }
	if (yr2 < 0.0) { yr2 = yr2 + (float) (N_TILES * TILE_LENGTH); }
	if (xr2 >= (float) (N_TILES * TILE_LENGTH))
	  { xr2 = xr2 - (float) (N_TILES * TILE_LENGTH); }
	if (yr2 >= (float) (N_TILES * TILE_LENGTH))
	  { yr2 = yr2 - (float) (N_TILES * TILE_LENGTH); }
	/* Convert back. */
	nxt = to_tile(xr2);
	nyt = to_tile(yr2);
	nxi = to_inner(xr2);
	nyi = to_inner(yr2);
	/* Send the message... */
	snprintf(buffer, BUFFER_SIZE, 
		 PROTOCOL_LN "\nPLAYER MOVE %s %d %d %d %d %f %f",
		 pcurr->name, pcurr->xt, pcurr->yt, nxt, nyt, nxi, nyi);
	send_pn(buffer, pcurr->xt, pcurr->yt, nxt, nyt);
	/* Does the player move out to a tile we don't control? */
	if (tiles[nxt][nyt]) {
	  /* Create a SEND PLAYER message. */
	  snprintf(buffer, BUFFER_SIZE, 
		   PROTOCOL_LN "\nSEND PLAYER %s %d %d %f %f %d %d %f %f %s %d",
		   pcurr->name, 
		   nxt, nyt, nxi, nyi, 
		   pcurr->txt, pcurr->tyt, pcurr->txi, pcurr->tyi, 
		   inet_ntoa(pcurr->udp.sin_addr), 
		   ntohs(pcurr->udp.sin_port));
	  if (sendto(su, buffer, strlen(buffer), 0, 
		     (struct sockaddr *) &(tiles[nxt][nyt]->udp), 
		     sizeof(tiles[nxt][nyt]->udp)) < 0) {
	    perror("Warning!  problem with sendto (send player -> map).  Continuing anyway.");
	  }
	  /* Tell the player to change server. */
	  snprintf(buffer, BUFFER_SIZE, 
		   PROTOCOL_LN "\nCHANGE SERVER %s %d",
		   inet_ntoa(tiles[nxt][nyt]->udp.sin_addr), 
		   ntohs(tiles[nxt][nyt]->udp.sin_port));
	  if (sendto(su, buffer, strlen(buffer), 0, 
		     (struct sockaddr *) &(pcurr->udp), 
		     sizeof(pcurr->udp)) < 0) {
	    perror("Warning!  problem with sendto (send player -> player).  Continuing anyway.");
	  }
	}
	/* Update local record. */
	pcurr->xt = nxt;
	pcurr->yt = nyt;
	pcurr->xi = nxi;
	pcurr->yi = nyi;
	pcurr->last_move = 0;
      } else {
	/* This one isn't moving.  Should we send a move message anyway? */
	pcurr->last_move = pcurr->last_move + MOVEPERIOD;
	if (pcurr->last_move > REFRESHPERIOD) {
	  snprintf(buffer, BUFFER_SIZE, 
		   PROTOCOL_LN "\nPLAYER MOVE %s %d %d %d %d %f %f",
		   pcurr->name, pcurr->xt, pcurr->yt, 
		   pcurr->xt, pcurr->yt, pcurr->xi, pcurr->yi);
	  send_pn(buffer, pcurr->xt, pcurr->yt, nxt, nyt);
	  pcurr->last_move = 0;
	}
	   
      } /* if d>EPSILON */
      /* Next! */
      pcurr = pcurr->next;
    }
    /* For each shot... */
    scurr = shead;
    while (scurr) {
      snext = scurr->next; /* Because we might delete scurr.... */
      /* Move shot. */
      xr0 = to_real(scurr->xt, scurr->xi);
      yr0 = to_real(scurr->yt, scurr->yi);
      xr1 = to_real(scurr->txt, scurr->txi);
      yr1 = to_real(scurr->tyt, scurr->tyi);
      xd = get_dir(xr0, xr1);
      yd = get_dir(yr0, yr1);
      d = distance(xd, yd);
      if (d > EPSILON) {
	if (d > ps) {
	  /* Too far this slice.  Reduce it to the maximum. */
	  scale = ps / d;
	  xd = xd * scale;
	  yd = yd * scale;
	}
	/* Do the move. */
	xr2 = xr0 + xd;
	yr2 = yr0 + yd;
	/* Check bounds. */
	if (xr2 < 0.0) { xr2 = xr2 + (float) (N_TILES * TILE_LENGTH); }
	if (yr2 < 0.0) { yr2 = yr2 + (float) (N_TILES * TILE_LENGTH); }
	if (xr2 >= (float) (N_TILES * TILE_LENGTH))
	  { xr2 = xr2 - (float) (N_TILES * TILE_LENGTH); }
	if (yr2 >= (float) (N_TILES * TILE_LENGTH))
	  { yr2 = yr2 - (float) (N_TILES * TILE_LENGTH); }
	/* Convert back. */
	nxt = to_tile(xr2);
	nyt = to_tile(yr2);
	nxi = to_inner(xr2);
	nyi = to_inner(yr2);
	/* Send the message... */
	snprintf(buffer, BUFFER_SIZE, 
		 PROTOCOL_LN "\nSHOT %s %d %d %d %d %f %f",
		 scurr->name, scurr->xt, scurr->yt, nxt, nyt, nxi, nyi);
	send_pn(buffer, scurr->xt, scurr->yt, nxt, nyt);
	/* Does the shot move out to a tile we don't control? */
	if (tiles[nxt][nyt]) {
	  /* Create a SEND SHOT message. */
	  snprintf(buffer, BUFFER_SIZE, 
		   PROTOCOL_LN "\nSEND SHOT %s %d %d %f %f %d %d %f %f",
		   scurr->name, 
		   nxt, nyt, nxi, nyi, 
		   scurr->txt, scurr->tyt, scurr->txi, scurr->tyi);
	  if (sendto(su, buffer, strlen(buffer), 0, 
		     (struct sockaddr *) &(tiles[nxt][nyt]->udp), 
		     sizeof(tiles[nxt][nyt]->udp)) < 0) {
	    perror("Warning!  problem with sendto (send shot -> map).  Continuing anyway.");
	  }
	}
	/* Update local record. */
	scurr->xt = nxt;
	scurr->yt = nyt;
	scurr->xi = nxi;
	scurr->yi = nyi;
      } /* if d>EPSILON */
      /* Shots always move, so no need to refresh non-moving shots. */

      /* Proximity fuses on shots, or if the shot reaches its
	 destination -- anyone dies? */
      bang = 0;
      /* At destination, er, target? */
      if (distance8(scurr->xt, scurr->yt, scurr->xi, scurr->yi,
		    scurr->txt, scurr->tyt, scurr->txi, scurr->tyi)
	  < EPSILON) {
	bang = 1;
      } else {
	/* Do any players set it off? */
	pcurr = phead;
	while (pcurr) {
	  if (strcmp(pcurr->name, scurr->name)) {
	    /* Shooter doesn't set off own shot. */
	    if (distance8(scurr->xt, scurr->yt, scurr->xi, scurr->yi,
			  pcurr->xt, pcurr->yt, pcurr->xi, pcurr->yi)
		< PROXIMITY) {
	      bang = 1;
	    }
	  }
	  pcurr = pcurr->next;
	}
      }
      if (bang) {
	printf("Shot from player %s BANG!\n", scurr->name);
	/* Create a REMOVE SHOT message. */
	snprintf(buffer, BUFFER_SIZE, 
		 PROTOCOL_LN "\nREMOVE SHOT %s %d %d",
		 scurr->name, scurr->xt, scurr->yt);
	send_pn(buffer, scurr->xt, scurr->yt, -1, -1);
	/* Which players are toast? */
	pcurr = phead;
	while (pcurr) {
	  pnext = pcurr->next;
	  if (distance8(scurr->xt, scurr->yt, scurr->xi, scurr->yi,
			pcurr->xt, pcurr->yt, pcurr->xi, pcurr->yi)
	      < BLAST) {
	    /* This player is dead. */
	    printf("Player %s blown up by shot from %s!\n",
		   pcurr->name, scurr->name);
	    snprintf(buffer, BUFFER_SIZE, 
		     PROTOCOL_LN "\nPLAYER DIED %s %d %d",
		     pcurr->name, pcurr->xt, pcurr->yt);
	    send_pn(buffer, pcurr->xt, pcurr->yt, -1, -1);
	    /* And tell the admin server. */
	    if (sendto(su, buffer, strlen(buffer), 0, 
		       (struct sockaddr *) &admin_a, sizeof(admin_a)) <0) {
	      perror("Warning!  problem with sendto (player died -> admin).  Continuing anyway.");
	    }
	    /* Add remove it from our records. */
	    delete_player(pcurr);
	  }
	  pcurr = pnext;
	}
	/* Remove the shot from our records. */
	delete_shot(scurr);
      } /* if bang */

      /* Next! */
      scurr = snext;
    }
     /* Unlock the mutex. */
    pthread_mutex_unlock(&pmutex);
    /* Sleep. */
    nanosleep(&ts, NULL);
  }
} 

void send_p(char *buffer, int xt, int yt, int xtp, int ytp) {
  /* Send to all players. */
  /* Only send to players who can see tile xt,yt, unless
     (xt,yt)=(-1,-1). */
  pnode   *pcurr;
  int     tell;
  
  pthread_mutex_lock(&pmutex);
  pcurr = phead;
  while (pcurr) {
    tell = 0;
    if ((xt == -1) && (yt == -1)) {
      tell = 1;
    } else {
      if (local_tile(pcurr->xt, pcurr->yt, xt, yt)) {
	tell = 1;
      } else if ( (xt != -1) 
		  && (yt != -1)
		  && ((xt != xtp) || (yt != ytp))  ) {
	if (local_tile(pcurr->xt, pcurr->yt, xtp, ytp)) {
	  tell = 1;
	}
      }
    }
    if (tell) {
      if (sendto(su, buffer, strlen(buffer), 0, 
		 (struct sockaddr *) &(pcurr->udp), 
		 sizeof(pcurr->udp)) < 0) {
	perror("Warning!  problem with sendto.  Continuing anyway.");
      }
    }
    pcurr=pcurr->next;
  }
  pthread_mutex_unlock(&pmutex);
}

void send_pn(char *buffer, int xt, int yt, int xtp, int ytp) {
  /* Send to all players and neighbouring map servers. */
  msnode  *nmscurr;
  
  nmscurr = nmshead;
  while (nmscurr) {
    if (sendto(su, buffer, strlen(buffer), 0, 
	       (struct sockaddr *) &(nmscurr->udp), 
	       sizeof(nmscurr->udp)) < 0) {
      perror("Warning!  problem with sendto.  Continuing anyway.");
    }
    nmscurr=nmscurr->next;
  }

  send_p(buffer, xt, yt, xtp, ytp);
}

int from_other(struct sockaddr_in *a) {
  msnode *mscurr;
  pnode  *pcurr;

  /* Message from admin? */
  if ((a->sin_addr.s_addr==admin_a.sin_addr.s_addr)
      && (ntohs(a->sin_port)==ntohs(admin_a.sin_port))) {
    return 1;
  }
  /* Message from neighbour? */
  mscurr = nmshead;
  while (mscurr) {
    if ((a->sin_addr.s_addr==mscurr->udp.sin_addr.s_addr)
	&& (ntohs(a->sin_port)==ntohs(mscurr->udp.sin_port))) {
      return 1;
    }
    mscurr = mscurr->next;
  }
  /* Message from player? */
  pthread_mutex_lock(&pmutex);
  pcurr = phead;
  while (pcurr) {
    if ((a->sin_addr.s_addr==pcurr->udp.sin_addr.s_addr)
	&& (ntohs(a->sin_port)==ntohs(pcurr->udp.sin_port))) {
      /* Got a match.  Return the pointer. */
      pthread_mutex_unlock(&pmutex);
      return 1;
    }
    pcurr = pcurr->next;
  }
  pthread_mutex_unlock(&pmutex);
  /* Failed to match. */
  return 0;
}

/* Return true if we handle tile xt, yt. */
int handle_tile(int xt, int yt) {
  tnode *tcurr;

  tcurr = thead;
  while (tcurr) {
    if (tcurr->x == xt && tcurr->y == yt) {
      return 1;
    }
    tcurr = tcurr->next;
  }
  return 0;
}
