#include "terminal.h"

/* This procedure will restore the terminal to it's previous state
 * before initialization.  It will return 1 on success, and -1 on failure.
 */

extern int restore_terminal(int term){

   if(ioctl(term ,TTYSET, &old_term) < 0) return -1;
   close(term);
   return 1;
}

/* This procedure will make the terminal into a cbreak terminal without
 * echo.  It returns the identifier for the terminal, so that the caller
 * may read/write to it.  If an error occurs, it will return a negative
 * number; and according to that number the error may be tracked down
 * inside the procedure.
 */
   
extern int terminal_cbreak(){
   
   tty_struct new;		/* Our flags to set up the cbreak term */
   int term;			/* The terminal identifier */
   
   if (term = open(TERMINAL,O_RDWR) < 0) {
      perror("readcmd: Error in Terminal Open\n");
      return -3;
   }

/* Save the current settings (old_term) and get a copy to manipulate */
   
   if(ioctl(term ,TTYGET, &old_term) < 0) return -2;
   if(ioctl(term ,TTYGET, &new) < 0) return -2;

#ifdef POSIX
   new.c_lflag &= ~ICANON;
   new.c_lflag &= ~ECHO;
   new.c_cc[VMIN] = 1;
   new.c_cc[VTIME] = 0;
#else
   new.sg_flags |= CBREAK;	/* Set flag for CBREAK */
   new.sg_flags &= ~ECHO;	/* Set flag for no ECHO */
#endif
   
   if (ioctl(term , TTYSET, &new) < 0) {
      perror("readcmd: Terminal Setup\n");
      return -1;
   }
   return term;
}



