/*
 *
 *   ttytest
 *
 *   Simple C++ program to test my::tty implementation against
 *   a modem port.
 *
 *   Copyright (C) 2001 by Matt Roberts, KK5JY,
 *   All rights reserved.
 *
 */


#include <iostream>
#include <my++/termios.h>
#include <my++/serialios.h>
#include <my++/conios.h>
#include <my++/multiplex.h>
//#include <my++/arguments.h>
#include <my++/muxtty.h>

#include <cstring>
#include <cstdio>

using namespace std;

const int default_flags = my::device::not_ctl_tty | my::device::nonblocking;


/*
 *
 *   main (...)
 *
 */

int main (int argc, char **argv) {
	//my::arguments args(argc, argv);
	my::termios console_config;
	my::serialios modem_config;
	std::string value;

	/*
	if (args.is_set ("p")) {
		value = args.get ("p");
		modem_config.setParity(value[0]);
	}

	if (args.is_set ("w")) {
		value = args.get ("w");
		modem_config.setCharSize(atoi(value.c_str()));
	}

	if (args.is_set ("o")) {
		value = args.get ("o");
		modem_config.setStopBits(atoi(value.c_str()));
	}

	if (args.is_set ("s")) {
		value = args.get ("s");
		if (modem_config.setSpeed(atoi(value.c_str())))
			cout << "Speed: " << value << "bps" << endl;
	}
	*/

	modem_config.setSpeed(9600);
	modem_config.setParity('O');
	modem_config.setHWflow (true);
	modem_config.setSWflow (false);
	modem_config.setLocal(true);
															 
	my::multiplexed::tty console;
	my::multiplexed::tty modem;

	cout << "Using the following configuration for MODEM:" << endl;
	cout << modem_config << endl; cout.flush();

	cout << "Using the following configuration for CONSOLE:" << endl;
	cout << console_config << endl; cout.flush();

	try {
		modem.open("/dev/modem", default_flags);
		modem.set_options (modem_config);
	} catch (const std::exception &e) {
		cerr << "Error opening /dev/modem: " << e.what() << endl;
		return 1;
	}

	try {
		console.open("/dev/tty", default_flags);
		console.set_options (console_config);
	} catch (const std::exception &e) {
		cerr << "Error opening /dev/tty: " << e.what() << endl;
		return 1;
	}

	my::multiplex mux;

	mux.add (console);
	mux.add (modem);

	char buffer [128];
	size_t count, iter, rtn;

	for (;;) {
		rtn = mux.watch();
		//cout << "watch() returned " << rtn << "\r\n";

		if (rtn > 0) {
			if (console.closed()) {
				console.close();
				modem.close();
				//cout << "Console TTY closed." << endl;
				return 0;
			}

			if (modem.closed()) {
				console.close();
				modem.close();
				//cout << "Modem TTY closed." << endl;
				return 0;
			}

			while (console.ready()) {
				count = console.get(buffer, sizeof(buffer));
				if (buffer[0] == 3)
					return 0;
				if (count > 0)
					modem.put(buffer, count);
			}

			while (modem.ready()) {
				count = modem.get(buffer, sizeof(buffer));
				if (count > 0)
					console.put(buffer, count);
			}
		}
	}
}
