# include "dvomerge.h"

// merge db2 into db1
int dvo_image_merge_dbs (IDmapType *IDmap, FITS_DB *out, FITS_DB *in) {

  Image *images;
  off_t Nimages;
  off_t Nout;
  off_t i, IDstart;
  int status;
 
  images = gfits_table_get_Image (&in[0].ftable, &Nimages, &in[0].swapped);
  ALLOCATE (IDmap->old, off_t, Nimages);
  ALLOCATE (IDmap->new, off_t, Nimages);
  IDmap->Nmap = Nimages;

 /* adjust header */
  Nout = 0;
  gfits_scan (&out[0].header, "NIMAGES", "%lld", 1, (long long *) &Nout);
  status = gfits_scan (&out[0].header, "IMAGEID", "%lld", 1, (long long *) &IDstart);
  if (!status) {
    IDstart = 1;
  }

  for (i = 0; i < Nimages; i++) {
    IDmap[0].old[i] = images[i].imageID;
    images[i].imageID = i + IDstart;
    IDmap[0].new[i] = images[i].imageID;
  }

  if (!out[0].swapped) {
    gfits_convert_Image ((Image *) out[0].ftable.buffer, sizeof(Image), Nout);
    out[0].swapped = TRUE;
  }

  Nout += Nimages;
  IDstart += Nimages;
  gfits_modify (&out[0].header, "NIMAGES", "%lld", 1, (long long) Nout);
  gfits_modify (&out[0].header, "IMAGEID", "%lld", 1, (long long) IDstart);

  gfits_add_rows (&out[0].ftable, (char *) images, Nimages, sizeof(Image));
  return TRUE;
}

// optimize with sort and bisection
off_t dvo_map_image_ID (IDmapType *IDmap, off_t oldID) {

  off_t i;

  for (i = 0; i < IDmap->Nmap; i++) {
    if (IDmap->old[i] != oldID) continue;
    return (IDmap->new[i]);
  }
  return 0;
}

int dvo_update_image_IDs (IDmapType *IDmap, Catalog *catalog) {

  off_t i, oldID, newID;

  for (i = 0; i < catalog[0].Nmeasure; i++) {
    oldID = catalog[0].measure[i].imageID;
    if (oldID == 0) continue;

    newID = dvo_map_image_ID (IDmap, oldID);
    if (newID == 0) {
      fprintf (stderr, "cannot find image ID %lld\n", (long long) oldID);
      exit (2);
    }
    catalog[0].measure[i].imageID = newID;
  }
  return TRUE;
}
