#include <stdio.h>
#include <errno.h>
#ifndef FALSE
#define FALSE 0
#endif
#ifndef TRUE
#define TRUE !FALSE
#endif
#include "comlib.h"
#include "lib.h"

#ifdef _DEBUG
//#define _DEBUG_THE_COM_PORT
#endif

extern void emsg(const char *format, ...);
extern void dmsg(const char *format, ...);

#ifdef WIN32
	struct comport {
		COMMTIMEOUTS Stored;
		DWORD Mask;
		HANDLE f;
		FILE *fp;
	};
#	define NEWLINE "\r\n"
#else
#	include <fcntl.h>
#	include <sys/time.h>
#	include <sys/types.h>
#	include <sys/stat.h>

	struct comport {
		struct termios cinf;
		int f;
		FILE *fp;
	};
#	define NEWLINE "\n"
#endif

Comport *com_new() {
	Comport *com = calloc(1,sizeof(Comport));
	return com;
}
void com_free(Comport **com) {
	if (com && *com) {
		com_close(*com);
		free(*com);
		*com = NULL;
	}
}
void com_dump(Comport *com, char *file) {
	if (com->fp) fclose(com->fp);
	com->fp = fopen(file,"ab");
	if (!com->fp) emsg("Failed to append to '%s', %s",file,strerror(errno));
}

