# include "data.h"

int ungridify (int argc, char **argv) {

  int i, j, n;
  int Nx, Ny, NX, NY;
  int Xmin, Xmax, Ymin, Ymax;
  float *v, *x, *y, *z;
  Buffer *bf;
  Vector *vx, *vy, *vz;

  if (argc != 9) {
    gprint (GP_ERR, "USAGE: ungridify buffer Xmin Xmax Ymin Ymax x y z\n");
    return (FALSE);
  }
  
  if ((bf = SelectBuffer (argv[1], OLDBUFFER, TRUE)) == NULL) return (FALSE);
  Xmin = atof (argv[2]);
  Xmax = atof (argv[3]);
  Ymin = atof (argv[4]);
  Ymax = atof (argv[5]);
  Nx = Xmax - Xmin;
  Ny = Ymax - Ymin;
  
  NX = bf[0].matrix.Naxis[0];
  NY = bf[0].matrix.Naxis[1];

  if ((vx = SelectVector (argv[6], ANYVECTOR, TRUE)) == NULL) return (FALSE);
  if ((vy = SelectVector (argv[7], ANYVECTOR, TRUE)) == NULL) return (FALSE);
  if ((vz = SelectVector (argv[8], ANYVECTOR, TRUE)) == NULL) return (FALSE);
  REALLOCATE (vx[0].elements, float, Nx*Ny);
  REALLOCATE (vy[0].elements, float, Nx*Ny);
  REALLOCATE (vz[0].elements, float, Nx*Ny);

  x = vx[0].elements;
  y = vy[0].elements;
  z = vz[0].elements;
  n = 0;
  v = (float *)bf[0].matrix.buffer;
  for (j = Ymin; j < Ymax; j++) {
    for (i = Xmin; i < Xmax; i++, x++, y++, z++, n++) {
      vx[0].elements[n] = i;
      vy[0].elements[n] = j;
      if (i < 0) continue;
      if (i >= NX) continue;
      if (j < 0) continue;
      if (j >= NY) continue;
      vz[0].elements[n] = v[i+j*NX];
    }
  }
  if (n != Nx*Ny) {
    gprint (GP_ERR, "error in ungrid: %d vs %d (%d x %d)\n", n, Nx*Ny, Nx, Ny);
  }
  vx[0].Nelements = vy[0].Nelements = vz[0].Nelements = n;
  return (TRUE);
}
