
#include <exec/types.h>
#include <libraries/dos.h>
#include <libraries/dosextens.h>

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

extern long CurrentDir(), Lock();
extern char *hist_table[HISTORY_LENGTH];
extern int hist_count;

do_history(), do_exit(), do_help(), do_prompt(), do_source(), do_cd(),
do_echo();

static Built_in jsh_internals[] =
   {
   "history", do_history,
   "exit", do_exit,
   "help", do_help,
   "prompt", do_prompt,
   "source", do_source,
   "cd", do_cd,
   "echo", do_echo,
   };

Built_in *
is_internal()
{
char lbuf[MAX_WORD];
int count;
register Built_in *blt;

if (!first_word(lbuf, buf) )
   {
   return(NULL);
   }
blt = jsh_internals;
count = sizeof(jsh_internals)/sizeof(Built_in);
while (--count >= 0)
   {
   if (strcmp(lbuf, blt->name) == 0)
      return(blt);
   blt++;
   }
return(NULL);
}

do_history()
{
register char **tab;
register int hist_left;
register int first_ix;

if (hist_count <= 20)
   {
   hist_left = hist_count;
   first_ix = 1;
   }
else
   {
   hist_left = 20;
   first_ix = hist_count - 20 +  1;
   }

tab = hist_table + hist_left;
while (--hist_left >= 0)
   {
   printf("%-3d %s\n", first_ix, *(--tab) );
   first_ix++;
   }
}

do_exit()
{
jsh_exit();
}

do_help()
{
register int count;
register Built_in *blt;

puts("available commands are:");
blt = jsh_internals;
count = sizeof(jsh_internals)/sizeof(Built_in);
while (--count >= 0)
   {
   puts(blt->name);
   blt++;
   }
}

do_prompt()
{
extern char *prompt;
register char *new_prompt;

if (new_prompt = next_word(buf) )
   {
   free(prompt);
   if (new_prompt = clone_string(new_prompt) )
	   prompt = new_prompt;
   }
else
   puts("usage: prompt newprompt");
}

do_source()
{
static char usage[] = "usage: source file";
char file_name[MAX_WORD];
register FILE *sfile;
register int length;
register char *what;

what = next_word(buf);
if (what == NULL)
   {
   puts(usage);
   return;
   }
first_word(file_name, what);
if ((sfile = fopen(file_name, "r")) == NULL)
   {
   printf("source couldn't open %s, sorry\n", file_name);
   return;
   }
buf = buf1;
for (;;)
   {
   if (fgets(buf1, sizeof(buf1), sfile) == NULL)
      {
	  fclose(sfile);
	  break;
	  }
   length = strlen(buf);
   if (buf[length-1] == '\n')  /*strip the newline like gets does...*/
      buf[length-1] = 0;
   one_line();
   }
}

do_cd()
{
extern long cdir;
register long ndir;
register char *new_dir;

if (new_dir = next_word(buf) )
   {
   if( (ndir = Lock(new_dir,(long)ACCESS_READ) ) == 0 )
      {
	  printf("couldn't cd to %s\n", new_dir);
	  return;
	  }
   UnLock(cdir);
   CurrentDir(ndir);
   cdir = ndir;
   }
else
   puts("cd to what?");
}

do_echo()
{
register char *what;

if (what = next_word(buf) )
   puts(what);
}

