/* File: abro_data.c
 *
 * Descr: Implementation of external C functions for I/O
 *
 * Author: Jan Lukoschus
 * Date: 2002-06-11
 */

#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <stdlib.h>
#include <termios.h>

/* Interface to esterel generated code */
#include "abro.h"

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
 * Set up terminal device to read single keys pressed
 * Taken from: http://www.gnu.org/manual/glibc-2.2.3/text/libc.txt
 */

struct termios saved_attributes;

void
reset_input_mode (void)
{
  tcsetattr (STDIN_FILENO, TCSANOW, &saved_attributes);
}

void
set_input_mode (void)
{
  struct termios tattr;

  /* Make sure stdin is a terminal. */
  if (!isatty (STDIN_FILENO))
    {
      fprintf (stderr, "Not a terminal.\n");
      exit (EXIT_FAILURE);
    }

  /* Save the terminal attributes so we can restore them later. */
  tcgetattr (STDIN_FILENO, &saved_attributes);
  atexit (reset_input_mode);

  /* Set the funny terminal modes. */
  tcgetattr (STDIN_FILENO, &tattr);
  tattr.c_lflag &= ~(ICANON|ECHO); /* Clear ICANON and ECHO. */
  tattr.c_cc[VMIN] = 0;
  tattr.c_cc[VTIME] = 0;
  tcsetattr (STDIN_FILENO, TCSAFLUSH, &tattr);
}

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

void ABRO_O_O(int i)
{
  printf("\nO: %i\n",i);
}

void initialize_inputs()
{
  char c;
  read (STDIN_FILENO, &c, 1);

  if (c=='a') { ABRO_I_A(); printf("A"); }
  if (c=='b') { ABRO_I_B(); printf("B"); }
  if (c=='r') { ABRO_I_R(); printf("R"); }

  if (c == '\004') /* `C-d' */
    {
      reset_input_mode();
      printf("\n");
      exit(0);
    }
}

int main()
{
  struct timespec time_req;
  struct timespec time_rest;

  time_req.tv_sec  = P / 1000;
  time_req.tv_nsec = (P % 1000) * 1000 * 1000;

  set_input_mode();
  printf("Press Keys A, B, R for signals, <Ctrl>-D to terminate.\n");

  ABRO_reset(); // reset automaton

  /* loop for automaton execution */
  do
    {
      nanosleep(&time_req,&time_rest);  // wait one time cycle
      printf("-");
      initialize_inputs(); // put values on all inputs
      fflush(stdout);
    }
  while (ABRO());

  return 0;
}




