# include "addstar.h"

int load2mass_catalog (Catalog *catalog, Stars *stars, int Nstars) {

  int i, j, Nsec, Nmeas, Nave, NMEAS, NAVE;

  Nsec = GetPhotcodeNsecfilt ();
  Nave = catalog[0].Naverage;
  Nmeas = catalog[0].Nmeasure;
   
  NAVE = Nave + 100;
  NMEAS = Nmeas + 100;
  REALLOCATE (catalog[0].average, Average, NAVE);
  REALLOCATE (catalog[0].secfilt, SecFilt, NAVE*Nsec);
  REALLOCATE (catalog[0].measure, Measure, NMEAS);

  for (i = 0; i < Nstars; i+=3) {

    // construct an average object for this object
    // XXX for now, the output objects will have limited astrometric interpretation...
    // XXX every 3 stars represents 3 measurements and 1 average
    catalog[0].average[Nave].R     = stars[i].average.R;
    catalog[0].average[Nave].D     = stars[i].average.D;
    catalog[0].average[Nave].dR    = 0;
    catalog[0].average[Nave].dD    = 0;
    catalog[0].average[Nave].uR    = 0;
    catalog[0].average[Nave].uD    = 0;
    catalog[0].average[Nave].duR   = 0;
    catalog[0].average[Nave].duD   = 0;
    catalog[0].average[Nave].P     = 0;
    catalog[0].average[Nave].dP    = 0;

    // XXX for now, set the average mag data to NULL
    catalog[0].average[Nave].Nmeasure  	   = 0;
    catalog[0].average[Nave].Nmissing  	   = 0;
    catalog[0].average[Nave].Xp        	   = NAN_S_SHORT;
    catalog[0].average[Nave].measureOffset = Nmeas;
    catalog[0].average[Nave].missingOffset = -1;
    catalog[0].average[Nave].flags         = 0;

    for (j = 0; j < Nsec; j++) {
      catalog[0].secfilt[Nave*Nsec+j].M     = NAN;
      catalog[0].secfilt[Nave*Nsec+j].dM    = NAN;
      catalog[0].secfilt[Nave*Nsec+j].Xm    = NAN_S_SHORT;
      catalog[0].secfilt[Nave*Nsec+j].M_20  = NAN_S_SHORT;
      catalog[0].secfilt[Nave*Nsec+j].M_80  = NAN_S_SHORT;
      catalog[0].secfilt[Nave*Nsec+j].Ncode = 0;
      catalog[0].secfilt[Nave*Nsec+j].Nused = 0;
    }

    // we now have the min chisq row. use this to supply the other filter values....
    for (j = 0; j < 3; j++) {
      catalog[0].measure[Nmeas]           = stars[i+j].measure;

      catalog[0].measure[Nmeas].dR        = 0.0;
      catalog[0].measure[Nmeas].dD        = 0.0;
      catalog[0].measure[Nmeas].dt        = NAN_S_SHORT;

      // XXX what about averef?

      catalog[0].average[Nave].Nmeasure++;
      Nmeas ++;
      CHECK_REALLOCATE (catalog[0].measure, Measure, NMEAS, Nmeas, 100);
    }

    Nave ++;
    if (Nave >= NAVE) {
      NAVE += 100;
      REALLOCATE (catalog[0].average, Average, NAVE);
      REALLOCATE (catalog[0].secfilt, SecFilt, NAVE*Nsec);
    }
  }
  catalog[0].Naverage = Nave;
  catalog[0].Nmeasure = Nmeas;
  catalog[0].Nsecf_mem = Nave*Nsec;
  return (TRUE);
}
