# include <dvo.h>

// return options: 
// * error (cannot lock, open, read, etc)
// * empty (file is not found)
// * ok

int dvo_catalog_secfilt_to_primary (Catalog *catalog, SecFilt **myPrimary, SecFilt **mySecfilt, int *myNsecfilt) {

  int i, j, Nallfilt, Nsecfilt, Ntotal;

  SecFilt *primary;
  SecFilt *secfilt;

  if (catalog[0].secfilt == NULL) {       
    fprintf (stderr, "missing secfilt, cannot build output averages (dvo_catalog_split.c)\n");
    exit (1);
  }
  secfilt = catalog[0].secfilt;

  // XXX this translation only works if we have loaded / created a matched average/secfilt set
  assert (catalog[0].Nsecf_mem == catalog[0].Nsecfilt*catalog[0].Naverage);

  Nallfilt = catalog[0].Nsecfilt;
  Nsecfilt = catalog[0].Nsecfilt - 1;
  Ntotal = Nsecfilt * catalog[0].Naverage;
  ALLOCATE (primary, SecFilt, catalog[0].Naverage);
  ALLOCATE (secfilt, SecFilt, Ntotal);

  for (i = 0; i < catalog[0].Naverage; i++) {
    primary[i] = secfilt[i*Nallfilt + 0];
    for (j = 0; j < Nsecfilt; j++) {
      secfilt[i*Nsecfilt + j] = catalog[0].secfilt[i*Nallfilt + j + 1];
    }
  }		
  catalog[0].Nsecfilt --;
  catalog[0].Nsecf_mem = catalog[0].Naverage*catalog[0].Nsecfilt;

  *myPrimary = primary;
  *mySecfilt = secfilt;
  *myNsecfilt = Nsecfilt;
  return (TRUE);
}

int dvo_catalog_primary_to_secfilt (Catalog *catalog, SecFilt *primary, int Naves) {

  int Ntmpfilt, Nsecfilt, Ntotal, i, j;
  SecFilt *tmpfilt;

  tmpfilt  = catalog[0].secfilt;
  Ntmpfilt = catalog[0].Nsecfilt;

  // we do NOT modify Nsecf_disk; this operation only modifies in in-memory values

  catalog[0].Nsecfilt ++;
  Nsecfilt = catalog[0].Nsecfilt;
  Ntotal = Nsecfilt * Naves;

  catalog[0].Nsecf_mem = Ntotal;

  ALLOCATE (catalog[0].secfilt, SecFilt, Ntotal);
  for (i = 0; i < Naves; i++) {
    catalog[0].secfilt[i*Nsecfilt + 0] = primary[i];
    for (j = 0; j < Ntmpfilt; j++) {
      catalog[0].secfilt[i*Nsecfilt + j + 1] = tmpfilt[i*Ntmpfilt + j];
    }
  }		
  free (tmpfilt);
  free (primary);
  return (TRUE);
}

int dvo_catalog_save_subcat (Catalog *catalog, FTable *ftable, int start, int Nrows, int Ndisk, int Ntotal) {

  Matrix matrix;

  /* rewind file pointers and truncate (file is still open) */
  fseek (catalog->f, 0, SEEK_SET);

  // write PHU header
  if (!gfits_fwrite_header  (catalog->f, &catalog->header)) {
    fprintf (stderr, "can't write primary header");
    return (FALSE);
  }

  // write the PHU matrix; this is probably a NOP, do I have to keep it in?
  gfits_create_matrix (&catalog->header, &matrix);
  if (!gfits_fwrite_matrix  (catalog->f, &matrix)) {
    fprintf (stderr, "can't write primary matrix");
    gfits_free_matrix (&matrix);
    return (FALSE);
  }
  gfits_free_matrix (&matrix);

  // write the table data
  if (!gfits_fwrite_ftable_range (catalog->f, ftable, start, Nrows, Ndisk, Ntotal)) {
    fprintf (stderr, "can't write table data");
    return (FALSE);
  }
  return (TRUE);
}

int dvo_catalog_open_subcat (Catalog *catalog, Catalog **Subcat, Header *header, char *name, int VERBOSE) {

  int Nskip, status;
  char *path, string[80];
  Catalog *subcat;

  /* in split mode, we need to init & open the corresponding measure file (even if we do not read
   * any data in at this stage) */
  ALLOCATE (subcat, Catalog, 1);
  dvo_catalog_init (subcat, TRUE);

  *Subcat = subcat;

  /* needed to find the split files below */
  path = pathname (catalog[0].filename);

  /* get split filename from main header (paths relative to cpt file) */
  if (!gfits_scan (&catalog[0].header, name,  "%s", 1, string)) {
    free (path);
    return (DVO_CAT_OPEN_FAIL);
  }
  ALLOCATE (subcat[0].filename, char, strlen(path) + strlen(string) + 2);
  sprintf (subcat[0].filename, "%s/%s", path, string);
  free (path);

  /* lock & open catalog file */
  status = dvo_catalog_lock (subcat, catalog[0].lockmode);
  if (status != DVO_CAT_OPEN_OK) {
    if (VERBOSE) {
      if (status == DVO_CAT_OPEN_EMPTY) {
	fprintf (stderr, "%s (%s) is empty\n", name, subcat[0].filename);
      } else {
	fprintf (stderr, "failure to lock %s (%s)\n", name, subcat[0].filename);
      }
    }
    return (status);
  }

  /* read PHU */
  if (!gfits_load_header (subcat[0].f, &subcat[0].header)) {
    if (VERBOSE) fprintf (stderr, "error reading %s header: %s\n", name, subcat[0].filename);
    return (DVO_CAT_OPEN_FAIL);
  }
  Nskip = gfits_data_size (&subcat[0].header);
  fseek (subcat[0].f, Nskip, SEEK_CUR);

  /* read Measure table header */
  if (!gfits_fread_header (subcat[0].f, header)) {
    if (VERBOSE) fprintf (stderr, "can't read %s PHU header\n", name);
    gfits_free_header (&subcat[0].header);
    return (DVO_CAT_OPEN_FAIL);
  }
  return (DVO_CAT_OPEN_OK);
}

