// -------------------------------------------------------

import java.net.*;
import java.io.*;

public class Guesser extends NetworkServer {
  public static void main(String[] args) {
    int port = 5555;
    if (args.length > 0)
      port = Integer.parseInt(args[0]);
    Guesser server = new Guesser(port);
    server.listen();
  }

  int num = 50; 

  public Guesser (int port) {
    super(port, 1);
    num = randomInt(100) + 1;
  }

  protected void handleConnection(Socket server) throws IOException {
    SocketUtil s = new SocketUtil(server);
    DataInputStream in = s.getDataStream();
    PrintStream out = s.getPrintStream();
    int guess = -1;
    int lower = 1;
    int higher = 100; 
    out.println(bounds(lower, higher));
    while (guess != num) {
      String input = in.readLine();
      System.out.println("Input was <" + input + ">");
      guess = Integer.parseInt(input);
      if (guess < num) {
        lower = Math.max(lower, guess);
        out.println("Too low!  " + bounds(lower, higher));
      } else if (guess > num) {
        higher = Math.min(higher, guess); 
        out.println("Too high!  " + bounds(lower, higher));
      }
    }
    out.println("Congratulations, you guessed the number!");
    server.close();
  }
  public String bounds (int lo, int hi) {
    return "Enter a guess between " + lo + " and " + hi;
  }
  public static int randomInt (int n) {
    int value = (int) (Math.random() * n) ;
    return value ;
  }
}
