NAME: 
  mkflat

 PURPOSE: 
  Collect and combine CCD flat frames into a superflat frame

 DESCRIPTION:

  The files are assumed to be named as 'root'NNN where 'root' is the
  root of the file name that you supply and NNN is a three digit number.
  If your file name has an imbedded '.' then add it to the root.

  The specified range of files are all read in from FITS files.  Then each
  image has the overscan mean subtracted (if desired), cropped (as indicated),
  input bias image is subtracted, and then the dark is multipled by each
  image's exposure time and then subtracted.  These images are then
  normalized using the mean of the SCALE region and then averaged weighting
  by the signal-to-noise ratio of each flat image.  The weighted averaging
  is done with AVGCLIP.PRO which does a robust average of the image
  stack so that cosmic rays, stars, and other transient image defects are
  eliminated.  This will do a very good sky flat if enough images are provided
  of different field pointings.

  When done, the resulting flat image is returned to the caller and the image
  is saved to a FITS file with the specified output filename.

 CATEGORY:
  CCD data processing

 CALLING SEQUENCE:
  mkflat,root,outsuf,start,nframes,bias,dark,flat

 INPUTS:
  root    - Root of the file name (you must include . in the name).
  outsuf  - The suffix of the final output file.
  start   - First frame number to read (integer or long).
               Start can also be a vector of explicit frame numbers to load.
               In this case, nframes need not be specified and in fact will
               be ignored.
  nframes - Number of frames to average.
  bias    - Bias frame image name to subtract from each raw flat.
  dark    - Dark frame image name to subtract from each raw flat.

 OPTIONAL INPUT PARAMETERS:

 KEYWORD INPUT PARAMETERS:

   CROP     = region of original image to save, default=no cropping.
                 [x1,x2,y1,y2]

   DDIR    - Path to the raw data, default = ''

   DIGITS   - Optional input to indicate how many digits are in the suffix
                of the file name.  The default for this input is 0.  In this
                case it uses the ROBOCCD scheme which is three digits up
                to 999.  After that, it gets complicated, see numtoflist
                for more information.  If you were to give it a value of
                three you would get the same behavior except you won't get
                the ROBOCDD extension.  This is really designed for when
                you have four or more digits.

   DISPLAY  - Flag, if set, generates some diagnostic plots

   EXCLUDE - Optional vector of image numbers that should be excluded from
                average.  Default is to include all frames.

   EXPKEY = String, FITS keyword to read to get exposure time, default=EXPTIME

   JUSTMEDIAN - Flag, if set will stop processing after the initial median
                  combination of the image cube and this will be the final
                  answer.  This should used only if the intrinsic noise
                  level of the result can never drop below 1 DN.  Particularly
                  useful for a small number of flat images.

   OVERSCAN = column overscan region to use for frame bias level,
                 default=no overscan subtraction.

   RDNOISE  - Read noise of CCD, [DN], default=10

   SAVECHK - String with name of directory to save graphics to.  The images
               saved are the final flat, the original image, and the
               flattened flat images.  They are heavily binned if large
               and are useful for figuring out if the input flats are good
               or not.  The default is '[[none]]' which means to not save
               any of the graphics.  Using this option causes the program to
               use the current graphics device to open and use window 7.

   SCALE - 4 element vector which, if provide, defines the region of the
           array dimensions that are used to scale the mean
           of the arrays before combining (.  If combined in this
           manner, the arrays are combined weighted by the means.
                 [x1,x2,y1,y2]
           These coordinates apply to the pixel locations AFTER cropping.
           The default is to use the center 50% of the image but not any
           bigger than 200x200 subsection at the center.

   MINGOOD - Minimum number of frames required to be considered a good
                bias.  (Default=15)

   MAXSIG  - Maximum sigma threshold for filtering bad frames.
                Default is inherited from gradebias
                default=3

 OUTPUTS:
  flat - Final robust averaged and normalized flat image.
  good - Flag, 1 if flat is considered good, 0 if not.

 KEYWORD OUTPUT PARAMETERS:
  NGOOD - Number of frames considered to be good at the end of operation.
            Note that this will usually be >0 even if the set is marked
            bad since all process stops once the number drops below MINGOOD.
          If NOGRADE is set the value returned is -1
  IDXGOOD - Indicies into the list of files for those that were considered
              to be good
  GAININFO - structure that provides some information derived from the
               good frames in the set of flats.
                gain:     e-/ADU gain from a linear fit
                gainsig:  uncertainty on the gain
                gstdev:   rms of residals [ADU]
                gain2:    e-/ADU gain from a quadratic fit
                gain2sig: uncertainty on gain2
                g2stdev:  rms of residuals from quadratic fit [ADU]
                mindn:    signal level of faintest good image [ADU]
                maxdn:    signal level of brightest good image [ADU]
                  
 COMMON BLOCKS:
 SIDE EFFECTS:
 RESTRICTIONS:
 PROCEDURE:

 MODIFICATION HISTORY:
  95/03/10 - Initial crude version written, Marc W. Buie, Lowell Observatory
  95/06/04, MWB, added EXCLUDE keyword
  95/06/13, MWB, added SCALE, OVERSCAN, CROP keywords
  99/06/10, MWB, added EXPTIME keyword and added documentation.
  2000/02/03, MWB, rewrite to add support for multigroup FITS files.
  2000/02/28, MWB, added support for frame numbers > 999.
  2001/02/23, MWB, added option to provide input file list.
  2001/04/28, MWB, added DDIR keyword
  2004/05/05, MWB, fixed SCALE keyword default action.  It was not working
                     right at all and the region selected was much too large.
  2006/07/14, MWB, added RDNOISE keyword
  2006/07/27, MWB, added JUSTMEDIAN keyword
  2006/10/23, MWB, fixed output header keyword problem (remove BSCALE/BZERO)
  2013/10/05, MWB, added SAVECHK keyword
  2015/04/26, MWB, added use of gradeflat
  2016/05/29, MWB, added DIGITS keyword
  2017/11/09, MWB, added showcall
  2018/12/17, MWB, capture failure of running avgclip
  2018/12/20, MWB, added NGOOD output keyword
  2019/05/15, MWB, added IDXGOOD output keyword
  2019/06/03, MWB, added GAININFO output keyword
  2019/12/02, MWB, added a check to make sure there are at least mingood
                      frames at the start, otherwise, return right away
                      and mark it all as bad.
  2019/12/03, MWB, added a trap for a special failure case
  2019/12/13, MWB, added DISPLAY keyword