#ifdef _DEBUG_THE_COM_PORT
#	include "thread.h"

	typedef struct action {
		char *cmd;
		char *response;
		int length;
	} Action;

	typedef struct actions {
		Action *list;
		int size,count;
	} Actions;

	Actions *init_actions() {
		Actions *a = calloc(1,sizeof(Actions));
		return a;
	}
	void add_action(Actions *a, char *cmd, char *response) {
		int i;

		for(i = 0; i < a->count; i++) {
			if (strcmp(a->list[i].cmd,cmd)!=0) continue;
			free(a->list[i].response);
			a->list[i].response = strdup(response);
			return ;
		}
		if (a->count == a->size) {
			a->size += 50;
			a->list = (Action *)realloc(a->list,sizeof(Action)*a->size);
		}
		a->list[a->count].cmd = strdup(cmd);
		a->list[a->count].response = strdup(response);
		a->list[a->count].length = strlen(response);
		a->count++;
	}
	void free_actions(Actions **a) {
		if (a && *a) {
			int i;

			for(i = 0; i < (*a)->count; i++) {
				free((*a)->list[i].cmd);
				free((*a)->list[i].response);
			}
			free((*a)->list);
			free(*a);
		}
	}

	Actions *alist;
	Mutex *lockim;
	int upto,bytes,size;
	char *raw;

	void add_response(char *bf, int bfsz) {
		th_mutex_get(lockim);
		if (upto > 0) {
			bytes -= upto;
			memmove(raw,&raw[upto],bytes);
			upto = 0;
		}
		if (bytes+bfsz >= size) {
			if (size == 0) size = 1000;
			else size += size/2;
			if (size < bytes+bfsz) size = bytes+bfsz+1;
			raw = realloc(raw,size);
		}
		memcpy(&raw[bytes],bf,bfsz);
		bytes += bfsz;
		th_mutex_release(lockim);
	}

	void com_debug(Comport *com, char *file, int crlf) {
		char bf[BFSZ],*r_endl,*w_endl,*p,*s;
		int bytes,mode;
		Action a;
		FILE *f;

		f = fopen(file,"r");
		if (!f) return;

		alist = init_actions();
		r_endl = "\r\n";
		w_endl = "\r";
		
		memset(&a,0,sizeof(Action));
		while(fgets(bf,BFSZ,f)) {
			strtok(bf,"\r\n");
			if (strcmp(bf,"]")==0) {
				mode = 0;
				continue;
			}
			
			if ((s = strstr(bf,"WROTE["))) {
				for(p = &s[6]; *p && *p != '['; p++);
				if (*p == '[') p++;
				mode = 1;
			}			
			else if ((s = strstr(bf,"READ["))) {
				for(p = &s[5]; *p && *p != '['; p++);
				if (*p == '[') p++;
				mode = 2;
			}
			else {
				p = bf;
			}

			if (mode == 0) continue;
			//if (!p[0]) continue;

			for(s = p; *s; s++);
			if (s != p) s--;

			if (mode == 1) {
				if (*s == ']') { mode = 3; *s = 0; }
				if (a.cmd && a.response) {
					add_action(alist,a.cmd,a.response);
					free(a.cmd); free(a.response);
					a.response = NULL;
				}
				a.cmd = malloc(strlen(p)+strlen(w_endl)+1);
				strcpy(a.cmd,p);
				if (mode == 3) mode = 1;
				else {
					if (p == bf && iseol(p[0])) ;
					else strcat(a.cmd,w_endl);
				}
			}
			else if (mode == 2) {
				if (*s == ']') { mode = 3; *s = 0; }
				if (a.response) bytes = strlen(a.response);
				else bytes = 0;
				a.response = realloc(a.response,bytes+strlen(p)+strlen(r_endl)+1);
				a.response[bytes] = 0;
				strcat(a.response,p);
				if (mode == 3) mode = 2;
				else {
					if (p == bf && iseol(p[0])) ;
					else strcat(a.response,r_endl);
				}
			}
		}
		fclose(f);

		if (a.cmd && a.response) {
			add_action(alist,a.cmd,a.response);
			free(a.cmd); free(a.response);
			a.response = NULL;
		}
	}
	/*
	void com_debug(Comport *com, char *file) {
		struct stat finf;
		char end[4],*ptr,*str;
		int endlen;
		FILE *fp;

		if (stat(file,&finf) == -1) return ;
		fp = fopen(file,"rb");
		if (!fp) {
			emsg("Failed to read com debug (%s), %s",file,strerror(errno));
			return ;
		}
		raw = calloc(finf.st_size+1,sizeof(char));
		bytes = fread(raw,sizeof(char),finf.st_size,fp);
		raw[bytes] = '\0';
		fclose(fp);
		upto = 0;

		sprintf(end,")%s",NEWLINE);
		endlen = strlen(end);

		for(ptr = strstr(raw,"WROTE["); ptr; ptr = strstr(ptr,"WROTE[")) {
			str = strstr(ptr,end);
			if (!str) break;

			str += endlen;
			if (strncmp(str,"READ[",5)==0);
			else if (strncmp(str,"WROTE[",6)==0);
			else {
				ptr++;
				continue;
			}

			memmove(ptr,str,bytes-(str-raw)+1);
			bytes -= (str-ptr);
		}

		for(ptr = strstr(raw,"READ["); ptr; ptr = strstr(ptr,"READ[")) {
			str = strchr(ptr,'(');
			if (!str) break;
			str++;
			memmove(ptr,str,bytes-(str-raw)+1);
			bytes -= (str-ptr);

			while(TRUE) {
				str = strstr(ptr,end);
				if (!str) break;

				ptr = str;
				str += endlen;
				if (*str == '\0');
				else if (strncmp(str,"READ[",5)==0);
				else if (strncmp(str,"WROTE[",6)==0);
				else {
					ptr++;
					continue;
				}

				memmove(ptr,str,bytes-(str-raw)+1);
				bytes -= (str-ptr);
				break;
			}
		}
	}
	*/
	int com_open(Comport *com, char *port, int baud) {
		lockim = th_mutex_new("DEBUG");
		return TRUE;
	}
	int com_close(Comport *com) {
		free_actions(&alist);
		th_mutex_free(lockim);
		return TRUE;
	}
	int com_setup(Comport *com, int baud) {
		return TRUE;
	}
	int com_wait(Comport *com) {
		return upto < bytes;
	}
	int com_read(Comport *com, char *bf, int bfsz) {
		int left;

		th_mutex_get(lockim);
		left = bytes-upto;

		if (left <= 0) {
			th_mutex_release(lockim);
			return 0;
		}
		if (bfsz > left) bfsz = left;

		memcpy(bf,&raw[upto],bfsz);
		upto += bfsz;
		th_mutex_release(lockim);

		return bfsz;
	}
	int com_write(Comport *com, char *bf, int bytes) {
		int i;

		for(i = 0; i < alist->count; i++) {
			if (memcmp(alist->list[i].cmd,bf,bytes) == 0) {
				add_response(alist->list[i].response,alist->list[i].length);
				break;
			}
		}
		return bytes;
	}
