
/* SIGTSTP defines job control */

/* if there is job control then we need termios.h instead of termio.h */
#include <signal.h>
#ifdef SIGTSTP
#define TERMIOS
#endif

#ifndef WIN32
#include <unistd.h>
#include <sys/ioctl.h>
#ifdef TERMIOS
#include <termios.h>
struct termios orig_termio, rl_termio;
#else
#include <termio.h>
struct termio orig_termio, rl_termio;
#endif /* TERMIOS */
static int term_set = 0;		/* =1 if rl_termio set */
#endif /* WIN32 */

void set_termio( )
{
#ifndef WIN32
	if (!isatty( STDIN_FILENO))
		return;
	if (term_set == 0) {
#ifdef TERMIOS
#ifdef TCGETS
		ioctl( 0, TCGETS, &orig_termio);
#else /* TCGETS */
		tcgetattr( 0, &orig_termio);
#endif /* TCGETS */
#else /* TERMIOS */
		ioctl( 0, TCGETA, &orig_termio);
#endif /* TERMIOS */
		rl_termio = orig_termio;
		rl_termio.c_iflag &= ~(BRKINT | PARMRK | INPCK | IXON | IXOFF);
		rl_termio.c_iflag |= (IGNBRK | IGNPAR);

#ifndef darwin					/* ONOCR unimplemented in Darwin */
		rl_termio.c_oflag &= ~(ONOCR);
#endif
		rl_termio.c_lflag &= ~(ICANON | ECHO | ECHOE | ECHOK | ECHONL | NOFLSH);
		rl_termio.c_lflag |= (ISIG);
		rl_termio.c_cc[VMIN] = 1;
		rl_termio.c_cc[VTIME] = 0;
#ifdef VSUSP

/* disable suspending process on ^Z */
		rl_termio.c_cc[VSUSP] = 0;
#endif /* VSUSP */
#ifdef TERMIOS
#ifdef TCSETSW
		ioctl( 0, TCSETSW, &rl_termio);
#else /* TCSETSW */
		tcsetattr( 0, TCSADRAIN, &rl_termio);
#endif /* TCSETSW */
#else /* TERMIOS */
		ioctl( 0, TCSETAW, &rl_termio);
#endif /* TERMIOS */
		term_set = 1;
#ifdef KEYPAD
		putc( 033, stderr);
		putc( '=', stderr);
#endif
	}
#endif /* WIN32 */
}

void reset_termio( )
{
#ifndef WIN32
	if (!isatty( STDIN_FILENO))
		return;
	if (term_set == 1) {
#ifdef TERMIOS
#ifdef TCSETSW
		ioctl( 0, TCSETSW, &orig_termio);
#else /* TCSETSW */
		tcsetattr( 0, TCSADRAIN, &orig_termio);
#endif /* TCSETSW */
#else /* TERMIOS */
		ioctl( 0, TCSETAW, &orig_termio);
#endif /* TERMIOS */
		term_set = 0;
#ifdef KEYPAD
		putc( 033, stderr);
		putc( '>', stderr);
#endif
	}
#endif /* WIN32 */
}

#ifndef WIN32
int get_termio_char( int code)
{
	return orig_termio.c_cc[code];
}
#endif /* WIN32 */
