# include "photdbc.h"

int copy_images (char *outdir) {

  int status, Nimage;
  char *ImageOut;
  FITS_DB in;
  FITS_DB out;
  Image *image;
  struct stat filestat;
  char *path;

  path = pathname (ImageCat);
  status = stat (path, &filestat);
  if (status == -1) Shutdown ("ERROR: CATDIR %s does not exist, no data in database", path);

  status = dvo_image_lock (&in, ImageCat, 60.0, LCK_SOFT);
  if (!status) {
    fprintf (stderr, "No images in catalog %s\n", ImageCat);
    return (TRUE);
  }
  if (in.dbstate == LCK_EMPTY) {
    fprintf (stderr, "No images in catalog %s\n", ImageCat);
    dvo_image_unlock (&in);
    return (TRUE);
  }

  // load the input image data
  if (!dvo_image_load (&in, VERBOSE, FALSE)) Shutdown ("can't read image catalog %s", in.filename);
  dvo_image_unlock (&in);

  // define output filename (replace CATDIR)
  ImageOut = strsubs (in.filename, CATDIR, outdir);
  if (ImageOut == NULL) Shutdown ("error with input or output catalog name");

  // lock the output catalog
  status = dvo_image_lock (&out, ImageOut, 60.0, LCK_SOFT);
  if (!status) Shutdown ("ERROR: failure to lock image catalog %s", ImageOut);
  if (out.dbstate != LCK_EMPTY) Shutdown ("ERROR: image table exists %s", ImageOut);

  out.mode   = dvo_catalog_catmode (CATMODE);
  out.format = dvo_catalog_catformat (CATFORMAT);
  dvo_image_create (&out, ZERO_POINT);
    
  image = gfits_table_get_Image (&in.ftable, &Nimage, &in.swapped);
  dvo_image_addrows (&out, image, Nimage);

  dvo_image_save (&out, VERBOSE);
  dvo_image_unlock (&out);
  return (TRUE);
}

// globals: ImageCat, VERBOSE, CATMODE, CATFORMAT, ZeroPt
