/*
  driver file for MiniBasic.
  by Malcolm Mclean
  Leeds University
*/

#include <stdio.h>
#include <stdlib.h>

#include "basic.h"

#if defined(BOARD)
#include "board.h"
#endif
#ifdef EMBEDDED
#define CONSOLE COM1
#else
char *loadfile(char *path);
#endif

/*
  here is a simple script to play with
*/
char *script =
"10 REM median.bas - Median program.\n"
"20 LET N = 0\n"
"30 DIM array(N+1)\n"
"40 PRINT \"Enter a number, q to quit\"\n"
"50 INPUT line$\n"
"60 IF line$ = \"q\" THEN 100\n"
"70 LET N = N + 1\n"
"80 LET array(N) = VAL(line$)\n"
"90 GOTO 30\n"
"100 PRINT N, \"numbers entered\"\n"
"105 IF N = 0 THEN 1000\n"
"106 IF N =  1 THEN 210\n"
"110 REM Bubble sort the numbers\n"
"120 LET flag = 0\n"
"130 LET i = 1\n"
"140 IF array(i) <= array(i+1) THEN 190\n"
"150 LET flag = 1\n"
"160 LET temp = array(i)\n"
"170 LET array(i) = array(i+1)\n"
"180 LET array(i+1) = temp\n"
"190 LET i = i + 1\n"
"195 IF i < N THEN 140\n"
"200 IF flag = 1 THEN 120\n"
"210 REM print out the middle\n"
"220 IF N MOD 2 = 0 THEN 250\n"
"230 LET mid = array( (N + 1) / 2)\n"
"240 GOTO 270\n"
"250 LET mid = array(N/2) + array(N/2+1)\n"
"260 LET mid = mid/2\n"
"270 PRINT \"Median\", mid\n"
"1000 REM end\n"
;

void usage(void)
{
  printf("MiniBasic: a BASIC interpreter\n");
  printf("usage:\n");
  printf("Basic <script>\n");
  printf("See documentation for BASIC syntax.\n");
  exit(EXIT_FAILURE);
}

/*
  call with the name of the Minibasic script file
*/
int main(int argc, char **argv)
{
#if defined(BOARD)
  boardInit();
#endif
#ifdef EMBEDDED
  printf("MiniBasic: a BASIC interpreter\n");
  basic(script, stdin, stdout, stderr);
  return 0;
}
#else
  char *scr;

  if(argc == 1)
  {
	/* comment out usage call to run test script */
	/* usage(); */
	printf("MiniBasic: a BASIC interpreter\n");
    basic(script, stdin, stdout, stderr);
  }
  else
  {
	scr = loadfile(argv[1]);
	if(scr)
	{
	  basic(scr, stdin, stdout, stderr);
	  free(scr);
	}
  }

  return 0;
}

/*
  function to slurp in an ASCII file
  Params: path - path to file
  Returns: malloced string containing whole file
*/
char *loadfile(char *path)
{
  FILE *fp;
  int ch;
  long i = 0;
  long size = 0;
  char *answer;

  fp = fopen(path, "r");
  if(!fp)
  {
    printf("Can't open %s\n", path);
	return 0;
  }

  fseek(fp, 0, SEEK_END);
  size = ftell(fp);
  fseek(fp, 0, SEEK_SET);

  answer = malloc(size + 100);
  if(!answer)
  {
    printf("Out of memory\n");
    fclose(fp);
	return 0;
  }

  while( (ch = fgetc(fp)) != EOF)
    answer[i++] = ch;

  answer[i++] = 0;

  fclose(fp);

  return answer;
}
#endif /* EMBEDDED */
