# include "data.h"

int subset (int argc, char **argv) {
  
  char *out;
  int  i, j, size;
  Vector *ivec, *ovec, *tvec;

  out = NULL;
  ivec = ovec = tvec = NULL;

  if ((argc < 6) || strcmp(argv[2], "=") || strcmp (argv[4], "if")) {
    fprintf (stderr, "SYNTAX: subset vec = vec if (logic expression)\n");
    return (FALSE);
  }

  if ((ovec = SelectVector (argv[1], ANYVECTOR, TRUE)) == NULL) goto error;
  if ((ivec = SelectVector (argv[3], OLDVECTOR, TRUE)) == NULL) goto error;

  out = dvomath (argc - 5, &argv[5], &size, 1);
  if (out == NULL) {
    print_error ();
    goto error;
  }
  if ((tvec = SelectVector (out, OLDVECTOR, TRUE)) == NULL) goto error;
  /* check size of ivec, tvec: must match */

  REALLOCATE (ovec[0].elements, float, MAX (tvec[0].Nelements, 1));
  for (j = i = 0; i < tvec[0].Nelements; i++) {
    if (tvec[0].elements[i]) {
      ovec[0].elements[j] = ivec[0].elements[i];
      j++;
    }
  }
  ovec[0].Nelements = j;
  REALLOCATE (ovec[0].elements, float, MAX (ovec[0].Nelements, 1));

  DeleteVector (tvec);
  return (TRUE);

 error:
  DeleteVector (tvec);
  DeleteVector (ovec);
  DeleteNamedVector (out);
  return (FALSE);
}

