//c - c++
#include "iostream"
#include <stdlib.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <signal.h>
#include <getopt.h>

//this
#include "SerLEDDeviceSerial.H"

using namespace std;



const int masks[2]={TIOCM_RTS, TIOCM_DTR};

//////////////////////////////////
// Initialize(const char dev)	//
//////////////////////////////////

void SerLEDDeviceSerial :: Initialize(const std::vector<std::string> &items)
	{
	if(items.size()<3)
		{
		cerr<<"Syntax error in config file!"<<endl;
		cerr<<"Not enough arguments to create serial device!"<<endl;
		exit(1);
		}
	_file_d = open(items[2].c_str() , O_RDWR | O_NOCTTY | O_NDELAY);
		if(_file_d==-1)
			{
			cerr<<"Cannot open'"<<items[2]<<"'!"<<endl;
			exit(1);
			}
//	Off(RTS);
//	Off(DTR);
	}


//////////////////////////////////////////////////////////////////
// GetLEDnumber(const std::vector<std::string> & items) const	//
//////////////////////////////////////////////////////////////////

int SerLEDDeviceSerial :: GetLEDNumber(const std::vector<std::string> & items)
	{
	int led_nr(-1);
	if(items[0]=="RTS") led_nr=RTS;
	if(items[0]=="DTR") led_nr=DTR;
	if(led_nr==-1) 
		{
		cerr<<"Led '"<<items[0]<<"' is unknown to device serial!"<<endl;
		return -1;
		}
//search for inverted flag
	for(unsigned int i=1; i<items.size(); i++)
		{
		cerr<<i<<": "<<items[i]<<endl;
		if(items[i]=="inverted") 
			{
			cerr<<"LED "<<led_nr<<" is inverted"<<endl;
			_inverted[led_nr]=true;
			}
		}	
	Off(led_nr);	
	return led_nr;
	}



//////////////////////////
// On(unsigned int led)	//
//////////////////////////

void SerLEDDeviceSerial :: On(int led)
	{
//	cerr<<"SerLEDDeviceSerial :: On"<<endl;
	int status;
	ioctl(_file_d, TIOCMGET, &status);
	if(_inverted[led])
		status&=~masks[led];
	else
		status|=masks[led];
	ioctl(_file_d, TIOCMSET, &status);	
	}

//////////////////////////////////
// Off(unsigned int led)	//
//////////////////////////////////

void SerLEDDeviceSerial :: Off(int led)
	{
//	cerr<<"SerLEDDeviceSerial :: Off"<<endl;
//	if(_inverted[led]) cerr<<"LED is inverted"<<endl;
//	else cerr<<"LED is not inverted"<<endl;
	int status;
	ioctl(_file_d, TIOCMGET, &status);
	if(!_inverted[led])
		status&=~masks[led];
	else
		status|=masks[led];
	ioctl(_file_d, TIOCMSET, &status);	
	}

