/**

  ***********************************
  * functions/lineread/my_getc_ub.c *
  *                                 *
  *   (c) 2006 Jannis Schnitzer     *
  *   my_getc_ub function           *
  *   gets a single character from stdin without echoing it.
  *                                 *
  *   Files: my_getc_ub.c           *
  ***********************************

  */




/**

  *******************************************************************************
  * This program is free software; you can redistribute it and/or modify	    *
  * it under the terms of the GNU General Public License as published by     	*
  * the Free Software Foundation; either version 2 of the License, or		    *
  * (at your option) any later version.                 						*
  * 									                                    	*
  * This program 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 General Public License for more details.				                *
  * 										                                    *
  * You should have received a copy of the GNU General Public License		    *
  * along with this program; if not, write to the				                *
  * Free Software Foundation, Inc.,						                        *
  * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.			        *
  *******************************************************************************

  */



/* DELETE THIS IF termios.h IS NOT PRESENT */
#define LINUX


#ifdef LINUX
#include <termios.h>
struct termios saved_attributes;
#endif

int set_input_mode ( void )
{
#ifdef LINUX
    struct termios tattr;
    
    if ( !isatty ( STDIN_FILENO ) )
    {
        fprintf ( stderr, "No terminal!\n" );
        return false;
    }
    
    tcgetattr ( STDIN_FILENO, &saved_attributes );
    
    tcgetattr ( STDIN_FILENO, &tattr );
    tattr.c_lflag     &= ~( ICANON | ECHO );
    tattr.c_cc[VMIN]   = true;
    tattr.c_cc[VTIME]  = false;
    tcsetattr ( STDIN_FILENO, TCSAFLUSH, &tattr );
#endif
    return true;
}


void reset_input_mode ( void )
{
#ifdef LINUX
    tcsetattr ( STDIN_FILENO, TCSANOW, &saved_attributes );
#else
    ;
#endif
}


int my_getc_ub ( void )
{
#ifdef LINUX
       char c;

       if ( !set_input_mode () )
	   return EOF;

       read ( STDIN_FILENO, &c, 1 );

       reset_input_mode ();

       return ( c != EOF || c != '\004' ) ? ( c ) : ( EOF );
#else
       return getchar ();
#endif
}
