

#include <stdio.h>
#include <ctype.h>
#include "jsh.h"

extern long CurrentDir(), DupLock();
long firstdir, cdir;

char buf1[BUF_LENGTH], buf2[BUF_LENGTH];  /* "double buffer" for expansion */
char *buf;
char *hist_table[HISTORY_LENGTH];
int hist_count;
char *prompt = "%";

extern Built_in *is_internal();

#ifdef AZTEC
extern int Enable_Abort;
#endif AZTEC

main()
{
#ifdef AZTEC
Enable_Abort = 0;	/*Aztec C turn off ^C checking */
#endif AXTEC;

/* save first directory to restore on exit  and dupe copy for cdir*/
firstdir = CurrentDir(0);	
CurrentDir(firstdir);
cdir = DupLock( firstdir );

prompt = clone_string(prompt);	/*so it's dynamic memory... */
buf = "source .login";  /* execute the .login file */
one_line();
for (;;)
  {
  buf = buf1;
  fputs(prompt, stdout);
  putchar(' ');
  if (gets(buf1) == NULL)
	 jsh_exit();
  one_line();
  }
}

jsh_exit()
{
CurrentDir(firstdir);
UnLock(cdir);
exit(0);
}

/*one_line() - executes the string in buf */
one_line()
{
register Built_in *internal;
register int err;

if (!replace_history())
   return;
add_history();
if (!expand_wildcards())
   return;
if (internal = is_internal())
   {
   (*internal->function)();
   err = 0;
   }
else
   {
   if (buf)
    	err = Execute(buf, NULL, NULL);
   }
return(err);
}


char *
find_buffer()
{
if (buf == buf1)
   return(buf2);
else
   return(buf1);
}


replace_history()
{
register int offset;
register char *s;

if (buf[0] == '!')
   {
   if (buf[1] == '!')
      buf = hist_table[0];
   else if (buf[1] == '-')
      {
	  offset = atoi(buf+2);
	  if (offset <= 0)
		 {
	     printf("minus %s history???\n", buf+2);
		 return(0);
		 }
	  if (offset > HISTORY_LENGTH)
		 {
	     printf("only have last %d commands in history\n", HISTORY_LENGTH);
		 return(0);
		 }
      buf = hist_table[offset-1];
	  }
   else if (isdigit( buf[1] ) )
      {
	  offset = atoi(buf+1);
	  if (offset > hist_count)
	     {
		 puts("you're asking for future history kid");
		 return(0);
		 }
	  if (offset == 0 || offset <= hist_count - HISTORY_LENGTH)
	     {
		 puts("I don't remember that far back");
		 return(0);
		 }
	  offset -= hist_count;
	  offset = -offset;
	  buf = hist_table[offset];
	  }
   else 
      {
	  s = lasthead(buf+1, hist_table, HISTORY_LENGTH);
	  if (!s)
		 {
		 printf("%s no found\n", buf+1);
	     return(0);
		 }
	  buf = s;
	  }
   puts(buf);	/* just to echo history after substitution */
   }
return(1);
}

add_history()
{
if (buf != NULL)
	{
	free_string(hist_table[HISTORY_LENGTH-1]);
	bcopy_ptrs(hist_table, hist_table+1, HISTORY_LENGTH-1);
	if ((hist_table[0] = clone_string(buf) ) == NULL)
	   puts("warning - out of memory in add_history");
	hist_count++;
	}
}

outta_mem()
{
puts("out of memory for shell!");
}
