# include "relastro.h"

static int Nmax;
static double *listR, *listD;
static double *dlistR, *dlistD;

void initObjectData (Catalog *catalog, int Ncatalog) {

  int i, j;
  
  Nmax = 0;
  for (i = 0; i < Ncatalog; i++) {
    for (j = 0; j < catalog[i].Naverage; j++) {
      Nmax = MAX (Nmax, catalog[i].average[j].Nm);
    }
  }

  ALLOCATE (list, double, MAX (1, Nmax));
  ALLOCATE (dlist, double, MAX (1, Nmax));
}  

int UpdateObjects (Catalog *catalog, int Ncatalog) {

  int i, j, k, m, N;
  float chisq;
  StatType statsR, statsD;

  for (i = 0; i < Ncatalog; i++) {
    for (j = 0; j < catalog[i].Naverage; j++) {

      /* calculate the average value of R,D for a single star */
      if (catalog[i].average[j].code & STAR_BAD) continue;  
      m = catalog[i].average[j].offset;

      N = 0;
      for (k = 0; k < catalog[i].average[j].Nm; k++, m++) {
	if (catalog[i].measure[m].flags & MEAS_BAD) continue;
	
	listR[N] = getMeanR (&catalog[i].measure[m], &catalog[i].average[j], &catalog[i].secfilt[j*PhotNsec]);
	listD[N] = getMeanD (&catalog[i].measure[m], &catalog[i].average[j], &catalog[i].secfilt[j*PhotNsec]);

	/* the astrometric errors are not being carried yet (but should be!) */
	/* we use the photometric mag error as a weighting term */
	dlistR[N] = MAX (catalog[i].measure[m].dM, MIN_ERROR);
	dlistD[N] = MAX (catalog[i].measure[m].dM, MIN_ERROR);
	N++;
      }
      if (N < STAR_TOOFEW) { /* too few measurements */
	catalog[i].average[j].code |= ID_STAR_FEW;
      } else {
	catalog[i].average[j].code &= ~ID_STAR_FEW;
      }	

      /* in here, we should be fitting the parallax and proper-motion components */

      liststats (listR, dlistR, N, &statsR);
      liststats (listR, dlistR, N, &statsD);

      catalog[i].average[j].R = statsR.mean;
      catalog[i].average[j].dR = statsR.sigma;

      catalog[i].average[j].D = statsD.mean;
      catalog[i].average[j].dD = statsD.sigma;

      chisq = 0.5*(statsR.chisq + statsD.chisq);
      catalog[i].average[j].Xp = (statsR.Nmeas > 1) ? 100.0*log10(chisq) : NO_MAG;

    }
  }
  return (TRUE);
}