int dvo_catalog_load_split (Catalog *catalog, int VERBOSE) {

  int Nbytes, Nitems, Naverage, Nmeasure, Nmissing, Nsecfilt, status;
  Header header;
  FTable ftable;
  SecFilt *primary;

  /* ftable header storage for below */
  ftable.header = &header;
  ftable.buffer = NULL;
  header.buffer = NULL;
  primary = NULL;

  /* get the components from the header - these duplicate information in the split files (NAXIS2) */
  if (!gfits_scan (&catalog[0].header, "NSTARS",   "%d", 1, &Naverage)) return (FALSE);
  if (!gfits_scan (&catalog[0].header, "NMEAS",    "%d", 1, &Nmeasure)) return (FALSE);
  if (!gfits_scan (&catalog[0].header, "NMISS",    "%d", 1, &Nmissing)) return (FALSE);
  if (!gfits_scan (&catalog[0].header, "NSECFILT", "%d", 1, &Nsecfilt)) Nsecfilt = 0;

  /* save the current number so we can do partial updates */
  catalog[0].Naves_disk = Naverage;
  catalog[0].Nmeas_disk = Nmeasure;
  catalog[0].Nmiss_disk = Nmissing;
  catalog[0].Nsecf_disk = Naverage * Nsecfilt;

  /**  Nsecfilt is unusual: it does not list the number of data items in the table
       instead, the number of items is Nsecfilt * Naverage.  **/
  catalog[0].Nsecfilt  = Nsecfilt;

  /* default values, but we will assign these a valid value before we exit (even if empty) */
  catalog[0].average = NULL;
  catalog[0].measure = NULL;
  catalog[0].missing = NULL;
  catalog[0].secfilt = NULL;

  /*** Average Table ***/
  if (catalog[0].catflags & LOAD_AVES) {
    /* move pointer past header -- must be already read (load_catalog) */
    Nbytes = catalog[0].header.size + gfits_data_size (&catalog[0].header);
    fseek (catalog[0].f, Nbytes, SEEK_SET);
    /* read Average table header */
    if (!gfits_fread_header (catalog[0].f, &header)) { 
      if (VERBOSE) fprintf (stderr, "can't read table average header");
      return (FALSE);
    }
    /* read Average table data : format is irrelevant here */
    if (!gfits_fread_ftable_data (catalog[0].f, &ftable)) { 
      if (VERBOSE) fprintf (stderr, "can't read table average data");
      return (FALSE);
    }
    /* convert the saved version of the table to the internal version.  Old versions of DVO stored
     * one of the average magnitudes in Average.  We save this in case it is needed below.  NOTE:
     * primary is only used if we read in the secfilt table, otherwise it should be freed */
    catalog[0].average = FtableToAverage (&ftable, &Naverage, &catalog[0].catformat, &primary);
    if (Naverage != catalog[0].Naves_disk) {
      fprintf (stderr, "Warning: mismatch between Naverage in PHU and Table headers (%d vs %d)\n", Naverage, catalog[0].Naves_disk);
    }
    gfits_free_header (&header);
    catalog[0].Naverage = catalog[0].Naves_disk;
    catalog[0].Naves_off = 0;
  } else {
    ALLOCATE (catalog[0].average, Average, 1);
    catalog[0].Naverage = 0;
    catalog[0].Naves_off = catalog[0].Naves_disk;
  }

  /*** Measure Table ***/
  status = dvo_catalog_open_subcat (catalog, &catalog[0].measure_catalog, ftable.header, "MEASURE", VERBOSE);
  if (status == DVO_CAT_OPEN_FAIL) {
    return (FALSE);
  }
  if ((status == DVO_CAT_OPEN_EMPTY) && (catalog[0].Nmeas_disk > 0)) {
    return (FALSE);
  }
  if ((status != DVO_CAT_OPEN_EMPTY) && (catalog[0].catflags & LOAD_MEAS)) {
    // XXX this allows an empty Measure catalog with non-empty Average catalog : is that OK?
    /* read Measure table data */
    if (!gfits_fread_ftable_data (catalog[0].measure_catalog[0].f, &ftable)) {
      if (VERBOSE) fprintf (stderr, "can't read table measure data\n");
      return (FALSE);
    }
    /* convert data format to internal : returns number of row read in Nmeasure */
    catalog[0].measure = FtableToMeasure (&ftable, &Nmeasure, &catalog[0].catformat);
    if (Nmeasure != catalog[0].Nmeas_disk) {
      fprintf (stderr, "Warning: mismatch between Nmeasure in PHU and Table headers (%d vs %d)\n", Nmeasure, catalog[0].Nmeas_disk);
    }
    catalog[0].Nmeasure = catalog[0].Nmeas_disk;
    catalog[0].Nmeas_off = 0;
  } else {
    // XXX is it necessary to generate a template header here?
    gfits_create_header (&catalog[0].measure_catalog[0].header);
    ALLOCATE (catalog[0].measure, Measure, 1);
    catalog[0].Nmeasure = 0;
    catalog[0].Nmeas_off = catalog[0].Nmeas_disk;
  }
  gfits_free_header (&header);

  /*** Missing Table ***/
  status = dvo_catalog_open_subcat (catalog, &catalog[0].missing_catalog, ftable.header, "MISSING", VERBOSE);
  if (status == DVO_CAT_OPEN_FAIL) {
    return (FALSE);
  }
  if ((status == DVO_CAT_OPEN_EMPTY) && (catalog[0].Nmiss_disk > 0)) {
    return (FALSE);
  }
  if ((status != DVO_CAT_OPEN_EMPTY) && (catalog[0].catflags & LOAD_MISS)) {
    /* read Missing table data */
    if (!gfits_fread_ftable_data (catalog[0].missing_catalog[0].f, &ftable)) {
      if (VERBOSE) fprintf (stderr, "can't read table missing data\n");
      return (FALSE);
    }
    /* no conversions currently defined : this just does the byte swap */
    catalog[0].missing = gfits_table_get_Missing (&ftable, &Nmissing, NULL);
    if (Nmissing != catalog[0].Nmiss_disk) {
      fprintf (stderr, "Warning: mismatch between Nmissing in PHU and Table headers (%d vs %d)\n", Nmissing, catalog[0].Nmiss_disk);
    }
    catalog[0].Nmissing = catalog[0].Nmiss_disk;
    catalog[0].Nmiss_off = 0;
  } else {
    // XXX is it necessary to generate a template header here?
    gfits_create_header (&catalog[0].missing_catalog[0].header);
    ALLOCATE (catalog[0].missing, Missing, 1);
    catalog[0].Nmissing = 0;
    catalog[0].Nmiss_off = catalog[0].Nmiss_disk;
  }
  gfits_free_header (ftable.header);

  /*** Secfilt Table ***/
  status = dvo_catalog_open_subcat (catalog, &catalog[0].secfilt_catalog, ftable.header, "SECFILT", VERBOSE);
  if (status == DVO_CAT_OPEN_FAIL) {
    return (FALSE);
  }
  if ((status == DVO_CAT_OPEN_EMPTY) && (catalog[0].Nsecf_disk > 0)) {
    return (FALSE);
  }
  if ((status != DVO_CAT_OPEN_EMPTY) && (catalog[0].catflags & LOAD_SECF)) {
    /* read secfilt table data */
    if (!gfits_fread_ftable_data (catalog[0].secfilt_catalog[0].f, &ftable)) {
      if (VERBOSE) fprintf (stderr, "can't read table secfilt data\n");
      return (FALSE);
    }
    catalog[0].secfilt = FtableToSecFilt (&ftable, &Nitems, &catalog[0].catformat);
    if (Nitems != catalog[0].Nsecf_disk) {
      fprintf (stderr, "Warning: mismatch between Nsecfilt items in PHU and Table headers (%d vs %d)\n", Nitems, catalog[0].Nsecf_disk);
    }
    catalog[0].Nsecf_mem = catalog[0].Nsecf_disk;
    catalog[0].Nsecf_off = 0;

    /* if primary is defined, we were supplied with one additional average magnitude from Average
       we need to interleave these magnitudes with the secfilt entries just loaded */
    if (primary != NULL) {
      // this modifies catalog.Nsecf_mem,Nsecfilt
      dvo_catalog_primary_to_secfilt (catalog, primary, catalog[0].Naves_disk);
    } 
  } else {
    if (primary != NULL) {
      free (primary);
      catalog[0].Nsecfilt ++;
    }
    gfits_create_header (&catalog[0].secfilt_catalog[0].header);
    ALLOCATE (catalog[0].secfilt, SecFilt, 1);
    catalog[0].Nsecf_mem = 0;
    catalog[0].Nsecf_off = catalog[0].Nsecf_disk;
  }
  gfits_free_header (ftable.header);

  return (TRUE);
}

