Index: trunk/Ohana/src/opihi/cmd.astro/cdensify.c
===================================================================
--- trunk/Ohana/src/opihi/cmd.astro/cdensify.c	(revision 41326)
+++ trunk/Ohana/src/opihi/cmd.astro/cdensify.c	(revision 41340)
@@ -39,11 +39,4 @@
   }
 
-  int binning = 1;
-  if ((N = get_argument (argc, argv, "-binning"))) {
-    remove_argument (N, &argc, argv);
-    binning = atoi(argv[N]);
-    remove_argument (N, &argc, argv);
-  }
-
   int PSFTYPE = IS_DOT;
   if ((N = get_argument (argc, argv, "-psf"))) {
@@ -87,9 +80,6 @@
   Ymax = graphmode.ymax;
   Ymin = graphmode.ymin;
-
-  // (dX, dY) are the pixel scale of the output image (output pixels / input pixels)
-
-  dX = binning * (Xmax - Xmin) / (Xpix - 1);
-  dY = binning * (Ymax - Ymin) / (Ypix - 1);
+  dX = (Xmax - Xmin) / (Xpix - 1);
+  dY = (Ymax - Ymin) / (Ypix - 1);
 
   CHECKVAL(Xmin);
Index: trunk/Ohana/src/opihi/cmd.astro/cdhistogram.c
===================================================================
--- trunk/Ohana/src/opihi/cmd.astro/cdhistogram.c	(revision 41326)
+++ trunk/Ohana/src/opihi/cmd.astro/cdhistogram.c	(revision 41340)
@@ -13,11 +13,4 @@
   int kapa;
   Graphdata graphmode;
-
-  int binning = 1;
-  if ((N = get_argument (argc, argv, "-binning"))) {
-    remove_argument (N, &argc, argv);
-    binning = atoi(argv[N]);
-    remove_argument (N, &argc, argv);
-  }
 
   range = NULL;
@@ -86,9 +79,6 @@
   Ymax = graphmode.ymax;
   Ymin = graphmode.ymin;
-
-  // (dX, dY) are the pixel scale of the output image (output pixels / input pixels)
-
-  dX = binning * (Xmax - Xmin) / (Xpix - 1);
-  dY = binning * (Ymax - Ymin) / (Ypix - 1);
+  dX = (Xmax - Xmin) / (Xpix - 1);
+  dY = (Ymax - Ymin) / (Ypix - 1);
 
   CHECKVAL(Xmin);
@@ -100,6 +90,6 @@
   CHECKVAL(dY);
 
-  int Nx = abs((Xmax - Xmin) / dX) + 1;
-  int Ny = abs((Ymax - Ymin) / dY) + 1;
+  int Nx = (Xmax - Xmin) / dX + 1;
+  int Ny = (Ymax - Ymin) / dY + 1;
   
   Coords newcoords = graphmode.coords;
Index: trunk/Ohana/src/opihi/cmd.astro/cgrid.c
===================================================================
--- trunk/Ohana/src/opihi/cmd.astro/cgrid.c	(revision 41326)
+++ trunk/Ohana/src/opihi/cmd.astro/cgrid.c	(revision 41340)
@@ -83,7 +83,4 @@
   Graphdata graphmode;
 
-  if ((N = get_argument (argc, argv, "-h"))) goto usage;
-  if ((N = get_argument (argc, argv, "--help"))) goto usage;
-
   RAbyHour = FALSE;
   if ((N = get_argument (argc, argv, "-ra-by-hour"))) {
@@ -118,6 +115,6 @@
   }
 
-  int JustifyRA = 8;
-  int JustifyDEC = 2;
+  int JustifyRA = 5;
+  double JustifyDEC = 5;
   if ((N = get_argument (argc, argv, "-justify-ra"))) {
     remove_argument (N, &argc, argv);
@@ -154,5 +151,8 @@
   if (!style_args (&graphmode, &argc, argv, &kapa)) return FALSE;
 
-  if (argc != 1) goto usage;
+  if (argc != 1) {
+    gprint (GP_ERR, "USAGE: cgrid [style] [-ra-by-hour] [-labels]\n");
+    return (FALSE);
+  }
 
   /* are we plotting one of the poles? */
@@ -182,5 +182,4 @@
     }
   }
-
   
   /* set spacings for DEC */
@@ -346,24 +345,3 @@
   return (TRUE);
 
- usage:
-
-  gprint (GP_ERR, "USAGE: cgrid [style] [options]\n");
-  gprint (GP_ERR, "  options:\n");
-  gprint (GP_ERR, "  -h, --help: show this list\n");
-  gprint (GP_ERR, "  -ra-by-hour : RA grid lines will be space on rounded hour lines (default is degrees)\n");
-  gprint (GP_ERR, "  -labels : add RA & dec coordinates\n");
-  gprint (GP_ERR, "  -major-spacing : grid lines drawn at major tickmarks, not minor tickmarks\n");
-  gprint (GP_ERR, "  -ra-spacing : specify size of RA grid steps in degrees (ignores -ra-by-hour)\n");
-  gprint (GP_ERR, "  -dec-spacing : specify size of dec grid steps in degrees\n");
-  gprint (GP_ERR, "  -justify-ra : choose how RA labels are justified (see below)\n");
-  gprint (GP_ERR, "  -justify-dec : choose how dec labels are justified (see below)\n");
-  gprint (GP_ERR, "  -label-ra : RA coordinate of the Dec-line labels\n");
-  gprint (GP_ERR, "  -label-dec : Dec coordinate of the RA-line labels\n");
-  gprint (GP_ERR, "  -label-color : color for the labels (independent of grid lines)\n");
-  gprint (GP_ERR, "  text justification: text is justified horizontally and vertically based on the following numbers:\n");
-  gprint (GP_ERR, "   6 7 8\n");
-  gprint (GP_ERR, "   3 4 5\n");
-  gprint (GP_ERR, "   0 1 2\n");
-  return (FALSE);
 }
-
Index: trunk/Ohana/src/opihi/cmd.astro/csystem.c
===================================================================
--- trunk/Ohana/src/opihi/cmd.astro/csystem.c	(revision 41326)
+++ trunk/Ohana/src/opihi/cmd.astro/csystem.c	(revision 41340)
@@ -12,14 +12,4 @@
   Vector *uxvec = NULL;
   Vector *uyvec = NULL;
-
-  int Quiet = FALSE;
-  if ((N = get_argument (argc, argv, "-q"))) {
-    Quiet = TRUE;
-    remove_argument (N, &argc, argv);
-  }
-  if ((N = get_argument (argc, argv, "-quiet"))) {
-    Quiet = TRUE;
-    remove_argument (N, &argc, argv);
-  }
 
   // transform proper motions at the same time
@@ -94,45 +84,7 @@
 
     if (uXname) {
-      if (!Quiet) {
-	gprint (GP_LOG, "%10.6f %10.6f @ %10.6f %10.6f\n", x, y, ux, uy);
-	switch (output) {
-	  case COORD_CELESTIAL:
-	    set_variable ("uR", ux);
-	    set_variable ("uD", uy);
-	    break;
-	  case COORD_ECLIPTIC:
-	    set_variable ("uL", ux);
-	    set_variable ("uB", uy);
-	    break;
-	  case COORD_GALACTIC:
-	  case COORD_GALACTIC_REID_2004:
-	    set_variable ("uLon", ux);
-	    set_variable ("uLat", uy);
-	    break;
-	  default:
-	    break;
-	}
-      }
+      gprint (GP_LOG, "%10.6f %10.6f @ %10.6f %10.6f\n", x, y, ux, uy);
     } else {
-      if (!Quiet) {
-	gprint (GP_LOG, "%10.6f %10.6f\n", x, y);
-      }
-    }
-    switch (output) {
-      case COORD_CELESTIAL:
-	set_variable ("RA", x);
-	set_variable ("DEC", y);
-	break;
-      case COORD_ECLIPTIC:
-	set_variable ("Lambda", x);
-	set_variable ("Beta", y);
-	break;
-      case COORD_GALACTIC:
-      case COORD_GALACTIC_REID_2004:
-	set_variable ("gLon", x);
-	set_variable ("gLat", y);
-	break;
-      default:
-	break;
+      gprint (GP_LOG, "%10.6f %10.6f\n", x, y);
     }
     free (transform);
@@ -202,9 +154,4 @@
   gprint (GP_ERR, " e.g.   : csystem C G R D -pm uR uD -> R D will contain glon, glat; uR, uD will contain uL, uB\n");
   gprint (GP_ERR, " e.g.   : csystem C G R D -pmback uL uB -> R D will contain glon, glat; uL, uB will contain uR, uD\n");
-  gprint (GP_ERR, "        :  if input values are vectors, their values are replaced with the transformed values\n");
-  gprint (GP_ERR, "        :  if input values are scalars, the transformed coordinates are printed (disable with -q)\n");
-  gprint (GP_ERR, "        :    and the following output variables will be set (names depend on output system)\n");
-  gprint (GP_ERR, "        :  output positions (RA, DEC), (Lambda, Beta), (gLon, gLat)\n");
-  gprint (GP_ERR, "        :  output motions   (uR, uD),  (uL, uB),       (uLon, uLat)\n");
   return FALSE;
 }
Index: trunk/Ohana/src/opihi/cmd.astro/fitplx_irls.c
===================================================================
--- trunk/Ohana/src/opihi/cmd.astro/fitplx_irls.c	(revision 41326)
+++ trunk/Ohana/src/opihi/cmd.astro/fitplx_irls.c	(revision 41340)
@@ -11,17 +11,4 @@
     remove_argument (N, &argc, argv);
     if ((mvec = SelectVector (argv[N], ANYVECTOR, TRUE)) == NULL) return (FALSE);
-    remove_argument (N, &argc, argv);
-  }
-
-  Vector *WxOutV = NULL; // mask vector
-  if ((N = get_argument (argc, argv, "-Wxvec"))) {
-    remove_argument (N, &argc, argv);
-    if ((WxOutV = SelectVector (argv[N], ANYVECTOR, TRUE)) == NULL) return (FALSE);
-    remove_argument (N, &argc, argv);
-  }
-  Vector *WyOutV = NULL; // mask vector
-  if ((N = get_argument (argc, argv, "-Wyvec"))) {
-    remove_argument (N, &argc, argv);
-    if ((WyOutV = SelectVector (argv[N], ANYVECTOR, TRUE)) == NULL) return (FALSE);
     remove_argument (N, &argc, argv);
   }
@@ -114,13 +101,4 @@
       mask = mvec->elements.Int;
     }
-  }
-
-  if (WxOutV) {
-    ResetVector (WxOutV, OPIHI_FLT, Ntotal);
-    for (i = 0; i < Ntotal; i++) { WxOutV->elements.Flt[i] = NAN; }
-  }
-  if (WyOutV) {
-    ResetVector (WyOutV, OPIHI_FLT, Ntotal);
-    for (i = 0; i < Ntotal; i++) { WyOutV->elements.Flt[i] = NAN; }
   }
 
@@ -191,20 +169,4 @@
 	}
       }
-    }
-  }
-  if (WxOutV) {
-    // save the calculated weights
-    for (i = 0; i < fitdata.Npts; i++) {
-      // fitdata only includes the previously unmasked points
-      int n = fitdata.index[i];
-      WxOutV->elements.Flt[n] = fitdata.Wx[i];
-    }
-  }
-  if (WyOutV) {
-    // save the calculated weights
-    for (i = 0; i < fitdata.Npts; i++) {
-      // fitdata only includes the previously unmasked points
-      int n = fitdata.index[i];
-      WyOutV->elements.Flt[n] = fitdata.Wy[i];
     }
   }
Index: trunk/Ohana/src/opihi/cmd.astro/mkgauss.c
===================================================================
--- trunk/Ohana/src/opihi/cmd.astro/mkgauss.c	(revision 41326)
+++ trunk/Ohana/src/opihi/cmd.astro/mkgauss.c	(revision 41340)
@@ -10,10 +10,4 @@
   double x, y, r, f, Xo, Yo;
   Buffer *buf;
-
-  int Normalize = FALSE;
-  if ((N = get_argument (argc, argv, "-norm"))) {
-    Normalize = TRUE;
-    remove_argument (N, &argc, argv);
-  }    
 
   // this should be Nx/2, Ny/2 if not set
@@ -66,6 +60,4 @@
   /* f = exp (-r), r = (x^2 / 2Sx) + (y^2 / 2Sy) + Sxy*x*y */
 
-  double Io = Normalize ? 1.0 / (2.0 * M_PI * Sig_x * Sig_y) : 1.0;
-
   in = (float *) buf[0].matrix.buffer;
   for (j = 0; j < Ny; j++) {
@@ -75,5 +67,5 @@
       y = j - Yo;
       r = 0.5*x*x/Sx + 0.5*y*y/Sy + x*y*Sxy;
-      f = Io * exp (-r);
+      f = exp (-r);
       *in += f;
     }
Index: trunk/Ohana/src/opihi/cmd.astro/region.c
===================================================================
--- trunk/Ohana/src/opihi/cmd.astro/region.c	(revision 41326)
+++ trunk/Ohana/src/opihi/cmd.astro/region.c	(revision 41340)
@@ -3,5 +3,5 @@
 int region (int argc, char **argv) {
   
-  double Ra, Dec;
+  double Ra, Dec, Radius;
   float dx, dy;
   int N, kapa, NoClear, dXpix, dYpix;
@@ -54,26 +54,4 @@
   }
 
-  float XSIZE = NAN;
-  if ((N = get_argument (argc, argv, "-xsize"))) {
-    remove_argument (N, &argc, argv);
-    XSIZE = atof (argv[N]);
-    remove_argument (N, &argc, argv);
-    if (XSIZE <= 0) {
-      gprint (GP_ERR, "ERROR: xsize <= 0\n");
-      return FALSE;
-    }
-  }
-
-  float YSIZE = NAN;
-  if ((N = get_argument (argc, argv, "-ysize"))) {
-    remove_argument (N, &argc, argv);
-    YSIZE = atof (argv[N]);
-    remove_argument (N, &argc, argv);
-    if (YSIZE <= 0) {
-      gprint (GP_ERR, "ERROR: xsize <= 0\n");
-      return FALSE;
-    }
-  }
-
   if ((N = get_argument (argc, argv, "-ew"))) {
     remove_argument (N, &argc, argv);
@@ -103,11 +81,6 @@
   }
 
-  int RadiusArg, CtypeArg;
-  if (!isnan(XSIZE) || !isnan(YSIZE)) {
-    RadiusArg = -1;
-    CtypeArg = 3;
-    if ((argc != 3) && (argc != 4)) {
-    gprint (GP_ERR, "USAGE: region Ra Dec [projection] [-xsize deg] [-ysize deg]\n");
-    gprint (GP_ERR, "   OR: region Ra Dec Radius [projection]\n");
+  if ((argc != 4) && (argc != 5)) {
+    gprint (GP_ERR, "USAGE: region Ra Dec Radius [projection] [orientation]\n");
     gprint (GP_ERR, "  [-image] [-ew] [+ew] [-ns] [+ns] [-no-clear] [-angle theta]\n");
     gprint (GP_ERR, " current: %f %f (%f x %f) (%s)\n", 
@@ -117,51 +90,28 @@
 	     &graphmode.coords.ctype[5]);
     return (FALSE);
-    }
-  } else {
-    RadiusArg = 3;
-    CtypeArg = 4;
-    if ((argc != 4) && (argc != 5)) {
-      gprint (GP_ERR, "USAGE: region Ra Dec Radius [projection]\n");
-      gprint (GP_ERR, "   OR: region Ra Dec [projection] [-xsize deg] [-ysize deg]\n");
-      gprint (GP_ERR, "  [-image] [-ew] [+ew] [-ns] [+ns] [-no-clear] [-angle theta]\n");
-      gprint (GP_ERR, " current: %f %f (%f x %f) (%s)\n", 
-	      graphmode.coords.crval1, graphmode.coords.crval2, 
-	      fabs(graphmode.xmax - graphmode.xmin), 
-	      fabs(graphmode.ymax - graphmode.ymin), 
-	      &graphmode.coords.ctype[5]);
-      return (FALSE);
-    }
-  }  
+  }
+  
   if (!ohana_str_to_radec (&Ra, &Dec, argv[1], argv[2])) return (FALSE);
+  Radius = atof (argv[3]);
+  InitCoords (&graphmode.coords, "DEC--TAN");
 
-  // region 0 0 sin -- should raise an error (radius = 0 or non-numeric)
-
-  // I want to be able to support the old style call in which both of these were valid:
-  // region 0 0 90 ait
-  // region 0 0 90      <- uses existing, sticky projection type
-  // but I also want to be able to use
-  // region 0 0 ait -xsize 5
-  // region 0 0 ait -ysize 5
-
-  double Radius = NAN;
-  if (RadiusArg >= 0) {
-    Radius = atof (argv[RadiusArg]);
+  if (argc == 5) {
+    if (!strcasecmp (argv[4], "TAN")) 
+      strcpy (graphmode.coords.ctype, "DEC--TAN");
+    if (!strcasecmp (argv[4], "SIN")) 
+      strcpy (graphmode.coords.ctype, "DEC--SIN");
+    if (!strcasecmp (argv[4], "ARC")) 
+      strcpy (graphmode.coords.ctype, "DEC--ARC");
+    if (!strcasecmp (argv[4], "STG")) 
+      strcpy (graphmode.coords.ctype, "DEC--STG");
+    if (!strcasecmp (argv[4], "ZEA"))
+      strcpy (graphmode.coords.ctype, "DEC--ZEA");
+    if (!strcasecmp (argv[4], "AIT")) 
+      strcpy (graphmode.coords.ctype, "DEC--AIT");
+    if (!strcasecmp (argv[4], "GLS")) 
+      strcpy (graphmode.coords.ctype, "DEC--GLS");
+    if (!strcasecmp (argv[4], "PAR")) 
+      strcpy (graphmode.coords.ctype, "DEC--PAR");
   }
-
-  InitCoords (&graphmode.coords, "DEC--TAN");
-  if (argc == CtypeArg + 1) {
-    if (!strcasecmp (argv[CtypeArg], "TAN")) { strcpy (graphmode.coords.ctype, "DEC--TAN"); goto got_ctype; }
-    if (!strcasecmp (argv[CtypeArg], "SIN")) { strcpy (graphmode.coords.ctype, "DEC--SIN"); goto got_ctype; }
-    if (!strcasecmp (argv[CtypeArg], "ARC")) { strcpy (graphmode.coords.ctype, "DEC--ARC"); goto got_ctype; }
-    if (!strcasecmp (argv[CtypeArg], "STG")) { strcpy (graphmode.coords.ctype, "DEC--STG"); goto got_ctype; }
-    if (!strcasecmp (argv[CtypeArg], "ZEA")) { strcpy (graphmode.coords.ctype, "DEC--ZEA"); goto got_ctype; }
-    if (!strcasecmp (argv[CtypeArg], "AIT")) { strcpy (graphmode.coords.ctype, "DEC--AIT"); goto got_ctype; }
-    if (!strcasecmp (argv[CtypeArg], "GLS")) { strcpy (graphmode.coords.ctype, "DEC--GLS"); goto got_ctype; }
-    if (!strcasecmp (argv[CtypeArg], "PAR")) { strcpy (graphmode.coords.ctype, "DEC--PAR"); goto got_ctype; }
-    gprint (GP_ERR, "ERROR: invalid projection type %s\n", argv[CtypeArg]);
-    gprint (GP_ERR, "allowed values: TAN, SIN, ARC, STG, ZEA, AIT, GLS, PAR\n");
-    return FALSE;
-  }
-got_ctype:
   
   graphmode.coords.crval1 = Ra;
@@ -176,6 +126,5 @@
   graphmode.coords.pc2_2 =  cos(Angle*RAD_DEG)*pc2_2;
 
-  // ask kapa for coordinate limits, to get the right aspect ratio 
-  // dx, dy are the size of the graph region in pixels
+  /* ask kapa for coordinate limits, to get the right aspect ratio */
   KapaGetLimits (kapa, &dx, &dy);
   dx = fabs (dx);
@@ -183,38 +132,15 @@
 
   /* define limits for Ra, Dec at center, grid in degrees */
-  if (RadiusArg >= 0) {
-    // force non-anamorphic projection with Radius set to smaller axis
-    if (dy < dx) {
-      graphmode.xmin = -(dx/dy)*Radius;
-      graphmode.ymin = -Radius;
-      graphmode.xmax = (dx/dy)*Radius;
-      graphmode.ymax = Radius;
-    } else {
-      graphmode.xmin = -Radius;
-      graphmode.ymin = -(dy/dx)*Radius;
-      graphmode.xmax = Radius;
-      graphmode.ymax = (dy/dx)*Radius;
-    } 
+  if (dy < dx) {
+    graphmode.xmin = -(dx/dy)*Radius;
+    graphmode.ymin = -Radius;
+    graphmode.xmax = (dx/dy)*Radius;
+    graphmode.ymax = Radius;
   } else {
-    if (isnan(XSIZE)) {
-      graphmode.xmin = -(dx/dy)*YSIZE/2.0;
-      graphmode.ymin = -YSIZE/2.0;
-      graphmode.xmax = (dx/dy)*YSIZE/2.0;
-      graphmode.ymax = YSIZE/2.0;
-    }
-    if (isnan(YSIZE)) {
-      graphmode.xmin = -XSIZE/2.0;
-      graphmode.ymin = -(dy/dx)*XSIZE/2.0;
-      graphmode.xmax = XSIZE/2.0;
-      graphmode.ymax = (dy/dx)*XSIZE/2.0;
-    }
-    // anamorphic projection:
-    if (!isnan(XSIZE) && !isnan(YSIZE)) {
-      graphmode.xmin = -XSIZE/2.0;
-      graphmode.ymin = -YSIZE/2.0;
-      graphmode.xmax =  XSIZE/2.0;
-      graphmode.ymax =  YSIZE/2.0;
-    }
-  }
+    graphmode.xmin = -Radius;
+    graphmode.ymin = -(dy/dx)*Radius;
+    graphmode.xmax = Radius;
+    graphmode.ymax = (dy/dx)*Radius;
+  } 
 
   set_variable ("XMIN", graphmode.xmin);
Index: trunk/Ohana/src/opihi/cmd.basic/init.c
===================================================================
--- trunk/Ohana/src/opihi/cmd.basic/init.c	(revision 41326)
+++ trunk/Ohana/src/opihi/cmd.basic/init.c	(revision 41340)
@@ -73,6 +73,4 @@
   {1, "??",            list_vars,          "list variables *"},
   {1, "#",             nop,                "a NOP function"},
-  {1, "##",            nop,                "a NOP function"},
-  {1, "###",           nop,                "a NOP function"},
   {1, "local",         local,              "define local variables"},
   {1, "macro",         macro,              "deal with the macros *"}, 
Index: trunk/Ohana/src/opihi/cmd.basic/list.c
===================================================================
--- trunk/Ohana/src/opihi/cmd.basic/list.c	(revision 41326)
+++ trunk/Ohana/src/opihi/cmd.basic/list.c	(revision 41340)
@@ -263,13 +263,7 @@
     gprint (GP_ERR, "USAGE: list (root) -split (words) 			       : create list from words\n");
     gprint (GP_ERR, "USAGE: list (root) -splitbychar (char) (word) [(words)..] : create list from words\n");
-    gprint (GP_ERR, "USAGE: list (root) -join (varname) 		       : convert a list to a single variable (space separated)\n");
     gprint (GP_ERR, "USAGE: list (root) -add (words)   			       : extend a list\n");    
     gprint (GP_ERR, "USAGE: list (root) -copy (list)   			       : copy a list to a new name\n");
     gprint (GP_ERR, "USAGE: list (root) -del (word)   			       : delete the entry by value\n");
-    gprint (GP_ERR, "USAGE: list (root) -glob (word)   			       : create a list from a file glob\n");
-    gprint (GP_ERR, "USAGE: list (root) -file (word)   			       : create a list from lines in a file\n");
-
-    gprint (GP_ERR, "OPTIONS: -excel   			                       : generate names of the for foo:A\n");
-    gprint (GP_ERR, "OPTIONS: -excel-style  	                               : generate names of the for foo:A\n");
     return (FALSE);
   }
Index: trunk/Ohana/src/opihi/cmd.basic/memory.c
===================================================================
--- trunk/Ohana/src/opihi/cmd.basic/memory.c	(revision 41326)
+++ trunk/Ohana/src/opihi/cmd.basic/memory.c	(revision 41340)
@@ -5,11 +5,4 @@
   
   if (argc < 2) goto usage;
-
-  if (!strcasecmp (argv[1], "max-lines")) {
-    if (argc != 3) goto usage;
-    int MaxLines = atoi(argv[2]);
-    ohana_memdump_set_maxlines (MaxLines);
-    return TRUE;
-  }
 
   if (!strcasecmp (argv[1], "all")) {
@@ -50,13 +43,6 @@
   }
 
-  if (!strncasecmp ("strings", argv[1], strlen(argv[1]))) {
-    ohana_memdump_strings_file (stderr, FALSE);
-    return (TRUE);
-  }
-
 usage:
-  gprint (GP_ERR, "USAGE: memory (mode) [-max-lines]\n");
-  gprint (GP_ERR, "USAGE: memory (max-lines) (N)\n");
-  gprint (GP_ERR, " mode options: all, leaks, check, checkfree, variables, vectors, buffers, macros, commands, strings\n");
+  gprint (GP_ERR, "USAGE: memory (all/leaks)\n");
   return (FALSE);
 }
Index: trunk/Ohana/src/opihi/cmd.basic/test/if.sh
===================================================================
--- trunk/Ohana/src/opihi/cmd.basic/test/if.sh	(revision 41326)
+++ trunk/Ohana/src/opihi/cmd.basic/test/if.sh	(revision 41340)
@@ -320,82 +320,2 @@
  end
 end
-
-# check memleaks
-macro memtest1
-
- local a b i N
-
- $i = 0
- $a = 1
-
- memory check
- output /dev/null 
- for i 0 1000
-   if ($a == 1)
-    echo "run"    
-   end
- end    
- output stdout
- memory check
-end
-
-# check memleaks
-macro memtest2
-
- local a b i N
-
- $i = 0
- $a = 1
- $b = 2
-
- memory check
- output /dev/null
- for i 0 1000
-   if (($a == 1) && ($b == 2))
-    echo "run"    
-   end
- end    
- output stdout
- memory check
-end
-
-# memory test using continue
-macro memtest3
-
- local a b i N
-
- $i = 0
- $a = 1
- $b = 2
-
- memory check
- output /dev/null
- for i 0 1000
-   if (($a == 1) && ($b == 2))
-    continue
-    echo "run"    
-   end
- end    
- output stdout
- memory check
-end
-
-# memory test using continue
-macro memtest4
-
- local a b i N bool
-
-
- $i = 0
- $a = 1
- $b = 2
- $bool = 0
-
- memory check
- output /dev/null
- for i 0 1000
-   $bool = (($a == 1) && ($b == 2))
- end    
- output stdout
- memory check
-end
Index: trunk/Ohana/src/opihi/cmd.basic/test/macro.sh
===================================================================
--- trunk/Ohana/src/opihi/cmd.basic/test/macro.sh	(revision 41326)
+++ trunk/Ohana/src/opihi/cmd.basic/test/macro.sh	(revision 41340)
@@ -7,13 +7,4 @@
 # Is the macro working?
 macro test_prep
- $test_var1 = check1
- $test_var2 = check2
- $var_count = $0
-end
-
-# Is the macro working?
-macro test_local
- local test_var test_var2 var_count
-
  $test_var1 = check1
  $test_var2 = check2
@@ -56,30 +47,2 @@
  end
 end
-
-# Memory Test for macro
-macro memtest2
-
- $i = 0
- test_prep
-
- memory check
- for i 0 10000
-  test_prep
- end    
- memory check
-  
-end
-
-# Memory Test for macro
-macro memtest3
-
- $i = 0
- test_local
-
- memory check
- for i 0 10000
-  test_local
- end    
- memory check
-  
-end
Index: trunk/Ohana/src/opihi/cmd.basic/test/stackmath.sh
===================================================================
--- trunk/Ohana/src/opihi/cmd.basic/test/stackmath.sh	(revision 41326)
+++ 	(revision )
@@ -1,128 +1,0 @@
-
-input tap.sh
-
-macro go
- plan {14 + 14}
- test1
- test2
- done
-end
-
-# test unary scalar ops
-macro test1
- $x = 5;                 ok ($x == 5) "scalar equality"
- $x = abs(-3);           ok ($x == 3) "scalar abs"
- $x = int(5.23);         ok ($x == 5) "scalar int"
- $x = floor(7.1234);     ok ($x == 7) "scalar floor"
- $x = floor(7.9876);     ok ($x == 7) "scalar floor"
- $x = ceil(7.1234);      ok ($x == 8) "scalar ceil"
- $x = ceil(7.9876);      ok ($x == 8) "scalar ceil"
-		         
- $x = exp(1.0);          ok ($x == 2.71828182846) "scalar exp"
- $x = ten(3.0);          ok ($x == 1000) "scalar ten"
- $x = log(10000);        ok ($x == 4) "scalar log"
- $x = ln(2.71828182846); ok ($x == 1) "scalar ln"
- $x = sqrt(9);           ok ($x == 3) "scalar sqrt"
- $x = dsin(30);          ok ($x == 0.5) "scalar dsin"
- $x = sin($M_PI/6);      ok ($x == 0.5) "scalar sin"
-end
-
-# test unary vector ops
-macro test2
- create x -3 3
-
- set y = x;                 ok (y[1] == -2) "vector equality"
- set y = abs(x);            ok (y[1] ==  2) "vector abs"
- 
- set y = ten(x);            ok (y[1] == 0.01) "vector ten"
-       	 		    ok (y[5] == 100) "vector ten"
- set z = log(y);            ok (z[5] == 2) "vector log"
-       	 		    ok (z[1] == -2) "vector ten"
-
- set y = exp(x);            ok (y[4] == 2.71828182846) "vector exp"
-       	 		    ok (y[2] == 0.367879441171) "vector exp"
- set z = ln(y);             ok (z[2] == -1) "vector ln"
-                            ok (z[4] == 1) "vector ln"
- create x 0 26
- set y = sqrt(x);           ok (y[4] == 2) "vector sqrt"
-       	 		    ok (y[9] == 3) "vector sqrt"
-
- create x 0 360 30
- set y = dsin(x);           ok (y[1] == 0.5) "vector dsin"
-                            ok (y[3] == 1.0) "vector dsin"
-end
-
-# here are all defined unary functions
-# SVM =
-# SVM abs    
-# SVM int    
-# SVM floor  
-#     round  
-# SVM ceil   
-#     rint   
-# SVM exp    
-# SVM ten    
-# SVM log    
-# SVM ln     
-# SVM sqrt   
-# SVM erf    
-# SVM sinh   
-# SVM cosh   
-# SVM asinh  
-# SVM acosh  
-# SVM sin    
-# SVM cos    
-# SVM tan    
-# SVM dsin   
-# SVM dcos   
-# SVM dtan   
-# SVM asin   
-# SVM acos   
-# SVM atan   
-# SVM dasin  
-# SVM dacos  
-# SVM datan  
-# SVM lgamma 
-# SVM rnd    
-# SVM drnd   
-# SVM lrnd   
-# SVM mrnd   
-# SVM not    
-# SVM negate
-# SVM isinf  
-# SVM isnan  
-#  VM ramp   
-#  VM xramp  
-#  VM yramp  
-#  VM zramp  
-#  VM zero   
-
-## tests are not reporting an error when using one of the unimplemented functions
-
-# here are all defined binary functions
-
-# V "^"
-# V max     "U"
-# V min     "D"
-# V atan2   "a"
-# V datan2  "d"
-# * <-      "l"
-# * ->      "r"
-# V @       
-# V /       
-# V *       
-# V %       
-# V +       
-# V -       
-# V &       
-# V |       
-# V <       
-# V >       
-# V ==      "E"
-# V !=      "N"
-# V <=      "L"
-# V >=      "G"
-# V >>      "U"
-# V <<      "D"
-# V &&      "A"
-# V ||      "O"
Index: trunk/Ohana/src/opihi/cmd.basic/test/tap.sh
===================================================================
--- trunk/Ohana/src/opihi/cmd.basic/test/tap.sh	(revision 41326)
+++ 	(revision )
@@ -1,61 +1,0 @@
-
-macro plan
- if ($0 != 2)
-  echo "USAGE: plan (Ntest)"
-  break
- end
-
- $tap_Nplan = $1
- $tap_Npass = 0
- $tap_Nfail = 0
- $tap_Ntest = 0
-end
-
-macro done
- if (not($?tap_Nplan))
-  echo "ERROR: tap tests not planned"
-  break
- end
-
- echo "planned $tap_Nplan tests, ran $tap_Ntest"
- echo "passed $tap_Npass tests, failed $tap_Nfail tests"
-
- if (($tap_Nfail == 0) && ($tap_Ntest == $tap_Nplan) && ($tap_Npass == $tap_Ntest))
-   echo "PASS: all tests run and passed"
-   return 1
- end
-
- if ($tap_Nfail > 0)
-   echo "FAIL: $tap_Nfail tests failed"
- end
-
- if ($tap_Ntest != $tap_Nplan)
-   echo "FAIL: not all tests run"
- end
-
- if ($tap_Ntest != $tap_Npass + $tap_Nfail)
-   echo "FAIL: inconsistent count: $tap_Ntest tests != $tap_Npass pass + $tap_Nfail fail"
- end
-end
-
-macro ok
- if ($0 != 3)
-  echo "USAGE (condition) (label)"
-  break
- end
- 
- if (not($?tap_Nplan))
-  echo "ERROR: tap tests not planned"
-  break
- end
- 
- if ($1)
-  echo "OK: $2"
-  $tap_Npass ++
- else     
-  echo "not OK: $2"
-  $tap_Nfail ++
- end
- $tap_Ntest ++
-end
-
Index: trunk/Ohana/src/opihi/cmd.data/Makefile
===================================================================
--- trunk/Ohana/src/opihi/cmd.data/Makefile	(revision 41326)
+++ trunk/Ohana/src/opihi/cmd.data/Makefile	(revision 41340)
@@ -19,5 +19,4 @@
 $(SRC)/init.$(ARCH).o          \
 $(SRC)/accum.$(ARCH).o		\
-$(SRC)/antialias.$(ARCH).o		\
 $(SRC)/applyfit1d.$(ARCH).o	\
 $(SRC)/applyfit2d.$(ARCH).o	\
@@ -79,5 +78,4 @@
 $(SRC)/join.$(ARCH).o		\
 $(SRC)/jpeg.$(ARCH).o		\
-$(SRC)/kapamemory.$(ARCH).o		\
 $(SRC)/kern.$(ARCH).o		\
 $(SRC)/keyword.$(ARCH).o	\
@@ -91,10 +89,8 @@
 $(SRC)/lookup.$(ARCH).o	\
 $(SRC)/matrix.$(ARCH).o	\
-$(SRC)/match1d.$(ARCH).o	\
 $(SRC)/match2d.$(ARCH).o	\
 $(SRC)/mkrgb.$(ARCH).o	\
 $(SRC)/mcreate.$(ARCH).o	\
 $(SRC)/medacc.$(ARCH).o	\
-$(SRC)/mgaussdev.$(ARCH).o	\
 $(SRC)/mget.$(ARCH).o		\
 $(SRC)/mget3d.$(ARCH).o		\
@@ -103,5 +99,4 @@
 $(SRC)/medimage.$(ARCH).o	\
 $(SRC)/medimage_commands.$(ARCH).o \
-$(SRC)/medimage_calc.$(ARCH).o \
 $(SRC)/mset.$(ARCH).o		\
 $(SRC)/needles.$(ARCH).o	\
@@ -117,5 +112,4 @@
 $(SRC)/point.$(ARCH).o		\
 $(SRC)/ps.$(ARCH).o		\
-$(SRC)/pdf.$(ARCH).o		\
 $(SRC)/print_vectors.$(ARCH).o 	\
 $(SRC)/mprint.$(ARCH).o 	\
@@ -130,5 +124,4 @@
 $(SRC)/queuesubstr.$(ARCH).o	\
 $(SRC)/queueinit.$(ARCH).o	\
-$(SRC)/queue2book.$(ARCH).o	\
 $(SRC)/radial.$(ARCH).o	\
 $(SRC)/rd.$(ARCH).o		\
@@ -176,5 +169,4 @@
 $(SRC)/vgauss.$(ARCH).o            \
 $(SRC)/vlorentz.$(ARCH).o          \
-$(SRC)/vsigmoid.$(ARCH).o          \
 $(SRC)/vellipse.$(ARCH).o          \
 $(SRC)/vmaxwell.$(ARCH).o          \
@@ -184,5 +176,4 @@
 $(SRC)/vzload.$(ARCH).o		   \
 $(SRC)/vpeaks.$(ARCH).o		   \
-$(SRC)/vtransitions.$(ARCH).o     \
 $(SRC)/vpop.$(ARCH).o		   \
 $(SRC)/vroll.$(ARCH).o		   \
@@ -191,6 +182,4 @@
 $(SRC)/vsmooth.$(ARCH).o	   \
 $(SRC)/vstats.$(ARCH).o		   \
-$(SRC)/virls.$(ARCH).o		   \
-$(SRC)/vwtmean.$(ARCH).o \
 $(SRC)/xsection.$(ARCH).o          \
 $(SRC)/vsh.$(ARCH).o	           \
Index: trunk/Ohana/src/opihi/cmd.data/antialias.c
===================================================================
--- trunk/Ohana/src/opihi/cmd.data/antialias.c	(revision 41326)
+++ 	(revision )
@@ -1,26 +1,0 @@
-# include "data.h"
-
-int antialias (int argc, char **argv) {
-
-  int N, kapa;
-  Graphdata graphmode;
-
-  char *name = NULL;
-  if ((N = get_argument (argc, argv, "-n"))) {
-    remove_argument (N, &argc, argv);
-    name = strcreate (argv[N]);
-    remove_argument (N, &argc, argv);
-  }
-  if (!GetGraph (&graphmode, &kapa, name)) return (FALSE);
-  FREE (name);
-
-  if (argc != 2) {
-    gprint (GP_ERR, "USAGE: antialias (sigma)\n");
-    return (FALSE);
-  }
-
-  float sigma = atof (argv[1]);
-
-  KapaSetSmoothSigma (kapa, sigma);
-  return (TRUE);
-}
Index: trunk/Ohana/src/opihi/cmd.data/create.c
===================================================================
--- trunk/Ohana/src/opihi/cmd.data/create.c	(revision 41326)
+++ trunk/Ohana/src/opihi/cmd.data/create.c	(revision 41340)
@@ -7,31 +7,4 @@
   Vector *vec;
   
-  // create a vector of empty strings
-  if ((N = get_argument (argc, argv, "-str"))) {
-    remove_argument (N, &argc, argv);
-
-    char *stringValue = NULL;
-    if ((N = get_argument (argc, argv, "-value"))) {
-      remove_argument (N, &argc, argv);
-      stringValue = strcreate (argv[N]);
-      remove_argument (N, &argc, argv);
-    }
-
-    if (argc != 3) {
-      gprint (GP_ERR, "USAGE: create vector Nelements -value word\n");
-      return (FALSE);
-    }
-
-    if ((vec = SelectVector (argv[1], ANYVECTOR, TRUE)) == NULL) return (FALSE);
-    int Nelements = atoi (argv[2]);
-
-    // a newly reset vector has NULL-valued pointers
-    ResetVector (vec, OPIHI_STR, Nelements);
-    for (int i = 0; i < Nelements; i++) {
-      vec[0].elements.Str[i] = stringValue ? strcreate (stringValue) : strcreate ("");
-    }
-    return TRUE;
-  }
-
   INT = FALSE;
   if ((N = get_argument (argc, argv, "-int"))) {
@@ -43,5 +16,4 @@
     gprint (GP_ERR, "USAGE: create vector start end [delta] [-int]\n");
     gprint (GP_ERR, " -int : resulting vector is integer type (delta must be integer)\n");
-    gprint (GP_ERR, " -str : resulting vector is string type (only give number of elements)\n");
     return (FALSE);
   }
Index: trunk/Ohana/src/opihi/cmd.data/cut.c
===================================================================
--- trunk/Ohana/src/opihi/cmd.data/cut.c	(revision 41326)
+++ trunk/Ohana/src/opihi/cmd.data/cut.c	(revision 41340)
@@ -1,71 +1,10 @@
 # include "data.h"
 
-enum {SUM, MEAN, MEDIAN, INNER, NGOOD};
-
-double cutstat (float *value, int Nvalue, int mode) {
-
-  double output = 0.0;
-
-  if (Nvalue == 0) return NAN;
-
-  if (mode == MEDIAN) {
-    fsort (value, Nvalue);
-    if (Nvalue % 2) {
-      int Ncenter = Nvalue / 2;
-      myAssert ((Ncenter >= 0) && (Ncenter < Nvalue), "cutstat");
-      output = value[Ncenter];
-    } else {
-      int Ncenter = Nvalue / 2 - 1;
-      myAssert ((Ncenter >= 0) && (Ncenter < Nvalue - 1), "cutstat");
-      output = 0.5*(value[Ncenter] + value[Ncenter + 1]);
-    }
-    return output;
-  } 
-  if (mode == INNER) {
-    fsort (value, Nvalue);
-
-    int Ns = 0, Ne = 0;
-    if (Nvalue % 2) {
-      // for an odd number of points take the same number below
-      // and above the center value
-      int Ncenter = Nvalue / 2;
-      int Nquarter = 0.25*Nvalue;
-      Ns = Ncenter - Nquarter;
-      Ne = Ncenter + Nquarter;
-    } else {
-      // for an even number, the middle lies between two points
-      // take the same number below as above
-      int Ncenter = (int)(Nvalue / 2) - 1;
-      int Nquarter = 0.25*Nvalue;
-      Ns = Ncenter     - Nquarter;
-      Ne = Ncenter + 1 + Nquarter;
-    }
-    int Nv = 0;
-    for (int i = Ns; i <= Ne; i++) {
-      myAssert ((i >= 0) && (i < Nvalue), "cutstat");
-      output += value[i];
-      Nv ++;
-    }
-    output /= Nv;
-    return output;
-  }
-  if (mode == NGOOD) {
-    return Nvalue;
-  }
-  if ((mode == MEAN) || (mode == SUM)) {
-    for (int i = 0; i < Nvalue; i++) {
-      myAssert ((i >= 0) && (i < Nvalue), "cutstat");
-      output += value[i];
-    }
-    if (mode == MEAN) { output /= Nvalue; }
-    return output;
-  }
-  return NAN;
-}
+enum {SUM, MEAN, MEDIAN};
 
 int cut (int argc, char **argv) {
   
   int i, j, N, Nx, Ny, Mode;
-  float *Vin, *Vbuf;
+  float *Vin, *Vbuf, value;
   int sx, sy, nx, ny;
   Vector *xvec, *yvec;
@@ -73,8 +12,4 @@
 
   Mode = SUM;
-  if ((N = get_argument (argc, argv, "-sum"))) {
-    remove_argument (N, &argc, argv);
-    Mode = SUM;
-  }
   if ((N = get_argument (argc, argv, "-median"))) {
     remove_argument (N, &argc, argv);
@@ -84,12 +19,4 @@
     remove_argument (N, &argc, argv);
     Mode = MEAN;
-  }
-  if ((N = get_argument (argc, argv, "-inner"))) {
-    remove_argument (N, &argc, argv);
-    Mode = INNER;
-  }
-  if ((N = get_argument (argc, argv, "-ngood"))) {
-    remove_argument (N, &argc, argv);
-    Mode = NGOOD;
   }
 
@@ -109,7 +36,6 @@
   Ny = buf[0].matrix.Naxis[1];
 
-  // ny & nx do not need to be constrained by the buffer, but they do need to be sensible
-  if ((nx < 0) || (ny < 0) || (nx > 1e8) || (ny > 1e8)) {
-    gprint (GP_ERR, "warning : extraction size is crazy: %d,%d\n", nx, ny);
+  if ((sx < 0) || (sy < 0) || (sx+nx > Nx) || (sy+ny > Ny)) {
+    gprint (GP_ERR, "region out of range\n");
     return (FALSE);
   }
@@ -131,31 +57,21 @@
 
     for (i = 0; i < nx; i++) {
-      // for out-of-range areas, set the output pixels to NAN
-      if (i + sx < 0) {
-	yvec[0].elements.Flt[i] = NAN;
-	continue;
+      /* accumulate values */
+      Vin = (float *)(buf[0].matrix.buffer) + sy*Nx + sx + i; 
+      for (j = 0; j < ny; j++, Vin += Nx) {
+	Vbuf[j] = *Vin;
       }
-      if (i + sx >= Nx) {
-	yvec[0].elements.Flt[i] = NAN;
-	continue;
+      /* apply stat of choice */
+      if (Mode == MEDIAN) {
+	fsort (Vbuf, ny);
+	value = Vbuf[(int)(0.5*ny)];
+      } else {
+	value = 0;
+	for (j = 0; j < ny; j++) {
+	  value += Vbuf[j];
+	}
+	if (Mode == MEAN) { value /= ny; }
       }
-
-      /* accumulate values */
-      // skip out-of-range areas in y
-      if (sy < 0) {
-	ny += sy;
-	sy = 0;
-      }
-      if (sy > Ny) sy = Ny;
-      if (sy + ny >= Ny) ny = Ny - sy;
-
-      Vin = (float *)(buf[0].matrix.buffer) + sy*Nx + sx + i; 
-      int Npix = 0;
-      for (j = 0; j < ny; j++, Vin += Nx) {
-	if (!isfinite(*Vin)) continue;
-	Vbuf[Npix] = *Vin;
-	Npix ++;
-      }
-      yvec[0].elements.Flt[i] = cutstat (Vbuf, Npix, Mode);
+      yvec[0].elements.Flt[i] = value;
     }
     free (Vbuf);
@@ -173,31 +89,21 @@
 
     for (i = 0; i < ny; i++) {
-      // for out-of-range areas, set the output pixels to NAN
-      if (i + sy < 0) {
-	yvec[0].elements.Flt[i] = NAN;
-	continue;
+      /* accumulate values */
+      Vin = (float *)(buf[0].matrix.buffer) + (sy + i)*Nx + sx; 
+      for (j = 0; j < nx; j++, Vin ++) {
+	Vbuf[j] = *Vin;
       }
-      if (i + sy >= Ny) {
-	yvec[0].elements.Flt[i] = NAN;
-	continue;
+      /* apply stat of choice */
+      if (Mode == MEDIAN) {
+	fsort (Vbuf, nx);
+	value = Vbuf[(int)(0.5*nx)];
+      } else {
+	value = 0;
+	for (j = 0; j < nx; j++) {
+	  value += Vbuf[j];
+	}
+	if (Mode == MEAN) { value /= nx; }
       }
-
-      /* accumulate values */
-      // skip out-of-range areas in x
-      if (sx < 0) {
-	nx += sx;
-	sx = 0;
-      }
-      if (sx > Nx) sx = Nx;
-      if (sx + nx >= Nx) nx = Nx - sx;
-
-      Vin = (float *)(buf[0].matrix.buffer) + (sy + i)*Nx + sx; 
-      int Npix = 0;
-      for (j = 0; j < nx; j++, Vin ++) {
-	if (!isfinite(*Vin)) continue;
-	Vbuf[Npix] = *Vin;
-	Npix ++;
-      }
-      yvec[0].elements.Flt[i] = cutstat (Vbuf, Npix, Mode);
+      yvec[0].elements.Flt[i] = value;
     }
     free (Vbuf);
Index: trunk/Ohana/src/opihi/cmd.data/dbselect.c
===================================================================
--- trunk/Ohana/src/opihi/cmd.data/dbselect.c	(revision 41326)
+++ trunk/Ohana/src/opihi/cmd.data/dbselect.c	(revision 41340)
@@ -80,5 +80,4 @@
       case FIELD_TYPE_DOUBLE:
       case FIELD_TYPE_TIME:
-      case FIELD_TYPE_TIMESTAMP:
       case FIELD_TYPE_DATE:
       case FIELD_TYPE_DATETIME:
@@ -116,5 +115,4 @@
 	    break;
 	  case FIELD_TYPE_TIME:
-	  case FIELD_TYPE_TIMESTAMP:
 	  case FIELD_TYPE_DATE:
 	  case FIELD_TYPE_DATETIME:
Index: trunk/Ohana/src/opihi/cmd.data/extract.c
===================================================================
--- trunk/Ohana/src/opihi/cmd.data/extract.c	(revision 41326)
+++ trunk/Ohana/src/opihi/cmd.data/extract.c	(revision 41340)
@@ -1,25 +1,11 @@
 # include "data.h"
-
-/* <from> : source image, must exist
-   <to>   : target image -- if it does not exist, it is created of size (Nx,Ny)
-   sx, sy : source starting coordinate -- need not be on a valid image pixel
-   nx, ny : number of source pixels -- currently must not go out of bounds -> allow out-of-bounds
-   Sx, Sy : target starting coordinate -- need not be on a valid image pixel
-   Nx, Ny : redundant information UNLESS <to> does exist (in which case it is required information) -> make Nx,Ny optional if <to> exists?
- */
 
 int extract (int argc, char **argv) {
   
-  int N;
+  int i, j;
+  float *Vin, *Vout;
+  int sx, sy, nx, ny, NX, NY;
+  int Sx, Sy, Nx, Ny;
   Buffer *in, *out;
-
-  float initValue = 0.0;
-  int initOutput = FALSE;
-  if ((N = get_argument (argc, argv, "-init"))) {
-    remove_argument (N, &argc, argv);
-    initValue = atof (argv[N]);
-    remove_argument (N, &argc, argv);
-    initOutput = TRUE;
-  }
 
   if (argc != 11) {
@@ -29,24 +15,22 @@
 
   if ((in = SelectBuffer (argv[1], OLDBUFFER, TRUE)) == NULL) return (FALSE);
-  int NX = in[0].matrix.Naxis[0];
-  int NY = in[0].matrix.Naxis[1];
+  NX = in[0].matrix.Naxis[0];
+  NY = in[0].matrix.Naxis[1];
 
-  int sx = atof (argv[3]);
-  int sy = atof (argv[4]);
-  int nx = atof (argv[5]);
-  int ny = atof (argv[6]);
+  sx = atof (argv[3]);
+  sy = atof (argv[4]);
+  nx = atof (argv[5]);
+  ny = atof (argv[6]);
 
-  int Sx = atof (argv[7]);
-  int Sy = atof (argv[8]);
-  int Nx = atof (argv[9]);
-  int Ny = atof (argv[10]);
+  Sx = atof (argv[7]);
+  Sy = atof (argv[8]);
+  Nx = atof (argv[9]);
+  Ny = atof (argv[10]);
 
   if ((Sy + ny > Ny) || (Sx + nx > Nx)) {
-    gprint (GP_ERR, "source pixels extend beyond target pixels\n");
+    gprint (GP_ERR, "mismatch between source and dest regions\n");
     gprint (GP_ERR, "%d + %d > %d or %d + %d > %d\n", Sy, ny, Ny, Sx, nx, Nx);
-    // return (FALSE);
+    return (FALSE);
   }
-
-  // XXX : allow source region to fall outside source image
 
   /* region is not on first image */
@@ -55,10 +39,14 @@
       (sy > in[0].matrix.Naxis[1])) {
     gprint (GP_ERR, "region outside of source image\n");
-    // return (FALSE);
+    return (FALSE);
   }
 
+  if ((Sx + nx > Nx) || (Sy + ny > Ny)) {
+    gprint (GP_ERR, "source region larger than dest region\n");
+    return (FALSE);
+  }
   if ((Sx < 0) || (Sy < 0)) {
     gprint (GP_ERR, "dest region out of range\n");
-    // return (FALSE);
+    return (FALSE);
   }
 
@@ -88,61 +76,13 @@
   }
 
-  // (NX,NY) : source image dimensions
-  // (Nx,Ny) : target image dimensions
-
-  // allow (sx, sy), (Sx, Sy) to be off image
-  // allow (sx+nx, sy+ny) to be off image
-
-  // if (sx < 0) {
-  //   nx += sx;
-  //   sx = 0;
-  // }
-  // if (sx > NX) sx = NX;
-  // 
-  // if (Sx < 0) {
-  //   Nx += sx;
-  //   sx = 0;
-  // }
-  // if (sx > NX) sx = NX;
-  
-  float *Vin = (float *)(in[0].matrix.buffer);
-  float *Vout = (float *)(out[0].matrix.buffer);
-
-  if (initOutput) {
-    for (int j = 0; j < Ny; j++) {
-      for (int i = 0; i < Nx; i++) {
-	Vout[i + Nx*j] = initValue;
-      }
-    }
-  }
-
-  int Nps = NX*NY;
-  int Npt = Nx*Ny;
-
-  for (int j = 0; j < ny; j++) {
-    if (j + sy < 0) continue; // not yet on source image
-    if (j + Sy < 0) continue; // not yet on target image
-    if (j + sy >= NY) continue; // past edge of source image
-    if (j + Sy >= Ny) continue; // past edge of target image
-
-    // Vin = (float *)(in[0].matrix.buffer) + (j + sy)*in[0].matrix.Naxis[0] + sx;  
-    // Vout = (float *)(out[0].matrix.buffer) + (j + Sy)*out[0].matrix.Naxis[0] + Sx;   
-
-    for (int i = 0; i < nx; i++) {
+  for (j = 0; j < ny; j++) {
+    if (j + sy < 0) continue;
+    if (j + sy >= NY) continue;
+    Vin = (float *)(in[0].matrix.buffer) + (j + sy)*in[0].matrix.Naxis[0] + sx;  
+    Vout = (float *)(out[0].matrix.buffer) + (j + Sy)*out[0].matrix.Naxis[0] + Sx;   
+    for (i = 0; i < nx; i++, Vin++, Vout++) {
       if (i + sx < 0) continue;
       if (i + sx >= NX) continue;
-      if (i + Sx < 0) continue;
-      if (i + Sx >= Nx) continue;
-
-      int ps = i + sx + (j + sy)*NX;
-      int pt = i + Sx + (j + Sy)*Nx;
-
-      myAssert (pt >= 0, "oops 1");
-      myAssert (pt < Npt, "oops 2");
-
-      myAssert (ps >= 0, "oops 3");
-      myAssert (ps < Nps, "oops 4");
-
-      Vout[pt] = Vin[ps];
+      *Vout = *Vin;
     }
   }
@@ -151,2 +91,3 @@
 
 }
+
Index: trunk/Ohana/src/opihi/cmd.data/init.c
===================================================================
--- trunk/Ohana/src/opihi/cmd.data/init.c	(revision 41326)
+++ trunk/Ohana/src/opihi/cmd.data/init.c	(revision 41340)
@@ -3,5 +3,4 @@
 
 int accum            PROTO((int, char **));
-int antialias        PROTO((int, char **));
 int applyfit         PROTO((int, char **));
 int applyfit1d       PROTO((int, char **));
@@ -68,5 +67,4 @@
 int join             PROTO((int, char **));
 int jpeg             PROTO((int, char **));
-int kapamemory       PROTO((int, char **));
 int kern             PROTO((int, char **));
 int keyword          PROTO((int, char **));
@@ -81,10 +79,8 @@
 int lookup           PROTO((int, char **));
 int matrix           PROTO((int, char **));
-int match1d          PROTO((int, char **));
 int match2d          PROTO((int, char **));
 int mkrgb            PROTO((int, char **));
 int mcreate          PROTO((int, char **));
 int medacc           PROTO((int, char **));
-int mgaussdev        PROTO((int, char **));
 int mget             PROTO((int, char **));
 int mget3d           PROTO((int, char **));
@@ -103,5 +99,4 @@
 int parity           PROTO((int, char **));
 int point            PROTO((int, char **));
-int pdf              PROTO((int, char **));
 int ps               PROTO((int, char **));
 int vprint           PROTO((int, char **));
@@ -116,5 +111,4 @@
 int queuesubstr      PROTO((int, char **));
 int queuesize        PROTO((int, char **));
-int queue2book       PROTO((int, char **));
 int rd               PROTO((int, char **));
 int rdseg            PROTO((int, char **));
@@ -162,5 +156,4 @@
 int vgauss           PROTO((int, char **));
 int vlorentz         PROTO((int, char **));
-int vsigmoid         PROTO((int, char **));
 int vellipse         PROTO((int, char **));
 int vmaxwell         PROTO((int, char **));
@@ -170,11 +163,7 @@
 int vzload           PROTO((int, char **));
 int vstats           PROTO((int, char **));
-int vstats           PROTO((int, char **));
-int virls            PROTO((int, char **));
-int vwtmean          PROTO((int, char **));
 int vroll            PROTO((int, char **));
 int vshift           PROTO((int, char **));
 int vpeaks           PROTO((int, char **));
-int vtransitions     PROTO((int, char **));
 int vpop             PROTO((int, char **));
 int vsmooth          PROTO((int, char **));
@@ -198,5 +187,4 @@
 static Command cmds[] = {  
   {1, "accum",        accum,            "accumulate vector values in another vector"},
-  {1, "antialias",    antialias,        "set anti-alias sigma value for display"},
   {1, "applyfit",     applyfit1d,       "apply 1-d fit to new vector"},
   {1, "applyfit1d",   applyfit1d,       "apply 1-d fit to new vector"},
@@ -267,5 +255,4 @@
   {1, "join",         join,             "find the join of two ID vectors"},
   {1, "jpeg",         jpeg,             "convert display image to JPEG"},
-  {1, "kapamemory",   kapamemory,       "manage kapa memory dump options"},
   {1, "kern",         kern,             "convolve with 3x3 kernel"},
   {1, "keyword",      keyword,          "extract a FITS keyword from image header"},
@@ -278,5 +265,4 @@
   {1, "imcreate",     mcreate,          "create an image"},
   {1, "medacc",       medacc,           "accumulate vector values in another vector"},
-  {1, "mgaussdev",    mgaussdev,        "generate a gaussian deviate image"},
   {1, "mget",         mget,             "extract a vector from an image"},
   {1, "mget3d",       mget3d,           "extract a vector from a 3D image"},
@@ -287,5 +273,4 @@
   {1, "medimage",     medimage_command, "median image manipulation"},
   {1, "matrix",       matrix,           "matrix math operations"},
-  {1, "match1d",      match1d,          "match 2 vectors and return matched indexes"},
   {1, "match2d",      match2d,          "match 2 pairs of X,Y vectors and return matched indexes"},
   {1, "mkrgb",        mkrgb,            "convert 3 images to rgb jpeg (use Kapa for better control)"},
@@ -304,5 +289,4 @@
   {1, "ppm",          jpeg,             "convert display graphic to PPM"},
   {1, "ps",           ps,               "convert display to PostScript"},
-  {1, "pdf",          pdf,              "convert display to PDF"},
   {1, "print_vectors", vprint,          "print a set of vectors"},
   {1, "vprint",       vprint,           "print a set of vectors"},
@@ -317,6 +301,4 @@
   {1, "queuesize",    queuesize,        "show queue size"},
   {1, "queuesubstr",  queuesubstr,      "bulk replace strings in queue"},
-  {1, "queue2book",   queue2book,       "convert queue with ipptool output to book"},
-  {1, "ipptool2book", queue2book,       "convert queue with ipptool output to book"},
   {1, "rd",           rd,               "load fits image"},
   {1, "rdseg",        rdseg,            "read a segment of an image from a file"},
@@ -365,5 +347,4 @@
   {1, "vgauss",       vgauss,           "fit a Gaussian to a vector"},
   {1, "vlorentz",     vlorentz,         "fit a Lorentzian to a vector"},
-  {1, "vsigmoid",     vsigmoid,         "fit a Sigmoid to a vector"},
   {1, "vellipse",     vellipse,         "fit a Ellipse to a vector pair"},
   {1, "vgrid",        vgrid,            "generate an image from a triplet of vectors"},
@@ -373,6 +354,5 @@
   {1, "vload",        vload,            "load vectors as overlay on image display"},
   {1, "vmaxwell",     vmaxwell,         "fit a Maxwellian to a vector"},
-  {1, "vpeaks",       vpeaks,           "find coord and flux of peaks in vector"},
-  {1, "vtransitions", vtransitions,     "find points in vector that cross the transition value"},
+  {1, "vpeaks",       vpeaks,           "fine coord and flux of peaks in vector"},
   {1, "vpop",         vpop,             "remove first element of a vector"},
   {1, "vroll",        vroll,            "roll vector elements by 1 entry"},
@@ -380,6 +360,4 @@
   {1, "vsmooth",      vsmooth,          "Gaussian smooth of a vector"},
   {1, "vstats",       vstats,           "statistics on a vector"},
-  {1, "vwtmean",      vwtmean,          "weighted mean of a vector"},
-  {1, "virls",        virls,            "IRLS mean of a vector"},
   {1, "vzload",       vzload,           "load vectors as overlay on image display (scaled points)"},
   {1, "vsh",          vsh,              "Vector Spherical Harmonics"},
Index: trunk/Ohana/src/opihi/cmd.data/interpolate_presort.c
===================================================================
--- trunk/Ohana/src/opihi/cmd.data/interpolate_presort.c	(revision 41326)
+++ trunk/Ohana/src/opihi/cmd.data/interpolate_presort.c	(revision 41340)
@@ -7,11 +7,4 @@
   double x0, dx, dy, y0;
   Vector *xout, *yout, *xin, *yin;
-
-  int N;
-  int FillEnds = FALSE;
-  if ((N = get_argument (argc, argv, "-fill-ends"))) {
-    FillEnds = TRUE;
-    remove_argument (N, &argc, argv);
-  }
 
   /** check basic syntax **/
@@ -43,12 +36,10 @@
   y0 = yin[0].elements.Flt[0];
   
-  // fill in the start with NANs
-  for (i = 0; (i < xout[0].Nelements) && (xout[0].elements.Flt[i] < xin[0].elements.Flt[0]); i++) {
-    yout[0].elements.Flt[i] = FillEnds ? yin[0].elements.Flt[0] : NAN;
-  }
+  /* in and out vectors are sorted */
+  j = 0;
 
   // every output pixel should get a value unless 
   // we are below the lowest in or above the highest in
-  for (j = 0; (i < xout[0].Nelements) && (j < xin[0].Nelements - 1); ) {
+  for (i = 0, j = 0; (i < xout[0].Nelements) && (j < xin[0].Nelements - 1); ) {
 
     yout[0].elements.Flt[i] = NAN;
@@ -75,10 +66,10 @@
 
   // fill in the rest with NANs
-  int NinLast = xin[0].Nelements - 1;
   while (i < yout[0].Nelements) {
-    yout[0].elements.Flt[i] = FillEnds ? yin[0].elements.Flt[NinLast] : NAN;
+    yout[0].elements.Flt[i] = NAN;
     i++;
   }
 
   return (TRUE);
+    
 }
Index: trunk/Ohana/src/opihi/cmd.data/kapamemory.c
===================================================================
--- trunk/Ohana/src/opihi/cmd.data/kapamemory.c	(revision 41326)
+++ 	(revision )
@@ -1,56 +1,0 @@
-# include "data.h"
-
-int kapamemory (int argc, char **argv) {
-
-  int N, kapa;
-
-  /* display source */
-  char *name = NULL;
-  if ((N = get_argument (argc, argv, "-n"))) {
-    remove_argument (N, &argc, argv);
-    name = strcreate (argv[N]);
-    remove_argument (N, &argc, argv);
-  }
-  if (!GetImage (NULL, &kapa, name)) return (FALSE);
-  FREE (name);
-
-  if (argc < 2) {
-    gprint (GP_ERR, "USAGE: kapamemory (mode)\n");
-    gprint (GP_ERR, "  mode = dump, nlines, exit\n");
-    return (FALSE);
-  }
-
-  if (!strcasecmp(argv[1], "dump")) {
-    KapaMemoryDump (kapa);
-    return TRUE;
-  }
-
-  if (!strcasecmp(argv[1], "exit")) {
-    if (argc != 3) goto exit_usage;
-    if (!strcasecmp(argv[2], "on")) {
-      KapaMemoryDumpOnExit (kapa, TRUE);
-      return TRUE;
-    }
-    if (!strcasecmp(argv[2], "off")) {
-      KapaMemoryDumpOnExit (kapa, FALSE);
-      return TRUE;
-    }
-  exit_usage:
-    gprint (GP_ERR, "USAGE: kapamemory exit (status)\n");
-    gprint (GP_ERR, "  statue = 'on' or 'off'\n");
-    return FALSE;
-  }
-
-  if (!strcasecmp(argv[1], "nlines")) {
-    if (argc != 3) {
-      gprint (GP_ERR, "USAGE: kapamemory nlines (N)\n");
-      return FALSE;
-    }
-    int Nlines = atoi (argv[2]);
-    KapaMemoryDumpLines (kapa, Nlines);
-    return TRUE;
-  }
-  gprint (GP_ERR, "ERROR: unknown kapamemory mode %s\n", argv[1]);
-  return FALSE;
-}
-
Index: trunk/Ohana/src/opihi/cmd.data/list_vectors.c
===================================================================
--- trunk/Ohana/src/opihi/cmd.data/list_vectors.c	(revision 41326)
+++ trunk/Ohana/src/opihi/cmd.data/list_vectors.c	(revision 41340)
@@ -32,26 +32,16 @@
   }
 
-  switch (vec->type) {
-    case OPIHI_FLT:
-      if (Variable) {
-	set_str_variable (Variable, "FLT");
-      } else {
-	gprint (GP_LOG, "%s : FLT\n", argv[1]);
-      }
-      break;
-    case OPIHI_INT:
-      if (Variable) {
-	set_str_variable (Variable, "INT");
-      } else {
-	gprint (GP_LOG, "%s : INT\n", argv[1]);
-      }
-      break;
-    case OPIHI_STR:
-      if (Variable) {
-	set_str_variable (Variable, "STR");
-      } else {
-	gprint (GP_LOG, "%s : STR\n", argv[1]);
-      }
-      break;
+  if (vec->type == OPIHI_FLT) {
+    if (Variable) {
+      set_str_variable (Variable, "FLT");
+    } else {
+      gprint (GP_LOG, "%s : FLT\n", argv[1]);
+    }
+  } else {
+    if (Variable) {
+      set_str_variable (Variable, "INT");
+    } else {
+      gprint (GP_LOG, "%s : INT\n", argv[1]);
+    }
   }
   if (Variable) free (Variable);
Index: trunk/Ohana/src/opihi/cmd.data/match1d.c
===================================================================
--- trunk/Ohana/src/opihi/cmd.data/match1d.c	(revision 41326)
+++ 	(revision )
@@ -1,248 +1,0 @@
-# include "data.h"
-
-int find_matches1d (Vector *X1, Vector *X2, double Radius, Vector *index1, Vector *index2, Vector *radiusMatch);
-int find_matches1d_closest (Vector *X1, Vector *X2, double Radius, Vector *index);
-
-// match1d (X1) (X2) (Radius) [-index1 (index1)] [-index2 (index2)] [-nomatch1 nomatch1] [-nomatch2 nomatch2]
-int match1d (int argc, char **argv) {
-  
-  int N, CLOSEST;
-  double Radius;
-  char *endptr;
-  Vector *X1vec, *X2vec;
-  Vector *index1, *index2;
-
-  if ((N = get_argument (argc, argv, "-h"))) goto usage;
-  if ((N = get_argument (argc, argv, "--help"))) goto usage;
-
-  CLOSEST = FALSE;
-  if ((N = get_argument (argc, argv, "-closest"))) {
-    remove_argument (N, &argc, argv);
-    CLOSEST = TRUE;
-  }
-
-  if ((N = get_argument (argc, argv, "-index1"))) {
-    remove_argument (N, &argc, argv);
-    if ((index1 = SelectVector (argv[N], ANYVECTOR, TRUE)) == NULL) return (FALSE);    
-    remove_argument (N, &argc, argv);
-  } else {
-    if ((index1 = SelectVector ("index1", ANYVECTOR, TRUE)) == NULL) return (FALSE);    
-  }
-
-  if ((N = get_argument (argc, argv, "-index2"))) {
-    remove_argument (N, &argc, argv);
-    if ((index2 = SelectVector (argv[N], ANYVECTOR, TRUE)) == NULL) return (FALSE);    
-    remove_argument (N, &argc, argv);
-  } else {
-    if ((index2 = SelectVector ("index2", ANYVECTOR, TRUE)) == NULL) return (FALSE);    
-  }
-
-  Vector *radiusMatch = NULL;
-  if ((N = get_argument (argc, argv, "-radius"))) {
-    if (CLOSEST) {
-      gprint (GP_ERR, "error: -radius and -closest are currently incompatible\n");
-      return (FALSE);
-    }
-    remove_argument (N, &argc, argv);
-    if ((radiusMatch = SelectVector (argv[N], ANYVECTOR, TRUE)) == NULL) return (FALSE);    
-    remove_argument (N, &argc, argv);
-  }
-
-  if (argc != 4) {
-    gprint (GP_ERR, "USAGE: match1d X1 X2 Radius [-index1 (index1)] [-index2 (index2)] [-closest]\n");
-    gprint (GP_ERR, "  use -h or --help for more detail\n");
-    return (FALSE);
-  }
-
-  /*
-    we have two modes of operation:  
-
-    without -closest, we are finding all matched pairs within the match radius.  in this
-    case, the two index vectors have the same length, one entry per matched pair.
-    x1[index1],y1[index1] matches to x2[index2],y2[index2].
-
-    with -closest selected, we are finding the closest element of set 1 to each of set 2
-    and vice versa.  in this case, index1 is always the same length as x1,y1, while index2
-    is the same lengths as x2,y2.  x2[index1],y2[index1] matches x1,y1 while
-    x1[index2],y1[index2] matches x2,y2
-
-   */
-
-  if ((X1vec = SelectVector (argv[1], OLDVECTOR, TRUE)) == NULL) return (FALSE);    
-  if ((X2vec = SelectVector (argv[2], OLDVECTOR, TRUE)) == NULL) return (FALSE);    
-
-  REQUIRE_VECTOR_FLT (X1vec, FALSE); 
-  REQUIRE_VECTOR_FLT (X2vec, FALSE); 
-
-  Radius = strtod (argv[3], &endptr);
-  if (*endptr) {
-    gprint (GP_ERR, "Radius must be numerical (%s)\n", argv[3]);
-    return (FALSE);
-  }
-
-  if (CLOSEST) {
-    find_matches1d_closest (X1vec, X2vec, Radius, index1);
-    find_matches1d_closest (X2vec, X1vec, Radius, index2);
-  } else {
-    find_matches1d (X1vec, X2vec, Radius, index1, index2, radiusMatch);
-  }
-  return (TRUE);
-
-usage:
-  gprint (GP_ERR, "we have two modes of operation:\n\n");
-
-  gprint (GP_ERR, "without -closest, we are finding all matched pairs within the match radius.  in this\n");
-  gprint (GP_ERR, "case, the two index vectors have the same length, one entry per matched pair.\n");
-  gprint (GP_ERR, "x1[index1] matches to x2[index2].\n\n");
-
-  gprint (GP_ERR, "with -closest selected, we are finding the closest element of set 1 to each of set 2\n");
-  gprint (GP_ERR, "and vice versa.  in this case, index1 is always the same length as x1, while index2\n");
-  gprint (GP_ERR, "is the same lengths as x2.  x2[index1] matches x1 while\n");
-  gprint (GP_ERR, "x1[index2] matches x2\n\n");
-
-  gprint (GP_ERR, "if -index1 or -index2 is not supplied, the vectors are created with names index1 or index2\n");
-  gprint (GP_ERR, "use 'reindex' to generate new vectors based on these index vectors\n");
-
-  gprint (GP_ERR, "if -radius (vector) is supplied, the vector will be filled with the distance between the matched pairs\n");
-  gprint (GP_ERR, "  not valid with -closest\n");
-  return FALSE;
-}
-
-// Radius is a 1-D separation
-int find_matches1d (Vector *X1, Vector *X2, double Radius, Vector *index1, Vector *index2, Vector *radiusMatch) {
-  
-  off_t i, j, first_j, I, J, *N1, *N2, Nmatch, NMATCH, DMATCH;
-  double dX, dR;
-
-  NMATCH = MAX(MAX(0.01*X1->Nelements, 0.01*X2->Nelements), 100);
-  DMATCH = NMATCH;
-
-  ResetVector (index1, OPIHI_INT, NMATCH);
-  ResetVector (index2, OPIHI_INT, NMATCH);
-  if (radiusMatch) ResetVector (radiusMatch, OPIHI_FLT, NMATCH);
-
-  ALLOCATE (N1, off_t, X1->Nelements);
-  ALLOCATE (N2, off_t, X2->Nelements);
-
-  for (i = 0; i < X1->Nelements; i++) { N1[i] = i; }
-  for (i = 0; i < X2->Nelements; i++) { N2[i] = i; }
-
-  dsort_indexonly (X1->elements.Flt, N1, X1->Nelements);
-  dsort_indexonly (X2->elements.Flt, N2, X2->Nelements);
-
-  Nmatch = 0;
-  for (i = j = 0; (i < X1->Nelements) && (j < X2->Nelements);) {
-    I = N1[i];
-    J = N2[j];
-
-    if (!isfinite(X1->elements.Flt[I])) { i++; continue; }
-    if (!isfinite(X2->elements.Flt[J])) { j++; continue; }
-
-    dX = X1->elements.Flt[I] - X2->elements.Flt[J];
-
-    if (dX <= -1.02*Radius) { i++; continue; }
-    if (dX >= +1.02*Radius) { j++; continue; }
-
-    // look for all matches of list2() to list1(i)
-    first_j = j;
-    for (j = first_j; (dX > -1.02*Radius) && (j < X2->Nelements); j++) {
-      J = N2[j];
-      dX = X1->elements.Flt[I] - X2->elements.Flt[J];
-      dR = fabs(dX);
-      if (dR < Radius) {
-	index1->elements.Int[Nmatch] = I;
-	index2->elements.Int[Nmatch] = J;
-	if (radiusMatch) radiusMatch->elements.Flt[Nmatch] = dR;
-
-	// XXX track matches 1 and 2 with internal vector, save new nomatch index vectors
-	// after this loop
-
-	Nmatch ++;
-	if (Nmatch >= NMATCH) {
-	  NMATCH += DMATCH;
-	  REALLOCATE (index1->elements.Int, opihi_int, NMATCH);
-	  REALLOCATE (index2->elements.Int, opihi_int, NMATCH);
-	  if (radiusMatch) { REALLOCATE (radiusMatch->elements.Flt, opihi_flt, NMATCH); }
-	}
-      }
-    }
-    j = first_j;
-    i++;
-  }
-  index1->Nelements = Nmatch;
-  index2->Nelements = Nmatch;
-  if (radiusMatch) radiusMatch->Nelements = Nmatch;
-
-  free (N1);
-  free (N2);
-
-  return (TRUE);
-}
-
-// find the elements of X2,Y2 which are closest to each element of X1,Y1 (-1 if no match)
-int find_matches1d_closest (Vector *X1, Vector *X2, double Radius, Vector *index) {
-  
-  off_t i, j, Jmin, Ji, I, J, *N1, *N2, NMATCH;
-  double dX, dR, Rmin;
-
-  NMATCH = X1->Nelements;
-  ResetVector (index, OPIHI_INT, NMATCH);
-
-  for (i = 0; i < index->Nelements; i++) { index->elements.Int[i] = -1; }
-
-  ALLOCATE (N1, off_t, X1->Nelements);
-  ALLOCATE (N2, off_t, X2->Nelements);
-
-  for (i = 0; i < X1->Nelements; i++) { N1[i] = i; }
-  for (i = 0; i < X2->Nelements; i++) { N2[i] = i; }
-
-  dsort_indexonly (X1->elements.Flt, N1, X1->Nelements);
-  dsort_indexonly (X2->elements.Flt, N2, X2->Nelements);
-
-  // find the closest entry in list 2 to the current entry in list 1:
-  for (i = j = 0; (i < X1->Nelements) && (j < X2->Nelements);) {
-    I = N1[i];
-    J = N2[j];
-
-    dX = X1->elements.Flt[I] - X2->elements.Flt[J];
-
-    if (dX <= -1.02*Radius) { 
-      // no match in list 2 to this entry
-      index->elements.Int[I] = -1;
-      i++; 
-      continue; 
-    }
-    if (dX >= +1.02*Radius) { j++; continue; }
-
-    // look for closest matches of list2() to list1(i)
-    Jmin = -1;
-    for (Ji = j; (dX > -1.02*Radius) && (Ji < X2->Nelements); Ji++) {
-      J = N2[Ji];
-      dX = X1->elements.Flt[I] - X2->elements.Flt[J];
-      dR = fabs(dX);
-      if (dR > Radius) continue;
-      if (dR < Rmin) {
-	Rmin = dR;
-	Jmin  = J;
-      }
-    }
-
-    // no match in list 2 to this entry
-    if (Jmin == -1) {
-      index->elements.Int[I] = -1;
-      i++;
-      continue;
-    }
-    index->elements.Int[I] = Jmin;
-    i++;
-  }
-  index->Nelements = NMATCH;
-
-  free (N1);
-  free (N2);
-
-  return (TRUE);
-}
-
-
-
Index: trunk/Ohana/src/opihi/cmd.data/medimage_calc.c
===================================================================
--- trunk/Ohana/src/opihi/cmd.data/medimage_calc.c	(revision 41326)
+++ 	(revision )
@@ -1,365 +1,0 @@
-# include "data.h"
-
-float weight_cauchy_square_flt (float x2);
-float irls_mean (float *val, float *wgt, int N, float *outvar, int *Npt);
-float irls_fraction_interpolate (float *values, float fraction, int Npts);
-float irls_robust_stdev (float *values, int Npts);
-float irls_wtmean (float *val, float *wgt, int *idx, int Npt, float *variance);
-void irls_bootstrap (int *idx, int Npts);
-void irls_init (int N);
-void irls_free (void);
-
-# define IRLS_TOLERANCE 1e-4
-int BOOTSTRAP = FALSE;
-int BOOTSTRAP_NITER = 100;
-
-static float *irls_valsub  = NULL;
-static float *irls_wgtsub  = NULL;
-static int   *irls_idx     = NULL;
-static float *irls_testval = NULL;
-
-enum {CALC_MEDIAN, CALC_MEAN, CALC_IRLS, CALC_WTMEAN};
-
-int medimage_calc (int argc, char **argv) {
-
-  int ix, iy, n, N;
-  Buffer *output;
-  
-  BOOTSTRAP = FALSE;
-  if ((N = get_argument (argc, argv, "-bootstrap"))) {
-    BOOTSTRAP = TRUE;
-    remove_argument (N, &argc, argv);
-  }
-  BOOTSTRAP_NITER = 100;
-  if ((N = get_argument (argc, argv, "-bootstrap-iter"))) {
-    remove_argument (N, &argc, argv);
-    BOOTSTRAP_NITER = atoi (argv[N]);
-    remove_argument (N, &argc, argv);
-    BOOTSTRAP = TRUE;
-  }
-
-  int mode = CALC_MEDIAN;
-  if ((N = get_argument (argc, argv, "-mean"))) {
-    mode = CALC_MEAN;
-    remove_argument (N, &argc, argv);
-  }
-  if ((N = get_argument (argc, argv, "-irls"))) {
-    if (mode != CALC_MEDIAN) { gprint (GP_ERR, "supply only one of -mean, -median, -irls, -wtmean\n"); return FALSE; }
-    mode = CALC_IRLS;
-    remove_argument (N, &argc, argv);
-  }
-  if ((N = get_argument (argc, argv, "-wtmean"))) {
-    if (mode != CALC_MEDIAN) { gprint (GP_ERR, "supply only one of -mean, -median, -irls, -wtmean\n"); return FALSE; }
-    mode = CALC_WTMEAN;
-    remove_argument (N, &argc, argv);
-  }
-  if ((N = get_argument (argc, argv, "-median"))) {
-    if (mode != CALC_MEDIAN) { gprint (GP_ERR, "supply only one of -mean, -median, -irls, -wtmean\n"); return FALSE; }
-    mode = CALC_MEDIAN;
-    remove_argument (N, &argc, argv);
-  }
-
-  Buffer *variance = NULL;
-  if ((N = get_argument (argc, argv, "-variance"))) {
-    remove_argument (N, &argc, argv);
-    if ((variance = SelectBuffer (argv[N], ANYBUFFER, TRUE)) == NULL) return (FALSE);
-    remove_argument (N, &argc, argv);
-  }
-
-  if (argc != 3) {
-    gprint (GP_ERR, "USAGE: medimage calc (name) (output) [-mean,-irls,-wtmean,-median] [-variance output] [-bootstrap] [-bootstrap-iter (N)]\n");
-    gprint (GP_ERR, "       calculate the median image for the median image set\n");
-    gprint (GP_ERR, "  This function calculates the 'average' image for the supplied set of images.\n");
-    gprint (GP_ERR, "  Four options are available to calculate the average:\n");
-    gprint (GP_ERR, "   -mean (straight arithmetic mean)\n");
-    gprint (GP_ERR, "   -median\n");
-    gprint (GP_ERR, "   -wtmean (arithmetic mean, weighted by supplied variances)\n");
-    gprint (GP_ERR, "   -irls (iteratively-reweighted least-squares)\n");
-    gprint (GP_ERR, "  If -variance is supplied the returned image represents the estimate of the variance on the average image\n");
-    gprint (GP_ERR, "  For the four average methods above, the sqrt of the variance has the following meanings:\n");
-    gprint (GP_ERR, "   -mean   : standard deviation / sqrt(Npts)\n");
-    gprint (GP_ERR, "   -median : standard deviation / sqrt(Npts)\n");
-    gprint (GP_ERR, "   -wtmean : formal error on the weighted mean [sum (1 / variances)]\n");
-    gprint (GP_ERR, "   -irls   : formal error on the pixels used (excluding ~3 sigma outliers)\n");
-    gprint (GP_ERR, "   note that the irls formal error slightly underestimates the observed standard deviation\n");
-    return FALSE;
-  }
-
-  MedImageType *median = FindMedImage (argv[1]);
-  if (!median) {
-    gprint (GP_ERR, "median image %s not found\n", argv[1]);
-    return FALSE;
-  }
-
-  if ((output = SelectBuffer (argv[2], ANYBUFFER, TRUE)) == NULL) return (FALSE);
-
-  int Ninput = median->Ninput;
-  int Nx = median->Nx;
-  int Ny = median->Ny;
-
-  ALLOCATE_PTR (val, float, Ninput);
-  ALLOCATE_PTR (wgt, float, Ninput);
-
-  if (mode == CALC_IRLS) irls_init (Ninput);
-
-  gfits_free_matrix (&output->matrix);
-  gfits_free_header (&output->header);
-  if (!CreateBuffer (output, Nx, Ny, -32, 0.0, 1.0)) return FALSE;
-
-  float *outvalue = (float *) output->matrix.buffer;
-  float *varvalue = NULL;
-  if (variance) {
-    gfits_free_matrix (&variance->matrix);
-    gfits_free_header (&variance->header);
-    if (!CreateBuffer (variance, Nx, Ny, -32, 0.0, 1.0)) return FALSE;
-
-    varvalue = (float *) variance->matrix.buffer;
-  }
-
-  // save the number of points per pixel
-  Buffer *nptbuf = SelectBuffer ("irls_npt", ANYBUFFER, TRUE);
-  gfits_free_matrix (&nptbuf->matrix);
-  gfits_free_header (&nptbuf->header);
-  if (!CreateBuffer (nptbuf, Nx, Ny, -32, 0.0, 1.0)) return FALSE;
-  float *NptVal = (float *) nptbuf->matrix.buffer;
-
-  for (iy = 0; iy < Ny; iy++) {
-    for (ix = 0; ix < Nx; ix++) {
-
-      int N = 0;
-      int Npix = ix + Nx*iy;
-      for (n = 0; n < Ninput; n++) {
-	float v = median->flx[n][Npix];
-	if (!isfinite(v)) continue;
-	val[N] = v;
-	wgt[N] = 1.0;
-	if (median->var[n]) {
-	  float s = median->var[n][Npix];
-	  if (!isfinite(s)) continue;
-	  if (fabs(s) < 2*FLT_MIN) s = 2*FLT_MIN;
-	  wgt[N] = 1.0 / s;
-	}
-	N++;
-      }
-      if (N == 0) continue;
-
-      switch (mode) {
-	case CALC_MEDIAN:
-	  fsort (val, N);
-	  outvalue[Npix] = val[(int)(0.5*N)];
-	  if (varvalue) {
-	    float sum = 0.0;
-	    for (n = 0; n < N; n++) {
-	      sum += SQ(val[n] - outvalue[Npix]);
-	    }
-	    // variance on the mean (stdev / sqrt(N))^2
-	    varvalue[Npix] = sum / (N - 1) / N;
-	  }
-	  break;
-	case CALC_MEAN: {
-	  float sum = 0.0;
-	  for (n = 0; n < N; n++) {
-	    sum += val[n];
-	  }
-	  outvalue[Npix] = sum / (float) N;
-
-	  if (varvalue) {
-	    float Sum = 0.0;
-	    for (n = 0; n < N; n++) {
-	      Sum += SQ(val[n] - outvalue[Npix]);
-	    }
-	    // variance on the mean (stdev / sqrt(N))^2
-	    varvalue[Npix] = Sum / (N - 1) / N;
-	  }
-	  break;
-	}
-	case CALC_WTMEAN: {
-	  float variance;
-	  outvalue[Npix] = irls_wtmean (val, wgt, NULL, N, &variance);
-	  if (varvalue) { varvalue[Npix] = variance; }
-	  break;
-	}
-	case CALC_IRLS: 
-	  if (varvalue) {
-	    int Npts = 0;
-	    outvalue[Npix] = irls_mean (val, wgt, N, &varvalue[Npix], &Npts);
-	    NptVal[Npix] = Npts;
-	  } else {
-	    int Npts = 0;
-	    outvalue[Npix] = irls_mean (val, wgt, N, NULL, &Npts);
-	    NptVal[Npix] = Npts;
-	  }
-      }
-    }
-  }
-  irls_free();
-  return TRUE;
-}
-
-// allocate temporary vectors
-void irls_init (int N) {
-
-  ALLOCATE (irls_valsub, float, N);
-  ALLOCATE (irls_wgtsub, float, N);
-  ALLOCATE (irls_idx, int, N);
-  ALLOCATE (irls_testval, float, BOOTSTRAP_NITER);
-}
-
-// free temporary vectors
-void irls_free (void) {
-  FREE (irls_valsub); 
-  FREE (irls_wgtsub);
-  FREE (irls_idx);
-  FREE (irls_testval);
-  irls_valsub = NULL;
-  irls_wgtsub = NULL;
-  irls_idx = NULL;
-  irls_testval = NULL;
-}
-
-float irls_mean (float *val, float *wgt, int N, float *outvar, int *Npt) {
-
-  // calculate weighted mean
-  float Value = irls_wtmean (val, wgt, NULL, N, NULL);
-
-  int converged = FALSE;
-  for (int i = 0; (i < 10) && !converged; i++) {
-    float ValueLast = Value;
-    float S1 = 0.0, S2 = 0.0;
-    
-    // calculate weight modification based on distances (squared).
-    // use modifier to calculate new weighted mean
-    for (int n = 0; n < N; n++) {
-      float dV = (val[n] - Value);
-      float d2 = SQ(dV) * wgt[n];
-      
-      float Mod = weight_cauchy_square_flt (d2);
-      S1 += Mod * wgt[n] * val[n];
-      S2 += Mod * wgt[n];
-    }
-    Value = S1 / S2;
-
-    float delta = fabs(Value - ValueLast);
-    if (delta < Value * IRLS_TOLERANCE) converged = TRUE;
-  }
-
-  if (outvar) {
-    if (BOOTSTRAP) {
-      // generate a subset vector of just the accepted points
-    
-      // calculate stdev of high-weight points
-      int npt = 0;
-      for (int n = 0; n < N; n++) {
-
-	float dV = (val[n] - Value);
-	float d2 = SQ(dV) * wgt[n];
-      
-	float Mod = weight_cauchy_square_flt (d2);
-	if (Mod < 0.1) continue; // totally ad-hoc number
-
-	irls_valsub[npt] = val[n];
-	irls_wgtsub[npt] = wgt[n];
-	npt ++;
-      }
-
-      for (int iter = 0; iter < BOOTSTRAP_NITER; iter++) {
-	irls_bootstrap (irls_idx, npt); // fill idx with the index of the resampled points
-	irls_testval[iter] = irls_wtmean (irls_valsub, irls_wgtsub, irls_idx, npt, NULL);
-      }
-
-      float sigma = irls_robust_stdev (irls_testval, BOOTSTRAP_NITER);
-
-      *outvar = SQ(sigma);
-      *Npt = npt;
-    } else {
-      // calculate stdev of high-weight points
-      float S1 = 0.0, S2 = 0.0;
-      int npt = 0;
-      for (int n = 0; n < N; n++) {
-
-	float dV = (val[n] - Value);
-	float d2 = SQ(dV) * wgt[n];
-      
-	float Mod = weight_cauchy_square_flt (d2);
-	if (Mod < 0.1) continue; // totally ad-hoc number
-
-	S1 += SQ(dV);
-	S2 += wgt[n];
-	npt ++;
-      }
-      *Npt = npt;
-      *outvar = 1 / S2;
-    }
-  }
-
-  return Value;
-}
-
-void irls_bootstrap (int *idx, int Npts) {
-  // generate an index (idx) containing the index values
-  // for the Npts randomly resampled points
-  for (int i = 0; i < Npts; i++) {
-    idx[i] = Npts * drand48();
-  }
-}
-
-float irls_wtmean (float *val, float *wgt, int *idx, int Npt, float *variance) {
-  float S1 = 0.0, S2 = 0.0;
-  for (int n = 0; n < Npt; n++) {
-    int N = idx ? idx[n] : n;
-    S1 += wgt[N] * val[N];
-    S2 += wgt[N];
-  }
-  float Value = S1 / S2;
-  if (variance) *variance = 1.0 / S2;
-  return Value;
-}
-
-float irls_robust_stdev (float *values, int Npts) {
-
-  fsort (values, Npts);
-
-  float Slo = irls_fraction_interpolate (values, 0.158655, Npts);
-  float Shi = irls_fraction_interpolate (values, 0.841345, Npts);
-  float sigma = (Shi - Slo) / 2.0;
-  
-  return sigma;
-}
-
-float irls_fraction_interpolate (float *values, float fraction, int Npts) {
-
-  float F = fraction * Npts;
-  int   N = fraction * Npts;
-
-  if (N < 0        ) return NAN;
-  if (N >= Npts - 2) return NAN;
-
-  // interpolate between N,N+1
-    
-  float S = (F - N) * (values[N+1] - values[N]) + values[N];
-  return S;
-}
-
-
-// exp(-(x^2/s^2)/2) = (1/2)
-//     -(x^2/s^2)/2  = ln(1/2)
-//      (x^2/s^2)/2  = ln(2)
-//      (x^2/s^2)    = 2ln(2)
-//      (x  /s)      = sqrt(2ln(2)) : half-width at half-max
-//       FWHM        = 2sqrt(2ln(2))
-
-// R2 = (X / 2.385)^2 = (X^2 / 2.385^2)
-
-# define CAUCY_FACTOR 2.0
-
-/*
-float weight_cauchy_square_flt (float x2) {
-  return (1.0);
-}
-*/
-
-float weight_cauchy_square_flt (float x2) {
-  float r2 = x2 / CAUCY_FACTOR;
-  return (1.0 / (1.0 + r2));
-}
-
Index: trunk/Ohana/src/opihi/cmd.data/medimage_commands.c
===================================================================
--- trunk/Ohana/src/opihi/cmd.data/medimage_commands.c	(revision 41326)
+++ trunk/Ohana/src/opihi/cmd.data/medimage_commands.c	(revision 41340)
@@ -15,30 +15,13 @@
 int medimage_add (int argc, char **argv) {
 
-  int N;
   Buffer *image;
-  Buffer *var = NULL;
-
-  if ((N = get_argument (argc, argv, "-variance"))) {
-    remove_argument (N, &argc, argv);
-    if ((var = SelectBuffer (argv[N], OLDBUFFER, TRUE)) == NULL) return (FALSE);
-    remove_argument (N, &argc, argv);
-  }
-
-  if (argc != 3) {
-    gprint (GP_ERR, "USAGE: medimage add (name) (image) [-variance variance]\n");
+
+  if (argc != 3) {
+    gprint (GP_ERR, "USAGE: medimage add (name) (image)\n");
     gprint (GP_ERR, "       add the given image to the set of images to be medianed\n");
-    gprint (GP_ERR, "       optionally supply variance image (for weighted calculations)\n");
     return FALSE;
   }
 
   if ((image = SelectBuffer (argv[2], OLDBUFFER, TRUE)) == NULL) return (FALSE);
-
-  if (var) {
-    if ((var->matrix.Naxis[0] != image->matrix.Naxis[0]) ||
-	(var->matrix.Naxis[1] != image->matrix.Naxis[1])) {
-      gprint (GP_ERR, "variance buffer does not match image buffer dimensions\n");
-      return FALSE;
-    }
-  }
 
   MedImageType *median = FindMedImage (argv[1]);
@@ -63,17 +46,76 @@
   // new image should match existing medimage dimensions
 
-  // AddMedImage (median, image, var);
   int Ninput = median->Ninput;
   median->Ninput ++;
-  REALLOCATE (median->flx, float *, median->Ninput);
-  REALLOCATE (median->var, float *, median->Ninput);
-
-  ALLOCATE (median->flx[Ninput], float, median->Nx*median->Ny);
-  memcpy (median->flx[Ninput], image->matrix.buffer, sizeof(float)*median->Nx*median->Ny);
-
-  median->var[Ninput] = NULL;
-  if (var) {
-    ALLOCATE (median->var[Ninput], float, median->Nx*median->Ny);
-    memcpy (median->var[Ninput], var->matrix.buffer, sizeof(float)*median->Nx*median->Ny);
+  REALLOCATE (median->buffers, float *, median->Ninput);
+
+  ALLOCATE (median->buffers[Ninput], float, median->Nx*median->Ny);
+  memcpy (median->buffers[Ninput], image->matrix.buffer, sizeof(float)*median->Nx*median->Ny);
+
+  return TRUE;
+}
+
+int medimage_calc (int argc, char **argv) {
+
+  int ix, iy, n, N;
+  Buffer *output;
+
+  int CALC_MEAN = FALSE;
+  if ((N = get_argument (argc, argv, "-mean"))) {
+    CALC_MEAN = TRUE;
+    remove_argument (N, &argc, argv);
+  }
+
+  if (argc != 3) {
+    gprint (GP_ERR, "USAGE: medimage calc (name) (output) [-mean]\n");
+    gprint (GP_ERR, "       calculate the median image for the median image set\n");
+    return FALSE;
+  }
+
+  MedImageType *median = FindMedImage (argv[1]);
+  if (!median) {
+    gprint (GP_ERR, "median image %s not found\n", argv[1]);
+    return FALSE;
+  }
+
+  if ((output = SelectBuffer (argv[2], ANYBUFFER, TRUE)) == NULL) return (FALSE);
+
+  int Ninput = median->Ninput;
+  int Nx = median->Nx;
+  int Ny = median->Ny;
+
+  float *value = NULL;
+  ALLOCATE (value, float, Ninput);
+
+  gfits_free_matrix (&output->matrix);
+  gfits_free_header (&output->header);
+  if (!CreateBuffer (output, Nx, Ny, -32, 0.0, 1.0)) return FALSE;
+
+  float *outvalue = (float *) output->matrix.buffer;
+
+  for (iy = 0; iy < Ny; iy++) {
+    for (ix = 0; ix < Nx; ix++) {
+
+      int N = 0;
+      int Npix = ix + Nx*iy;
+      for (n = 0; n < Ninput; n++) {
+	float v = median->buffers[n][Npix];
+	if (!isfinite(v)) continue;
+	value[N] = v;
+	N++;
+      }
+      if (N == 0) continue;
+
+      if (CALC_MEAN) {
+	float sum = 0.0;
+	for (n = 0; n < N; n++) {
+	  sum += value[n];
+	}
+	outvalue[Npix] = sum / (float) N;
+      } else {
+	fsort (value, N);
+	outvalue[Npix] = value[(int)(0.5*N)];
+      }
+    }
   }
 
@@ -82,39 +124,39 @@
 
 /* 
-   int medimage_save (int argc, char **argv) {
-
-   int N;
-
-   int APPEND = FALSE;
-   if ((N = get_argument (argc, argv, "-append"))) {
-   APPEND = TRUE;
-   remove_argument (N, &argc, argv);
-   }
-
-   if (argc != 3) {
-   gprint (GP_ERR, "USAGE: medimage save (name) (filename) [-append]\n");
-   return FALSE;
-   }
-
-   if (!SaveMedImage(argv[2], argv[1], APPEND)) {
-   gprint (GP_ERR, "failed to save medimage %s\n", argv[1]);
-   return (FALSE);
-   }
-   return TRUE;
-   }
-
-   int medimage_load (int argc, char **argv) {
-
-   if (argc != 3) {
-   gprint (GP_ERR, "USAGE: medimage load (name) (filename)\n");
-   return FALSE;
-   }
-
-   if (!LoadMedImage(argv[2], argv[1])) {
-   gprint (GP_ERR, "failed to load medimage %s\n", argv[1]);
-   return (FALSE);
-   }
-   return TRUE;
-   }
+int medimage_save (int argc, char **argv) {
+
+  int N;
+
+  int APPEND = FALSE;
+  if ((N = get_argument (argc, argv, "-append"))) {
+    APPEND = TRUE;
+    remove_argument (N, &argc, argv);
+  }
+
+  if (argc != 3) {
+    gprint (GP_ERR, "USAGE: medimage save (name) (filename) [-append]\n");
+    return FALSE;
+  }
+
+  if (!SaveMedImage(argv[2], argv[1], APPEND)) {
+    gprint (GP_ERR, "failed to save medimage %s\n", argv[1]);
+    return (FALSE);
+  }
+  return TRUE;
+}
+
+int medimage_load (int argc, char **argv) {
+
+  if (argc != 3) {
+    gprint (GP_ERR, "USAGE: medimage load (name) (filename)\n");
+    return FALSE;
+  }
+
+  if (!LoadMedImage(argv[2], argv[1])) {
+    gprint (GP_ERR, "failed to load medimage %s\n", argv[1]);
+    return (FALSE);
+  }
+  return TRUE;
+}
 */
 
Index: trunk/Ohana/src/opihi/cmd.data/mgaussdev.c
===================================================================
--- trunk/Ohana/src/opihi/cmd.data/mgaussdev.c	(revision 41326)
+++ 	(revision )
@@ -1,34 +1,0 @@
-# include "data.h"
-
-int mgaussdev (int argc, char **argv) {
-  
-  Buffer *buf;
-
-  if (argc != 6) goto usage;
-
-  if ((buf = SelectBuffer (argv[1], ANYBUFFER, TRUE)) == NULL) return (FALSE);
-  int Nx = atof (argv[2]);
-  int Ny = atof (argv[3]);
-
-  double mean = atof (argv[4]);
-  double sigma = atof (argv[5]);
-
-  /* I should encapsulate this in a create_default_buffer */
-  gfits_free_matrix (&buf[0].matrix);
-  gfits_free_header (&buf[0].header);
-
-  // 3D CUBE OPTION: if (!CreateBuffer3D (buf, Nx, Ny, Nz, -32, 1.0, 0.0)) return FALSE;
-  if (!CreateBuffer (buf, Nx, Ny, -32, 1.0, 0.0)) return FALSE;
-
-  ohana_gaussdev_init ();
-  
-  float *v = (float *) buf[0].matrix.buffer;
-  for (int i = 0; i < Nx*Ny; i++, v++) {
-    *v = ohana_gaussdev_rnd (mean, sigma);
-  }
-  return (TRUE);
-
- usage:
-  gprint (GP_ERR, "USAGE: mgaussdev (buff) Nx Ny mean sigma\n");
-  return (FALSE);
-}
Index: trunk/Ohana/src/opihi/cmd.data/pdf.c
===================================================================
--- trunk/Ohana/src/opihi/cmd.data/pdf.c	(revision 41326)
+++ 	(revision )
@@ -1,73 +1,0 @@
-# include "data.h"
-
-int pdf (int argc, char **argv) {
-
-  char filename[1024], pagename[1024], *name;
-  int N, kapa, scaleMode, pageMode;
-  
-  if ((N = get_argument (argc, argv, "--help"))) goto help;
-  if ((N = get_argument (argc, argv, "-h"))) goto help;
-
-  pageMode = KAPA_PS_NEWPLOT;
-
-  /* new page? */
-  /*
-  if ((N = get_argument (argc, argv, "-newpage"))) {
-    remove_argument (N, &argc, argv);
-    pageMode = KAPA_PS_NEWPAGE;
-  }
-  if ((N = get_argument (argc, argv, "-raw"))) {
-    remove_argument (N, &argc, argv);
-    pageMode = KAPA_PS_RAWPAGE;
-  }
-  */
-
-  /* scale image? */
-  scaleMode = TRUE;
-  if ((N = get_argument (argc, argv, "-noscale"))) {
-    remove_argument (N, &argc, argv);
-    scaleMode = FALSE;
-  }
-
-  /* what file? */
-  filename[0] = 0;
-  if ((N = get_argument (argc, argv, "-name"))) {
-    remove_argument (N, &argc, argv);
-    strcpy (filename, argv[N]);
-    remove_argument (N, &argc, argv);
-  }
-  /* pagename ? */
-  strcpy (pagename, "default");
-  if ((N = get_argument (argc, argv, "-pagename"))) {
-    remove_argument (N, &argc, argv);
-    strcpy (pagename, argv[N]);
-    remove_argument (N, &argc, argv);
-  }
-
-  /* which tool */
-  name = NULL;
-  if ((N = get_argument (argc, argv, "-n"))) {
-    remove_argument (N, &argc, argv);
-    name = strcreate (argv[N]);
-    remove_argument (N, &argc, argv);
-  }
-
-  if ((argc > 1) && filename[0]) goto help;
-
-  if (argc > 1) strcpy (filename, argv[1]);
-
-  // get the connection to kapa, false if none available
-  if (!GetGraphdata (NULL, &kapa, name)) return (FALSE);
-  FREE (name);
-
-  if (!filename[0]) strcpy (filename, "kapa.ps");
-  
-  /* tell Ximage/Xgraph to ps the image */
-  KapaPDF (kapa, filename, scaleMode, pageMode, pagename);
-  return (TRUE);
-
-help:
-  gprint (GP_ERR, "USAGE: ps [-name file.ps] [-g | -i] [-n device] [-raw] [-noscale] [-newpage] [-pagename (name]\n");
-  return (FALSE);
-}
-
Index: trunk/Ohana/src/opihi/cmd.data/peak.c
===================================================================
--- trunk/Ohana/src/opihi/cmd.data/peak.c	(revision 41326)
+++ trunk/Ohana/src/opihi/cmd.data/peak.c	(revision 41340)
@@ -39,5 +39,4 @@
       if (*X < start) continue;
       if (*X > end) continue;
-      if (!isfinite(*Y)) continue;
       if (*Y < ymax) continue;
       xmax = *X;
@@ -64,5 +63,4 @@
       if (*X < start) continue;
       if (*X > end) continue;
-      if (!isfinite(*Y)) continue;
       if (*Y < ymax) continue;
       xmax = *X;
Index: trunk/Ohana/src/opihi/cmd.data/print_vectors.c
===================================================================
--- trunk/Ohana/src/opihi/cmd.data/print_vectors.c	(revision 41326)
+++ trunk/Ohana/src/opihi/cmd.data/print_vectors.c	(revision 41340)
@@ -56,11 +56,7 @@
 	if (vec[i][0].type == OPIHI_FLT) {
 	  gprint (GP_LOG, "%f ", vec[i][0].elements.Flt[j]);
-	} 
-	if (vec[i][0].type == OPIHI_INT) {
+	} else {
 	  gprint (GP_LOG, OPIHI_INT_FMT" ", vec[i][0].elements.Int[j]);
-	} 
-	if (vec[i][0].type == OPIHI_STR) {
-	  gprint (GP_LOG, "%s ", vec[i][0].elements.Str[j]);
-	} 
+	}
       }
     }
Index: trunk/Ohana/src/opihi/cmd.data/queue2book.c
===================================================================
--- trunk/Ohana/src/opihi/cmd.data/queue2book.c	(revision 41326)
+++ 	(revision )
@@ -1,248 +1,0 @@
-# include "pantasks.h"
-
-# define FREEKEYS \
-  if (keys) { for (i = 0; i < Nkeys; i++) { free (keys[i]); } free (keys); } \
-  for (i = 0; i < setWordN; i++) { free (setWordList[i]); free (setWordValue[i]); } \
-  free (setWordValue); free (setWordList);
-
-// convert the named queue with ipptool metadata output into book format
-int queue2book (int argc, char **argv) {
-
-  int i, N, onPage, found, Unique, Nkeys, NKEYS;
-  char *line, *tmpword, *tmpvalue;
-  char pagename[512]; // XXX this should be made dynamic, though it is an unlikey problem
-  char *bookName, **keys, *p, *q;
-  char **setWordList;
-  char **setWordValue;
-  int setWordN, setWordNalloc;
-
-  Page *page = NULL;
-  Book *book = NULL;
-  Queue *queue = NULL;
-
-  /* supply additional constant words */
-  setWordN = 0;
-  setWordNalloc = 10;
-  ALLOCATE (setWordList, char *, setWordNalloc);
-  ALLOCATE (setWordValue, char *, setWordNalloc);
-  while ((N = get_argument (argc, argv, "-setword"))) {
-    remove_argument (N, &argc, argv);
-    setWordList[setWordN] = strcreate (argv[N]);
-    remove_argument (N, &argc, argv);
-    setWordValue[setWordN] = strcreate (argv[N]);
-    remove_argument (N, &argc, argv);
-    setWordN ++;
-    if (setWordN >= setWordNalloc) {
-      setWordNalloc += 10;
-      REALLOCATE (setWordList, char *, setWordNalloc);
-      REALLOCATE (setWordValue, char *, setWordNalloc);
-    }      
-  }
-
-  Unique = FALSE;
-  if ((N = get_argument (argc, argv, "-uniq"))) {
-    remove_argument (N, &argc, argv);
-    Unique = TRUE;
-  }
-
-  Nkeys = 0;
-  keys = NULL;
-  if ((N = get_argument (argc, argv, "-key"))) {
-    remove_argument (N, &argc, argv);
-
-    /* parse the key (word:word:word) into constituents */
-    NKEYS = 10;
-    ALLOCATE (keys, char *, NKEYS);
-    
-    p = q = argv[N];
-    while (q != NULL) {
-      q = strchr (p, ':');
-      keys[Nkeys] = (q == NULL) ? strcreate (p) : strncreate (p, q - p);
-      p = q + 1;
-      Nkeys ++;
-      CHECK_REALLOCATE (keys, char *, NKEYS, Nkeys, 10);
-    }
-    remove_argument (N, &argc, argv);
-  }
-
-  if (argc != 3) {
-    gprint (GP_ERR, "USAGE: queue2book (queue) (book) [-uniq] [-key key[:key..]]\n");
-    gprint (GP_ERR, "       converts the named queue  with ipptool metadata output into book format\n");
-    FREEKEYS;
-    return (TRUE);
-  }
-
-  queue = FindQueue (argv[1]);
-  if (queue == NULL) {
-    gprint (GP_ERR, "queue %s not found\n", argv[1]);
-    FREEKEYS;
-    return (TRUE);
-  }
-    
-  book = CreateBook (argv[2]);
-
-  /* the first non-whitespace line of the queue should contain:
-     BookName MULTI
-  */
-
-  /* scan for first non-emtpy line */
-  while (TRUE) {
-    line = PopQueue (queue);
-    if (!line) {
-      FREEKEYS;
-      return (TRUE); // no output in queue - not an error?
-    }
-    stripwhite (line);
-    if (line[0] == '#') {
-      free (line);
-      continue;
-    }
-    if (*line) break;
-    free (line);
-  }
-  bookName = thisword (line);
-  tmpword = nextword (line);
-
-  if (!tmpword || strcmp(tmpword, "MULTI")) {
-    gprint (GP_ERR, "ERROR: missing metadata output name on first line\n");
-    free (bookName);
-    free (line);
-    FREEKEYS;
-    return (TRUE);
-  }
-  free (line);
-  
-  onPage = FALSE;
-  while (TRUE) {
-    line = PopQueue (queue);
-    if (!line) {
-      free (bookName);
-      if (onPage) {
-	gprint (GP_ERR, "ERROR: unterminated metadata\n");
-	FREEKEYS;
-	return (TRUE);
-      }
-      FREEKEYS;
-      return (TRUE);
-    }
-    stripwhite (line);
-    if (!*line) {
-      free (line);
-      continue;
-    }
-    if (line[0] == '#') {
-      free (line);
-      continue;
-    }
-    
-    tmpword = thisword (line);
-    if (tmpword == NULL) abort(); // should not happen if line exists
-
-    if (!onPage) {
-      if (strcmp(tmpword, bookName)) {
-	gprint (GP_ERR, "ERROR: unexpected metadata name %s\n", tmpword);
-	free (line);
-	free (tmpword);
-	free (bookName);
-	FREEKEYS;
-	return (TRUE);
-      }
-      free (tmpword);
-      tmpword = thisword (nextword (line));
-      if (strcmp(tmpword, "METADATA")) {
-	gprint (GP_ERR, "ERROR: missing METADATA tag\n");
-	free (line);
-	free (tmpword);
-	free (bookName);
-	FREEKEYS;
-	return TRUE;
-      }
-      onPage = TRUE;
-      // we don't know the page name until we load its data?
-      sprintf (pagename, "page.%03d", book[0].Npages);
-      page = CreatePage (book, pagename);
-      free (line);
-      free (tmpword);
-      continue;
-    } 
-
-    /* close out the page */
-    if (!strcmp(tmpword, "END")) {
-      // XXX set the page name based on the contents
-      free (tmpword);
-      free (line);
-
-      if (keys) {
-	memset (pagename, 0, 512);
-	for (i = 0; i < Nkeys; i++) {
-	  tmpword = BookGetWord (page, keys[i]);
-	  if (tmpword == NULL) {
-	    gprint (GP_ERR, "ERROR: missing key %s for ID\n", keys[i]);
-	    FREEKEYS;
-	    return (TRUE);
-	  }
-	  if (i > 0) strcat (pagename, ":");
-	  strcat (pagename, tmpword);
-	}
-	free (page[0].name);
-	page[0].name = strcreate (pagename);
-      }
-
-      // add the fixed words to the page
-      for (i = 0; i < setWordN; i++) {
-	BookSetWord (page, setWordList[i], setWordValue[i]);
-      }
-
-      if (Unique) {
-	/* search for an existing page with this name
-	   delete this one if one is found */
-	/* XXX don't attach this page to the book until this step is passed */	
-
-	found = FALSE;
-	for (i = 0; !found && (i < book[0].Npages); i++) {
-	  if (book[0].pages[i] == page) continue;
-	  if (!strcmp (book[0].pages[i][0].name, page[0].name)) {
-	    found = TRUE;
-	  }
-	}
-	if (found) {
-	  DeletePage (book, page);
-	}
-      }
-
-      onPage = FALSE;
-      continue;
-    }
-
-    tmpvalue = thisword (nextword(nextword(line)));
-    if (tmpvalue == NULL) {
-      gprint (GP_ERR, "ERROR: missing value for %s\n", tmpword);
-      free (tmpword);
-      free (line);
-      free (bookName);
-      FREEKEYS;
-      return (TRUE);
-    }
-    BookSetWord (page, tmpword, tmpvalue);
-    free (tmpword);
-    free (tmpvalue);
-    free (line);
-  }    
-  FREEKEYS;
-  return (TRUE);
-}
-
-/* scan through the queue lines.  these should look like:  
-
-bookName METADATA
-key type value
-key type value
-...
-END
-
-bookName METADATA
-key type value
-key type value
-...
-END
-*/
Index: trunk/Ohana/src/opihi/cmd.data/read_vectors.c
===================================================================
--- trunk/Ohana/src/opihi/cmd.data/read_vectors.c	(revision 41326)
+++ trunk/Ohana/src/opihi/cmd.data/read_vectors.c	(revision 41340)
@@ -35,5 +35,5 @@
 
 // vector types
-enum {COLTYPE_NONE, COLTYPE_FLT, COLTYPE_INT, COLTYPE_TIME, COLTYPE_DATE, COLTYPE_CHAR, COLTYPE_STR, COLTYPE_HMS};
+enum {COLTYPE_NONE, COLTYPE_FLT, COLTYPE_INT, COLTYPE_TIME, COLTYPE_CHAR};
 
 static int      Nvec     = 0;
@@ -91,11 +91,8 @@
     gprint (GP_ERR, "     -skip N : skip N lines before reading\n");
     gprint (GP_ERR, "     column names may include a type: name:type\n");
-    gprint (GP_ERR, "       type is int, float, char, str, time, date, hms\n");
+    gprint (GP_ERR, "       type is int, float, char, time\n");
     gprint (GP_ERR, "       for char, values are placed into a list $name:0 - $name:n\n");
-    gprint (GP_ERR, "       for str, values are placed into a string-typed vector\n");
-    gprint (GP_ERR, "       for hms, values are sexigesimal values HH:MM:SS (good for degrees as well)\n");
-    gprint (GP_ERR, "       for date, values are human-readable date strings YYYY/MM/DD\n");
     gprint (GP_ERR, "       for time, values are human-readable date/time strings YYYY/MM/DD,hh:mm:ss\n");
-    gprint (GP_ERR, "         date & time values are stored as a float using the TIMEFORMAT, TIMEREF values for the conversion\n");
+    gprint (GP_ERR, "       the resulting vector is a float based on the TIMEFORMAT, TIMEREF values\n");
 
     gprint (GP_ERR, "     -fits options:\n");
@@ -155,8 +152,5 @@
       if (!strcasecmp(ptr, "int"))   { coltype[i] = COLTYPE_INT; }
       if (!strcasecmp(ptr, "char"))  { coltype[i] = COLTYPE_CHAR; }
-      if (!strcasecmp(ptr, "str"))   { coltype[i] = COLTYPE_STR; }
-      if (!strcasecmp(ptr, "date"))  { coltype[i] = COLTYPE_DATE; }
       if (!strcasecmp(ptr, "time"))  { coltype[i] = COLTYPE_TIME; }
-      if (!strcasecmp(ptr, "hms"))   { coltype[i] = COLTYPE_HMS; }
       if (!coltype[i]) goto bad_colname;
     }
@@ -216,11 +210,7 @@
 	break;
       case COLTYPE_FLT:
-      case COLTYPE_HMS:
       case COLTYPE_TIME:
-      case COLTYPE_DATE:
+	// note that COLTYPE_TIME is a type of float
 	ResetVector (vec[i], OPIHI_FLT, NELEM);
-	break;
-      case COLTYPE_STR:
-	ResetVector (vec[i], OPIHI_STR, NELEM);
 	break;
       case COLTYPE_CHAR:
@@ -297,5 +287,4 @@
 	time_t tvalue;
 	int readStatus = FALSE;
-	int dataStatus = FALSE;
 	// need to make the if cases for coltype[i]
 	switch (coltype[i]) {
@@ -322,20 +311,4 @@
 	      break;
 	    }
-	  case COLTYPE_STR:
-	    {
-	      // I need to get an isolated word in 'value' with the string value of this field 
-	      char *ptr = IsCSV ? ptrparse_csv (col[i], c0) : ptrparse (col[i], c0);
-	      char *value = NULL;
-	      if (IsCSV) {
-		char *end = parse_nextword_csv (ptr);
-		if (end) {
-		  value = end ? strncreate (ptr, end - ptr) : strcreate (ptr);
-		}
-	      } else {
-		value = thisword(ptr);
-	      }
-	      vec[i][0].elements.Str[Nelem] = value; // needs to be freed later.
-	      break;
-	    }
 	  case COLTYPE_FLT:
 	    readStatus = IsCSV ? dparse_csv (&dvalue, col[i], c0) : dparse (&dvalue, col[i], c0);
@@ -347,29 +320,4 @@
 	    vec[i][0].elements.Flt[Nelem] = readStatus ? dvalue : NAN;
 	    break;
-	  case COLTYPE_DATE: {
-	    char *string = NULL;
-	    if (IsCSV) {
-	      char *ptr = ptrparse_csv (col[i], c0);
-	      string = strcreate (ptr); // create separate string (NULL-safe)
-	      ptr = (string == NULL) ? NULL : strchr (string, ',');
-	      if (ptr != NULL) *ptr = 0; // place an EOL here so parsing does not go past the comma
-	    } else {
-	      char *ptr = ptrparse (col[i], c0); // NULL-safe
-	      string = getword (ptr); // NULL-safe
-	    }	      
-	    tvalue = ohana_date_to_sec (string); // NULL-safe (returns 0)
-	    dvalue = TimeValue (tvalue, TimeReference, TimeFormat);
-	    vec[i][0].elements.Flt[Nelem] = string ? dvalue : NAN;
-	    FREE (string);
-	    break;
-	  }
-	  case COLTYPE_HMS: {
-	    char *ptr = IsCSV ? ptrparse_csv (col[i], c0) : ptrparse (col[i], c0);
-	    char *string = strcreate (ptr); // make a copy so we can munge it in ohana_dms_to_ddd
-	    dataStatus = ohana_dms_to_ddd (&dvalue, string);
-	    vec[i][0].elements.Flt[Nelem] = ((string != NULL) && dataStatus) ? dvalue : NAN;
-	    FREE (string);
-	    break;
-	  }
 	}
 	if (!readStatus && VERBOSE) {
@@ -397,11 +345,6 @@
 	      break;
 	    case COLTYPE_FLT:
-	    case COLTYPE_HMS:
 	    case COLTYPE_TIME:
-	    case COLTYPE_DATE:
 	      ResetVector (vec[i], OPIHI_FLT, NELEM);
-	      break;
-	    case COLTYPE_STR:
-	      ResetVector (vec[i], OPIHI_STR, NELEM);
 	      break;
 	    case COLTYPE_CHAR:
@@ -423,11 +366,6 @@
 	break;
       case COLTYPE_FLT:
-      case COLTYPE_HMS:
       case COLTYPE_TIME:
-      case COLTYPE_DATE:
 	ResetVector (vec[i], OPIHI_FLT, Nelem);
-	break;
-      case COLTYPE_STR:
-	ResetVector (vec[i], OPIHI_STR, Nelem);
 	break;
       case COLTYPE_CHAR:
@@ -531,10 +469,6 @@
   }
 
-  // by default, we now store a string-type field as a string-type vector.
-
-  // if CharAsList is selected (and My < 10000), char fields will be saved as $NAME:0 - $NAME:m for m rows
-
-  // if CharAsVectors is selected, char fields will be saved as vectors NAME:0 -- NAME:n for n characters
-
+  // if CharAsVectors, char fields will be saved as vectors NAME:0 -- NAME:n for n characters
+  // else char fields will be saved as $NAME:0 - $NAME:m for m rows
   // if (Ny > 10000), force CharAsVectors
   int CharAsVectors = FALSE;
@@ -542,9 +476,4 @@
     remove_argument (N, &argc, argv);
     CharAsVectors = TRUE;
-  }
-  int CharAsList = FALSE;
-  if ((N = get_argument (argc, argv, "-char-list"))) {
-    remove_argument (N, &argc, argv);
-    CharAsList = TRUE;
   }
 
@@ -722,46 +651,26 @@
     if (!FITS_TRANSPOSE) {
       // read string column into a list rather than a vector
-      if (!strcmp (type, "char")) {
-	// save char-type field as a List:
-	if (CharAsList && (Ny < 3000)) {
-	  char *fieldName = argv[i];
-	  char *Ptr = data;
-	  char varname[1024];  // used as a buffer for the names of string fields
-	  for (j = 0; j < Ny; j++) {
-	    set_list_varname (varname, fieldName, j, FALSE);
-	    char *value = strncreate (&Ptr[j*Nval], Nval);
-	    // replace instances of $ with _
-	    char *p = strchr (value, '$');
-	    while (p) { 
-	      *p = '_';
-	      p = strchr (p, '$');
-	    }
-	    set_str_variable (varname, value);
-	    free (value);
+      if (!strcmp (type, "char") && !CharAsVectors && (Ny < 3000)) {
+	char *fieldName = argv[i];
+	char *Ptr = data;
+	char varname[1024];  // used as a buffer for the names of string fields
+	for (j = 0; j < Ny; j++) {
+	  set_list_varname (varname, fieldName, j, FALSE);
+	  char *value = strncreate (&Ptr[j*Nval], Nval);
+	  // replace instances of $ with _
+	  char *p = strchr (value, '$');
+	  while (p) { 
+	    *p = '_';
+	    p = strchr (p, '$');
 	  }
-	  sprintf (varname, "%s:n", fieldName);
-	  set_int_variable (varname, Ny);
-	  continue;
+	  set_str_variable (varname, value);
+	  free (value);
 	}
-	// save char-type field as a string-type vector:
-	if (!CharAsVectors) {
-	  Vector *myVector = NULL;
-	  sprintf (name, "%s", argv[i]);
-	  if ((myVector = SelectVector (name, ANYVECTOR, TRUE)) == NULL) ESCAPE ("bad vector name\n");
-	  ResetVector (myVector, OPIHI_STR, Ny);
-
-	  char *Ptr = data;
-	  for (j = 0; j < Ny; j++) {
-	    myVector[0].elements.Str[j] = strncreate (&Ptr[j*Nval], Nval);
-	    // replace instances of $ with _
-	    char *p = strchr (myVector[0].elements.Str[j], '$');
-	    while (p) { *p = '_'; p = strchr (p, '$'); }
-	  }
-	  continue;
-	}
+	sprintf (varname, "%s:n", fieldName);
+	set_int_variable (varname, Ny);
+	continue;
       }
 
       // define the multifield vector names (Nval vectors x Ny elements)
-      // CharAsVectors is handled below automatically
       ALLOCATE (vec, Vector *, Nval);
       for (j = 0; j < Nval; j++) {
Index: trunk/Ohana/src/opihi/cmd.data/roll.c
===================================================================
--- trunk/Ohana/src/opihi/cmd.data/roll.c	(revision 41326)
+++ trunk/Ohana/src/opihi/cmd.data/roll.c	(revision 41340)
@@ -3,9 +3,7 @@
 int roll (int argc, char **argv) {
   
+  int Nbytes, Nextra;
+  int dX, dx, dy, nx, ny;
   Buffer *buf;
-
-  // this function is probably not needed
-  gprint (GP_ERR, "ERROR: use 'shift' instead of 'roll'\n");
-  return (FALSE);
 
   if (argc != 4) {
@@ -16,71 +14,32 @@
   if ((buf = SelectBuffer (argv[1], OLDBUFFER, TRUE)) == NULL) return (FALSE);
 
-  int dx = atoi (argv[2]);
-  int dy = atoi (argv[3]);
-
-  /* if (dx,dy < 0), we are moving the start position backwards,
-     if (dx,dy > 0), we are moving the start position forward */
-  
-  int Nx = buf[0].matrix.Naxis[0];
-  int Ny = buf[0].matrix.Naxis[1];
-
-  if (dy == 0) {
-    // moves in just dx can be done row-by-row
-
-    int dX = abs(dx);
-    int Nbytes = (Nx * Ny - dX) * sizeof (float);
-    int Nextra = dX * sizeof (float);
-
-    if (dx < 0) {
-      memmove (buf[0].matrix.buffer, &buf[0].matrix.buffer[dX*sizeof(float)], Nbytes);
-      memset (&buf[0].matrix.buffer[Nbytes], 0, Nextra);
-    } else {
-      memmove (&buf[0].matrix.buffer[dX*sizeof(float)], buf[0].matrix.buffer, Nbytes);
-      memset (buf[0].matrix.buffer, 0, Nextra);
-    }
-
-    return TRUE;
+  dx = atof (argv[2]);
+  dy = atof (argv[3]);
+  if (dy != 0) {
+    gprint (GP_ERR, "only x rolls implemented for now\n");
   }
 
-  if (dx == 0) {
-    // moves in just dy can be done row-by-row
+  /* if (dx < 0), we are moving the start position back by dx pixels,
+     if (dx > 0), we are moving the start position forward by dx pixels */
+  
+  nx = buf[0].matrix.Naxis[0];
+  ny = buf[0].matrix.Naxis[1];
 
-    ALLOCATE_PTR (output, float, Nx*Ny);
+  dX = abs(dx);
+  Nbytes = nx * ny * sizeof (float);
+  Nextra = (nx * ny + dX) * sizeof (float);
 
-    float *input = (float *) buf[0].matrix.buffer;
+  REALLOCATE (buf[0].matrix.buffer, char, Nextra);
 
-    for (int iy = 0; iy < Ny; iy++) {
-      if (iy + dy < 0) continue;
-      if (iy + dy >= Ny) continue;
-      memcpy (&output[iy*Nx], &input[(iy + dy)*Nx], Nx);
-    }
-    if (dy > 0) {
-      memset (output, 0, dy*Nx*sizeof(float));
-    } else {
-      int Nbytes = Nx * (Ny - abs(dy)) * sizeof (float);
-      int Nextra = abs(dy) * Nx * sizeof (float);
-      memset (&output[Nbytes], 0, Nextra);
-    }
-    free (buf[0].matrix.buffer);
-    buf[0].matrix.buffer = (char *) output;
-    return TRUE;
+  if (dx < 0) {
+    memmove (buf[0].matrix.buffer, &buf[0].matrix.buffer[dX*sizeof(float)], Nbytes);
+  } else {
+    memmove (&buf[0].matrix.buffer[dX*sizeof(float)], buf[0].matrix.buffer, Nbytes);
   }
 
-  ALLOCATE_PTR (output, float, Nx*Ny);
-  float *input = (float *) buf[0].matrix.buffer;
+  REALLOCATE (buf[0].matrix.buffer, char, Nbytes);
 
-  for (int iy = 0; iy < Ny; iy++) {
-    if (iy + dy < 0) continue;
-    if (iy + dy >= Ny) continue;
-    for (int ix = 0; ix < Nx; ix++) {
-      if (ix + dx < 0) continue;
-      if (ix + dx >= Nx) continue;
-      output[ix + iy*Nx] = input[(ix + dx) + (iy + dy)*Nx];
-    }
-  }
-  free (buf[0].matrix.buffer);
-  buf[0].matrix.buffer = (char *) output;
-  return TRUE;
+  return (TRUE);
+
 }
 
-
Index: trunk/Ohana/src/opihi/cmd.data/rotate.c
===================================================================
--- trunk/Ohana/src/opihi/cmd.data/rotate.c	(revision 41326)
+++ trunk/Ohana/src/opihi/cmd.data/rotate.c	(revision 41340)
@@ -3,19 +3,19 @@
 int rotate (int argc, char **argv) {
   
-  int i, j, NX, NY;
+  int i, j, NX, NY, X, Y, Lx, Ly, N;
   float *in_buff, *out_buff, *c;
-  double Xo, Yo, x, y, X1, Y1;
+  double angle, CosAngle, SinAngle, Xo, Yo, dX, dY, fx, fy, x, y, X1, Y1;
   double pc11, pc12, pc21, pc22, PC11, PC12, PC21, PC22;
   Buffer *buf;
 
-//  Xo = 0;
-//  Yo = 0;
-//  if ((N = get_argument (argc, argv, "-center"))) {
-//    remove_argument (N, &argc, argv);
-//    Xo  = atof(argv[N]);
-//    remove_argument (N, &argc, argv);
-//    Yo  = atof(argv[N]);
-//    remove_argument (N, &argc, argv);
-//  }
+  Xo = 0;
+  Yo = 0;
+  if ((N = get_argument (argc, argv, "-center"))) {
+    remove_argument (N, &argc, argv);
+    Xo  = atof(argv[N]);
+    remove_argument (N, &argc, argv);
+    Yo  = atof(argv[N]);
+    remove_argument (N, &argc, argv);
+  }
 
   if (argc != 3) {
@@ -221,26 +221,30 @@
   }
 
-  double angle = atof (argv[2]);
-  double CosAngle = cos (angle*RAD_DEG);
-  double SinAngle = sin (angle*RAD_DEG);
+  angle = atof (argv[2]);
+  CosAngle = cos (angle*RAD_DEG);
+  SinAngle = sin (angle*RAD_DEG);
   
   gprint (GP_ERR, "rotating: %f %f %f\n", angle, CosAngle, SinAngle);
 
-  // we are rotating about the center pixel, (NX/2, NY/2),
-  // but we are then putting the result in a new image
-  // of size (Lx,Ly).
-
-  // (x,y) = (i - Nx/2),(j - Ny/2)
-  // (x',y') = R(theta) (x,y)
-  // (I,J) = (x' + Lx/2),(y' + Ly/2)
-
-  int Lx = NX*fabs(CosAngle) + NY*fabs(SinAngle);
-  int Ly = NX*fabs(SinAngle) + NY*fabs(CosAngle);
+  Lx = NX*fabs(CosAngle) + NY*fabs(SinAngle);
+  Ly = NX*fabs(SinAngle) + NY*fabs(CosAngle);
+  dX = MAX(0,NY*SinAngle);
+  dY = MAX(0,-NX*SinAngle);
+  /*
+  gprint (GP_ERR, "%f %f  -->  ", Xo, Yo);
+  X1 = Xo*CosAngle - Yo*SinAngle + dX;
+  Y1 =  Xo*SinAngle + Yo*CosAngle + dY;
+  gprint (GP_ERR, "%f %f\n", X1, Y1);
+  */
 
   /* fix reference pixel */
   gfits_scan (&buf[0].header, "CRPIX1", "%lf", 1, &Xo);
   gfits_scan (&buf[0].header, "CRPIX2", "%lf", 1, &Yo);
-  X1 = (Xo - NX/2)*CosAngle + (Yo - NY/2)*SinAngle + Lx/2;
-  Y1 = (NX/2 - Xo)*SinAngle + (Yo - NY/2)*CosAngle + Ly/2;
+  /*
+  X1 = (Xo - dX)*CosAngle - (Yo - dY)*SinAngle;
+  Y1 = (dX - Xo)*SinAngle + (Yo - dY)*CosAngle;
+  */
+  X1 = Xo*CosAngle - Yo*SinAngle + dX;
+  Y1 =  Xo*SinAngle + Yo*CosAngle + dY;
   gfits_modify (&buf[0].header, "CRPIX1", "%lf", 1, X1);
   gfits_modify (&buf[0].header, "CRPIX2", "%lf", 1, Y1);
@@ -251,8 +255,8 @@
   gfits_scan (&buf[0].header, "PC002001", "%lf", 1, &pc21);
   gfits_scan (&buf[0].header, "PC002002", "%lf", 1, &pc22);
-  PC11 = pc11*CosAngle + pc21*SinAngle;
-  PC12 = pc12*CosAngle + pc22*SinAngle;
-  PC21 = pc21*CosAngle - pc11*SinAngle;
-  PC22 = pc22*CosAngle - pc12*SinAngle;
+  PC11 = pc11*CosAngle - pc21*SinAngle;
+  PC12 = pc12*CosAngle - pc22*SinAngle;
+  PC21 = pc21*CosAngle + pc11*SinAngle;
+  PC22 = pc22*CosAngle + pc12*SinAngle;
   gfits_modify (&buf[0].header, "PC001001", "%le", 1, PC11);
   gfits_modify (&buf[0].header, "PC001002", "%le", 1, PC12);
@@ -266,33 +270,22 @@
   gfits_create_matrix (&buf[0].header, &buf[0].matrix);
   gfits_print_alt (&buf[0].header, "HISTORY", "%S", 1, "WARNING: rotated image!");
-
   out_buff = (float *)buf[0].matrix.buffer;
-
   for (j = 0; j < Ly; j++) {
     for (i = 0; i < Lx; i++, out_buff++) {
 
-      float xo = (i - Lx/2);
-      float yo = (j - Ly/2);
-
-      x =  xo*CosAngle + yo*SinAngle;
-      y = -xo*SinAngle + yo*CosAngle;
-
-      int I = x + NX/2;
-      int J = y + NY/2;
-
-      if (I < 0) continue;
-      if (I >= NX - 1) continue;
-      if (J < 0) continue;
-      if (J >= NY - 1) continue;
-
-      c = &in_buff[I + NX*J];
-
-      int X = (int) x;
-      int Y = (int) y;
-      double fx = x - X;
-      double fy = y - Y;
-
+      x = (i - dX)*CosAngle + (j - dY)*SinAngle;
+      y = (dX - i)*SinAngle + (j - dY)*CosAngle;
+      X = (int) x;
+      Y = (int) y;
+
+      if (X < 0) continue;
+      if (X >= NX - 1) continue;
+      if (Y < 0) continue;
+      if (Y >= NY - 1) continue;
+
+      c = &in_buff[X + NX*Y];
+      fx = x - X;
+      fy = y - Y;
       *out_buff = (c[0]*(1-fx) + c[1]*fx)*(1-fy) + (c[NX+1]*fx + c[NX]*(1-fx))*fy;
-//    *out_buff = c[0];
     }
   }
Index: trunk/Ohana/src/opihi/cmd.data/spline.c
===================================================================
--- trunk/Ohana/src/opihi/cmd.data/spline.c	(revision 41326)
+++ trunk/Ohana/src/opihi/cmd.data/spline.c	(revision 41340)
@@ -7,5 +7,4 @@
 int spline_load (int argc, char **argv);
 int spline_save (int argc, char **argv);
-int spline_print (int argc, char **argv);
 int spline_delete (int argc, char **argv);
 int spline_rename (int argc, char **argv);
@@ -19,5 +18,4 @@
   {1, "load",       spline_load,       "write a spline to a FITS file"},
   {1, "save",       spline_save,       "read a spline from a FITS file"},
-  {1, "print",      spline_print,      "print a spline to stdout"},
   {1, "delete",     spline_delete,     "delete a spline"},
   {1, "rename",     spline_rename,     "rename a spline"},
@@ -37,5 +35,4 @@
   gprint (GP_ERR, "    spline load   (spline) (filename)            : load a spline from a FITS file\n");
   gprint (GP_ERR, "    spline save   (spline) (filename) [-append]  : save a spline in FITS format\n");
-  gprint (GP_ERR, "    spline print  (spline)                       : print a spline to stdout\n");
 
   return FALSE;
Index: trunk/Ohana/src/opihi/cmd.data/spline_commands.c
===================================================================
--- trunk/Ohana/src/opihi/cmd.data/spline_commands.c	(revision 41326)
+++ trunk/Ohana/src/opihi/cmd.data/spline_commands.c	(revision 41340)
@@ -28,9 +28,4 @@
   if (xvec->Nelements != yvec->Nelements) {
     gprint (GP_ERR, "x and y vectors must be the same length\n");
-    return FALSE;
-  }
-
-  if (xvec->Nelements < 3) {
-    gprint (GP_ERR, "cannot make a spline with fewer than 3 knots\n");
     return FALSE;
   }
@@ -98,26 +93,4 @@
 }
 
-int spline_print (int argc, char **argv) {
-
-  int i;
-
-  if (argc != 2) {
-    gprint (GP_ERR, "USAGE: spline print (name)\n");
-    return FALSE;
-  }
-
-  Spline *myspline = FindSpline (argv[1]);
-  if (!myspline) {
-    gprint (GP_ERR, "spline %s not found\n", argv[1]);
-    return (FALSE);
-  }
-
-  for (i = 0; i < myspline->Nknots; i++) {
-    gprint (GP_LOG, "%lf : %lf : %lf\n", myspline->xk[i], myspline->yk[i], myspline->y2[i]);
-  }    
-
-  return TRUE;
-}
-
 int spline_load (int argc, char **argv) {
 
@@ -136,11 +109,6 @@
 int spline_delete (int argc, char **argv) {
 
-  int N, status;
-
-  int QUIET = FALSE;
-  if ((N = get_argument (argc, argv, "-q"))) {
-    QUIET = TRUE;
-    remove_argument (N, &argc, argv);
-  }
+  int status;
+  Spline *spline;
 
   if (argc != 2) {
@@ -149,7 +117,6 @@
   }
 
-  Spline *spline = FindSpline (argv[1]);
+  spline = FindSpline (argv[1]);
   if (spline == NULL) {
-    if (QUIET) return TRUE;
     gprint (GP_ERR, "spline %s not found\n", argv[1]);
     return FALSE;
@@ -163,4 +130,6 @@
 int spline_rename (int argc, char **argv) {
 
+  Spline *spline;
+
   if (argc != 3) {
     gprint (GP_ERR, "USAGE: spline rename (spline) (newname)\n");
@@ -168,13 +137,8 @@
   }
 
-  Spline *spline = FindSpline (argv[1]);
+  spline = FindSpline (argv[1]);
   if (spline == NULL) {
     gprint (GP_ERR, "spline %s not found\n", argv[1]);
     return FALSE;
-  }
-
-  Spline *newname = FindSpline (argv[2]);
-  if (newname != NULL) {
-    DeleteSpline (newname);
   }
 
@@ -183,2 +147,24 @@
   return TRUE;
 }
+
+/* 
+int spline_listspline (int argc, char **argv) {
+
+  Spline *spline;
+
+  if (argc != 2) {
+    gprint (GP_ERR, "USAGE: spline listspline (spline)\n");
+    return FALSE;
+  }
+
+  spline = FindSpline (argv[1]);
+  if (spline == NULL) {
+    gprint (GP_ERR, "spline %s not found\n", argv[1]);
+    return FALSE;
+  }
+
+  ListPages (spline);
+  return TRUE;
+}
+*/
+
Index: trunk/Ohana/src/opihi/cmd.data/test/cut.sh
===================================================================
--- trunk/Ohana/src/opihi/cmd.data/test/cut.sh	(revision 41326)
+++ trunk/Ohana/src/opihi/cmd.data/test/cut.sh	(revision 41340)
@@ -4,46 +4,4 @@
  memtest1
 end
-
-macro test2
-
-  mgaussdev z 50 100 0.0 1.0
-
-  cut z x y_sum    x 0 0 z[][0] z[0][]
-  cut z x y_median x 0 0 z[][0] z[0][] -median
-  cut z x y_mean   x 0 0 z[][0] z[0][] -mean
-  cut z x y_inner  x 0 0 z[][0] z[0][] -inner
-  
-end
-
-macro checkrange
-  if ($0 != 2)
-    echo "USAGE: checkrange (Npts)"
-    break
-  end
-
-  $Npts = $1
-  if ($Npts % 2)
-    $Ncenter = int($Npts / 2)
-    $Nquarter = int(0.25 * $Npts)
-    $Ns = $Ncenter - $Nquarter
-    $Ne = $Ncenter + $Nquarter
-  else
-    $Ncenter = int($Npts / 2) - 1
-    $Nquarter = int(0.25 * $Npts)
-    $Ns = $Ncenter - $Nquarter
-    $Ne = $Ncenter + $Nquarter + 1
-  end
-  if ($Ns < 0)
-    echo "error: Ns < 0: $Ns $Ncenter $Nquarter"
-  end
-  if ($Ne >= $Npts)
-    echo "error: Ne >= Npts: $Ne $Ncenter $Nquarter"
-  end
-  echo "$Npts : $Ncenter : $Nquarter : $Ns $Ne"
-  for i 0 $Npts
-    echo $i {($i >= $Ns) && ($i <= $Ne)}
-  end
-end
-
 
 # Test if cut works
@@ -79,42 +37,2 @@
  end
 end
-
-macro memtest1
-
- $i = 0
- mcreate tim 100 100
- cut tim xdir imx X 40 4 60 6
- # do one to set up memory that should stay used
-
- memory check
- for i 0 100
-   cut tim xdir imx X 40 4 60 6
- end
- memory check
-   
- for i 0 100
-   cut tim xdir imx y 40 4 60 6
- end
- memory check
-   
- for i 0 100
-   cut -median tim xdir imx X 40 4 60 6
- end
- memory check
-   
- for i 0 100
-   cut -median tim xdir imx y 40 4 60 6
- end
- memory check
-   
- for i 0 100
-   cut -mean tim xdir imx X 40 4 60 6
- end
- memory check
-   
- for i 0 100
-   cut -mean tim xdir imx y 40 4 60 6
- end
- memory check
-   
-end
Index: trunk/Ohana/src/opihi/cmd.data/test/delete.sh
===================================================================
--- trunk/Ohana/src/opihi/cmd.data/test/delete.sh	(revision 41326)
+++ trunk/Ohana/src/opihi/cmd.data/test/delete.sh	(revision 41340)
@@ -49,13 +49,2 @@
 
 end
-
-# Test delete
-macro test2
-
- $PASS = 1
-
- for i 0 1000
-   create v 0 200
-   delete v
- end
-end
Index: trunk/Ohana/src/opihi/cmd.data/test/headtest.sh
===================================================================
--- trunk/Ohana/src/opihi/cmd.data/test/headtest.sh	(revision 41326)
+++ 	(revision )
@@ -1,15 +1,0 @@
-
-macro init.test
- create x 0 10
- set y  = x^2
- mcreate blank 0 0 
- keyword blank TE0 -wd 56
- keyword blank TE1 -w "TEST LINE"
- keyword blank TE2 -wf 5.12342341
- keyword blank TE3 -wb T
- keyword blank TE4 -wc "not sure what do say"
- keyword blank TE4 -wf 4.5
- keyword blank TE5 -ws "this is a long comment"
- keyword blank TE2 -wc "this is a short comment"
- write -fits DATA test2.fits x y -header blank
-end
Index: trunk/Ohana/src/opihi/cmd.data/test/medimage.sh
===================================================================
--- trunk/Ohana/src/opihi/cmd.data/test/medimage.sh	(revision 41326)
+++ trunk/Ohana/src/opihi/cmd.data/test/medimage.sh	(revision 41340)
@@ -1,540 +1,11 @@
 
-macro test.mean
-
- $Nsample = 16
- medimage delete -q t1
- for i 0 $Nsample
-  mgaussdev t 50 50 0.0 1.0
-  medimage add t1 t
-  imhist -q t x y -range -10 10 -delta 0.1
-
-  $C0 = 0
-  $C1 = 1.5
-  $C2 = 400
-  $C3 = 0
-  vgauss -q x y con yf
-  # echo $C1
+macro go
+ mcreate a 30 30
+ for i 0 40
+  set a$i = zero(a) + $i
  end
 
- medimage calc t1 T -mean
-
- imhist -q T x y -range -10 10 -delta 0.1
- lim -n 1 x y; clear; box; plot -x hist x y
- $C0 = 0
- $C1 = 1.5
- $C2 = 400
- $C3 = 0
- vgauss -q x y con yf
- echo "expect {1/sqrt($Nsample)} : $C1"
- plot -c red -x line x yf
+ for i 0 40
+  medimage add t1 a$i
+ end
 end
-
-macro test.median
-
- $Nsample = 16
- medimage delete -q t1
- for i 0 $Nsample
-  mgaussdev t 50 50 0.0 1.0
-  medimage add t1 t
-  imhist -q t x y -range -10 10 -delta 0.1
-
-  $C0 = 0
-  $C1 = 1.5
-  $C2 = 400
-  $C3 = 0
-  vgauss -q x y con yf
- end
-
- # note that median of a gaussian distributed variable is not distributed with sigma' = sigma / sqrt(N)
- # (somewhat higher scatter)
- medimage calc t1 T
-
- imhist -q T x y -range -10 10 -delta 0.1
- lim -n 1 x y; clear; box; plot -x hist x y
- $C0 = 0
- $C1 = 1.5
- $C2 = 400
- $C3 = 0
- vgauss -q x y con yf
- echo "expect {1/sqrt($Nsample)} : $C1 (actually should be a bit higher)"
- plot -c red -x line x yf
-end
- 
-macro test.wtmean
-
- $Nsample = 8
- $sig1 = 1.0
- $sig2 = 3.0
-
- medimage delete -q t1
- for i 0 $Nsample
-  mgaussdev t 50 50 0.0 $sig1
-  set v = $sig1^2 + zero(t)      
-  medimage add t1 t -variance v
-  imhist -q t x y -range -10 10 -delta 0.1
-
-  $C0 = 0
-  $C1 = 1.5
-  $C2 = 400
-  $C3 = 0
-  vgauss -q x y con yf
-  # echo $C1
- end
-
- for i 0 $Nsample
-  mgaussdev t 50 50 0.0 $sig2
-  set v = $sig2^2 + zero(t)      
-  medimage add t1 t -variance v
-  imhist -q t x y -range -10 10 -delta 0.1
-
-  $C0 = 0
-  $C1 = 1.5
-  $C2 = 400
-  $C3 = 0
-  vgauss -q x y con yf
-  # echo $C1
- end
-
- # note that median of a gaussian distributed variable is not distributed with sigma' = sigma / sqrt(N)
- # (somewhat higher scatter)
- medimage calc t1 T -wtmean
-
- imhist -q T x y -range -10 10 -delta 0.1
- lim -n 1 x y; clear; box; plot -x hist x y
- $C0 = 0
- $C1 = 1.5
- $C2 = 400
- $C3 = 0
- vgauss -q x y con yf
- $S1 = $Nsample / $sig1^2 + $Nsample / $sig2^2
- echo "expect {1/sqrt($S1)} : $C1"
- plot -c red -x line x yf
-end
-
-macro test.irls
- medimage delete -q t1
- $Nsample = 16
- $sig = 1.0
- for i 0 $Nsample
-  mgaussdev t 50 50 0.0 $sig
-  set v = $sig^2 + zero(t)      
-
-  set bad = (rnd(t) < 0.05) ? 10*rnd(t) + 5 : zero(t)
-  set ts = t + bad
-
-  medimage add t1 ts -variance v
-  imhist -q t x y -range -10 10 -delta 0.1
-
-  $C0 = 0
-  $C1 = 1.5
-  $C2 = 400
-  $C3 = 0
-  vgauss -q x y con yf
-  # echo $C1
- end
-
- # get stats for straight mean:
- medimage calc t1 Tm -mean
-
- imhist -q Tm x y -range -10 10 -delta 0.1
- lim -n 1 x y; clear; box; plot -x hist x y
- $C0 = 0
- $C1 = 1.5
- $C2 = 400
- $C3 = 0
- vgauss -q x y con yf
- echo "sigma from straight stdev: $C1"
- # stats Tm
- 
- plot -c red -x line x yf
-
- # get stats for irls
- medimage calc t1 Ti -irls
-
- imhist -q Ti x y -range -10 10 -delta 0.1
- lim -n 2 x y; clear; box; plot -x hist x y
- $C0 = 0
- $C1 = 1.5
- $C2 = 400
- $C3 = 0
- vgauss -q x y con yf
- echo "sigma from irls: $C1 (ideal is {$sig/sqrt($Nsample)})"
- # stats Ti
- 
- plot -c red -x line x yf
-end
-
-
-###################33
-
-
-macro test.mean.var
-
- $Nsample = 64
- $sig = 2.0
- medimage delete -q t1
- for i 0 $Nsample
-  mgaussdev t 100 100 0.0 $sig
-  medimage add t1 t
-  imhist -q t x y -range -10 10 -delta 0.1
-
-  $C0 = 0
-  $C1 = 1.5
-  $C2 = 400
-  $C3 = 0
-  vgauss -q x y con yf
-  # echo $C1
- end
-
- medimage calc t1 T -mean -variance Tv
-
- imhist -q T x y -range -10 10 -delta 0.1
- lim -n 1 x y; clear; box; plot -x hist x y
- $C0 = 0
- $C1 = 1.5
- $C2 = 400
- $C3 = 0
- vgauss -q x y con yf
- plot -c red -x line x yf
-
- imhist Tv xv yv -range -1 4 -delta 0.1
- lim -n 2 xv yv; clear; box; plot xv yv -x hist
-
- stat Tv
- echo "$C1 vs {sqrt($MEDIAN)} : expect {$sig/sqrt($Nsample)}"
-end
-
-macro test.median.var
-
- $Nsample = 64
- $sig = 2.0
- medimage delete -q t1
- for i 0 $Nsample
-  mgaussdev t 50 50 0.0 $sig
-  medimage add t1 t
-  imhist -q t x y -range -10 10 -delta 0.1
-
-  $C0 = 0
-  $C1 = 1.5
-  $C2 = 400
-  $C3 = 0
-  vgauss -q x y con yf
-  # echo $C1
- end
-
- # note that median of a gaussian distributed variable is not distributed with sigma' = sigma / sqrt(N)
- # (somewhat higher scatter)
- medimage calc t1 T -variance Tv
-
- imhist -q T x y -range -10 10 -delta 0.1
- lim -n 1 x y; clear; box; plot -x hist x y
- $C0 = 0
- $C1 = 1.5
- $C2 = 400
- $C3 = 0
- vgauss -q x y con yf
- plot -c red -x line x yf
-
- imhist Tv xv yv -range -1 4 -delta 0.1
- lim -n 2 xv yv; clear; box; plot xv yv -x hist
-
- stat Tv
- echo "$C1 vs {sqrt($MEDIAN)} : expect {$sig/sqrt($Nsample)}"
-end
- 
-macro test.wtmean.var
-
- $Nsample = 32
- $sig1 = 1.0
- $sig2 = 1.0
-
- medimage delete -q t1
- for i 0 $Nsample
-  mgaussdev t 50 50 0.0 $sig1
-  set v = $sig1^2 + zero(t)      
-  medimage add t1 t -variance v
-  imhist -q t x y -range -10 10 -delta 0.1
-
-  $C0 = 0
-  $C1 = 1.5
-  $C2 = 400
-  $C3 = 0
-  vgauss -q x y con yf
-  # echo $C1
- end
-
- for i 0 $Nsample
-  mgaussdev t 50 50 0.0 $sig2
-  set v = $sig2^2 + zero(t)      
-  medimage add t1 t -variance v
-  imhist -q t x y -range -10 10 -delta 0.1
-
-  $C0 = 0
-  $C1 = 1.5
-  $C2 = 400
-  $C3 = 0
-  vgauss -q x y con yf
-  # echo $C1
- end
-
- # note that median of a gaussian distributed variable is not distributed with sigma' = sigma / sqrt(N)
- # (somewhat higher scatter)
- medimage calc t1 T -wtmean -variance Tv
-
- imhist -q T x y -range -10 10 -delta 0.1
- lim -n 1 x y; clear; box; plot -x hist x y
- $C0 = 0
- $C1 = 1.5
- $C2 = 400
- $C3 = 0
- vgauss -q x y con yf
- plot -c red -x line x yf
-
- stat -q Tv
- $S1 = $Nsample / $sig1^2 + $Nsample / $sig2^2
- echo $C1 vs {sqrt($MEDIAN)} : expect {1/sqrt($S1)}
-end
-
-macro test.irls.var
-
- $Nsample = 16
- $sig = 1.0
-
- medimage delete -q t1
- for i 0 $Nsample
-  mgaussdev t 50 50 0.0 $sig
-  set v = $sig^2 + zero(t)      
-
-  set bad = (rnd(t) < 0.05) ? 10*rnd(t) + 5 : zero(t)
-  set ts = t + bad
-
-  medimage add t1 ts -variance v
-  imhist -q t x y -range -10 10 -delta 0.1
-
-  $C0 = 0
-  $C1 = 1.5
-  $C2 = 400
-  $C3 = 0
-  vgauss -q x y con yf
-  # echo $C1
- end
-
- # get stats for straight mean:
- medimage calc t1 Tm -mean -variance Tv
-
- imhist -q Tm x y -range -10 10 -delta 0.1
- lim -n 1 x y; clear; box; plot -x hist x y
- $C0 = 0
- $C1 = 1.5
- $C2 = 400
- $C3 = 0
- vgauss -q x y con yf
- echo "sigma from straight stdev: $C1"
- # stats Tm
- 
- plot -c red -x line x yf
-
- # get stats for irls
- medimage calc t1 Ti -irls -variance Tv
-
- imhist -q Ti x y -range -10 10 -delta 0.1
- lim -n 2 x y; clear; box; plot -x hist x y
- $C0 = 0
- $C1 = 1.5
- $C2 = 400
- $C3 = 0
- vgauss -q x y con yf
- echo "sigma from irls: $C1 (ideal is {$sig/sqrt($Nsample)})"
- # stats Ti
- 
- plot -c red -x line x yf
-
- set dTv = sqrt(Tv)
- imhist dTv xv yv -range -1 4 -delta 0.02; lim -n 3 xv yv; clear; box; plot xv yv -x hist
-
- stat -q Tv
- echo $C1 vs {sqrt($MEDIAN)} (ideal is {$sig/sqrt($Nsample)})"
-end
-
-macro test.irls.boot.var
-
- $Nsample = 64
- $sig = 1.0
-
- medimage delete -q t1
- for i 0 $Nsample
-  mgaussdev t 200 200 0.0 $sig
-  set v = $sig^2 + zero(t)      
-
-  set bad = (rnd(t) < 0.05) ? 10*rnd(t) + 5 : zero(t)
-  set ts = t + bad
-
-  mgaussdev noise 200 200 0.0 0.5
-  set ts = ts + noise
-
-  medimage add t1 ts -variance v
-  imhist -q t x y -range -10 10 -delta 0.1
-
-  $C0 = 0
-  $C1 = 1.5
-  $C2 = 400
-  $C3 = 0
-  vgauss -q x y con yf
-  # echo $C1
- end
-
- # get stats for straight mean:
- medimage calc t1 Tm -mean -variance Tv
-
- imhist -q Tm x y -range -10 10 -delta 0.02
- lim -n 1 x y; clear; box; plot -x hist x y
- peak -q x y
- $C0 = $peakpos
- $C1 = 1.5*$sig / sqrt($Nsample)
- $C2 = $peakval
- $C3 = 0
- vgauss -q x y con yf
- echo "sigma from straight stdev: $C1"
- # stats Tm
- 
- plot -c red -x line x yf
-
- # get stats for irls
- date
- medimage calc t1 Ti -irls -variance Tv -bootstrap-iter 100
- date
-
- imhist -q Ti x y -range -10 10 -delta 0.02
- lim -n 2 x y; clear; box; plot -x hist x y
- peak -q x y
- $C0 = $peakpos
- $C1 = 1.5*$sig / sqrt($Nsample)
- $C2 = $peakval
- $C3 = 0
- vgauss -q x y con yf
- echo "sigma from irls: $C1 (ideal is {$sig/sqrt($Nsample)})"
- # stats Ti
- 
- plot -c red -x line x yf
-
- set dTv = sqrt(Tv)
- imhist dTv xv yv -range 0 {5*$sig/sqrt($Nsample)} -delta 0.02; lim -n 3 xv yv; clear; box; plot xv yv -x hist
-
- stat -q Tv
- echo $C1 vs {sqrt($MEDIAN)} (ideal is {$sig/sqrt($Nsample)})"
-end
-
-##############################
-macro test.irls.boot.test
-
- $Nsample = 100
- $sig1 = 1.0
-
- medimage delete -q t1
- for i 0 $Nsample
-  mgaussdev t 100 100 0.0 $sig1
-  set v = $sig1^2 + zero(t)      
-
-  medimage add t1 t -variance v
- end
-
- # get stats for irls
- medimage calc t1 Ti -irls -variance Tv -bootstrap
-
- imhist -q Ti x y -range {-10*$sig1/sqrt($Nsample)} {10*$sig1/sqrt($Nsample)} -delta 0.01
- lim -n 2 x y; clear; box; plot -x hist x y
- peak -q x y
- $C0 = $peakpos
- $C1 = 1.5*$sig1/sqrt($Nsample)
- $C2 = $peakval
- $C3 = 0
- vgauss x y con yf
- echo "sigma from irls: $C1 (ideal is {$sig1/sqrt($Nsample)})"
- # stats Ti
- 
- plot -c red -x line x yf
-
- set dTv = sqrt(Tv)
- imhist dTv xv yv -range 0 {5*$sig1/sqrt($Nsample)} -delta 0.02; lim -n 3 xv yv; clear; box; plot xv yv -x hist
-
- stat -q irls_npt
- $Npix = $MEAN
-
- stat -q Tv
- echo "sigma of irls average: $C1, sqrt(mean) of irls variance: {sqrt($MEAN)}, (ideal is {$sig1/sqrt($Npix)})"
-end
-
-macro test.irls.range.var
- medimage delete -q t1
- for i 0 8
-  mgaussdev t 50 50 0.0 1.0
-  set v = 1.0 + zero(t)      
-
-  set bad = (rnd(t) < 0.05) ? 10*rnd(t) + 5 : zero(t)
-  set ts = t + bad
-
-  medimage add t1 ts -variance v
-  imhist -q t x y -range -10 10 -delta 0.1
-
-  $C0 = 0
-  $C1 = 1.5
-  $C2 = 400
-  $C3 = 0
-  vgauss -q x y con yf
-  echo $C1
- end
-
- for i 0 8
-  mgaussdev t 50 50 0.0 3.0
-  set v = 3.0 + zero(t)      
-
-  set bad = (rnd(t) < 0.05) ? 10*rnd(t) + 5 : zero(t)
-  set ts = t + bad
-
-  medimage add t1 ts -variance v
-  imhist -q t x y -range -10 10 -delta 0.1
-
-  $C0 = 0
-  $C1 = 1.5
-  $C2 = 400
-  $C3 = 0
-  vgauss -q x y con yf
-  echo $C1
- end
-
- # get stats for straight mean:
- medimage calc t1 Tm -mean -variance Tv
-
- imhist -q Tm x y -range -10 10 -delta 0.1
- lim -n 1 x y; clear; box; plot -x hist x y
- $C0 = 0
- $C1 = 1.5
- $C2 = 400
- $C3 = 0
- vgauss -q x y con yf
- echo $C1
- stats Tm
- 
- plot -c red -x line x yf
-
- # get stats for irls
- medimage calc t1 Ti -irls -variance Tv
-
- imhist -q Ti x y -range -10 10 -delta 0.1
- lim -n 2 x y; clear; box; plot -x hist x y
- $C0 = 0
- $C1 = 1.5
- $C2 = 400
- $C3 = 0
- vgauss -q x y con yf
- echo $C1
- stats Ti
- 
- plot -c red -x line x yf
-
- stat -q Tv
- echo $C1 vs {sqrt($MEDIAN)}
-
- set dTv = sqrt(Tv)
- imhist dTv xv yv -range -1 4 -delta 0.02; lim -n 3 xv yv; clear; box; plot xv yv -x hist
-end
Index: trunk/Ohana/src/opihi/cmd.data/test/set.sh
===================================================================
--- trunk/Ohana/src/opihi/cmd.data/test/set.sh	(revision 41326)
+++ 	(revision )
@@ -1,43 +1,0 @@
-
-macro memtest1
-
- create x -10 10 0.1
- set y = zero(x)
- $i = 0
-
- memory check
- for i 0 1000
-   set y = exp(x)
- end
- memory check
-   
-end
-
-macro memtest2
-
- create x -10 10 0.1
- set y = zero(x)
- $i = 0
-
- memory check
- for i 0 1000
-   set y = (x < 0) ? x : exp(x)
- end
- memory check
-   
-end
-
-macro memtest3
-
- create x -10 10 0.1
- set y = zero(x)
- $i = 0
-
- memory check
- for i 0 1000
-   set y = (x < 5 + 2*$i) ? x : exp(x)
- end
- memory check
-   
-end
-
Index: trunk/Ohana/src/opihi/cmd.data/test/spline.sh
===================================================================
--- trunk/Ohana/src/opihi/cmd.data/test/spline.sh	(revision 41326)
+++ 	(revision )
@@ -1,11 +1,0 @@
-
-macro test1
-
-  for i 0 100
-    create x 0 50
-    set y = x^2
-    spline create t$i x y
-    spline rename t$i test
-    spline delete test
-  end
-end
Index: trunk/Ohana/src/opihi/cmd.data/test/vsigmoid.sh
===================================================================
--- trunk/Ohana/src/opihi/cmd.data/test/vsigmoid.sh	(revision 41326)
+++ 	(revision )
@@ -1,263 +1,0 @@
-
-list tests
- test1
- test2
- test3
-end
-
-macro test1
- $PASS = 1
- break -auto off
-
- create x -10 10 0.1
- set y = 0 + 5 / (1 + exp((x - 3)/4))
-
- $C0 = 1
- $C1 = 2
- $C2 = 10
- $C3 = 1
- set dy = sqrt(y)
-
- vsigmoid -q x y dy yfit
- lim x y; clear; box; plot -x 1 -c black x y; plot -c red x yfit
- # cursor
-
- if (abs($C0 - 0.0) > 0.01)
-   $PASS = 0
- end
- if (abs($C1 - 3.0) > 0.01)
-   $PASS = 0
- end
- if (abs($C2 - 5.0) > 0.01)
-   $PASS = 0
- end
- if (abs($C3 - 0.0) > 0.01)
-   $PASS = 0
- end
-end
-
-# noise of 0.1
-macro test2
- $PASS = 1
- break -auto off
-
- create x -10 10 0.1
- set y = 50 + 1000 / (1 + exp((x - 3)/2))
- set dy = (rnd(y) - 0.5)/0.5
- set y = y + dy
-
- $C0 = 2
- $C1 = 3
- $C2 = 900
- $C3 = 1
-
- vsigmoid -q x y dy yfit
- lim x y; clear; box; plot -x 1 -c black x y; plot -c red x yfit
- # cursor
-
- if (abs($C0 - 0.0) > 0.01)
-   $PASS = 0
- end
- if (abs($C1 - 3.0) > 0.01)
-   $PASS = 0
- end
- if (abs($C2 - 1000.0) > 0.1)
-   $PASS = 0
- end
- if (abs($C3 - 0.0) > 0.1)
-   $PASS = 0
- end
-end
-
-# poisson-distributed noise
-macro test3
- $PASS = 1
- break -auto off
-
- $C0o = 3
- $C1o = 2
- $C2o = 20
- $C3o = -2
-
- create x -10 10 0.1
- set y = $C3o + $C2o / (1 + exp((x - $C0o)/$C1o))
-
- gaussdev dY y[] 0.0 1.0
- set dy = dY * sqrt(abs(y))
- set y = y + dy
-
- $C0 = $C0o + 2
- $C1 = $C1o + 2
- $C2 = $C2o + 50
- $C3 = $C3o + 10
-
- vsigmoid x y dy yfit
- lim x y; clear; box; plot -x 1 -c black x y; plot -c red x yfit
- # cursor
-
- $dS = 3.0 / sqrt(y[])
-
- if (abs($C0 - $C0o) > $dS)
-   $PASS = 0
- end
- if (abs($C1 - $C1o)/$C1o > $dS)
-   $PASS = 0
- end
- if (abs($C2 - $C2o)/$C2o > $dS)
-   $PASS = 0
- end
- if (abs($C3 - $C3o) > $dS)
-   $PASS = 0
- end
-end
-
-macro test1rev
- $PASS = 1
- break -auto off
-
- create x -10 10 0.1
- set y = 5 / (1 + exp(-(x - 3)/4))
-
- $C0 = 1
- $C1 = 2
- $C2 = 10
- $C3 = 1
- set dy = sqrt(abs(y))
-
- vsigmoid -r -q x y dy yfit
- lim x y; clear; box; plot -x 1 -c black x y; plot -c red x yfit
- # cursor
-
- if (abs($C0 - 0.0) > 0.01)
-   $PASS = 0
- end
- if (abs($C1 - 3.0) > 0.01)
-   $PASS = 0
- end
- if (abs($C2 - 5.0) > 0.01)
-   $PASS = 0
- end
- if (abs($C3 - 0.0) > 0.01)
-   $PASS = 0
- end
-end
-
-# noise of 0.1
-macro test2rev
- $PASS = 1
- break -auto off
-
- create x -10 10 0.1
- set y = 50 + 1000 / (1 + exp(-(x - 3)/2))
- set dy = (rnd(y) - 0.5)/0.5
- set y = y + dy
-
- $C0 = 2
- $C1 = 3
- $C2 = 900
- $C3 = 1
-
- vsigmoid -r -q x y dy yfit
- lim x y; clear; box; plot -x 1 -c black x y; plot -c red x yfit
- # cursor
-
- if (abs($C0 - 0.0) > 0.01)
-   $PASS = 0
- end
- if (abs($C1 - 3.0) > 0.01)
-   $PASS = 0
- end
- if (abs($C2 - 1000.0) > 0.1)
-   $PASS = 0
- end
- if (abs($C3 - 0.0) > 0.1)
-   $PASS = 0
- end
-end
-
-# poisson-distributed noise
-macro test3rev
- $PASS = 1
- break -auto off
-
- $C0o = 3
- $C1o = 2
- $C2o = 20
- $C3o = -2
-
- create x -10 10 0.1
- set y = $C3o + $C2o / (1 + exp(-(x - $C0o)/$C1o))
-
- gaussdev dY y[] 0.0 1.0
- set dy = dY * sqrt(abs(y))
- set y = y + dy
-
- $C0 = $C0o + 2
- $C1 = $C1o + 2
- $C2 = $C2o + 50
- $C3 = $C3o + 10
-
- vsigmoid -r -q x y dy yfit
- lim x y; clear; box; plot -x 1 -c black x y; plot -c red x yfit
- # cursor
-
- $dS = 3.0 / sqrt(y[])
-
- if (abs($C0 - $C0o) > $dS)
-   $PASS = 0
- end
- if (abs($C1 - $C1o)/$C1o > $dS)
-   $PASS = 0
- end
- if (abs($C2 - $C2o)/$C2o > $dS)
-   $PASS = 0
- end
- if (abs($C3 - $C3o) > $dS)
-   $PASS = 0
- end
-end
-
-macro memtest1
-
- create x -10 10 0.1
- set y = 0 + 5 / (1 + exp((x - 3)/4))
-
- $C0 = 1
- $C1 = 2
- $C2 = 10
- $C3 = 1
- set dy = sqrt(y)
- set yfit = zero(y)
-
- $i = 0
-
- memory check
- for i 0 1000
-   vsigmoid -q x y dy yfit
- end
- memory check
-   
-end
-
-macro memtest2
-
- create x -10 10 0.1
- set y = 0 + 5 / (1 + exp((x - 3)/4))
-
- $C0 = 1
- $C1 = 2
- $C2 = 10
- $C3 = 1
- set dy = sqrt(y)
- set yfit = zero(y)
-
- $i = 0
-
- memory check
- for i 0 1000
-   vsigmoid -q -r x y dy yfit
- end
- memory check
-   
-end
-
Index: trunk/Ohana/src/opihi/cmd.data/test/vstat.sh
===================================================================
--- trunk/Ohana/src/opihi/cmd.data/test/vstat.sh	(revision 41326)
+++ 	(revision )
@@ -1,28 +1,0 @@
-
-macro memtest1
-
- # preset variables so memory usage does not change
- $PMIN = -10
- $PMAX = 9.9
- $MIN = -10
- $MAX = 9.9
- $MEDIAN = -0.1097
- $MEAN = -0.05
- $MODE = -10
- $TOTAL = -10
- $NPIX = 200
- $NPTS = 200
- $NUSED = 200
- $SIGMA = 5.7879184514
-
- create x -10 10 0.1
- $i = 0
-
- memory check
- for i 0 1000
-   vstat -q x
- end
- memory check
-   
-end
-
Index: trunk/Ohana/src/opihi/cmd.data/threshold.c
===================================================================
--- trunk/Ohana/src/opihi/cmd.data/threshold.c	(revision 41326)
+++ trunk/Ohana/src/opihi/cmd.data/threshold.c	(revision 41340)
@@ -25,14 +25,4 @@
     remove_argument (N, &argc, argv);
     BinMax = atoi (argv[N]);
-    remove_argument (N, &argc, argv);
-  }
-
-  float ValMin = NAN;
-  float ValMax = NAN;
-  if ((N = get_argument (argc, argv, "-vrange"))) {
-    remove_argument (N, &argc, argv);
-    ValMin = atof (argv[N]);
-    remove_argument (N, &argc, argv);
-    ValMax = atof (argv[N]);
     remove_argument (N, &argc, argv);
   }
@@ -74,16 +64,4 @@
   }
 
-  // ValMin, ValMax not compatible with BinMin, BinMax
-  if (isfinite(ValMin)) {
-    int binTest = ohana_bisection_double (vecx[0].elements.Flt, vecx[0].Nelements, ValMin);
-    BinMin = (vecx[0].elements.Flt[binTest+1] == ValMin) ? binTest : binTest + 1;
-    // XXX dangerous: check that this does not run off the end, etc
-  }
-  if (isfinite(ValMax)) {
-    int binTest = ohana_bisection_double (vecx[0].elements.Flt, vecx[0].Nelements, ValMax);
-    BinMax = (vecx[0].elements.Flt[binTest+1] == ValMax) ? binTest : binTest + 1;
-    // XXX dangerous: check that this does not run off the end, etc
-  }
-
   // use bisection to find the value
 
@@ -93,13 +71,4 @@
 
   if (!REVERSE) {
-    // this algorithm assumes vecy[BinMax] > threshold, vecy[BinMin] < threshold
-    if (vecy[0].elements.Flt[BinMin] > value) {
-      gprint (GP_ERR, "ERROR: all values above threshold\n");
-      return FALSE;
-    }
-    if (vecy[0].elements.Flt[BinMax] < value) {
-      gprint (GP_ERR, "ERROR: all values below threshold\n");
-      return FALSE;
-    }
     while (Nhi - Nlo > 10) {
       N = 0.5*(Nlo + Nhi);
@@ -120,13 +89,4 @@
     }
   } else {
-    // this algorithm assumes vecy[BinMin] > threshold, vecy[BinMax] < threshold
-    if (vecy[0].elements.Flt[BinMin] < value) {
-      gprint (GP_ERR, "ERROR: all values below threshold\n");
-      return FALSE;
-    }
-    if (vecy[0].elements.Flt[BinMax] > value) {
-      gprint (GP_ERR, "ERROR: all values above threshold\n");
-      return FALSE;
-    }
     while (Nhi - Nlo > 10) {
       N = 0.5*(Nlo + Nhi);
Index: trunk/Ohana/src/opihi/cmd.data/tvcolors.c
===================================================================
--- trunk/Ohana/src/opihi/cmd.data/tvcolors.c	(revision 41326)
+++ trunk/Ohana/src/opihi/cmd.data/tvcolors.c	(revision 41340)
@@ -37,8 +37,21 @@
     gprint (GP_ERR, "USAGE: tvcolors (colormap) [-nan red green blue]\n");
     gprint (GP_ERR, " colormap options : greyscale, -greyscale, rainbow, heat, fullcolor, ruffcolor (also grayscale, -grayscale)\n");
-    gprint (GP_ERR, " colormap file: if colormap name is given as file:path/to/file, the colormap is read from the file\n");
+    gprint (GP_ERR, " colormap file name of the for WORD:PATH where WORD = (file,csvf,lgcy,cetf)\n");
+    gprint (GP_ERR, " lgcy:\n");
+    gprint (GP_ERR, "   the colormap file must contain 4 columns: f R B G; each line defines a color transition.\n");
+    gprint (GP_ERR, "   f: 0 - 1 defines the scale value for the transition\n");
+    gprint (GP_ERR, "   R,B,G: 0 - 1 define the value of the color at the transition point\n");
+    gprint (GP_ERR, " file:\n");
     gprint (GP_ERR, "   the colormap file must contain 4 columns: f R G B; each line defines a color transition.\n");
     gprint (GP_ERR, "   f: 0 - 1 defines the scale value for the transition\n");
     gprint (GP_ERR, "   R,G,B: 0 - 1 define the value of the color at the transition point\n");
+    gprint (GP_ERR, " csvf:\n");
+    gprint (GP_ERR, "   the colormap file must contain 4 columns: f,R,G,B separate by commas; each line defines a color transition.\n");
+    gprint (GP_ERR, "   f: 0 - 1 defines the scale value for the transition\n");
+    gprint (GP_ERR, "   R,G,B: 0 - 1 define the value of the color at the transition point\n");
+    gprint (GP_ERR, " cetf:\n");
+    gprint (GP_ERR, "   the colormap file must 256 rows contain 3 columns: R,G,B separate by commas; each line defines a color transition.\n");
+    gprint (GP_ERR, "   R,G,B: 0 - 1 define the value of the color at the transition point\n");
+    gprint (GP_ERR, "   CETF-format files can be found at : https://peterkovesi.com/projects/colourmaps\n");
     return (FALSE);
   }
Index: trunk/Ohana/src/opihi/cmd.data/vgauss.c
===================================================================
--- trunk/Ohana/src/opihi/cmd.data/vgauss.c	(revision 41326)
+++ trunk/Ohana/src/opihi/cmd.data/vgauss.c	(revision 41340)
@@ -3,5 +3,4 @@
 /* local private functions */
 opihi_flt fgaussOD (opihi_flt, opihi_flt *, int, opihi_flt *);
-int vgauss_apply (int argc, char **argv);
 
 # define GET_VAR(V,A) \
@@ -21,10 +20,4 @@
   Vector *xvec, *yvec, *svec, *ovec;
   char *c, name[16];
-
-  if ((N = get_argument (argc, argv, "-apply"))) {
-    remove_argument (N, &argc, argv);
-    int status = vgauss_apply (argc, argv);
-    return status;
-  }
 
   Quiet = FALSE;
@@ -111,6 +104,4 @@
   }  
   if (!Quiet) gprint (GP_ERR, "%d iterations\n", i); 
-  set_variable ("Chisq", chisq);
-  set_variable ("ChisqNu", chisq / (float) (Npts - Npar));
 
   for (i = 0; i < Npts; i++) {
@@ -134,38 +125,4 @@
 }
 
-int vgauss_apply (int argc, char **argv) {
-
-  opihi_flt par[4];
-  Vector *xvec, *ovec;
-  char *c;
-
-  // NOTE: -apply has already been stripped by vgauss call
-  if (argc != 3) {
-    gprint (GP_ERR, "USAGE: vgauss -apply <x> <out>\n");
-    return (FALSE);
-  }
-  
-  if ((xvec = SelectVector (argv[1], OLDVECTOR, TRUE)) == NULL) return (FALSE);
-  if ((ovec = SelectVector (argv[2], ANYVECTOR, TRUE)) == NULL) return (FALSE);
-
-  CastVector (xvec, OPIHI_FLT);
-
-  GET_VAR (par[0], "C0");
-  GET_VAR (par[1], "C1");
-  GET_VAR (par[2], "C2");
-  GET_VAR (par[3], "C3");
-  int Npar = 4;
-
-  int Npts = xvec[0].Nelements;
-  ResetVector (ovec, OPIHI_FLT, Npts);
-
-  for (int i = 0; i < Npts; i++) {
-    ovec[0].elements.Flt[i] = fgaussOD (xvec[0].elements.Flt[i], par, Npar, NULL);
-  }
-  ovec[0].Nelements = Npts;
-
-  return TRUE;
-}
-
 /* pars: x_o, sigma, I, back */
 opihi_flt fgaussOD (opihi_flt x, opihi_flt *par, int Npar, opihi_flt *dpar) {
@@ -178,10 +135,8 @@
   f = par[2]*r + par[3];
 
-  if (dpar) {
-    dpar[0] = par[2]*r*z/par[1];
-    dpar[1] = par[2]*r*z*z/par[1];
-    dpar[2] = r;
-    dpar[3] = 1;
-  }
+  dpar[0] = par[2]*r*z/par[1];
+  dpar[1] = par[2]*r*z*z/par[1];
+  dpar[2] = r;
+  dpar[3] = 1;
   
   return (f);
Index: trunk/Ohana/src/opihi/cmd.data/virls.c
===================================================================
--- trunk/Ohana/src/opihi/cmd.data/virls.c	(revision 41326)
+++ 	(revision )
@@ -1,103 +1,0 @@
-# include "data.h"
-
-double opihi_irls_mean_dbl (double *val, double *wgt, int N, int *Converged);
-double weight_cauchy_square_dbl (double x2);
-
-# define IRLS_TOLERANCE 1e-4
-
-int virls (int argc, char **argv) {
-  
-  if (argc != 3) {
-    gprint (GP_ERR, "USAGE: virls (values) (sigmas)\n");
-    gprint (GP_ERR, "NOTE: sigmas with abs values < %e will be truncated to that value\n", FLT_MIN);
-    return (FALSE);
-  }
-
-  Vector *value, *sigma;
-
-  if ((value = SelectVector (argv[1], OLDVECTOR, TRUE)) == NULL) return (FALSE);
-  if ((sigma = SelectVector (argv[2], OLDVECTOR, TRUE)) == NULL) return (FALSE);
-
-  if (value->Nelements != sigma->Nelements) {
-    gprint (GP_ERR, "vectors are not the same length\n");
-    return FALSE;
-  }
-  if (value->type != OPIHI_FLT) {
-    gprint (GP_ERR, "%s is not a floating point vector\n", argv[1]);
-    return FALSE;
-  }
-  if (sigma->type != OPIHI_FLT) {
-    gprint (GP_ERR, "%s is not a floating point vector\n", argv[2]);
-    return FALSE;
-  }
-
-  ALLOCATE_PTR (val, opihi_flt, value->Nelements);
-  ALLOCATE_PTR (wgt, opihi_flt, value->Nelements);
-
-  int N = 0;
-  for (int i = 0; i < value->Nelements; i++) {
-    if (!isfinite(value->elements.Flt[i])) continue;
-
-    double s = sigma->elements.Flt[i];
-    if (!isfinite(s)) continue;
-
-    if (fabs(s) < FLT_MIN) s = FLT_MIN;
-
-    val[N] = value->elements.Flt[i];
-    wgt[N] = 1.0 / SQ(s);
-    N ++;
-  }
-
-  int converged = TRUE;
-  double Value = opihi_irls_mean_dbl (val, wgt, N, &converged);
-
-  set_variable ("WTMEAN",     Value);
-  set_int_variable ("NUSED", N);
-  set_int_variable ("CONVERGED", converged);
-  return (TRUE);
-}
-
-double opihi_irls_mean_dbl (double *val, double *wgt, int N, int *Converged) {
-
-  // calculate weighted mean
-  double S1 = 0.0, S2 = 0.0;
-  for (int n = 0; n < N; n++) {
-    S1 += wgt[n] * val[n];
-    S2 += wgt[n];
-  }
-  double Value = S1 / S2;
-  
-  int converged = FALSE;
-  for (int i = 0; (i < 10) && !converged; i++) {
-    double ValueLast = Value;
-
-    double S1 = 0.0, S2 = 0.0;
-
-    // calculate weight modification based on distances (squared).
-    // use modifier to calculate new weighted mean
-    for (int n = 0; n < N; n++) {
-      double dV = (val[n] - Value);
-      double d2 = SQ(dV) * wgt[n];
-      
-      double Mod = weight_cauchy_square_dbl (d2);
-      S1 += Mod * wgt[n] * val[n];
-      S2 += Mod * wgt[n];
-      fprintf (stderr, "%f %f : %f %f : %f\n", val[n], wgt[n], dV, sqrt(d2), Mod);
-    }
-    Value = S1 / S2;
-
-    double delta = fabs(Value - ValueLast);
-    if (delta < Value * IRLS_TOLERANCE) converged = TRUE;
-
-    // XXX if the answer is close to zero, we might not converge
-  }
-  *Converged = converged;
-  return Value;
-}
-
-# define CAUCY_FACTOR 1.0
-
-double weight_cauchy_square_dbl (double x2) {
-  double r2 = x2 / CAUCY_FACTOR;
-  return (1.0 / (1.0 + r2));
-}
Index: trunk/Ohana/src/opihi/cmd.data/vsigmoid.c
===================================================================
--- trunk/Ohana/src/opihi/cmd.data/vsigmoid.c	(revision 41326)
+++ 	(revision )
@@ -1,192 +1,0 @@
-# include "data.h"
-
-typedef opihi_flt FitFunc (opihi_flt, opihi_flt *, int, opihi_flt *);
-
-/* local private functions */
-opihi_flt fsigmoidOD (opihi_flt, opihi_flt *, int, opihi_flt *);
-opihi_flt rsigmoidOD (opihi_flt, opihi_flt *, int, opihi_flt *);
-
-# define GET_VAR(V,A) {					\
-    char *c = get_variable (A);				\
-    if (c == NULL) {					\
-      gprint (GP_ERR, "missing fit parameter A\n");	\
-      return (FALSE);					\
-    }							\
-    V = atof (c);					\
-    free (c); }
-
-// XXX this fitting function works but fails if the input vectors have NANs
-int vsigmoid (int argc, char **argv) {
-
-  int N;
-  Vector *xvec, *yvec, *svec, *ovec;
-
-  FitFunc *FUNC = fsigmoidOD;
-  if ((N = get_argument (argc, argv, "-r"))) {
-    FUNC = rsigmoidOD;
-    remove_argument (N, &argc, argv);
-  }
-  if ((N = get_argument (argc, argv, "-rev"))) {
-    FUNC = rsigmoidOD;
-    remove_argument (N, &argc, argv);
-  }
-
-  int Quiet = FALSE;
-  if ((N = get_argument (argc, argv, "-q"))) {
-    Quiet = TRUE;
-    remove_argument (N, &argc, argv);
-  }
-  if ((N = get_argument (argc, argv, "-quiet"))) {
-    Quiet = TRUE;
-    remove_argument (N, &argc, argv);
-  }
-
-  if (argc != 5) {
-    gprint (GP_ERR, "USAGE: vsigmoid [-q] [-r] [-rev] <x> <y> <dy> (out)\n");
-    gprint (GP_ERR, "  <dy> may be the words 'con[stant]' or 'poi[sson]', in which case the error is constructed'\n");
-    gprint (GP_ERR, " uses guesses: C0 (center), C1 (sigma), C2 (top), C3 (bottom)\n");
-    gprint (GP_ERR, " forward sigmoid : bottom + top / (1 + exp(-z)), z = (x - center) / sigma\n");
-    gprint (GP_ERR, " -r / -rev : reverse sigmoid : bottom + top / (1 + exp(z))\n");
-    return (FALSE);
-  }
-  
-  if ((xvec = SelectVector (argv[1], OLDVECTOR, TRUE)) == NULL) return (FALSE);
-  if ((yvec = SelectVector (argv[2], OLDVECTOR, TRUE)) == NULL) return (FALSE);
-  if ((ovec = SelectVector (argv[4], ANYVECTOR, TRUE)) == NULL) return (FALSE);
-
-  CastVector (xvec, OPIHI_FLT);
-  CastVector (yvec, OPIHI_FLT);
-
-  int Nsvec = strlen(argv[3]);
-
-  if ((Nsvec >= 3) && (!strncasecmp ("poisson", argv[3], Nsvec) || !strncasecmp ("constant", argv[3], Nsvec))) {
-    svec = SelectVector ("vsigmoid_err", ANYVECTOR, TRUE);
-    if (svec == NULL) return (FALSE);
-    MatchVector (svec, xvec, OPIHI_FLT);
-    opihi_flt *v1 = svec[0].elements.Flt;
-    opihi_flt *v2 = yvec[0].elements.Flt;
-    if (!strncasecmp ("poisson", argv[3], Nsvec)) {
-      for (int i = 0; i < svec[0].Nelements; i++) {
-	v1[i] = (isfinite(v2[i]) && (v2[i] > 0)) ? sqrt(v2[i]) : 1.0;
-      }
-    } else {
-      for (int i = 0; i < svec[0].Nelements; i++) {
-	v1[i] = 1.0;
-      }
-    }
-  } else {
-    if ((svec = SelectVector (argv[3], OLDVECTOR, TRUE)) == NULL) return (FALSE);
-  }
-
-  CastVector (svec, OPIHI_FLT);
-  // XXX Cast is failing.
-
-  int Npts = xvec[0].Nelements;
-  ResetVector (ovec, OPIHI_FLT, Npts);
-
-  ALLOCATE_PTR (dy, opihi_flt, Npts);
-
-  opihi_flt par[4];
-  GET_VAR (par[0], "C0");
-  GET_VAR (par[1], "C1");
-  GET_VAR (par[2], "C2");
-  GET_VAR (par[3], "C3");
-  int Npar = 4;
-
-  // mrqmin takes the inverse variance (do not generate NANs)
-  opihi_flt *v1 = svec[0].elements.Flt;
-  opihi_flt *v2 = dy;
-  for (int i = 0; i < Npts; i++, v1++, v2++) {
-      *v2 = (*v1 == 0.0) ? 0.0 : 1.0 / (*v1 * *v1);
-  } 
-  
-  opihi_flt ochisq = mrqinit (xvec[0].elements.Flt, yvec[0].elements.Flt, dy, Npts, par, Npar, FUNC, !Quiet);
-  opihi_flt dchisq = ochisq + 2*Npts;
-
-  int Niter;
-  for (Niter = 0; (Niter < 20) && ((dchisq > 0.1*(Npts - Npar)) || (dchisq <= 0.0)); Niter++) {
-    opihi_flt chisq = mrqmin (xvec[0].elements.Flt, yvec[0].elements.Flt, dy, Npts, par, Npar, FUNC, !Quiet);
-    dchisq = ochisq - chisq;
-    ochisq = chisq;
-    if (!Quiet) gprint (GP_ERR, "dchisq: %f, Ndof: %d\n", dchisq, Npts - Npar);
-  }  
-  if (!Quiet) gprint (GP_ERR, "%d iterations\n", Niter); 
-
-  for (int i = 0; i < Npts; i++) {
-    ovec[0].elements.Flt[i] = FUNC (xvec[0].elements.Flt[i], par, Npar, dy);
-  }
-  ovec[0].Nelements = Npts;
-  /* set output *before* variable renomalization */
-
-  opihi_flt **covar = mrqcovar (Npar);
-  for (int i = 0; i < Npar; i++) {
-    char name[16];
-    sprintf (name, "C%d", i);
-    set_variable (name, par[i]);
-    if (!Quiet) gprint (GP_ERR, "%d  %f  %f\n", i, par[i], sqrt(covar[i][i]));
-    sprintf (name, "dC%d", i);
-    set_variable (name, sqrt(covar[i][i]));
-  }
-
-  free (dy);
-  mrqfree (Npar);
-  return (TRUE);
-}
-
-/* pars: x_o, sigma, top, bottom */
-opihi_flt rsigmoidOD (opihi_flt x, opihi_flt *par, int Npar, opihi_flt *dpar) {
-  OHANA_UNUSED_PARAM(Npar);
-
-  double z = (x - par[0])/par[1];
-  double r = exp (z);
-  double s = 1 + r;
-  double q = 1 / s;
-  double f = par[2]*q + par[3];
-
-  // df/dp0 = df/dq * dq/dr * dr/dz * dz/dp0
-  // df/dq  = par[2]
-  // dq/ds  = -s^-2 = -q/s
-  // ds/dr  = 1
-  // dr/dz  = r
-  // dz/dp0 = -1 / par[1]
-  // dz/dp1 = -z / par[1]
-
-  // df/dp0 = par[2]*(-q/s)*r*(-1/par[1]) = par[2]*q*r/(s*par[1])
-  // df/dp1 = par[2]*(-q/s)*r*(-z/par[1]) = par[2]*q*r*z/(s*par[1])
-
-  dpar[0] = par[2]*q*r/(s*par[1]); 
-  dpar[1] = dpar[0]*z;
-  dpar[2] = q;
-  dpar[3] = 1;
-  
-  return (f);
-}
-
-/* pars: x_o, sigma, top, bottom */
-opihi_flt fsigmoidOD (opihi_flt x, opihi_flt *par, int Npar, opihi_flt *dpar) {
-  OHANA_UNUSED_PARAM(Npar);
-
-  double z = (x - par[0])/par[1];
-  double r = exp (-z);
-  double s = 1 + r;
-  double q = 1 / s;
-  double f = par[2]*q + par[3];
-
-  // df/dp0 = df/dq * dq/dr * dr/dz * dz/dp0
-  // df/dq  = par[2]
-  // dq/ds  = -s^-2 = -q/s
-  // ds/dr  = 1
-  // dr/dz  = -r
-  // dz/dp0 = -1 / par[1]
-  // dz/dp1 = -z / par[1]
-
-  // df/dp0 = -par[2]*(-q/s)*r*(-1/par[1]) = par[2]*q*r/(s*par[1])
-  // df/dp1 = -par[2]*(-q/s)*r*(-z/par[1]) = par[2]*q*r*z/(s*par[1])
-
-  dpar[0] = -par[2]*q*r/(s*par[1]); 
-  dpar[1] = dpar[0]*z;
-  dpar[2] = q;
-  dpar[3] = 1;
-  
-  return (f);
-}
Index: trunk/Ohana/src/opihi/cmd.data/vtransitions.c
===================================================================
--- trunk/Ohana/src/opihi/cmd.data/vtransitions.c	(revision 41326)
+++ 	(revision )
@@ -1,175 +1,0 @@
-# include "data.h"
-
-static int isFltX = FALSE;
-static int isFltY = FALSE;
-static double interpolate_position (Vector *vecx, Vector *vecy, int bin, float value);
-
-int vtransitions (int argc, char **argv) {
-  
-  int N;
-  Vector *vecx, *vecy, *outbin, *outval, *outpos;
-
-  int QUIET = FALSE;
-  if ((N = get_argument (argc, argv, "-q"))) {
-    QUIET = TRUE;
-    remove_argument (N, &argc, argv);
-  }
-
-  int UP_TRANSITIONS = TRUE;
-  if ((N = get_argument (argc, argv, "-dn"))) {
-    UP_TRANSITIONS = FALSE;
-    remove_argument (N, &argc, argv);
-  }
-  if ((N = get_argument (argc, argv, "-down"))) {
-    UP_TRANSITIONS = FALSE;
-    remove_argument (N, &argc, argv);
-  }
-  if ((N = get_argument (argc, argv, "-up"))) {
-    UP_TRANSITIONS = TRUE;
-    remove_argument (N, &argc, argv);
-  }
-
-  int BinMin = -1;
-  int BinMax = -1;
-  if ((N = get_argument (argc, argv, "-range"))) {
-    remove_argument (N, &argc, argv);
-    BinMin = atoi (argv[N]);
-    remove_argument (N, &argc, argv);
-    BinMax = atoi (argv[N]);
-    remove_argument (N, &argc, argv);
-  }
-
-  if (argc != 4) {
-    gprint (GP_ERR, "USAGE: vtransitions <x> <y> (value) (-up|-down,-dn) [-q] [-range BinMin BinMax]\n");
-    gprint (GP_ERR, "  find the x coordinates at which we pass the specified value going up\n");
-    gprint (GP_ERR, "  -q : quiet mode\n");
-    gprint (GP_ERR, "  -r : reverse (find downward transition)\n");
-    return (FALSE);
-  }
-  
-  if ((vecx = SelectVector (argv[1], OLDVECTOR, TRUE)) == NULL) return (FALSE);
-  if ((vecy = SelectVector (argv[2], OLDVECTOR, TRUE)) == NULL) return (FALSE);
-  if (vecx[0].Nelements != vecy[0].Nelements) return FALSE;
-  int Nelements = vecx[0].Nelements;
-  
-  if ((outbin = SelectVector ("vtr_bin", ANYVECTOR, TRUE)) == NULL) return (FALSE); // bins containing transitions
-  if ((outval = SelectVector ("vtr_val", ANYVECTOR, TRUE)) == NULL) return (FALSE); // value of bins containing transitions
-  if ((outpos = SelectVector ("vtr_pos", ANYVECTOR, TRUE)) == NULL) return (FALSE); // interpolated coordinate of transitions
-
-  double value = atof (argv[3]);
-  
-  isFltX = (vecx[0].type == OPIHI_FLT);
-  isFltY = (vecy[0].type == OPIHI_FLT);
-
-  // BinMin = -1 -> range not provide
-  if (BinMin == -1) {
-    BinMin = 0;
-    BinMax = Nelements - 1;
-  } else {
-    if ((BinMin >= vecx[0].Nelements) || (BinMin < -1*vecx[0].Nelements)) {
-      gprint (GP_ERR, "vector subscript out of range\n"); 
-      return FALSE;
-    }
-    if (BinMin < 0) BinMin += vecx[0].Nelements;
-    if ((BinMax >= vecx[0].Nelements) || (BinMax < -1*vecx[0].Nelements)) {
-      gprint (GP_ERR, "vector subscript out of range\n"); 
-      return FALSE;
-    }
-    if (BinMax < 0) BinMax += vecx[0].Nelements;
-  }
-
-  int Nout = 0;
-  int NOUT = 100;
-  ResetVector (outbin, OPIHI_INT,    NOUT);
-  ResetVector (outval, vecy[0].type, NOUT);
-  ResetVector (outpos, OPIHI_FLT,    NOUT);
-  
-  // starting disposition
-  int isUp = isFltY ? (vecy[0].elements.Flt[BinMin] > value) : (vecy[0].elements.Int[BinMin] > value);
-
-  for (int i = BinMin; i <= BinMax; i++) {
-    double testval = isFltY ? vecy[0].elements.Flt[i] : vecy[0].elements.Int[i];
-    if (isUp && (testval < value)) {
-      isUp = FALSE;
-      if (!UP_TRANSITIONS) {
-	// save this value
-	outbin->elements.Int[Nout] = i;
-	if (isFltY) {
-	  outval->elements.Flt[Nout] = testval;
-	} else {
-	  outval->elements.Int[Nout] = testval;
-	}
-	outpos->elements.Flt[Nout] = interpolate_position (vecx, vecy, i, value);
-	Nout ++;
-	if (Nout == NOUT) {
-	  NOUT += 100;
-	  ResetVector (outbin, OPIHI_INT,    NOUT);
-	  ResetVector (outval, vecy[0].type, NOUT);
-	  ResetVector (outpos, OPIHI_FLT,    NOUT);
-	}
-      }
-      continue;
-    }
-    if (!isUp && (testval > value)) {
-      isUp = TRUE;
-      if (UP_TRANSITIONS) {
-	// save this value
-	outbin->elements.Int[Nout] = i;
-	if (isFltY) {
-	  outval->elements.Flt[Nout] = testval;
-	} else {
-	  outval->elements.Int[Nout] = testval;
-	}
-	outpos->elements.Flt[Nout] = interpolate_position (vecx, vecy, i, value);
-	Nout ++;
-	if (Nout == NOUT) {
-	  NOUT += 100;
-	  ResetVector (outbin, OPIHI_INT,    NOUT);
-	  ResetVector (outval, vecy[0].type, NOUT);
-	  ResetVector (outpos, OPIHI_FLT,    NOUT);
-	}
-      }    
-    }
-  }
-
-  ResetVector (outbin, OPIHI_INT,    Nout);
-  ResetVector (outval, vecy[0].type, Nout);
-  ResetVector (outpos, OPIHI_FLT,    Nout);
-
-  if (!QUIET) gprint (GP_LOG, "found %d transitions\n", Nout);
-
-  return (TRUE);
-}
-
-static double interpolate_position (Vector *vecx, Vector *vecy, int bin, float value) {
-
-  double x0, x1, y0, y1, Xvalue;
-
-  if (vecy[0].Nelements == 0) return NAN;
-  if (vecy[0].Nelements == 1) return isFltY ? vecy[0].elements.Flt[0] : vecy[0].elements.Int[0];
-
-  if (bin == 0) {
-    // interpolate to value:
-    y0 = isFltY ? vecy[0].elements.Flt[bin] : vecy[0].elements.Int[bin];
-    y1 = isFltY ? vecy[0].elements.Flt[bin+1]   : vecy[0].elements.Int[bin+1];
-    x0 = isFltX ? vecx[0].elements.Flt[bin] : vecy[0].elements.Int[bin];
-    x1 = isFltX ? vecx[0].elements.Flt[bin+1]   : vecy[0].elements.Int[bin+1];
-    if (y0 == y1) {
-      Xvalue = 0.5*(x0 + x1);
-    } else {
-      Xvalue = (value - y0) * (x1 - x0) / (y1 - y0) + x0;
-    }    
-  } else {
-    // interpolate to value:
-    y0 = isFltY ? vecy[0].elements.Flt[bin-1] : vecy[0].elements.Int[bin-1];
-    y1 = isFltY ? vecy[0].elements.Flt[bin]   : vecy[0].elements.Int[bin];
-    x0 = isFltX ? vecx[0].elements.Flt[bin-1] : vecy[0].elements.Int[bin-1];
-    x1 = isFltX ? vecx[0].elements.Flt[bin]   : vecy[0].elements.Int[bin];
-    if (y0 == y1) {
-      Xvalue = 0.5*(x0 + x1);
-    } else {
-      Xvalue = (value - y0) * (x1 - x0) / (y1 - y0) + x0;
-    }
-  }
-  return Xvalue;
-}
Index: trunk/Ohana/src/opihi/cmd.data/vwtmean.c
===================================================================
--- trunk/Ohana/src/opihi/cmd.data/vwtmean.c	(revision 41326)
+++ 	(revision )
@@ -1,70 +1,0 @@
-# include "data.h"
-
-double opihi_wt_mean_dbl (double *val, double *wgt, int N, double *Sigma);
-
-int vwtmean (int argc, char **argv) {
-  
-  if (argc != 3) {
-    gprint (GP_ERR, "USAGE: vwtmean (values) (sigmas)\n");
-    gprint (GP_ERR, "NOTE: sigmas with abs values < %e will be truncated to that value\n", FLT_MIN);
-    return (FALSE);
-  }
-
-  Vector *value, *sigma;
-
-  if ((value = SelectVector (argv[1], OLDVECTOR, TRUE)) == NULL) return (FALSE);
-  if ((sigma = SelectVector (argv[2], OLDVECTOR, TRUE)) == NULL) return (FALSE);
-
-  if (value->Nelements != sigma->Nelements) {
-    gprint (GP_ERR, "vectors are not the same length\n");
-    return FALSE;
-  }
-  if (value->type != OPIHI_FLT) {
-    gprint (GP_ERR, "%s is not a floating point vector\n", argv[1]);
-    return FALSE;
-  }
-  if (sigma->type != OPIHI_FLT) {
-    gprint (GP_ERR, "%s is not a floating point vector\n", argv[2]);
-    return FALSE;
-  }
-
-  ALLOCATE_PTR (val, opihi_flt, value->Nelements);
-  ALLOCATE_PTR (wgt, opihi_flt, value->Nelements);
-
-  int N = 0;
-  for (int i = 0; i < value->Nelements; i++) {
-    if (!isfinite(value->elements.Flt[i])) continue;
-
-    double s = sigma->elements.Flt[i];
-    if (!isfinite(s)) continue;
-
-    if (fabs(s) < FLT_MIN) s = FLT_MIN;
-
-    val[N] = value->elements.Flt[i];
-    wgt[N] = 1.0 / SQ(s);
-    N ++;
-  }
-
-  double Sigma = NAN;
-  double Value = opihi_wt_mean_dbl (val, wgt, N, &Sigma);
-
-  set_variable ("WTMEAN",     Value);
-  set_variable ("WTSIGMA",    Sigma);
-  set_int_variable ("NUSED", N);
-  return (TRUE);
-}
-
-double opihi_wt_mean_dbl (double *val, double *wgt, int N, double *Sigma) {
-
-  // calculate weighted mean
-  double S1 = 0.0, S2 = 0.0;
-  for (int n = 0; n < N; n++) {
-    S1 += wgt[n] * val[n];
-    S2 += wgt[n];
-  }
-  double Value = S1 / S2;
-  *Sigma = 1.0 / S2;
-  
-  return Value;
-}
-
Index: trunk/Ohana/src/opihi/cmd.data/write_vectors.c
===================================================================
--- trunk/Ohana/src/opihi/cmd.data/write_vectors.c	(revision 41326)
+++ trunk/Ohana/src/opihi/cmd.data/write_vectors.c	(revision 41340)
@@ -32,23 +32,12 @@
   }
 
-  // option generate a FITS output table (FITS holds the filename) 
-  // in FITS output context, -header is interpretted as a buffer containing
-  // header keywords to supplement the FITS table header
+  /* option generate a FITS output table */
   char *FITS = NULL;
-  Header *fitsheader = NULL;
-  Buffer *headbuffer = NULL;
   if ((N = get_argument (argc, argv, "-fits"))) {
     remove_argument (N, &argc, argv);
     FITS = strcreate (argv[N]);
     remove_argument (N, &argc, argv);
-
-    if ((N = get_argument (argc, argv, "-header"))) {
-      remove_argument (N, &argc, argv);
-      if ((headbuffer = SelectBuffer (argv[N], OLDBUFFER, TRUE)) == NULL) return (FALSE);
-      fitsheader = &headbuffer->header;
-      remove_argument (N, &argc, argv);
-    }
-  }
-  
+  }
+
   /* option generate a FITS output table */
   int CSV = FALSE;
@@ -135,5 +124,5 @@
 
   if (FITS) {
-    int status = WriteVectorTableFITS (argv[1], FITS, fitsheader, vec, Nvec, append, compress, format, Ntile);
+    int status = WriteVectorTableFITS (argv[1], FITS, vec, Nvec, append, compress, format, Ntile);
     free (vec);
     return status;
@@ -154,8 +143,8 @@
   if (ADD_HEADER) {
     for (j = 0; j < Nvec; j++) {
-      if (j == 0) fprintf (f, "# ");
       if (CSV) {
 	fprintf (f, "%s,", vec[j][0].name);
       } else {
+	if (j == 0) fprintf (f, "# ");
 	fprintf (f, "%s ", vec[j][0].name);
       }
@@ -166,17 +155,18 @@
   /* default output format */
   if (format == (char *) NULL) {
-    char padChar = CSV ? ',' : ' ';
     for (i = 0; i < vec[0][0].Nelements; i++) {
       for (j = 0; j < Nvec; j++) {
-	switch (vec[j][0].type) {
-	  case OPIHI_FLT:
-	    fprintf (f, "%.12g%c", vec[j][0].elements.Flt[i], padChar);
-	    break;
-	  case OPIHI_INT:
-	    fprintf (f, OPIHI_INT_FMT"%c", vec[j][0].elements.Int[i], padChar);
-	    break;
-	  case OPIHI_STR:
-	    fprintf (f, "%s%c", vec[j][0].elements.Str[i], padChar);
-	    break;
+	if (vec[j][0].type == OPIHI_FLT) {
+	  if (CSV) {
+	    fprintf (f, "%.12g,", vec[j][0].elements.Flt[i]);
+	  } else {
+	    fprintf (f, "%.12g ", vec[j][0].elements.Flt[i]);
+	  }
+	} else {
+	  if (CSV) {
+	    fprintf (f, OPIHI_INT_FMT",", vec[j][0].elements.Int[i]);
+	  } else {
+	    fprintf (f, OPIHI_INT_FMT" ", vec[j][0].elements.Int[i]);
+	  }
 	}
       }
@@ -225,9 +215,6 @@
 	fmttype[j] = 'd';
 	break;
-      case 's':
-	fmttype[j] = 's';
-	break;
       default:
-	gprint (GP_ERR, "syntax error in format (only e,f,d,c,x,s allowed)\n");
+	gprint (GP_ERR, "syntax error in format (only e,f,d,c,x allowed)\n");
 	return (FALSE);
     }
@@ -236,23 +223,4 @@
   strcat (fmtlist[Nvec-1], p0);
   
-  // check format types against vector types:
-  for (j = 0; j < Nvec; j++) {
-    switch (vec[j][0].type) {
-      case OPIHI_FLT:
-      case OPIHI_INT:
-	if (fmttype[j] == 's') {
-	  gprint (GP_ERR, "mismatch between string format and numerical vector for %s\n", vec[j][0].name);
-	  return FALSE;
-	}
-	break;
-      case OPIHI_STR:
-	if (fmttype[j] != 's') {
-	  gprint (GP_ERR, "mismatch between numerical format and string vector for %s\n", vec[j][0].name);
-	  return FALSE;
-	}
-	break;
-    }
-  }
-
   for (i = 0; i < vec[0][0].Nelements; i++) {
     for (j = 0; j < Nvec; j++) {
@@ -271,7 +239,4 @@
 	}
       } 
-      if (fmttype[j] == 's') {
-	fprintf (f, fmtlist[j], vec[j][0].elements.Str[i]);
-      } 
     }
     fprintf (f, "\n");
@@ -295,6 +260,4 @@
     gprint (GP_ERR, "  -append : write to the end of the existing file\n");
     gprint (GP_ERR, "  -fits NAME : write a fits table (extention name is NAME, column names match vector names)\n");
-    gprint (GP_ERR, "     in FITS output context, -header takes an additional argument which is interpretted\n");
-    gprint (GP_ERR, "     as a buffer containing header keywords to supplement the FITS table header\n");
     gprint (GP_ERR, "  -csv : write a comma-separated values file (eg, to read in excel)\n");
     gprint (GP_ERR, "  -f \"format\" : provide formatting codes for output:\n");
Index: trunk/Ohana/src/opihi/dvo/Makefile
===================================================================
--- trunk/Ohana/src/opihi/dvo/Makefile	(revision 41326)
+++ trunk/Ohana/src/opihi/dvo/Makefile	(revision 41340)
@@ -67,5 +67,4 @@
 $(SRC)/gstar.$(ARCH).o		  	\
 $(SRC)/hosts.$(ARCH).o	  	\
-$(SRC)/cimages.$(ARCH).o	  	\
 $(SRC)/images.$(ARCH).o	  	\
 $(SRC)/imbox.$(ARCH).o		  	\
Index: trunk/Ohana/src/opihi/dvo/avextract.c
===================================================================
--- trunk/Ohana/src/opihi/dvo/avextract.c	(revision 41326)
+++ trunk/Ohana/src/opihi/dvo/avextract.c	(revision 41340)
@@ -272,5 +272,5 @@
   // write vectors to a table (this is used by parallel dvo operations, but can be used elsewhere)
   if (RESULT_FILE && !SKIP_RESULTS) {
-    int status = WriteVectorTableFITS (RESULT_FILE, "RESULT", NULL, vec, Nreturn, FALSE, FALSE, NULL, 0);
+    int status = WriteVectorTableFITS (RESULT_FILE, "RESULT", vec, Nreturn, FALSE, FALSE, NULL, 0);
     if (!status) {
       goto escape;
Index: trunk/Ohana/src/opihi/dvo/avmatch.c
===================================================================
--- trunk/Ohana/src/opihi/dvo/avmatch.c	(revision 41326)
+++ trunk/Ohana/src/opihi/dvo/avmatch.c	(revision 41340)
@@ -114,5 +114,5 @@
 
       CoordsFile = abspath("coords.fits", 1024);
-      int status = WriteVectorTableFITS (CoordsFile, "COORDS", NULL, vec, 2, FALSE, FALSE, NULL, 0);
+      int status = WriteVectorTableFITS (CoordsFile, "COORDS", vec, 2, FALSE, FALSE, NULL, 0);
       if (!status) goto escape;
     }
@@ -301,5 +301,5 @@
       vec[i][0].Nelements = Nfound;
     }
-    int status = WriteVectorTableFITS (RESULT_FILE, "RESULT", NULL, vec, Nfields + 1, FALSE, FALSE, NULL, 0);
+    int status = WriteVectorTableFITS (RESULT_FILE, "RESULT", vec, Nfields + 1, FALSE, FALSE, NULL, 0);
     free (vec[Nfields]->elements.Int);
     free (vec[Nfields]);
Index: trunk/Ohana/src/opihi/dvo/avperiodomatch.c
===================================================================
--- trunk/Ohana/src/opihi/dvo/avperiodomatch.c	(revision 41326)
+++ trunk/Ohana/src/opihi/dvo/avperiodomatch.c	(revision 41340)
@@ -99,5 +99,5 @@
 
       CoordsFile = abspath("coords.fits", 1024);
-      int status = WriteVectorTableFITS (CoordsFile, "COORDS", NULL, vec, 2, FALSE, FALSE, NULL, 0);
+      int status = WriteVectorTableFITS (CoordsFile, "COORDS", vec, 2, FALSE, FALSE, NULL, 0);
       if (!status) goto escape;
       free (vec);
Index: trunk/Ohana/src/opihi/dvo/avselect.c
===================================================================
--- trunk/Ohana/src/opihi/dvo/avselect.c	(revision 41326)
+++ trunk/Ohana/src/opihi/dvo/avselect.c	(revision 41340)
@@ -132,5 +132,5 @@
 
       CoordsFile = abspath("coords.fits", 1024);
-      int status = WriteVectorTableFITS (CoordsFile, "COORDS", NULL, vec, 2, FALSE, FALSE, NULL, 0);
+      int status = WriteVectorTableFITS (CoordsFile, "COORDS", vec, 2, FALSE, FALSE, NULL, 0);
       if (!status) goto escape;
     }
@@ -327,5 +327,5 @@
       vec[NfieldsOut-1] = RADvec;
     }
-    int status = WriteVectorTableFITS (RESULT_FILE, "RESULT", NULL, vec, NfieldsOut, FALSE, FALSE, NULL, 0);
+    int status = WriteVectorTableFITS (RESULT_FILE, "RESULT", vec, NfieldsOut, FALSE, FALSE, NULL, 0);
     if (!status) goto escape;
   }
Index: trunk/Ohana/src/opihi/dvo/cimages.c
===================================================================
--- trunk/Ohana/src/opihi/dvo/cimages.c	(revision 41326)
+++ 	(revision )
@@ -1,379 +1,0 @@
-# include "dvoshell.h"
-# define BETA 0.41421
-
-int wordhash (char *word);
-
-int cimages (int argc, char **argv) {
-
-  off_t i, Nimage, Nmosaic;
-  int j, status, InPic, leftside, TimeSelect, ByName;
-  int WITH_MOSAIC, SOLO_MOSAIC;
-  time_t tzero, tend;
-  int n, N, NPTS, Npts, kapa, *foundMosaic;
-  Vector Xvec, Yvec, Zvec;
-  double r[8], d[8], x[8], y[8], Rmin, Rmax, Rmid, trange, Radius;
-  Image *image;
-  Graphdata graphmode;
-  char name[256];
-  int typehash;
-  PhotCode *photcode;
-  int Nsec, photcodeEquiv;
-
-  if (!InitPhotcodes ()) return (FALSE);
-  if (!style_args (&graphmode, &argc, argv, &kapa)) goto usage;
-
-  WITH_MOSAIC = FALSE;
-  if ((N = get_argument (argc, argv, "+mosaic"))) {
-    remove_argument (N, &argc, argv);
-    WITH_MOSAIC = TRUE;
-  }
-
-  SOLO_MOSAIC = FALSE;
-  foundMosaic = NULL;
-  if ((N = get_argument (argc, argv, "-mosaic"))) {
-    remove_argument (N, &argc, argv);
-    SOLO_MOSAIC = TRUE;
-    WITH_MOSAIC = TRUE;
-  }
-
-  // int HIDDEN = FALSE;
-  // if ((N = get_argument (argc, argv, "-hidden"))) {
-  //   remove_argument (N, &argc, argv);
-  //   HIDDEN = TRUE;
-  // }
-
-  photcode = NULL;
-  photcodeEquiv = FALSE;
-  if ((N = get_argument (argc, argv, "-p"))) {
-    remove_argument (N, &argc, argv);
-    photcode = GetPhotcodebyName (argv[N]);
-    if (photcode == NULL) {
-      gprint (GP_ERR, "photcode %s not found\n", argv[N]);
-      return FALSE;
-    }
-    remove_argument (N, &argc, argv);
-    Nsec = GetPhotcodeNsec (photcode->code);
-    if (Nsec != -1) photcodeEquiv = TRUE;
-  }
-  if ((N = get_argument (argc, argv, "-photcode"))) {
-    remove_argument (N, &argc, argv);
-    photcode = GetPhotcodebyName (argv[N]);
-    if (photcode == NULL) {
-      gprint (GP_ERR, "photcode %s not found\n", argv[N]);
-      return FALSE;
-    }
-    remove_argument (N, &argc, argv);
-    Nsec = GetPhotcodeNsec (photcode->code);
-    if (Nsec != -1) photcodeEquiv = TRUE;
-  }
-
-  ByName = FALSE;
-  if ((N = get_argument (argc, argv, "-name"))) {
-    remove_argument (N, &argc, argv);
-    strcpy (name, argv[N]);
-    remove_argument (N, &argc, argv);
-    ByName = TRUE;
-  }
-
-  Radius = 45;
-  if ((N = get_argument (argc, argv, "-radius"))) {
-    remove_argument (N, &argc, argv);
-    Radius = atof (argv[N]);
-    remove_argument (N, &argc, argv);
-  }
-
-  TimeSelect = FALSE;
-  if ((N = get_argument (argc, argv, "-time"))) {
-    remove_argument (N, &argc, argv);
-    if (!ohana_str_to_time (argv[N], &tzero)) {
-      gprint (GP_ERR, "syntax error\n");
-      goto usage;
-    }
-    remove_argument (N, &argc, argv);
-    if (!ohana_str_to_dtime (argv[N], &trange)) { 
-      gprint (GP_ERR, "syntax error\n");
-      goto usage;
-    }
-    remove_argument (N, &argc, argv);
-    if (trange < 0) {
-      trange = fabs (trange);
-      tzero -= trange;
-    }
-    TimeSelect = TRUE;
-  }
-  if ((N = get_argument (argc, argv, "-trange"))) {
-    remove_argument (N, &argc, argv);
-    if (!ohana_str_to_time (argv[N], &tzero)) { 
-      gprint (GP_ERR, "syntax error\n");
-      goto usage;
-    }
-    remove_argument (N, &argc, argv);
-    if (!ohana_str_to_time (argv[N], &tend)) { 
-      gprint (GP_ERR, "syntax error\n");
-      goto usage;
-    }
-    remove_argument (N, &argc, argv);
-    trange = tend - tzero;
-    if (trange < 0) {
-      trange = fabs (trange);
-      tzero -= trange;
-    }
-    TimeSelect = TRUE;
-  }
- 
-  if (argc != 3) goto usage;
-  float vmin = atof (argv[1]);
-  float vmax = atof (argv[2]);
-
-  /* it is not an error for the database not to have any images */
-  if ((image = LoadImagesDVO (&Nimage)) == NULL) return (TRUE);
-  // BuildChipMatch (image, Nimage);
-
-  if (SOLO_MOSAIC && photcode) {
-    ALLOCATE(foundMosaic, int, Nimage);
-    memset(foundMosaic, 0, Nimage*sizeof(int));
-  }
-
-  Rmin = graphmode.coords.crval1 - 180.0;
-  Rmax = graphmode.coords.crval1 + 180.0;
-  Rmid = 0.5*(Rmin + Rmax);
-  
-  int DistortImage = wordhash ("-DIS");
-  int ChipImage    = wordhash ("-WRP");
-  int TriangleUp   = wordhash ("TRP-");
-  int TriangleDn   = wordhash ("TRM-");
-  int TrianglePts  = wordhash ("TRI-");
-
-  NPTS = 200;
-  SetVector (&Xvec, OPIHI_FLT, NPTS);
-  SetVector (&Yvec, OPIHI_FLT, NPTS);
-  SetVector (&Zvec, OPIHI_FLT, NPTS);
-
-  Image *mosaic = NULL;
-
-  /******** stage 1 : find the images to plot *********/
-
-  n = 0; // tracks number of images
-  N = 0; // tracks number of vertices
-  for (i = 0; i < Nimage; i++) {
-    if (ByName && strncmp (image[i].name, name, strlen(name))) continue;
-    if (TimeSelect && ((image[i].tzero < tzero) || (image[i].tzero+image[i].trate*image[i].NY > tzero + trange))) continue;
-
-    mosaic = image[i].parent;
-    Nmosaic = (SOLO_MOSAIC && mosaic) ? mosaic - image : -1;
-
-    if (photcode) {
-      if ( photcodeEquiv && (photcode[0].code != GetPhotcodeEquivCodebyCode(image[i].photcode))) continue;
-      if (!photcodeEquiv && (photcode[0].code != image[i].photcode)) continue;
-    }
-
-    Npts = 4;
-    status = TRUE;
-    leftside = FALSE;
-
-    typehash = wordhash (&image[i].coords.ctype[4]);
-
-    if (photcode && SOLO_MOSAIC && (Nmosaic >= 0)) {
-      // mosaic (DIS) images are not currently given a photcode : plot these via the WRP entries
-      /* DIS images represent a field, not a chip */
-      if (typehash != ChipImage) continue;
-      if (foundMosaic[Nmosaic]) continue;
-      x[0] = -0.5*mosaic->NX; y[0] = -0.5*mosaic->NY;
-      x[1] = +0.5*mosaic->NX; y[1] = -0.5*mosaic->NY;
-      x[2] = +0.5*mosaic->NX; y[2] = +0.5*mosaic->NY;
-      x[3] = -0.5*mosaic->NX; y[3] = +0.5*mosaic->NY;
-      for (j = 0; j < Npts; j++) {
-	status = XY_to_RD (&r[j], &d[j], x[j], y[j], &mosaic->coords);
-	if (!status) break;
-	r[j] = ohana_normalize_angle (r[j]);
-	while (r[j] < Rmin) { r[j] += 360.0; }
-	while (r[j] > Rmax) { r[j] -= 360.0; }
-	if (j == 0) {
-	  leftside = (r[j] < Rmid);
-	} 
-	if (j > 0) { 
-	  if ( leftside && (r[j] > Rmid + 90)) { r[j] -= 360.0; }
-	  if (!leftside && (r[j] < Rmid - 90)) { r[j] += 360.0; }
-	}
-      }
-      foundMosaic[Nmosaic] = TRUE;
-      goto plot_points;
-    }
-
-    /* DIS images represent a field, not a chip */
-    if ((typehash == DistortImage) && !WITH_MOSAIC) continue; // do not plot the mosaic images
-    if ((typehash != DistortImage) &&  SOLO_MOSAIC) continue; // plot only the mosaic images
-
-    if (typehash == DistortImage) {
-      x[0] = -0.5*image[i].NX; y[0] = -0.5*image[i].NY;
-      x[1] = +0.5*image[i].NX; y[1] = -0.5*image[i].NY;
-      x[2] = +0.5*image[i].NX; y[2] = +0.5*image[i].NY;
-      x[3] = -0.5*image[i].NX; y[3] = +0.5*image[i].NY;
-      goto got_type;
-    }
-
-    typehash = wordhash (image[i].coords.ctype);
-    if (typehash == TriangleUp) {
-      Npts = 3;
-      x[0] =                0; y[0] = +0.5*image[i].NY;
-      x[1] = +0.5*image[i].NX; y[1] = -0.5*image[i].NY;
-      x[2] = -0.5*image[i].NX; y[2] = -0.5*image[i].NY;
-      goto got_type;
-    }
-    if (typehash == TriangleDn) {
-      Npts = 3;
-      x[0] =                0; y[0] = -0.5*image[i].NY;
-      x[1] = +0.5*image[i].NX; y[1] = +0.5*image[i].NY;
-      x[2] = -0.5*image[i].NX; y[2] = +0.5*image[i].NY;
-      goto got_type;
-    }
-    // For 'TrianglePts' (TRI-), we are absurdly overloaded values otherwise not used
-    if (typehash == TrianglePts) {
-      Npts = 3;
-      x[0] = image[0].dXpixSys;      y[0] = image[0].dYpixSys;
-      x[1] = image[0].dMagSys;       y[1] = image[0].nFitAstrom;
-      x[2] = image[0].photom_map_id; y[2] = image[0].astrom_map_id;
-      goto got_type;
-    }
-
-    // default layout
-    {
-      x[0] = 0;           y[0] = 0;
-      x[1] = image[i].NX; y[1] = 0;
-      x[2] = image[i].NX; y[2] = image[i].NY;
-      x[3] = 0;           y[3] = image[i].NY;
-    }
-
-  got_type:
-
-    /**** project this image to screen display coords ****/
-
-    // check for boundary overlap?
-    for (j = 0; j < Npts; j++) {
-      status = XY_to_RD (&r[j], &d[j], x[j], y[j], &image[i].coords);
-      if (!status) break;
-      r[j] = ohana_normalize_angle (r[j]);
-      while (r[j] < Rmin) { r[j] += 360.0; }
-      while (r[j] > Rmax) { r[j] -= 360.0; }
-      if (j == 0) {
-	leftside = (r[j] < Rmid);
-      } 
-      if (j > 0) { 
-	if ( leftside && (r[j] > Rmid + 90)) { r[j] -= 360.0; }
-	if (!leftside && (r[j] < Rmid - 90)) { r[j] += 360.0; }
-      }
-    }
-
-   // extremely large-scale images with certain projections will have odd boundaries.
-    // eg, the ASCA images are essentially circles of radius ~60 degrees.  plot these as 
-    // octagons with some dummy size.
-    if (!status) {
-      int jp, xo, yo;
-      double rc, dc;
-      xo = 0.5*image[i].NX;
-      yo = 0.5*image[i].NY;
-      // is the image center on the screen?
-      status = XY_to_RD (&rc, &dc, 0.5*x[2], 0.5*y[2], &image[i].coords);
-      if (status && (image[i].NX * image[i].coords.cdelt2 > 90)) {
-	// draw an octagon with radius 45 degrees
-	double dX = Radius / image[i].coords.cdelt2;
-	x[0] = xo+dX;      y[0] = yo+BETA*dX;
-	x[1] = xo+BETA*dX; y[1] = yo+dX;
-	x[2] = xo-BETA*dX; y[2] = yo+dX;
-	x[3] = xo-dX;      y[3] = yo+BETA*dX;
-	x[4] = xo-dX;      y[4] = yo-BETA*dX;
-	x[5] = xo-BETA*dX; y[5] = yo-dX;
-	x[6] = xo+BETA*dX; y[6] = yo-dX;
-	x[7] = xo+dX;      y[7] = yo-BETA*dX;
-	Npts = 8;
-	j = 0;
-	for (jp = 0; jp < 8; jp++) {
-	  status = XY_to_RD (&r[j], &d[j], x[jp], y[jp], &image[i].coords);
-	  if (!status) continue;
-	  r[j] = ohana_normalize_angle (r[j]);
-	  while (r[j] < Rmin) { r[j] += 360.0; }
-	  while (r[j] > Rmax) { r[j] -= 360.0; }
-	  if (j == 0) {
-	    leftside = (r[j] < Rmid);
-	  } 
-	  if (j > 0) { 
-	    if ( leftside && (r[j] > Rmid + 90)) { r[j] -= 360.0; }
-	    if (!leftside && (r[j] < Rmid - 90)) { r[j] += 360.0; }
-	  }
-	  j++;
-	}
-	Npts = j;
-      } else {
-	continue;
-      }
-    }
-    if (Npts == 0) continue;
-
-  plot_points:
-
-    /**** transform corners to screen coordinates ******/
-
-    status = FALSE;
-    for (j = 0; j < Npts; j++) {
-      status |= RD_to_XY (&Xvec.elements.Flt[N+j], &Yvec.elements.Flt[N+j], r[j], d[j], &graphmode.coords);
-      Zvec.elements.Flt[N+j] = MIN(1.0, MAX(0.01, (image[i].exptime - vmin) / (vmax - vmin)));
-    }
-    if (!status) continue;
-    // if none of the points are on the visible side of the projection, do not plot the image
-
-    InPic = FALSE;
-    for (j = 0; j < Npts; j++) {
-      if ((Xvec.elements.Flt[N+j] >= graphmode.xmin) && 
-	  (Xvec.elements.Flt[N+j] <= graphmode.xmax) && 
-	  (Yvec.elements.Flt[N+j] >= graphmode.ymin) && 
-	  (Yvec.elements.Flt[N+j] <= graphmode.ymax))
-	InPic = TRUE;
-    }
-    // if (!status && HIDDEN) status = TRUE;
-    if (!InPic) continue;
-
-    n ++;
-    N += Npts;
-    if (N + 16 >= NPTS) {  /* need to leave room for 8 point image */
-      NPTS += 400;
-      REALLOCATE (Xvec.elements.Flt, opihi_flt, NPTS);
-      REALLOCATE (Yvec.elements.Flt, opihi_flt, NPTS);
-      REALLOCATE (Zvec.elements.Flt, opihi_flt, NPTS);
-    }
-  }
-
-  gprint (GP_ERR, "plotting %d images\n", n);
-  Xvec.Nelements = Yvec.Nelements = Zvec.Nelements = N;
-  if (N > 0) {
-    // XXX note that ptype limits us to plot only a single type of
-    // image in a single pass
-    graphmode.style = KAPA_PLOT_POLYFILL; /* points */
-    graphmode.ptype = Npts; /* connect pairs of points */
-    graphmode.etype = 0;
-    graphmode.size = -1; /* point size determined by Zvec */
-    graphmode.color = -1; // use z-vec for color
-    PlotVectorTriplet (kapa, &Xvec, &Yvec, &Zvec, NULL, &graphmode);
-//  PlotVectorPair (kapa, &Xvec, &Yvec, NULL, &graphmode);
-  }
-
-  FREE (Xvec.elements.Flt);
-  FREE (Yvec.elements.Flt);
-  FREE (Zvec.elements.Flt);
-  FreeImagesDVO (image);
-  FREE (foundMosaic);
-  return (TRUE);
-
-
- usage:
-  gprint (GP_ERR, "USAGE: cimage (vmin) (vmax) [options]\n");
-  gprint (GP_ERR, "  +mosaic : show mosaic outline\n");
-  gprint (GP_ERR, "  -mosaic : only mosaic outline\n");
-  gprint (GP_ERR, "  -hidden : (deprecated)\n");
-  gprint (GP_ERR, "  -name   : only names matching (start of name)\n");
-  gprint (GP_ERR, "  -radius : display all-sky images with given radius octagon\n");
-  gprint (GP_ERR, "  -time (start) (range)  : show images for time and interval\n");
-  gprint (GP_ERR, "  -trange (start) (stop) : show images within time range\n");
-  return (FALSE);
-}
-
-
Index: trunk/Ohana/src/opihi/dvo/dvo_host_utils.c
===================================================================
--- trunk/Ohana/src/opihi/dvo/dvo_host_utils.c	(revision 41326)
+++ trunk/Ohana/src/opihi/dvo/dvo_host_utils.c	(revision 41340)
@@ -233,5 +233,5 @@
   // write vectors to a table (this is used by parallel dvo operations, but can be used elsewhere)
   if (ResultFile) {
-    int status = WriteVectorTableFITS (ResultFile, "RESULT", NULL, vec, Nvec, FALSE, FALSE, NULL, 0);
+    int status = WriteVectorTableFITS (ResultFile, "RESULT", vec, Nvec, FALSE, FALSE, NULL, 0);
     if (!status) {
       gprint (GP_ERR, "failed to write result file %s\n", ResultFile);
Index: trunk/Ohana/src/opihi/dvo/images.c
===================================================================
--- trunk/Ohana/src/opihi/dvo/images.c	(revision 41326)
+++ trunk/Ohana/src/opihi/dvo/images.c	(revision 41340)
@@ -12,9 +12,8 @@
 
   off_t i, Nimage, Nmosaic;
-  int j, status, InPic, leftside, TimeSelect, ByName;
-  // int *plist, n, npts; -- what is/was plist?
+  int j, status, InPic, leftside, *plist, TimeSelect, ByName;
   int WITH_MOSAIC, SOLO_MOSAIC;
   time_t tzero, tend;
-  int n, N, NPTS, Npts, kapa, *foundMosaic;
+  int N, NPTS, n, npts, Npts, kapa, *foundMosaic;
   Vector Xvec, Yvec;
   double r[8], d[8], x[8], y[8], Rmin, Rmax, Rmid, trange, Radius;
@@ -149,6 +148,5 @@
   int TrianglePts  = wordhash ("TRI-");
 
-  // npts = 200
-  NPTS = 200;
+  npts = NPTS = 200;
   SetVector (&Xvec, OPIHI_FLT, NPTS);
   SetVector (&Yvec, OPIHI_FLT, NPTS);
@@ -156,9 +154,6 @@
   Image *mosaic = NULL;
 
-  /******** stage 1 : find the images to plot *********/
-
-  // ALLOCATE (plist, int, NPTS);
-  n = 0; // tracks number of images
-  N = 0; // tracks number of vertices
+  ALLOCATE (plist, int, NPTS);
+  n = N = 0;
   for (i = 0; i < Nimage; i++) {
     if (ByName && strncmp (image[i].name, name, strlen(name))) continue;
@@ -340,12 +335,11 @@
     if (!InPic) continue;
 
-    // plist[n] = i;
-    // n++;
-    // if (n > npts - 1) {
-    //   npts += 200;
-    //   REALLOCATE (plist, int, npts);
-    // }
-    n ++;
-    N += 2*Npts;
+    plist[n] = i;
+    n++;
+    if (n > npts - 1) {
+      npts += 200;
+      REALLOCATE (plist, int, npts);
+    }
+    N+=2*Npts;
     if (N + 16 >= NPTS) {  /* need to leave room for 8 point image */
       NPTS += 400;
Index: trunk/Ohana/src/opihi/dvo/init.c
===================================================================
--- trunk/Ohana/src/opihi/dvo/init.c	(revision 41326)
+++ trunk/Ohana/src/opihi/dvo/init.c	(revision 41340)
@@ -14,5 +14,4 @@
 int catdir_define   PROTO((int, char **));
 int ccd             PROTO((int, char **));
-int cimages         PROTO((int, char **));
 int cmatch          PROTO((int, char **));
 int cmd             PROTO((int, char **));
@@ -81,5 +80,4 @@
   {1, "catdir",      catdir_define,"re-define CATDIR"},
 //  {1, "ccd",         ccd,          "plot color-color diagram"},
-  {1, "cimages",     cimages,      "fill image boxes with a color"},
   {1, "cmatch",      cmatch,       "match two catalogs"},
 //  {1, "cmd",         cmd,          "plot cmd of stars in current region"},
Index: trunk/Ohana/src/opihi/dvo/mextract.c
===================================================================
--- trunk/Ohana/src/opihi/dvo/mextract.c	(revision 41326)
+++ trunk/Ohana/src/opihi/dvo/mextract.c	(revision 41340)
@@ -352,5 +352,5 @@
   // write vectors to a table (this is used by parallel dvo operations, but can be used elsewhere)
   if (RESULT_FILE && !SKIP_RESULTS) {
-    int status = WriteVectorTableFITS (RESULT_FILE, "RESULT", NULL, vec, Nreturn, FALSE, FALSE, NULL, 0);
+    int status = WriteVectorTableFITS (RESULT_FILE, "RESULT", vec, Nreturn, FALSE, FALSE, NULL, 0);
     if (!status) goto escape;
   }
Index: trunk/Ohana/src/opihi/dvo/mmatch.c
===================================================================
--- trunk/Ohana/src/opihi/dvo/mmatch.c	(revision 41326)
+++ trunk/Ohana/src/opihi/dvo/mmatch.c	(revision 41340)
@@ -148,5 +148,5 @@
       // XXX this is now set for both cases...
       CoordsFile = abspath("coords.fits", 1024);
-      int status = WriteVectorTableFITS (CoordsFile, "COORDS", NULL, vec, 2, FALSE, FALSE, NULL, 0);
+      int status = WriteVectorTableFITS (CoordsFile, "COORDS", vec, 2, FALSE, FALSE, NULL, 0);
       if (!status) goto escape;
     }
@@ -349,5 +349,5 @@
       vec[Nfields-1] = IDXvec;
     }
-    int status = WriteVectorTableFITS (RESULT_FILE, "RESULT", NULL, vec, Nfields, FALSE, FALSE, NULL, 0);
+    int status = WriteVectorTableFITS (RESULT_FILE, "RESULT", vec, Nfields, FALSE, FALSE, NULL, 0);
     if (!status) goto escape;
   }
Index: trunk/Ohana/src/opihi/dvo/skyregion.c
===================================================================
--- trunk/Ohana/src/opihi/dvo/skyregion.c	(revision 41326)
+++ trunk/Ohana/src/opihi/dvo/skyregion.c	(revision 41340)
@@ -5,27 +5,4 @@
   
   int N;
-
-  // alternate call form: skyregion -box Rcenter Dcenter radius
-  if ((N = get_argument (argc, argv, "-box"))) {
-    if ((N != 1) && (argc != 5)) {
-      gprint (GP_ERR, "USAGE: skyregion -box (Rcenter) (Dcenter) (radius)\n");
-      gprint (GP_ERR, "  Rcenter, Dcenter, radius in decimal degrees\n");
-      return (FALSE);
-    }
-
-    // argv[1] = -box
-    double Rcenter = atof(argv[2]);
-    double Dcenter = atof(argv[3]);
-    double Radius  = atof(argv[4]);
-
-    double Rmin = Rcenter - Radius/cos(DEG_RAD*Dcenter);
-    double Rmax = Rcenter + Radius/cos(DEG_RAD*Dcenter);
-    double Dmin = Dcenter - Radius;
-    double Dmax = Dcenter + Radius;
-
-    set_skyregion (Rmin, Rmax, Dmin, Dmax);
-    return TRUE;
-  }
-  
 
   // dvo_client should have 2 standard arguments: -hostID and -hostdir
@@ -49,5 +26,4 @@
       gprint (GP_ERR, "current skyregion: %f - %f : %f - %f\n", Rmin, Rmax, Dmin, Dmax);
       gprint (GP_ERR, "USAGE:  skyregion (min RA) (max RA) (min DEC) (max DEC)\n");
-      gprint (GP_ERR, "        skyregion -box (RA) (DEC) (radius) [sets Rmin,Rmax & Dmin,Dmax]\n");
       return FALSE;
     }
Index: trunk/Ohana/src/opihi/include/data.h
===================================================================
--- trunk/Ohana/src/opihi/include/data.h	(revision 41326)
+++ trunk/Ohana/src/opihi/include/data.h	(revision 41340)
@@ -48,6 +48,5 @@
   int Nx;
   int Ny;
-  float **flx;
-  float **var;
+  float **buffers;
 } MedImageType;
 
Index: trunk/Ohana/src/opihi/include/deimos.h
===================================================================
--- trunk/Ohana/src/opihi/include/deimos.h	(revision 41326)
+++ trunk/Ohana/src/opihi/include/deimos.h	(revision 41340)
@@ -7,5 +7,5 @@
 } DeimosResult;
 
-float     *deimos_make_model (opihi_flt *obj, opihi_flt *sky, opihi_flt *bck, Vector *psf, Vector *profile, Spline *slit_trace_red, Spline *slit_trace_blu, float redlimit, Spline *psf_trace, int Nx, int Ny, int row);
+float     *deimos_make_model (opihi_flt *obj, opihi_flt *sky, opihi_flt *bck, Vector *psf, Vector *profile, Spline *trace, int Nx, int Ny, int row);
 void       deimos_make_kernel (float stilt, int Nx);
 void       deimos_free_kernel ();
@@ -13,8 +13,8 @@
 
 // internal to make_model:
-float     *deimos_make_straight_image (opihi_flt *obj, opihi_flt *sky, Vector *psf, Spline *psf_trace, int Nx, int Ny, int row);
+float     *deimos_make_straight_image (opihi_flt *obj, opihi_flt *sky, Vector *psf, int Nx, int Ny, int row);
 float     *deimos_apply_tilt (float *input, int Nx, int Ny);
 void       deimos_apply_profile (Vector *profile, float *out, int Nx, int Ny);
 void       deimos_add_background (opihi_flt *backgnd, float *out, int Nx, int Ny, int row);
-float     *deimos_apply_trace (Spline *slit_trace_red, Spline *slit_trace_blu, float redlimit, float *input, int Nx, int Ny, int row);
+float     *deimos_apply_trace (Spline *trace, float *input, int Nx, int Ny, int row);
 
Index: trunk/Ohana/src/opihi/include/dvomath.h
===================================================================
--- trunk/Ohana/src/opihi/include/dvomath.h	(revision 41326)
+++ trunk/Ohana/src/opihi/include/dvomath.h	(revision 41340)
@@ -6,7 +6,9 @@
 # define OPIHI_NAME_SIZE 1024
 
-/* OPIHI_FLT, OPIHI_INT and related are defined in libdvo/include/dvodb.h */
-
 # define NCHARS 256
+// # define opihi_flt double
+// # define opihi_int int
+// NOTE: if opihi_int is changed to unsigned, all subtraction and negation operations
+// need to result in a float value (or 3 - 5 will yield the unexpected value 2^32 - 2)
 
 # define REQUIRE_VECTOR_FLT(VECT,RVAL) { \
@@ -24,4 +26,7 @@
 enum {ANYVECTOR, NEWVECTOR, OLDVECTOR};
 enum {ANYBUFFER, NEWBUFFER, OLDBUFFER};
+#ifdef NOT_MOVED_TO_LIBDVO
+enum {OPIHI_FLT, OPIHI_INT};
+#endif
 
 typedef struct {			/* representation of a variable (0-D) */
@@ -35,5 +40,4 @@
   union {
     void      *Ptr;
-    char     **Str;
     opihi_flt *Flt;
     opihi_int *Int;
@@ -165,5 +169,5 @@
 
 /* vector IO functions */
-int           WriteVectorTableFITS  PROTO((char *filename, char *extname, Header *extraheader, Vector **vec, int Nvec, int append, char *compress, char *format, int Ntile));
+int           WriteVectorTableFITS  PROTO((char *filename, char *extname, Vector **vec, int Nvec, int append, char *compress, char *format, int Ntile));
 Vector      **ReadVectorTableFITS   PROTO((char *filename, char *extname, int *Nvec));
 
Index: trunk/Ohana/src/opihi/lib.data/MedImageOps.c
===================================================================
--- trunk/Ohana/src/opihi/lib.data/MedImageOps.c	(revision 41326)
+++ trunk/Ohana/src/opihi/lib.data/MedImageOps.c	(revision 41340)
@@ -32,9 +32,7 @@
   free (medimage[0].name);
   for (i = 0; i < medimage[0].Ninput; i++) {
-    free (medimage[0].flx[i]);
-    FREE (medimage[0].var[i]);
+    free (medimage[0].buffers[i]);
   }
-  free (medimage[0].flx);
-  free (medimage[0].var);
+  free (medimage[0].buffers);
   free (medimage);
 }
@@ -77,6 +75,5 @@
   medimage->Nx = Nx;
   medimage->Ny = Ny;
-  ALLOCATE (medimage->flx, float *, 1);
-  ALLOCATE (medimage->var, float *, 1);
+  ALLOCATE (medimage->buffers, float *, 1);
 
   medimages[N] = medimage;
Index: trunk/Ohana/src/opihi/lib.data/SplineOps.c
===================================================================
--- trunk/Ohana/src/opihi/lib.data/SplineOps.c	(revision 41326)
+++ trunk/Ohana/src/opihi/lib.data/SplineOps.c	(revision 41340)
@@ -41,9 +41,7 @@
     ALLOCATE (spline[0].y2, opihi_flt, spline[0].Nknots);
   }
-  if (spline[0].Nknots) {
-    memset (spline[0].xk, 0, spline[0].Nknots * sizeof(opihi_flt));
-    memset (spline[0].yk, 0, spline[0].Nknots * sizeof(opihi_flt));
-    memset (spline[0].y2, 0, spline[0].Nknots * sizeof(opihi_flt));
-  }
+  memset (spline[0].xk, 0, spline[0].Nknots * sizeof(opihi_flt));
+  memset (spline[0].yk, 0, spline[0].Nknots * sizeof(opihi_flt));
+  memset (spline[0].y2, 0, spline[0].Nknots * sizeof(opihi_flt));
 }
 
@@ -181,7 +179,7 @@
 
   // NOTE: if we want to compress the output table, use native byte order here (last element)
-  gfits_set_bintable_column_reformat (&theader, &ftable, "X_KNOT", "double", myspline->xk, myspline->Nknots, 0, FALSE);
-  gfits_set_bintable_column_reformat (&theader, &ftable, "Y_KNOT", "double", myspline->yk, myspline->Nknots, 0, FALSE);
-  gfits_set_bintable_column_reformat (&theader, &ftable, "DY2_DX", "double", myspline->y2, myspline->Nknots, 0, FALSE);
+  gfits_set_bintable_column_reformat (&theader, &ftable, "X_KNOT", "double", myspline->xk, myspline->Nknots, FALSE);
+  gfits_set_bintable_column_reformat (&theader, &ftable, "Y_KNOT", "double", myspline->yk, myspline->Nknots, FALSE);
+  gfits_set_bintable_column_reformat (&theader, &ftable, "DY2_DX", "double", myspline->y2, myspline->Nknots, FALSE);
 
   if (!append) {
Index: trunk/Ohana/src/opihi/lib.data/open_kapa.c
===================================================================
--- trunk/Ohana/src/opihi/lib.data/open_kapa.c	(revision 41326)
+++ trunk/Ohana/src/opihi/lib.data/open_kapa.c	(revision 41340)
@@ -266,5 +266,4 @@
 int close_kapa (char *name) {
 
-  struct timespec request, remain;
   int N;
 
@@ -275,24 +274,4 @@
   }
   DelKapaDevice (name);
-
-  // avoid blocking on waitpid, test every 1 msec, up to 500 msec
-  request.tv_sec = 0;
-  request.tv_nsec = 1000000;
-
-  // try to harvest the child PID
-  int waitstatus = 0;
-  int result = waitpid (-1, &waitstatus, WNOHANG);
-  for (int i = 0; (i < 500) && (result == 0); i++) {
-    nanosleep (&request, &remain);
-    result = waitpid (-1, &waitstatus, WNOHANG);
-  }
-
-  if ((result == -1) && (errno != ECHILD)) {
-    fprintf (stderr, "unexpected error from waitpid (%d): programming error\n", errno);
-  }
-  if (result == 0) {
-    fprintf (stderr, "child did not exit (close_kapa), timeout");
-  }
-
   return (TRUE);
 }
Index: trunk/Ohana/src/opihi/lib.data/spline.c
===================================================================
--- trunk/Ohana/src/opihi/lib.data/spline.c	(revision 41326)
+++ trunk/Ohana/src/opihi/lib.data/spline.c	(revision 41340)
@@ -7,7 +7,4 @@
   float dy, dx, *tmp;
   
-  // spline is not valid with < 3 points
-  if (N < 3) return;
-
   ALLOCATE (tmp, float, N);
 
@@ -72,7 +69,4 @@
   opihi_flt dy, dx, *tmp;
   
-  // spline is not valid with < 3 points
-  if (N < 3) return;
-
   ALLOCATE (tmp, opihi_flt, N);
 
Index: trunk/Ohana/src/opihi/lib.data/starfuncs.c
===================================================================
--- trunk/Ohana/src/opihi/lib.data/starfuncs.c	(revision 41326)
+++ trunk/Ohana/src/opihi/lib.data/starfuncs.c	(revision 41340)
@@ -75,6 +75,4 @@
   FWHMx = 2.355*sqrt (fabs(x2 / I - x*x));
   FWHMy = 2.355*sqrt (fabs(y2 / I - y*y));
-
-  // fprintf (stderr, "Mxx, Myy: %f, %f\n", x2/I - x*x, y2/I - y*y);
   Sxy   = xy / I - x*y;
   mag = -2.5*log10(I);
Index: trunk/Ohana/src/opihi/lib.data/style_args.c
===================================================================
--- trunk/Ohana/src/opihi/lib.data/style_args.c	(revision 41326)
+++ trunk/Ohana/src/opihi/lib.data/style_args.c	(revision 41340)
@@ -72,14 +72,4 @@
   }
 
-  if ((graphmode[0].style == KAPA_PLOT_POLYGON) || (graphmode[0].style == KAPA_PLOT_POLYFILL)) {
-    if ((N = get_argument (*argc, argv, "-npoint"))) {
-      remove_argument (N, argc, argv);
-      graphmode[0].ptype = atoi (argv[N]);
-      remove_argument (N, argc, argv);
-    } else {
-      gprint (GP_ERR, "polygon & polyfill styles require number of points argument: -npoint N\n");
-      return FALSE;
-    }
-  }
   return (TRUE);
 }
Index: trunk/Ohana/src/opihi/lib.shell/VectorIO.c
===================================================================
--- trunk/Ohana/src/opihi/lib.shell/VectorIO.c	(revision 41326)
+++ trunk/Ohana/src/opihi/lib.shell/VectorIO.c	(revision 41340)
@@ -2,16 +2,4 @@
 void gfits_compress_timing ();
   
-static int VectorGetMaxStringLength (Vector *vec) {
-
-  int MaxLength = 0;
-
-  if (vec[0].type != OPIHI_STR) return 0;
-
-  for (int i = 0; i < vec[0].Nelements; i++) {
-    MaxLength = MAX (MaxLength, strlen(vec[0].elements.Str[i]));
-  }
-  return MaxLength;
-}
-
 // write a set of vectors to a FITS FTable structure (vectors names become fits column names)
 static int WriteVectorTable (FTable *ftable, char *extname, Vector **vec, int Nvec, char *format, char nativeOrder) {
@@ -19,28 +7,17 @@
   int j;
 
+  char *tformat = NULL;
+
   Header *theader = ftable->header;
   gfits_create_table_header (theader, "BINTABLE", extname);
 
-  // allocate an array of strings to represent the format for each output field
-  // formats include single column formats (BIJKDE) and multi-column formats (e.g., 2I)
-  // we will have no more than Nvec fields (but we can have fewer)
-  int Nfield = 0;
-  ALLOCATE_PTR (tformat, char *, Nvec);
-  ALLOCATE_PTR (Nelement, int, Nvec);
-
+  ALLOCATE (tformat, char, 2*Nvec);
   if (format) {
-    // the bintable format string can defines the byte-width of each field and number of elements (columns per field).
-    // valid output columns are currently:
+    // the bintable format string can only define the byte-width of each field.  valid output columns are currently:
     // B (char), I (16 bit short), J (32 bit int), E (32 bit float), D (64 bit double).
-    // the format string is just the sequence of types, eg: LIIJEED.
-    // it may have spaces or integer element counts:
-    // "2D 4I EEJ"
-
-    // *** validate the format string
-
-    // as I parse each elements, if it is a digit, I need parse that value
-
+    // the format string is just the sequence of types, eg: LIIJEED
+    // validate the format string
     char *ptr = format;
-    for (j = 0; j < Nvec; ) {
+    for (j = 0; j < Nvec; j++) {
       while (*ptr && OHANA_WHITESPACE (*ptr)) ptr++;
       if (*ptr == 0) {
@@ -48,48 +25,11 @@
 	goto escape;
       }
-
-      // is there a leading integer?
-      char *endptr;
-      Nelement[Nfield] = strtol (ptr, &endptr, 10);
-      if (endptr == ptr) {
-	Nelement[Nfield] = 1;
-      }
-      ptr = endptr; // this should now point at the letter that is the format type
-      if ((*ptr != 'B') && (*ptr != 'I') && (*ptr != 'J') && (*ptr != 'K') && (*ptr != 'D') && (*ptr != 'E') && (*ptr != 'A')) {
+      if ((*ptr != 'B') && (*ptr != 'I') && (*ptr != 'J') && (*ptr != 'K') && (*ptr != 'D') && (*ptr != 'E')) {
 	gprint (GP_ERR, "error in binary table format %s: invalid character %c\n", format, *ptr);
 	goto escape;
       }
-
-      int Nchar = snprintf (tformat[Nfield], 0, "%d%c", Nelement[Nfield], *ptr);
-      ALLOCATE (tformat[Nfield], char, Nchar + 1);
-      int Nout = snprintf (tformat[Nfield], Nchar + 1, "%d%c", Nelement[Nfield], *ptr);
-      myAssert (Nout <= Nchar, "oops");
-
-      // tformat[2*j + 0] = *ptr;
-      // tformat[2*j + 1] = 0; // a bit sleazy : use a 2xN string to store N 1-byte strings
-
-      // For numeric multi-valued fields, the number of elements from the format defines the number of
-      // vectors which go into that field.  For string-type vectors, the format specifies the maximum number of characters
-      // that go into the field.
-
-      // for example, a format code of 3E should match a list of three numeric-type vectors while a format code of 15A should
-      // match a single string-type vector which will supply up to 15 chars per row.
-
-      if (*ptr != 'A') {
-	j += Nelement[Nfield]; // advance past Nelement vectors
-      } else {
-	if (vec[j][0].type != OPIHI_STR) {
-	  gprint (GP_ERR, "error in binary table format %s (mismatch between string format and numeric vector %s)\n", format, vec[j][0].name);
-	  goto escape;
-	}
-	j ++; // advance past a single string-type vector (validate that?)
-      }
-      if (j > Nvec) {
-	gprint (GP_ERR, "error in binary table format %s (too few vectors for listed field)\n", format);
-	goto escape;
-      }
-
+      tformat[2*j + 0] = *ptr;
+      tformat[2*j + 1] = 0; // a bit sleazy : use a 2xN string to store N 1-byte strings
       ptr ++;
-      Nfield ++;
     }
     while (*ptr && OHANA_WHITESPACE (*ptr)) ptr++;
@@ -100,24 +40,8 @@
   } else {
     for (j = 0; j < Nvec; j++) {
-      switch (vec[j][0].type) {
-	case OPIHI_FLT:
-	case OPIHI_INT:
-	  // if the format is not defined, just use the native byte-widths
-	  ALLOCATE (tformat[j], char, 2);
-	  tformat[j][0] = (vec[j][0].type == OPIHI_FLT) ? 'D' : 'K';
-	  tformat[j][1] = 0;
-	  Nelement[j] = 1;
-	  break;
-	case OPIHI_STR:
-	  // we need to examine the vector to determine the length
-	  Nelement[j] = VectorGetMaxStringLength(vec[j]); 
-	  int Nchar = snprintf (tformat[j], 0, "%d%c", Nelement[j], 'A');
-	  ALLOCATE (tformat[j], char, Nchar + 1);
-	  int Nout = snprintf (tformat[j], Nchar + 1, "%d%c", Nelement[j], 'A');
-	  myAssert (Nout <= Nchar, "oops");
-	  break;
-      }
-    }
-    Nfield = Nvec;
+      // if the format is not defined, just use the native byte-widths
+      tformat[2*j + 0] = (vec[j][0].type == OPIHI_FLT) ? 'D' : 'K'; // this depends on opihi_int == int64_t for Int
+      tformat[2*j + 1] = 0;
+    }
   }
 
@@ -125,19 +49,6 @@
   // output table (because the data goes to the named column below).  need to enforce
   // this somehow
-  int ivec = 0;
-  for (j = 0; j < Nfield; j++) {
-    // XX need to loop over fields, and skip the additional vectors that are part of a field
-    // this call supported multiple columns per named field
-    gfits_define_bintable_column (theader, tformat[j], vec[ivec][0].name, NULL, NULL, 1.0, 0.0);
-    if (vec[ivec][0].type == OPIHI_STR) {
-      ivec ++;
-    } else {
-      ivec += Nelement[j];
-    }
-  }
-
-  // need to free the array 
-  for (j = 0; j < Nfield; j++) {
-    free (tformat[j]);
+  for (j = 0; j < Nvec; j++) {
+    gfits_define_bintable_column (theader, &tformat[2*j], vec[j][0].name, NULL, NULL, 1.0, 0.0);
   }
   free (tformat);
@@ -146,37 +57,11 @@
   gfits_create_table (theader, ftable);
 
-  // I need to add each vector in order, but I need to
-  // track which field it corresponds to.
-
   // add the vectors to the output array
-  for (ivec = 0, j = 0; j < Nfield; j++) {
-    // the first vector provides the name for the field
-    char *fieldname = vec[ivec][0].name;
-
-    if (vec[ivec][0].type == OPIHI_STR) {
-      // string-type vectors need to be copied into a contiguous buffer with the right dimensions:
-      Vector *thisvec = vec[ivec];
-
-      ALLOCATE_PTR (strbuffer, char, Nelement[j]*thisvec->Nelements);
-      for (int i = 0; i < thisvec->Nelements; i++) {
-	int nChar = MIN (strlen (thisvec->elements.Str[i]), Nelement[j]);
-	// fprintf (stderr, "%d %d %d : %d : %d : %s\n", ivec, j, i, Nelement[j], nChar, thisvec->elements.Str[i]);
-	memcpy (&strbuffer[i*Nelement[j]], thisvec->elements.Str[i], nChar);
-      }
-      gfits_set_bintable_column (theader, ftable, fieldname, strbuffer, thisvec->Nelements);
-      free (strbuffer);
-      ivec ++;
+  for (j = 0; j < Nvec; j++) {
+    if (vec[j][0].type == OPIHI_FLT) {
+      gfits_set_bintable_column_reformat (theader, ftable, vec[j][0].name, "double",  vec[j][0].elements.Flt, vec[j][0].Nelements, nativeOrder);
     } else {
-      for (int k = 0; k < Nelement[j]; k++, ivec++) {
-	Vector *thisvec = vec[ivec];
-	switch (thisvec->type) {
-	  case OPIHI_FLT:
-	    gfits_set_bintable_column_reformat (theader, ftable, fieldname, "double",  thisvec->elements.Flt, thisvec->Nelements, k, nativeOrder);
-	    break;
-	  case OPIHI_INT:
-	    gfits_set_bintable_column_reformat (theader, ftable, fieldname, "int64_t", thisvec->elements.Int, thisvec->Nelements, k, nativeOrder);
-	    break;
-	}
-      }
+//    gfits_set_bintable_column_reformat (theader, ftable, vec[j][0].name, "int",     vec[j][0].elements.Int, vec[j][0].Nelements, nativeOrder);
+      gfits_set_bintable_column_reformat (theader, ftable, vec[j][0].name, "int64_t", vec[j][0].elements.Int, vec[j][0].Nelements, nativeOrder);
     }
   }
@@ -225,50 +110,6 @@
 }
 
-// insert a new header line, return end pointer
-char *gfits_insert_header_line (Header *header, char *endptr, char *newline) {
-
-  if (0) {
-    char temp1[32], temp2[32];
-    memset (temp1, 0, 32);
-    memset (temp2, 0, 32);
-
-    if (endptr) {
-      memcpy (temp1, endptr, 8);
-    }
-    memcpy (temp2, newline, 8);
-    fprintf (stderr, "insert: %s : %s\n", temp1, temp2);
-  }
-
-  /* find the END of the header, if not supplied */
-  if (!endptr) {
-    endptr = gfits_header_field (header, "END", 1);
-    if (endptr == NULL) return NULL; 
-  }
-
-  /* is there enough space for 1 more line? */
-  if (header[0].datasize - (endptr - (header[0].buffer)) < 2*FT_LINE_LENGTH) {
-    // no, so expand by a full header block (FT_RECORD_SIZE = 32*80 = 2880)
-    header[0].datasize += FT_RECORD_SIZE;
-    REALLOCATE (header[0].buffer, char, header[0].datasize);
-    // re-find the "END" marker, in case new memory block is used 
-    endptr = gfits_header_field (header, "END", 1);
-    if (endptr == NULL) return NULL; 
-    memset (endptr + FT_LINE_LENGTH, ' ', FT_RECORD_SIZE);
-  }
-
-  /* push END line back 1 */
-  memmove ((endptr + FT_LINE_LENGTH), endptr, FT_LINE_LENGTH);
-  memset (endptr, ' ', FT_LINE_LENGTH);
-
-  strncpy (endptr, newline, 80);
-  endptr += FT_LINE_LENGTH;
-
-  return endptr;
-}
-  
-static char *rawkeywords[] = {"SIMPLE", "BITPIX", "NAXIS", "PCOUNT", "GCOUNT", "EXTEND", "EXTNAME", "BSCALE", "BZERO", "TFIELDS", "TFORM", "TZERO", "TSCAL", "        ", NULL};
-
 // write a set of vectors to a FITS file (vectors names become fits column names)
-int WriteVectorTableFITS (char *filename, char *extname, Header *extraheader, Vector **vec, int Nvec, int append, char *compress, char *format, int Ntile) {
+int WriteVectorTableFITS (char *filename, char *extname, Vector **vec, int Nvec, int append, char *compress, char *format, int Ntile) {
   
   Header rawheader;
@@ -298,5 +139,5 @@
   rawtable.header = &rawheader;
   if (!WriteVectorTable (&rawtable, extname, vec, Nvec, format, (compress != NULL))) goto escape;
-  // NOTE : for compression, the table is constructed in native byte order 
+  // NOTE : for compression, the table is constructed in native by order 
 
   FTable *outtable = &rawtable;
@@ -322,5 +163,4 @@
 
   if (!append) {
-    // generate a blank PHU header
     Header header;
     Matrix matrix;
@@ -336,30 +176,4 @@
   }
 
-  if (extraheader) {
-    // copy keywords which are not the standard or table keywords
-    char *buf = extraheader->buffer;
-    char *endptr = NULL;
-    for (int i = 0; i < extraheader->datasize; i+= FT_LINE_LENGTH, buf += FT_LINE_LENGTH) {
-
-      if (0) { 
-	char temp1[32];
-	memset (temp1, 0, 32);
-	memcpy (temp1, buf, 8);
-	fprintf (stderr, "buffer: %s\n", temp1);
-      }
-
-      for (int j = 0; rawkeywords[j] != NULL; j++) {
-	if (!strncmp (buf, rawkeywords[j], strlen(rawkeywords[j]))) goto skip_insert;
-      }
-      endptr = gfits_insert_header_line (outheader, endptr, buf);
-      if (!endptr) {
-	gprint (GP_ERR, "failed to update FITS header with extra keywords\n");
-	return (FALSE);
-      }
-    skip_insert:
-      continue;
-    }
-  }
-
   // write the actual table data
   gfits_fwrite_Theader (f, outheader);
Index: trunk/Ohana/src/opihi/lib.shell/VectorOps.c
===================================================================
--- trunk/Ohana/src/opihi/lib.shell/VectorOps.c	(revision 41326)
+++ trunk/Ohana/src/opihi/lib.shell/VectorOps.c	(revision 41340)
@@ -129,5 +129,4 @@
   if (mode == NEWVECTOR) goto error;
   if (vectors[i]) {
-    // XXX warning: this will be a leak if vector is type OPIHI_STR
     if (vectors[i][0].elements.Ptr) free (vectors[i][0].elements.Ptr);
     free (vectors[i]);
@@ -151,5 +150,4 @@
   if (i == Nvectors) return (FALSE);
 
-  // XXX warning: this will be a leak if vector is type OPIHI_STR
   if (vectors[i][0].elements.Ptr) free (vectors[i][0].elements.Ptr);
   free (vectors[i]);
@@ -172,5 +170,4 @@
   if (i == Nvectors) return (FALSE);
 
-  // XXX warning: this will be a leak if vector is type OPIHI_STR
   if (vectors[i][0].elements.Ptr) free (vectors[i][0].elements.Ptr);
   free (vectors[i]);
@@ -194,5 +191,4 @@
 
 int CopyVector (Vector *out, Vector *in) {
-  // XXX warning: this will be a leak if vector is type OPIHI_STR
   if (out[0].elements.Ptr) free (out[0].elements.Ptr);
   out[0].Nelements = in[0].Nelements;
@@ -212,5 +208,4 @@
 
 int MatchVector(Vector *out, Vector *in, char type) {
-  // XXX warning: this will be a leak if vector is type OPIHI_STR
   if (out[0].elements.Ptr) free (out[0].elements.Ptr);
   out[0].Nelements = in[0].Nelements;
@@ -227,28 +222,12 @@
 int ResetVector (Vector *vec, char type, int Nelements) {
 
-  // if the supplied vector is a string but the output is not a string, we need to free
-  // the unused elements
-  if ((vec[0].type == OPIHI_STR) && (vec[0].type != type)) {
-    for (int i = 0; i < vec[0].Nelements; i++) {
-      FREE (vec[0].elements.Str[i]);
-    }
-  }
-
   // a vector can only have >= 0 elements
   vec[0].Nelements = MAX(Nelements,0);
-
-  switch (type) {
-    case OPIHI_FLT:
-      REALLOCATE (vec[0].elements.Flt, opihi_flt, MAX(1, Nelements));
-      vec[0].type = OPIHI_FLT;
-      break;
-    case OPIHI_INT:
-      REALLOCATE (vec[0].elements.Int, opihi_int, MAX(1, Nelements));
-      vec[0].type = OPIHI_INT;
-      break;
-    case OPIHI_STR:
-      REALLOCATE (vec[0].elements.Str, char *, MAX(1, Nelements));
-      vec[0].type = OPIHI_STR;
-      break;
+  if (type == OPIHI_FLT) {
+    REALLOCATE (vec[0].elements.Flt, opihi_flt, MAX(1, Nelements));
+    vec[0].type = OPIHI_FLT;
+  } else {
+    REALLOCATE (vec[0].elements.Int, opihi_int, MAX(1, Nelements));
+    vec[0].type = OPIHI_INT;
   }
   return TRUE;
@@ -272,22 +251,13 @@
 
 // SetVector (vecx, OPIHI_FLT, MAX (Npts, 1));
-// Use this for an unallocated vector (e.g., static variable)
 int SetVector (Vector *vec, char type, int Nelements) {
 
   vec[0].Nelements = MAX(Nelements,0);
-
-  switch (type) {
-    case OPIHI_FLT:
-      ALLOCATE (vec[0].elements.Flt, opihi_flt, MAX(1,Nelements));
-      vec[0].type = OPIHI_FLT;
-      break;
-    case OPIHI_INT:
-      ALLOCATE (vec[0].elements.Int, opihi_int, MAX(1,Nelements));
-      vec[0].type = OPIHI_INT;
-      break;
-    case OPIHI_STR:
-      ALLOCATE (vec[0].elements.Ptr, char *, MAX(1,Nelements));
-      vec[0].type = OPIHI_STR;
-      break;
+  if (type == OPIHI_FLT) {
+    ALLOCATE (vec[0].elements.Flt, opihi_flt, MAX(1,Nelements));
+    vec[0].type = OPIHI_FLT;
+  } else {
+    ALLOCATE (vec[0].elements.Int, opihi_int, MAX(1,Nelements));
+    vec[0].type = OPIHI_INT;
   }
   return TRUE;
@@ -302,35 +272,26 @@
   if (vec[0].type == type) return TRUE;
 
-  switch (type) {
-    case OPIHI_FLT: {
-      opihi_flt *temp;
-      ALLOCATE (temp, opihi_flt, vec[0].Nelements);
-      opihi_flt *vo = temp;
-      opihi_int *vi = vec[0].elements.Int;
-      for (i = 0; i < vec[0].Nelements; i++, vo++, vi++) {
-	*vo = *vi;
-      }
-      free (vec[0].elements.Int);
-      vec[0].elements.Flt = temp;
-      vec[0].type = OPIHI_FLT;
-      break;
-    }
-    case OPIHI_INT: {
-      opihi_int *temp;
-      ALLOCATE (temp, opihi_int, vec[0].Nelements);
-      opihi_int *vo = temp;
-      opihi_flt *vi = vec[0].elements.Flt;
-      for (i = 0; i < vec[0].Nelements; i++, vo++, vi++) {
-	*vo = *vi;
-      }
-      free (vec[0].elements.Flt);
-      vec[0].elements.Int = temp;
-      vec[0].type = OPIHI_INT;
-      break;
-    }
-    case OPIHI_STR: 
-    default: 
-      // does it make sense to cast an int/flt vector to string?
-      break;
+  if (type == OPIHI_FLT) {
+    opihi_flt *temp;
+    ALLOCATE (temp, opihi_flt, vec[0].Nelements);
+    opihi_flt *vo = temp;
+    opihi_int *vi = vec[0].elements.Int;
+    for (i = 0; i < vec[0].Nelements; i++, vo++, vi++) {
+      *vo = *vi;
+    }
+    free (vec[0].elements.Int);
+    vec[0].elements.Flt = temp;
+    vec[0].type = OPIHI_FLT;
+  } else {
+    opihi_int *temp;
+    ALLOCATE (temp, opihi_int, vec[0].Nelements);
+    opihi_int *vo = temp;
+    opihi_flt *vi = vec[0].elements.Flt;
+    for (i = 0; i < vec[0].Nelements; i++, vo++, vi++) {
+      *vo = *vi;
+    }
+    free (vec[0].elements.Flt);
+    vec[0].elements.Int = temp;
+    vec[0].type = OPIHI_INT;
   }
   return TRUE;
@@ -381,14 +342,8 @@
   gprint (GP_LOG, "    N       name      size\n");
   for (i = 0; i < Nvectors; i++) {
-    switch (vectors[i][0].type) {
-      case OPIHI_FLT:
-	gprint (GP_LOG, "%5d %10s %10d (FLT)\n", i, vectors[i][0].name, vectors[i][0].Nelements);
-	break;
-      case OPIHI_INT:
-	gprint (GP_LOG, "%5d %10s %10d (INT)\n", i, vectors[i][0].name, vectors[i][0].Nelements);
-	break;
-      case OPIHI_STR:
-	gprint (GP_LOG, "%5d %10s %10d (STR)\n", i, vectors[i][0].name, vectors[i][0].Nelements);
-	break;
+    if (vectors[i][0].type == OPIHI_FLT) {
+      gprint (GP_LOG, "%5d %10s %10d (FLT)\n", i, vectors[i][0].name, vectors[i][0].Nelements);
+    } else {
+      gprint (GP_LOG, "%5d %10s %10d (INT)\n", i, vectors[i][0].name, vectors[i][0].Nelements);
     }
   }
Index: trunk/Ohana/src/opihi/lib.shell/convert_to_RPN.c
===================================================================
--- trunk/Ohana/src/opihi/lib.shell/convert_to_RPN.c	(revision 41326)
+++ trunk/Ohana/src/opihi/lib.shell/convert_to_RPN.c	(revision 41340)
@@ -78,8 +78,4 @@
     if (!strcmp (argv[i], "atan2"))  { type = ST_BINARY; strcpy (argv[i], "a"); goto gotit; }
     if (!strcmp (argv[i], "datan2")) { type = ST_BINARY; strcpy (argv[i], "d"); goto gotit; }
-
-    if (!strcmp (argv[i], "<~"))     { type = ST_BINARY; strcpy (argv[i], "l"); goto gotit; }
-    if (!strcmp (argv[i], "~>"))     { type = ST_BINARY; strcpy (argv[i], "r"); goto gotit; }
-
     if (!strcmp (argv[i], ","))      { type = ST_COMMA; goto gotit; }
 
@@ -103,8 +99,4 @@
     if (!strcmp (argv[i], ">>"))     { type = ST_LOGIC; strcpy (argv[i], "U"); goto gotit; }
     if (!strcmp (argv[i], "<<"))     { type = ST_LOGIC; strcpy (argv[i], "D"); goto gotit; }
-
-    /* XXX I would like to change the syntax to allow << and >> to mean bitshifts
-       but that means breaking these older values which means MIN and MAX */
-    // for now, use <- and -> to mean bitshift 
 
     if (!strcmp (argv[i], "&&"))     { type = ST_AND; strcpy (argv[i], "A"); goto gotit; }
Index: trunk/Ohana/src/opihi/lib.shell/multicommand.c
===================================================================
--- trunk/Ohana/src/opihi/lib.shell/multicommand.c	(revision 41326)
+++ trunk/Ohana/src/opihi/lib.shell/multicommand.c	(revision 41340)
@@ -63,6 +63,4 @@
 
   p = line; 
-  int Nline = strlen(line);
-  
   done = FALSE;
   status = TRUE;
@@ -76,95 +74,82 @@
     tmpline = strncreate (p, q - p);
     stripwhite (tmpline);
-    myAssert (tmpline, "oops");
+    if (*tmpline) {
 
-    // empty command, free and continue
-    if (*tmpline == 0) {
-      free (tmpline);
-      if (q == line + Nline) {
-	done = TRUE;
-      } else {
-	p = q + 1;
-	myAssert (p - line <= Nline, "oops");
+      if (bufferPending) {
+	// flush old messages
+	ExpectMessage (server, 0.2, &message);
+	bufferPending = FALSE;
       }
-      continue;
-    }
 
-    if (bufferPending) {
-      // flush old messages
-      ExpectMessage (server, 0.2, &message);
-      bufferPending = FALSE;
-    }
+      status = command (tmpline, &outline, verbose);
 
-    // input tmpline is freed by command
-    status = command (tmpline, &outline, verbose);
+      if (status == -1) {
+	if (server) {
+	  // send the command to the server instead
+	  if (!SendMessage (server, "%s", outline)) {
+	    switch (errno) {
+	      case EPIPE:
+		gprint (GP_ERR, "server connection has died\n");
+		exit (32);
+	      default:
+		gprint (GP_ERR, "server is busy...32\n");
+		bufferPending = TRUE;
+		goto escape;
+	    }
+	  }
 
-    if (status == -1) {
-      if (server) {
-	// send the command to the server instead
-	if (!SendMessage (server, "%s", outline)) {
-	  switch (errno) {
-	    case EPIPE:
-	      gprint (GP_ERR, "server connection has died\n");
-	      exit (32);
-	    default:
-	      gprint (GP_ERR, "server is busy...32\n");
-	      bufferPending = TRUE;
-	      goto escape;
+	  // receive the command exit status
+	  if (ExpectMessage (server, MSG_TIMEOUT, &message)) {
+	    switch (errno) {
+	      case EPIPE:
+		gprint (GP_ERR, "server connection has died\n");
+		exit (33);
+	      default:
+		gprint (GP_ERR, "server is busy...33\n");
+		bufferPending = TRUE;
+		goto escape;
+	    }
+	  } else {
+	    sscanf (message.buffer, "STATUS %d", &status);
 	  }
-	}
 
-	// receive the command exit status
-	if (ExpectMessage (server, MSG_TIMEOUT, &message)) {
-	  switch (errno) {
-	    case EPIPE:
-	      gprint (GP_ERR, "server connection has died\n");
-	      exit (33);
-	    default:
-	      gprint (GP_ERR, "server is busy...33\n");
-	      bufferPending = TRUE;
-	      goto escape;
+	  // receive the resulting stderr
+	  if (ExpectMessage (server, MSG_TIMEOUT, &message)) {
+	    switch (errno) {
+	      case EPIPE:
+		gprint (GP_ERR, "server connection has died\n");
+		exit (34);
+	      default:
+		gprint (GP_ERR, "server is busy...34\n");
+		bufferPending = TRUE;
+		goto escape;
+	    }
+	  } else {
+	    gwrite (message.buffer, 1, message.Nbuffer, GP_ERR);
+	  }
+
+	  // receive the resulting stdout
+	  if (ExpectMessage (server, MSG_TIMEOUT, &message)) {
+	    switch (errno) {
+	      case EPIPE:
+		gprint (GP_ERR, "server connection has died\n");
+		exit (35);
+	      default:
+		gprint (GP_ERR, "server is busy...35\n");
+		bufferPending = TRUE;
+		goto escape;
+	    }
+	  } else {
+	    gwrite (message.buffer, 1, message.Nbuffer, GP_LOG);
 	  }
 	} else {
-	  sscanf (message.buffer, "STATUS %d", &status);
-	}
-
-	// receive the resulting stderr
-	if (ExpectMessage (server, MSG_TIMEOUT, &message)) {
-	  switch (errno) {
-	    case EPIPE:
-	      gprint (GP_ERR, "server connection has died\n");
-	      exit (34);
-	    default:
-	      gprint (GP_ERR, "server is busy...34\n");
-	      bufferPending = TRUE;
-	      goto escape;
-	  }
-	} else {
-	  gwrite (message.buffer, 1, message.Nbuffer, GP_ERR);
-	}
-
-	// receive the resulting stdout
-	if (ExpectMessage (server, MSG_TIMEOUT, &message)) {
-	  switch (errno) {
-	    case EPIPE:
-	      gprint (GP_ERR, "server connection has died\n");
-	      exit (35);
-	    default:
-	      gprint (GP_ERR, "server is busy...35\n");
-	      bufferPending = TRUE;
-	      goto escape;
-	  }
-	} else {
-	  gwrite (message.buffer, 1, message.Nbuffer, GP_LOG);
-	}
-      } else {
-	// if no server is defined, we treat an unknown command as an error
-	status = FALSE;
-      }	
+	  // if no server is defined, we treat an unknown command as an error
+	  status = FALSE;
+	}	
+      }
+    escape:
+      if (outline != NULL) free (outline);
+      if (!status && auto_break) done = TRUE;
     }
-  escape:
-    if (outline != NULL) free (outline);
-    if (!status && auto_break) done = TRUE;
-
     p = q + 1;
   }
Index: trunk/Ohana/src/opihi/lib.shell/parse.c
===================================================================
--- trunk/Ohana/src/opihi/lib.shell/parse.c	(revision 41326)
+++ trunk/Ohana/src/opihi/lib.shell/parse.c	(revision 41340)
@@ -66,5 +66,5 @@
 	/* dvomath returns a new string, or NULL, with the result of the expression */
 	val = dvomath (1, &V1, &size, 0);
-	if (val == NULL) { print_error (); goto error; }
+	if (val == NULL) goto error;
 	fval += atof(val);
 	// save the result
@@ -88,5 +88,5 @@
 	/* dvomath returns a new string, or NULL, with the result of the expression */
 	val = dvomath (1, &V1, &size, 0);
-	if (val == NULL) { print_error (); goto error; }
+	if (val == NULL) goto error;
 	fval -= atof(val);
 	// save the result
Index: trunk/Ohana/src/opihi/lib.shell/stack_math.c
===================================================================
--- trunk/Ohana/src/opihi/lib.shell/stack_math.c	(revision 41326)
+++ trunk/Ohana/src/opihi/lib.shell/stack_math.c	(revision 41340)
@@ -34,5 +34,5 @@
     case '?': SSS_FUNC(M1 ? M2: M3);
     default:
-      snprintf (line, 512, "error: op %c not defined as scalar trinary op!", op[0]);
+      snprintf (line, 512, "error: op %c not defined!", op[0]);
       push_error (line);
       return (FALSE);
@@ -162,5 +162,5 @@
     case '?': VVV_FUNC(*M1 ? *M2: *M3);
     default:
-      snprintf (line, 512, "error: op %c not defined as vector trinary op!", op[0]);
+      snprintf (line, 512, "error: op %c not defined!", op[0]);
       push_error (line);
       return (FALSE);
@@ -227,5 +227,5 @@
     case '?': MMM_FUNC(*M1 ? *M2: *M3);
     default:
-      snprintf (line, 512, "error: op %c not defined as matrix trinary op!", op[0]);
+      snprintf (line, 512, "error: op %c not defined!", op[0]);
       push_error (line);
       return (FALSE);
@@ -357,48 +357,6 @@
     case 'A': VV_FUNC(ST_SCALAR_INT, (*M1 && *M2) ? 1 : 0);
     case 'O': VV_FUNC(ST_SCALAR_INT, (*M1 || *M2) ? 1 : 0);
-
-    // for the bitshift operators, we have to treat the INT and FLT values differently
-    // this makes the operator incompatible with the macros used above
-    case 'l': {
-      CopyVector (OUT[0].vector, V1[0].vector);
-      if ((V1->vector->type == OPIHI_FLT) || (V2->vector->type == OPIHI_FLT)) {
-	// bitshift is not valid with float valuess
-	for (i = 0; i < Nx; i++) {
-	  OUT[0].vector[0].elements.Flt[i] = NAN;
-	}
-	break;
-      }
-      // I could just do this for all types and bitshift regardless...
-      opihi_int *M1  =  V1[0].vector[0].elements.Int;
-      opihi_int *M2  =  V2[0].vector[0].elements.Int;
-      opihi_int *out = OUT[0].vector[0].elements.Int;
-      for (i = 0; i < Nx; i++, out++, M1++, M2++) {
-  	*out = *M1 << *M2;
-      }
-      break;
-    }
-
-    case 'r': {
-      CopyVector (OUT[0].vector, V1[0].vector);
-      if ((V1->vector->type == OPIHI_FLT) || (V2->vector->type == OPIHI_FLT)) {
-	// bitshift is not valid with float valuess
-	CopyVector (OUT[0].vector, V1[0].vector);
-	for (i = 0; i < Nx; i++) {
-	  OUT[0].vector[0].elements.Flt[i] = NAN;
-	}
-	break;
-      }
-      // I could just do this for all types and bitshift regardless...
-      opihi_int *M1  =  V1[0].vector[0].elements.Int;
-      opihi_int *M2  =  V2[0].vector[0].elements.Int;
-      opihi_int *out = OUT[0].vector[0].elements.Int;
-      for (i = 0; i < Nx; i++, out++, M1++, M2++) {
-  	*out = *M1 >> *M2;
-      }
-      break;
-    }
-
     default:
-      snprintf (line, 512, "error: op %c not defined for (vector OP vector)!", op[0]);
+      snprintf (line, 512, "error: op %c not defined!", op[0]);
       push_error (line);
       return (FALSE);
@@ -511,45 +469,6 @@
     case 'A': SV_FUNC(ST_SCALAR_INT, (M1 && *M2) ? 1 : 0);
     case 'O': SV_FUNC(ST_SCALAR_INT, (M1 || *M2) ? 1 : 0);
-
-    // for the bitshift operators, we have to treat the INT and FLT values differently
-    // this makes the operator incompatible with the macros used above
-    case 'l': {
-      CopyVector (OUT[0].vector, V2[0].vector);
-      if ((V1->type == ST_SCALAR_FLT) || (V2->vector->type == OPIHI_FLT)) {
-	// bitshift is not valid with float valuess
-	for (i = 0; i < Nx; i++) {
-	  OUT[0].vector[0].elements.Flt[i] = NAN;
-	}
-	break;
-      }
-      opihi_int  M1  =  V1[0].IntValue;					\
-      opihi_int *M2  =  V2[0].vector[0].elements.Int;
-      opihi_int *out = OUT[0].vector[0].elements.Int;
-      for (i = 0; i < Nx; i++, out++, M2++) {
-  	*out = M1 << *M2;
-      }
-      break;
-    }
-
-    case 'r': {
-      CopyVector (OUT[0].vector, V2[0].vector);
-      if ((V1->type == ST_SCALAR_FLT) || (V2->vector->type == OPIHI_FLT)) {
-	// bitshift is not valid with float valuess
-	for (i = 0; i < Nx; i++) {
-	  OUT[0].vector[0].elements.Flt[i] = NAN;
-	}
-	break;
-      }
-      opihi_int  M1  =  V1[0].IntValue;					\
-      opihi_int *M2  =  V2[0].vector[0].elements.Int;
-      opihi_int *out = OUT[0].vector[0].elements.Int;
-      for (i = 0; i < Nx; i++, out++, M2++) {
-  	*out = M1 >> *M2;
-      }
-      break;
-    }
-
     default:
-      snprintf (line, 512, "error: op %c not defined for (scalar OP vector)!", op[0]);
+      snprintf (line, 512, "error: op %c not defined!", op[0]);
       push_error (line);
       return (FALSE);
@@ -658,44 +577,6 @@
     case 'A': VS_FUNC(ST_SCALAR_INT, (*M1 && M2) ? 1 : 0);
     case 'O': VS_FUNC(ST_SCALAR_INT, (*M1 || M2) ? 1 : 0);
-
-    case 'l': {
-      CopyVector (OUT[0].vector, V1[0].vector);
-      if ((V1->vector->type == OPIHI_FLT) || (V2->type == ST_SCALAR_FLT)) {
-	// bitshift is not valid with float valuess
-	for (i = 0; i < Nx; i++) {
-	  OUT[0].vector[0].elements.Flt[i] = NAN;
-	}
-	break;
-      }
-      opihi_int *M1  =  V1[0].vector[0].elements.Int;
-      opihi_int  M2  =  V2[0].IntValue;					\
-      opihi_int *out = OUT[0].vector[0].elements.Int;
-      for (i = 0; i < Nx; i++, out++, M1++) {
-  	*out = *M1 << M2;
-      }
-      break;
-    }
-
-    case 'r': {
-      CopyVector (OUT[0].vector, V1[0].vector);
-      if ((V1->vector->type == OPIHI_FLT) || (V2->type == ST_SCALAR_FLT)) {
-	// bitshift is not valid with float valuess
-	CopyVector (OUT[0].vector, V1[0].vector);
-	for (i = 0; i < Nx; i++) {
-	  OUT[0].vector[0].elements.Flt[i] = NAN;
-	}
-	break;
-      }
-      opihi_int *M1  =  V1[0].vector[0].elements.Int;
-      opihi_int  M2  =  V2[0].IntValue;					\
-      opihi_int *out = OUT[0].vector[0].elements.Int;
-      for (i = 0; i < Nx; i++, out++, M1++) {
-  	*out = *M1 >> M2;
-      }
-      break;
-    }
-
     default:
-      snprintf (line, 512, "error: op %c not defined for (vector OP scalar)!", op[0]);
+      snprintf (line, 512, "error: op %c not defined!", op[0]);
       push_error (line);
       return (FALSE);
@@ -789,7 +670,6 @@
     case 'A': MV_FUNC((*M1 && *M2) ? 1 : 0);
     case 'O': MV_FUNC((*M1 || *M2) ? 1 : 0);
-
     default:
-      snprintf (line, 512, "error: op %c not defined for (matrix OP vector)!", op[0]);
+      snprintf (line, 512, "error: op %c not defined!", op[0]);
       push_error (line);
       return (FALSE);
@@ -888,5 +768,5 @@
     case 'O': VM_FUNC((*M1 || *M2) ? 1 : 0);
     default:
-      snprintf (line, 512, "error: op %c not defined for (vector OP matrix)!", op[0]);
+      snprintf (line, 512, "error: op %c not defined!", op[0]);
       push_error (line);
       return (FALSE);
@@ -969,5 +849,5 @@
     case 'O': MM_FUNC((*M1 || *M2) ? 1 : 0);
     default:
-      snprintf (line, 512, "error: op %c not defined for (matrix OP matrix)!", op[0]);
+      snprintf (line, 512, "error: op %c not defined!", op[0]);
       push_error (line);
       return (FALSE);
@@ -1055,5 +935,5 @@
     case 'O': MS_FUNC((*M1 || M2) ? 1 : 0);
     default:
-      snprintf (line, 512, "error: op %c not defined for (matrix OP scalar)!", op[0]);
+      snprintf (line, 512, "error: op %c not defined!", op[0]);
       push_error (line);
       return (FALSE);
@@ -1132,5 +1012,5 @@
     case 'O': SM_FUNC((M1 || *M2) ? 1 : 0);
     default:
-      snprintf (line, 512, "error: op %c not defined for (scalar OP matrix)!", op[0]);
+      snprintf (line, 512, "error: op %c not defined!", op[0]);
       push_error (line);
       return (FALSE);
@@ -1214,37 +1094,6 @@
     case 'A': SS_FUNC(ST_SCALAR_INT, (M1 && M2) ? 1 : 0);
     case 'O': SS_FUNC(ST_SCALAR_INT, (M1 || M2) ? 1 : 0);
-
-    // for the bitshift operators, we have to treat the INT and FLT values differently
-    // this makes the operator incompatible with the macros used above
-    case 'l': {
-      if ((V1->type == ST_SCALAR_FLT) || (V2->type == ST_SCALAR_FLT)) {
-	// bitshift is not valid with float valuess
-	OUT[0].type = ST_SCALAR_FLT;
-	OUT[0].FltValue = NAN;
-	break;
-      }
-      opihi_int M1 = V1[0].IntValue;
-      opihi_int M2 = V2[0].IntValue;
-      OUT[0].type = ST_SCALAR_INT;
-      OUT[0].IntValue = M1 << M2;
-      break;
-    }
-
-    case 'r': {
-      if ((V1->type == ST_SCALAR_FLT) || (V2->type == ST_SCALAR_FLT)) {
-	// bitshift is not valid with float valuess
-	OUT[0].type = ST_SCALAR_FLT;
-	OUT[0].FltValue = NAN;
-	break;
-      }
-      opihi_int M1 = V1[0].IntValue;
-      opihi_int M2 = V2[0].IntValue;
-      OUT[0].type = ST_SCALAR_INT;
-      OUT[0].IntValue = M1 >> M2;
-      break;
-    }
-
     default:
-      snprintf (line, 512, "error: op %c not defined for (scalar OP scalar)!", op[0]);
+      snprintf (line, 512, "error: op %c not defined!", op[0]);
       push_error (line);
       return (FALSE);
@@ -1319,4 +1168,6 @@
 int S_unary (StackVar *OUT, StackVar *V1, char *op) {
 
+  char line[512]; // this is only used to report an error 
+  
 # define S_FUNC(OP,FTYPE) {						\
     if (V1->type == ST_SCALAR_FLT) {					\
@@ -1359,4 +1210,5 @@
   if (!strcmp (op, "asinh"))  S_FUNC(asinh (M1), ST_SCALAR_FLT);
   if (!strcmp (op, "acosh"))  S_FUNC(acosh (M1), ST_SCALAR_FLT);
+  if (!strcmp (op, "lgamma")) S_FUNC(lgamma (M1), ST_SCALAR_FLT);
   if (!strcmp (op, "sin"))    S_FUNC(sin (M1), ST_SCALAR_FLT);
   if (!strcmp (op, "cos"))    S_FUNC(cos (M1), ST_SCALAR_FLT);
@@ -1371,5 +1223,4 @@
   if (!strcmp (op, "dacos"))  S_FUNC(acos (M1)*DEG_RAD, ST_SCALAR_FLT);
   if (!strcmp (op, "datan"))  S_FUNC(atan (M1)*DEG_RAD, ST_SCALAR_FLT);
-  if (!strcmp (op, "lgamma")) S_FUNC(lgamma (M1), ST_SCALAR_FLT);
   if (!strcmp (op, "rnd"))    S_FUNC(0.0*M1 + drand48(), ST_SCALAR_FLT);
   if (!strcmp (op, "drnd"))   S_FUNC(0.0*M1 + drand48(), ST_SCALAR_FLT);
@@ -1384,9 +1235,8 @@
 
   clear_stack (V1);
-
-  char line[512]; // this is only used to report an error 
-  snprintf (line, 512, "error: op %s not defined as unary scalar op!", op);
+  snprintf (line, 512, "error: op %s not defined!", op);
   push_error (line);
   return (FALSE);
+
 }
 
@@ -1445,4 +1295,5 @@
   if (!strcmp (op, "asinh"))  V_FUNC(asinh(*M1), ST_SCALAR_FLT);
   if (!strcmp (op, "acosh"))  V_FUNC(acosh(*M1), ST_SCALAR_FLT);
+  if (!strcmp (op, "lgamma")) V_FUNC(lgamma(*M1), ST_SCALAR_FLT);
   if (!strcmp (op, "sin"))    V_FUNC(sin(*M1), ST_SCALAR_FLT);
   if (!strcmp (op, "cos"))    V_FUNC(cos(*M1), ST_SCALAR_FLT);
@@ -1457,23 +1308,23 @@
   if (!strcmp (op, "dacos"))  V_FUNC(acos(*M1)*DEG_RAD, ST_SCALAR_FLT);
   if (!strcmp (op, "datan"))  V_FUNC(atan(*M1)*DEG_RAD, ST_SCALAR_FLT);
-  if (!strcmp (op, "lgamma")) V_FUNC(lgamma(*M1), ST_SCALAR_FLT);
   if (!strcmp (op, "rnd"))    V_FUNC(drand48(), ST_SCALAR_FLT);
   if (!strcmp (op, "drnd"))   V_FUNC(drand48(), ST_SCALAR_FLT);
   if (!strcmp (op, "lrnd"))   V_FUNC(lrand48(), ST_SCALAR_INT);
   if (!strcmp (op, "mrnd"))   V_FUNC(mrand48(), ST_SCALAR_INT);
+  if (!strcmp (op, "ramp"))   V_FUNC(i, ST_SCALAR_INT);
+  if (!strcmp (op, "zero"))   V_FUNC(0, ST_SCALAR_INT);
   if (!strcmp (op, "not"))    V_FUNC(!(*M1), ST_SCALAR_INT);
   if (!strcmp (op, "--"))     V_FUNC(-1*(*M1), ST_SCALAR_INT); // NOTE: opihi_int is signed
   if (!strcmp (op, "isinf"))  V_FUNC(!finite(*M1), ST_SCALAR_FLT);
   if (!strcmp (op, "isnan"))  V_FUNC(isnan((opihi_flt)(*M1)), ST_SCALAR_FLT);
-  if (!strcmp (op, "ramp"))   V_FUNC(i, ST_SCALAR_INT);
   if (!strcmp (op, "xramp"))  V_FUNC(i, ST_SCALAR_INT);
   if (!strcmp (op, "yramp"))  V_FUNC(0, ST_SCALAR_INT);
   if (!strcmp (op, "zramp"))  V_FUNC(0, ST_SCALAR_INT);
-  if (!strcmp (op, "zero"))   V_FUNC(0, ST_SCALAR_INT);
   /* xramp, yramp, zramp above only make sense for matrices. for vectors, xramp = ramp, yramp = zero */
 
 # undef V_FUNC
 
-  // free the temp vector if needed
+escape:
+
   if (V1[0].type == ST_VECTOR_TMP) {
     free (V1[0].vector[0].elements.Ptr);
@@ -1483,24 +1334,9 @@
 
   clear_stack (V1);
-
-  char line[512]; // this is only used to report an error 
-  snprintf (line, 512, "error: op %s not defined as unary vector op!", op);
-  push_error (line);
-  return (FALSE);
-
-escape:
-
-  if (V1[0].type == ST_VECTOR_TMP) {
-    free (V1[0].vector[0].elements.Ptr);
-    free (V1[0].vector);
-    V1[0].vector = NULL;
-  }  
-
-  clear_stack (V1);
-  return (TRUE);
-
-}
-
-# define M_FUNC(OP) { for (i = 0; i < Npix; i++, out++, M1++) { *out = (OP); } goto escape; }
+  return (TRUE);
+
+}
+
+# define M_FUNC(OP) { for (i = 0; i < Npix; i++, out++, M1++) { *out = (OP); }}
 
 int M_unary (StackVar *OUT, StackVar *V1, char *op) {
@@ -1524,5 +1360,5 @@
 // if (!strcmp (op, "rint"))  { for (i = 0; i < Npix; i++, out++, M1++) { *out = nearbyint (*M1); }}
   
-  if (!strcmp (op, "="))      { goto escape; }
+  if (!strcmp (op, "="))     { }
   if (!strcmp (op, "abs"))    M_FUNC(fabs(*M1));
   if (!strcmp (op, "int"))    M_FUNC((opihi_flt)(long long)(*M1));
@@ -1539,4 +1375,5 @@
   if (!strcmp (op, "asinh"))  M_FUNC(asinh(*M1));
   if (!strcmp (op, "acosh"))  M_FUNC(acosh(*M1));
+  if (!strcmp (op, "lgamma")) M_FUNC(lgamma(*M1));
   if (!strcmp (op, "sin"))    M_FUNC(sin(*M1));
   if (!strcmp (op, "cos"))    M_FUNC(cos(*M1));
@@ -1551,15 +1388,14 @@
   if (!strcmp (op, "dacos"))  M_FUNC(acos(*M1)*DEG_RAD);
   if (!strcmp (op, "datan"))  M_FUNC(atan(*M1)*DEG_RAD);
-  if (!strcmp (op, "lgamma")) M_FUNC(lgamma(*M1));
+  if (!strcmp (op, "not"))    M_FUNC(!(*M1));
+  if (!strcmp (op, "--"))     M_FUNC(-(*M1));
   if (!strcmp (op, "rnd"))    M_FUNC(drand48());
   if (!strcmp (op, "drnd"))   M_FUNC(drand48());
   if (!strcmp (op, "lrnd"))   M_FUNC(lrand48());
   if (!strcmp (op, "mrnd"))   M_FUNC(mrand48());
-  if (!strcmp (op, "not"))    M_FUNC(!(*M1));
-  if (!strcmp (op, "--"))     M_FUNC(-(*M1));
   if (!strcmp (op, "ramp"))   M_FUNC(i);
+  if (!strcmp (op, "zero"))   M_FUNC(0);
   if (!strcmp (op, "isinf"))  M_FUNC(!finite(*M1));
   if (!strcmp (op, "isnan"))  M_FUNC(isnan(*M1));
-  if (!strcmp (op, "zero"))   M_FUNC(0);
 
   /* xrm and yrm only make sense for 2D matrices. see special meaning for vectors */
@@ -1575,5 +1411,4 @@
       }
     }
-    goto escape; 
   }
   if (!strcmp (op, "yramp")) {
@@ -1588,5 +1423,4 @@
       }
     }
-    goto escape; 
   }
   if (!strcmp (op, "zramp")) {
@@ -1601,22 +1435,6 @@
       }
     }
-    goto escape; 
-  }
-  
-  if (V1[0].type == ST_MATRIX_TMP) {
-    free (V1[0].buffer[0].header.buffer);
-    free (V1[0].buffer[0].matrix.buffer);
-    free (V1[0].buffer);
-  }
-
-  clear_stack (V1);
-
-  char line[512]; // this is only used to report an error 
-  snprintf (line, 512, "error: op %s not defined as unary matrix op!", op);
-  push_error (line);
-  return (FALSE);
-
- escape:
-
+  }
+  
   if (V1[0].type == ST_MATRIX_TMP) {
     free (V1[0].buffer[0].header.buffer);
Index: trunk/Ohana/src/opihi/lib.shell/startup.c
===================================================================
--- trunk/Ohana/src/opihi/lib.shell/startup.c	(revision 41326)
+++ trunk/Ohana/src/opihi/lib.shell/startup.c	(revision 41340)
@@ -107,16 +107,4 @@
       LOAD_RC = FALSE;
     }
-    if ((N = get_argument (*argc, argv, "--no-rc"))) {
-      remove_argument (N, argc, argv);
-      LOAD_RC = FALSE;
-    }
-    if ((N = get_argument (*argc, argv, "-norc"))) {
-      remove_argument (N, argc, argv);
-      LOAD_RC = FALSE;
-    }
-    if ((N = get_argument (*argc, argv, "-no-rc"))) {
-      remove_argument (N, argc, argv);
-      LOAD_RC = FALSE;
-    }
     
     ONLY_INPUT = FALSE;
Index: trunk/Ohana/src/opihi/mana/Makefile
===================================================================
--- trunk/Ohana/src/opihi/mana/Makefile	(revision 41326)
+++ trunk/Ohana/src/opihi/mana/Makefile	(revision 41340)
@@ -26,8 +26,8 @@
 $(SRC)/deimos_getobj.$(ARCH).o \
 $(SRC)/deimos_fitobj.$(ARCH).o \
+$(SRC)/deimos_fitalt.$(ARCH).o \
+$(SRC)/deimos_mkalt.$(ARCH).o \
 $(SRC)/deimos_mkmodel.$(ARCH).o \
 $(SRC)/deimos_arclines.$(ARCH).o \
-$(SRC)/deimos_fitarc.$(ARCH).o \
-$(SRC)/deimos_fitprofile.$(ARCH).o \
 $(SRC)/findrowpeaks.$(ARCH).o 
 
Index: trunk/Ohana/src/opihi/mana/deimos.c
===================================================================
--- trunk/Ohana/src/opihi/mana/deimos.c	(revision 41326)
+++ trunk/Ohana/src/opihi/mana/deimos.c	(revision 41340)
@@ -4,23 +4,19 @@
 int deimos_fitslit (int argc, char **argv);
 int deimos_mkobj (int argc, char **argv);
+int deimos_mkalt (int argc, char **argv);
 int deimos_getobj (int argc, char **argv);
-// int deimos_getalt (int argc, char **argv);
 int deimos_fitobj (int argc, char **argv);
-// int deimos_fitalt (int argc, char **argv);
+int deimos_fitalt (int argc, char **argv);
 int deimos_arclines (int argc, char **argv);
-int deimos_fitarc (int argc, char **argv);
-int deimos_fitprofile (int argc, char **argv);
 
 static Command deimos_commands[] = {
-  {1, "fitobj",     deimos_fitobj,     "fit for object parameters using LMM"},
-  {1, "fitalt",     deimos_fitobj,     "fit for object parameters using LMM"},
-  {1, "getobj",     deimos_getobj,     "determine crude object parameters"},
-  {1, "getalt",     deimos_getobj,     "determine crude object parameters"},
-  {1, "mkobj",      deimos_mkobj,      "make a full object image"},
-  {1, "mkslit",     deimos_mkslit,     "make a slit image"},
-  {1, "fitslit",    deimos_fitslit,    "fit slit image to observed slit flux"},
-  {1, "arclines",   deimos_arclines,   "detect arclines using LSF and STILT"},
-  {1, "fitarc",     deimos_fitarc,     "fit arclamp lines"},
-  {1, "fitprofile", deimos_fitprofile, "fit slit profile"},
+  {1, "fitobj", deimos_fitobj, "fit for object parameters"},
+  {1, "fitalt", deimos_fitalt, "fit for object parameters using LMM"},
+  {1, "getobj", deimos_getobj, "determine crude object parameters"},
+  {1, "mkobj", deimos_mkobj, "make a full object image"},
+  {1, "mkalt", deimos_mkalt, "make a full object image (uses deimos_make_object, for a test)"},
+  {1, "mkslit", deimos_mkslit, "make a slit image"},
+  {1, "fitslit", deimos_fitslit, "fit slit image to observed slit flux"},
+  {1, "arclines", deimos_arclines, "detect arclines using LSF and STILT"},
 };
 
Index: trunk/Ohana/src/opihi/mana/deimos_arclines.c
===================================================================
--- trunk/Ohana/src/opihi/mana/deimos_arclines.c	(revision 41326)
+++ trunk/Ohana/src/opihi/mana/deimos_arclines.c	(revision 41340)
@@ -53,14 +53,7 @@
   deimos_make_LSF_kernel (LSF, stilt, Nx);
 
-  // FILE *Fout = NULL;
-
   // loop over the rows
   for (int iy = 0; iy < Ny; iy++) {
     float Fsum = 0;
-    float Ksum = 0;
-
-    // if (iy == 5802) Fout = fopen ("test.5802.dat", "w");
-    // if (iy == 5815) Fout = fopen ("test.5815.dat", "w");
-
     // cross-correlation of buffer values and kernel values
     for (int ix = 0; ix < Nx; ix++) {
@@ -69,16 +62,7 @@
 	if ((iy + ky) < 0) continue;
 	if ((iy + ky) >= Ny) continue;
-	if (!isfinite(Fin[ix + (iy + ky)*Nx])) continue;
-	if (!isfinite(kernel[ix + ko*Nx])) continue;
 	Fsum += Fin[ix + (iy + ky)*Nx] * kernel[ix + ko*Nx];
-	Ksum += kernel[ix + ko*Nx];
-	// if ((iy == 5815) || (iy == 5802)) {
-	//   fprintf (Fout, "%d %d %d : %f %f\n", iy, ix, ky, Fin[ix + (iy + ky)*Nx], kernel[ix + ko*Nx]);
-	// }
       }
     }
-
-    // if ((iy == 5815) || (iy == 5802)) fclose (Fout);
-
     coord->elements.Flt[iy] = iy;
     flux->elements.Flt[iy] = Fsum;
Index: trunk/Ohana/src/opihi/mana/deimos_fitalt.c
===================================================================
--- trunk/Ohana/src/opihi/mana/deimos_fitalt.c	(revision 41340)
+++ trunk/Ohana/src/opihi/mana/deimos_fitalt.c	(revision 41340)
@@ -0,0 +1,447 @@
+# include "data.h"
+# include "deimos.h"
+
+# if (0) 
+int deimos_fitalt (int argc, char **argv) {
+  OHANA_UNUSED_PARAM(argc);
+  OHANA_UNUSED_PARAM(argv);
+  return FALSE;
+}
+
+# else
+
+/*
+  this is starting to work OK.  some improvements to make
+  * use Gaussdev to sample
+  * do not scale down range (or user-set scale-down)
+ */
+
+// internal functions to fitobj
+static float      deimos_get_chisq (float *buffer, float *model, int Nx, int Ny, int row, int *Npts);
+double            deimos_LMM_update (float *data, float *model_ref, float *model_obj, float *model_sky, float *model_bck, float *dObj, float *dSky, float *dBck, int Nx, int Ny, int row, float lambda);
+static opihi_flt *deimos_make_test (opihi_flt *guess, float sigma, int row, int Nrow, float *dValue);
+opihi_flt        *deimos_subvector (opihi_flt *fullVec, int row, int Nrow);
+
+int deimos_fitalt (int argc, char **argv) {
+
+  // input parameters:
+  // * buffer      : 2D image of slit (full frame or cutout?)
+  // * trace       : spline fit of slit central x pos vs y-coord
+  // * profile     : slit window profile (vector)
+  // * PSF         : point-spread function vector (flux normalized, x-dir)
+  // * stilt       : slit tilt response : 2D kernel? 
+
+  // in-out parameters:
+  // * obj  : vector of object flux vs y-coord (starting guess and result)
+  // * sky  : vector of local sky signal vs y-coord 
+  // * bck  : vector of extra-slit background flux vs y-coord
+
+  int N;
+
+  Spline *trace   = NULL;
+  Vector *profile = NULL;
+
+  Vector *obj     = NULL;
+  Vector *sky     = NULL;
+  Vector *bck     = NULL;
+
+  Vector *psf     = NULL;
+
+  Buffer *buffer  = NULL;
+
+  float stilt = 0.0; // angle of the slit
+  ohana_gaussdev_init ();
+
+  int DO_PLUS = FALSE;
+  if ((N = get_argument (argc, argv, "-plus"))) {
+    remove_argument (N, &argc, argv);
+    DO_PLUS = TRUE;
+  }
+
+  int VERBOSE = FALSE;
+  if ((N = get_argument (argc, argv, "-v"))) {
+    remove_argument (N, &argc, argv);
+    VERBOSE = TRUE;
+  }
+
+  // a crude noise model valid for both the guess vectors and the
+  // data buffer:
+  float gain = 1.0;
+  if ((N = get_argument (argc, argv, "-gain"))) {
+    remove_argument (N, &argc, argv);
+    gain = atof(argv[N]);
+    remove_argument (N, &argc, argv);
+  }
+  float noise = 0.0;
+  if ((N = get_argument (argc, argv, "-noise"))) {
+    remove_argument (N, &argc, argv);
+    noise = atof(argv[N]);
+    remove_argument (N, &argc, argv);
+  }
+  float nsigma = 2.0;
+  if ((N = get_argument (argc, argv, "-nsigma"))) {
+    remove_argument (N, &argc, argv);
+    nsigma = atof(argv[N]);
+    remove_argument (N, &argc, argv);
+  }
+  float lambda = 1.0;
+  if ((N = get_argument (argc, argv, "-lambda"))) {
+    remove_argument (N, &argc, argv);
+    lambda = atof(argv[N]);
+    remove_argument (N, &argc, argv);
+  }
+
+  int Niter = 25;
+  if ((N = get_argument (argc, argv, "-iter"))) {
+    remove_argument (N, &argc, argv);
+    Niter = atoi(argv[N]);
+    remove_argument (N, &argc, argv);
+  }
+  int Nrow = 5;
+  if ((N = get_argument (argc, argv, "-row"))) {
+    remove_argument (N, &argc, argv);
+    Nrow = atoi(argv[N]);
+    remove_argument (N, &argc, argv);
+  }
+
+  // Input parameters:
+  if ((N = get_argument (argc, argv, "-trace"))) {
+    remove_argument (N, &argc, argv);
+    if ((trace = FindSpline (argv[N])) == NULL) return (FALSE);
+    remove_argument (N, &argc, argv);
+  } else { goto usage; }
+  if ((N = get_argument (argc, argv, "-profile"))) {
+    remove_argument (N, &argc, argv);
+    if ((profile = SelectVector (argv[N], OLDVECTOR, TRUE)) == NULL) return (FALSE);
+    remove_argument (N, &argc, argv);
+  } else { goto usage; }
+  if ((N = get_argument (argc, argv, "-psf"))) {
+    remove_argument (N, &argc, argv);
+    if ((psf = SelectVector (argv[N], OLDVECTOR, TRUE)) == NULL) return (FALSE);
+    remove_argument (N, &argc, argv);
+  } else { goto usage; }
+  if ((N = get_argument (argc, argv, "-stilt"))) {
+    remove_argument (N, &argc, argv);
+    stilt = atof (argv[N]);
+    remove_argument (N, &argc, argv);
+  } else { goto usage; }
+
+  // In-Out parameters:
+  if ((N = get_argument (argc, argv, "-object"))) {
+    remove_argument (N, &argc, argv);
+    if ((obj = SelectVector (argv[N], OLDVECTOR, TRUE)) == NULL) return (FALSE);
+    remove_argument (N, &argc, argv);
+  } else { goto usage; }
+  if ((N = get_argument (argc, argv, "-sky"))) {
+    remove_argument (N, &argc, argv);
+    if ((sky = SelectVector (argv[N], OLDVECTOR, TRUE)) == NULL) return (FALSE);
+    remove_argument (N, &argc, argv);
+  } else { goto usage; }
+  if ((N = get_argument (argc, argv, "-backgnd"))) {
+    remove_argument (N, &argc, argv);
+    if ((bck = SelectVector (argv[N], OLDVECTOR, TRUE)) == NULL) return (FALSE);
+    remove_argument (N, &argc, argv);
+  } else { goto usage; }
+
+  if (argc != 3) goto usage;
+
+  // buffer is the full image, Xref is reference coordinate of the profile in the buffer
+  if ((buffer = SelectBuffer (argv[1], OLDBUFFER, TRUE)) == NULL) return (FALSE);
+  
+  // profile and PSF are defined with central reference pixel mapped to Xref (+ trace)
+  if (profile->Nelements % 2 == 0) {
+    gprint (GP_ERR, "slit profile vector must have an odd number of pixels\n");
+    return FALSE;
+  }
+  if (psf->Nelements % 2 == 0) {
+    gprint (GP_ERR, "PSF vector must have an odd number of pixels\n");
+    return FALSE;
+  }
+
+  // observed buffer size
+  int Nx = buffer[0].matrix.Naxis[0];
+  int Ny = buffer[0].matrix.Naxis[1];
+  float *bufVal = (float *) buffer->matrix.buffer;
+
+  // obj, sky, bck must be consistent with data
+  if (Ny != obj->Nelements) {
+    gprint (GP_ERR, "inconsistent wavelength scales (object)\n");
+    return FALSE;
+  }
+  if (Ny != sky->Nelements) {
+    gprint (GP_ERR, "inconsistent wavelength scales (sky)\n");
+    return FALSE;
+  }
+  if (Ny != bck->Nelements) {
+    gprint (GP_ERR, "inconsistent wavelength scales (backgnd)\n");
+    return FALSE;
+  }
+
+  // for the cross-dispersion reference pixel, use the user value or set to Nx/2 if < 0
+  deimos_set_cross_ref (atoi(argv[2]), Nx); 
+  deimos_make_kernel (stilt, Nx);
+
+  Vector  *objMin = NULL;
+  Vector  *skyMin = NULL;
+  Vector  *bckMin = NULL;
+
+  if ((objMin = SelectVector ("objMin", ANYVECTOR, TRUE)) == NULL) { return (FALSE); } ResetVector (objMin, OPIHI_FLT, Ny);
+  if ((skyMin = SelectVector ("skyMin", ANYVECTOR, TRUE)) == NULL) { return (FALSE); } ResetVector (skyMin, OPIHI_FLT, Ny);
+  if ((bckMin = SelectVector ("bckMin", ANYVECTOR, TRUE)) == NULL) { return (FALSE); } ResetVector (bckMin, OPIHI_FLT, Ny);
+
+  // the functions below accept an opihi_flt array for object, sky, background
+  opihi_flt *objVal = objMin->elements.Flt;
+  opihi_flt *skyVal = skyMin->elements.Flt;
+  opihi_flt *bckVal = bckMin->elements.Flt;
+
+  // we make a copy of the input guess vectors and minimize them
+  for (int iy = 0; iy < Ny; iy++) {
+    objVal[iy] = obj->elements.Flt[iy];
+    skyVal[iy] = sky->elements.Flt[iy];
+    bckVal[iy] = bck->elements.Flt[iy];
+  }
+
+  float noiseVar = SQ(noise);
+  ALLOCATE_PTR (objNoise, float, Ny);
+  ALLOCATE_PTR (skyNoise, float, Ny);
+  ALLOCATE_PTR (bckNoise, float, Ny);
+
+  // generate noise vectors
+  for (int iy = 0; iy < Ny; iy++) {
+    objNoise[iy] = nsigma*sqrt(hypot(fabs(objVal[iy]) / gain, noiseVar));
+    skyNoise[iy] = nsigma*sqrt(hypot(fabs(skyVal[iy]) / gain, noiseVar));
+    bckNoise[iy] = nsigma*sqrt(hypot(fabs(bckVal[iy]) / gain, noiseVar));
+  }
+
+  // obj, sky, bck are initial guesses.  Also use these values to define a range for the initial guesses.
+
+  // XXX worry about last segment (< Nrow rows)
+  for (int iter = 0; iter < Niter; iter++) {
+
+    int dRow = Nrow/2;
+
+    // use scaled-noise to define test ranges
+    // we are going to try each row using a window Nrow wide to measure chisq:
+    for (int row = dRow; row < Ny - dRow - 1; row++) {
+      
+      // I am using a numerical equivalent of Levenberg-Marquardt, but only for a single
+      // p_m[i] = (obj,sky,bck) triplet [m is the index of obj,sky,bck; i is the row
+      // index] at a time.  I start with a current best guess set of (obj,sky,bck).  I
+      // need to calculate the model at this location, and then at offset locations p_m +
+      // dp_m.  Note that I do not need to calculate chisq for each of these to generate
+      // the elements of the LMM equations:
+
+      int row_0 = row - dRow; // start row of the subset test range
+
+      // Nrow = 5, dRow = 2, Ny = 100, last start is Ny - 2 - 1 = 97
+      // last row_0 is 95
+
+      // generate subset vectors for the range **centered** on row
+      opihi_flt *objCurr = deimos_subvector (objVal, row_0, Nrow);
+      opihi_flt *skyCurr = deimos_subvector (skyVal, row_0, Nrow);
+      opihi_flt *bckCurr = deimos_subvector (bckVal, row_0, Nrow);
+
+      // current vector value:
+      // for deimos_make_model, row is the starting point of the subimage
+      float *model_ref = deimos_make_model (objCurr, skyCurr, bckCurr, psf, profile, trace, Nx, Nrow, row_0);
+
+      // in the test functions below, dRow is the central pixel of the subset, e.g., obj[row] => objCurr[dRow]
+
+      float dObj = 0.0, dSky = 0.0, dBck = 0.0;
+
+      // delta obj (save dObj)
+      opihi_flt *objtest = deimos_make_test (objCurr, objNoise[row], dRow, Nrow, &dObj);
+      float *model_obj = deimos_make_model (objtest, skyCurr, bckCurr, psf, profile, trace, Nx, Nrow, row_0);
+
+      // delta sky (save dSky)
+      opihi_flt *skytest = deimos_make_test (skyCurr, skyNoise[row], dRow, Nrow, &dSky);
+      float *model_sky = deimos_make_model (objCurr, skytest, bckCurr, psf, profile, trace, Nx, Nrow, row_0);
+
+      // delta bck (save dBck)
+      opihi_flt *bcktest = deimos_make_test (bckCurr, bckNoise[row], dRow, Nrow, &dBck);
+      float *model_bck = deimos_make_model (objCurr, skyCurr, bcktest, psf, profile, trace, Nx, Nrow, row_0);
+
+      // dObj, dSky, dBck carry the delta used derivatives in and the delta applied to the values out
+      float chisq = deimos_LMM_update (bufVal, model_ref, model_obj, model_sky, model_bck, &dObj, &dSky, &dBck, Nx, Nrow, row_0, lambda);
+
+      if (1) {
+	if (DO_PLUS) {
+	  objVal[row] += dObj;
+	  skyVal[row] += dSky;
+	  bckVal[row] += dBck;
+	} else {
+	  objVal[row] -= dObj;
+	  skyVal[row] -= dSky;
+	  bckVal[row] -= dBck;
+	}
+      }
+
+      free (objCurr);
+      free (skyCurr);
+      free (bckCurr);
+
+      free (model_ref);
+
+      free (model_obj);
+      free (model_sky);
+      free (model_bck);
+
+      free (objtest);
+      free (skytest);
+      free (bcktest);
+
+      if (VERBOSE) fprintf (stderr, "chisq: %f (%f, %f, %f)\n", chisq, dObj, dSky, dBck);
+    }
+
+    float *model_full = deimos_make_model (objVal, skyVal, bckVal, psf, profile, trace, Nx, Ny, 0);
+
+    int Npts = 0;
+    float chisq_full  = deimos_get_chisq (bufVal, model_full, Nx, Ny, 0, &Npts);
+
+    fprintf (stderr, "** Full chisq: %f (%d) : %f)\n", chisq_full, Npts, chisq_full / (1.0 * Npts));
+  }
+
+  return TRUE;
+
+ usage:
+  gprint (GP_ERR, "USAGE: deimos fitobj (buffer) (Xref) -object vector -sky vector -backgnd vector -trace spline -profile vector -psf vector -stilt (angle)\n");
+  return FALSE;
+}
+
+/****************** fitobj Support Functions *******************/
+
+// we generate a new vector with a single element (row) modified based on sigma
+opihi_flt *deimos_subvector (opihi_flt *fullVec, int row, int Nrow) {
+
+  ALLOCATE_PTR (value, opihi_flt, Nrow);
+
+  for (int i = 0; i < Nrow; i++) {
+    value[i] = fullVec[i + row];
+  }
+
+  return value;
+}
+
+
+// we generate a new vector with a single element (row) modified based on sigma
+static opihi_flt *deimos_make_test (opihi_flt *guess, float sigma, int row, int Nrow, float *dValue) {
+
+  // if fullInput is TRUE,  the guess vector runs from 0 to Ny (full wavelength range)
+  // if fullInput is FALSE, the guess vector runs from row to row + Nrow (subset range)
+  // sigma is valid for the element at row
+
+  ALLOCATE_PTR (value, opihi_flt, Nrow);
+
+  for (int i = 0; i < Nrow; i++) {
+    value[i] = guess[i];
+  }
+
+  value[row] = guess[row] + 0.1*sigma;
+
+  *dValue = 0.1*sigma;
+  return value;
+}
+
+
+double deimos_LMM_update (float *data, float *model_ref,
+			  float *model_obj, float *model_sky, float *model_bck,
+			  float *dObj, float *dSky, float *dBck, int Nx, int Ny, int row, float lambda) {
+  
+  // we are going to loop over the images calculating the following value:
+
+  // W = 1 / sigma^2, leave as 1.0 for now
+  // chisq = sum W * (data - model_ref)^2 
+  // dF_X = sum W * (data - model_ref) * (model_ref - model_X) / dX
+  // d2F_XY = sum W * (model_ref - model_X) * (model_ref - model_Y) / (dX * dY)
+
+  double chisq = 0.0;
+  double dF_obj = 0.0, dF_sky = 0.0, dF_bck = 0.0;
+  double d2F_obj_obj = 0.0, d2F_obj_sky = 0.0, d2F_obj_bck = 0.0, d2F_sky_sky = 0.0, d2F_sky_bck = 0.0, d2F_bck_bck = 0.0;
+
+  float W = 1.0;
+
+  for (int iy = 0; iy < Ny; iy++) {
+    for (int ix = 0; ix < Nx; ix++) {
+      int pix = ix + iy*Nx;
+      int pix_data  = ix + (iy + row)*Nx;
+
+      // if any of the pixel values are NAN, skip the point:
+      if (!isfinite(data[pix_data])) continue;
+      if (!isfinite(model_ref[pix])) continue;
+      if (!isfinite(model_obj[pix])) continue;
+      if (!isfinite(model_sky[pix])) continue;
+      if (!isfinite(model_bck[pix])) continue;
+
+      float df = W * (data[pix_data] - model_ref[pix]);
+
+      chisq += SQ(df);
+
+      float df_obj = (model_ref[pix] - model_obj[pix]) / *dObj;
+      float df_sky = (model_ref[pix] - model_sky[pix]) / *dSky;
+      float df_bck = (model_ref[pix] - model_bck[pix]) / *dBck;
+
+      dF_obj += df*df_obj;
+      dF_sky += df*df_sky;
+      dF_bck += df*df_bck;
+
+      d2F_obj_obj += W * SQ(df_obj);
+      d2F_sky_sky += W * SQ(df_sky);
+      d2F_bck_bck += W * SQ(df_bck);
+
+      d2F_obj_sky += W * df_obj * df_sky;
+      d2F_obj_bck += W * df_obj * df_bck;
+      d2F_sky_bck += W * df_sky * df_bck;
+    }
+  }
+
+  // these are the elements of Ax = B
+  ALLOCATE_PTR (A, double *, 3);
+  ALLOCATE_PTR (B, double *, 3);
+  for (int i = 0; i < 3; i++) {
+    ALLOCATE (A[i], double, 3);
+    ALLOCATE (B[i], double, 1);
+  }
+
+  A[0][0] = d2F_obj_obj * (1.0 + lambda);
+  A[1][1] = d2F_sky_sky * (1.0 + lambda);
+  A[2][2] = d2F_bck_bck * (1.0 + lambda);
+
+  A[0][1] = A[1][0] = d2F_obj_sky;
+  A[1][2] = A[2][1] = d2F_sky_bck;
+  A[0][2] = A[2][0] = d2F_obj_bck;
+
+  B[0][0] = dF_obj;
+  B[1][0] = dF_sky;
+  B[2][0] = dF_bck;
+
+  dgaussjordan (A, B, 3, 1);
+
+  *dObj = B[0][0];
+  *dSky = B[1][0];
+  *dBck = B[2][0];
+
+  return chisq;
+}
+
+static float deimos_get_chisq (float *buffer, float *model, int Nx, int Ny, int row, int *Npts) {
+
+  int npts = 0;
+  float chisq = 0;
+
+  for (int iy = 0; iy < Ny; iy++) {
+
+    for (int ix = 0; ix < Nx; ix++) {
+
+      int pix_buffer = ix + (iy + row)*Nx;
+      int pix_model  = ix +  iy*Nx;
+
+      if (!isfinite(buffer[pix_buffer])) continue;
+      if (!isfinite(model[pix_model])) continue;
+      chisq += SQ(buffer[pix_buffer] - model[pix_model]);
+      npts ++;
+    }
+  }
+  *Npts = npts;
+  return chisq;
+}
+# endif
Index: trunk/Ohana/src/opihi/mana/deimos_fitarc.c
===================================================================
--- trunk/Ohana/src/opihi/mana/deimos_fitarc.c	(revision 41326)
+++ 	(revision )
@@ -1,237 +1,0 @@
-# include "data.h"
-# define NPAR 4
-
-typedef opihi_flt FitFunc (opihi_flt, opihi_flt *, int, opihi_flt *);
-
-opihi_flt fgaussOD (opihi_flt x, opihi_flt *par, int Npar, opihi_flt *dpar);
-
-void gaussian_fit_irls (opihi_flt *xprofile, opihi_flt *fprofile, opihi_flt *wprofile, opihi_flt *oprofile, int Npts, opihi_flt *par, int Npar);
-void gaussian_fit (opihi_flt *xprofile, opihi_flt *fprofile, opihi_flt *wprofile, opihi_flt *oprofile, int Npts, opihi_flt *par, int Npar, FitFunc *FUNC);
-
-double deimos_weight_cauchy (double x);
-
-// use these globals to carry into sigmoid_fit
-static int VERBOSE = FALSE;
-static int QUIET   = FALSE;
-static int MaxIterations = 10;
-
-/* fitarc buffer Xo Yo Nx Ny 
-
- * for each col, fit the y-dir profile with a gauss
- * fit the C0 values to a line to get the angle
- */
-
-int deimos_fitarc (int argc, char **argv) {
-
-  // input parameters:
-  // * xprofile    : extracted slit window coordinates (vector)
-  // * xprofile    : extracted slit window profile (vector)
-  // * Xs, Xe      : scale coordinates of window boundaries
-
-  // output parameters:
-  // * sigmoid_left_center, etc : coordinates of window boundaries
-
-  int N;
-  Buffer *buffer  = NULL;
-
-  QUIET = FALSE;
-  if ((N = get_argument (argc, argv, "-q"))) {
-    QUIET = TRUE;
-    remove_argument (N, &argc, argv);
-  }
-  if ((N = get_argument (argc, argv, "-quiet"))) {
-    QUIET = TRUE;
-    remove_argument (N, &argc, argv);
-  }
-  VERBOSE = FALSE;
-  if ((N = get_argument (argc, argv, "-v"))) {
-    VERBOSE = TRUE;
-    remove_argument (N, &argc, argv);
-  }
-  MaxIterations = 10;
-  if ((N = get_argument (argc, argv, "-max-iterations"))) {
-    remove_argument (N, &argc, argv);
-    MaxIterations = atof(argv[N]);
-    remove_argument (N, &argc, argv);
-  }
-
-  Buffer *residbuf = NULL;
-  if ((N = get_argument (argc, argv, "-resid"))) {
-    remove_argument (N, &argc, argv);
-    residbuf = SelectBuffer (argv[N], ANYBUFFER, TRUE);
-    if (!residbuf) goto usage;
-    remove_argument (N, &argc, argv);
-  }
-  
-  Buffer *varbuf = NULL;
-  if ((N = get_argument (argc, argv, "-varbuf"))) {
-    remove_argument (N, &argc, argv);
-    varbuf = SelectBuffer (argv[N], OLDBUFFER, TRUE);
-    if (!varbuf) goto usage;
-    remove_argument (N, &argc, argv);
-  }
-  
-  if (argc != 6) goto usage;
-  if ((buffer = SelectBuffer (argv[1], OLDBUFFER, TRUE)) == NULL) return (FALSE);
-
-  int nx = buffer[0].matrix.Naxis[0];
-  int ny = buffer[0].matrix.Naxis[1];
-
-  // supplied guess for boundaries
-  int Xs = atof(argv[2]);
-  int Ys = atof(argv[3]);
-  int Nx = atof(argv[4]);
-  int Ny = atof(argv[5]);
-
-  if (residbuf) {
-    ResetBuffer (residbuf, nx, ny, -32, 0.0, 1.0);
-  }
-
-  // validate Xs, Ys, Nx, Ny
-  // Xs + Nx <= nx
-
-  // loop over the cols
-
-  ALLOCATE_PTR (xcol, double, Ny);
-  ALLOCATE_PTR (ycol, double, Ny);
-  ALLOCATE_PTR (ocol, double, Ny); // fitted value
-
-  float *bufVal = (float *) buffer->matrix.buffer;
-
-  for (int ix = Xs; ix < Xs + Nx; ix++) {
-
-    // loop over the pixels in this column to get the x and y vectors
-    // find the peak at the same time
-
-    double xmax = -HUGE_VAL;
-    double ymax = -HUGE_VAL;
-    int Nc = 0;
-
-    for (int iy = 0; iy < Ny; iy++) {
-
-      float yval = bufVal[ix + (iy + Ys)*Nx];
-      if (!isfinite(yval)) continue;
-
-      xcol[Nc] = iy + Ys;
-      ycol[Nc] = yval;
-
-      if (yval > ymax) {
-	ymax = yval;
-	xmax = iy + Ys;
-      }
-      Nc ++;
-    }
-
-    // now do a Gauss fit given C0 = xmax, C1 = 2, C2 = ymax, C3 = 0
-    
-    // temporary storage vectors 
-    opihi_flt par[NPAR];
-    par[0] = xmax;
-    par[1] = 2;
-    par[2] = ymax;
-    par[3] = 0;
-    gaussian_fit_irls (xcol, ycol, NULL, ocol, Nc, par, NPAR);
-
-    fprintf (stderr, "%d : %f %f : %f %f\n", ix, par[0], par[2], par[1], par[3]);
-    set_variable ("C0", par[0]);
-    set_variable ("C1", par[1]);
-    set_variable ("C2", par[2]);
-    set_variable ("C3", par[3]);
-
-    if (residbuf) {
-      float *residVal = (float *) residbuf->matrix.buffer;
-      for (int iy = 0; iy < Ny; iy++) {
-	float yval = fgaussOD (iy + Ys, par, NPAR, NULL);
-	// residVal[ix + (iy + Ys)*Nx] = bufVal[ix + (iy + Ys)*Nx] - yval;
-	residVal[ix + (iy + Ys)*Nx] = yval;
-      }
-    }
-  } 
-
-  return TRUE;
-  
- usage:
-  gprint (GP_ERR, "USAGE: deimos fitarc buff Xo Yo Nx Ny\n");
-  gprint (GP_ERR, " [-resid buffer] : output residual image\n");
-  gprint (GP_ERR, " [-varbuf buffer] : input variance image\n");
-  return FALSE;
-}
-
-# define FIT_TOLERANCE 1e-4
-# define FLT_TOLERANCE 1e-6
-
-// xprofile : x-coordinate
-// fprofile : flux (counts)
-// wprofile : weight (true poisson error)
-// oprofile : output profile (not used?)
-void gaussian_fit_irls (opihi_flt *xprofile, opihi_flt *fprofile, opihi_flt *wprofile, opihi_flt *oprofile, int Npts, opihi_flt *par, int Npar) {
-  
-  // buffer to store result from each iteration
-  ALLOCATE_PTR (par_old, opihi_flt, Npar);
-
-  // define initial weights as 1.0
-  ALLOCATE_PTR (wt, opihi_flt, Npts);
-  ALLOCATE_PTR (wtemp, opihi_flt, Npts);
-  for (int i = 0; i < Npts; i++) { 
-    wtemp[i] = wprofile ? (fabs(wprofile[i]) > 1e-5 ? wprofile[i] : 1e-5) : 1.0;
-    wt[i] = 1.0 / SQ(wtemp[i]);
-  }
-
-  // initial fit with ordinary least-squares
-  // otemp is the fitted value of the function at xtemp
-  gaussian_fit (xprofile, fprofile, wt, NULL, Npts, par, Npar, fgaussOD);
-
-  int converged = FALSE;
-  for (int iterations = 0; !converged && (iterations < MaxIterations); iterations++) {
-
-    for (int i = 0; i < Npts; i++) {
-      wt[i] = deimos_weight_cauchy ((fprofile[i] - oprofile[i]) / wtemp[i]) / SQ(wtemp[i]);
-    }
-
-    gaussian_fit (xprofile, fprofile, wt, oprofile, Npts, par, Npar, fgaussOD);
-
-    // save this solution
-    for (int i = 0; i < Npar; i++) {
-      par_old[i] = par[i];
-    }
-
-    converged = TRUE;
-    for (int i = 0; i < Npts; i++) {
-      if ((fabs(par[i] - par_old[i]) > FIT_TOLERANCE * fabs(par[i])) && 
-	  (fabs(par[i] - par_old[i]) > FLT_TOLERANCE))
-	converged = FALSE;
-    }
-  }
-
-  for (int i = 0; i < Npts; i++) {
-    oprofile[i] = fgaussOD (xprofile[i], par, Npar, NULL);
-  }
-
-  FREE (par_old);
-  FREE (wt);
-}
-
-void gaussian_fit (opihi_flt *xprofile, opihi_flt *fprofile, opihi_flt *wprofile, opihi_flt *oprofile, int Npts, opihi_flt *par, int Npar, FitFunc *FUNC) {
-
-  double ochisq = mrqinit (xprofile, fprofile, wprofile, Npts, par, Npar, FUNC, VERBOSE);
-  double dchisq = ochisq + 2*Npts;
-
-  int Niter;
-  for (Niter = 0; (Niter < 20) && ((dchisq > 0.1*(Npts - Npar)) || (dchisq <= 0.0)); Niter++) {
-    double chisq = mrqmin (xprofile, fprofile, wprofile, Npts, par, Npar, FUNC, VERBOSE);
-    dchisq = ochisq - chisq;
-    ochisq = chisq;
-    if (VERBOSE) gprint (GP_ERR, "dchisq: %f, Ndof: %d\n", dchisq, Npts - Npar);
-  }  
-  if (VERBOSE) gprint (GP_ERR, "%d iterations\n", Niter); 
-
-  if (!QUIET) gprint (GP_LOG, "gauss @ %f (%f) : top %f bottom %f\n", par[0], par[1], par[2], par[3]);
-
-  if (oprofile) {
-    for (int i = 0; i < Npts; i++) {
-      oprofile[i] = FUNC (xprofile[i], par, Npar, NULL);
-    }
-  }
-
-  mrqfree (Npar);
-}  
Index: trunk/Ohana/src/opihi/mana/deimos_fitobj.c
===================================================================
--- trunk/Ohana/src/opihi/mana/deimos_fitobj.c	(revision 41326)
+++ trunk/Ohana/src/opihi/mana/deimos_fitobj.c	(revision 41340)
@@ -1,4 +1,13 @@
 # include "data.h"
 # include "deimos.h"
+
+# if (0) 
+int deimos_fitobj (int argc, char **argv) {
+  OHANA_UNUSED_PARAM(argc);
+  OHANA_UNUSED_PARAM(argv);
+  return FALSE;
+}
+
+# else
 
 /*
@@ -9,19 +18,19 @@
 
 // internal functions to fitobj
-static float      deimos_get_chisq (float *buffer, float *vardata, float *model, int Nx, int Ny, int row, int *Npts);
-double            deimos_LMM_update (float *data, float *vardata, float *model_ref, float *model_obj, float *model_sky, float *model_bck, float *dObj, float *dSky, float *dBck, int Nx, int Ny, int row, float lambda);
-static opihi_flt *deimos_make_test (opihi_flt *guess, float sigma, int row, int Nrow, float *dValue);
-opihi_flt        *deimos_subvector (opihi_flt *fullVec, int row, int Nrow);
+static float      deimos_get_chisq (float *buffer, float *model, int Nx, int Ny, int row, int *Npts);
+int              *deimos_sort_result (DeimosResult *result, int Nresult);
+int               deimos_get_random_sample (int Nresult);
+static opihi_flt *deimos_make_test (opihi_flt *guess, float *sigma, int row, int Nrow, int fullInput);
+
+int USE_GAUSS_DEV = FALSE;
 
 int deimos_fitobj (int argc, char **argv) {
 
   // input parameters:
-  // * buffer         : 2D image of slit (full frame or cutout?)
-  // * slit_trace_red : spline fit of slit central x pos vs y-coord
-  // * slit_trace_blu : spline fit of slit central x pos vs y-coord
-  // * psf_trace      : spline fit of slit central x pos vs y-coord
-  // * profile        : slit window profile (vector)
-  // * PSF            : point-spread function vector (flux normalized, x-dir)
-  // * stilt          : slit tilt response : 2D kernel? 
+  // * buffer      : 2D image of slit (full frame or cutout?)
+  // * trace       : spline fit of slit central x pos vs y-coord
+  // * profile     : slit window profile (vector)
+  // * PSF         : point-spread function vector (flux normalized, x-dir)
+  // * stilt       : slit tilt response : 2D kernel? 
 
   // in-out parameters:
@@ -32,48 +41,17 @@
   int N;
 
-  Spline *slit_trace_red = NULL;
-  Spline *slit_trace_blu = NULL;
-  Spline *psf_trace  = NULL;
-
-  Vector *profile    = NULL;
-  Vector *psf        = NULL;
-
-  Vector *obj        = NULL;
-  Vector *sky        = NULL;
-  Vector *bck        = NULL;
-
-  Buffer *buffer     = NULL;
-
-  float stilt        = 0.0; // angle of the slit
-
+  Spline *trace   = NULL;
+  Vector *profile = NULL;
+
+  Vector *obj     = NULL;
+  Vector *sky     = NULL;
+  Vector *bck     = NULL;
+
+  Vector *psf     = NULL;
+
+  Buffer *buffer  = NULL;
+
+  float stilt = 0.0; // angle of the slit
   ohana_gaussdev_init ();
-
-  int DO_PLUS = FALSE;
-  if ((N = get_argument (argc, argv, "-plus"))) {
-    remove_argument (N, &argc, argv);
-    DO_PLUS = TRUE;
-  }
-
-  int VERBOSE = FALSE;
-  if ((N = get_argument (argc, argv, "-v"))) {
-    remove_argument (N, &argc, argv);
-    VERBOSE = TRUE;
-  }
-
-  int SKIPFIT = FALSE;
-  if ((N = get_argument (argc, argv, "-skipfit"))) {
-    remove_argument (N, &argc, argv);
-    SKIPFIT = TRUE;
-  }
-
-  // for a red vs blu spline, we need to specify the split point
-  // XXX this is REALLY ad-hoc for Deimos.  not sure how to make
-  // this more generic (need to define the ranges somewhere)
-  int redlimit = 4096;
-  if ((N = get_argument (argc, argv, "-redlimit"))) {
-    remove_argument (N, &argc, argv);
-    redlimit = atoi (argv[N]);
-    remove_argument (N, &argc, argv);
-  }
 
   // a crude noise model valid for both the guess vectors and the
@@ -97,10 +75,11 @@
     remove_argument (N, &argc, argv);
   }
-  float lambda = 1.0;
-  if ((N = get_argument (argc, argv, "-lambda"))) {
-    remove_argument (N, &argc, argv);
-    lambda = atof(argv[N]);
-    remove_argument (N, &argc, argv);
-  }
+  float scale = 0.75;
+  if ((N = get_argument (argc, argv, "-scale"))) {
+    remove_argument (N, &argc, argv);
+    scale = atof(argv[N]);
+    remove_argument (N, &argc, argv);
+  }
+
 
   int Niter = 25;
@@ -110,4 +89,10 @@
     remove_argument (N, &argc, argv);
   }
+  int Ntry = 5;
+  if ((N = get_argument (argc, argv, "-try"))) {
+    remove_argument (N, &argc, argv);
+    Ntry = atoi(argv[N]);
+    remove_argument (N, &argc, argv);
+  }
   int Nrow = 5;
   if ((N = get_argument (argc, argv, "-row"))) {
@@ -117,19 +102,26 @@
   }
 
+  USE_GAUSS_DEV = FALSE;
+  if ((N = get_argument (argc, argv, "-gaussdev"))) {
+    remove_argument (N, &argc, argv);
+    USE_GAUSS_DEV = TRUE;
+  }
+
+  int SAVE_ALL_VECTORS = FALSE;
+  if ((N = get_argument (argc, argv, "-save-all-vectors"))) {
+    remove_argument (N, &argc, argv);
+    SAVE_ALL_VECTORS = TRUE;
+  }
+
+  int SAVE_MIN_VECTORS = FALSE;
+  if ((N = get_argument (argc, argv, "-save-min-vectors"))) {
+    remove_argument (N, &argc, argv);
+    SAVE_MIN_VECTORS = TRUE;
+  }
+
   // Input parameters:
-  if ((N = get_argument (argc, argv, "-slit-trace-red"))) {
-    remove_argument (N, &argc, argv);
-    if ((slit_trace_red = FindSpline (argv[N])) == NULL) return (FALSE);
-    remove_argument (N, &argc, argv);
-  } else { goto usage; }
-  if ((N = get_argument (argc, argv, "-slit-trace-blu"))) {
-    remove_argument (N, &argc, argv);
-    if ((slit_trace_blu = FindSpline (argv[N])) == NULL) return (FALSE);
-    remove_argument (N, &argc, argv);
-  } else { goto usage; }
-
-  if ((N = get_argument (argc, argv, "-psf-trace"))) {
-    remove_argument (N, &argc, argv);
-    if ((psf_trace = FindSpline (argv[N])) == NULL) return (FALSE);
+  if ((N = get_argument (argc, argv, "-trace"))) {
+    remove_argument (N, &argc, argv);
+    if ((trace = FindSpline (argv[N])) == NULL) return (FALSE);
     remove_argument (N, &argc, argv);
   } else { goto usage; }
@@ -166,20 +158,4 @@
     remove_argument (N, &argc, argv);
   } else { goto usage; }
-
-  // save the model
-  Buffer *model = NULL;
-  if ((N = get_argument (argc, argv, "-model"))) {
-    remove_argument (N, &argc, argv);
-    if ((model = SelectBuffer (argv[N], ANYBUFFER, TRUE)) == NULL) return (FALSE);
-    remove_argument (N, &argc, argv);
-  }
-
-  // save the model
-  Buffer *varim = NULL;
-  if ((N = get_argument (argc, argv, "-variance"))) {
-    remove_argument (N, &argc, argv);
-    if ((varim = SelectBuffer (argv[N], OLDBUFFER, TRUE)) == NULL) return (FALSE);
-    remove_argument (N, &argc, argv);
-  }
 
   if (argc != 3) goto usage;
@@ -203,10 +179,4 @@
   float *bufVal = (float *) buffer->matrix.buffer;
 
-  if (varim) {
-    if (Nx != varim[0].matrix.Naxis[0]) { gprint (GP_ERR, "inconsistent sizes for image and varim\n"); return FALSE; }
-    if (Ny != varim[0].matrix.Naxis[1]) { gprint (GP_ERR, "inconsistent sizes for image and varim\n"); return FALSE; }
-  }
-  float *varVal = varim ? (float *) varim->matrix.buffer : NULL;
-
   // obj, sky, bck must be consistent with data
   if (Ny != obj->Nelements) {
@@ -223,141 +193,240 @@
   }
 
-  if (model) {
-    if (!CreateBuffer (model, Nx, Ny, -32, 1.0, 0.0)) { gprint (GP_ERR, "error generating output model buffer\n"); return FALSE; }
-  }
-
-  // for the cross-dispersion reference pixel, use the user value or set to Nx/2 if < 0
+  // for the cross-dispersion reference pixle, use the user value or set to Nx/2 if < 0
   deimos_set_cross_ref (atoi(argv[2]), Nx); 
   deimos_make_kernel (stilt, Nx);
 
+  // the functions below accept an opihi_flt array for object, sky, background
+  opihi_flt *objVal = obj->elements.Flt;
+  opihi_flt *skyVal = sky->elements.Flt;
+  opihi_flt *bckVal = bck->elements.Flt;
+
+  int NRESULT = Niter + Ntry*Niter + 1;
+  ALLOCATE_PTR (result, DeimosResult, NRESULT);
+
+  Vector **objOut = NULL;
+  Vector **skyOut = NULL;
+  Vector **bckOut = NULL;
   Vector  *objMin = NULL;
   Vector  *skyMin = NULL;
   Vector  *bckMin = NULL;
 
-  if ((objMin = SelectVector ("objMin", ANYVECTOR, TRUE)) == NULL) { return (FALSE); } ResetVector (objMin, OPIHI_FLT, Ny);
-  if ((skyMin = SelectVector ("skyMin", ANYVECTOR, TRUE)) == NULL) { return (FALSE); } ResetVector (skyMin, OPIHI_FLT, Ny);
-  if ((bckMin = SelectVector ("bckMin", ANYVECTOR, TRUE)) == NULL) { return (FALSE); } ResetVector (bckMin, OPIHI_FLT, Ny);
-
-  // the functions below accept an opihi_flt array for object, sky, background
-  opihi_flt *objVal = objMin->elements.Flt;
-  opihi_flt *skyVal = skyMin->elements.Flt;
-  opihi_flt *bckVal = bckMin->elements.Flt;
-
-  // we make a copy of the input guess vectors and minimize them
-  for (int iy = 0; iy < Ny; iy++) {
-    objVal[iy] = obj->elements.Flt[iy];
-    skyVal[iy] = sky->elements.Flt[iy];
-    bckVal[iy] = bck->elements.Flt[iy];
+  // Save all result vectors for each of obj, sky, bck:
+  if (SAVE_ALL_VECTORS) {
+    ALLOCATE (objOut, Vector *, NRESULT);
+    ALLOCATE (skyOut, Vector *, NRESULT);
+    ALLOCATE (bckOut, Vector *, NRESULT);
+    for (int i = 0; i < NRESULT; i++) {
+      char name[64];
+      snprintf (name, 64, "obj_%04d", i); if ((objOut[i] = SelectVector (name, ANYVECTOR, TRUE)) == NULL) { return (FALSE); } ResetVector (objOut[i], OPIHI_FLT, Ny);
+      snprintf (name, 64, "sky_%04d", i); if ((skyOut[i] = SelectVector (name, ANYVECTOR, TRUE)) == NULL) { return (FALSE); } ResetVector (skyOut[i], OPIHI_FLT, Ny);
+      snprintf (name, 64, "bck_%04d", i); if ((bckOut[i] = SelectVector (name, ANYVECTOR, TRUE)) == NULL) { return (FALSE); } ResetVector (bckOut[i], OPIHI_FLT, Ny);
+      for (int iy = 0; iy < Ny; iy++) {
+	objOut[i]->elements.Flt[iy] = 0.0;
+	skyOut[i]->elements.Flt[iy] = 0.0;
+	bckOut[i]->elements.Flt[iy] = 0.0;
+      }
+    }
+  }
+  if (SAVE_MIN_VECTORS) {
+    if ((objMin = SelectVector ("objMin", ANYVECTOR, TRUE)) == NULL) { return (FALSE); } ResetVector (objMin, OPIHI_FLT, Ny);
+    if ((skyMin = SelectVector ("skyMin", ANYVECTOR, TRUE)) == NULL) { return (FALSE); } ResetVector (skyMin, OPIHI_FLT, Ny);
+    if ((bckMin = SelectVector ("bckMin", ANYVECTOR, TRUE)) == NULL) { return (FALSE); } ResetVector (bckMin, OPIHI_FLT, Ny);
+    for (int iy = 0; iy < Ny; iy++) {
+      objMin->elements.Flt[iy] = 0.0;
+      skyMin->elements.Flt[iy] = 0.0;
+      bckMin->elements.Flt[iy] = 0.0;
+    }
+  }
+  Vector *chisqVect;
+  if ((chisqVect = SelectVector ("chisqOut", ANYVECTOR, TRUE)) == NULL) { return FALSE; }
+  ResetVector (chisqVect, OPIHI_FLT, NRESULT);
+  for (int i = 0; i < NRESULT; i++) { chisqVect->elements.Flt[i] = 0.0; }
+
+  // XXX temp hack: save chisq subset vectors for each row pass
+  int Npass = Ny / Nrow;
+  ALLOCATE_PTR (chiPass, Vector *, Npass);
+  for (int pass = 0; pass < Npass; pass++) {
+    char name[64];
+    snprintf (name, 64, "chiPass_%03d", pass);
+    if ((chiPass[pass] = SelectVector (name, ANYVECTOR, TRUE)) == NULL) { return FALSE; } ResetVector (chiPass[pass], OPIHI_FLT, NRESULT);
   }
 
   float noiseVar = SQ(noise);
-  ALLOCATE_PTR (objNoise, float, Ny);
-  ALLOCATE_PTR (skyNoise, float, Ny);
-  ALLOCATE_PTR (bckNoise, float, Ny);
-
-  // generate noise vectors
-  for (int iy = 0; iy < Ny; iy++) {
-    objNoise[iy] = nsigma*sqrt(hypot(fabs(objVal[iy]) / gain, noiseVar));
-    skyNoise[iy] = nsigma*sqrt(hypot(fabs(skyVal[iy]) / gain, noiseVar));
-    bckNoise[iy] = nsigma*sqrt(hypot(fabs(bckVal[iy]) / gain, noiseVar));
-  }
-
-  // obj, sky, bck are initial guesses.  Also use these values to define a range for the initial guesses.
-
+  ALLOCATE_PTR (objNoise, float, Nrow);
+  ALLOCATE_PTR (skyNoise, float, Nrow);
+  ALLOCATE_PTR (bckNoise, float, Nrow);
+
+  // work on segments of Nrow at a time
   // XXX worry about last segment (< Nrow rows)
-  for (int iter = 0; iter < Niter; iter++) {
-
-    int dRow = Nrow/2;
-
-    // use scaled-noise to define test ranges
-    // we are going to try each row using a window Nrow wide to measure chisq:
-    for (int row = dRow; !SKIPFIT && (row < Ny - dRow - 1); row++) {
+  int pass = 0;
+  for (int row = 0; row < Ny - Nrow; row += Nrow, pass++) {
+
+    int Nresult = 0;
+
+    // obj, sky, bck are initial guesses.  Also use these values to define a range for the initial guesses.
+
+    // If I just use the value in a given bin to define the range, random noise for the
+    // faint end could have bad results (range ~ 0.0).  For that matter, if I am in a
+    // region with large dynamic range (e.g., on an emission or absorption line), then we
+    // likely have large errors in how the guess follows the truth. 
+
+    /** old concept:
+    float objRange = 0, skyRange = 0, bckRange = 0;
+    for (int iy = 0; iy < Nrow; iy++) {
+      objRange = MAX(objVal[iy + row], objRange);
+      skyRange = MAX(skyVal[iy + row], skyRange);
+      bckRange = MAX(bckVal[iy + row], bckRange);
+    }
+    **/
+
+    // new concept: start with 2-sigma range, then ramp down below
+    for (int iy = 0; iy < Nrow; iy++) {
+      objNoise[iy] = nsigma*sqrt(hypot(fabs(objVal[iy + row]) / gain, noiseVar));
+      skyNoise[iy] = nsigma*sqrt(hypot(fabs(skyVal[iy + row]) / gain, noiseVar));
+      bckNoise[iy] = nsigma*sqrt(hypot(fabs(bckVal[iy + row]) / gain, noiseVar));
+    }
+
+    // first test is the input guess
+    if (1) { 
+      opihi_flt *objtest = deimos_make_test (objVal, NULL, row, Nrow, TRUE);
+      opihi_flt *skytest = deimos_make_test (skyVal, NULL, row, Nrow, TRUE);
+      opihi_flt *bcktest = deimos_make_test (bckVal, NULL, row, Nrow, TRUE);
+
+      // generate the model based on the test values
+      // objtest, skytest, bcktest are segments of the full parameter vectors
+      float *model = deimos_make_model (objtest, skytest, bcktest, psf, profile, trace, Nx, Nrow, row);
       
-      // I am using a numerical equivalent of Levenberg-Marquardt, but only for a single
-      // p_m[i] = (obj,sky,bck) triplet [m is the index of obj,sky,bck; i is the row
-      // index] at a time.  I start with a current best guess set of (obj,sky,bck).  I
-      // need to calculate the model at this location, and then at offset locations p_m +
-      // dp_m.  Note that I do not need to calculate chisq for each of these to generate
-      // the elements of the LMM equations:
-
-      int row_0 = row - dRow; // start row of the subset test range
-
-      // Nrow = 5, dRow = 2, Ny = 100, last start is Ny - 2 - 1 = 97
-      // last row_0 is 95
-
-      // generate subset vectors for the range **centered** on row
-      opihi_flt *objCurr = deimos_subvector (objVal, row_0, Nrow);
-      opihi_flt *skyCurr = deimos_subvector (skyVal, row_0, Nrow);
-      opihi_flt *bckCurr = deimos_subvector (bckVal, row_0, Nrow);
-
-      // current vector value:
-      // for deimos_make_model, row is the starting point of the subimage
-      float *model_ref = deimos_make_model (objCurr, skyCurr, bckCurr, psf, profile, slit_trace_red, slit_trace_blu, redlimit, psf_trace, Nx, Nrow, row_0);
-
-      // in the test functions below, dRow is the central pixel of the subset, e.g., obj[row] => objCurr[dRow]
-
-      float dObj = 0.0, dSky = 0.0, dBck = 0.0;
-
-      // delta obj (save dObj)
-      opihi_flt *objtest = deimos_make_test (objCurr, objNoise[row], dRow, Nrow, &dObj);
-      float *model_obj = deimos_make_model (objtest, skyCurr, bckCurr, psf, profile, slit_trace_red, slit_trace_blu, redlimit, psf_trace, Nx, Nrow, row_0);
-
-      // delta sky (save dSky)
-      opihi_flt *skytest = deimos_make_test (skyCurr, skyNoise[row], dRow, Nrow, &dSky);
-      float *model_sky = deimos_make_model (objCurr, skytest, bckCurr, psf, profile, slit_trace_red, slit_trace_blu, redlimit, psf_trace, Nx, Nrow, row_0);
-
-      // delta bck (save dBck)
-      opihi_flt *bcktest = deimos_make_test (bckCurr, bckNoise[row], dRow, Nrow, &dBck);
-      float *model_bck = deimos_make_model (objCurr, skyCurr, bcktest, psf, profile, slit_trace_red, slit_trace_blu, redlimit, psf_trace, Nx, Nrow, row_0);
-
-      // dObj, dSky, dBck carry the delta used derivatives in and the delta applied to the values out
-      float chisq = deimos_LMM_update (bufVal, varVal, model_ref, model_obj, model_sky, model_bck, &dObj, &dSky, &dBck, Nx, Nrow, row_0, lambda);
-
-      if (FALSE && (row > 10) && (row < 20)) {
-	fprintf (stderr, "%d %d : %f %f %f\n", iter, row, dObj, dSky, dBck);
-      }
-
-      if (1) {
-	if (DO_PLUS) {
-	  objVal[row] += dObj;
-	  skyVal[row] += dSky;
-	  bckVal[row] += dBck;
-	} else {
-	  objVal[row] -= dObj;
-	  skyVal[row] -= dSky;
-	  bckVal[row] -= dBck;
+      // calculate the current chisq
+      // XXX need to add in the per-pixel error or variance
+      int Npts = 0;
+      float chisq = deimos_get_chisq (bufVal, model, Nx, Nrow, row, &Npts);
+      fprintf (stderr, "guess: chisq: %f, Npts: %d\n", chisq, Npts);
+      free (model);
+
+      if (pass < Npass) {
+	chiPass[pass]->elements.Flt[Nresult] = chisq / (float) Npts;
+      }
+
+      // save the results
+      result[Nresult].chisq = chisq / (float) Npts;
+      result[Nresult].obj = objtest;
+      result[Nresult].sky = skytest;
+      result[Nresult].bck = bcktest;
+      Nresult ++;
+    }
+
+    // run Niter iterations
+    for (int iter = 0; iter < Niter; iter ++) {
+
+      // generate a set of test values for obj, sky, backgnd based on the current guess
+      opihi_flt *objtest = deimos_make_test (objVal, objNoise, row, Nrow, TRUE);
+      opihi_flt *skytest = deimos_make_test (skyVal, skyNoise, row, Nrow, TRUE);
+      opihi_flt *bcktest = deimos_make_test (bckVal, bckNoise, row, Nrow, TRUE);
+      
+      for (int itmp = 0; FALSE && (itmp < Nrow); itmp++) {
+	fprintf (stderr, "val: %f %f %f, tst: %f %f %f\n",
+		 objVal[itmp + row],  skyVal[itmp + row],  bckVal[itmp + row], 
+		 objtest[itmp], skytest[itmp], bcktest[itmp]);
+      }
+
+      // generate the model based on the test values
+      // objtest, skytest, bcktest are segments of the full parameter vectors
+      float *model = deimos_make_model (objtest, skytest, bcktest, psf, profile, trace, Nx, Nrow, row);
+      
+      // calculate the current chisq
+      // XXX need to add in the per-pixel error or variance
+      int Npts = 0;
+      float chisq = deimos_get_chisq (bufVal, model, Nx, Nrow, row, &Npts);
+      // fprintf (stderr, "iter: %d, chisq: %f, Npts: %d\n", iter, chisq, Npts);
+      free (model);
+
+      if (pass < Npass) {
+	chiPass[pass]->elements.Flt[Nresult] = chisq / (float) Npts;
+      }
+
+      // save the results
+      result[Nresult].chisq = chisq / (float) Npts;
+      result[Nresult].obj = objtest;
+      result[Nresult].sky = skytest;
+      result[Nresult].bck = bcktest;
+      Nresult ++;
+    }
+      
+    for (int try = 0; try < Ntry; try ++) {
+      // generate an index of results sorted by chisq
+      int *IDX = deimos_sort_result (result, Nresult);
+
+      int Nnewset = 0;
+
+      // XXX not sure this scaling factor concept is good
+      for (int iy = 0; iy < Nrow; iy++) {
+	objNoise[iy] = scale*objNoise[iy];
+	skyNoise[iy] = scale*skyNoise[iy];
+	bckNoise[iy] = scale*bckNoise[iy];
+      }
+
+      // run Niter iterations, selecting guess values from the result set
+      for (int iter = 0; iter < Niter; iter ++) {
+	int bin = deimos_get_random_sample (Nresult);
+	int entry = IDX[bin];
+	// fprintf (stderr, "try: %d : %d, %f\n", bin, entry, result[entry].chisq);
+
+	// generate a set of test values for obj, sky, backgnd based on the current guess
+	opihi_flt *objtest = deimos_make_test (result[entry].obj, objNoise, row, Nrow, FALSE);
+	opihi_flt *skytest = deimos_make_test (result[entry].sky, skyNoise, row, Nrow, FALSE);
+	opihi_flt *bcktest = deimos_make_test (result[entry].bck, bckNoise, row, Nrow, FALSE);
+      
+	for (int itmp = 0; FALSE && (itmp < Nrow); itmp++) {
+	  fprintf (stderr, "val: %f %f %f, tst: %f %f %f\n",
+		   result[entry].obj[itmp], result[entry].sky[itmp], result[entry].bck[itmp], 
+		   objtest[itmp], skytest[itmp], bcktest[itmp]);
 	}
-      }
-
-      free (objCurr);
-      free (skyCurr);
-      free (bckCurr);
-
-      free (model_ref);
-
-      free (model_obj);
-      free (model_sky);
-      free (model_bck);
-
-      free (objtest);
-      free (skytest);
-      free (bcktest);
-
-      if (VERBOSE) fprintf (stderr, "chisq: %f (%f, %f, %f)\n", chisq, dObj, dSky, dBck);
-    }
-
-    float *model_full = deimos_make_model (objVal, skyVal, bckVal, psf, profile, slit_trace_red, slit_trace_blu, redlimit, psf_trace, Nx, Ny, 0);
-
-    int Npts = 0;
-    float chisq_full  = deimos_get_chisq (bufVal, varVal, model_full, Nx, Ny, 0, &Npts);
-
-    if (model) {
-      free (model[0].matrix.buffer);
-      model[0].matrix.buffer = (char *) model_full;
-    } else {
-      free (model_full);
-    }
-
-    fprintf (stderr, "** Full chisq: %f (%d) : %f)\n", chisq_full, Npts, chisq_full / (1.0 * Npts));
+
+	// generate the model based on the test values
+	float *model = deimos_make_model (objtest, skytest, bcktest, psf, profile, trace, Nx, Nrow, row);
+      
+	// calculate the current chisq
+	int Npts = 0;
+	float chisq = deimos_get_chisq (bufVal, model, Nx, Nrow, row, &Npts);
+	// fprintf (stderr, "try: %d, iter: %d, chisq: %f, Npts: %d\n", try, iter, chisq, Npts);
+	free (model);
+
+	if (pass < Npass) {
+	  chiPass[pass]->elements.Flt[Nresult + Nnewset] = chisq / (float) Npts;
+	}
+
+	// save the results
+	result[Nresult + Nnewset].chisq = chisq / (float) Npts;
+	result[Nresult + Nnewset].obj = objtest;
+	result[Nresult + Nnewset].sky = skytest;
+	result[Nresult + Nnewset].bck = bcktest;
+	Nnewset ++;
+      }
+      Nresult += Nnewset;
+    }
+
+    int *IDX = deimos_sort_result (result, Nresult);
+
+    // ENDING: save the best result and info about the allowed chisq region
+    // int *index = sort_result (result, Nresult);
+    // copy result[index[0]].obj,sky,bck to obj,sky,bck
+    for (int i = 0; i < Nresult; i++) {
+      for (int iy = 0; iy < Nrow; iy++) {
+	if (SAVE_ALL_VECTORS) {
+	  objOut[i]->elements.Flt[iy + row] = result[IDX[i]].obj[iy];
+	  skyOut[i]->elements.Flt[iy + row] = result[IDX[i]].sky[iy];
+	  bckOut[i]->elements.Flt[iy + row] = result[IDX[i]].bck[iy];
+	}
+      }
+      chisqVect->elements.Flt[i] += result[IDX[i]].chisq;
+    }
+    if (SAVE_MIN_VECTORS) {
+      for (int iy = 0; iy < Nrow; iy++) {
+	objMin->elements.Flt[iy + row] = result[IDX[0]].obj[iy];
+	skyMin->elements.Flt[iy + row] = result[IDX[0]].sky[iy];
+	bckMin->elements.Flt[iy + row] = result[IDX[0]].bck[iy];
+      }
+    }
   }
 
@@ -365,6 +434,5 @@
 
  usage:
-  gprint (GP_ERR, "USAGE: deimos fitobj (buffer) (Xref) -object vector -sky vector -backgnd vector -slit-trace-red (spline) -slit-trace-blu (spline) -psf-trace (spline) -profile vector -psf vector -stilt (angle)\n");
-  gprint (GP_ERR, "OPTIONS: [-model image] [-variance image] [-gain value] [-noise value] [-nsigma value] [-lambda value] [-iter N] [-row N] [-redlimit Npixel] [-skipfit] [-v] [-plus]\n");
+  gprint (GP_ERR, "USAGE: deimos fitobj (buffer) (Xref) -object vector -sky vector -backgnd vector -trace spline -profile vector -psf vector -stilt (angle)\n");
   return FALSE;
 }
@@ -372,120 +440,38 @@
 /****************** fitobj Support Functions *******************/
 
-// we generate a new vector with a single element (row) modified based on sigma
-opihi_flt *deimos_subvector (opihi_flt *fullVec, int row, int Nrow) {
+static opihi_flt *deimos_make_test (opihi_flt *guess, float *sigma, int row, int Nrow, int fullInput) {
+
+  // we have a vector, guess, with some length >= row + Nrow.
+  // generate a set of random values in the vicinty of guess[row] to guess[row+Nrow]
+  // return vector is of length Nrow
+
+  // if fullInput is TRUE,  the guess vector runs from 0 to Ny (full wavelength range)
+  // if fullInput is FALSE, the guess vector runs from row to row + Nrow (subset range)
+  // sigma is always only Nrow long
 
   ALLOCATE_PTR (value, opihi_flt, Nrow);
 
-  for (int i = 0; i < Nrow; i++) {
-    value[i] = fullVec[i + row];
-  }
-
+  int start_pix = fullInput ? row : 0;
+  int stop_pix  = fullInput ? row + Nrow : Nrow;
+
+  int iv = 0;
+  for (int i = start_pix; i < stop_pix; i++, iv++) {
+    if (!sigma) {
+      value[iv] = guess[i];
+      continue;
+    }
+    if (USE_GAUSS_DEV) {
+      value[iv] = ohana_gaussdev_rnd(guess[i], sigma[iv]);
+      continue;
+    } 
+    
+    // uniform distribution:
+    value[iv] = sigma[iv]*(drand48() - 0.5) + guess[i];
+  }
   return value;
 }
 
 
-// we generate a new vector with a single element (row) modified based on sigma
-static opihi_flt *deimos_make_test (opihi_flt *guess, float sigma, int row, int Nrow, float *dValue) {
-
-  // if fullInput is TRUE,  the guess vector runs from 0 to Ny (full wavelength range)
-  // if fullInput is FALSE, the guess vector runs from row to row + Nrow (subset range)
-  // sigma is valid for the element at row
-
-  ALLOCATE_PTR (value, opihi_flt, Nrow);
-
-  for (int i = 0; i < Nrow; i++) {
-    value[i] = guess[i];
-  }
-
-  value[row] = guess[row] + 0.1*sigma;
-
-  *dValue = 0.1*sigma;
-  return value;
-}
-
-
-double deimos_LMM_update (float *data, float *vardata, float *model_ref,
-			  float *model_obj, float *model_sky, float *model_bck,
-			  float *dObj, float *dSky, float *dBck, int Nx, int Ny, int row, float lambda) {
-  
-  // we are going to loop over the images calculating the following value:
-
-  // W = 1 / sigma^2, leave as 1.0 for now
-  // chisq = sum W * (data - model_ref)^2 
-  // dF_X = sum W * (data - model_ref) * (model_ref - model_X) / dX
-  // d2F_XY = sum W * (model_ref - model_X) * (model_ref - model_Y) / (dX * dY)
-
-  double chisq = 0.0;
-  double dF_obj = 0.0, dF_sky = 0.0, dF_bck = 0.0;
-  double d2F_obj_obj = 0.0, d2F_obj_sky = 0.0, d2F_obj_bck = 0.0, d2F_sky_sky = 0.0, d2F_sky_bck = 0.0, d2F_bck_bck = 0.0;
-
-  for (int iy = 0; iy < Ny; iy++) {
-    for (int ix = 0; ix < Nx; ix++) {
-      int pix = ix + iy*Nx;
-      int pix_data  = ix + (iy + row)*Nx;
-
-      // if any of the pixel values are NAN, skip the point:
-      if (!isfinite(data[pix_data])) continue;
-      if (!isfinite(model_ref[pix])) continue;
-      if (!isfinite(model_obj[pix])) continue;
-      if (!isfinite(model_sky[pix])) continue;
-      if (!isfinite(model_bck[pix])) continue;
-
-      if (vardata && !isfinite(vardata[pix_data])) continue;
-      float Var = vardata ? vardata[pix_data] : 1.0;
-      float W = (fabs(Var) < 0.01) ? 100.0 : 1.0 / Var;
-
-      float df = W * (data[pix_data] - model_ref[pix]);
-
-      chisq += SQ(df);
-
-      float df_obj = (model_ref[pix] - model_obj[pix]) / *dObj;
-      float df_sky = (model_ref[pix] - model_sky[pix]) / *dSky;
-      float df_bck = (model_ref[pix] - model_bck[pix]) / *dBck;
-
-      dF_obj += df*df_obj;
-      dF_sky += df*df_sky;
-      dF_bck += df*df_bck;
-
-      d2F_obj_obj += W * SQ(df_obj);
-      d2F_sky_sky += W * SQ(df_sky);
-      d2F_bck_bck += W * SQ(df_bck);
-
-      d2F_obj_sky += W * df_obj * df_sky;
-      d2F_obj_bck += W * df_obj * df_bck;
-      d2F_sky_bck += W * df_sky * df_bck;
-    }
-  }
-
-  // these are the elements of Ax = B
-  ALLOCATE_PTR (A, double *, 3);
-  ALLOCATE_PTR (B, double *, 3);
-  for (int i = 0; i < 3; i++) {
-    ALLOCATE (A[i], double, 3);
-    ALLOCATE (B[i], double, 1);
-  }
-
-  A[0][0] = d2F_obj_obj * (1.0 + lambda);
-  A[1][1] = d2F_sky_sky * (1.0 + lambda);
-  A[2][2] = d2F_bck_bck * (1.0 + lambda);
-
-  A[0][1] = A[1][0] = d2F_obj_sky;
-  A[1][2] = A[2][1] = d2F_sky_bck;
-  A[0][2] = A[2][0] = d2F_obj_bck;
-
-  B[0][0] = dF_obj;
-  B[1][0] = dF_sky;
-  B[2][0] = dF_bck;
-
-  dgaussjordan (A, B, 3, 1);
-
-  *dObj = B[0][0];
-  *dSky = B[1][0];
-  *dBck = B[2][0];
-
-  return chisq;
-}
-
-static float deimos_get_chisq (float *buffer, float *vardata, float *model, int Nx, int Ny, int row, int *Npts) {
+static float deimos_get_chisq (float *buffer, float *model, int Nx, int Ny, int row, int *Npts) {
 
   int npts = 0;
@@ -501,12 +487,5 @@
       if (!isfinite(buffer[pix_buffer])) continue;
       if (!isfinite(model[pix_model])) continue;
-
-      if (vardata && !isfinite(vardata[pix_buffer])) continue;
-      float Var = vardata ? vardata[pix_buffer] : 1.0;
-      float W = (fabs(Var) < 0.01) ? 100.0 : 1.0 / Var;
-
-      float dchisq = SQ(buffer[pix_buffer] - model[pix_model]) * W;
-      if (!isfinite(dchisq)) continue;
-      chisq += dchisq;
+      chisq += SQ(buffer[pix_buffer] - model[pix_model]);
       npts ++;
     }
@@ -515,2 +494,42 @@
   return chisq;
 }
+
+int *deimos_sort_result (DeimosResult *result, int Nresult) {
+
+  ALLOCATE_PTR (IDX,   int,   Nresult);
+  ALLOCATE_PTR (chisq, float, Nresult);
+
+  for (int i = 0; i < Nresult; i++) {
+    IDX[i] = i;
+    chisq[i] = result[i].chisq;
+  }
+
+  sort_float_index (chisq, IDX, Nresult);
+  free (chisq);
+
+  return IDX;
+}
+
+static float DEIMOS_A = 2.0; // value for random sample
+
+int deimos_get_random_sample (int Nresult) {
+
+  // choose a bin from the range 0 - Nresult, with front-loaded weighting.
+
+  // bin = Nresult * (exp(q) - exp(-A)) / (exp(A) - exp(-A))
+  // q = 2A(x - 1/2) : random number between -A and +A
+  // x : random number between 0 and 1
+
+  // f(q;A) = (exp(q) - exp(-A)) / (exp(A) - exp(-A))
+  // f(q;A) ranges from 0 to +1 as x ranges from 0 to +1
+
+  float x = drand48();
+  float q = 2*DEIMOS_A*(x - 0.5);
+  float f = (exp(q) - exp(-DEIMOS_A)) / (exp(DEIMOS_A) - exp(-DEIMOS_A));
+  // XXX optimization : precalculate and save the elements of this function
+  
+  int bin = floor(Nresult * f);
+
+  return bin;
+}
+# endif
Index: trunk/Ohana/src/opihi/mana/deimos_fitobj.v0.c
===================================================================
--- trunk/Ohana/src/opihi/mana/deimos_fitobj.v0.c	(revision 41326)
+++ 	(revision )
@@ -1,538 +1,0 @@
-# include "data.h"
-# include "deimos.h"
-
-# if (0) 
-int deimos_fitobj (int argc, char **argv) {
-  OHANA_UNUSED_PARAM(argc);
-  OHANA_UNUSED_PARAM(argv);
-  return FALSE;
-}
-
-# else
-
-/*
-  this is starting to work OK.  some improvements to make
-  * use Gaussdev to sample
-  * do not scale down range (or user-set scale-down)
- */
-
-// internal functions to fitobj
-static float      deimos_get_chisq (float *buffer, float *model, int Nx, int Ny, int row, int *Npts);
-int              *deimos_sort_result (DeimosResult *result, int Nresult);
-int               deimos_get_random_sample (int Nresult);
-static opihi_flt *deimos_make_test (opihi_flt *guess, float *sigma, int row, int Nrow, int fullInput);
-
-int USE_GAUSS_DEV = FALSE;
-
-int deimos_fitobj (int argc, char **argv) {
-
-  // input parameters:
-  // * buffer      : 2D image of slit (full frame or cutout?)
-  // * trace       : spline fit of slit central x pos vs y-coord
-  // * profile     : slit window profile (vector)
-  // * PSF         : point-spread function vector (flux normalized, x-dir)
-  // * stilt       : slit tilt response : 2D kernel? 
-
-  // in-out parameters:
-  // * obj  : vector of object flux vs y-coord (starting guess and result)
-  // * sky  : vector of local sky signal vs y-coord 
-  // * bck  : vector of extra-slit background flux vs y-coord
-
-  int N;
-
-  Spline *trace   = NULL;
-  Vector *profile = NULL;
-
-  Vector *obj     = NULL;
-  Vector *sky     = NULL;
-  Vector *bck     = NULL;
-
-  Vector *psf     = NULL;
-
-  Buffer *buffer  = NULL;
-
-  float stilt = 0.0; // angle of the slit
-  ohana_gaussdev_init ();
-
-  fprintf (stderr, "use deimos fitalt instead\n");
-  return FALSE;
-
-  // a crude noise model valid for both the guess vectors and the
-  // data buffer:
-  float gain = 1.0;
-  if ((N = get_argument (argc, argv, "-gain"))) {
-    remove_argument (N, &argc, argv);
-    gain = atof(argv[N]);
-    remove_argument (N, &argc, argv);
-  }
-  float noise = 0.0;
-  if ((N = get_argument (argc, argv, "-noise"))) {
-    remove_argument (N, &argc, argv);
-    noise = atof(argv[N]);
-    remove_argument (N, &argc, argv);
-  }
-  float nsigma = 2.0;
-  if ((N = get_argument (argc, argv, "-nsigma"))) {
-    remove_argument (N, &argc, argv);
-    nsigma = atof(argv[N]);
-    remove_argument (N, &argc, argv);
-  }
-  float scale = 0.75;
-  if ((N = get_argument (argc, argv, "-scale"))) {
-    remove_argument (N, &argc, argv);
-    scale = atof(argv[N]);
-    remove_argument (N, &argc, argv);
-  }
-
-
-  int Niter = 25;
-  if ((N = get_argument (argc, argv, "-iter"))) {
-    remove_argument (N, &argc, argv);
-    Niter = atoi(argv[N]);
-    remove_argument (N, &argc, argv);
-  }
-  int Ntry = 5;
-  if ((N = get_argument (argc, argv, "-try"))) {
-    remove_argument (N, &argc, argv);
-    Ntry = atoi(argv[N]);
-    remove_argument (N, &argc, argv);
-  }
-  int Nrow = 5;
-  if ((N = get_argument (argc, argv, "-row"))) {
-    remove_argument (N, &argc, argv);
-    Nrow = atoi(argv[N]);
-    remove_argument (N, &argc, argv);
-  }
-
-  USE_GAUSS_DEV = FALSE;
-  if ((N = get_argument (argc, argv, "-gaussdev"))) {
-    remove_argument (N, &argc, argv);
-    USE_GAUSS_DEV = TRUE;
-  }
-
-  int SAVE_ALL_VECTORS = FALSE;
-  if ((N = get_argument (argc, argv, "-save-all-vectors"))) {
-    remove_argument (N, &argc, argv);
-    SAVE_ALL_VECTORS = TRUE;
-  }
-
-  int SAVE_MIN_VECTORS = FALSE;
-  if ((N = get_argument (argc, argv, "-save-min-vectors"))) {
-    remove_argument (N, &argc, argv);
-    SAVE_MIN_VECTORS = TRUE;
-  }
-
-  // Input parameters:
-  if ((N = get_argument (argc, argv, "-trace"))) {
-    remove_argument (N, &argc, argv);
-    if ((trace = FindSpline (argv[N])) == NULL) return (FALSE);
-    remove_argument (N, &argc, argv);
-  } else { goto usage; }
-  if ((N = get_argument (argc, argv, "-profile"))) {
-    remove_argument (N, &argc, argv);
-    if ((profile = SelectVector (argv[N], OLDVECTOR, TRUE)) == NULL) return (FALSE);
-    remove_argument (N, &argc, argv);
-  } else { goto usage; }
-  if ((N = get_argument (argc, argv, "-psf"))) {
-    remove_argument (N, &argc, argv);
-    if ((psf = SelectVector (argv[N], OLDVECTOR, TRUE)) == NULL) return (FALSE);
-    remove_argument (N, &argc, argv);
-  } else { goto usage; }
-  if ((N = get_argument (argc, argv, "-stilt"))) {
-    remove_argument (N, &argc, argv);
-    stilt = atof (argv[N]);
-    remove_argument (N, &argc, argv);
-  } else { goto usage; }
-
-  // In-Out parameters:
-  if ((N = get_argument (argc, argv, "-object"))) {
-    remove_argument (N, &argc, argv);
-    if ((obj = SelectVector (argv[N], OLDVECTOR, TRUE)) == NULL) return (FALSE);
-    remove_argument (N, &argc, argv);
-  } else { goto usage; }
-  if ((N = get_argument (argc, argv, "-sky"))) {
-    remove_argument (N, &argc, argv);
-    if ((sky = SelectVector (argv[N], OLDVECTOR, TRUE)) == NULL) return (FALSE);
-    remove_argument (N, &argc, argv);
-  } else { goto usage; }
-  if ((N = get_argument (argc, argv, "-backgnd"))) {
-    remove_argument (N, &argc, argv);
-    if ((bck = SelectVector (argv[N], OLDVECTOR, TRUE)) == NULL) return (FALSE);
-    remove_argument (N, &argc, argv);
-  } else { goto usage; }
-
-  if (argc != 3) goto usage;
-
-  // buffer is the full image, Xref is reference coordinate of the profile in the buffer
-  if ((buffer = SelectBuffer (argv[1], OLDBUFFER, TRUE)) == NULL) return (FALSE);
-  
-  // profile and PSF are defined with central reference pixel mapped to Xref (+ trace)
-  if (profile->Nelements % 2 == 0) {
-    gprint (GP_ERR, "slit profile vector must have an odd number of pixels\n");
-    return FALSE;
-  }
-  if (psf->Nelements % 2 == 0) {
-    gprint (GP_ERR, "PSF vector must have an odd number of pixels\n");
-    return FALSE;
-  }
-
-  // observed buffer size
-  int Nx = buffer[0].matrix.Naxis[0];
-  int Ny = buffer[0].matrix.Naxis[1];
-  float *bufVal = (float *) buffer->matrix.buffer;
-
-  // obj, sky, bck must be consistent with data
-  if (Ny != obj->Nelements) {
-    gprint (GP_ERR, "inconsistent wavelength scales (object)\n");
-    return FALSE;
-  }
-  if (Ny != sky->Nelements) {
-    gprint (GP_ERR, "inconsistent wavelength scales (sky)\n");
-    return FALSE;
-  }
-  if (Ny != bck->Nelements) {
-    gprint (GP_ERR, "inconsistent wavelength scales (backgnd)\n");
-    return FALSE;
-  }
-
-  // for the cross-dispersion reference pixle, use the user value or set to Nx/2 if < 0
-  deimos_set_cross_ref (atoi(argv[2]), Nx); 
-  deimos_make_kernel (stilt, Nx);
-
-  // the functions below accept an opihi_flt array for object, sky, background
-  opihi_flt *objVal = obj->elements.Flt;
-  opihi_flt *skyVal = sky->elements.Flt;
-  opihi_flt *bckVal = bck->elements.Flt;
-
-  int NRESULT = Niter + Ntry*Niter + 1;
-  ALLOCATE_PTR (result, DeimosResult, NRESULT);
-
-  Vector **objOut = NULL;
-  Vector **skyOut = NULL;
-  Vector **bckOut = NULL;
-  Vector  *objMin = NULL;
-  Vector  *skyMin = NULL;
-  Vector  *bckMin = NULL;
-
-  // Save all result vectors for each of obj, sky, bck:
-  if (SAVE_ALL_VECTORS) {
-    ALLOCATE (objOut, Vector *, NRESULT);
-    ALLOCATE (skyOut, Vector *, NRESULT);
-    ALLOCATE (bckOut, Vector *, NRESULT);
-    for (int i = 0; i < NRESULT; i++) {
-      char name[64];
-      snprintf (name, 64, "obj_%04d", i); if ((objOut[i] = SelectVector (name, ANYVECTOR, TRUE)) == NULL) { return (FALSE); } ResetVector (objOut[i], OPIHI_FLT, Ny);
-      snprintf (name, 64, "sky_%04d", i); if ((skyOut[i] = SelectVector (name, ANYVECTOR, TRUE)) == NULL) { return (FALSE); } ResetVector (skyOut[i], OPIHI_FLT, Ny);
-      snprintf (name, 64, "bck_%04d", i); if ((bckOut[i] = SelectVector (name, ANYVECTOR, TRUE)) == NULL) { return (FALSE); } ResetVector (bckOut[i], OPIHI_FLT, Ny);
-      for (int iy = 0; iy < Ny; iy++) {
-	objOut[i]->elements.Flt[iy] = 0.0;
-	skyOut[i]->elements.Flt[iy] = 0.0;
-	bckOut[i]->elements.Flt[iy] = 0.0;
-      }
-    }
-  }
-  if (SAVE_MIN_VECTORS) {
-    if ((objMin = SelectVector ("objMin", ANYVECTOR, TRUE)) == NULL) { return (FALSE); } ResetVector (objMin, OPIHI_FLT, Ny);
-    if ((skyMin = SelectVector ("skyMin", ANYVECTOR, TRUE)) == NULL) { return (FALSE); } ResetVector (skyMin, OPIHI_FLT, Ny);
-    if ((bckMin = SelectVector ("bckMin", ANYVECTOR, TRUE)) == NULL) { return (FALSE); } ResetVector (bckMin, OPIHI_FLT, Ny);
-    for (int iy = 0; iy < Ny; iy++) {
-      objMin->elements.Flt[iy] = 0.0;
-      skyMin->elements.Flt[iy] = 0.0;
-      bckMin->elements.Flt[iy] = 0.0;
-    }
-  }
-  Vector *chisqVect;
-  if ((chisqVect = SelectVector ("chisqOut", ANYVECTOR, TRUE)) == NULL) { return FALSE; }
-  ResetVector (chisqVect, OPIHI_FLT, NRESULT);
-  for (int i = 0; i < NRESULT; i++) { chisqVect->elements.Flt[i] = 0.0; }
-
-  // XXX temp hack: save chisq subset vectors for each row pass
-  int Npass = Ny / Nrow;
-  ALLOCATE_PTR (chiPass, Vector *, Npass);
-  for (int pass = 0; pass < Npass; pass++) {
-    char name[64];
-    snprintf (name, 64, "chiPass_%03d", pass);
-    if ((chiPass[pass] = SelectVector (name, ANYVECTOR, TRUE)) == NULL) { return FALSE; } ResetVector (chiPass[pass], OPIHI_FLT, NRESULT);
-  }
-
-  float noiseVar = SQ(noise);
-  ALLOCATE_PTR (objNoise, float, Nrow);
-  ALLOCATE_PTR (skyNoise, float, Nrow);
-  ALLOCATE_PTR (bckNoise, float, Nrow);
-
-  // work on segments of Nrow at a time
-  // XXX worry about last segment (< Nrow rows)
-  int pass = 0;
-  for (int row = 0; row < Ny - Nrow; row += Nrow, pass++) {
-
-    int Nresult = 0;
-
-    // obj, sky, bck are initial guesses.  Also use these values to define a range for the initial guesses.
-
-    // If I just use the value in a given bin to define the range, random noise for the
-    // faint end could have bad results (range ~ 0.0).  For that matter, if I am in a
-    // region with large dynamic range (e.g., on an emission or absorption line), then we
-    // likely have large errors in how the guess follows the truth. 
-
-    /** old concept:
-    float objRange = 0, skyRange = 0, bckRange = 0;
-    for (int iy = 0; iy < Nrow; iy++) {
-      objRange = MAX(objVal[iy + row], objRange);
-      skyRange = MAX(skyVal[iy + row], skyRange);
-      bckRange = MAX(bckVal[iy + row], bckRange);
-    }
-    **/
-
-    // new concept: start with 2-sigma range, then ramp down below
-    for (int iy = 0; iy < Nrow; iy++) {
-      objNoise[iy] = nsigma*sqrt(hypot(fabs(objVal[iy + row]) / gain, noiseVar));
-      skyNoise[iy] = nsigma*sqrt(hypot(fabs(skyVal[iy + row]) / gain, noiseVar));
-      bckNoise[iy] = nsigma*sqrt(hypot(fabs(bckVal[iy + row]) / gain, noiseVar));
-    }
-
-    // first test is the input guess
-    if (1) { 
-      opihi_flt *objtest = deimos_make_test (objVal, NULL, row, Nrow, TRUE);
-      opihi_flt *skytest = deimos_make_test (skyVal, NULL, row, Nrow, TRUE);
-      opihi_flt *bcktest = deimos_make_test (bckVal, NULL, row, Nrow, TRUE);
-      
-      // generate the model based on the test values
-      // objtest, skytest, bcktest are segments of the full parameter vectors
-      float *model = deimos_make_model (objtest, skytest, bcktest, psf, profile, trace, NULL, Nx, Nrow, row);
-      
-      // calculate the current chisq
-      // XXX need to add in the per-pixel error or variance
-      int Npts = 0;
-      float chisq = deimos_get_chisq (bufVal, model, Nx, Nrow, row, &Npts);
-      fprintf (stderr, "guess: chisq: %f, Npts: %d\n", chisq, Npts);
-      free (model);
-
-      if (pass < Npass) {
-	chiPass[pass]->elements.Flt[Nresult] = chisq / (float) Npts;
-      }
-
-      // save the results
-      result[Nresult].chisq = chisq / (float) Npts;
-      result[Nresult].obj = objtest;
-      result[Nresult].sky = skytest;
-      result[Nresult].bck = bcktest;
-      Nresult ++;
-    }
-
-    // run Niter iterations
-    for (int iter = 0; iter < Niter; iter ++) {
-
-      // generate a set of test values for obj, sky, backgnd based on the current guess
-      opihi_flt *objtest = deimos_make_test (objVal, objNoise, row, Nrow, TRUE);
-      opihi_flt *skytest = deimos_make_test (skyVal, skyNoise, row, Nrow, TRUE);
-      opihi_flt *bcktest = deimos_make_test (bckVal, bckNoise, row, Nrow, TRUE);
-      
-      for (int itmp = 0; FALSE && (itmp < Nrow); itmp++) {
-	fprintf (stderr, "val: %f %f %f, tst: %f %f %f\n",
-		 objVal[itmp + row],  skyVal[itmp + row],  bckVal[itmp + row], 
-		 objtest[itmp], skytest[itmp], bcktest[itmp]);
-      }
-
-      // generate the model based on the test values
-      // objtest, skytest, bcktest are segments of the full parameter vectors
-      float *model = deimos_make_model (objtest, skytest, bcktest, psf, profile, trace, NULL, Nx, Nrow, row);
-      
-      // calculate the current chisq
-      // XXX need to add in the per-pixel error or variance
-      int Npts = 0;
-      float chisq = deimos_get_chisq (bufVal, model, Nx, Nrow, row, &Npts);
-      // fprintf (stderr, "iter: %d, chisq: %f, Npts: %d\n", iter, chisq, Npts);
-      free (model);
-
-      if (pass < Npass) {
-	chiPass[pass]->elements.Flt[Nresult] = chisq / (float) Npts;
-      }
-
-      // save the results
-      result[Nresult].chisq = chisq / (float) Npts;
-      result[Nresult].obj = objtest;
-      result[Nresult].sky = skytest;
-      result[Nresult].bck = bcktest;
-      Nresult ++;
-    }
-      
-    for (int try = 0; try < Ntry; try ++) {
-      // generate an index of results sorted by chisq
-      int *IDX = deimos_sort_result (result, Nresult);
-
-      int Nnewset = 0;
-
-      // XXX not sure this scaling factor concept is good
-      for (int iy = 0; iy < Nrow; iy++) {
-	objNoise[iy] = scale*objNoise[iy];
-	skyNoise[iy] = scale*skyNoise[iy];
-	bckNoise[iy] = scale*bckNoise[iy];
-      }
-
-      // run Niter iterations, selecting guess values from the result set
-      for (int iter = 0; iter < Niter; iter ++) {
-	int bin = deimos_get_random_sample (Nresult);
-	int entry = IDX[bin];
-	// fprintf (stderr, "try: %d : %d, %f\n", bin, entry, result[entry].chisq);
-
-	// generate a set of test values for obj, sky, backgnd based on the current guess
-	opihi_flt *objtest = deimos_make_test (result[entry].obj, objNoise, row, Nrow, FALSE);
-	opihi_flt *skytest = deimos_make_test (result[entry].sky, skyNoise, row, Nrow, FALSE);
-	opihi_flt *bcktest = deimos_make_test (result[entry].bck, bckNoise, row, Nrow, FALSE);
-      
-	for (int itmp = 0; FALSE && (itmp < Nrow); itmp++) {
-	  fprintf (stderr, "val: %f %f %f, tst: %f %f %f\n",
-		   result[entry].obj[itmp], result[entry].sky[itmp], result[entry].bck[itmp], 
-		   objtest[itmp], skytest[itmp], bcktest[itmp]);
-	}
-
-	// generate the model based on the test values
-	float *model = deimos_make_model (objtest, skytest, bcktest, psf, profile, trace, NULL, Nx, Nrow, row);
-      
-	// calculate the current chisq
-	int Npts = 0;
-	float chisq = deimos_get_chisq (bufVal, model, Nx, Nrow, row, &Npts);
-	// fprintf (stderr, "try: %d, iter: %d, chisq: %f, Npts: %d\n", try, iter, chisq, Npts);
-	free (model);
-
-	if (pass < Npass) {
-	  chiPass[pass]->elements.Flt[Nresult + Nnewset] = chisq / (float) Npts;
-	}
-
-	// save the results
-	result[Nresult + Nnewset].chisq = chisq / (float) Npts;
-	result[Nresult + Nnewset].obj = objtest;
-	result[Nresult + Nnewset].sky = skytest;
-	result[Nresult + Nnewset].bck = bcktest;
-	Nnewset ++;
-      }
-      Nresult += Nnewset;
-    }
-
-    int *IDX = deimos_sort_result (result, Nresult);
-
-    // ENDING: save the best result and info about the allowed chisq region
-    // int *index = sort_result (result, Nresult);
-    // copy result[index[0]].obj,sky,bck to obj,sky,bck
-    for (int i = 0; i < Nresult; i++) {
-      for (int iy = 0; iy < Nrow; iy++) {
-	if (SAVE_ALL_VECTORS) {
-	  objOut[i]->elements.Flt[iy + row] = result[IDX[i]].obj[iy];
-	  skyOut[i]->elements.Flt[iy + row] = result[IDX[i]].sky[iy];
-	  bckOut[i]->elements.Flt[iy + row] = result[IDX[i]].bck[iy];
-	}
-      }
-      chisqVect->elements.Flt[i] += result[IDX[i]].chisq;
-    }
-    if (SAVE_MIN_VECTORS) {
-      for (int iy = 0; iy < Nrow; iy++) {
-	objMin->elements.Flt[iy + row] = result[IDX[0]].obj[iy];
-	skyMin->elements.Flt[iy + row] = result[IDX[0]].sky[iy];
-	bckMin->elements.Flt[iy + row] = result[IDX[0]].bck[iy];
-      }
-    }
-  }
-
-  return TRUE;
-
- usage:
-  gprint (GP_ERR, "USAGE: deimos fitobj (buffer) (Xref) -object vector -sky vector -backgnd vector -trace spline -profile vector -psf vector -stilt (angle)\n");
-  return FALSE;
-}
-
-/****************** fitobj Support Functions *******************/
-
-static opihi_flt *deimos_make_test (opihi_flt *guess, float *sigma, int row, int Nrow, int fullInput) {
-
-  // we have a vector, guess, with some length >= row + Nrow.
-  // generate a set of random values in the vicinty of guess[row] to guess[row+Nrow]
-  // return vector is of length Nrow
-
-  // if fullInput is TRUE,  the guess vector runs from 0 to Ny (full wavelength range)
-  // if fullInput is FALSE, the guess vector runs from row to row + Nrow (subset range)
-  // sigma is always only Nrow long
-
-  ALLOCATE_PTR (value, opihi_flt, Nrow);
-
-  int start_pix = fullInput ? row : 0;
-  int stop_pix  = fullInput ? row + Nrow : Nrow;
-
-  int iv = 0;
-  for (int i = start_pix; i < stop_pix; i++, iv++) {
-    if (!sigma) {
-      value[iv] = guess[i];
-      continue;
-    }
-    if (USE_GAUSS_DEV) {
-      value[iv] = ohana_gaussdev_rnd(guess[i], sigma[iv]);
-      continue;
-    } 
-    
-    // uniform distribution:
-    value[iv] = sigma[iv]*(drand48() - 0.5) + guess[i];
-  }
-  return value;
-}
-
-
-static float deimos_get_chisq (float *buffer, float *model, int Nx, int Ny, int row, int *Npts) {
-
-  int npts = 0;
-  float chisq = 0;
-
-  for (int iy = 0; iy < Ny; iy++) {
-
-    for (int ix = 0; ix < Nx; ix++) {
-
-      int pix_buffer = ix + (iy + row)*Nx;
-      int pix_model  = ix +  iy*Nx;
-
-      if (!isfinite(buffer[pix_buffer])) continue;
-      if (!isfinite(model[pix_model])) continue;
-      chisq += SQ(buffer[pix_buffer] - model[pix_model]);
-      npts ++;
-    }
-  }
-  *Npts = npts;
-  return chisq;
-}
-
-int *deimos_sort_result (DeimosResult *result, int Nresult) {
-
-  ALLOCATE_PTR (IDX,   int,   Nresult);
-  ALLOCATE_PTR (chisq, float, Nresult);
-
-  for (int i = 0; i < Nresult; i++) {
-    IDX[i] = i;
-    chisq[i] = result[i].chisq;
-  }
-
-  sort_float_index (chisq, IDX, Nresult);
-  free (chisq);
-
-  return IDX;
-}
-
-static float DEIMOS_A = 2.0; // value for random sample
-
-int deimos_get_random_sample (int Nresult) {
-
-  // choose a bin from the range 0 - Nresult, with front-loaded weighting.
-
-  // bin = Nresult * (exp(q) - exp(-A)) / (exp(A) - exp(-A))
-  // q = 2A(x - 1/2) : random number between -A and +A
-  // x : random number between 0 and 1
-
-  // f(q;A) = (exp(q) - exp(-A)) / (exp(A) - exp(-A))
-  // f(q;A) ranges from 0 to +1 as x ranges from 0 to +1
-
-  float x = drand48();
-  float q = 2*DEIMOS_A*(x - 0.5);
-  float f = (exp(q) - exp(-DEIMOS_A)) / (exp(DEIMOS_A) - exp(-DEIMOS_A));
-  // XXX optimization : precalculate and save the elements of this function
-  
-  int bin = floor(Nresult * f);
-
-  return bin;
-}
-# endif
Index: trunk/Ohana/src/opihi/mana/deimos_fitprofile.c
===================================================================
--- trunk/Ohana/src/opihi/mana/deimos_fitprofile.c	(revision 41326)
+++ 	(revision )
@@ -1,299 +1,0 @@
-# include "data.h"
-
-typedef opihi_flt FitFunc (opihi_flt, opihi_flt *, int, opihi_flt *);
-typedef enum {MODE_UPPER, MODE_LOWER} SigmoidMode;
-
-void sigmoid_fit (opihi_flt *xprofile, opihi_flt *fprofile, opihi_flt *wprofile, opihi_flt *oprofile, int Npts, opihi_flt *par, int Npar, FitFunc *FUNC);
-void sigmoid_fit_irls (opihi_flt *xprofile, opihi_flt *fprofile, opihi_flt *wprofile, opihi_flt *oprofile, int NptsAll, opihi_flt *par, int Npar, SigmoidMode mode, double limit);
-
-opihi_flt fsigmoidDeimos (opihi_flt, opihi_flt *, int, opihi_flt *);
-opihi_flt rsigmoidDeimos (opihi_flt, opihi_flt *, int, opihi_flt *);
-
-double deimos_weight_cauchy (double x);
-
-// use these globals to carry into sigmoid_fit
-static int VERBOSE = FALSE;
-static int QUIET   = FALSE;
-static int MaxIterations = 10;
-
-int deimos_fitprofile (int argc, char **argv) {
-
-  // fit simple slit window profile model to vector
-  // I am fitting a sigmoid at both edges
-
-  // input parameters:
-  // * xprofile    : extracted slit window coordinates (vector)
-  // * xprofile    : extracted slit window profile (vector)
-  // * Xs, Xe      : scale coordinates of window boundaries
-
-  // output parameters:
-  // * sigmoid_left_center, etc : coordinates of window boundaries
-
-  int N;
-  Vector *xprofile = NULL;
-  Vector *fprofile = NULL;
-  Vector *wprofile = NULL;
-
-  QUIET = FALSE;
-  if ((N = get_argument (argc, argv, "-q"))) {
-    QUIET = TRUE;
-    remove_argument (N, &argc, argv);
-  }
-  if ((N = get_argument (argc, argv, "-quiet"))) {
-    QUIET = TRUE;
-    remove_argument (N, &argc, argv);
-  }
-  VERBOSE = FALSE;
-  if ((N = get_argument (argc, argv, "-v"))) {
-    VERBOSE = TRUE;
-    remove_argument (N, &argc, argv);
-  }
-  MaxIterations = 10;
-  if ((N = get_argument (argc, argv, "-max-iterations"))) {
-    remove_argument (N, &argc, argv);
-    MaxIterations = atof(argv[N]);
-    remove_argument (N, &argc, argv);
-  }
-
-  if (argc != 6) goto usage;
-  if ((xprofile = SelectVector (argv[1], OLDVECTOR, TRUE)) == NULL) return (FALSE);
-  if ((fprofile = SelectVector (argv[2], OLDVECTOR, TRUE)) == NULL) return (FALSE);
-  if ((wprofile = SelectVector (argv[3], OLDVECTOR, TRUE)) == NULL) return (FALSE);
-  if (xprofile->Nelements != fprofile->Nelements) goto usage;
-  if (xprofile->Nelements != wprofile->Nelements) goto usage;
-
-  // supplied guess for boundaries
-  double Xs = atof(argv[4]);
-  double Xe = atof(argv[5]);
-
-  // output vectors of fits
-  Vector *Lprofile = SelectVector ("sigmoid_left", ANYVECTOR, TRUE);
-  if (Lprofile == NULL) return (FALSE);
-  MatchVector (Lprofile, xprofile, OPIHI_FLT);
-  Vector *Rprofile = SelectVector ("sigmoid_right", ANYVECTOR, TRUE);
-  if (Rprofile == NULL) return (FALSE);
-  MatchVector (Rprofile, xprofile, OPIHI_FLT);
-
-  // first, use supplied Xs & Xe guess to make a guess for BckL, Sky, BckR
-  
-  float Sky_V = 0.0, BckL_V = 0.0, BckR_V = 0.0;
-  float Sky_N = 0.0, BckL_N = 0.0, BckR_N = 0.0;
-  for (int i = 0; i < xprofile->Nelements; i++) {
-    if (!isfinite(wprofile->elements.Flt[i])) continue;
-    if (!isfinite(fprofile->elements.Flt[i])) continue;
-    float wt = 1 / SQ(wprofile->elements.Flt[i]);
-    if (xprofile->elements.Flt[i] < Xs) {
-      BckL_V += fprofile->elements.Flt[i]*wt;
-      BckL_N += wt;
-      continue;
-    }
-    if (xprofile->elements.Flt[i] > Xe) {
-      BckR_V += fprofile->elements.Flt[i]*wt;
-      BckR_N += wt;
-      continue;
-    }
-    Sky_V += fprofile->elements.Flt[i]*wt;
-    Sky_N += wt;
-  }
-  float Sky = Sky_V / Sky_N;
-  float BckL = BckL_V / BckL_N;
-  float BckR = BckR_V / BckR_N;
-
-  // temporary storage vectors 
-  opihi_flt par[4];
-
-  float Xmid = 0.5*(Xs + Xe);
-
-  int Npar = 4;
-  par[0] = Xs;
-  par[1] = 1;
-  par[2] = Sky;
-  par[3] = BckL;
-  sigmoid_fit_irls (xprofile->elements.Flt, fprofile->elements.Flt, wprofile->elements.Flt, Lprofile->elements.Flt, xprofile->Nelements, par, Npar, MODE_LOWER, Xmid);
-  set_variable ("sigmoid_left_center", par[0]);
-  set_variable ("sigmoid_left_sigma",  par[1]);
-  set_variable ("sigmoid_left_top",    par[2]);
-  set_variable ("sigmoid_left_bottom", par[3]);
-
-  par[0] = Xe;
-  par[1] = 1;
-  par[2] = Sky;
-  par[3] = BckR;
-  sigmoid_fit_irls (xprofile->elements.Flt, fprofile->elements.Flt, wprofile->elements.Flt, Rprofile->elements.Flt, xprofile->Nelements, par, Npar, MODE_UPPER, Xmid);
-  set_variable ("sigmoid_right_center", par[0]);
-  set_variable ("sigmoid_right_sigma",  par[1]);
-  set_variable ("sigmoid_right_top",    par[2]);
-  set_variable ("sigmoid_right_bottom", par[3]);
- 
-  return TRUE;
-  
-usage:
-  gprint (GP_ERR, "USAGE: deimos fitprofile xprof fprof wprof Xs Xe\n");
-  return FALSE;
-}
-
-/* pars: x_o, sigma, top, bottom */
-opihi_flt rsigmoidDeimos (opihi_flt x, opihi_flt *par, int Npar, opihi_flt *dpar) {
-  OHANA_UNUSED_PARAM(Npar);
-
-  double z = (x - par[0])/par[1];
-  double r = exp (z);
-  double s = 1 + r;
-  double q = 1 / s;
-  double f = par[2]*q + par[3];
-
-  // df/dp0 = df/dq * dq/dr * dr/dz * dz/dp0
-  // df/dq  = par[2]
-  // dq/ds  = -s^-2 = -q/s
-  // ds/dr  = 1
-  // dr/dz  = r
-  // dz/dp0 = -1 / par[1]
-  // dz/dp1 = -z / par[1]
-
-  // df/dp0 = par[2]*(-q/s)*r*(-1/par[1]) = par[2]*q*r/(s*par[1])
-  // df/dp1 = par[2]*(-q/s)*r*(-z/par[1]) = par[2]*q*r*z/(s*par[1])
-
-  if (dpar) {
-    dpar[0] = par[2]*q*r/(s*par[1]); 
-    dpar[1] = dpar[0]*z;
-    dpar[2] = q;
-    dpar[3] = 1;
-  }
-  
-  return (f);
-}
-
-/* pars: x_o, sigma, top, bottom */
-opihi_flt fsigmoidDeimos (opihi_flt x, opihi_flt *par, int Npar, opihi_flt *dpar) {
-  OHANA_UNUSED_PARAM(Npar);
-
-  double z = (x - par[0])/par[1];
-  double r = exp (-z);
-  double s = 1 + r;
-  double q = 1 / s;
-  double f = par[2]*q + par[3];
-
-  // df/dp0 = df/dq * dq/dr * dr/dz * dz/dp0
-  // df/dq  = par[2]
-  // dq/ds  = -s^-2 = -q/s
-  // ds/dr  = 1
-  // dr/dz  = -r
-  // dz/dp0 = -1 / par[1]
-  // dz/dp1 = -z / par[1]
-
-  // df/dp0 = -par[2]*(-q/s)*r*(-1/par[1]) = par[2]*q*r/(s*par[1])
-  // df/dp1 = -par[2]*(-q/s)*r*(-z/par[1]) = par[2]*q*r*z/(s*par[1])
-
-  if (dpar) {
-    dpar[0] = -par[2]*q*r/(s*par[1]); 
-    dpar[1] = dpar[0]*z;
-    dpar[2] = q;
-    dpar[3] = 1;
-  }
-  
-  return (f);
-}
-
-# define FIT_TOLERANCE 1e-4
-# define FLT_TOLERANCE 1e-6
-
-// wprofile is the true poisson error
-void sigmoid_fit_irls (opihi_flt *xprofile, opihi_flt *fprofile, opihi_flt *wprofile, opihi_flt *oprofile, int NptsAll, opihi_flt *par, int Npar, SigmoidMode mode, double limit) {
-
-  FitFunc *FUNC = (mode == MODE_LOWER) ? fsigmoidDeimos : rsigmoidDeimos;
-
-  ALLOCATE_PTR (par_old, opihi_flt, Npar);
-
-  // allocate these as global static in this file?
-  ALLOCATE_PTR (xtemp, opihi_flt, NptsAll);
-  ALLOCATE_PTR (ytemp, opihi_flt, NptsAll);
-  ALLOCATE_PTR (wtemp, opihi_flt, NptsAll);
-  ALLOCATE_PTR (otemp, opihi_flt, NptsAll);
-
-  // extract the points on the right side and fit
-  int Npts = 0;
-  for (int i = 0; i < NptsAll; i++) {
-    if (!isfinite(wprofile[i])) continue;
-    if (!isfinite(fprofile[i])) continue;
-    int keep = (mode == MODE_UPPER) ^ (xprofile[i] < limit);
-    if (keep) {
-      xtemp[Npts] = xprofile[i];
-      ytemp[Npts] = fprofile[i];
-      wtemp[Npts] = (wprofile[i] == 0.0) ? 1.0 : wprofile[i]; // crude
-      Npts ++;
-    }
-  }
-
-  // define initial weights as 1.0
-  ALLOCATE_PTR (wt, opihi_flt, Npts);
-  for (int i = 0; i < Npts; i++) { 
-    wt[i] = 1.0 / SQ(wtemp[i]);
-  }
-
-  // initial fit with ordinary least-squares
-  // otemp is the fitted value of the function at xtemp
-  sigmoid_fit (xtemp, ytemp, wt, otemp, Npts, par, Npar, FUNC);
-
-  int converged = FALSE;
-  for (int iterations = 0; !converged && (iterations < MaxIterations); iterations++) {
-
-    for (int i = 0; i < Npts; i++) {
-      wt[i] = deimos_weight_cauchy ((ytemp[i] - otemp[i]) / wtemp[i]) / SQ(wtemp[i]);
-    }
-
-    sigmoid_fit (xtemp, ytemp, wt, otemp, Npts, par, Npar, FUNC);
-
-    // save this solution
-    for (int i = 0; i < Npar; i++) {
-      par_old[i] = par[i];
-    }
-
-    converged = TRUE;
-    for (int i = 0; i < Npts; i++) {
-      if ((fabs(par[i] - par_old[i]) > FIT_TOLERANCE * fabs(par[i])) && 
-	  (fabs(par[i] - par_old[i]) > FLT_TOLERANCE))
-	converged = FALSE;
-    }
-  }
-
-  for (int i = 0; i < NptsAll; i++) {
-    oprofile[i] = FUNC (xprofile[i], par, Npar, NULL);
-  }
-
-  FREE (xtemp);
-  FREE (ytemp);
-  FREE (wtemp);
-  FREE (otemp);
-
-  FREE (par_old);
-  FREE (wt);
-}
-
-void sigmoid_fit (opihi_flt *xprofile, opihi_flt *yprofile, opihi_flt *wprofile, opihi_flt *oprofile, int Npts, opihi_flt *par, int Npar, FitFunc *FUNC) {
-
-  double ochisq = mrqinit (xprofile, yprofile, wprofile, Npts, par, Npar, FUNC, VERBOSE);
-  double dchisq = ochisq + 2*Npts;
-
-  int Niter;
-  for (Niter = 0; (Niter < 20) && ((dchisq > 0.1*(Npts - Npar)) || (dchisq <= 0.0)); Niter++) {
-    double chisq = mrqmin (xprofile, yprofile, wprofile, Npts, par, Npar, FUNC, VERBOSE);
-    dchisq = ochisq - chisq;
-    ochisq = chisq;
-    if (VERBOSE) gprint (GP_ERR, "dchisq: %f, Ndof: %d\n", dchisq, Npts - Npar);
-  }  
-  if (VERBOSE) gprint (GP_ERR, "%d iterations\n", Niter); 
-
-  if (!QUIET) gprint (GP_LOG, "sigmoid @ %f (%f) : top %f bottom %f\n", par[0], par[1], par[2], par[3]);
-
-  for (int i = 0; i < Npts; i++) {
-    oprofile[i] = FUNC (xprofile[i], par, Npar, NULL);
-  }
-
-  mrqfree (Npar);
-}  
-
-double deimos_weight_cauchy (double x) {
-  double r = x / 2.385;
-  return (1.0 / (1.0 + SQ(r)));
-}
-
Index: trunk/Ohana/src/opihi/mana/deimos_fitslit.c
===================================================================
--- trunk/Ohana/src/opihi/mana/deimos_fitslit.c	(revision 41326)
+++ trunk/Ohana/src/opihi/mana/deimos_fitslit.c	(revision 41340)
@@ -1,11 +1,9 @@
 # include "data.h"
-# define IRLS_TOLERANCE 1e-4
-
-float weight_cauchy_square_flt (float x2);
-static void fitflux (float *Fwind, float *Fprof, float *weight, int Nx, double *flux, double *sky);
 
 int deimos_fitslit (int argc, char **argv) {
 
-  // fitslit (window) (vari) (slit) (flux) (sky)
+  // fitslit (window) (slit) (flux) (sky)
+
+  // int N;
 
   Vector *flux    = NULL;
@@ -13,25 +11,9 @@
 
   Buffer *wind    = NULL;
-  Buffer *vari    = NULL;
   Buffer *slit    = NULL;
 
-  int N;
-  int Niter = 10;
-  if ((N = get_argument (argc, argv, "-irls-iter"))) {
-    remove_argument (N, &argc, argv);
-    Niter = atoi (argv[N]);
-    remove_argument (N, &argc, argv);
-  }
-
-  Buffer *model = NULL;
-  if ((N = get_argument (argc, argv, "-model"))) {
-    remove_argument (N, &argc, argv);
-    if ((model = SelectBuffer (argv[N], ANYBUFFER, TRUE)) == NULL) return (FALSE);
-    remove_argument (N, &argc, argv);
-  }
-
-  if (argc != 6) {
-    gprint (GP_ERR, "USAGE: deimos fitslit (window) (variance) (slit) (flux) (sky)\n");
-    gprint (GP_ERR, "  inputs:  window (observed 2D flux), variance (on 2D flux), slit (model 2D flux)\n");
+  if (argc != 5) {
+    gprint (GP_ERR, "USAGE: deimos fitslit (window) (slit) (flux) (sky)\n");
+    gprint (GP_ERR, "  inputs:  window (observed 2D flux), slit (model 2D flux)\n");
     gprint (GP_ERR, "  outputs: flux (best-fit 1D flux), sky (best-fit 1D background)\n");
     return FALSE;
@@ -40,8 +22,9 @@
   // XXX I probably should rename FindSpline as SelectSpline and give it the same behavior
   if ((wind = SelectBuffer (argv[1], OLDBUFFER, TRUE)) == NULL) return (FALSE);
-  if ((vari = SelectBuffer (argv[2], OLDBUFFER, TRUE)) == NULL) return (FALSE);
-  if ((slit = SelectBuffer (argv[3], OLDBUFFER, TRUE)) == NULL) return (FALSE);
-  if ((flux = SelectVector (argv[4], ANYVECTOR, TRUE)) == NULL) return (FALSE);
-  if ((sky  = SelectVector (argv[5], ANYVECTOR, TRUE)) == NULL) return (FALSE);
+  if ((slit = SelectBuffer (argv[2], OLDBUFFER, TRUE)) == NULL) return (FALSE);
+  if ((flux = SelectVector (argv[3], ANYVECTOR, TRUE)) == NULL) return (FALSE);
+  if ((sky  = SelectVector (argv[4], ANYVECTOR, TRUE)) == NULL) return (FALSE);
+
+  // XXX confirm slit and wind have same dimensions
 
   // define the output window
@@ -49,117 +32,42 @@
   int Ny = wind[0].matrix.Naxis[1];
   
-  // confirm wind, vari, slit have same dimensions
   if (Nx != slit[0].matrix.Naxis[0]) { gprint (GP_ERR, "size mismatch in fitslit for window and slit\n"); return FALSE; }
   if (Ny != slit[0].matrix.Naxis[1]) { gprint (GP_ERR, "size mismatch in fitslit for window and slit\n"); return FALSE; }
-  if (Nx != vari[0].matrix.Naxis[0]) { gprint (GP_ERR, "size mismatch in fitslit for window and variance\n"); return FALSE; }
-  if (Ny != vari[0].matrix.Naxis[1]) { gprint (GP_ERR, "size mismatch in fitslit for window and variance\n"); return FALSE; }
 
   ResetVector (flux, OPIHI_FLT, Ny);
   ResetVector (sky,  OPIHI_FLT, Ny);
 
-  if (model) {
-    if (!CreateBuffer (model, Nx, Ny, -32, 1.0, 0.0)) { gprint (GP_ERR, "error generating output model buffer\n"); return FALSE; }
-  }
-
   float *Fwind = (float *) wind[0].matrix.buffer;
-  float *Fvari = (float *) vari[0].matrix.buffer;
   float *Fprof = (float *) slit[0].matrix.buffer;
-  float *FmodOut = model ? (float *) model[0].matrix.buffer : NULL;
-
-  ALLOCATE_PTR (weight, float, Nx);
-  ALLOCATE_PTR (rawwgt, float, Nx);
 
   // loop over the rows
   for (int iy = 0; iy < Ny; iy++) {
 
-    double F = 0.0, S = 0.0;
+    // calculate elements of the chi-square for this row:
 
-    // set weight based on the variance
+    double R = 0.0, P = 0.0, P2 = 0.0, f = 0.0, fp = 0.0;
+    double wt = 1.0;
+
     for (int ix = 0; ix < Nx; ix++) {
-      float vari = Fvari[ix + iy*Nx];
-      weight[ix] = !isfinite(vari) || (fabs(vari) < 1e-6) ? 1.0 : 1.0 / vari;
-      rawwgt[ix] = weight[ix];
+      
+      float fxy = Fwind[ix + iy*Nx];
+      float pxy = Fprof[ix + iy*Nx];
+
+      R  += wt; 
+      P  += pxy*wt;
+      P2 += pxy*pxy*wt;
+      f  += fxy*wt;
+      fp += fxy*pxy*wt;
     }
 
-    // calculate elements of the chi-square for this row:
-    fitflux (&Fwind[iy*Nx], &Fprof[iy*Nx], weight, Nx, &F, &S);
-
-    // do an IRLS loop here to reject outliers
-    int converged = FALSE;
-    for (int iter = 0; (iter < Niter) && !converged; iter++) {
-
-      double Flast = F;
-      double Slast = S;
-
-      // calculate weight modification based on distances (squared).
-      // use modifier to calculate new weighted mean
-      for (int ix = 0; ix < Nx; ix++) {
-
-	// F & S are model parameters; compare the model and observed values for each pixel
-	float Fmodel = S + F*Fprof[ix + iy*Nx];
-	float dV = (Fwind[ix + iy*Nx] - Fmodel);
-	float d2 = SQ(dV) * rawwgt[ix];
-	
-	float Mod = weight_cauchy_square_flt (d2);
-	weight[ix] = Mod * rawwgt[ix];
-      }
-      fitflux (&Fwind[iy*Nx], &Fprof[iy*Nx], weight, Nx, &F, &S);
-
-      float dF = fabs(F - Flast);
-      float dS = fabs(S - Slast);
-
-      if ((dF < F * IRLS_TOLERANCE) && (dS < S * IRLS_TOLERANCE)) converged = TRUE;
-    }
-
-    if (FmodOut) {
-      for (int ix = 0; ix < Nx; ix++) {
-	// F & S are model parameters; compare the model and observed values for each pixel
-	float Fmodel = S + F*Fprof[ix + iy*Nx];
-	float dV = (Fwind[ix + iy*Nx] - Fmodel);
-	float d2 = SQ(dV) * rawwgt[ix];
-	float Mod = weight_cauchy_square_flt (d2);
-	if (Mod < 0.1) {
-	  FmodOut[ix + iy*Nx] = NAN;
-	} else {
-	  FmodOut[ix + iy*Nx] = Fmodel;
-	}
-      }
-    }
+    double det = R*P2 - P*P;
+    double S = (P2*f - P*fp) / det;
+    double F = (R*fp - P*f) / det;
 
     flux->elements.Flt[iy] = F;
     sky->elements.Flt[iy] = S;
   }
+
   return TRUE;
 }
 
-// weight is 1 / variance
-// Fwind, Fprof are pointers to the start of a single row 
-// Fwind is the observed flux in the window
-// Fprof is the slit profile
-void fitflux (float *Fwind, float *Fprof, float *weight, int Nx, double *flux, double *sky) {
-
-  // calculate elements of the chi-square fit for this row:
-
-  double R = 0.0, P = 0.0, P2 = 0.0, f = 0.0, fp = 0.0;
-
-  for (int ix = 0; ix < Nx; ix++) {
-      
-    double fxy = Fwind[ix];
-    double pxy = Fprof[ix];
-
-    // skip NAN / Inf pixels in either window or slit
-    if (!isfinite(fxy)) continue;
-    if (!isfinite(pxy)) continue;
-
-    double wt = (weight == NULL) ? 1.0 : weight[ix];
-    R  += wt;
-    P  += pxy*wt;
-    P2 += pxy*pxy*wt;
-    f  += fxy*wt;
-    fp += fxy*pxy*wt;
-  }
-
-  double det = R*P2 - P*P;
-  *sky = (P2*f - P*fp) / det;
-  *flux = (R*fp - P*f) / det;
-}
Index: trunk/Ohana/src/opihi/mana/deimos_getobj.c
===================================================================
--- trunk/Ohana/src/opihi/mana/deimos_getobj.c	(revision 41326)
+++ trunk/Ohana/src/opihi/mana/deimos_getobj.c	(revision 41340)
@@ -3,17 +3,29 @@
 // temporary storage used in local functions:
 
-static float *tmpv = NULL;
-static float *tmpx = NULL;
-
-float get_median_flt (float *val, int Nval) {
-
-  if (Nval <= 0) return NAN;
-
-  int Nval2 = Nval / 2;
-
-  fsort (val, Nval);
-  float value = (Nval % 2) ? val[Nval2] : 0.5*(val[Nval2-1] + val[Nval2]);
-
-  return value;
+float *tmpv = NULL;
+float *tmpx = NULL;
+
+// pass in a pointer to the row (&buffV[iy*Nx])
+float get_segment_median (float *buffV, float Xs, float Xe, float *Xref) {
+
+  // get the pixels in the left portion below profile:
+  // XXX: worry about the effect of a fractional offset
+  for (int ix = Xs + 0.5; ix < Xe + 0.5; ix++) {
+    int i = ix - Xs;
+    tmpv[i] = buffV[ix];
+    tmpx[i] = ix;
+  }
+  int Nv = Xe - Xs;
+
+  // generate a statistic from these pixels: mean, median, etc?
+  fsort (tmpv, Nv);
+  int Nv2 = Nv/2; // Nv == 1, Nv2 = 0, Nv == 2, Nv2 = 1, Nv == 3, Nv2 = 1, Nv == 4, Nv == 2
+  float V = (Nv % 2) ? tmpv[Nv2] : 0.5*(tmpv[Nv2-1] + tmpv[Nv2]);
+    
+  // calculate average coordinate (not flux-weighted...)
+  // XXX : if we allow (and exclude) NAN-valued pixels, we can calculate this more explicitly
+  *Xref = 0.5*(Xe + Xs);
+
+  return V;
 }
 
@@ -25,12 +37,7 @@
   // not used : LSF -- not needed (measurement per disp pixel)
 
-  // This version uses the median of the pixels in the image which are
-  // in regions where the slit profile is < 15% (as opposed to the
-  // getobj version which attempts to fit both background and sky regions
-
   // input parameters:
   // * buffer      : 2D image of slit (full frame or cutout?)
-  // * slit_trace  : spline fit of slit central x pos vs y-coord
-  // * psf_trace   : spline fit of psf central x pos vs y-coord
+  // * trace       : spline fit of slit central x pos vs y-coord
   // * profile     : slit window profile (vector)
   // * PSF         : point-spread function vector (flux normalized, x-dir)
@@ -44,7 +51,5 @@
   int N;
 
-  Spline *slit_trace_red = NULL;
-  Spline *slit_trace_blu = NULL;
-  Spline *psf_trace  = NULL;
+  Spline *trace   = NULL;
   Vector *profile = NULL;
 
@@ -59,28 +64,14 @@
   float stilt = 0.0; // angle of the slit
 
-  // for a red vs blu spline, we need to specify the split point
-  // XXX this is REALLY ad-hoc for Deimos.  not sure how to make
-  // this more generic (need to define the ranges somewhere)
-  int redlimit = 4096;
-  if ((N = get_argument (argc, argv, "-redlimit"))) {
-    remove_argument (N, &argc, argv);
-    redlimit = atoi (argv[N]);
-    remove_argument (N, &argc, argv);
-  }
+  int SaveSegments = FALSE;
+  if ((N = get_argument (argc, argv, "-save-segments"))) {
+    remove_argument (N, &argc, argv);
+    SaveSegments = TRUE;
+  } 
 
   // Input parameters:
-  if ((N = get_argument (argc, argv, "-slit-trace-red"))) {
-    remove_argument (N, &argc, argv);
-    if ((slit_trace_red = FindSpline (argv[N])) == NULL) return (FALSE);
-    remove_argument (N, &argc, argv);
-  }
-  if ((N = get_argument (argc, argv, "-slit-trace-blu"))) {
-    remove_argument (N, &argc, argv);
-    if ((slit_trace_blu = FindSpline (argv[N])) == NULL) return (FALSE);
-    remove_argument (N, &argc, argv);
-  }
-  if ((N = get_argument (argc, argv, "-psf-trace"))) {
-    remove_argument (N, &argc, argv);
-    if ((psf_trace = FindSpline (argv[N])) == NULL) return (FALSE);
+  if ((N = get_argument (argc, argv, "-trace"))) {
+    remove_argument (N, &argc, argv);
+    if ((trace = FindSpline (argv[N])) == NULL) return (FALSE);
     remove_argument (N, &argc, argv);
   } else { goto usage; }
@@ -146,4 +137,47 @@
   ResetVector (backgnd, OPIHI_FLT, Ny);
   
+  // I need to generate a sky-left and sky-right vector in a region on the slit portion of
+  // the profile, but off the object.  Then each of these vectors can be shifted up and down
+  // based on stilt.  Use these sky vectors to predict the sky under the PSF
+
+  // *** scan the profile to determine the background and sky cut points ***
+
+  // values below in the profile coordinate system need to be shifted by (Xref - Nprofile/2)
+  // to match the image coordinate system
+
+  int B_s_l = 0, B_e_l = -1; // left background window
+  int B_s_r = -1, B_e_r = Nprofile - 1; // right background window
+  int S_left = -1, S_right = -1; // top portion of profile
+  for (int i = 0; i < Nprofile; i++) {
+    if ((B_e_l   <  0) && (profile->elements.Flt[i] > 0.10)) B_e_l = i - 1;
+    if ((B_e_l   >= 0) && (S_left  < 0) && (profile->elements.Flt[i] > 0.95)) S_left = i;
+    if ((S_left  >= 0) && (S_right < 0) && (profile->elements.Flt[i] < 0.95)) S_right = i - 1;
+    if ((S_right >= 0) && (profile->elements.Flt[i] < 0.10)) { B_s_r = i; break; }
+  }
+  if (B_e_l == B_s_l) B_e_l ++;
+  if (B_e_r == B_s_r) B_s_r --;
+
+  // S_left to S_right defines are window at the top, choose 0.05 - 0.15, 0.85 - 0.95
+  int N_top = S_right - S_left + 1;
+
+  // if N_top < 20, these jumps might be too small
+  // if N_top < 20, these jumps might be too small
+  int S_s_l = S_left + 0.05*N_top;
+  int S_e_l = S_left + 0.15*N_top;
+  if (S_e_l == S_s_l) S_e_l ++;
+  int S_s_r = S_left + 0.85*N_top;
+  int S_e_r = S_left + 0.95*N_top;
+  if (S_e_r == S_s_r) S_s_r --;
+
+  gprint (GP_ERR, "windows: %.1f - %.1f, %.1f - %.1f, %.1f - %.1f, %.1f - %.1f\n",
+	  B_s_l + Xref - Xprofile, B_e_l + Xref - Xprofile,
+	  S_s_l + Xref - Xprofile, S_e_l + Xref - Xprofile,
+	  S_s_r + Xref - Xprofile, S_e_r + Xref - Xprofile,
+	  B_s_r + Xref - Xprofile, B_e_r + Xref - Xprofile);
+
+  // OPEN QUESTIONS:
+  // NOTE: if the range of pixels in the windows is too large, then the tilt will wash out the signal.
+  // this pass is a guess, so perhaps that does not matter, but there is clearly a trade-off here.
+
   // generate two buffers to store the flux and coordinate for the background, sky, object pixels:
   ALLOCATE (tmpv, float, Nx);
@@ -152,9 +186,75 @@
   float *buffV = (float *) buffer[0].matrix.buffer;
 
+  // use these to store the flux vectors
+  ALLOCATE_PTR (bckF_lf, float, Ny);
+  ALLOCATE_PTR (bckF_rt, float, Ny);
+  ALLOCATE_PTR (skyF_lf, float, Ny);
+  ALLOCATE_PTR (skyF_rt, float, Ny);
+
+  // use these to store the x-coord vectors
+  ALLOCATE_PTR (bckX_lf, float, Ny);
+  ALLOCATE_PTR (bckX_rt, float, Ny);
+  ALLOCATE_PTR (skyX_lf, float, Ny);
+  ALLOCATE_PTR (skyX_rt, float, Ny);
+
   float dxMax = 0; // maximum distance between sky regions
 
+  Vector *skyLsV = NULL, *skyLeV = NULL, *skyLfV = NULL, *skyRsV = NULL, *skyReV = NULL, *skyRfV = NULL;
+  Vector *bckLsV = NULL, *bckLeV = NULL, *bckLfV = NULL, *bckRsV = NULL, *bckReV = NULL, *bckRfV = NULL;
+  if (SaveSegments) {
+    skyLsV = SelectVector ("skyLs", ANYVECTOR, TRUE);  ResetVector (skyLsV, OPIHI_FLT, Ny);
+    skyLeV = SelectVector ("skyLe", ANYVECTOR, TRUE);  ResetVector (skyLeV, OPIHI_FLT, Ny);
+    skyLfV = SelectVector ("skyLf", ANYVECTOR, TRUE);  ResetVector (skyLfV, OPIHI_FLT, Ny);
+    skyRsV = SelectVector ("skyRs", ANYVECTOR, TRUE);  ResetVector (skyRsV, OPIHI_FLT, Ny);
+    skyReV = SelectVector ("skyRe", ANYVECTOR, TRUE);  ResetVector (skyReV, OPIHI_FLT, Ny);
+    skyRfV = SelectVector ("skyRf", ANYVECTOR, TRUE);  ResetVector (skyRfV, OPIHI_FLT, Ny);
+    bckLsV = SelectVector ("bckLs", ANYVECTOR, TRUE);  ResetVector (bckLsV, OPIHI_FLT, Ny);
+    bckLeV = SelectVector ("bckLe", ANYVECTOR, TRUE);  ResetVector (bckLeV, OPIHI_FLT, Ny);
+    bckLfV = SelectVector ("bckLf", ANYVECTOR, TRUE);  ResetVector (bckLfV, OPIHI_FLT, Ny);
+    bckRsV = SelectVector ("bckRs", ANYVECTOR, TRUE);  ResetVector (bckRsV, OPIHI_FLT, Ny);
+    bckReV = SelectVector ("bckRe", ANYVECTOR, TRUE);  ResetVector (bckReV, OPIHI_FLT, Ny);
+    bckRfV = SelectVector ("bckRf", ANYVECTOR, TRUE);  ResetVector (bckRfV, OPIHI_FLT, Ny);
+  }
+
+  // loop over the y positions
+  for (int iy = 0; iy < Ny; iy++) {
+
+    // evaluate the trace spline at this y-coord to find the x-coord offset of the profile center
+    float dXtrace = spline_apply_dbl (trace->xk, trace->yk, trace->y2, trace->Nknots, iy);
+
+    // Xref is the reference coordinate of the profile on the image
+    // Xprofile is the center of the profile.  
+    // dXtrace follows the x-dir variations of the slit profile
+    float Xtrace = Xref - Xprofile + dXtrace;
+
+    bckF_lf[iy] = get_segment_median(&buffV[iy*Nx], B_s_l + Xtrace, B_e_l + Xtrace, &bckX_lf[iy]);
+    bckF_rt[iy] = get_segment_median(&buffV[iy*Nx], B_s_r + Xtrace, B_e_r + Xtrace, &bckX_rt[iy]);
+    skyF_lf[iy] = get_segment_median(&buffV[iy*Nx], S_s_l + Xtrace, S_e_l + Xtrace, &skyX_lf[iy]);
+    skyF_rt[iy] = get_segment_median(&buffV[iy*Nx], S_s_r + Xtrace, S_e_r + Xtrace, &skyX_rt[iy]);
+    dxMax = MAX (dxMax, skyX_rt[iy] - skyX_lf[iy]); // this is a constant value unless we ignore some of the pixels
+    // assert skyX_rt > skyX_lf ?
+
+    if (SaveSegments) {
+      skyLsV->elements.Flt[iy] = S_s_l + Xtrace;
+      skyLeV->elements.Flt[iy] = S_e_l + Xtrace;
+      skyLfV->elements.Flt[iy] = skyF_lf[iy];
+      skyRsV->elements.Flt[iy] = S_s_r + Xtrace;
+      skyReV->elements.Flt[iy] = S_e_r + Xtrace;
+      skyRfV->elements.Flt[iy] = skyF_rt[iy];
+      bckLsV->elements.Flt[iy] = B_s_l + Xtrace;
+      bckLeV->elements.Flt[iy] = B_e_l + Xtrace;
+      bckLfV->elements.Flt[iy] = bckF_lf[iy];
+      bckRsV->elements.Flt[iy] = B_s_r + Xtrace;
+      bckReV->elements.Flt[iy] = B_e_r + Xtrace;
+      bckRfV->elements.Flt[iy] = bckF_rt[iy];
+    }
+  }
+
   // extract sky-subtracted values for the psf fit, using the two sky vectors to predict the sky
-  float sin_stilt = sin(stilt*RAD_DEG);
-  float dyMax = dxMax*sin_stilt;  // dxMax is based on the profile width, calculated above
+  float dyMax = dxMax*sin(stilt*RAD_DEG);  // dxMax is based on the profile width, calculated above
+
+  // find nominal dy_lf, dy_rt offsets for the sky vectors.  
+  int dy_lf = -dyMax / 2; 
+  int dy_rt = +dyMax / 2;
 
   // we are fitting this PSF to the data:
@@ -173,99 +273,32 @@
   }    
 
+
+  // Ys, Ye based on the dyMax value above (skip the first few lines to avoid running out of bounds on sky)
   for (int iy = fabs(dyMax); iy < Ny - fabs(dyMax); iy++) {
 
+    // X_lf & X_rt are calculated in image x-coords
+    float S_lf = skyF_lf[iy + dy_lf];
+    float S_rt = skyF_rt[iy + dy_rt];
+    float X_lf = skyX_lf[iy + dy_lf];
+    float X_rt = skyX_rt[iy + dy_rt];
+    
     // evaluate the trace spline at this y-coord to find the x-coord offset of the profile center
-    Spline *slit_trace = (iy < redlimit) ? slit_trace_red : slit_trace_blu;
-    float dXtraceSLIT = spline_apply_dbl (slit_trace->xk, slit_trace->yk, slit_trace->y2, slit_trace->Nknots, iy);
-    float dXtracePSF  = spline_apply_dbl (psf_trace->xk, psf_trace->yk, psf_trace->y2, psf_trace->Nknots, iy);
+    float dXtrace = spline_apply_dbl (trace->xk, trace->yk, trace->y2, trace->Nknots, iy);
       
     // Xref is the reference coordinate of the profile on the image
     // Xpsf is the center of the PSF.  
     // dXtrace follows the x-dir variations of the slit profile (or PSF?)
-
-    // XtracePSF is the offset between the buffer ix and the psf elements at this location
-    float XtracePSF = Xref - Xpsf + dXtraceSLIT + dXtracePSF;
-
-    // XtraceSLIT is the offset between the buffer ix and the slit profile elements at this location
-    float XtraceSLIT = Xref - Xprofile + dXtraceSLIT;
-
-    // measure the background outside the slit
-
-    // select pixels from the image which are in the background regions (profile < 0.15)
-    int Nbck = 0;
-    int Nsky = 0;
-    for (int ix = 0; ix < Nx; ix ++) {
-      int islit = ix - XtraceSLIT - 0.5; // slit window coordinate
-      int ipsf = ix - XtracePSF - 0.5;   // psf model coordinate
-
-      if (islit < 0) continue;
-      if (islit >= Nprofile) continue;
-
-      // coordinate of the PSF center:
-      int dxpsf = ipsf - Xpsf;
-      int dypsf = dxpsf * sin_stilt;
-
-      int iY = iy + dypsf;
-
-      if (iy == 6000) {
-	fprintf (stderr, "bck : %d %d %d : %f : %f\n", ix, islit, ipsf, buffV[ix + iY*Nx], profile->elements.Flt[islit]);
-      }
-
-      // pixels in the off-slit background:
-      if (profile->elements.Flt[islit] < 0.15) {
-	tmpv[Nbck] = buffV[ix + iY*Nx];
-	if (!isfinite(tmpv[Nbck])) continue;
-	Nbck ++;
-	continue;
-      }
-
-      // the psf window can be smaller than the slit window
-      if (ipsf < 0) continue;
-      if (ipsf >= Npsf) continue;
-
-      // pixels in the on-slit sky:
-      if ((profile->elements.Flt[islit] > 0.95) && (psfV[ipsf] < 0.15)) {
-	tmpx[Nsky] = buffV[ix + iY*Nx];
-	if (!isfinite(tmpx[Nsky])) continue;
-	Nsky ++;
-      }
-    }
-    backgnd->elements.Flt[iy] = get_median_flt (tmpv, Nbck);
-    float So = get_median_flt (tmpx, Nsky);
-    sky->elements.Flt[iy] = So;
+    float Xtrace = Xref - Xpsf + dXtrace;
+    
+    // include the PSF trace and restrict the fit below to portions where the profile is > 0.95
 
     // now I need to find the limits of the PSF in the buffer at this iy location
-    int Ntmp = 0;
-    for (int ix = 0; ix < Nx; ix ++) {
-      int islit = ix - XtraceSLIT - 0.5; // slit window coordinate
-      int ipsf = ix - XtracePSF - 0.5;   // psf model coordinate
-
-      if (islit < 0) continue;
-      if (islit >= Nprofile) continue;
-
-      // the psf window can be smaller than the slit window
-      if (ipsf < 0) continue;
-      if (ipsf >= Npsf) continue;
-
-      // coordinate of the PSF center:
-      int dxpsf = ipsf - Xpsf;
-      int dypsf = dxpsf * sin_stilt;
-
-      int iY = iy + dypsf;
-
-      // filter on the PSF value?
-      if (profile->elements.Flt[islit] < 0.95) continue;
-
-      if (iy == 6000) {
-	fprintf (stderr, "%d %d %d : %f %f : %f : %f\n", ix, islit, ipsf, buffV[ix + iY*Nx] - So, psfV[ipsf], (buffV[ix + iY*Nx] - So)*psfV[ipsf], profile->elements.Flt[islit]);
-      }
-
-      tmpv[Ntmp] = buffV[ix + iY*Nx] - So;
-      tmpx[Ntmp] = psfV[ipsf];
-
-      if (!isfinite(tmpv[Ntmp])) continue;
-      if (!isfinite(tmpx[Ntmp])) continue;
-
-      Ntmp ++;
+    for (int ipsf = 0; ipsf < Npsf; ipsf ++) {
+
+      int ix = ipsf + Xtrace + 0.5; // image coordinate (nearest pixel center)
+      float So = S_lf + (ix - X_lf)*(S_rt - S_lf)/(X_rt - X_lf); // interpolated sky under PSF peak
+
+      tmpv[ipsf] = buffV[ix + iy*Nx] - So;
+      tmpx[ipsf] = ipsf;
     }
 
@@ -273,16 +306,31 @@
     // now fit the PSF to tmpv by calculating a normalization
     float S1 = 0.0, S2 = 0.0;
-    for (int ipsf = 0; ipsf < Ntmp; ipsf++) {
+    for (int ipsf = 0; ipsf < Npsf; ipsf++) {
       if (iy == 6000) {
-	fprintf (stderr, "%d : %f %f : %f\n", ipsf, tmpv[ipsf], tmpx[ipsf], tmpv[ipsf]*tmpx[ipsf]);
+	fprintf (stderr, "%d : %f %f : %f\n", ipsf, tmpv[ipsf], psfV[ipsf], tmpv[ipsf]*psfV[ipsf]);
       }
-      S1 += tmpv[ipsf]*tmpx[ipsf]; // if we have an errorbar, include / SQ(sigv[i])
-      S2 += tmpx[ipsf]*tmpx[ipsf]; // if we have an errorbar, include / SQ(sigv[i])
+      S1 += tmpv[ipsf]*psfV[ipsf]; // if we have an errorbar, include / SQ(sigv[i])
+      S2 += psfV[ipsf]*psfV[ipsf]; // if we have an errorbar, include / SQ(sigv[i])
     }
+
+    int Xo = Xref - dXtrace; // center of PSF in image x-coordinates
+    float So = S_lf + (Xo - X_lf)*(S_rt - S_lf)/(X_rt - X_lf); // interpolated sky under PSF peak
     object->elements.Flt[iy] = S1 / S2;
+    sky->elements.Flt[iy] = So;
+    backgnd->elements.Flt[iy] = 0.5*(bckF_lf[iy] + bckF_rt[iy]);
   }
 
   free (tmpv);
   free (tmpx);
+
+  free (bckF_lf);
+  free (bckF_rt);
+  free (skyF_lf);
+  free (skyF_rt);
+
+  free (bckX_lf);
+  free (bckX_rt);
+  free (skyX_lf);
+  free (skyX_rt);
 
   return TRUE;
Index: trunk/Ohana/src/opihi/mana/deimos_getobj.v0.c
===================================================================
--- trunk/Ohana/src/opihi/mana/deimos_getobj.v0.c	(revision 41326)
+++ 	(revision )
@@ -1,383 +1,0 @@
-# include "data.h"
-
-// temporary storage used in local functions:
-
-static float *tmpv = NULL;
-static float *tmpx = NULL;
-
-// pass in a pointer to the row (&buffV[iy*Nx])
-float get_segment_median (float *buffV, float Xs, float Xe, float *Xref) {
-
-  // get the pixels in the left portion below profile:
-  // XXX: worry about the effect of a fractional offset
-  for (int ix = Xs + 0.5; ix < Xe + 0.5; ix++) {
-    int i = ix - Xs;
-    tmpv[i] = buffV[ix];
-    tmpx[i] = ix;
-  }
-  int Nv = Xe - Xs;
-
-  // generate a statistic from these pixels: mean, median, etc?
-  fsort (tmpv, Nv);
-  int Nv2 = Nv/2; // Nv == 1, Nv2 = 0, Nv == 2, Nv2 = 1, Nv == 3, Nv2 = 1, Nv == 4, Nv == 2
-  float V = (Nv % 2) ? tmpv[Nv2] : 0.5*(tmpv[Nv2-1] + tmpv[Nv2]);
-    
-  // calculate average coordinate (not flux-weighted...)
-  // XXX : if we allow (and exclude) NAN-valued pixels, we can calculate this more explicitly
-  *Xref = 0.5*(Xe + Xs);
-
-  return V;
-}
-
-int deimos_getobj (int argc, char **argv) {
-
-  // determine rough object model parameters based on quick stats
-  // input : buffer PSF trace profile stilt
-  // output : object sky background
-  // not used : LSF -- not needed (measurement per disp pixel)
-
-  // input parameters:
-  // * buffer      : 2D image of slit (full frame or cutout?)
-  // * slit_trace  : spline fit of slit central x pos vs y-coord
-  // * psf_trace   : spline fit of psf central x pos vs y-coord
-  // * profile     : slit window profile (vector)
-  // * PSF         : point-spread function vector (flux normalized, x-dir)
-  // * stilt       : slit tilt response : 2D kernel? 
-
-  // output parameters:
-  // * object      : vector of object flux vs y-coord 
-  // * sky         : vector of local sky signal vs y-coord
-  // * background  : vector of extra-slit background flux vs y-coord
-
-  int N;
-
-  Spline *slit_trace = NULL;
-  Spline *psf_trace  = NULL;
-  Vector *profile = NULL;
-
-  Vector *object  = NULL;
-  Vector *sky     = NULL;
-  Vector *backgnd = NULL;
-
-  Vector *psf     = NULL;
-
-  Buffer *buffer  = NULL;
-
-  float stilt = 0.0; // angle of the slit
-
-  int SaveSegments = FALSE;
-  if ((N = get_argument (argc, argv, "-save-segments"))) {
-    remove_argument (N, &argc, argv);
-    SaveSegments = TRUE;
-  } 
-
-  // Input parameters:
-  if ((N = get_argument (argc, argv, "-slit-trace"))) {
-    remove_argument (N, &argc, argv);
-    if ((slit_trace = FindSpline (argv[N])) == NULL) return (FALSE);
-    remove_argument (N, &argc, argv);
-  } else { goto usage; }
-  if ((N = get_argument (argc, argv, "-psf-trace"))) {
-    remove_argument (N, &argc, argv);
-    if ((psf_trace = FindSpline (argv[N])) == NULL) return (FALSE);
-    remove_argument (N, &argc, argv);
-  } else { goto usage; }
-  if ((N = get_argument (argc, argv, "-profile"))) {
-    remove_argument (N, &argc, argv);
-    if ((profile = SelectVector (argv[N], OLDVECTOR, TRUE)) == NULL) return (FALSE);
-    remove_argument (N, &argc, argv);
-  } else { goto usage; }
-  if ((N = get_argument (argc, argv, "-psf"))) {
-    remove_argument (N, &argc, argv);
-    if ((psf = SelectVector (argv[N], OLDVECTOR, TRUE)) == NULL) return (FALSE);
-    remove_argument (N, &argc, argv);
-  } else { goto usage; }
-  if ((N = get_argument (argc, argv, "-stilt"))) {
-    remove_argument (N, &argc, argv);
-    stilt = atof (argv[N]);
-    remove_argument (N, &argc, argv);
-  } else { goto usage; }
-
-  // Output parameters:
-  if ((N = get_argument (argc, argv, "-object"))) {
-    remove_argument (N, &argc, argv);
-    if ((object = SelectVector (argv[N], ANYVECTOR, TRUE)) == NULL) return (FALSE);
-    remove_argument (N, &argc, argv);
-  } else { goto usage; }
-  if ((N = get_argument (argc, argv, "-sky"))) {
-    remove_argument (N, &argc, argv);
-    if ((sky = SelectVector (argv[N], ANYVECTOR, TRUE)) == NULL) return (FALSE);
-    remove_argument (N, &argc, argv);
-  } else { goto usage; }
-  if ((N = get_argument (argc, argv, "-backgnd"))) {
-    remove_argument (N, &argc, argv);
-    if ((backgnd = SelectVector (argv[N], ANYVECTOR, TRUE)) == NULL) return (FALSE);
-    remove_argument (N, &argc, argv);
-  } else { goto usage; }
-
-  if (argc != 3) goto usage;
-
-  // buffer is the full image, Xref is reference coordinate of the profile in the buffer
-  if ((buffer = SelectBuffer (argv[1], OLDBUFFER, TRUE)) == NULL) return (FALSE);
-  float Xref = atof(argv[2]);
-  
-  // profile and PSF are defined with central reference pixel mapped to Xref (+ trace)
-  int Nprofile = profile->Nelements;
-  if (Nprofile % 2 == 0) {
-    gprint (GP_ERR, "slit profile vector must have an odd number of pixels\n");
-    return FALSE;
-  }
-  int Xprofile = Nprofile / 2;
-
-  int Npsf = psf->Nelements;
-  if (Npsf % 2 == 0) {
-    gprint (GP_ERR, "PSF vector must have an odd number of pixels\n");
-    return FALSE;
-  }
-  int Xpsf = Npsf / 2;
-
-  // we will generate output vectors (object, sky, background) of length Ny
-  int Nx = buffer[0].matrix.Naxis[0];
-  int Ny = buffer[0].matrix.Naxis[1];
-  ResetVector (object,  OPIHI_FLT, Ny);
-  ResetVector (sky,     OPIHI_FLT, Ny);
-  ResetVector (backgnd, OPIHI_FLT, Ny);
-  
-  // I need to generate a sky-left and sky-right vector in a region on the slit portion of
-  // the profile, but off the object.  Then each of these vectors can be shifted up and down
-  // based on stilt.  Use these sky vectors to predict the sky under the PSF
-
-  // *** scan the profile to determine the background and sky cut points ***
-
-  // values below in the profile coordinate system need to be shifted by (Xref - Nprofile/2)
-  // to match the image coordinate system
-
-  int B_s_l = 0, B_e_l = -1; // left background window
-  int B_s_r = -1, B_e_r = Nprofile - 1; // right background window
-  int S_left = -1, S_right = -1; // top portion of profile
-  for (int i = 0; i < Nprofile; i++) {
-    if ((B_e_l   <  0) && (profile->elements.Flt[i] > 0.10)) B_e_l = i - 1;
-    if ((B_e_l   >= 0) && (S_left  < 0) && (profile->elements.Flt[i] > 0.95)) S_left = i;
-    if ((S_left  >= 0) && (S_right < 0) && (profile->elements.Flt[i] < 0.95)) S_right = i - 1;
-    if ((S_right >= 0) && (profile->elements.Flt[i] < 0.10)) { B_s_r = i; break; }
-  }
-  if (B_e_l == B_s_l) B_e_l ++;
-  if (B_e_r == B_s_r) B_s_r --;
-
-  // S_left to S_right defines are window at the top, choose 0.05 - 0.15, 0.85 - 0.95
-  int N_top = S_right - S_left + 1;
-
-  // if N_top < 20, these jumps might be too small
-  // if N_top < 20, these jumps might be too small
-  int S_s_l = S_left + 0.05*N_top;
-  int S_e_l = S_left + 0.15*N_top;
-  if (S_e_l == S_s_l) S_e_l ++;
-  int S_s_r = S_left + 0.85*N_top;
-  int S_e_r = S_left + 0.95*N_top;
-  if (S_e_r == S_s_r) S_s_r --;
-
-  gprint (GP_ERR, "windows: %.1f - %.1f, %.1f - %.1f, %.1f - %.1f, %.1f - %.1f\n",
-	  B_s_l + Xref - Xprofile, B_e_l + Xref - Xprofile,
-	  S_s_l + Xref - Xprofile, S_e_l + Xref - Xprofile,
-	  S_s_r + Xref - Xprofile, S_e_r + Xref - Xprofile,
-	  B_s_r + Xref - Xprofile, B_e_r + Xref - Xprofile);
-
-  // OPEN QUESTIONS:
-  // NOTE: if the range of pixels in the windows is too large, then the tilt will wash out the signal.
-  // this pass is a guess, so perhaps that does not matter, but there is clearly a trade-off here.
-
-  // generate two buffers to store the flux and coordinate for the background, sky, object pixels:
-  ALLOCATE (tmpv, float, Nx);
-  ALLOCATE (tmpx, float, Nx);
-
-  float *buffV = (float *) buffer[0].matrix.buffer;
-
-  // use these to store the flux vectors
-  ALLOCATE_PTR (bckF_lf, float, Ny);
-  ALLOCATE_PTR (bckF_rt, float, Ny);
-  ALLOCATE_PTR (skyF_lf, float, Ny);
-  ALLOCATE_PTR (skyF_rt, float, Ny);
-
-  // use these to store the x-coord vectors
-  ALLOCATE_PTR (bckX_lf, float, Ny);
-  ALLOCATE_PTR (bckX_rt, float, Ny);
-  ALLOCATE_PTR (skyX_lf, float, Ny);
-  ALLOCATE_PTR (skyX_rt, float, Ny);
-
-  float dxMax = 0; // maximum distance between sky regions
-
-  Vector *skyLsV = NULL, *skyLeV = NULL, *skyLfV = NULL, *skyRsV = NULL, *skyReV = NULL, *skyRfV = NULL;
-  Vector *bckLsV = NULL, *bckLeV = NULL, *bckLfV = NULL, *bckRsV = NULL, *bckReV = NULL, *bckRfV = NULL;
-  if (SaveSegments) {
-    skyLsV = SelectVector ("skyLs", ANYVECTOR, TRUE);  ResetVector (skyLsV, OPIHI_FLT, Ny);
-    skyLeV = SelectVector ("skyLe", ANYVECTOR, TRUE);  ResetVector (skyLeV, OPIHI_FLT, Ny);
-    skyLfV = SelectVector ("skyLf", ANYVECTOR, TRUE);  ResetVector (skyLfV, OPIHI_FLT, Ny);
-    skyRsV = SelectVector ("skyRs", ANYVECTOR, TRUE);  ResetVector (skyRsV, OPIHI_FLT, Ny);
-    skyReV = SelectVector ("skyRe", ANYVECTOR, TRUE);  ResetVector (skyReV, OPIHI_FLT, Ny);
-    skyRfV = SelectVector ("skyRf", ANYVECTOR, TRUE);  ResetVector (skyRfV, OPIHI_FLT, Ny);
-    bckLsV = SelectVector ("bckLs", ANYVECTOR, TRUE);  ResetVector (bckLsV, OPIHI_FLT, Ny);
-    bckLeV = SelectVector ("bckLe", ANYVECTOR, TRUE);  ResetVector (bckLeV, OPIHI_FLT, Ny);
-    bckLfV = SelectVector ("bckLf", ANYVECTOR, TRUE);  ResetVector (bckLfV, OPIHI_FLT, Ny);
-    bckRsV = SelectVector ("bckRs", ANYVECTOR, TRUE);  ResetVector (bckRsV, OPIHI_FLT, Ny);
-    bckReV = SelectVector ("bckRe", ANYVECTOR, TRUE);  ResetVector (bckReV, OPIHI_FLT, Ny);
-    bckRfV = SelectVector ("bckRf", ANYVECTOR, TRUE);  ResetVector (bckRfV, OPIHI_FLT, Ny);
-  }
-
-  // loop over the y positions
-  // examine the slit window profile to measure background and slit sky
-  for (int iy = 0; iy < Ny; iy++) {
-
-    // evaluate the trace spline at this y-coord to find the x-coord offset of the profile center
-    float dXtrace = spline_apply_dbl (slit_trace->xk, slit_trace->yk, slit_trace->y2, slit_trace->Nknots, iy);
-
-    // Xref is the reference coordinate of the profile on the image
-    // Xprofile is the center of the profile.  
-    // dXtrace follows the x-dir variations of the slit profile
-    float Xtrace = Xref - Xprofile + dXtrace;
-
-    bckF_lf[iy] = get_segment_median(&buffV[iy*Nx], B_s_l + Xtrace, B_e_l + Xtrace, &bckX_lf[iy]);
-    bckF_rt[iy] = get_segment_median(&buffV[iy*Nx], B_s_r + Xtrace, B_e_r + Xtrace, &bckX_rt[iy]);
-    skyF_lf[iy] = get_segment_median(&buffV[iy*Nx], S_s_l + Xtrace, S_e_l + Xtrace, &skyX_lf[iy]);
-    skyF_rt[iy] = get_segment_median(&buffV[iy*Nx], S_s_r + Xtrace, S_e_r + Xtrace, &skyX_rt[iy]);
-    dxMax = MAX (dxMax, skyX_rt[iy] - skyX_lf[iy]); // this is a constant value unless we ignore some of the pixels
-    // assert skyX_rt > skyX_lf ?
-
-    if (SaveSegments) {
-      skyLsV->elements.Flt[iy] = S_s_l + Xtrace;
-      skyLeV->elements.Flt[iy] = S_e_l + Xtrace;
-      skyLfV->elements.Flt[iy] = skyF_lf[iy];
-      skyRsV->elements.Flt[iy] = S_s_r + Xtrace;
-      skyReV->elements.Flt[iy] = S_e_r + Xtrace;
-      skyRfV->elements.Flt[iy] = skyF_rt[iy];
-      bckLsV->elements.Flt[iy] = B_s_l + Xtrace;
-      bckLeV->elements.Flt[iy] = B_e_l + Xtrace;
-      bckLfV->elements.Flt[iy] = bckF_lf[iy];
-      bckRsV->elements.Flt[iy] = B_s_r + Xtrace;
-      bckReV->elements.Flt[iy] = B_e_r + Xtrace;
-      bckRfV->elements.Flt[iy] = bckF_rt[iy];
-    }
-  }
-
-  // extract sky-subtracted values for the psf fit, using the two sky vectors to predict the sky
-  float dyMax = dxMax*sin(stilt*RAD_DEG);  // dxMax is based on the profile width, calculated above
-
-  // find nominal dy_lf, dy_rt offsets for the sky vectors.  
-  int dy_lf = -dyMax / 2; 
-  int dy_rt = +dyMax / 2;
-
-  // we are fitting this PSF to the data:
-  opihi_flt *psfV = psf->elements.Flt;
-
-  // init the regions which are outside the valid region
-  for (int iy = 0; iy < fabs(dyMax); iy++) {
-    object->elements.Flt[iy] = 0;
-    sky->elements.Flt[iy] = 0;
-    backgnd->elements.Flt[iy] = 0;
-  }    
-  for (int iy = Ny - fabs(dyMax); iy < Ny; iy++) {
-    object->elements.Flt[iy] = 0;
-    sky->elements.Flt[iy] = 0;
-    backgnd->elements.Flt[iy] = 0;
-  }    
-
-
-  // Ys, Ye based on the dyMax value above (skip the first few lines to avoid running out of bounds on sky)
-  for (int iy = fabs(dyMax); iy < Ny - fabs(dyMax); iy++) {
-
-    // X_lf & X_rt are calculated in image x-coords
-    float S_lf = skyF_lf[iy + dy_lf];
-    float S_rt = skyF_rt[iy + dy_rt];
-    float X_lf = skyX_lf[iy + dy_lf];
-    float X_rt = skyX_rt[iy + dy_rt];
-    
-    // evaluate the trace spline at this y-coord to find the x-coord offset of the profile center
-    float dXtraceSLIT = spline_apply_dbl (slit_trace->xk, slit_trace->yk, slit_trace->y2, slit_trace->Nknots, iy);
-    float dXtracePSF  = spline_apply_dbl (psf_trace->xk, psf_trace->yk, psf_trace->y2, psf_trace->Nknots, iy);
-      
-    // Xref is the reference coordinate of the profile on the image
-    // Xpsf is the center of the PSF.  
-    // dXtrace follows the x-dir variations of the slit profile (or PSF?)
-    float XtracePSF = Xref - Xpsf + dXtraceSLIT + dXtracePSF;
-    float XtraceSLIT = Xref - Xprofile + dXtraceSLIT;
-
-    // include the PSF trace and restrict the fit below to portions where the profile is > 0.95
-
-    // now I need to find the limits of the PSF in the buffer at this iy location
-    int Ntmp = 0;
-    for (int ipsf = 0; ipsf < Npsf; ipsf ++) {
-
-      int ix = ipsf + XtracePSF + 0.5; // image coordinate (nearest pixel center)
-      int islit = ix - XtraceSLIT - 0.5; // image coordinate (nearest pixel center)
-
-      float So = S_lf + (ix - X_lf)*(S_rt - S_lf)/(X_rt - X_lf); // interpolated sky under PSF peak
-
-      if (islit < 0) continue;
-      if (islit >= profile->Nelements) continue;
-
-      if (iy == 6000) {
-	fprintf (stderr, "%d : %f %f : %f : %f\n", ipsf, buffV[ix + iy*Nx] - So, psfV[ipsf], (buffV[ix + iy*Nx] - So)*psfV[ipsf], profile->elements.Flt[islit]);
-      }
-
-      if (profile->elements.Flt[islit] < 0.95) continue;
-
-      tmpv[Ntmp] = buffV[ix + iy*Nx] - So;
-      tmpx[Ntmp] = psfV[ipsf];
-      Ntmp ++;
-    }
-
-    // I now have a pair of vectors (tmpx, tmpv) which are aligned to the PSF at this location
-    // now fit the PSF to tmpv by calculating a normalization
-    float S1 = 0.0, S2 = 0.0;
-    for (int ipsf = 0; ipsf < Ntmp; ipsf++) {
-      if (iy == 6000) {
-	fprintf (stderr, "%d : %f %f : %f\n", ipsf, tmpv[ipsf], tmpx[ipsf], tmpv[ipsf]*tmpx[ipsf]);
-      }
-      S1 += tmpv[ipsf]*tmpx[ipsf]; // if we have an errorbar, include / SQ(sigv[i])
-      S2 += tmpx[ipsf]*tmpx[ipsf]; // if we have an errorbar, include / SQ(sigv[i])
-    }
-
-    int Xo = Xref - dXtraceSLIT - dXtracePSF; // center of PSF in image x-coordinates
-    float So = S_lf + (Xo - X_lf)*(S_rt - S_lf)/(X_rt - X_lf); // interpolated sky under PSF peak
-    object->elements.Flt[iy] = S1 / S2;
-    sky->elements.Flt[iy] = So;
-    backgnd->elements.Flt[iy] = 0.5*(bckF_lf[iy] + bckF_rt[iy]);
-  }
-
-  free (tmpv);
-  free (tmpx);
-
-  free (bckF_lf);
-  free (bckF_rt);
-  free (skyF_lf);
-  free (skyF_rt);
-
-  free (bckX_lf);
-  free (bckX_rt);
-  free (skyX_lf);
-  free (skyX_rt);
-
-  return TRUE;
-
- usage:
-  gprint (GP_ERR, "USAGE: deimos getobj (buffer) (Xref) -object vector -sky vector -backgnd vector -trace spline -profile vector -psf vector -stilt (angle)\n");
-  // can I make default values for trace (0.0), profile (?), psf (fraction of profile?), stilt (0.0)
-  return FALSE;
-}
-
-  /* 
-    // convolve the object flux at this y-coord with PSF and add sky
-    for (int ix = 0; i < Nx; i++) {
-      opihi_flt g = s = 0;
-      for (int n = -Npsf; n <= Npsf; n++) {
-	if (ix + n < 0) continue;
-	if (ix + n >= Nx) continue;
-	opihi_flt value = objV ? objV[ix+n] : 1.0;
-	s += psfV[n]*value;
-	g += psfV[n];
-      }
-      out[ix + iy*Nx] = Npsf ? s / g : (objV ? objV[ix+n] : 1.0);
-      if (skyV) {
-	out[ix + iy*Nx] += skyV[iy]
-    }
-  */
-  
Index: trunk/Ohana/src/opihi/mana/deimos_mkalt.c
===================================================================
--- trunk/Ohana/src/opihi/mana/deimos_mkalt.c	(revision 41326)
+++ trunk/Ohana/src/opihi/mana/deimos_mkalt.c	(revision 41340)
@@ -1,6 +1,4 @@
 # include "data.h"
 # include "deimos.h"
-
-XXX: deprecated
 
 // Use this to test the deimos_make_object function used by deimos_fitobj
@@ -94,5 +92,5 @@
 
   // generate the model based on the test values
-  float *model = deimos_make_model (objV, skyV, bckV, psf, profile, trace, NULL, Nx, Ny, 0);
+  float *model = deimos_make_model (objV, skyV, bckV, psf, profile, trace, Nx, Ny, 0);
 
   ResetBuffer (output, Nx, Ny, -32, 0.0, 1.0);
Index: trunk/Ohana/src/opihi/mana/deimos_mkmodel.c
===================================================================
--- trunk/Ohana/src/opihi/mana/deimos_mkmodel.c	(revision 41326)
+++ trunk/Ohana/src/opihi/mana/deimos_mkmodel.c	(revision 41340)
@@ -86,12 +86,11 @@
 // generate a subimage of the full model for the range row - row + Ny
 // obj,sky,bck are subset vectors corresponding to the range row to row+Ny
-// the slit_trace_* and psf_trace refer to the full image starting at row
-float *deimos_make_model (opihi_flt *obj, opihi_flt *sky, opihi_flt *bck, Vector *psf, Vector *profile, Spline *slit_trace_red, Spline *slit_trace_blu, float redlimit, Spline *psf_trace, int Nx, int Ny, int row) {
-
-  float *raw = deimos_make_straight_image (obj, sky, psf, psf_trace, Nx, Ny, row);
+float *deimos_make_model (opihi_flt *obj, opihi_flt *sky, opihi_flt *bck, Vector *psf, Vector *profile, Spline *trace, int Nx, int Ny, int row) {
+
+  float *raw = deimos_make_straight_image (obj, sky, psf, Nx, Ny, row);
   float *new = deimos_apply_tilt (raw, Nx, Ny);
   deimos_apply_profile (profile, new, Nx, Ny);
   deimos_add_background (bck, new, Nx, Ny, row);
-  float *out = deimos_apply_trace (slit_trace_red, slit_trace_blu, redlimit, new, Nx, Ny, row);
+  float *out = deimos_apply_trace (trace, new, Nx, Ny, row);
 
   free (raw);
@@ -105,5 +104,5 @@
 // *** generate a raw image with no slit tilt and no trace offsets.  apply the PSF to the
 // object flux, add in the sky flux
-float *deimos_make_straight_image (opihi_flt *obj, opihi_flt *sky, Vector *psf, Spline *psf_trace, int Nx, int Ny, int row) {
+float *deimos_make_straight_image (opihi_flt *obj, opihi_flt *sky, Vector *psf, int Nx, int Ny, int row) {
   OHANA_UNUSED_PARAM(row);
   
@@ -114,5 +113,5 @@
 
   // Xref is a global supplied by the user (defaults to Nx/2 if < 0)
-  int XoffRef = (int)(Xref - Npsf);
+  int Xoff = (int)(Xref - Npsf);
 
   // Nx : width of output window
@@ -124,26 +123,7 @@
     
     // we are generating the image for just the row range row to row+Ny
-    // note that obj & sky are subset vectors for just this range of pixels
     opihi_flt objVy = obj[iy]; // if we shift to using the row offset: obj[iy + row]
     opihi_flt skyVy = sky[iy]; // if we shift to using the row offset: sky[iy + row]
       
-    // integral and fractional pixel offsets of PSF (none, by default)
-    int dxi = 0;
-    float dxf = 0.0, dxr = 1.0;
-    int Xoff = XoffRef;
-    
-    if (psf_trace) {
-      // the psf_trace is referenced against the full image, so we need to add row to iy:
-      float dx = spline_apply_dbl (psf_trace->xk, psf_trace->yk, psf_trace->y2, psf_trace->Nknots, iy + row);
-      dxi = floor(dx);
-      dxf = dx - dxi;  // -1.7 -> +0.3, -0.5 -> +0.5, +0.5 ->+0.5, +1.7 -> +0.7
-      dxr = 1 - dxf;
-      Xoff += dxi;
-      // fprintf (stderr, "%d: %f : %d\n", iy + row, dx, Xoff);
-    }
-
-    // if fractional offset is small, do not interpolate
-    int doInterp = fabs(dxf) < 1e-5 ? FALSE : TRUE;
-
     // flux = obj * PSF + sky
     for (int ix = 0; ix < Nx; ix++) {
@@ -156,20 +136,5 @@
       // only add in the flux if we are in range of the PSF
       if ((n >= 0) && (n < NpsfFull)) {
-	if (doInterp) {
-	  if ((n > 0) && (n < NpsfFull)) {
-	    if (isfinite(psfV[n]) && isfinite(psfV[n-1])) {
-	      value += objVy*psfV[n]*dxr + objVy*psfV[n-1]*dxf;
-	    }
-	  }
-	  if (n == 0) {
-	    if (isfinite(psfV[n])) {
-	      value += objVy*psfV[n]*dxr;
-	    }
-	  }
-	} else {
-	  if (isfinite(psfV[n])) {
-	    value += objVy * psfV[n];
-	  }
-	}
+	value += objVy * psfV[n];
       }
       out[ix + iy*Nx] = value;
@@ -254,5 +219,5 @@
 
 // shift pixels in x based on the trace
-float *deimos_apply_trace (Spline *slit_trace_red, Spline *slit_trace_blu, float redlimit, float *input, int Nx, int Ny, int row) {
+float *deimos_apply_trace (Spline *trace, float *input, int Nx, int Ny, int row) {
 
   ALLOCATE_PTR (output, float, Nx*Ny);
@@ -262,7 +227,5 @@
     // evaluate the trace spline at this y-coord to find the x-coord offset of the profile center
     // NOTE: spline is evaluated at full dispersion coordinate
-    int iy_full = iy + row;
-    Spline *slit_trace = (iy_full < redlimit) ? slit_trace_red : slit_trace_blu;
-    float dx = -spline_apply_dbl (slit_trace->xk, slit_trace->yk, slit_trace->y2, slit_trace->Nknots, iy_full);
+    float dx = -spline_apply_dbl (trace->xk, trace->yk, trace->y2, trace->Nknots, iy + row);
       
     // extract the integer pixel offset and the fractional offset
Index: trunk/Ohana/src/opihi/mana/deimos_mkobj.c
===================================================================
--- trunk/Ohana/src/opihi/mana/deimos_mkobj.c	(revision 41326)
+++ trunk/Ohana/src/opihi/mana/deimos_mkobj.c	(revision 41340)
@@ -6,60 +6,33 @@
 
   // input parameters:
-  // * slit_trace_red : spline fit of slit central x pos vs y-coord for red chip
-  // * slit_trace_blu : spline fit of slit central x pos vs y-coord for blu chip
-  // * psf_trace      : spline fit of psf central x pos vs y-coord
-  // * profile        : slit window profile (vector)
-  // * object         : vector of object flux vs y-coord 
-  // * sky            : vector of local sky signal vs y-coord
-  // * backgnd        : vector of extra-slit background flux vs y-coord
-  // * PSF            : point-spread function vector (flux normalized, x-dir)
-  // * LSF            : sline-spread function vector (flux normalized, y-dir)
-  // * stilt          : slit tilt response : 2D kernel? 
-
-  // * redlimit       : pixel break between red and blu chips
-  // * Nwave          : number of wavelength pixels in output image
+  // * trace       : spline fit of slit central x pos vs y-coord
+  // * profile     : slit window profile (vector)
+  // * object      : vector of object flux vs y-coord 
+  // * sky         : vector of local sky signal vs y-coord
+  // * background  : vector of extra-slit background flux vs y-coord
+  // * PSF         : point-spread function vector (flux normalized, x-dir)
+  // * LSF         : sline-spread function vector (flux normalized, y-dir)
+  // * stilt       : slit tilt response : 2D kernel? 
 
   int N;
 
   // if any of these are not defined, they will have assumed identity values
-  Spline *slit_trace_red = NULL;
-  Spline *slit_trace_blu = NULL;
-  Spline *psf_trace  = NULL;
-  Vector *profile    = NULL;
-  Vector *object     = NULL;
-  Vector *sky        = NULL;
-  Vector *backgnd    = NULL;
-		     
-  Vector *psf        = NULL;
-  Vector *lsf        = NULL;
+  Spline *trace   = NULL;
+  Vector *profile = NULL;
+  Vector *object  = NULL;
+  Vector *sky     = NULL;
+  Vector *backgnd = NULL;
+
+  Vector *psf     = NULL;
+  Vector *lsf     = NULL;
   // add tilt later
 
-  Buffer *output     = NULL;
+  Buffer *output  = NULL;
 
   float stilt = 0.0; // angle of the slit
 
-  // for a red vs blu spline, we need to specify the split point
-  // XXX this is REALLY ad-hoc for Deimos.  not sure how to make
-  // this more generic (need to define the ranges somewhere)
-  int redlimit = 4096;
-  if ((N = get_argument (argc, argv, "-redlimit"))) {
-    remove_argument (N, &argc, argv);
-    redlimit = atoi (argv[N]);
-    remove_argument (N, &argc, argv);
-  }
-
-  if ((N = get_argument (argc, argv, "-slit-trace-red"))) {
-    remove_argument (N, &argc, argv);
-    if ((slit_trace_red = FindSpline (argv[N])) == NULL) return (FALSE);
-    remove_argument (N, &argc, argv);
-  }
-  if ((N = get_argument (argc, argv, "-slit-trace-blu"))) {
-    remove_argument (N, &argc, argv);
-    if ((slit_trace_blu = FindSpline (argv[N])) == NULL) return (FALSE);
-    remove_argument (N, &argc, argv);
-  }
-  if ((N = get_argument (argc, argv, "-psf-trace"))) {
-    remove_argument (N, &argc, argv);
-    if ((psf_trace = FindSpline (argv[N])) == NULL) return (FALSE);
+  if ((N = get_argument (argc, argv, "-trace"))) {
+    remove_argument (N, &argc, argv);
+    if ((trace = FindSpline (argv[N])) == NULL) return (FALSE);
     remove_argument (N, &argc, argv);
   }
@@ -108,24 +81,6 @@
   }
 
-  int VERBOSE = FALSE;
-  if ((N = get_argument (argc, argv, "-v"))) {
-    remove_argument (N, &argc, argv);
-    VERBOSE = TRUE;
-  }
-
   if (argc != 3) {
-    gprint (GP_ERR, "USAGE: deimos mkobj (buffer) (Ncross) [-object vector] [-sky vector] [-backgnd vector] [-slit-trace-red spline] [-slit-trace-blu spline] [-psf-trace spline] [-profile vector] [-psf vector] [-lsf vector] [-stilt angle] [-Nwave Npixel] [-redlimit pixel]\n");
-    gprint (GP_ERR, "  slit_trace_red : spline fit of slit central x pos vs y-coord for red chip\n");
-    gprint (GP_ERR, "  slit_trace_blu : spline fit of slit central x pos vs y-coord for blu chip\n");
-    gprint (GP_ERR, "  psf_trace      : spline fit of psf central x pos vs y-coord\n");
-    gprint (GP_ERR, "  profile        : slit window profile (vector)\n");
-    gprint (GP_ERR, "  object         : vector of object flux vs y-coord \n");
-    gprint (GP_ERR, "  sky            : vector of local sky signal vs y-coord\n");
-    gprint (GP_ERR, "  backgnd        : vector of extra-slit background flux vs y-coord\n");
-    gprint (GP_ERR, "  PSF            : point-spread function vector (flux normalized, x-dir)\n");
-    gprint (GP_ERR, "  LSF            : sline-spread function vector (flux normalized, y-dir)\n");
-    gprint (GP_ERR, "  stilt          : slit tilt response : 2D kernel? \n");
-    gprint (GP_ERR, "  redlimit       : pixel break between red and blu chips\n");
-    gprint (GP_ERR, "  Nwave          : number of wavelength pixels in output image\n");
+    gprint (GP_ERR, "USAGE: deimos mkobj (buffer) (Ncross) [-Nwave N] [-object vector] [-sky vector] [-backgnd vector] [-trace spline] [-profile vector]\n");
     return FALSE;
   }
@@ -168,11 +123,10 @@
   // if we are appying a trace offset spline, we need to generate an output window which
   // is Nx + the full swing of the trace, then window back down
-  if (slit_trace_red && slit_trace_blu) {
+  if (trace) {
     float dXmin = +1000;
     float dXmax = -1000;
     for (int iy = 0; iy < Ny; iy++) {
       // evaluate the trace spline at this y-coord to find the x-coord offset of the profile center
-      Spline *slit_trace = (iy < redlimit) ? slit_trace_red : slit_trace_blu;
-      float dx = spline_apply_dbl (slit_trace->xk, slit_trace->yk, slit_trace->y2, slit_trace->Nknots, iy);
+      float dx = spline_apply_dbl (trace->xk, trace->yk, trace->y2, trace->Nknots, iy);
       dXmin = MIN (dx, dXmin);
       dXmax = MAX (dx, dXmax);
@@ -227,21 +181,4 @@
     if (psf) Npof -= Npsf;
 
-    // integral and fractional pixel offsets of PSF (none, by default)
-    int dxi = 0;
-    float dxf = 0.0, dxr = 1.0;
-    
-    if (psf_trace) {
-      float dx = spline_apply_dbl (psf_trace->xk, psf_trace->yk, psf_trace->y2, psf_trace->Nknots, iy);
-      dxi = floor(dx);
-      dxf = dx - dxi;  // -1.7 -> +0.3, -0.5 -> +0.5, +0.5 ->+0.5, +1.7 -> +0.7
-      dxr = 1 - dxf;
-      Npof += dxi;
-      // fprintf (stderr, "%d: %f : %d\n", iy, dx, Npof);
-      if (VERBOSE && (iy % 200 == 0)) { gprint (GP_ERR, "%d : %f : %d : %f %f\n", iy, dx, dxi, dxf, dxr); }
-    }
-
-    // if fractional offset is small, do not interpolate
-    int doInterp = fabs(dxf) < 1e-5 ? FALSE : TRUE;
-
     // flux = obj * PSF + sky
     for (int ix = 0; ix < Nx; ix++) {
@@ -254,20 +191,5 @@
 	// only add in the flux if we are in range of the PSF
 	if ((n >= 0) && (n < NpsfFull)) {
-	  if (doInterp) {
-	    if ((n > 0) && (n < NpsfFull)) {
-	      if (isfinite(psfV[n]) && isfinite(psfV[n-1])) {
-		value += objVy*psfV[n]*dxr + objVy*psfV[n-1]*dxf;
-	      }
-	    }
-	    if (n == 0) {
-	      if (isfinite(psfV[n])) {
-		value += objVy*psfV[n]*dxr;
-	      }
-	    }
-	  } else {
-	    if (isfinite(psfV[n])) {
-	      value += objVy*psfV[n];
-	    }
-	  }
+	  value += objVy * psfV[n];
 	}
       } else {
@@ -407,5 +329,5 @@
 
   // shift pixels in x based on the trace
-  if (slit_trace_red && slit_trace_blu) {
+  if (trace) {
     ALLOCATE_PTR (outTraceBuffer, char, NxBase*Ny*sizeof(float));
     float *outTrace = (float *) outTraceBuffer;
@@ -415,6 +337,5 @@
 
       // evaluate the trace spline at this y-coord to find the x-coord offset of the profile center
-      Spline *slit_trace = (iy < redlimit) ? slit_trace_red : slit_trace_blu;
-      float dx = -spline_apply_dbl (slit_trace->xk, slit_trace->yk, slit_trace->y2, slit_trace->Nknots, iy);
+      float dx = -spline_apply_dbl (trace->xk, trace->yk, trace->y2, trace->Nknots, iy);
       
       // extract the integer pixel offset and the fractional offset
Index: trunk/Ohana/src/opihi/mana/deimos_mkslit.c
===================================================================
--- trunk/Ohana/src/opihi/mana/deimos_mkslit.c	(revision 41326)
+++ trunk/Ohana/src/opihi/mana/deimos_mkslit.c	(revision 41340)
@@ -7,21 +7,14 @@
   // input parameters:
   //   slit profile response : vector of fractional flux vs x-coord
-  //   trace_ref,trace_blu   : spline fit of slit central x pos vs y-coord
-  //   flux (optional)       : vector of input signal vs y-coord
-  //   sky  (optional)       : vector of input signal vs y-coord
-  //   fluxbins (optional)   : size of output image in y-direction
-  //   NOTE: one of flux, sky, or fluxbins must be defined
-
-  // output : buff (an image with Nx defined by profile and Ny defined
-  //                by flux, sky, or fluxbins)
+  //   trace                 : spline fit of slit central x pos vs y-coord
+  //   flux                  : vector of input signal vs y-coord
 
   int N;
 
-  Vector *profile   = NULL;
-  Vector *flux      = NULL;
-  Vector *sky       = NULL;
-  Spline *trace_red = NULL;
-  Spline *trace_blu = NULL;
-  Buffer *buff      = NULL;
+  Vector *profile = NULL;
+  Vector *flux    = NULL;
+  Vector *sky     = NULL;
+  Spline *trace   = NULL;
+  Buffer *buff    = NULL;
 
   // user-specified flux value (otherwise assumed to be 1)
@@ -47,24 +40,6 @@
   }
 
-  // either flux or fluxbins must be specified to define output size
-  int profilebins = 0;
-  if ((N = get_argument (argc, argv, "-profilebins"))) {
-    remove_argument (N, &argc, argv);
-    profilebins = atoi (argv[N]);
-    remove_argument (N, &argc, argv);
-  }
-
-  // for a red vs blu spline, we need to specify the split point
-  // XXX this is REALLY ad-hoc for Deimos.  not sure how to make
-  // this more generic (need to define the ranges somewhere)
-  int redlimit = 4096;
-  if ((N = get_argument (argc, argv, "-redlimit"))) {
-    remove_argument (N, &argc, argv);
-    redlimit = atoi (argv[N]);
-    remove_argument (N, &argc, argv);
-  }
-
-  if (argc != 5) {
-    gprint (GP_ERR, "USAGE: deimos mkslit (profile) (trace_red) (trace_blu) (buffer) [-flux vector] [-fluxbins N] [-sky vector]\n");
+  if (argc != 4) {
+    gprint (GP_ERR, "USAGE: deimos mkslit (profile) (trace) (buffer) [-flux vector] [-fluxbins N] [-sky vector]\n");
     return FALSE;
   }
@@ -76,12 +51,10 @@
 
   // XXX I probably should rename FindSpline as SelectSpline and give it the same behavior
-  if ((profile   = SelectVector (argv[1], OLDVECTOR, TRUE)) == NULL) return (FALSE);
-  if ((trace_red = FindSpline (argv[2])) == NULL) return (FALSE);
-  if ((trace_blu = FindSpline (argv[3])) == NULL) return (FALSE);
-  if ((buff      = SelectBuffer (argv[4], ANYBUFFER, TRUE)) == NULL) return (FALSE);
+  if ((profile = SelectVector (argv[1], OLDVECTOR, TRUE)) == NULL) return (FALSE);
+  if ((trace   = FindSpline (argv[2])) == NULL) return (FALSE);
+  if ((buff    = SelectBuffer (argv[3], ANYBUFFER, TRUE)) == NULL) return (FALSE);
 
   // define the output window
-  // if no profile half-width is specified, use supplied profile 
-  int Nx = profilebins ? 2*profilebins + 1 : 2*profile[0].Nelements + 1;
+  int Nx = 2*profile[0].Nelements + 1;
   int Ny = flux ? flux[0].Nelements : fluxbins;
   
@@ -100,5 +73,4 @@
 
     // evaluate the trace spline at this y-coord to find the x-coord offset of the profile center
-    Spline *trace = (iy < redlimit) ? trace_red : trace_blu;
     float dx = spline_apply_dbl (trace->xk, trace->yk, trace->y2, trace->Nknots, iy);
     
@@ -118,5 +90,5 @@
 
       // set the sky in the entire window 
-      out[ix + iy*Nx] = NAN;
+      out[ix + iy*Nx] = sky ? sky->elements.Flt[iy] : 0.0;
 
       // equivalent coord in the profile:
@@ -126,5 +98,4 @@
 
       // a default value:
-      float vsky = sky ? sky->elements.Flt[iy] : 0.0;
       float vout = NAN;
 
@@ -150,5 +121,5 @@
       if (flux) vout *= flux->elements.Flt[iy];
 
-      out[ix + iy*Nx] = vsky + vout;
+      out[ix + iy*Nx] += vout;
     }
   }
Index: trunk/Ohana/src/opihi/pantasks/Makefile
===================================================================
--- trunk/Ohana/src/opihi/pantasks/Makefile	(revision 41326)
+++ trunk/Ohana/src/opihi/pantasks/Makefile	(revision 41340)
@@ -92,5 +92,6 @@
 $(SRC)/task_command.$(ARCH).o \
 $(SRC)/task_options.$(ARCH).o \
-$(SRC)/version.$(ARCH).o
+$(SRC)/version.$(ARCH).o \
+$(SRC)/ipptool2book.$(ARCH).o
 
 libs = \
Index: trunk/Ohana/src/opihi/pantasks/init.c
===================================================================
--- trunk/Ohana/src/opihi/pantasks/init.c	(revision 41326)
+++ trunk/Ohana/src/opihi/pantasks/init.c	(revision 41340)
@@ -25,4 +25,5 @@
 int verbose         PROTO((int, char **));
 int version         PROTO((int, char **));
+int ipptool2book    PROTO((int, char **));
 
 static Command cmds[] = {  
@@ -34,4 +35,5 @@
   {1, "host",       task_host,     "define host machine for a task"},
   {1, "nice",       task_nice,     "set nice level for a task"},
+  {1, "ipptool2book", ipptool2book, "convert queue with ipptool output to book"},
   {1, "kill",       kill_job,      "kill job"},
   {1, "nmax",       task_nmax,     "define maximum number of jobs for a task"},
Index: trunk/Ohana/src/opihi/pantasks/init_server.c
===================================================================
--- trunk/Ohana/src/opihi/pantasks/init_server.c	(revision 41326)
+++ trunk/Ohana/src/opihi/pantasks/init_server.c	(revision 41340)
@@ -23,4 +23,5 @@
 int version         PROTO((int, char **));
 int server          PROTO((int, char **));
+int ipptool2book    PROTO((int, char **));
 
 int server_run	    PROTO((int, char **));
@@ -35,4 +36,5 @@
   {1, "host",       task_host,     "define host machine for a task"},
   {1, "nice",       task_nice,     "set nice level for a task"},
+  {1, "ipptool2book", ipptool2book, "convert queue with ipptool output to book"},
   {1, "kill",       kill_job,      "kill job"},
   {1, "nmax",       task_nmax,     "define maximum number of jobs for a task"},
Index: trunk/Ohana/src/opihi/pantasks/ipptool2book.c
===================================================================
--- trunk/Ohana/src/opihi/pantasks/ipptool2book.c	(revision 41340)
+++ trunk/Ohana/src/opihi/pantasks/ipptool2book.c	(revision 41340)
@@ -0,0 +1,247 @@
+# include "pantasks.h"
+
+# define FREEKEYS \
+  if (keys) { for (i = 0; i < Nkeys; i++) { free (keys[i]); } free (keys); } \
+  for (i = 0; i < setWordN; i++) { free (setWordList[i]); free (setWordValue[i]); } \
+  free (setWordValue); free (setWordList);
+
+// convert the named queue with ipptool metadata output into book format
+int ipptool2book (int argc, char **argv) {
+
+  int i, N, onPage, found, Unique, Nkeys, NKEYS;
+  char *line, *tmpword, *tmpvalue;
+  char pagename[512]; // XXX this should be made dynamic, though it is an unlikey problem
+  char *bookName, **keys, *p, *q;
+  char **setWordList;
+  char **setWordValue;
+  int setWordN, setWordNalloc;
+
+  Page *page = NULL;
+  Book *book = NULL;
+  Queue *queue = NULL;
+
+  /* supply additional constant words */
+  setWordN = 0;
+  setWordNalloc = 10;
+  ALLOCATE (setWordList, char *, setWordNalloc);
+  ALLOCATE (setWordValue, char *, setWordNalloc);
+  while ((N = get_argument (argc, argv, "-setword"))) {
+    remove_argument (N, &argc, argv);
+    setWordList[setWordN] = strcreate (argv[N]);
+    remove_argument (N, &argc, argv);
+    setWordValue[setWordN] = strcreate (argv[N]);
+    remove_argument (N, &argc, argv);
+    setWordN ++;
+    if (setWordN >= setWordNalloc) {
+      setWordNalloc += 10;
+      REALLOCATE (setWordList, char *, setWordNalloc);
+      REALLOCATE (setWordValue, char *, setWordNalloc);
+    }      
+  }
+
+  Unique = FALSE;
+  if ((N = get_argument (argc, argv, "-uniq"))) {
+    remove_argument (N, &argc, argv);
+    Unique = TRUE;
+  }
+
+  Nkeys = 0;
+  keys = NULL;
+  if ((N = get_argument (argc, argv, "-key"))) {
+    remove_argument (N, &argc, argv);
+
+    /* parse the key (word:word:word) into constituents */
+    NKEYS = 10;
+    ALLOCATE (keys, char *, NKEYS);
+    
+    p = q = argv[N];
+    while (q != NULL) {
+      q = strchr (p, ':');
+      keys[Nkeys] = (q == NULL) ? strcreate (p) : strncreate (p, q - p);
+      p = q + 1;
+      Nkeys ++;
+      CHECK_REALLOCATE (keys, char *, NKEYS, Nkeys, 10);
+    }
+    remove_argument (N, &argc, argv);
+  }
+
+  if (argc != 3) {
+    gprint (GP_ERR, "USAGE: ipptool2book (queue) (book) [-uniq] [-key key[:key..]]\n");
+    FREEKEYS;
+    return (TRUE);
+  }
+
+  queue = FindQueue (argv[1]);
+  if (queue == NULL) {
+    gprint (GP_ERR, "queue %s not found\n", argv[1]);
+    FREEKEYS;
+    return (TRUE);
+  }
+    
+  book = CreateBook (argv[2]);
+
+  /* the first non-whitespace line of the queue should contain:
+     BookName MULTI
+  */
+
+  /* scan for first non-emtpy line */
+  while (TRUE) {
+    line = PopQueue (queue);
+    if (!line) {
+      FREEKEYS;
+      return (TRUE); // no output in queue - not an error?
+    }
+    stripwhite (line);
+    if (line[0] == '#') {
+      free (line);
+      continue;
+    }
+    if (*line) break;
+    free (line);
+  }
+  bookName = thisword (line);
+  tmpword = nextword (line);
+
+  if (!tmpword || strcmp(tmpword, "MULTI")) {
+    gprint (GP_ERR, "ERROR: missing metadata output name on first line\n");
+    free (bookName);
+    free (line);
+    FREEKEYS;
+    return (TRUE);
+  }
+  free (line);
+  
+  onPage = FALSE;
+  while (TRUE) {
+    line = PopQueue (queue);
+    if (!line) {
+      free (bookName);
+      if (onPage) {
+	gprint (GP_ERR, "ERROR: unterminated metadata\n");
+	FREEKEYS;
+	return (TRUE);
+      }
+      FREEKEYS;
+      return (TRUE);
+    }
+    stripwhite (line);
+    if (!*line) {
+      free (line);
+      continue;
+    }
+    if (line[0] == '#') {
+      free (line);
+      continue;
+    }
+    
+    tmpword = thisword (line);
+    if (tmpword == NULL) abort(); // should not happen if line exists
+
+    if (!onPage) {
+      if (strcmp(tmpword, bookName)) {
+	gprint (GP_ERR, "ERROR: unexpected metadata name %s\n", tmpword);
+	free (line);
+	free (tmpword);
+	free (bookName);
+	FREEKEYS;
+	return (TRUE);
+      }
+      free (tmpword);
+      tmpword = thisword (nextword (line));
+      if (strcmp(tmpword, "METADATA")) {
+	gprint (GP_ERR, "ERROR: missing METADATA tag\n");
+	free (line);
+	free (tmpword);
+	free (bookName);
+	FREEKEYS;
+	return TRUE;
+      }
+      onPage = TRUE;
+      // we don't know the page name until we load its data?
+      sprintf (pagename, "page.%03d", book[0].Npages);
+      page = CreatePage (book, pagename);
+      free (line);
+      free (tmpword);
+      continue;
+    } 
+
+    /* close out the page */
+    if (!strcmp(tmpword, "END")) {
+      // XXX set the page name based on the contents
+      free (tmpword);
+      free (line);
+
+      if (keys) {
+	memset (pagename, 0, 512);
+	for (i = 0; i < Nkeys; i++) {
+	  tmpword = BookGetWord (page, keys[i]);
+	  if (tmpword == NULL) {
+	    gprint (GP_ERR, "ERROR: missing key %s for ID\n", keys[i]);
+	    FREEKEYS;
+	    return (TRUE);
+	  }
+	  if (i > 0) strcat (pagename, ":");
+	  strcat (pagename, tmpword);
+	}
+	free (page[0].name);
+	page[0].name = strcreate (pagename);
+      }
+
+      // add the fixed words to the page
+      for (i = 0; i < setWordN; i++) {
+	BookSetWord (page, setWordList[i], setWordValue[i]);
+      }
+
+      if (Unique) {
+	/* search for an existing page with this name
+	   delete this one if one is found */
+	/* XXX don't attach this page to the book until this step is passed */	
+
+	found = FALSE;
+	for (i = 0; !found && (i < book[0].Npages); i++) {
+	  if (book[0].pages[i] == page) continue;
+	  if (!strcmp (book[0].pages[i][0].name, page[0].name)) {
+	    found = TRUE;
+	  }
+	}
+	if (found) {
+	  DeletePage (book, page);
+	}
+      }
+
+      onPage = FALSE;
+      continue;
+    }
+
+    tmpvalue = thisword (nextword(nextword(line)));
+    if (tmpvalue == NULL) {
+      gprint (GP_ERR, "ERROR: missing value for %s\n", tmpword);
+      free (tmpword);
+      free (line);
+      free (bookName);
+      FREEKEYS;
+      return (TRUE);
+    }
+    BookSetWord (page, tmpword, tmpvalue);
+    free (tmpword);
+    free (tmpvalue);
+    free (line);
+  }    
+  FREEKEYS;
+  return (TRUE);
+}
+
+/* scan through the queue lines.  these should look like:  
+
+bookName METADATA
+key type value
+key type value
+...
+END
+
+bookName METADATA
+key type value
+key type value
+...
+END
+*/
