import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

public class GrnvsTcpClient {
	private static BufferedReader in;
	private static BufferedWriter out;
	private static Socket socket;

	public static void main(String[] args) {
		if (args.length != 2) {
			System.err.println("Usage: java GrnvsTcpClient <host> <port>");
			System.exit(1);
		}
		// The communication will get handled by the communicate-method...
		communicate(args[0], Integer.parseInt(args[1]));
	}

	private static void communicate(String host, int port) {
		try {
			/*
			 * Create the socket and the according buffers...
			 */

			socket = new Socket(host, port);
			in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
			/*
			 * Implement the protocol... Send only ONE Name per session, so if
			 * your team has two members run the code twice, once with each of
			 * your names... Don't forget to check if the submission
			 * succeeded...
			 */
			System.out.println(in.readLine()); // Greetings
			say("HELLO"); // say HELLO
			
			// to do...
			// discard blurb
			hear();
			hear();
			
			// first map... oh wait, map only works ok in Scala
			int[] numbers = {0, 0, 0};
			for (int i = 0; i < 3; i++) {
				String line = in.readLine();
				numbers[i] = Integer.parseInt(line.trim());
			}
			
			// then reduce... oh wait, that also only works in Scala
			int sum = 0;
			for (int i = 0; i < 3; i++) {
				sum += numbers[i];
			}
			say(String.valueOf(sum));
			
			// discard more blurb
			if (!hear().equals("Please send your Teamletter...")) {
				System.err.println("Sum didn't match");
				return;
			}
			say("G");
			hear();
			say("Kerscher Michael");
			
			// kthxbai
			out.close();
			in.close();
			socket.close();
		} catch (IOException e) {
			System.err.println(e.toString());
			System.exit(1);
		}

	}
	
	private static String hear() {
		try {
			String read = in.readLine();
			System.out.println(read);
			return read;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	private static void say(String msg) {
		/*
		 * We have to do a lot of sending to the Server so we summed this up
		 * here...
		 */
		try {
			System.out.println("--> " + msg); // Output locally for debug...
			out.write(msg + "\r\n"); // Send to the receiving server
			                         // socket...
			out.flush(); // Send data out now and do not wait until the send
			             // buffer is full...
		} catch (IOException e) {
			System.err.println(e.toString());
		}
	}
}