// I need to always read both average and secfilt at the same time to correctly manage the
// primary secfilt values...
int dvo_catalog_load_segment_split (Catalog *catalog, int VERBOSE, int start, int Nrows) {

  int Nbytes, Naverage, Nexpect, Nitems, Nmeasure, Nmissing;
  Header header;
  FTable ftable;
  SecFilt *primary;

  /* ftable header storage for below */
  ftable.header = &header;
  ftable.buffer = NULL;
  header.buffer = NULL;
  primary = NULL;

  /*** Average (& SecFilt) Table ***/
  if (catalog[0].catflags & LOAD_AVES) {

    /*** load the Average data ***/
    /* move pointer past header and matrix -- must be already read (load_catalog) */
    Nbytes = catalog[0].header.size + gfits_data_size (&catalog[0].header);
    fseek (catalog[0].f, Nbytes, SEEK_SET);
    /* read Average table header */
    if (!gfits_fread_header (catalog[0].f, &header)) {
      if (VERBOSE) fprintf (stderr, "can't read table average header");
      return (FALSE);
    }
    /* read Average table data : format is irrelevant here */
    if (!gfits_fread_ftable_range (catalog[0].f, &ftable, start, Nrows)) {
      if (VERBOSE) fprintf (stderr, "can't read table average data");
      return (FALSE);
    }

    /* convert the saved version of the table to the internal version.  Old versions of DVO stored
     * one of the average magnitudes in Average.  We save this in case it is needed below.  NOTE:
     * primary is only used if we read in the secfilt table, otherwise it should be freed */
    catalog[0].average = FtableToAverage (&ftable, &Naverage, &catalog[0].catformat, &primary);
    if (Naverage != Nrows) {
      // XXX this condition denotes the eof has been reached; not an error or a warning
      // fprintf (stderr, "Warning: mismatch between Naverage in PHU and Table headers (%d vs %d)\n", Naverage, Nrows);
    }
    gfits_free_header (&header);
    catalog[0].Naverage = Naverage;
    catalog[0].Naves_off = start;

    /*** load the secfilt data ***/
    Catalog *subcat = catalog[0].secfilt_catalog;

    /* move pointer past header -- must be already read (load_catalog) */
    Nbytes = subcat[0].header.size + gfits_data_size (&subcat[0].header);
    fseek (subcat[0].f, Nbytes, SEEK_SET);

    /* read Secfilt table header */
    if (!gfits_fread_header (subcat[0].f, &header)) {
      if (VERBOSE) fprintf (stderr, "can't read table measure header");
      return (FALSE);
    }
    /* read Secfilt table data : format is irrelevant here */
    if (!gfits_fread_ftable_range (subcat[0].f, &ftable, start*catalog[0].Nsecfilt, catalog[0].Naverage*catalog[0].Nsecfilt)) {
      if (VERBOSE) fprintf (stderr, "can't read table measure data");
      return (FALSE);
    }

    Nexpect = catalog[0].Naverage * catalog[0].Nsecfilt;
    catalog[0].secfilt = FtableToSecFilt (&ftable, &Nitems, &catalog[0].catformat);
    if (Nitems != Nexpect) {
      fprintf (stderr, "Warning: mismatch between Nsecfilt items in PHU and Table headers (%d vs %d)\n", Nitems, Nexpect);
    }
    catalog[0].Nsecf_mem = catalog[0].Naverage * catalog[0].Nsecfilt;
    catalog[0].Nsecf_off = start               * catalog[0].Nsecfilt;

    /* if primary is defined, we were supplied with one additional average magnitude from Average
       we need to interleave these magnitudes with the secfilt entries just loaded */
    if (primary != NULL) {
      dvo_catalog_primary_to_secfilt (catalog, primary, Nrows);
    } 
    gfits_free_header (&header);
  }

  // XXX check the open status of the catalog
  if (catalog[0].catflags & LOAD_MEAS) {

    Catalog *subcat = catalog[0].measure_catalog;

    /* move pointer past header -- must be already read (load_catalog) */
    Nbytes = subcat[0].header.size + gfits_data_size (&subcat[0].header);
    fseek (subcat[0].f, Nbytes, SEEK_SET);

    /* read Measure table header */
    if (!gfits_fread_header (subcat[0].f, &header)) {
      if (VERBOSE) fprintf (stderr, "can't read table measure header");
      return (FALSE);
    }
    /* read Measure table data : format is irrelevant here */
    if (!gfits_fread_ftable_range (subcat[0].f, &ftable, start, Nrows)) {
      if (VERBOSE) fprintf (stderr, "can't read table measure data");
      return (FALSE);
    }

    /* convert data format to internal : returns number of row read in Nmeasure */
    catalog[0].measure = FtableToMeasure (&ftable, &Nmeasure, &catalog[0].catformat);
    if (Nmeasure != Nrows) {
      fprintf (stderr, "Warning: mismatch between Nmeasure in PHU and Table headers (%d vs %d)\n", Nmeasure, Nrows);
    }
    gfits_free_header (&header);
    catalog[0].Nmeasure = Nmeasure;
    catalog[0].Nmeas_off = start;
  }

  // XXX check the open status of the catalog?
  if (catalog[0].catflags & LOAD_MISS) {

    Catalog *subcat = catalog[0].missing_catalog;

    /* move pointer past header -- must be already read (load_catalog) */
    Nbytes = subcat[0].header.size + gfits_data_size (&subcat[0].header);
    fseek (subcat[0].f, Nbytes, SEEK_SET);

    /* read Missing table header */
    if (!gfits_fread_header (subcat[0].f, &header)) {
      if (VERBOSE) fprintf (stderr, "can't read table missing header");
      return (FALSE);
    }
    /* read Missing table data : format is irrelevant here */
    if (!gfits_fread_ftable_range (subcat[0].f, &ftable, start, Nrows)) {
      if (VERBOSE) fprintf (stderr, "can't read table missing data");
      return (FALSE);
    }

    /* no conversions currently defined : this just does the byte swap */
    catalog[0].missing = gfits_table_get_Missing (&ftable, &Nmissing, NULL);
    if (Nmissing != Nrows) {
      fprintf (stderr, "Warning: mismatch between Nmissing in PHU and Table headers (%d vs %d)\n", Nmissing, Nrows);
    }
    gfits_free_header (&header);
    catalog[0].Nmissing = Nmissing;
    catalog[0].Nmiss_off = start;
  }
  return (TRUE);
}

