#include "stdint.h"
#include "socket.h"
#include <iostream>
#include <stdlib.h>

int main(int argc, char **argv)
{
	string		request;
	uint32_t 	bytesReceived;

	try {
		int tcp_port = atoi(argv[1]);
		cout << ((tcp_port == 4002) ? "Winch " : "Level Wind ") << "Emulator" << endl;
		tcp_listener tl(tcp_port);

		tl.listen();
		cout << "LISTENING on " << tl.my_endpoint() << endl;

		tcp_socket s = tl.accept();
		cout << "CONNECTION from "  << s.peer() << endl;
		s.set_input_formatter(new line_input_formatter());

		for (;;) {
			bytesReceived = s.recv(request);
			if (bytesReceived > 0) {
				cout << "Received: >" << request << "<\n";
				if (tcp_port == 4002)
					s.send("Hello from winch\n");
				else
					s.send("Hello from level wind\n");
			}
		}
	}
	catch (socket_error_ex& e) {
		cout << "Exception: " << e.what() << endl;
		cout << "Err=" << e.whaterr() << endl;
		cout << "Txt=" << e.whatsystext() << endl;
	}
	catch (socket_error& e) {
		cout << "Exception: " << e.what() << endl;
	}
}
