#include <fcntl.h>
#include <termios.h>

/*
 *Preconditions: none
 *Postconditions: Sets the terminal input settings to per character input
 *  and leaves echo on.
 */
void setup_input(void);

/*
 *Preconditions: setup_input() has been previously called.
 *Postcondistions: Restores the terminal options from before the most recent
 *  setup_input() call.
 */
void reset_input(void);

/*
 *Preconditions: none
 *Postconditions: Turns on local character echoing.
 */
void echo_on(void);

/*
 *Preconditions: none
 *Postconditions: Turns off local character echoing.
 */
void echo_off(void);

static struct termios stored_settings;

void setup_input(void)
{
	struct termios new_settings;

	tcgetattr(0, &stored_settings);
	new_settings = stored_settings;
	new_settings.c_lflag &= ~ICANON;
	//new_settings.c_lflag &= ~ECHO; /*turn off local echo*/
	new_settings.c_cc[VTIME] = 0;
	tcgetattr(0, &stored_settings);
	new_settings.c_cc[VMIN] = 1;
	tcsetattr(0, TCSANOW, &new_settings);

	fcntl(0, F_SETFL, O_NONBLOCK);
}

void echo_on()
{
	struct termios term_settings;
	tcgetattr(0, &term_settings);
	term_settings.c_lflag |= ECHO;
	tcsetattr(0, TCSANOW, &term_settings);
}

void echo_off()
{
	struct termios term_settings;
	tcgetattr(0, &term_settings);
	term_settings.c_lflag &= ~ECHO;
	tcsetattr(0, TCSANOW, &term_settings);
}

void reset_input(void)
{
	tcsetattr(0, TCSANOW, &stored_settings);  
}
