#include <limits.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main(int argc,char *argv[]) {
  int n;
  pid_t pid;
  char arg[10];
  int p[2];
  int p2[2];
  sscanf(argv[1],"%d",&n);
  pipe(p);
  if (fork()==0) {
    close(p[0]);
    dup2(p[1],STDOUT_FILENO);
    close(p[1]);
    execlp("elimine","elimine","1",NULL);
    exit(1);
  }
  close(p[1]);
  for (int i=2; i<=n; i++) {
    pipe(p2);
    switch(pid = fork()) {
    case 0:
      sprintf(arg,"%d",i);
      dup2(p[0],STDIN_FILENO);
      close(p[0]);
      close(p2[0]);
      dup2(p2[1],STDOUT_FILENO);
      close(p2[1]);
      execlp("elimine","elimine",arg,NULL);
      exit(1);
      break;
    case -1:
      fprintf(stderr,"oups\n");
      break;
    default:
      close(p2[1]);
      p[0] = p2[0];
      p[1] = p2[1];
      break;
    }
  }
  if (fork()==0) {
    dup2(p[0],STDIN_FILENO);
    close(p[0]);
    execlp("elimine","elimine","0",NULL);
    exit(1);
  }
  for (int i=1; i<=n; i++) {
    waitpid(-1,NULL,0);
  }
  exit(0);
}