# include "addstar.h"

// XXX this function is somewhat specific to the elixir format output files 
// it is capable of distinguishing several format versions defined for elixir/psphot

// examine the header sets and set the Image entries for the the valid images
int LoadData (FILE *f, char *file, Image **images, int *nvalid, Stars **stars, int *Nstars, Header **headers, int *extsize, HeaderSet *headerSets, int Nimages) {

  char *name;
  int i, j, Nvalid, Nhead, Ndata, Nskip;
  Stars *inStars;

  if (images[0] == NULL) {
    Nvalid = 0;
    NVALID = 10;
    ALLOCATE (images[0], Image, NVALID);
  } else {
    Nvalid = *nvalid;
    NVALID = Nvalid + 10;
    REALLOCATE (images[0], Image, NVALID);
  }    

  // find image rootname
  name = filebasename (file);

  // now run through the images, interpret the headers and read the stars
  for (i = 0; i < Nimages; i++) {
    Nhead = headerSets[i].extnum_head;

    if (VERBOSE) fprintf (stderr, "reading header for %s (%s)\n", headerSets[i].exthead, headerSets[i].extdata);
    if (!ReadImageHeader (headers[Nhead], &images[0][Nvalid], 0)) {
      fprintf (stderr, "skipping %s\n", headerSets[i].exthead);
      continue;
    }
    images[0][Nvalid].imageID = Nvalid;
    images[0][Nvalid].externID = 0;
    images[0][Nvalid].sourceID = 0;

    // XXX EAM : I seemed to have dropped the ability to support TEXT (old-style cmp format files).
    // I need to detect them here and load them with ReadStarsTEXT instead of calling the code
    // below.

    // XXX use something to set the chip name? EXTNAME?
    if (!strcmp(headerSets[i].exthead, "PHU") && (Nimages == 1)) {
      snprintf (images[0][Nvalid].name, 64, "%s", name);
    } else {
      snprintf (images[0][Nvalid].name, 64, "%s[%s]", name, headerSets[i].exthead);
    }

    // skip the table if there is no data segment (eg, mosaic WRP image)
    if (!strcmp(headerSets[i].extdata, "NONE")) {
      Nvalid++;
      CHECK_REALLOCATE (images[0], Image, NVALID, Nvalid, 10);
      continue;
    }

    // advance the pointer to the start of the corresponding table block
    Ndata = headerSets[i].extnum_data;
    Nskip = 0;
    for (j = 0; j < Ndata; j++) {
      Nskip += extsize[j];
    }
    fseek (f, Nskip, SEEK_SET); 
	 
    inStars = ReadStarsFITS (f, headers[Nhead], headers[Ndata], &images[0][Nvalid].nstar);
    inStars = FilterStars (inStars, &images[0][Nvalid], Nvalid);
    *stars = MergeStars (*stars, Nstars, inStars, images[0][Nvalid].nstar);
    Nvalid++;
    CHECK_REALLOCATE (images[0], Image, NVALID, Nvalid, 10);
  }
  free (name);
  *nvalid = Nvalid;
  return (TRUE);
}

