/*
 * This file is part of the OLH system.
 *
 *      Lucien Van Elsen
 *      MIT Project Athena
 *
 * Copyright (C) 1990 by the Massachusetts Institute of Technology.
 * For copying and distribution information, see the file "mit-copyright.h".
 *
 *      $Source: /afs/sipb.mit.edu/project/sipb-athena/repository/src/olh/ascii/anykey.c,v $
 *      $Id: anykey.c,v 1.4 1996/03/19 11:25:20 warlord Exp $
 *      $Author: warlord $
 */

/* simple program to wait for any key to be pressed, and then exit */

#include <sys/types.h>
#include <sys/time.h>
#ifdef SOLARIS
#define CBREAK          O_CBREAK 
#include <sys/ttold.h>
#endif
#include <sys/ioctl.h>
#include <stdio.h>
#ifdef __NetBSD__
#include <sgtty.h>
#endif
#ifdef linux
#include <bsd/sgtty.h>
#endif

void
  keypressed()
{
  /* These are for ioctl */
  struct sgttyb tty, ntty;
  int ttyset, stat;
  char c;
  
  ttyset = 0;
  
  /*
   * The TIOCGETP ioctl call gets the tty information structure.
   * See tty(4) for details about the contents of that structure.
   */
  stat = ioctl(0, TIOCGETP, &tty);
  if (stat == -1) {
    perror("ioctl");
    return;
  }
  
  /*
   * CBREAK is the status flag that controls character by character
   * input mode.  This if statement checks to see if CBREAK is
   * already enabled and only enables it if it is not.
   */
  if (! (tty.sg_flags & CBREAK)) {
    ntty = tty;
    ttyset = (! ttyset);
    /* OR'ing the status bits with CBREAK turns it on. */
    ntty.sg_flags |= CBREAK;
    /* TIOCSETN changes the terminal characteristics, without */
    /* discarding pending data.                               */
    stat = ioctl(0, TIOCSETN, &ntty);
    if (stat == -1) {
      perror("ioctl");
      return;
    }
  }
  
  c = getchar();
  
  if (ttyset) {
    /* put the tty characteristics back to their original form */
    stat = ioctl(0, TIOCSETN, &tty);
    if (stat == -1) {
      perror("ioctl");
      return;
    }
  }
  return;
}

int foo(c)
  char c;
{
  putchar(c);
}

main()
{
  char bp[1024];
  char start_inv[20],end_inv[20];
  char *s_loc = &start_inv[0];
  char *e_loc = &end_inv[0];
  int status = 0;
  
  if (tgetent(bp,getenv("TERM")) == 1)
    if ((tgetstr("so",&s_loc) != NULL) &&
	(tgetstr("se",&e_loc) != NULL))
      status = 1;

  if (status) {
    tputs(start_inv,1,foo);
    printf("Press any key to continue... ");
    tputs(end_inv,1,foo);
  }
  else
    printf("Press any key to continue... ");

  keypressed();
}
