#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <ctype.h>
#include <fcntl.h>

main()
{
  int pid, stat;
  char *words[100];

  while(1){
    write(1, "$ ", 2);

    readcommand(words);

    if((pid = fork()) == 0){
      execv(words[0], words);
      oops("execv failed");
    } else if(pid > 0){
      wait(&stat);
    } else {
      oops("fork failed");
    }
  }
}

readcommand(char *words[])
{
  static char buf[512];
  int n, argc, i, ispipe = 0;

  i = 0;
  while(1){
    if(i >= 511)
      oops("input line too long");
    if(read(0, buf + i, 1) != 1)
      exit(0);
    if(buf[i] == '\n' || buf[i] == '\r')
      break;
    if(buf[i] == '|'){
      ispipe = 1;
      break;
    }
    i++;
  }
  n = i;

  argc = 0;
  i = 0;
  while(argc < 99){
    while(i < n && isspace(buf[i]))
      i++;
    if(i >= n)
      break;
    words[argc++] = buf + i;
    while(i < n && !isspace(buf[i]))
      i++;
    buf[i++] = '\0';
  }
  words[argc] = 0;

  return ispipe;
}

oops(char *s)
{
  fprintf(stderr, "%s\n", s);
  exit(1);
}
