// spoggle.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
void siginthandler(int param)
{
	printf("Program Terminating...\n");
	exit(param);
}

void print_usage() {
	fprintf(stdout, "Usage: %s options\n", "spoggle");
	fprintf(stdout, "  -h --help                  Display this usage information.\n");
	fprintf(stdout, "  -d --device				  Serial device to trigger through (i.e. COM1) \n");

	exit(0);
}

void print_menu() {
	fprintf(stdout, "Please enter a command\n"
		"(1) Toggle RTS Line HIGH\n"
		"(2) Toggle RTS Line LOW\n\n"
		"What is your selection? ");
}

int _tmain(int argc, _TCHAR* argv[])
{
	triggerSerialPort * tspTrigger;
	static int verbose_flag;
	int c;

	TCHAR sDevice[6] = TEXT("COM1"); // accommodates serial ports < 100
	
	//PROCESS OPTIONS
	while (1)
	{
		static struct option long_options[] =
		{
			{ _T("verbose"), ARG_NONE, &verbose_flag, 1 },
			{ _T("brief"), ARG_NONE, &verbose_flag, 0 },
			{ _T("help"), ARG_NONE, 0, _T('h') },
			{ _T("device"), ARG_NONE, 0, _T('d') },
			{ ARG_NULL, ARG_NULL, ARG_NULL, ARG_NULL }
		};

		int option_index = 0;
		c = getopt_long(argc, argv, _T("hd:"), long_options, &option_index);

		// Check for end of operation or error
		if (c == -1)
			break;

		// Handle options
		switch (c)
		{
		case 0:
			/* If this option set a flag, do nothing else now. */
			if (long_options[option_index].flag != 0)
				break;
			_tprintf(_T("option %s"), long_options[option_index].name);
			if (optarg)
				_tprintf(_T(" with arg %s"), optarg);
			_tprintf(_T("\n"));
			break;

		case _T('h'):
			print_usage();
			break;


		case _T('d'):
			_tprintf(_T("Setting trigger serial device to `%s'\n"), optarg);
			_tcscpy_s(sDevice, optarg);
			break;

		case '?':
			/* getopt_long already printed an error message. */
			print_usage();
			break;

		default:
			abort();
		}
	}

	//SET UP SERIAL PORT
	tspTrigger = new triggerSerialPort(sDevice);
	if (!tspTrigger->isConnected()) {
		fprintf(stderr, "spoggle::main() ERROR Cannot open serial port %s\n", sDevice);
		siginthandler(-1);
	}

	//Enter command loop
	int gc;
	while (1) {
		print_menu();
		gc = getchar();
		
		if (gc == EOF) {
			fprintf(stdout, "Incorrect input, try again, q to quit.\n\n");
			continue;
		}
		switch (gc) {
		case '1':
			if (!tspTrigger->setRTS(1))
				fprintf(stdout,"Failed to set RTS line HIGH");
			break;
		case '2':
			if (!tspTrigger->setRTS(0))
				fprintf(stdout,"Failed to set RTS line LOW");
			break;
		case '3': 
			if (!tspTrigger->sendTrigger())
				fprintf(stdout, "Failed to send trigger");
			break;
		case 'q':
			siginthandler(0);
			break;

		}
	}


	signal(SIGINT, siginthandler);
	return 0;
}