/* save_catalog_split writes all data currently in memory to disk */
int dvo_catalog_save_split (Catalog *catalog, char VERBOSE) {

  int Nitems;
  Header header;
  FTable ftable;
  SecFilt *primary, *secfilt;
  int Nsecfilt;
  int Naves_disk_new, Nmeas_disk_new, Nmiss_disk_new, Nsecf_disk_new;
  int first, start, Nrows;

  ftable.header = &header;
  ftable.buffer = NULL;
  header.buffer = NULL;
  primary = NULL;
  
  // skip empty catalogs: it is illegal to have Measures without corresponding Averages
  Naves_disk_new = MAX (catalog[0].Naves_disk, catalog[0].Naverage + catalog[0].Naves_off);
  if (Naves_disk_new == 0) {
    if (VERBOSE) fprintf (stderr, "no stars in catalog, skipping\n");
    return (TRUE);
  }

  // for the appropriate types, pull out the first secfilt and pass to AverageToFtable as primary
  switch (catalog[0].catformat) {
    case DVO_FORMAT_ELIXIR: // special case for ELIXIR
    case DVO_FORMAT_LONEOS: // special case for LONEOS
      dvo_catalog_secfilt_to_primary (catalog, &primary, &secfilt, &Nsecfilt);
      break;
    default:
      primary = NULL;
      secfilt = catalog[0].secfilt;
      Nsecfilt = catalog[0].Nsecfilt;
      break;
  }

  Nmeas_disk_new = MAX (catalog[0].Nmeas_disk, catalog[0].Nmeasure + catalog[0].Nmeas_off);
  Nmiss_disk_new = MAX (catalog[0].Nmiss_disk, catalog[0].Nmissing + catalog[0].Nmiss_off);
  Nsecf_disk_new = MAX (catalog[0].Nsecf_disk, catalog[0].Naverage*Nsecfilt + catalog[0].Nsecf_off);

  /* make sure header is consistent with data */
  gfits_modify (&catalog[0].header, "NSTARS",   "%d", 1, Naves_disk_new);
  gfits_modify (&catalog[0].header, "NMEAS",    "%d", 1, Nmeas_disk_new);
  gfits_modify (&catalog[0].header, "NMISS",    "%d", 1, Nmiss_disk_new);
  gfits_modify (&catalog[0].header, "NSECFILT", "%d", 1, Nsecfilt);
  gfits_modify (&catalog[0].header, "EXTEND",   "%t", 1, TRUE);

  /* in split mode, we can save only part of the data */ 

  /*** Average Table ***/
  if ((catalog[0].catflags & LOAD_AVES) && (catalog[0].average != NULL)) {

    first  = 0;                    // first row in memory to write
    start  = catalog[0].Naves_off; // first disk row to write
    Nrows  = catalog[0].Naverage - first;

    assert (Nrows >= 0);
    assert (first >= 0);
    assert (first <= catalog[0].Naverage);
    assert (catalog[0].Naves_disk >= catalog[0].Naves_off);

    /* convert internal to external format */
    if (!AverageToFtable (&ftable, &catalog[0].average[first], Nrows, catalog[0].catformat, primary)) {
      fprintf (stderr, "trouble converting format\n");
      goto failure;
    }

    if (!dvo_catalog_save_subcat (catalog, &ftable, start, Nrows, catalog[0].Naves_disk, Naves_disk_new)) {
      fprintf (stderr, "failure writing Average table\n");
      goto failure;
    }
    gfits_free_header (&header);
    gfits_free_table (&ftable);
  } else {
    // even if we do not save the average table, we need to keep the header in sync
    /* rewind file pointers and truncate (file is still open) */
    fseek (catalog[0].f, 0, SEEK_SET);

    /* write table PHU header - always write this out */
    /* XXX EAM : check if disk file size has changed */
    if (!gfits_fwrite_header  (catalog[0].f, &catalog[0].header)) {
      fprintf (stderr, "can't write primary header");
      goto failure;
    }
  }

  /*** Measure Table ***/
  if ((catalog[0].catflags & LOAD_MEAS) && (catalog[0].measure != NULL)) {

    first  = 0;                    // first row in memory to write
    start  = catalog[0].Nmeas_off; // first disk row to write
    Nrows  = catalog[0].Nmeasure - first;

    assert (Nrows >= 0);
    assert (first >= 0);
    assert (first <= catalog[0].Nmeasure);
    assert (catalog[0].Nmeas_disk >= catalog[0].Nmeas_off);

    // convert to external table format
    if (!MeasureToFtable (&ftable, &catalog[0].measure[first], Nrows, catalog[0].catformat)) {
      fprintf (stderr, "trouble converting format\n");
      goto failure;
    }

    // write out Measure table
    if (!dvo_catalog_save_subcat (catalog[0].measure_catalog, &ftable, start, Nrows, catalog[0].Nmeas_disk, Nmeas_disk_new)) {
      fprintf (stderr, "trouble writing Measure table\n");
      goto failure;
    }
    gfits_free_header (&header);
    gfits_free_table (&ftable);
  }

  /*** Missing Table ***/
  if ((catalog[0].catflags & LOAD_MISS) && (catalog[0].missing != NULL)) {

    if (catalog[0].Nmiss_off != 0) {
      fprintf (stderr, "inconsistency: Missing table cannot be written in segments\n");
      goto failure;
    }

    // convert to external table format
    if (!gfits_table_set_Missing (&ftable, catalog[0].missing, catalog[0].Nmissing)) {
      fprintf (stderr, "trouble converting format\n");
      goto failure;
    }

    // write out Missing table (must write out entire table)
    if (!dvo_catalog_save_subcat (catalog[0].missing_catalog, &ftable, 0, catalog[0].Nmissing, catalog[0].Nmissing, catalog[0].Nmissing)) {
      fprintf (stderr, "trouble writing Missing Table\n");
      goto failure;
    }
    gfits_free_header (&header);
    gfits_free_table (&ftable);
  }

  /*** Secfilt Table ***/
  if ((catalog[0].catflags & LOAD_SECF) && (catalog[0].secfilt != NULL)) {

    first  = 0;                    // first row in memory to write
    start  = catalog[0].Nsecf_off; // first disk row to write
    Nitems = catalog[0].Nsecf_mem;
    Nrows  = Nitems - first;

    assert (Nrows >= 0);
    assert (first >= 0);
    assert (first <= Nitems);
    assert (catalog[0].Nsecf_disk >= catalog[0].Nsecf_off);
    // XXX check these for consistency...

    // convert to external table format
    SecFiltToFtable (&ftable, &secfilt[first], Nrows, catalog[0].catformat);

    // write out SecFilt table
    if (!dvo_catalog_save_subcat (catalog[0].secfilt_catalog, &ftable, start, Nrows, catalog[0].Nsecf_disk, Nsecf_disk_new)) {
      fprintf (stderr, "failure writing SecFilt table\n");
      goto failure;
    }
    gfits_free_header (&header);
    gfits_free_table (&ftable);
  }

  /* free temp storage */
  if (primary != NULL) {
    free (primary);
    free (secfilt);
  }
  return (TRUE);

failure:
  /* free temp storage */
  gfits_free_header (&header);
  gfits_free_table (&ftable);
  if (primary != NULL) {
    free (primary);
    free (secfilt);
  }
  return (FALSE);
}

