Index: /branches/eam_branches/ipp-20101103/Ohana/src/dvomerge/Makefile
===================================================================
--- /branches/eam_branches/ipp-20101103/Ohana/src/dvomerge/Makefile	(revision 29693)
+++ /branches/eam_branches/ipp-20101103/Ohana/src/dvomerge/Makefile	(revision 29694)
@@ -70,5 +70,16 @@
 $(BIN)/dvosecfilt.$(ARCH) : $(DVOSECFILT)
 
-INSTALL = dvomerge dvoconvert dvosecfilt
+DVOREPAIR = \
+$(SRC)/dvorepair.$(ARCH).o \
+$(SRC)/psps_ids.$(ARCH).o \
+$(SRC)/LoadImages.$(ARCH).o \
+$(SRC)/match_image.$(ARCH).o \
+$(SRC)/ImageOps.$(ARCH).o
+
+$(DVOREPAIR)  : $(INC)/dvomerge.h
+
+$(BIN)/dvorepair.$(ARCH) : $(DVOREPAIR)
+
+INSTALL = dvomerge dvoconvert dvosecfilt dvorepair
 
 # dependancy rules for binary code #########################
Index: /branches/eam_branches/ipp-20101103/Ohana/src/dvomerge/include/dvomerge.h
===================================================================
--- /branches/eam_branches/ipp-20101103/Ohana/src/dvomerge/include/dvomerge.h	(revision 29693)
+++ /branches/eam_branches/ipp-20101103/Ohana/src/dvomerge/include/dvomerge.h	(revision 29694)
@@ -86,2 +86,6 @@
 off_t 	   dvo_map_image_ID       PROTO((IDmapType *IDmap, off_t oldID));
 int   	   dvo_update_image_IDs   PROTO((IDmapType *IDmap, Catalog *catalog));
