#include <stdio.h>
#include <string.h>
#include <assert.h>

#ifdef UNIX

#include <readline/readline.h>

#else

#include <windows.h>

#endif

#include "yanling.h"
#include "jobs.h" 
#include "history.h"
#include "util.h"
#include "command.h"

#ifdef UNIX
void handleSIGTSTP(int sig){

  if (ccForeground == NULL){
    /* do nothing if there is no foreground process running */
  }
  else{
    if(kill(ccForeground->pid, SIGSTOP)){
      perror("shell: ctrl-Z");
      exit(1);
    }
    else{
      /* succesfully stopped the foreground job, there should be
	 no more foreground jobs, ccForeground = NULL */
      addStoppedJob(ccForeground -> pid, strclone(ccForeground->cmdLine));
      ccForeground = NULL;
    }
  }
}
#endif

int main (int argc, char **argv) {
  struct history *h=historyAlloc(HISTORY_MAX);
#ifdef UNIX
  signal(SIGTSTP, handleSIGTSTP);
#endif
  while (1){
    struct command *cc=commandAlloc();

    printJobStatus();
    printPrompt();
    cc->cmdLine= readline("");
    if (historyExpand(h,&(cc->cmdLine))) {
      free((char*)cc->cmdLine);
      continue;
    }
    if (strlen(cc->cmdLine)) historyAdd(h,cc->cmdLine);
    commandSplit(cc);
    if (cc->argc>0) {
      commandExec(cc,argv[0],h);
    }
    commandFree(cc);
  }
  historyFree(h);
}