/* save_catalog_split writes all data currently in memory to disk, truncating if the disk file was larger */
int dvo_catalog_save_split_complete (Catalog *catalog, char VERBOSE) {

  int Nitems;
  Header header;
  FTable ftable;
  SecFilt *primary, *secfilt;
  int Nsecfilt;
  int Naves_disk_new, Nmeas_disk_new, Nmiss_disk_new, Nsecf_disk_new;
  int first, start, Nrows;

  ftable.header = &header;
  ftable.buffer = NULL;
  header.buffer = NULL;
  primary = NULL;
  
  // skip empty catalogs: it is illegal to have Measures without corresponding Averages
  if (catalog[0].Naves_off > 0) {
    fprintf (stderr, "ERROR: only partial catalog (Average) was loaded\n");
    goto failure;
  }
  if (catalog[0].Nmeas_off > 0) {
    fprintf (stderr, "ERROR: only partial catalog (Measure) was loaded\n");
    goto failure;
  }
  if (catalog[0].Nmiss_off > 0) {
    fprintf (stderr, "ERROR: only partial catalog (Missing) was loaded\n");
    goto failure;
  }
  if (catalog[0].Nsecf_off > 0) {
    fprintf (stderr, "ERROR: only partial catalog (Secfilt) was loaded\n");
    goto failure;
  }

  if ((catalog[0].Naverage > 0) && (Naves_disk_new == 0)) {
    Naves_disk_new = catalog[0].Naverage;
    if (VERBOSE) fprintf (stderr, "resulting catalog is empty; delete it\n");
    // unlink ();
    return (TRUE);
  }

  Naves_disk_new = catalog[0].Naverage;

  // for the appropriate types, pull out the first secfilt and pass to AverageToFtable as primary
  switch (catalog[0].catformat) {
    case DVO_FORMAT_ELIXIR: // special case for ELIXIR
    case DVO_FORMAT_LONEOS: // special case for LONEOS
      dvo_catalog_secfilt_to_primary (catalog, &primary, &secfilt, &Nsecfilt);
      break;
    default:
      primary = NULL;
      secfilt = catalog[0].secfilt;
      Nsecfilt = catalog[0].Nsecfilt;
      break;
  }

  Nmeas_disk_new = catalog[0].Nmeasure;
  Nmiss_disk_new = catalog[0].Nmissing;
  Nsecf_disk_new = catalog[0].Naverage*Nsecfilt;

  /* make sure header is consistent with data */
  gfits_modify (&catalog[0].header, "NSTARS",   "%d", 1, Naves_disk_new);
  gfits_modify (&catalog[0].header, "NMEAS",    "%d", 1, Nmeas_disk_new);
  gfits_modify (&catalog[0].header, "NMISS",    "%d", 1, Nmiss_disk_new);
  gfits_modify (&catalog[0].header, "NSECFILT", "%d", 1, Nsecfilt);
  gfits_modify (&catalog[0].header, "EXTEND",   "%t", 1, TRUE);

  /* in split mode, we can save only part of the data */ 

  /*** Average Table ***/
  if ((catalog[0].catflags & LOAD_AVES) && (catalog[0].average != NULL)) {

    first  = 0;                    // first row in memory to write
    start  = catalog[0].Naves_off; // first disk row to write
    Nrows  = catalog[0].Naverage - first;

    assert (Nrows >= 0);
    assert (first >= 0);
    assert (first <= catalog[0].Naverage);
    assert (catalog[0].Naves_disk >= catalog[0].Naves_off);

    /* convert internal to external format */
    if (!AverageToFtable (&ftable, &catalog[0].average[first], Nrows, catalog[0].catformat, primary)) {
      fprintf (stderr, "trouble converting format\n");
      goto failure;
    }

    if (!dvo_catalog_save_subcat (catalog, &ftable, start, Nrows, catalog[0].Naves_disk, Naves_disk_new)) {
      fprintf (stderr, "failure writing Average table\n");
      goto failure;
    }
    gfits_free_header (&header);
    gfits_free_table (&ftable);
  } else {
    // even if we do not save the average table, we need to keep the header in sync
    /* rewind file pointers and truncate (file is still open) */
    fseek (catalog[0].f, 0, SEEK_SET);

    /* write table PHU header - always write this out */
    /* XXX EAM : check if disk file size has changed */
    if (!gfits_fwrite_header  (catalog[0].f, &catalog[0].header)) {
      fprintf (stderr, "can't write primary header");
      goto failure;
    }
  }

  /*** Measure Table ***/
  if ((catalog[0].catflags & LOAD_MEAS) && (catalog[0].measure != NULL)) {

    first  = 0;                    // first row in memory to write
    start  = catalog[0].Nmeas_off; // first disk row to write
    Nrows  = catalog[0].Nmeasure - first;

    assert (Nrows >= 0);
    assert (first >= 0);
    assert (first <= catalog[0].Nmeasure);
    assert (catalog[0].Nmeas_disk >= catalog[0].Nmeas_off);

    // convert to external table format
    if (!MeasureToFtable (&ftable, &catalog[0].measure[first], Nrows, catalog[0].catformat)) {
      fprintf (stderr, "trouble converting format\n");
      goto failure;
    }

    // write out Measure table
    if (!dvo_catalog_save_subcat (catalog[0].measure_catalog, &ftable, start, Nrows, catalog[0].Nmeas_disk, Nmeas_disk_new)) {
      fprintf (stderr, "trouble writing Measure table\n");
      goto failure;
    }
    gfits_free_header (&header);
    gfits_free_table (&ftable);
  }

  /*** Missing Table ***/
  if ((catalog[0].catflags & LOAD_MISS) && (catalog[0].missing != NULL)) {

    if (catalog[0].Nmiss_off != 0) {
      fprintf (stderr, "inconsistency: Missing table cannot be written in segments\n");
      goto failure;
    }

    // convert to external table format
    if (!gfits_table_set_Missing (&ftable, catalog[0].missing, catalog[0].Nmissing)) {
      fprintf (stderr, "trouble converting format\n");
      goto failure;
    }

    // write out Missing table (must write out entire table)
    if (!dvo_catalog_save_subcat (catalog[0].missing_catalog, &ftable, 0, catalog[0].Nmissing, catalog[0].Nmissing, catalog[0].Nmissing)) {
      fprintf (stderr, "trouble writing Missing Table\n");
      goto failure;
    }
    gfits_free_header (&header);
    gfits_free_table (&ftable);
  }

  /*** Secfilt Table ***/
  if ((catalog[0].catflags & LOAD_SECF) && (catalog[0].secfilt != NULL)) {

    first  = 0;                    // first row in memory to write
    start  = catalog[0].Nsecf_off; // first disk row to write
    Nitems = catalog[0].Nsecf_mem;
    Nrows  = Nitems - first;

    assert (Nrows >= 0);
    assert (first >= 0);
    assert (first <= Nitems);
    assert (catalog[0].Nsecf_disk >= catalog[0].Nsecf_off);
    // XXX check these for consistency...

    // convert to external table format
    SecFiltToFtable (&ftable, &secfilt[first], Nrows, catalog[0].catformat);

    // write out SecFilt table
    if (!dvo_catalog_save_subcat (catalog[0].secfilt_catalog, &ftable, start, Nrows, catalog[0].Nsecf_disk, Nsecf_disk_new)) {
      fprintf (stderr, "failure writing SecFilt table\n");
      goto failure;
    }
    gfits_free_header (&header);
    gfits_free_table (&ftable);
  }

  /* free temp storage */
  if (primary != NULL) {
    free (primary);
    free (secfilt);
  }
  return (TRUE);

failure:
  /* free temp storage */
  gfits_free_header (&header);
  gfits_free_table (&ftable);
  if (primary != NULL) {
    free (primary);
    free (secfilt);
  }
  return (FALSE);
}

