#include <stdio.h>
#include <iostream.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#include "cs697lsh.h"
#include "history.h"

History cmdhist;

main()
{
  char *buf;
  cmd command;

  signal(SIGINT, SIG_IGN);
  signal(SIGCHLD, errhandler);
  signal(SIGPIPE, errhandler);

  if(!getenv("CS697L_PROMPT"))
    putenv("CS697L_PROMPT=cs697l% ");

  while(buf = getcommand())
  {
    buf = cmdhist.subst(buf);
    if(!cmdhist.substerr)
    {
      cmdhist << buf;
      command.parse(buf, 0);
      if(command.parseerr >= 0)
        command.cmdexec();
    }
    command.reset();
    while(waitpid(-1, 0, WNOHANG) > 0);
  }
  cout << "exit\n";
  exit(0);
}

char *getcommand()
{
  static char buf[256];
  int c, ret;
  cout << getenv("CS697L_PROMPT");
  if(!fgets(buf, 256, stdin))
    return (char*)0;

  if(buf[c = strlen(buf)-1] == '\n')
    buf[c] = 0;

  return buf;
}

static void errhandler(int sig)
{
  if(sig == SIGCHLD)
    while(waitpid(-1, 0, WNOHANG) > 0);
  if(sig == SIGPIPE)
    cerr << "Broken pipe.\n";
}

