#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>

#include <sys/socket.h>
#include <sys/un.h>

#define NSTRS 1
#define ADDRESS   "mysocket"
#define MAXCLI      10
#define NUMLOOP 20000

static  double d;
static  int it;

/*
 * String we send to client.
 */
char *strs[NSTRS] = {
  "S"
};

void
compute_long(int iteration){

  int j, i;

  for(j=0; j < NUMLOOP ; j++){
    for(i=0; i < iteration; i++){
      d = iteration;
      d = d*30;
      d = d/10.0;
      d = d/3.1;
      it = iteration;
      it = it - it*it;
      it = it/(iteration+1);
    }
    //usleep(1);
  }
}




int main(int argc, char **argv){
  char c;
  fd_set rfds;
  int retval, len, numcli, numipc, s, fromlen;
  int ns[MAXCLI], maxns = 0;
  struct sockaddr_un saun, fsaun;
  FILE *fp;
  int NUMIPC, NUMCLI;

  int count = 0;

  
  if(argc != 3){
    printf("server-select #client #total_IPC\n");
    return 0;
  }
  NUMCLI = atoi(argv[1]);
  NUMIPC = atoi(argv[2]);

  //printf("*NUMCLI %d, NUMIPC %d\n", NUMCLI, NUMIPC);
  
  if((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0){
    perror("server: socket");
    exit(1);
  }

  saun.sun_family = AF_UNIX;
  strcpy(saun.sun_path, ADDRESS);

  unlink(ADDRESS);
  len = sizeof(saun.sun_family) + strlen(saun.sun_path);
  if(bind(s, &saun, len) <0 ){
    perror("server: bind");
    exit(1);
  }

  if(listen(s, 5) < 0){
    perror("server: listen");
    exit(1);
  }
  
  /*
   * here I will assume lowest number is the reserved client...
   */ 
  for(numcli = 0 ; numcli < NUMCLI; numcli++){
    if((ns[numcli] = accept(s, &fsaun, &fromlen)) < 0){
      perror("server: accept");
      exit(1);
    }
  }


  for( numipc = 0 ;  numipc < NUMIPC; numipc++){

    /* Watch stdin (fd 0) */
    FD_ZERO(&rfds);

    /*printf("%d:  ns=", count);*/
    for(numcli=0; numcli < NUMCLI; numcli++){
      if(ns[numcli] > maxns)
	maxns = ns[numcli];
      /*printf("%d ", ns[numcli]);*/
      FD_SET(ns[numcli], &rfds);
    }

    sleep(1);
    retval = select(maxns+1, &rfds, NULL, NULL, NULL);
    /*printf("retval = %d ", retval);*/
    
    for(numcli=0; numcli < NUMCLI; numcli++){
      if(FD_ISSET(ns[numcli], &rfds))
	break;
    }
    //printf("choose = %d\n", numcli);
    fp = fdopen(ns[numcli], "r");
    c = fgetc(fp);
    compute_long(200);
    send(ns[numcli], strs[0], strlen(strs[0]), 0);
    count++;
  }
  exit(0);
}