/* update_catalog_split only writes new lines to file. */
int dvo_catalog_update_split (Catalog *catalog, char VERBOSE) {

  Header header;
  FTable ftable;
  SecFilt *primary, *secfilt;
  int Nsecfilt;
  int Naves_disk_new, Nmeas_disk_new, Nmiss_disk_new, Nsecf_disk_new;
  int first, start, Nrows;

  ftable.header = &header;
  ftable.buffer = NULL;
  header.buffer = NULL;

  // skip empty catalogs: it is illegal to have Measures without corresponding Averages
  Naves_disk_new = MAX (catalog[0].Naves_disk, catalog[0].Naverage + catalog[0].Naves_off);
  if (Naves_disk_new == 0) {
    if (VERBOSE) fprintf (stderr, "no stars in catalog, skipping\n");
    return (TRUE);
  }

  // for the appropriate types, pull out the first secfilt and pass to AverageToFtable as primary 
  switch (catalog[0].catformat) {
    case DVO_FORMAT_ELIXIR: // special case for ELIXIR
    case DVO_FORMAT_LONEOS: // special case for LONEOS
      dvo_catalog_secfilt_to_primary (catalog, &primary, &secfilt, &Nsecfilt);
      break;
    default:
      primary = NULL;
      secfilt = catalog[0].secfilt;
      Nsecfilt = catalog[0].Nsecfilt;
      break;
  }

  Nmeas_disk_new = MAX (catalog[0].Nmeas_disk, catalog[0].Nmeasure + catalog[0].Nmeas_off);
  Nmiss_disk_new = MAX (catalog[0].Nmiss_disk, catalog[0].Nmissing + catalog[0].Nmiss_off);
  Nsecf_disk_new = MAX (catalog[0].Nsecf_disk, catalog[0].Naverage*Nsecfilt + catalog[0].Nsecf_off);

  /* make sure header is consistent with data */
  gfits_modify (&catalog[0].header, "NSTARS",   "%d", 1, Naves_disk_new);
  gfits_modify (&catalog[0].header, "NMEAS",    "%d", 1, Nmeas_disk_new);
  gfits_modify (&catalog[0].header, "NMISS",    "%d", 1, Nmiss_disk_new);
  gfits_modify (&catalog[0].header, "NSECFILT", "%d", 1, Nsecfilt);
  gfits_modify (&catalog[0].header, "EXTEND",   "%t", 1, TRUE);

  /* in split mode, we can save only part of the data */ 

  /*** Average Table ***/
  if (catalog[0].average != NULL) {

    first  = catalog[0].Naves_disk - catalog[0].Naves_off; // first row to write (memory)
    start  = catalog[0].Naves_disk;                        // first row to write (disk)
    Nrows  = catalog[0].Naverage - first;

    assert (Nrows >= 0);
    assert (first >= 0);
    assert (first <= catalog[0].Naverage);
    assert (catalog[0].Naves_disk >= catalog[0].Naves_off);

    /* convert internal to external format */
    if (!AverageToFtable (&ftable, &catalog[0].average[first], Nrows, catalog[0].catformat, primary)) {
      fprintf (stderr, "trouble converting format\n");
      goto failure;
    }

    if (!dvo_catalog_save_subcat (catalog, &ftable, start, Nrows, catalog[0].Naves_disk, Naves_disk_new)) {
      fprintf (stderr, "failure writing Average table\n");
      goto failure;
    }
    gfits_free_header (&header);
    gfits_free_table (&ftable);
  } else {
    // even if we do not save the average table, we need to keep the header in sync
    /* rewind file pointers and truncate (file is still open) */
    fseek (catalog[0].f, 0, SEEK_SET);

    /* write table PHU header - always write this out */
    /* XXX EAM : check if disk file size has changed */
    if (!gfits_fwrite_header  (catalog[0].f, &catalog[0].header)) {
      fprintf (stderr, "can't write primary header");
      goto failure;
    }
  }

  /*** Measure Table ***/
  if (catalog[0].measure != NULL) {

    first  = catalog[0].Nmeas_disk - catalog[0].Nmeas_off;  // first row in memory to write
    start  = catalog[0].Nmeas_disk; // first disk row to write
    Nrows  = catalog[0].Nmeasure - first;

    assert (Nrows >= 0);
    assert (first >= 0);
    assert (first <= catalog[0].Nmeasure);
    assert (catalog[0].Nmeas_disk >= catalog[0].Nmeas_off);

    // convert to external table format
    if (!MeasureToFtable (&ftable, &catalog[0].measure[first], Nrows, catalog[0].catformat)) {
      fprintf (stderr, "trouble converting format\n");
      goto failure;
    }

    // write out Measure table
    if (!dvo_catalog_save_subcat (catalog[0].measure_catalog, &ftable, start, Nrows, catalog[0].Nmeas_disk, Nmeas_disk_new)) {
      fprintf (stderr, "trouble writing Measure table\n");
      goto failure;
    }
    gfits_free_header (&header);
    gfits_free_table (&ftable);
  }

  /* missing table CANNOT be written unsorted, thus it is always written 
     out in full */

  /*** Missing Table ***/

  if (catalog[0].missing != NULL) {

    if (catalog[0].Nmiss_off != 0) {
      fprintf (stderr, "inconsistency: Missing table cannot be written in segments\n");
      goto failure;
    }

    // convert to external table format
    if (!gfits_table_set_Missing (&ftable, catalog[0].missing, catalog[0].Nmissing)) {
      fprintf (stderr, "trouble converting format\n");
      goto failure;
    }

    // write out Missing table (must write out entire table)
    if (!dvo_catalog_save_subcat (catalog[0].missing_catalog, &ftable, 0, catalog[0].Nmissing, catalog[0].Nmissing, catalog[0].Nmissing)) {
      fprintf (stderr, "trouble writing Missing Table\n");
      goto failure;
    }
    gfits_free_header (&header);
    gfits_free_table (&ftable);
  }

  /*** Secfilt Table ***/
  if (catalog[0].secfilt != NULL) {

    first  = catalog[0].Nsecf_disk - catalog[0].Nsecf_off;  // first row in memory to write
    start  = catalog[0].Nsecf_disk; // first disk row to write
    Nrows  = catalog[0].Nsecf_mem - first;

    assert (Nrows >= 0);
    assert (first >= 0);
    assert (catalog[0].Nsecf_disk >= catalog[0].Nsecf_off);

    // convert to external table format
    SecFiltToFtable (&ftable, &secfilt[first], Nrows, catalog[0].catformat);

    // write out SecFilt table
    if (!dvo_catalog_save_subcat (catalog[0].secfilt_catalog, &ftable, start, Nrows, catalog[0].Nsecf_disk, Nsecf_disk_new)) {
      fprintf (stderr, "failure writing SecFilt table\n");
      goto failure;
    }
    gfits_free_header (&header);
    gfits_free_table (&ftable);
  }

  /* free temp storage */
  if (primary != NULL) {
    free (primary);
    free (secfilt);
  }

  return (TRUE);

failure:
  /* free temp storage */
  if (primary != NULL) {
    free (primary);
    free (secfilt);
  }
  return (FALSE);
}

/* in split mode, extra files are linked to catalog->measure_catalog, etc.  Each
   has a valid filename, f, header.  The primary catalog data pointers are set
   to point at the corresponding entries from the elements on the chain. An
   unloaded entry has a null pointer here.
*/

/* XXX EAM : this file needs work on the error exit conditions and memory leaks, esp under errors */

/* XXX EAM : update is not efficient.  MeasureToFtable should only 
   convert the new rows (Nmeas_disk to Nmeasure). the resulting
   table represents the end rows of the ftable.  we need to define
   the vtable based on the ftable, but with Ny = Nmeasure */  
  


    // * convert to an ftable
    // * optionally write the PHU header/matrix
    // * advance to the start of the output data block:
    // ** Nx * catalog[0].Nmeas_off
    // * write out the ftable data block
    // * if Nmeas_off + Nmeasure >= Nmeas_disk, update padding
    // ** start = Nmeas_off
    // ** Nrows = Nmeasure

