/*
 *
 *
 *   pipetest
 *
 *   Simple C++ program to test my::pipe implementation.
 *
 *   Copyright (C) 2003 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++/muxtty.h>
#include <my++/muxpipe.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::termios console_config;
	std::string value;

	my::multiplexed::tty console;
	my::multiplexed::pipeend in, out;

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

	try {
		my::pipe(in, out);
	} catch (const std::exception &e) {
		cerr << "Error creating pipe: " << 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 (in);
	mux.add (out);

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

	for (;;) {
		rtn = mux.watch();

		if (rtn > 0) {
			if (console.closed()) {
				console.close();
				in.close();
				out.close();
				cerr << "Exit due to console device EOF." << endl;
				return 0;
			}

			if (in.closed()) {
				console.close();
				out.close();
				in.close();
				cerr << "Exit due to pipe EOF." << endl;
				return 0;
			}

			while (console.ready()) {
				count = console.get(buffer, sizeof(buffer));
				if (count == 0)
					return 0;
				if (buffer[0] == 3) {
					console.close();
					in.close();
					out.close();
					cerr << "Exit due to ^C press." << endl;
					return 0;
				}
				out.put(buffer, count);
			}

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