# include <dvo.h>

/* this function saves the FITS photcode file into the internal photcode table */
/* locking is used to avoid collisions with programs trying to update the photcodes values */
/* XXX better distinction between NOT FOUND and FAILURE */
int SavePhotcodesFITS (char *filename) {

  PhotCodeData *table = NULL;
  PhotCode *photcode;
  FITS_DB db;

  int i, code, Ncode, Nsec;

  table = GetPhotcodeTable ();
  if (table == NULL) {
    fprintf (stderr, "ERROR: no internal photcode table is defined\n");
    return FALSE;
  }

  /* XXX choose more sensible lock timeouts! */
  db.lockstate = LCK_XCLD;
  db.timeout   = 10.0;
  gfits_db_init (&db);

  /* does this mean the db is empty, non-existent, or has access errors? */
  if (!gfits_db_lock (&db, filename)) {
    fprintf (stderr, "ERROR: failure to lock db, cannot save photcode table to %s\n", filename);
    gfits_db_close (&db);
    return FALSE;
  }

  /* convert FITS format data to internal format (just byteswaps) */
  gfits_db_create (&db);
  gfits_table_set_PhotCode (&db.ftable, table[0].code, table[0].Ncode);
  gfits_db_save (&db);
  gfits_db_close (&db);

  /* gfits_table_set_PhotCode performs the needed byte swap.  swap back */
  gfits_convert_PhotCode (table[0].code, sizeof(PhotCode), table[0].Ncode);
  return TRUE;
}
