# include "data.h"

char *get_variable (char *);

int applyfit (int argc, char **argv) {
  
  int i, j, order;
  char *c, name[64];
  double *C, X;
  float *x, *y;
  Vector *xvec, *yvec;

  if (argc != 3) {
    gprint (GP_ERR, "USAGE: applyfit x y\n");
    return (FALSE);
  }

  c = get_variable ("Cn");
  if (c == (char *) NULL) {
    gprint (GP_ERR, "no fit available\n");
    return (FALSE);
  }
  order = atof (c);

  if ((xvec = SelectVector (argv[1], OLDVECTOR, TRUE)) == NULL) return (FALSE);    
  if ((yvec = SelectVector (argv[2], ANYVECTOR, TRUE)) == NULL) return (FALSE);    

  ALLOCATE (C, double, order+1);
  for (i = 0; i < order + 1; i++) {
    sprintf (name, "C%d", i);
    c = get_variable (name);
    if (c == (char *) NULL) {
      gprint (GP_ERR, "missing fit term %d\n", i);
      return (FALSE);
    }
    C[i] = atof (c);
  }
  yvec[0].Nelements = xvec[0].Nelements;
  REALLOCATE (yvec[0].elements, float, yvec[0].Nelements);
  bzero (yvec[0].elements, sizeof(float)*yvec[0].Nelements);
  x = xvec[0].elements;
  y = yvec[0].elements;

  for (j = 0; j < xvec[0].Nelements; j++, x++, y++) {
    X = 1;
    for (i = 0; i < order + 1; i++) {
      *y += C[i]*X;
      X = X * (*x);
    }
  }

  return (TRUE);

}




