# include "dvoImageExtract.h"

/* given image, find catalog images which overlap it */
int WriteImages (char *filename, Image *images, off_t Nimages, off_t *matches, off_t Nmatches) {
  
  int i, N;
  int nWRP, newWRP, isWRP;
  FILE *f;

  /* matches here are only based on string comparisons */

  f = fopen (filename, "w");
  if (f == NULL) {
    fprintf (stderr, "failed to open output file %s\n", filename);
    exit (1);
  }

  nWRP = -1;
  isWRP = FALSE;
  for (i = 0; i < Nmatches; i++) {
    if (!strcmp (&images[0].coords.ctype[4], "-WRP")) {
      if (!FindMosaicForImage (images, Nimages, i)) {
	fprintf (stderr, "failed to find matching mosaic\n");
	exit (1);
      }
      if (isWRP) {
	newWRP = GetRegisteredMosaic();
	if (newWRP != nWRP) {
	  fprintf (stderr, "only one mosaic allowed in an output file\n");
	  exit (1);
	}
      } else {
	nWRP = GetRegisteredMosaic();
	isWRP = TRUE;
      }
    }      
  }

  if (isWRP) {
    WriteImageFITS (f, &images[nWRP]);
  } else {
    // write a blank
    if (Nmatches > 1) {
      WriteImageFITS (f, NULL);
    }
  }

  for (i = 0; i < Nmatches; i++) {
    N = matches[i];
    WriteImageFITS (f, &images[N]);
  }  

  fclose (f);
  return TRUE;
}
