# include "addstar.h"

void wimage (FILE *f, int dbstate, Image *image, int Nstars) {
  
  int Nimages, status, offset;
  Header header;

  /* place file pointer at beginning of file */
  fseek (f, 0, SEEK_SET);

  if (dbstate == LCK_EMPTY) {
    if (VERBOSE) fprintf (stderr, "can't find %s, creating a new one\n", ImageCat);
    if (!fits_read_header (ImageTemplate, &header)) {
      fprintf (stderr, "ERROR: can't find template header %s\n", ImageTemplate);
      exit (1);
    }
    /* assign Zero Point provided by first image in dB */
    fits_modify (&header, "ZERO_PT", "%lf", 1, ZeroPt);
  } else {
    if (!fits_load_header (f, &header)) {
      fprintf (stderr, "ERROR: can't read image header %s\n", ImageCat);
      exit (1);
    }
  }
  
  Nimages = 0;
  fits_scan (&header, "NIMAGES", "%d", 1, &Nimages);
  Nimages ++;
  fits_modify (&header, "NIMAGES", "%d", 1, Nimages);

  /* position to begining of file to write header */
  fseek (f, 0, SEEK_SET);
  status = Fwrite (header.buffer, 1, header.size, f, "char");
  if (status != header.size) {
    fprintf (stderr, "ERROR: failed writing data to image header\n");
    exit (1);
  }

  /* position to end of data array */
  offset = (Nimages - 1)*sizeof(Image) + header.size;
  fseek (f, offset, SEEK_SET);

  status = Fwrite (image, sizeof(Image), 1, f, "image");
  if (status != 1) {
    fprintf (stderr, "ERROR: failed writing data to image catalog\n");
    exit (1);
  }
}

/* the image we add in this routine is always a new image.  
   We only need to do two things:
     1) append the data for the image to the end of the file
     2) update the NIMAGES field in the header (which means, read in header, re-write)
 */