+
+Image *LoadImages (char *filename, off_t *Nimage);
+Image *MatchImage (Image *image, off_t Nimage, unsigned int time, short int source, unsigned int imageID);
+off_t match_image (Image *image, off_t Nimage, unsigned int T, short int S);
Index: /branches/eam_branches/ipp-20101103/Ohana/src/dvomerge/src/ImageOps.c
===================================================================
--- /branches/eam_branches/ipp-20101103/Ohana/src/dvomerge/src/ImageOps.c	(revision 29694)
+++ /branches/eam_branches/ipp-20101103/Ohana/src/dvomerge/src/ImageOps.c	(revision 29694)
@@ -0,0 +1,22 @@
+# include "dvomerge.h"
+
+Image *MatchImage (Image *image, off_t Nimage, unsigned int time, short int source, unsigned int imageID) { 
+
+  int m = -1;
+
+  if ((imageID != 0) && (imageID < Nimage)) {
+    // imageID is in range for the array of images. If the table is still in order and
+    // no images have been deleted the index of the image we are looking for will be imageID - 1
+    // If this is the case, we have it. Otherwise we'll have to go search for it below
+    int guess = (int) imageID - 1;
+    if (image[guess].imageID == imageID) {
+        m = guess;
+    }
+  } 
+  if (m == -1) {
+    m = match_image (image, Nimage, time, source);
+  }
+  if (m == -1) return (NULL);
+  if (!FindMosaicForImage (image, Nimage, m)) return (NULL);
+  return (&image[m]);
+}
Index: /branches/eam_branches/ipp-20101103/Ohana/src/dvomerge/src/LoadImages.c
===================================================================
--- /branches/eam_branches/ipp-20101103/Ohana/src/dvomerge/src/LoadImages.c	(revision 29694)
+++ /branches/eam_branches/ipp-20101103/Ohana/src/dvomerge/src/LoadImages.c	(revision 29694)
@@ -0,0 +1,90 @@
+# include "dvomerge.h"
+
+int dvoUseImageCache = 1;
+
+static char *lastFilename = NULL;
+static time_t lastModified = 0;
+static Image *imageCache = NULL;
+static off_t cacheNimage = 0;
+
+static time_t getLastModified(char *filename);
+
+Image *LoadImages (char *filename, off_t *Nimage) {
+
+  int status;
+  Image *image;
+  FITS_DB db;
+  
+  if (lastFilename) {
+    if (dvoUseImageCache && !strcmp(lastFilename, filename)) {
+      // Make sure the file hasn't changed since we loaded it
+      if (getLastModified(filename) == lastModified) {
+        *Nimage = cacheNimage;
+        return  imageCache;
+      }
+    }
+    free(lastFilename);
+    lastFilename = NULL;
+    free(imageCache);
+    imageCache = NULL;
+    cacheNimage = 0;
+    lastModified = 0;
+  }
+
+
+  gfits_db_init (&db);
+  db.lockstate = LCK_SOFT;
+  db.timeout   = 120.0;
+
+  if (!gfits_db_lock (&db, filename)) {
+    fprintf (stderr, "error opening image catalog %s (1)\n", filename);
+    return (NULL);
+  }
+
+  if (db.dbstate == LCK_EMPTY) {
+    fprintf (stderr, "note: image catalog is empty\n");
+    ALLOCATE (image, Image, 1);
+    *Nimage = 1;
+    return (image);
+  }
+
+  status = dvo_image_load (&db, TRUE, FALSE);
+  gfits_db_close (&db);
+
+  if (!status) {
+    fprintf (stderr, "problem loading image database table\n");
+    return (NULL);
+  }
+
+  image = gfits_table_get_Image (&db.ftable, Nimage, &db.swapped);
+  if (!image) {
+    fprintf (stderr, "ERROR: failed to read images\n");
+    return (NULL);
+  }
+  if (dvoUseImageCache && image) {
+    cacheNimage = *Nimage;
+    imageCache = image;
+    lastFilename = strdup(filename);
+    lastModified = getLastModified(filename);
+  }
+
+  return (image);
+}
+
+static time_t getLastModified(char *filename) {
+  struct stat statbuf;
+  if (!stat(filename, &statbuf)) {
+    return statbuf.st_mtime;
+  } else {
+    return 0;
+  }
+}
+
+void FreeImages(Image *images) {
+  if (!dvoUseImageCache && (images != NULL)) {
+    free(images);
+  } else {
+    // defer free until next LoadImages with a different or modified Images.dat
+  }
+}
+
Index: /branches/eam_branches/ipp-20101103/Ohana/src/dvomerge/src/dvorepair.c
===================================================================
--- /branches/eam_branches/ipp-20101103/Ohana/src/dvomerge/src/dvorepair.c	(revision 29694)
+++ /branches/eam_branches/ipp-20101103/Ohana/src/dvomerge/src/dvorepair.c	(revision 29694)
@@ -0,0 +1,188 @@
+# include "dvomerge.h"
+
+# define myAbort(MSG) { fprintf (stderr, "%s\n", MSG); abort(); }
+# define myAssert(LOGIC,MSG) { if (!LOGIC) { fprintf (stderr, "%s\n", MSG); abort(); } }
+
+// broken cpt file, valid cpm file: we can recover everything in the cpt file from the cpm file:
+// * load the full cpm file
+// * loop over detections
+// * if ave_ref is new: create a new object
+//   * determine RA & DEC from ext_id
+//   * obj_id, cat_id are defined in detection
+//   * 
+
+int main (int argc, char **argv) {
+
+  off_t Nmeasure, Nimage;
+  int i, Nbytes, NaveMax, Naverage, NAVERAGE, Nave, Nold;
+  int *found;
+
+  Image *image, *thisImage;
+  Average *average;
+  Measure *measure;
+
+  Matrix matrix;
+
+  char *cpmFilename, *cptFilenameSrc, *cptFilenameTgt, *imageFilename;
+
+  Header cptHeaderPHU, cptHeaderTBL;
+  Header cpmHeaderPHU, cpmHeaderTBL;
+  FTable cpmFtable, cptFtable;
+
+  FILE *cptFileSrc = NULL;
+  FILE *cptFileTgt = NULL;
+  FILE *cpmFile = NULL;
+
+  char catformat;
+
+  if (argc != 5) {
+    fprintf (stderr, "USAGE: dvorepair (images) (cpm) (cptInput) (cptOutput)\n");
+    exit (2);
+  }
+
+  imageFilename  = argv[1];
+  cpmFilename    = argv[2];
+  cptFilenameSrc = argv[3];
+  cptFilenameTgt = argv[4];
+
+  cpmFtable.header = &cpmHeaderTBL;
+  cptFtable.header = &cptHeaderTBL;
+
+  // XXX don't bother locking for now: this is totally manual..
+
+  // load the image data
+  if ((image = LoadImages (imageFilename, &Nimage)) == NULL) return (FALSE);
+  BuildChipMatch (image, Nimage);
+
+  // open cpm file
+  cpmFile = fopen(cpmFilename, "r");
+  myAssert(cpmFile, "failed to open cpm file");
+
+  // load the cpm header
+  if (!gfits_fread_header (cpmFile, &cpmHeaderPHU)) {
+    myAbort("failure to cpm header");
+  }
+
+  // move to TBL header
+  Nbytes = cpmHeaderPHU.datasize + gfits_data_size (&cpmHeaderPHU);
+  fseeko (cpmFile, Nbytes, SEEK_SET);
+
+  // read cpm TBL header
+  if (!gfits_fread_header (cpmFile, &cpmHeaderTBL)) { 
+    myAbort("can't read header for cpm table");
+  }
+  // read Measure table data : format is irrelevant here */
+  if (!gfits_fread_ftable_data (cpmFile, &cpmFtable)) { 
+    myAbort("can't read data for cpm table");
+  }
+
+  measure = FtableToMeasure (&cpmFtable, &Nmeasure, &catformat);
+  myAssert(measure, "failed to convert ftable to measure data");
+
+  NaveMax = 0;
+  NAVERAGE = 1000;
+  ALLOCATE (average, Average, NAVERAGE);
+  memset (average, 0, NAVERAGE*sizeof(Average));
+
+  ALLOCATE (found, int, NAVERAGE);
+  memset (found, 0, NAVERAGE*sizeof(int));
+
+  // examine all measurements and new objects as needed
+  for (i = 0; i < Nmeasure; i++) {
+    Nave = measure[i].averef;
+    if (found[Nave]) {
+      average[Nave].Nmeasure ++;
+      myAssert(average[Nave].objID == measure[i].objID, "objIDs do not match!");
+      myAssert(average[Nave].catID == measure[i].catID, "catIDs do not match!");
+      continue;
+    }
+
+    if (Nave >= NAVERAGE) {
+      Nold = NAVERAGE;
+      NAVERAGE = MAX(Nave + 1000, NAVERAGE + 1000);
+      REALLOCATE (average, Average, NAVERAGE);
+      memset (&average[Nold], 0, (NAVERAGE - Nold)*sizeof(Average));
+
+      REALLOCATE (found, int, NAVERAGE);
+      memset (&found[Nold], 0, (NAVERAGE - Nold)*sizeof(int));
+    }
+
+    NaveMax = MAX(Nave, NaveMax);
+
+    found[Nave] = TRUE;
+
+    // we are going to leave most of the elements of average unset: they are the result of 
+    // the relastro analysis for this object and can be recreated with a call to relastro
+
+    // fields we have to set:
+
+    // need to find image so we can use ccd coordinates to determine RA & DEC
+    thisImage = MatchImage (image, Nimage, measure[i].t, measure[i].photcode, measure[i].imageID);
+    XY_to_RD (&average[Nave].R, &average[Nave].D, measure[i].Xccd, measure[i].Yccd, &thisImage[0].coords);
+
+    average[Nave].Nmeasure = 1;
+    average[Nave].Nmissing = 0;
+
+    // assume the resulting table set is unsorted
+    average[Nave].measureOffset = -1;
+    average[Nave].missingOffset = -1;
+    average[Nave].extendOffset = -1;
+
+    average[Nave].objID = measure[i].objID;
+    average[Nave].catID = measure[i].catID;
+    average[Nave].extID = CreatePSPSObjectID(average[Nave].R, average[Nave].D);
+  }
+  Naverage = NaveMax + 1;
+
+  // have we created all objects in the range 0 - Naverage?
+  for (i = 0; i < Naverage; i++) {
+    myAssert(found[i], "failed to find one");
+  }
+
+  // open source cpt file
+  cptFileSrc = fopen(cptFilenameSrc, "r");
+  myAssert(cptFileSrc, "failed to open cpt file");
+
+  // load the cpt header (use for CATID, RA,DEC range, filenames)
+  if (!gfits_fread_header (cptFileSrc, &cptHeaderPHU)) {
+    myAbort("failure to cpt header");
+  }
+
+  // update the output header
+  gfits_modify (&cptHeaderPHU, "NSTARS",     "%d",      1,  Naverage);
+  gfits_modify (&cptHeaderPHU, "NMEAS",      OFF_T_FMT, 1,  Nmeasure);
+  gfits_modify (&cptHeaderPHU, "NMISS",      "%d",      1,  0);
+  gfits_modify_alt (&cptHeaderPHU, "SORTED", "%t",      1,  FALSE);
+
+  /* convert internal to external format */
+  if (!AverageToFtable (&cptFtable, average, Naverage, catformat, NULL)) {
+    myAbort("trouble converting format");
+  }
+
+  // create and write the output file
+  cptFileTgt = fopen(cptFilenameTgt, "w");
+  myAssert(cptFileTgt, "failed to open cpt file");
+    
+  // write PHU header
+  if (!gfits_fwrite_header (cptFileTgt, &cptHeaderPHU)) {
+    myAbort("can't write primary header");
+  }
+
+  // write the PHU matrix; this is probably a NOP, do I have to keep it in?
+  gfits_create_matrix (&cptHeaderPHU, &matrix);
+  if (!gfits_fwrite_matrix  (cptFileTgt, &matrix)) {
+    myAbort("can't write primary matrix");
+  }
+  gfits_free_matrix (&matrix);
+
+  // write the table data
+  if (!gfits_fwrite_ftable_range (cptFileTgt, &cptFtable, 0, Naverage, 0, Naverage)) {
+    myAbort("can't write table data");
+  }
+  
+  fclose(cptFileTgt);
+  fclose(cptFileSrc);
+  fclose(cpmFile);
+
+  exit (0);
+}
Index: /branches/eam_branches/ipp-20101103/Ohana/src/dvomerge/src/match_image.c
===================================================================
--- /branches/eam_branches/ipp-20101103/Ohana/src/dvomerge/src/match_image.c	(revision 29694)
+++ /branches/eam_branches/ipp-20101103/Ohana/src/dvomerge/src/match_image.c	(revision 29694)
@@ -0,0 +1,37 @@
+# include "dvomerge.h"
+
+off_t match_image (Image *image, off_t Nimage, unsigned int T, short int S) {
+
+  off_t N, Nlo, Nhi, N1, N2;
+
+  /* bracket first value of interest */
+  Nlo = 0; Nhi = Nimage;
+  while (Nhi - Nlo > 10) {
+    N = 0.5*(Nlo + Nhi);
+    if (image[N].tzero < T) {
+      Nlo = N;
+    } else {
+      Nhi = N + 1;
+    }
+  }
+  N1 = Nlo;
+
+  /* bracket last value of interest */
+  Nlo = 0; Nhi = Nimage;
+  while (Nhi - Nlo > 10) {
+    N = 0.5*(Nlo + Nhi);
+    if (image[N].tzero > T) {
+      Nhi = N;
+    } else {
+      Nlo = N - 1;
+    }
+  }
+  N2 = Nhi;
+
+  for (N = N1; N < N2; N++) {
+    if ((image[N].tzero == T) && (image[N].photcode == S)) {
+      return (N);
+    }
+  }
+  return (-1);
+}
