# include <ohana.h>
# include <loneos.h>

/* the function in this file uses the old definition of Catalog,
   and is deprecated by the new locking scheme */

typedef struct {
  Average *average;
  Measure *measure; 
  Missing *missing; 
  SecFilt *secfilt;
  Header  header;
  int Naverage, Nmeasure, Nmissing, Nsecfilt;
  int *found;
  int *image;
  float *X, *Y;
} Catalog;

save_catalog (char *filename, Catalog *catalog, char VERBOSE) {

  int i, Nitems, nitems, mode;
  FILE *f;

  if (catalog[0].Naverage == 0) {
    if (VERBOSE) fprintf (stderr, "no stars in catalog, skipping\n");
    return (2);
  }

  f = fopen (filename, "w");
  if (f == NULL) {
    fprintf (stderr, "ERROR: can't create new catalog file: %s\n", filename);
    return (0);
  }

  mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
  chmod (filename, mode);
 
  fits_modify (&catalog[0].header, "NSTARS",   "%d", 1, catalog[0].Naverage);
  fits_modify (&catalog[0].header, "NMEAS",    "%d", 1, catalog[0].Nmeasure);
  fits_modify (&catalog[0].header, "NMISS",    "%d", 1, catalog[0].Nmissing);
  fits_modify (&catalog[0].header, "NSECFILT", "%d", 1, catalog[0].Nsecfilt);
  fits_modify (&catalog[0].header, "NEWMEAS",  "%t", 1, TRUE);
  fits_modify (&catalog[0].header, "NEWAVES",  "%t", 1, TRUE);
  fits_modify (&catalog[0].header, "NEWSECF",  "%t", 1, TRUE);

  nitems = Fwrite (catalog[0].header.buffer, 1, catalog[0].header.size, f, "char");
  if (nitems != catalog[0].header.size) {
    fprintf (stderr, "ERROR: failed to write header\n");
    return (0);
  }

  Nitems = catalog[0].Naverage;
  nitems = Fwrite (catalog[0].average, sizeof(Average), Nitems, f, "average");
  if (nitems != Nitems) {
    fprintf (stderr, "ERROR: failed to write catalog file aves %s\n", filename);
    return (0);
  }
  
  Nitems = catalog[0].Nmeasure;
  nitems = Fwrite (catalog[0].measure, sizeof(Measure), Nitems, f, "measure");
  if (nitems != Nitems) {
    fprintf (stderr, "ERROR: failed to write catalog file meas %s\n", filename);
    return (0);
  }

  Nitems = catalog[0].Nmissing;
  nitems = Fwrite (catalog[0].missing, sizeof(Missing), Nitems, f, "missing");
  if (nitems != Nitems) {
    fprintf (stderr, "ERROR: failed to write catalog file miss %s\n", filename);
    return (0);
  }

  Nitems = catalog[0].Naverage * catalog[0].Nsecfilt;
  nitems = Fwrite (catalog[0].secfilt, sizeof(SecFilt), Nitems, f, "secfilt");
  if (nitems != Nitems) {
    fprintf (stderr, "ERROR: failed to write catalog file secondary filters %s\n", filename);
    return (0);
  }

  fclose (f);
  return (1);

}

  /* possible exit status: 
     0 - serious failure
     1 - success
     2 - data non-existent */