#else
	void com_debug(Comport *com, char *file, int crlf) {
		emsg("Cannot DEBUG, debug build required");
	}
#ifdef WIN32
	int com_open(Comport *com, char *port, int baud) {
		COMMTIMEOUTS Timeouts = {MAXDWORD,0,0,0,0};
		DCB dcb = {0};

		com->f = CreateFile(port,GENERIC_READ|GENERIC_WRITE,0,0,OPEN_EXISTING,0,0);
		if (com->f == INVALID_HANDLE_VALUE) {
			emsg("CreateFile failed");
			return FALSE;
		}

		if (!GetCommTimeouts(com->f,&com->Stored)) {
			emsg("GetCommTimeouts failed");
			return FALSE;
		}
		if (!SetCommTimeouts(com->f,&Timeouts)) {
			emsg("SetCommTimeouts failed");
			return FALSE;
		}

		if (!GetCommState(com->f,&dcb)) {
			emsg("GetCommState failed");
			return FALSE;
		}
		dcb.fParity = FALSE;
		dcb.BaudRate = baud;
		dcb.StopBits = ONESTOPBIT;
		dcb.ByteSize = 8;
		dcb.Parity = NOPARITY;
		dcb.fDtrControl = DTR_CONTROL_ENABLE;
		dcb.fRtsControl =  RTS_CONTROL_ENABLE;
		dcb.fTXContinueOnXoff = TRUE;
		dcb.fAbortOnError = TRUE;
		dcb.XonLim = 2048;
		dcb.XoffLim = 512;
		dcb.XonChar = 17;
		dcb.XoffChar = 19;

		/* Read data despite state of line low/high etc */
		dcb.fDsrSensitivity = FALSE;

		/* Disable output flow control */
		dcb.fOutxCtsFlow = FALSE;
		dcb.fOutxDsrFlow = FALSE;
		dcb.fOutX = FALSE;

		/*
		dcb.BaudRate = baud;
		dcb.fBinary = TRUE;
		dcb.fParity = FALSE;
		dcb.fOutxCtsFlow = TRUE;
		dcb.fOutxDsrFlow = FALSE;
		dcb.fDtrControl = DTR_CONTROL_ENABLE;
		dcb.fDsrSensitivity = FALSE;
		dcb.fTXContinueOnXoff = TRUE;
		dcb.fOutX = FALSE;
		dcb.fInX = FALSE;
		dcb.fErrorChar = TRUE;
		dcb.fNull = TRUE;
		dcb.fRtsControl = RTS_CONTROL_ENABLE;
		dcb.fAbortOnError = TRUE;
		dcb.fDummy2 = 0;
		dcb.wReserved = 0;
		dcb.XonLim = 2048;
		dcb.XoffLim = 512;
		dcb.ByteSize = 8;
		dcb.Parity = NOPARITY;
		dcb.StopBits = ONESTOPBIT;
		dcb.XonChar = 17;
		dcb.XoffChar = 19;
		dcb.ErrorChar = 0;
		dcb.EofChar = 0;
		dcb.EvtChar = 0;
		dcb.wReserved1 = 0;
		*/
		if (!SetCommState(com->f,&dcb)) {
			emsg("SetCommState failed");
			return FALSE;
		}

		return TRUE;
	}
	int com_close(Comport *com) {
		if (com->f == INVALID_HANDLE_VALUE) return TRUE;
		SetCommTimeouts(com->f,&com->Stored);
		/*SetCommMask(com->f,com->Mask);*/
		CloseHandle(com->f);
		com->f = INVALID_HANDLE_VALUE;
		return TRUE;
	}

	/*
	int com_setup(Comport *com, int baud) {
		DCB dcb = {0};

		//if (!GetCommMask(com->f,&com->Mask)) return FALSE;
		//if (!SetCommMask(com->f,EV_RXCHAR)) return FALSE;
		if (!GetCommState(com->f,&dcb)) return FALSE;
		dcb.fParity = FALSE;
		dcb.BaudRate = baud;
		dcb.StopBits = ONESTOPBIT;
		dcb.ByteSize = 8;
		dcb.Parity = NOPARITY;
		dcb.fDtrControl = DTR_CONTROL_ENABLE;
		dcb.fRtsControl =  RTS_CONTROL_ENABLE;
		dcb.fTXContinueOnXoff = TRUE;
		dcb.fAbortOnError = TRUE;
		dcb.XonLim = 2048;
		dcb.XoffLim = 512;
		dcb.XonChar = 17;
		dcb.XoffChar = 19;

		// Read data despite state of line low/high etc
		dcb.fDsrSensitivity = FALSE;

		// Disable output flow control
		dcb.fOutxCtsFlow = FALSE;
		dcb.fOutxDsrFlow = FALSE;
		dcb.fOutX = FALSE;

		//
		dcb.BaudRate = baud;
		dcb.fBinary = TRUE;
		dcb.fParity = FALSE;
		dcb.fOutxCtsFlow = TRUE;
		dcb.fOutxDsrFlow = FALSE;
		dcb.fDtrControl = DTR_CONTROL_ENABLE;
		dcb.fDsrSensitivity = FALSE;
		dcb.fTXContinueOnXoff = TRUE;
		dcb.fOutX = FALSE;
		dcb.fInX = FALSE;
		dcb.fErrorChar = TRUE;
		dcb.fNull = TRUE;
		dcb.fRtsControl = RTS_CONTROL_ENABLE;
		dcb.fAbortOnError = TRUE;
		dcb.fDummy2 = 0;
		dcb.wReserved = 0;
		dcb.XonLim = 2048;
		dcb.XoffLim = 512;
		dcb.ByteSize = 8;
		dcb.Parity = NOPARITY;
		dcb.StopBits = ONESTOPBIT;
		dcb.XonChar = 17;
		dcb.XoffChar = 19;
		dcb.ErrorChar = 0;
		dcb.EofChar = 0;
		dcb.EvtChar = 0;
		dcb.wReserved1 = 0;
		return SetCommState(com->f,&dcb);
	}
	*/

	int com_wait(Comport *com) {
		DWORD Mask;

		if (!WaitCommEvent(com->f,&Mask,NULL)) return -1;
		return TRUE;
	}

	int com_read(Comport *com, char *bf, int bfsz) {
		DWORD Read = 0;

		while(TRUE) {
			if (!ReadFile(com->f,bf,bfsz,&Read,NULL)) break;
			if (Read == 0) break;
			if (com->fp) {
				char tmp[BFSZ];
				struct tm tm;
				time_t t;
				DWORD i;

				time(&t);
				fprintf(com->fp,"%.15s READ[%d][%.*s]%s",safe_asctime(safe_localtime(&t,&tm),tmp)+4,Read,Read,bf,NEWLINE);
				for(i = 0; i < Read && isprint(bf[i]); i++) {}
				if (i < Read) {
					fprintf(com->fp,"BINARY[");
					for(i = 0; i < Read; i++) fprintf(com->fp,"%.2X ",bf[i]);
					fprintf(com->fp,"]\n");
				}
				fflush(com->fp);
			}
			return Read;
		}
		return 0;
	}

	int com_write(Comport *com, char *bf, int bytes) {
		DWORD Written = 0;

		if (WriteFile(com->f,bf,bytes,&Written,NULL)) {
			if (com->fp) {
				char tmp[BFSZ];
				struct tm tm;
				time_t t;

				time(&t);
				fprintf(com->fp,"%.15s WROTE[%d][%.*s]%s",safe_asctime(safe_localtime(&t,&tm),tmp)+4,Written,Written,bf,NEWLINE);
				fflush(com->fp);
			}
			return Written;
		}
		return 0;
	}
