/*---------------------------------------------------------------------------*\

    Unix replacement for Win32 kbhit() function

         Voicetronix Voice Processing Board (VPB) Software

         Copyright (C) 2007 Voicetronix www.voicetronix.com.au

         This library is free software; you can redistribute it and/or
         modify it under the terms of the GNU Lesser General Public
         License as published by the Free Software Foundation; either
         version 2.1 of the License, or (at your option) any later version.

         This library is distributed in the hope that it will be useful,
         but WITHOUT ANY WARRANTY; without even the implied warranty of
         MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
         Lesser General Public License for more details.

         You should have received a copy of the GNU Lesser General Public
         License along with this library; if not, write to the Free Software
         Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
         MA  02110-1301  USA

\*---------------------------------------------------------------------------*/

#ifndef __KBHIT__
#define __KBHIT__

#ifdef WIN32
  #include <conio.h>
#else

#include <unistd.h>
#include <termios.h>

// Check if a key has been pressed.  Returns the ascii value of the character
// genrated by the key if so, or returns 0 if no key has been pressed.
// Always returns immediately.
inline int kbhit()
{
	struct termios old_attr;
	tcgetattr( 0, &old_attr );

	struct termios new_attr = old_attr;

	new_attr.c_lflag &= ~ICANON;
	new_attr.c_cc[VTIME] = 0;
	new_attr.c_cc[VMIN]  = 0;

	tcsetattr(0, TCSANOW, &new_attr);

	char  ch;
	int   ret = read( STDIN_FILENO, &ch, 1 ) ? ch : 0;

	tcsetattr(0, TCSANOW, &old_attr);

	return ret;
}

// Similar to kbhit, except it will wait for a single key press if none have
// already occurred yet.
inline int getkey()
{
	struct termios old_attr;
	tcgetattr( 0, &old_attr );

	struct termios new_attr = old_attr;

	new_attr.c_lflag &= ~ICANON;
	new_attr.c_cc[VTIME] = 0;
	new_attr.c_cc[VMIN]  = 1;

	tcsetattr(0, TCSANOW, &new_attr);

	char  ch;
	int   ret = read( STDIN_FILENO, &ch, 1 ) ? ch : 0;

	tcsetattr(0, TCSANOW, &old_attr);

	return ret;
}

#endif

#endif

