# include "basic.h"
# define D_NLINES 100
static char prompt[] = ">> ";

int run_for (int argc, char **argv) {

  int ThisList, depth, i, done, status, NLINES, j;
  double start, end, delta;
  char *input;
  double value, sign;
  Macro loop;

  if ((argc != 4) && (argc != 5)) {
    fprintf (stderr, "USAGE: for (var) (start) (stop) [delta] -- terminate with 'END'\n");
    return (FALSE);
  }

  start = atof (argv[2]);
  end   = atof (argv[3]);
  delta = 1.0;
  if (argc == 5) delta = atof (argv[4]);
  sign = SIGN(delta);

  NLINES = D_NLINES;
  ALLOCATE (loop.line, char *, NLINES);

  /* read in loop */
  depth = 0;
  ThisList = Nlists;
  for (i = 0, done = FALSE; !done; ) {

    /* get the next line (from correct place) */
    if (ThisList == 0) 
      input = readline (prompt);
    else 
      input = get_next_listentry (ThisList);
    stripwhite (input);

    /* check for end-of-data syntax error */
    if (input == (char *) NULL) {
      if (ThisList == 0)  {
	fprintf (stderr, "end loop with 'END'\n");
	continue;
      } else {
	fprintf (stderr, "misbalanced loop\n");
	for (j = 0; j < loop.Nlines; j++) {
	  free (loop.line[j]);
	}
	free (loop.line);
	return (FALSE);
      }	
    }

    /* test for new macro (or other list, in the future?) */
    if (is_list (input)) depth ++;

    /* test for end of nested list -- if not nested, END refers to this macro */
    if (!strncasecmp (input, "END", 3)) {
      depth --;
      if (depth < 0) break;
    }

    /* if line has data, add to loop list */
    if (*input) { 
      loop.line[i] = input;
      i++;
      if (i == NLINES - 1) {
	NLINES += D_NLINES;
	REALLOCATE (loop.line, char *, NLINES);
      }
    }
  }

  /* cleanup loop data */
  free (input);
  loop.Nlines = i;
  REALLOCATE (loop.line, char *, MAX (loop.Nlines, 1));

  for (value = start; (sign*value < sign*end) && !interrupt; value += delta) {
    loop_continue = loop_break = FALSE;
    if ((int)value == value) 
      set_int_variable (argv[1], (int) value);
    else 
      set_variable (argv[1], value);
    status = exec_loop (&loop);
    value = get_double_variable (argv[1]);
    if (loop_break) break;
    if (loop_continue) continue;
  }
  loop_continue = loop_break = FALSE;
  if (auto_break && !status) loop_break = TRUE;

  /* cleanup list */
  for (j = 0; j < loop.Nlines; j++) {
    free (loop.line[j]);
  }
  free (loop.line);
  if (loop_break) return (FALSE);
  return (TRUE);
}

/*
  If we are entering at the keyboard (Nlists == 0), use readline.
  Otherwise, read from the current list, remove list lines.
  execute when we hit the final "END" (the true END -- we count macro defines!!) 
*/
     