#else
	int com_open(Comport *com, char *port, int baud) {
		int flags;

		com->f = open(port,O_RDWR|O_NONBLOCK);
		//O_NOCTTY
		if(com->f == -1) return FALSE;

		//fcntl(com->f,F_SETFL,O_NONBLOCK);
		//fcntl(com->f,F_SETFL,O_NDELAY);
		//fcntl(com->f,F_SETFL,O_NOCTTY);

		/* get current options */
		if (tcgetattr(com->f,&com->cinf) != 0) {
			com_close(com);
			return FALSE;
		}

#if defined(ISFREEBSD) || defined(OSX)
		/* Some systems will require this instead of specifying the baud in the c_cflag
		i.e. freebsd, macosx */
		if (cfsetispeed(&com->cinf,baud) != 0) return FALSE;
		if (cfsetospeed(&com->cinf,baud) != 0) return FALSE;

		/* Mask char to 8 bits, 1 stop bit, no parity */
		/* FreeBSD does not accept baud here! */
		com->cinf.c_cflag = (CS8 | CREAD | CLOCAL);
#else
		/* Mask char to 8 bits, 1 stop bit, no parity */
		com->cinf.c_cflag = (CS8 | CREAD | CLOCAL | baud);
#endif
		com->cinf.c_iflag = 0;
		com->cinf.c_oflag = 0;
		com->cinf.c_lflag = 0;

		if (tcsetattr(com->f,TCSANOW,&com->cinf) != 0) {
			com_close(com);
			return FALSE;
		}

		return TRUE;
	}
	int com_close(Comport *com) {
		if (com->f == -1) return TRUE;
		close(com->f);
		com->f = -1;
		return TRUE;
	}

	/*
	int com_setup(Comport *com, int baud) {
		if (cfsetispeed(&com->cinf,baud) != 0) return FALSE;
		if (cfsetospeed(&com->cinf,baud) != 0) return FALSE;
		return TRUE;
	}
	*/

	int com_wait(Comport *com) {
		fd_set readfd,exceptfd;

		if (com->f == -1) return FALSE;

		FD_ZERO(&readfd);		FD_ZERO(&exceptfd);
		FD_SET(com->f,&readfd);	FD_SET(com->f,&exceptfd);

		return select(com->f,&readfd,NULL,&exceptfd,NULL);
	}

	int com_read(Comport *com, char *bf, int bfsz) {
		int r;

		if (com->f == -1) return 0;
		r = read(com->f,bf,bfsz);
		/*
		fprintf(com->fp,"READ[%d](%d=%s)\n",r,errno,strerror(errno));
		fflush(com->fp);
		*/
		if (r == 0);
		else if (r == -1) {
			if (errno == EAGAIN) r = 0;
		}
		else if (com->fp) {
			char tmp[BFSZ];
			struct tm tm;
			time_t t;

			time(&t);
			fprintf(com->fp,"%.15s READ[%d][%.*s]%s",safe_asctime(safe_localtime(&t,&tm),tmp)+4,r,r,bf,NEWLINE);
			fflush(com->fp);
		}
		return r;
	}

	int com_write(Comport *com, char *bf, int bytes) {
		int r;

		if (com->f == -1) return -1;
		r = write(com->f,bf,bytes);
		if (r > 0 && com->fp) {
			char tmp[BFSZ];
			struct tm tm;
			time_t t;

			time(&t);
			fprintf(com->fp,"%.15s WROTE[%d][%.*s]%s",safe_asctime(safe_localtime(&t,&tm),tmp)+4,r,r,bf,NEWLINE);
			fflush(com->fp);
		}
		return r;
	}
