# include "opihi.h"

int exec_loop (Macro *loop) {

  int n, Nlines, j, status, ThisList, Signal;
  char *outline;
  
  /* increase the shell level (Nlists) by one */
  Nlists ++;
  ThisList = Nlists;
  REALLOCATE (lists, List, MAX (ThisList, 0) + 1);
  
  /* copy the macro to the current list */
  lists[ThisList].Nlines = loop[0].Nlines;
  ALLOCATE (lists[ThisList].line, char *, MAX (lists[ThisList].Nlines, 1));
  for (j = 0; j < lists[ThisList].Nlines; j++) {
    lists[ThisList].line[j] = strcreate (loop[0].line[j]);
  }

  /* set up interrupts */
  Signal = (int) signal (SIGINT, handle_interrupt);
  interrupt = FALSE;

  /* process the list */
  loop_continue = loop_break = FALSE;
  status = TRUE;
  Nlines = lists[ThisList].Nlines;
  for (n = 0; (n < Nlines) && !interrupt; n++) {
    lists[ThisList].n = n; 
    status = command (lists[ThisList].line[n], &outline);
    n = lists[ThisList].n;
    Nlines = lists[ThisList].Nlines;
    if (outline != NULL) free (outline);
    if (auto_break && !status) loop_break = TRUE;
    if (loop_break || loop_continue) break;
  }
  signal (SIGINT, (void *) Signal);

  /* free up the list and decrement the shell level */
  free (lists[ThisList].line);
  Nlists --;
  REALLOCATE (lists, List, MAX (Nlists, 0) + 1);

  if (loop_break) return (FALSE);
  return (TRUE);
}

/** note that the list number runs from 1 - Nlists+1 **/
