/*
   <p>Get a single keystroke from stdin.</p>

   <kbd>
   <b>environ - C programming support functions</b><br>
   Copyright (C) 2005  Martin C Gregorie
   
   This program is free software; you can redistribute it and/or
   modify it under the terms of the Lesser GNU General Public License.
   
   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 Lesser 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.
   </kbd>
  
   <p>Contact Martin Gregorie at <i>martin@gregorie.org</i></p>
*/ 

#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include "environ.h"

/*
   Get a single keystroke from stdin. 

   This is a raw, unbuffered keyboard single
   key terminal read operation.
    
*/
char getkey(void)
{
    char           c;
    struct termios modes, savemodes;
    
    fflush(stdout);
    if (tcgetattr(0, &modes) < 0)
        error(progname(),
              "getkey:",
              "tcgetattr() failed");

        savemodes = modes;
  	modes.c_lflag &= ~ICANON;
    if (tcsetattr(0, TCSAFLUSH, &modes) < 0)
        error(progname(),
              "getkey:",
              "tcsetattr() failed");

    if (fread(&c, sizeof(char), 1, stdin) == 0)
        c = 0x1b;

    if (tcsetattr(0, TCSAFLUSH, &savemodes) < 0)
        error(progname(),
              "getkey:",
              "tcsetattr() failed restoring settings");
    return c;
}