#endif
#endif

/*
		struct termios {
			tcflag_t c_iflag;      // input modes
			tcflag_t c_oflag;      // output modes
			tcflag_t c_cflag;      // control modes
			tcflag_t c_lflag;      // local modes
			cc_t c_cc[NCCS];       // control chars
		}

	   c_iflag flag constants:

       IGNBRK ignore BREAK condition on input

       BRKINT If IGNBRK is not set, generate SIGINT on BREAK con­
              dition, else read BREAK as character \0.

       IGNPAR ignore framing errors and parity errors.

       PARMRK if  IGNPAR  is  not  set, prefix a character with a
              parity error or framing error  with  \377  \0.   If
              neither  IGNPAR nor PARMRK is set, read a character
              with a parity error or framing error as \0.

       INPCK  enable input parity checking

       ISTRIP strip off eighth bit

       INLCR  translate NL to CR on input

       IGNCR  ignore carriage return on input

       ICRNL  translate  carriage  return  to  newline  on  input
              (unless IGNCR is set)

       IUCLC  map uppercase characters to lowercase on input

       IXON   enable XON/XOFF flow control on output

       IXANY  enable any character to restart output

       IXOFF  enable XON/XOFF flow control on input

       IMAXBEL
              ring bell when input queue is full

       c_oflag flag constants:

       OPOST  enable implementation-defined output processing

       OLCUC  map lowercase characters to uppercase on output

       ONLCR  map NL to CR-NL on output

       OCRNL  map CR to NL on output

       ONOCR  don't output CR at column 0

       ONLRET don't output CR

       OFILL  send fill characters for a delay, rather than using
              a timed delay

       OFDEL  fill character is ASCII DEL.  If unset, fill  char­
              acter is ASCII NUL

       NLDLY  newline delay mask.  Values are NL0 and NL1.

       CRDLY  carriage  return  delay mask.  Values are CR0, CR1,
              CR2, or CR3.

       TABDLY horizontal tab delay mask.  Values are TAB0,  TAB1,
              TAB2,  TAB3,  or  XTABS.   A value of XTABS expands
              tabs  to  spaces  (with  tab  stops   every   eight
              columns).

       BSDLY  backspace delay mask.  Values are BS0 or BS1.

       VTDLY  vertical tab delay mask.  Values are VT0 or VT1.

       FFDLY  form feed delay mask.  Values are FF0 or FF1.

       c_cflag flag constants:

       CSIZE  character  size mask.  Values are CS5, CS6, CS7, or
              CS8.

       CSTOPB set two stop bits, rather than one.

       CREAD  enable receiver.

       PARENB enable  parity  generation  on  output  and  parity
              checking for input.

       PARODD parity for input and output is odd.

       HUPCL  lower modem control lines after last process closes
              the device (hang up).

       CLOCAL ignore modem control lines

       CIBAUD mask for input speeds (not used).

       CRTSCTS
              flow control.

       c_lflag flag constants:

       ISIG   when any of the characters  INTR,  QUIT,  SUSP,  or
              DSUSP are received, generate the corresponding sig­
              nal.

       ICANON enable canonical mode.  This  enables  the  special
              characters  EOF,  EOL,  EOL2, ERASE, KILL, REPRINT,
              STATUS, and WERASE, and buffers by lines.

       XCASE  if ICANON is also set, terminal is uppercase  only.
              Input is converted to lowercase, except for charac­
              ters preceded by \.  On output,  uppercase  charac­
              ters are preceded by \ and lowercase characters are
              converted to uppercase.

       ECHO   echo input characters.

       ECHOE  if ICANON is also set, the ERASE  character  erases
              the  preceding  input  character, and WERASE erases
              the preceding word.

       ECHOK  if ICANON is also set, the  KILL  character  erases
              the current line.

       ECHONL if  ICANON  is also set, echo the NL character even
              if ECHO is not set.

       ECHOCTL
              if ECHO is also set, ASCII  control  signals  other
              than  TAB,  NL,  START,  and STOP are echoed as ^X,
              where X is  the  character  with  ASCII  code  0x40
              greater  than  the  control  signal.   For example,
              character 0x08 (BS) is echoed as ^H.

       ECHOPRT
              if ICANON and IECHO are also  set,  characters  are
              printed as they are being erased.

       ECHOKE if  ICANON  is  also set, KILL is echoed by erasing
              each character on the line, as specified  by  ECHOE
              and ECHOPRT.

       FLUSHO output  is  being flushed.  This flag is toggled by
              typing the DISCARD character.

       NOFLSH disable flushing the input and output  queues  when
              generating  the  SIGINT  and  SIGQUIT  signals, and
              flushing the input queue when generating  the  SIG­
              flushing the input queue when generating  the  SIG­
              SUSP signal.

       TOSTOP send  the  SIGTTOU signal to the process group of a
              background process which tries to write to its con­
              trolling terminal.

       PENDIN all  characters  in  the  input queue are reprinted
              when the next character  is  read.   (bash  handles
              typeahead this way.)

       IEXTEN enable implementation-defined input processing.
*/

