# include "opihi.h"

char *expand_vectors (char *line) {

  char *newline, *tmpline, *val;
  char *L, *N, *p, *q, *w;
  int n, I, size;
  double f1;
  Vector *vec;

  if (line == NULL) return (NULL);

  ALLOCATE (newline, char, 1024);  /* WARNING: this limits the length of the input line */
  ALLOCATE (tmpline, char, 1024);  /* WARNING: this limits the length of the input line */

  /* look for form fred[stuff] */
  /* skip first word (command) */
  L = nextword (line);
  if (L == NULL) {
    free (newline);
    free (tmpline);
    return (line);
  }

  n = L - line;
  strncpy (newline, line, n);
  N = newline + n;
  while (1) {
    /* find vector subscript */
    p = strchr (L, '[');
    q = strchr (L, ']');
    if ((p == NULL) && (q != NULL)) goto dumpline;
    if ((p != NULL) && (q == NULL)) goto dumpline;
    if ((p == NULL) && (q == NULL)) goto dumpline;
    if (p > q) goto dumpline; /* odd state: unmatched pair: ][ */
    n = (int) (q - p - 1);
    if (n == 0) {
      ALLOCATE (val, char, 64);
      sprintf (val, "-1");
      /* this choice of sentinel prevents us from using 
	 x[-1], x[-2], and is not really needed */
    } else {
      strncpy (tmpline, p+1, n);
      tmpline[n] = 0;
      val = dvomath (1, &tmpline, &size, 0);
      if (val == NULL) goto dumpline; /* not a valid vector subscript */
    }
    I = atoi (val);
    free (val);

    /* find vector name */
    for (w = p - 1; (w >= line) && !OHANA_WHITESPACE(*w) && (isalnum(*w) || (*w == ':') || (*w == '_')); w--);
    w ++;
    n = (int)(p - w);
    strncpy (tmpline, w, n);
    tmpline[n] = 0;
    if ((vec = SelectVector (tmpline, OLDVECTOR, TRUE)) == NULL) goto dumpline;

    /* find vector element */
    if (I >= vec[0].Nelements) {
      gprint (GP_ERR, "vector subscript out of range\n"); 
      goto escape;
    }
    if (I < 0) {
      f1 = vec[0].Nelements;
    } else {
      f1 = vec[0].elements[I];
    }
    if ((int)f1 == f1) 
      sprintf (tmpline, "%.0f", f1);
    else
      sprintf (tmpline, "%.9g", f1);
    /* interpolate vector element */
    n = (int) (w - L);
    strncpy (N, L, n);
    N += n;
    n = strlen (tmpline);
    strncpy (N, tmpline, n);
    N += n;
    L = q + 1;
  }

dumpline:
  n = strlen (L);
  strncpy (N, L, n);
  N[n] = 0;
  free (line);
  free (tmpline);
  return (newline);
  
escape:
  free (line);
  free (newline);
  free (tmpline);
  return (NULL);
}

