# include "data.h"

int sort_vectors (int argc, char **argv) {
  
  int i, j, Nvec, Nval;
  float *temp, *index, *T, *V, *I;
  Vector **vec;

  if (argc < 2) {
    gprint (GP_ERR, "USAGE: sort (vector) [vectors ...] \n");
    gprint (GP_ERR, "  first vector is sort key for others\n");
    return (FALSE);
  }

  Nvec = (argc - 1);
  ALLOCATE (vec, Vector *, Nvec);

  Nval = 0;
  /* find vectors and check sizes */
  for (i = 0; i < Nvec; i++) {
    if ((vec[i] = SelectVector (argv[i + 1], OLDVECTOR, FALSE)) == NULL) {
      gprint (GP_ERR, "USAGE: sort vector vector ...\n");
      free (vec);
      return (FALSE);    
    }
    if (i == 0) {
      Nval = vec[i][0].Nelements;
    } else {
      if (Nval != vec[i][0].Nelements) {
	free (vec);
	gprint (GP_ERR, "vectors must all be same length\n");
	return (FALSE);
      }
    }
  }
  
  /* create index (use float to use sortpair) */
  ALLOCATE (index, float, Nval);
  for (i = 0; i < Nval; i++) index[i] = i;

  /* sort key & index */
  fsortpair (vec[0][0].elements, index, Nval);

  ALLOCATE (temp, float, Nval);
  for (i = 1; i < Nvec; i++) {
    T = temp;
    V = vec[i][0].elements;
    I = index;
    for (j = 0; j < Nval; j++, T++, I++) {
      *T = V[(int)(*I)];
    }
    /* swap .elements (== V) and temp */ 
    vec[i][0].elements = temp;
    temp = V;
  }
  free (temp);
  free (vec);
  free (index);

  return (TRUE);

}


