#include "h9.h"

int launch_game(struct termios *tio, struct winsize *ws)
{
  int status;
  pid_t pid;
  int pty, tty, r;
  char *pts, buf[K];

  if ((pty = posix_openpt(O_RDWR | O_NOCTTY)) < 0) {
    perror("openpt");
    exit(1);
  }
  if (grantpt(pty) < 0) {
    perror("grantpt");
    exit(1);
  }
  if (unlockpt(pty) < 0) {
    perror("unlockpt");
    exit(1);
  }
  if ((pts = ptsname(pty)) == NULL) {
    perror("ptsname");
    exit(1);
  }
  pid = fork();
  if (pid < 0) {
    perror("fork");
    exit(1);
  }
  if (pid == 0) {
    if ((tty = open(pts, O_RDWR)) < 0) {
      perror("slave open");
      exit(1);
    }
    dup2(tty, 0);
    dup2(tty, 1);
    dup2(tty, 2);
    close(tty);
    if (tcsetattr(0, TCSANOW, tio) < 0) {
      perror("tcsetattr");
    }
    if (ioctl(0, TIOCSWINSZ, ws) < 0) {
      fprintf(stderr,"winsize\n");
    }
    for(;;) {
      pid = fork();
      if (pid < 0) {
	perror("fork");
	sleep(10);
	continue;
      }
      if (pid) waitpid(pid, &status, 0);
      else execlp("arogue", "arogue", NULL);
    }
  }
  return pty;
}
