NAME: 
  optspec
 PURPOSE:
  Optimal extraction of a point source spectrum from OSIRIS XD data.
 DESCRIPTION:
  This program is custom built to extract spectra from OSIRIS XD data.
    The spectral images contain usually 3 or 4 cross-dispersed orders.
    Because of the high and variable sky background signal, all images are
    reduced as image pairs to permit excluding most sky signal at the
    very first step.

  As the program progresses, numerous plot and display windows are opened.
    Window 0: Image window that contain 4 rows of strip images.  The strip
              images come from extracting the relevant portions of the
              original image such that the object spectrum will be
              parallel to a row in the resampled image.  All pixels outside
              the slit are discarded.  The 4 rows contain:
                0 (top)    - Original image, scaled from image min to max.
                1          - Original image, scaled from +/- 3 sigma about the
                                robust mean of the image.
                2          - Image after final sky subtraction scaled on same
                                range and row #1.  This strip should have no
                                remnant sky structure if everything works.
                3 (bottom) - Image from row #2 after subtracting out the
                                postive spectrum.  Ideally, you should not
                                see a remnant of the positive spectral image.

    Window 1: Trivial sum over the positive image aperture.

    Window 2: Average column profile computed by summing all columns.  This
                 summation is robust against bad pixels, no data, etc.
                 Superimposed on the profile are (1) the +/- threshold
                 that is used to locate the positive and negative image.
                 The lines are drawn at +/- 3 sigma from the background (fit
                 by a linear fuction). (2) red diamonds show those pixels
                 identified as pure sky. (3) orange '*' show the positive
                 image pixels. (4) brownish-green '*' show the negative image
                 pixels.

    Window 5,6,7,8: Plot of the residuals of pixel location of spectrum vs.
                 column.  Each order is plotted in a different window.

    Window 10: Plot of the optimally extracted spectrum.  It's most useful
                 to compare this against the plot in window 1.

    Window 11: Ratio of the optimal spectrum to the summation spectrum.

    Window 12: Plot of spectrum location in all orders in the original
                 image coordinates.  White points are those considered good
                 during the process of tracing the centerlines.  Red points
                 are those flagged as bad because the position was outside
                 the positive aperture.  The brownish-green points
                 are those flagged as bad because the FWHM at that column
                 was abberant.
    Window 13: Plot of the true image profiles in each order.  If not FINAL
                 this shows the actual profile with the gaussian approximation
                 overlain.  When FINAL is set, you will also see an overlay
                 of the actual numerical image profile that was generated.

 CATEGORY:
  Spectroscopy
 CALLING SEQUENCE:
  optspec,calib,root,i1,i2,spec,all
 INPUTS:
  calib- Anonymous structure containing all pertinent calibration
           information.  This structure is usually loaded beforehand using
           the routine, "ldcalir"
  root - string containing the root of the file name (with leading path
         if desired).  DO NOT include the . between the root and suffix.
  i1   - Frame id (integer) of first image.
  i2   - Frame id (integer) of second image.
 OPTIONAL INPUT PARAMETERS:
 KEYWORD INPUT PARAMETERS:
  FINAL   - Flag, if set, indicates that this is a final pass extraction.
              If it is not "final" then the optimal extractor uses a
              gaussian profile fitted to the data.  This option is most
              often used when the bad pixel mask does not yet exist.
              When FINAL is set, a full numerical profile is generated and
              used for the optimal extraction.  In this case, the gaussian
              profile is used to help with locating the centerline but not
              for the spectral extraction.
  FINDBAD - Flag, if set causes program to look for bad pixels in the sky
              region.  Upon completion, a strip array is written to disk with
              the file name, mask.NNN, where the bad pixels have been set to 1.
  GAUSSCOR- Correction factor from the directly computed image FWHM (per order)
              to the final optimal weighting profile.  (Default = 1.3, this
              number is only approximately correct but seems to be pretty
              close.  A number smaller than this will often lead to spurious
              periodic noise, often quite a lot of noise.  A number that is
              too large will add a small amount of extra noise.  Ideally this
              should be set for each and every spectrum but this has not yet
              proved tractable.)
  NONEG   - Flag, if true will inhibit all treatment of the negative image.
              This should only be used if you know that there is no negative
              spectral image and will preserve the maximum amount of sky in
              the process.
  RAW     - Flag, if true will inhibit the column-wise background subtraction.
              The default is to fit the background in each column (along the
              slit) and subtract the fitted background.  Use a linear function
              for the background.
  MASK    - Strip image mask.  Good pixels are 1, bad pixels are 0.  Bad pixels
              are passed over during the profile weighting summation.
  SAVE    - Flag, if true, final spectrum will be saved to a file.  The output
              file name is root+'s'+suffix.  Thus 950911.003 would be saved to
              the file 950911s.003.  Also, a file with the average spatial
              profile is saved to root+'p'+suffix.
  OUTPATH - The path to the location where data is to be saved, default is
              the current directory.
  PATH    - optional string that points to the directory containing the data.
              This information is not used if the root already begins with '/'.
              If root is not an absolute pathname, then PATH is prepended to
              root for READ operations.  This path is not used for saving.
              This allows reading from one directory (possible a read only area)
              and then saving to the current directory.
  PLOTS   - Which plots to show.
              0 - Show them all (default).
              1 - Don't show any plots or images.
              2 - Just show windows 0, 2, and 13 (strip image, average column
                     profile, actual profile of each order).
  CLEAN   - Flag, if set, calls clnspec to allow removing bad points before
              saving spectrum (this is actually obsolete but left in for now).

 OUTPUTS:
  spec - 1-D spectrum extracted from spectral image.
  all  - i1-i2 after XD spectra extracted to strip image. (see getpair)
 KEYWORD OUTPUT PARAMETERS:
 COMMON BLOCKS:
 SIDE EFFECTS:
 RESTRICTIONS:
  Specifically written for OSIRIS cross-dispersed spectral data.  MASK
  does not work particularly well.
 PROCEDURE:
 MODIFICATION HISTORY:
  97/03, Written by Marc W. Buie, Lowell Observatory, cloned from getspec
  97/08/07, MWB, massive reworking and debugging.
  97/12/10, MWB, finalize new version, added OUTPATH keyword
  98/06/09, MWB, added GAUSSCOR keyword.  Also numerous additions for
                   improved bad pixel flagging.
  98/08/11, MWB, removed obsolete keywords and updated the documentation.
  98/08/25, MWB, added PLOTS=2 option.  Added NONEG flag.