# include "addstar.h"

wimage (filename, image, Nstars)
char *filename;
Image image[];
int Nstars;
{
  
  int Nimages, status;
  FILE *f;
  Header header;

  if (!fits_read_header (ImageCat, &header)) {
    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);
      clear_lockfile ();
      exit (0);
    }
    f = fopen (ImageCat, "w");
    if (f == NULL) {
      fprintf (stderr, "ERROR: can't create/open image catalog file: %s\n", ImageCat);
      clear_lockfile ();
      exit (0);
    }
  }
  
  Nimages = 0;
  fits_scan (&header, "NIMAGES", "%d", 1, &Nimages);
  Nimages ++;
  fits_modify (&header, "NIMAGES", "%d", 1, Nimages);

  f = fopen (ImageCat, "r+");
  if (f == NULL) {
    fprintf (stderr, "ERROR: can't create/open image catalog file: %s\n", ImageCat);
    clear_lockfile ();
    exit (0);
  }

  /* 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, "ERRPR: failed writing data to image header\n");
    clear_lockfile ();
    exit (0);
  }

  fseek (f, 0, SEEK_END);
  fprintf (stderr, "Image: %d\n", sizeof(Image));
  status = Fwrite (image, sizeof(Image), 1, f, "image");
  if (status != 1) {
    fprintf (stderr, "ERRPR: failed writing data to image catalog\n");
    clear_lockfile ();
    exit (0);
  }

  fclose (f);
  

}

/* 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)
 */