/*
ioctl params...

// <include/asm-i386/termios.h>
0x00005401  TCGETS            struct termios *
0x00005402  TCSETS            const struct termios *
0x00005403  TCSETSW           const struct termios *
0x00005404  TCSETSF           const struct termios *
0x00005405  TCGETA            struct termio *
0x00005406  TCSETA            const struct termio *
0x00005407  TCSETAW           const struct termio *
0x00005408  TCSETAF           const struct termio *
0x00005409  TCSBRK            int
0x0000540A  TCXONC            int
0x0000540B  TCFLSH            int
0x0000540C  TIOCEXCL               void
0x0000540D  TIOCNXCL               void
0x0000540E  TIOCSCTTY              int
0x0000540F  TIOCGPGRP              pid_t *
0x00005410  TIOCSPGRP              const pid_t *
0x00005411  TIOCOUTQ               int *
0x00005412  TIOCSTI           const char *
0x00005413  TIOCGWINSZ             const struct winsize *
0x00005414  TIOCSWINSZ             struct winsize *
0x00005415  TIOCMGET               int *
0x00005416  TIOCMBIS               const int *
0x00005417  TIOCMBIC               const int *
0x00005418  TIOCMSET               const int *
0x00005419  TIOCGSOFTCAR      int *
0x0000541A  TIOCSSOFTCAR      const int *
0x0000541B  FIONREAD               int *
0x0000541B  TIOCINQ           int *
0x0000541C  TIOCLINUX              const char *             // MORE
0x0000541D  TIOCCONS               void
0x0000541E  TIOCGSERIAL            struct serial_struct *
0x0000541F  TIOCSSERIAL            const struct serial_struct *
0x00005420  TIOCPKT           const int *
0x00005421  FIONBIO           const int *
0x00005422  TIOCNOTTY              void
0x00005423  TIOCSETD               const int *
0x00005424  TIOCGETD               int *
0x00005425  TCSBRKP           int
0x00005426  TIOCTTYGSTRUCT         struct tty_struct *
0x00005450  FIONCLEX               void
0x00005451  FIOCLEX           void
0x00005452  FIOASYNC               const int *
0x00005453  TIOCSERCONFIG          void
0x00005454  TIOCSERGWILD      int *
0x00005455  TIOCSERSWILD      const int *
0x00005456  TIOCGLCKTRMIOS         struct termios *
0x00005457  TIOCSLCKTRMIOS         const struct temios *
0x00005458  TIOCSERGSTRUCT         struct async_struct *
0x00005459  TIOCSERGETLSR          int *
0x0000545A  TIOCSERGETMULTI        struct serial_multiport_struct *
0x0000545B  TIOCSERSETMULTI        const struct serial_multiport_struct *
*/