# include "addstar.h"

// given a file with the pointer at the start of the table block and the 
// corresponding image header, load the stars from the table
Stars *ReadStarsFITS (FILE *f, Header *header, Header *in_theader, unsigned int *nstars) {

  int i, Nskip, Nstars;
  char type[80];
  Header theader;
  FTable table;
  Stars *stars;
  
  if (in_theader == NULL) {
    table.header = &theader;
  } else {
    table.header = in_theader;
  }

  /* load the table header (skip this?) */
  if (in_theader == NULL) {
    if (!gfits_fread_header (f, &theader)) {
      fprintf (stderr, "ERROR: can't read table header\n");
      exit (1);
    }
  } else {
    Nskip = in_theader[0].size;
    fseek (f, Nskip, SEEK_CUR); 
  }

  /* load the table data */
  if (!gfits_fread_ftable_data (f, &table)) {
    fprintf (stderr, "ERROR: can't read table header\n");
    exit (1);
  }

  if (!gfits_scan (&theader, "EXTTYPE", "%s", 1, type)) {
    strcpy (type, "SMPDATA");
  }

  stars = NULL;
  if (!strcmp (type, "SMPDATA")) {
    stars = ConvertSMPDATA (&table, &Nstars);
  }
# if (0)
  if (!strcmp (type, "PS1DATA")) {
    stars = ConvertPS1DATA (&table, &Nstars);
  }
# endif
  if (stars == NULL) {
    fprintf (stderr, "ERROR: invalid table type %s\n", type);
    exit (1);
  }
  if (*nstars != Nstars) {
    fprintf (stderr, "WARNING: inconsistent number of stars? %d vs %d\n", *nstars, Nstars);
  }
  *nstars = Nstars;
  return stars;
}

Stars *ConvertSMPDATA (FTable *table, int *nstars) {

  int i, Nstars, swapped;
  Stars *stars = NULL;
  SMPData *smpdata = NULL;

  swapped = FALSE;
  smpdata = gfits_table_get_SMPData (table, &Nstars, &swapped);
  /* XXX we need to check at least the size of the loaded table */

  ALLOCATE (stars, Stars, Nstars);
  for (i = 0; i < Nstars; i++) {
    stars[i].X      = smpdata[i].X;
    stars[i].Y      = smpdata[i].Y;
    stars[i].M      = smpdata[i].M;
    stars[i].dM     = smpdata[i].dM*0.001;
    stars[i].dophot = smpdata[i].dophot;

    stars[i].Mgal   = smpdata[i].M;
    stars[i].Map    = smpdata[i].dM;
    stars[i].fx     = smpdata[i].fx;
    stars[i].fy     = smpdata[i].fy;
    stars[i].df     = smpdata[i].df;
  }    
  *nstars = Nstars;
  return (stars);
}

# if (0)
Stars *ConvertPS1DATA (FTable *table, int *nstars) {

  int i, Nstars;
  Stars *stars;
  PS1Data *ps1data;

  ps1data = gfits_table_get_PS1Data (table, &Nstars, NULL);

  ALLOCATE (stars, Stars, Nstars);
  for (i = 0; i < Nstars; i++) {
    stars[i].X      = ps1data[i].X;
    stars[i].Y      = ps1data[i].Y;
    stars[i].M      = ps1data[i].M;
    stars[i].dM     = ps1data[i].dM;
    stars[i].dophot = ps1data[i].dophot;

    stars[i].Mgal   = ps1data[i].M;
    stars[i].Map    = ps1data[i].dM;
    stars[i].fx     = ps1data[i].fx;
    stars[i].fy     = ps1data[i].fy;
    stars[i].df     = ps1data[i].df;
  }    
  *nstars = Nstars;
  return (stars);
}
# endif
