import java.lang.*;
import java.io.*;

class RunPair {
  static boolean quiet = false;

  public static boolean isRunning(Process process) {
    if (process == null) {
      return false;
    }
    try {
      process.exitValue();
      return false;
    } catch(IllegalThreadStateException e) {
      return true;
    }
  }

  public static void terminateProcess(Process process, String name) {
    if (process != null && isRunning(process)) {
      if (!quiet) {
        System.out.println("stop process " + name);
      }
      process.destroy();
    }
  }

  public static boolean fileExists(String fileName) {
    return new File(fileName).exists();
  }

  public static void main(String[] args) throws Exception {
    
    if (args.length < 2) {
      System.err.println("Runs interaction with your hedgehog");
      System.err.println("Usage: <interactor.exe> <executable-file-with-hedgehog-algo> [-q]");
      System.err.println("  -q = disable debug output");
      return;
    }

    for (int i = 1; i < args.length; i++) {
      if (args[i].equals("-q")) {
        quiet = true;
      }
    }

    Process p1 = new ProcessBuilder(args[0]).start();
    Process p2 = new ProcessBuilder(args[1]).start();

    if (p1 == null || p2 == null) {
      System.err.println("Can not launch processes INTERACT = " + (p1 != null) + ", SOLUTION = " + (p2 != null));
      terminateProcess(p1, "interact");
      terminateProcess(p2, "solution");
      return;
    }

    InputStream p1_in = p1.getInputStream();
    OutputStream p1_out = p1.getOutputStream();
	InputStream p1_err = p1.getErrorStream();
	
    InputStream p2_in = p2.getInputStream();
    OutputStream p2_out = p2.getOutputStream();

    while ((isRunning(p1) && isRunning(p2)) && System.in.available() == 0) {
      if (p1_in.available() > 0) {
        int next = p1_in.read();
        p2_out.write(next);
        p2_out.flush();
        if (!quiet) {
          System.out.print((char)next);
        }
      }
	  while (p1_err.available() > 0) {
		int c = p1_err.read();
		System.err.print((char) c);
	  }
      if (p2_in.available() > 0) {
        int next = p2_in.read();
        p1_out.write(next);
        p1_out.flush();
        if (!quiet) {
          System.out.print((char)next);
        }
      }
//      Thread.sleep(100);
    }
    Thread.sleep(100);
    terminateProcess(p1, "Interact");
    terminateProcess(p2, "solution");
  }
}
