# include "opihi.h"
# include "macro.h"

/* return a new string consisting of the next line in the current list */
char *get_next_listentry (int ThisList) {

  char *output;

  lists[ThisList].n++;

  if (lists[ThisList].n >= lists[Nlists].Nlines) 
    return ((char *) NULL);

  output = lists[Nlists].line[lists[ThisList].n];
  
  return (output);

}

char *remove_listentry (int current) {

  int i;
  char *output;

  if ((current + 1) >= lists[Nlists].Nlines) 
    return ((char *) NULL);

  output = lists[Nlists].line[current + 1];
  
  for (i = current + 1; i < lists[Nlists].Nlines - 1; i++) {
    lists[Nlists].line[i] = lists[Nlists].line[i + 1];
  }

  lists[Nlists].Nlines --;
  return (output);

}

int is_for_loop (char *line) {

  char *comm;

  comm = thisword (line);
  if (comm == (char *) NULL) return (FALSE);

  if (strcmp (comm, "for")) {
    free (comm);
    return (FALSE);
  }

  return (TRUE);

}

int is_macro_create (char *line) {

  int i, N;
  char *comm;
  char *this_macro;


  comm = thisword (line);
  if (comm == (char *) NULL)
    return (FALSE);
  if (strcmp (comm, "macro")) {
    free (comm);
    return (FALSE);
  }
  
  this_macro = thisword (nextword (line));

  if (this_macro == (char *)NULL) {
    return (FALSE);
  }

  N = sizeof (in_macro) / sizeof (Command);

  /* find the macro sub-command which matches from the list. */
  /* if sub-command is not found, assume this is creating a new macro */
  for (i = 0; i < N; i++) {
    if (!strcmp (in_macro[i].name, this_macro)) {
      free (this_macro);
      return (FALSE);
    }
  }

  free (this_macro);
  return (TRUE);

}

int is_if_block (char *line) {

  char *comm, *temp;

  temp = thisword (nextword (nextword (line)));
  comm = thisword (line);

  if (comm == NULL) goto escape;

  if (strcmp (comm, "if")) goto escape;

  if ((temp != NULL) && !strcmp (temp, "break")) goto escape;

  free (comm);
  return (TRUE);

escape: 
  if (comm != NULL) free (comm);
  if (temp != NULL) free (temp);
  return (FALSE);
}

int is_loop (char *line) {

  char *comm;

  comm = thisword (line);
  if (comm == (char *) NULL) return (FALSE);

  if (strcmp (comm, "while")) {
    free (comm);
    return (FALSE);
  }
  free (comm);
  return (TRUE);
}


int is_list (char *line) {
  
  int status;

  status = is_if_block (line);
  status |= is_macro_create (line);
  status |= is_for_loop (line);
  status |= is_loop (line);

  return (status);

}
