#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>

#ifdef USE_LIBEDIT
#include <editline/readline.h>
#endif
#ifdef USE_EDITLINE
#include <editline.h>
#endif
#ifdef USE_READLINE
#include <readline/readline.h>
#include <readline/history.h>
#endif
#ifdef USE_NLLINE
#include <nlline.h>
#endif
#if defined(USE_GETLINE) || defined(USE_FGETS)
#include "readline.h"
#define readline(prompt) command_readline(prompt)
#define add_history(line) command_add_history(line)
#endif

#ifdef USE_NLLIBC
#include <nllibc.h>
#endif

static void signal_init(void);

static int sigint_handled = 0;

static void sigint_handler(int arg)
{
  sigint_handled++;
#ifdef WIN32
  signal_init();
#endif
  return;
}

#ifdef WIN32
#define USE_OLD_SIGNAL
#endif

static void signal_init(void)
{
#ifndef USE_OLD_SIGNAL
  struct sigaction sa;

  memset(&sa, 0, sizeof(sa));
  sa.sa_handler = sigint_handler;

  sigaction(SIGINT, &sa, NULL);
#else
  signal(SIGINT, sigint_handler);
#endif
}

static void signal_reset(void)
{
#ifndef USE_OLD_SIGNAL
  struct sigaction sa;

  memset(&sa, 0, sizeof(sa));
  sa.sa_handler = SIG_DFL;

  sigaction(SIGINT, &sa, NULL);
#else
  signal(SIGINT, SIG_DFL);
#endif
}

int main(int argc, char *argv[], char *envp[])
{
  char *line;

  signal_init();

  while (1) {
    sigint_handled = 0;

    line = readline("command> ");

    if (sigint_handled) { /* break by Ctrl+C */
      if (!line) {
	write(1, "\n", 1); /* for libedit */
      } else {
	free(line);
      }
      continue;
    }

    if (line == NULL) /* exit by Ctrl+D */
      break;

    if (!strcmp(line, "exit"))
      break;

    if (line[0])
      add_history(line);

    free(line);
  }

  signal_reset();

  return 0;
}
