Документ взят из кэша поисковой машины. Адрес оригинального документа : http://www.stsci.edu/~mperrin/software/idl_sources.shtml
Дата изменения: Unknown
Дата индексирования: Sun Apr 10 16:05:49 2016
Кодировка:

Поисковые слова: vallis
Marshall Perrin's IDL Routines By Category

Marshall Perrin's IDL Routines

Back to my main IDL page

List Last updated: Mon Sep 17 17:04:02 2012.


Routines by Category

Categories: Astronomical Utility - Data Cubes - Database - I/O - Image Display - Image Processing - IRCAL Pipeline - Mathematics - Misc - Plotting - Programming

Astronomical Utility

Data Cubes

Database

I/O

Image Display

Image Processing

IRCAL Pipeline

Mathematics

Misc

Plotting

Programming


Routine Descriptions


Category: Astronomical Utility

[List of Routines]


ZD2AIRMASS

[Next Routine] [List of Routines]
(See sources/zd2airmass.pro)

 NAME: airmass

 PURPOSE:
 	Compute airmass vs. zenith distance.

 ALGORITHM:
 	Formula from John Huchra'a Harvard Ay192 notes, 1999.

 INPUTS:
 	zd	zenith distance, in degrees
 KEYWORDS:
 OUTPUTS:

 HISTORY:
 	Began 2004-10-18 19:36:56 by Marshall Perrin 

(See sources/zd2airmass.pro)


LSTNOW

[Previous Routine] [Next Routine] [List of Routines]
(See sources/lstnow.pro)

 NAME: lstnow

 PURPOSE:
 	return current lst, for a given observatory

 INPUTS:
 KEYWORDS:
 OUTPUTS:

 HISTORY:
 	Began 2005-07-14 17:30:20 by Marshall Perrin 

(See sources/lstnow.pro)


SUNTIMES

[Previous Routine] [Next Routine] [List of Routines]
(See sources/suntimes.pro)

 NAME: suntimes

 PURPOSE:
 	compute APPROXIMATE sunrise and sunset times

 NOTES:
 	Uses algorithms from the
 	Buie Lowell IDL library.

 	This is not likely to be the most accurate thing in the world.

 	Particularly since it doesn't account for the motion of the sun
 	during the day in question.


 USAGE:
 	suntimes,jd,rise,set, [/today, /lst, obsname="lick", degrees=12]

 INPUTS:
 KEYWORDS:
		degrees=	how many degrees below the horizon? 
					Default is 0.25, so the sun is just tangent to the horizon
 		/lst		return results in LST, not CT
 
 OUTPUTS:

 HISTORY:
 	Began 2005-07-14 16:07:24 by Marshall Perrin 
 		see 'obsplan.pro' from the Buie library for algorithm source.

(See sources/suntimes.pro)


LASERTIMES

[Previous Routine] [Next Routine] [List of Routines]
(See sources/lasertimes.pro)

 NAME: lasertimes

 PURPOSE:
 	Compute the start and stop allowable times for the Lick Laser, in LST.
 	These correspond to 11 pm and 5 am, local time (either PST or PDT)

 USAGE:
 	suntimes,jd,rise,set, [/date, /lst]

 INPUTS:
 KEYWORDS:
 OUTPUTS:

 BUGS:
 		Not daylight savings time aware. It assumes that the entire year
 		uses whatever the current timezone setting is. (i.e. if it's
 		PDT when you run the program, it assumes it's -always- PDT, and
 		vice versa for PST)

 HISTORY:
 	Began 2005-07-14 16:07:24 by Marshall Perrin 
 		see 'obsplan.pro' from the Buie library for algorithm source.

(See sources/lasertimes.pro)


FINDINGCHART

[Previous Routine] [Next Routine] [List of Routines]
(See sources/findingchart.pro)

 NAME: findingchart.pro
 PURPOSE:
 	make a finding chart for an object on screen or PDF. 

 NOTES:
 	For Lick, you want to call this as
 		
		findingchart,"Vega", /ps

	This script requires the "skvbatch" and "webquery" perl scripts to 
	access SkyView at Goddard. Get them from here:
		http://skyview.gsfc.nasa.gov/downloads/software/batch/skvbatch
	It also requires a version of the Goddard IDL Astronomy library more
	recent than 2003-07-14, incorporating bug fixes to hrotate.pro and
	imcontour.pro which were added then.

 INPUTS:
 	objectname	a name or coordinates for an object suitable for SIMBAD.
 	
 KEYWORDS:
 	filename	File to use. If set, This file is used and labelled as
      		 	"objectname". If not set, the field containing 
     			objectname is downloaded from SkyView at Goddard. Once 
      			the data is downloaded, it is saved in the current 
 	         	directory for future use.
 	/noflip		don't flip the direction of the RA axis. Default is to 
 				flip it so as to match the geometry of the Lick display.
 	rotangle	Angle to rotate the image by, clockwise. If /flip is 
 	    		set, that happens first. Default is 23 degrees, which 
 	    		is the angle for the Lick guider camera.
 	/ps  		Output to a postscript file as well as to the screen.
        	 	The file will be named find_.ps
 	/forcedl	Force the download of data even if it wouldn't happen otherwise.
 				i.e. You can use this to re-download the image for a source
 				even if it's been saved already.
 OUTPUTS:

 HISTORY:
 	Began 2003-07-04 13:01:34 by Marshall Perrin 
 	Documentation added 2003-07-11   Marshall Perrin
 	2003-07-20		Added guider FOV outline. Marshall Perrin
 	2003-11-02		Lick finding camera is now rotated 180 degrees from where
					it used to be in July...

(See sources/findingchart.pro)


MULTIFINDINGCHART

[Previous Routine] [Next Routine] [List of Routines]
(See sources/multifindingchart.pro)

 NAME: multifindingchart
 PURPOSE:
 	call findingchart for a bunch of sources listed in a file.

 INPUTS:
 KEYWORDS:
 	/coords		use coords from the target file, not just names.
 				Useful for targets not in SIMBAD
 	wait=#		wait # seconds between images
 	/ps			write to PS
 OUTPUTS:

 HISTORY:
 	Began 2005-07-14 18:16:08 by Marshall Perrin 
 	2005-09-29	added /wait, and /ps

(See sources/multifindingchart.pro)


MAG_ERRPROP

[Previous Routine] [List of Routines]
(See sources/mag_errprop.pro)

 NAME: mag_errprop

 PURPOSE:
 		Convert fluxes to magnitudes, with error propagation.

 INPUTS:
 	f1,f2		fluxes
 	err1,err2	uncertainties in fluxes
 KEYWORDS:
 	/silent		don't print
 OUTPUTS:
 	mags=		returns magnitudes
 	errmags=	returns errors in magnitudes

 HISTORY:

(See sources/mag_errprop.pro)


Category: Data Cubes

[List of Routines]


CUBE_COLLAPSE

[Next Routine] [List of Routines]
(See sources/cube_collapse.pro)

 NAME: cube_collapse 
 PURPOSE:
	Collapse a cube along the wavelength axis.

	The default is to average the cube, but there are options to median or
	total combine instead. 

	There is some support for using quality flags to indicate bad pixels to skip
	when collapsing. 

 INPUTS:
 	cubestruct		a cubestruct
 KEYWORDS:
 	zrange=			which Z axis range to include? Default is all. 
 	cropmult=		crop the collapsed image to multiples of this many pixels
 					(for consistency with what cube_rebin does for odd axis
 					sizes)
 	/median			median collapse it
 	/total			total it, instead of averaging or medianing.
 	/silent			suppress printed output
 OUTPUTS:
 	a modified cubestruct (really an image structure) which contains the
 	collpased image, header, and astrometry

 HISTORY:
 	Began 2007-07-16 17:40:19 by Marshall Perrin 
 	2008-02-06	Some support for zrange and quality flags added

(See sources/cube_collapse.pro)


CUBE_GETWAVEAXIS

[Previous Routine] [Next Routine] [List of Routines]
(See sources/cube_getwaveaxis.pro)

 NAME: cube_getwaveaxis 
 PURPOSE: return which axis of a cube is the wavelength dimension
 INPUTS:
 KEYWORDS:
 OUTPUTS:
 			The index for the axis of the cube that is wavelength. 

 			NOTE: this is ZERO-INDEXED. So the first axis is 0 and the second is
 			1, etc.

 HISTORY:
 	Began 2007-07-16 17:41:43 by Marshall Perrin 

(See sources/cube_getwaveaxis.pro)


CUBE_READ

[Previous Routine] [Next Routine] [List of Routines]
(See sources/cube_read.pro)

 NAME: cube_read
 PURPOSE:
 	Read in a data cube into a standardized structure

 INPUTS:
 KEYWORDS:
 	/force_osiris	tell it the input cube is an OSIRIS one. For missing header
 	problem.
 OUTPUTS:

 HISTORY:
 	Began 2007-07-16 18:34:14 by Marshall Perrin 

(See sources/cube_read.pro)


CUBE_REBIN

[Previous Routine] [Next Routine] [List of Routines]
(See sources/cube_rebin.pro)

 NAME: cube_rebin 
 PURPOSE:
 	Rebin a cube in the X and Y dimensions, while leaving the Z dimension
 	unchanged.

 INPUTS:
 KEYWORDS:
 OUTPUTS:

 HISTORY:
 	Began 2007-07-16 17:40:19 by Marshall Perrin 

(See sources/cube_rebin.pro)


CUBE_SUBTRACTCONTINUUM

[Previous Routine] [Next Routine] [List of Routines]
(See sources/cube_subtractcontinuum.pro)

 NAME:  cube_subtractcontinuum
 PURPOSE:
 		Crude continuum subtraction for IFS datacubes

 		Almost any algorithm will be better than this!

 INPUTS:
 KEYWORDS:

 	/mean		use a crude moving average to compute the continuum
 	/median		use a moving median to compute the continuum
 OUTPUTS:

 HISTORY:
 	Began 2007-07-13 17:19:22 by Marshall Perrin 
 	2008-07		Bug fixes by M. Perrin and B. Sitarski

(See sources/cube_subtractcontinuum.pro)


CUBEDISP_GRIDSPEC

[Previous Routine] [Next Routine] [List of Routines]
(See sources/cubedisp_gridspec.pro)

 NAME:  cubedisp_gridspec
 PURPOSE:

 		Overplot a grid of spectra on top of a greyscale image of a cube
 		
 		This was inspired by a figure in (I think) one of Tracey Beck's papers.

 EXAMPLE:
 	cubedisp_gridspec,subc,color=fsc_color('red'),plotrange=[-1e-19,1e-17],waverange=[6700,6750],rebin=3



 INPUTS:
 	cubestruct	a standard datacube+header structure
 KEYWORDS:
 	rebin=		how many pixels to use for each overplotted spectrum?
 	zrange=		Z axis range to use, in pixels
 	waverange=	Z axis range to use, in Wavelength
 	plotrange=	display yrange for overplotted spectra
 	/stop		convenient breakpoints
 	/nogrid		don't draw the grid
 	/nospec		no spectra at all, just draw the greyscale.
 OUTPUTS:

 HISTORY:
 	Began 2007-07-16 17:35:02 by Marshall Perrin 

(See sources/cubedisp_gridspec.pro)


EXTAST3

[Previous Routine] [Next Routine] [List of Routines]
(See sources/extast3.pro)

 NAME:
     EXTAST3

		EXTAST from the Goddard IDL Astro library, but modified to 
		allow WCSAXES >2 for datacubes by M. Perrin
     
 PURPOSE:
     Extract ASTrometry parameters from a FITS image header. (3D version for
     datacubes)
 EXPLANATION:
     Extract World Coordinate System information 
     ( http://fits.gsfc.nasa.gov/fits_wcs.html ) from a FITS header and 
     place it into an IDL structure.

 CALLING SEQUENCE:
     EXTAST, hdr, [ astr, noparams, ALT= ]   

 INPUT:
     HDR - variable containing the FITS header (string array)


 OUTPUTS:
     ASTR - Anonymous structure containing astrometry info from the FITS 
             header ASTR always contains the following tags (even though 
             some projections do not require all the parameters)
			 'N' is the number of WCS axes, which may be arbitrarily large..
             
       .NAXIS - N element array giving image size
      .CD   -  N x N array containing the astrometry parameters CD1_1 CD1_2 etc
               in DEGREES/PIXEL                                 CD2_1 CD2_2 ...
               												 etc   ...   ...
      .CDELT - N element double vector giving physical increment at the 
                 reference pixel
      .CRPIX - N element double vector giving X and Y coordinates of reference 
               pixel (def = NAXIS/2) in FITS convention (first pixel is 1,1)
      .CRVAL - N element double precision vector giving R.A. and DEC of 
             reference pixel in DEGREES
      .CTYPE - N element string vector giving projection types, default
             ['RA---TAN','DEC--TAN']
      .CUNIT - N element string array giving units of each axis.
      .LONGPOLE - scalar giving native longitude of the celestial pole 
             (default = 180 for zenithal projections) 
      .LATPOLE - scalar giving native latitude of the celestial pole default=0)
      .PV2 - Vector of projection parameter associated with latitude axis
             PV2 will have up to 21 elements for the ZPN projection, up to 3 
             for the SIN projection and no more than 2 for any other 
             projection  
      .DISTORT - optional substructure specifying any distortion parameters
                 currently implemented only for "SIP" (Spitzer Imaging 
                 Polynomial) distortion parameters

       NOPARAMS -  Scalar indicating the results of EXTAST
             -1 = Failure - Header missing astrometry parameters
             1 = Success - Header contains CROTA + CDELT (AIPS-type) astrometry
             2 = Success - Header contains CDn_m astrometry, rec.    
             3 = Success - Header contains PCn_m + CDELT astrometry. 
             4 = Success - Header contains ST  Guide Star Survey astrometry
                           (see gsssextast.pro )
 OPTIONAL INPUT KEYWORDS:
    ALT=      single character 'A' through 'Z' or ' ' specifying an alternate 
              astrometry system present in the FITS header.    The default is
              to use the primary astrometry or ALT = ' '.   If /ALT is set, 
              then this is equivalent to ALT = 'A'.   See Section 3.3 of 
              Greisen & Calabretta (2002, A&A, 395, 1061) for information about
              alternate astrometry keywords.
   /SILENT	   Don't print anything, even error messages
 PROCEDURE:
       EXTAST checks for astrometry parameters in the following order:

       (1) the CD matrix PC1_1,PC1_2...plus CDELT*, CRPIX and CRVAL
       (3) the CD matrix CD1_1,CD1_2... plus CRPIX and CRVAL.   
       (3) CROTA2 (or CROTA1) and CDELT plus CRPIX and CRVAL.

       All three forms are valid FITS according to the paper "Representations 
       of World Coordinates in FITS by Greisen and Calabretta (2002, A&A, 395,
       1061 http://www.aoc.nrao.edu/~egreisen) although form (1) is preferred/

 NOTES:
       An anonymous structure is created to avoid structure definition
       conflicts.    This is needed because some projection systems
       require additional dimensions (i.e. spherical cube
       projections require a specification of the cube face).

 PROCEDURES CALLED:
      GSSSEXTAST, ZPARCHECK
 REVISION HISTORY
 	   Split from EXTAST.PRO by Marshall Perrin in July 2007 - 
 	     see EXTAST.PRO for history earlier than that.	
      Modified to check for WCSAXES/NAXES > 2 and read parameters 
      		accordingly for all dimensions. M. Perrin, July 2007

(See sources/extast3.pro)


PUTAST3

[Previous Routine] [Next Routine] [List of Routines]
(See sources/putast3.pro)

 NAME:
    PUTAST3
    	Like PUTAST from the Goddard Library, but for datacubes
    	
 PURPOSE:
    Put WCS astrometry parameters into a given FITS header. (3D version for
    datacubes)

 CALLING SEQUENCE:
     putast, hdr              ;Prompt for all values
               or
     putast, hdr, astr, [EQUINOX =, CD_TYPE =, ALT= , NAXIS=]
               or
     putast, hdr, cd,[ crpix, crval, ctype], [ EQUINOX =, CD_TYPE =, ALT= ]    

 INPUTS:
     HDR -  FITS header, string array.   HDR will be updated to contain
             the supplied astrometry.
     ASTR - IDL structure containing values of the astrometry parameters
            CDELT, CRPIX, CRVAL, CTYPE, LONGPOLE, and PV2
            See EXTAST.PRO for more info about the structure definition
                            or
     CD   - 2 x 2 array containing the astrometry parameters CD1_1 CD1_2
                                                             CD2_1 CD2_2
              in units of DEGREES/PIXEL
     CRPIX - 2 element vector giving X and Y coord of reference pixel
              BE SURE THE COORDINATES IN CRPIX ARE GIVEN IN FITS STANDARD
              (e.g. first pixel in image is [1,1] ) AND NOT IDL STANDARD
              (first pixel in image is [0,0]
     CRVAL - 2 element vector giving R.A. and DEC of reference pixel 
               in degrees
     CTYPE - 2 element string vector giving projection types for the two axes.
             For example, to specify a tangent projection one should set
             ctype = ['RA---TAN','DEC--TAN'] 

 OUTPUTS:
      HDR - FITS header now contains the updated astrometry parameters
               A brief HISTORY record is also added.

 OPTIONAL KEYWORD INPUTS:
       ALT -  single character 'A' through 'Z' or ' ' specifying an alternate 
              astrometry system to write in the FITS header.    The default is
              to write primary astrometry or ALT = ' '.   If /ALT is set, 
              then this is equivalent to ALT = 'A'.   See Section 3.3 of 
              Greisen & Calabretta (2002, A&A, 395, 1061) for information about
              alternate astrometry keywords.


       CD_TYPE - Integer scalar, either 0, 1 or 2 specifying how the CD matrix
                is to be written into the header
               (0) write PCn_m values along with CDELT values
               (1) convert to rotation and write as a CROTA2 value (+ CDELT)
               (2) as CDn_m values (IRAF standard) 

            All three forms are valid representations according to Greisen &
            Calabretta (2002, A&A, 395, 1061), also available at 
            http://www.aoc.nrao.edu/~egreisen/) although form (0) is preferred.
            Form (1) is the former AIPS standard and is now  deprecated and
            cannot be used if any skew is present.
            If CD_TYPE is not supplied, PUTAST will try to determine the 
            type of astrometry already in the header.   If there is no 
            astrometry in the header then the default is CD_TYPE = 2.

      EQUINOX - numeric scalar giving the year of equinox  of the reference 
                coordinates.   Default (if EQUINOX keyword is not already
                present in header) is 2000.

      NAXIS - By default, PUTAST does not update the NAXIS keywords in the
            FITS header.    If NAXIS is set, and an astrometry structure is
            supplied then the NAXIS1 and NAXIS2 keywords in the FITS header 
            will be updated with the .NAXIS structure tags values.     If an 
            astrometry structure is not supplied, then one can set NAXIS to a 
            two element vector to update the NAXIS1, NAXIS2 keywords. 
 NOTES:
       The recommended use of this procedure is to supply an astrometry
       structure.     The PC matrix form (CD_TYPE = 0) can only be used 
       if an asrometry structure is supplied.   

       PUTAST does not delete astrometry parameters already present in the 
       header, unless they are explicity overwritten.    
 PROMPTS:
       If only a header is supplied, the user will be prompted for a plate 
       scale, the X and Y coordinates of a reference pixel, the RA and
       DEC of the reference pixel, the equinox of the RA and Dec and a 
       rotation angle.

 PROCEDURES USED:
       GETOPT(), GET_COORDS, GET_EQUINOX, SXADDPAR, SXPAR(), TAG_EXIST(), 
       ZPARCHECK
 REVISION HISTORY:
 		July 2007		Made from a modified version of Goddard's PUTAST.PRO by
 						Marshall Perrin. See PUTAST.PRO for history earlier than
 						this.

(See sources/putast3.pro)


XYZ2ADL

[Previous Routine] [List of Routines]
(See sources/xyz2adl.pro)

 NAME:
     XYZ2ADL

     Like XY2AD, but for IFU data cubes containing 2 spatial and 1 spectral
     dimension.

 PURPOSE:
     Compute R.A., Dec, and Wavelength from X, Y, and Z and a FITS astrometry structure
 EXPLANATION:
     The astrometry structure must first be extracted by EXTAST from a FITS
     header.   The offset from the reference pixel is computed and the CD 
     matrix is applied.     If distortion is present then this is corrected.
     If a WCS projection (Calabretta & Greisen 2002, A&A, 395, 1077) is 
     present, then the procedure WCSXY2SPH is used to compute astronomical
     coordinates.    Angles are returned in  degrees.
   

 CALLING SEQUENCE:
     XYZ2ADL, x, y, z, astr, a, d, lambda

 INPUTS:
     X     - row position in pixels, scalar or vector
     Y     - column position in pixels, scalar or vector
     Z     - slice position in pixels, scalar or vector
           X,Y,Z should be in the standard IDL convention (first pixel is
           0), and not the FITS convention (first pixel is 1). 
     ASTR - astrometry structure, output from EXTAST3 procedure containing:
        .CD   -  3 x 3 array containing the astrometry parameters 
               in DEGREES/PIXEL                                   
        .CDELT - 3 element vector giving physical increment at reference pixel
        .CRPIX - 3 element vector giving X and Y coordinates of reference pixel
               (def = NAXIS/2)
        .CRVAL - 3 element vector giving R.A. and DEC of reference pixel 
               in DEGREES
        .CTYPE - 3 element vector giving projection types 
        .LONGPOLE - scalar longitude of north pole
        .LATPOLE - scalar giving native latitude of the celestial pole
        .PV2 - Vector of projection parameter associated with latitude axis
             PV2 will have up to 21 elements for the ZPN projection, up to 3
             for the SIN projection and no more than 2 for any other
             projection
        .DISTORT - Optional substructure specifying distortion parameters
                  

 OUTPUT:
     A - R.A. in DEGREES, same number of elements as X and Y
     D - Dec. in DEGREES, same number of elements as X and Y
     Lambda - wavelength in whatever units CUNITx is

 OPTIONAL KEYWORD OUTPUT:
     waveunits=	String giving units for wavelength axis, from header CUNIT
     				keyword.

 RESTRICTIONS:
       Note that all angles are in degrees, including CD and CRVAL
       Also note that the CRPIX keyword assumes an FORTRAN type
       array beginning at (1,1), while X and Y give the IDL position
       beginning at (0,0).   No parameter checking is performed.

 NOTES:
	   This routine automatically determines which axis is wavelength and
	   which axes are RA and Dec. 

	   The Wavelength axis MUST be linear; no other axes types are supported.
	   The RA and Dec axes can be anything that will work in regular XY2AD.
	   
      
 PROCEDURES USED:
       TAG_EXIST(), WCSXY2SPH
 REVISION HISTORY:
 	Written by M. Perrin, UC Berkeley, based on XY2AD.PRO as of July 2, 2007.
       

(See sources/xyz2adl.pro)


Category: Database

[List of Routines]


IS_MYSQL_PRESENT

[Next Routine] [List of Routines]
(See sources/is_mysql_present.pro)

 NAME: is_mysql_present
 PURPOSE:
 	Is there a mysql database here? 
 	This routine lets you run the code either with or without mysql,
 	depending on the local machine functionality.
 NOTES:

 	Uncomment whichever of the two answers is appropriate for your setup!
 		
	TODO: make this autodetect mysql somehow (tricky to make all cases work...)

 INPUTS:
 KEYWORDS:
 OUTPUTS:

 HISTORY:
 	Began 2006-07-08 17:55:58 by Marshall Perrin 

(See sources/is_mysql_present.pro)


MYSQLCHECK

[Previous Routine] [Next Routine] [List of Routines]
(See sources/mysqlcheck.pro)

 NAME: mysqlcheck
 PURPOSE:
 	check that a connection to mysql is open; 
 	open one if it isn't

 INPUTS:
 KEYWORDS:
 	database	database name to open (default is "Astronomy")
 OUTPUTS:

 HISTORY:
 	Began 2005-10-05 18:47:04 by Marshall Perrin 

(See sources/mysqlcheck.pro)


MYSQLQUERY2

[Previous Routine] [Next Routine] [List of Routines]
(See sources/mysqlquery2.pro)

 NAME:
   mysqlquery2
   				a version of mysqlquery modified by M. Perrin to have
   				an improved output format
 PURPOSE:
   Submit MySQL query and get response as an array of structures.
 DESCRIPTION:
   Submit a simple SQL query to MySQL server, using the connection
   previously opened with openmysql.  Retrieve the result into
   a STRUCTURE ARRAY, as does QUERYVIZIER.PRO
 CATEGORY:
   Database

 CALLING SEQUENCE:
   mysqlquery,lun,query,[varables...],[format='(a,f,...)']

 INPUTS:
    lun    - The logical unit of the pipe (opened by openmysql).
    query  - String (or array of strings) to send to pipe.

 OPTIONAL INPUT PARAMETERS:
 KEYWORD INPUT PARAMETERS:
    format  - Specify format of output variables (default is ascii).
    cmd     - Flag indicating this is a command, not a query so
                don't bother processing the output (but do report the
                number of rows affected/warnings? - not implimented).
    verbose - Flag turns on debugging output to standard out.

 OUTPUTS:
    variables - A list of variables to recieve columns of output.
                   Default type is ascii, but use the format keyword to
                   specify other data types.

 KEYWORD OUTPUT PARAMETERS:
    heads   - String to receive array of column heads.

 COMMON BLOCKS:
 SIDE EFFECTS:
 RESTRICTIONS:
   Requires an open connection to MySQL server (established by
   use of openmysql) as well as valid permissions for whatever
   query or command is to be executed.

 PROCEDURE:
 MODIFICATION HISTORY:
   2002-02-14 Will Grundy, adapted from earlier version called mysql.pro
   2002-02-27 WG changed behavior so 'NULL' becomes NaN instead of
                  making the line be ignored when it occurs in a numerical
                  field.
   2002-03-25 WG changed to split on tab instead of white space, so that
       strings with internal spaces (but not tabs) can be retrieved.
   2003/01/10, MWB, fixed multi-line query error.  Only one query per
                       call is allowed.
   2005-10-11, M. Perrin 	Fixed NaN replacement for NULLs
   2006-05-14, M. Perrin 	Fixed handling of null strings in query results
   2007-06-01, M. Perrin	Modified output format to be a structure array.

 BUGS/WISH LIST:
   Ought to verify connection to MySQL server.
   Does nothing helpful with SQL command results.
   Does nothing helpful to identify/report bad SQL syntax.

(See sources/mysqlquery2.pro)


QUERY_2MASS

[Previous Routine] [Next Routine] [List of Routines]
(See sources/query_2mass.pro)

 NAME: query_2mass 
PURPOSE:
 	Given a name, query the 2MASS catalog on Vizier for its
 	J, H, and Ks magnitudes (and their errors).
 NOTES:
 	Requires the 'queryvizier' procedure from Goddard IDLAstro, and others.

 USAGE:
   query_2mass,name,J,H,Ks,Jerr,Herr,Kserr,radius=radius,stop=stop,auto=auto

 INPUTS:
 	name	Simbad-resolvable object name or coordinates
 KEYWORDS:
 	id=		2MASS object ID (used instead of name)
 	radius=	Radius around that object to search; same as on the
 			Vizier query page. In units of arcseconds.
 	/stop	Stop at a breakpoint after doing the query
 	/auto	Return after an error. By default, it stops after an error.
 OUTPUTS:
 	J,H,Ks				Magnitudes, from 2MASS, for the object with 
 						the closest location to the requested name.
 	Jerr,Herr,Kserr		Errors in Magnitudes
 	results=			keyword to return the full 2mass results structure

 HISTORY:
 	Began 2005-10-07 04:00:19 by Marshall Perrin 
 		Based on Keck's 'findttref.pro'

(See sources/query_2mass.pro)


QUERY_IRAS

[Previous Routine] [Next Routine] [List of Routines]
(See sources/query_iras.pro)

 NAME: query_iras
 PURPOSE:
 	Given a name, query the IRAS catalog on Vizier for its
 	J, H, and Ks magnitudes (and their errors).
 NOTES:
 	Requires the 'queryvizier' procedure from Goddard IDLAstro, and others.

 USAGE:
   query_2mass,name,J,H,Ks,Jerr,Herr,Kserr,radius=radius,stop=stop,auto=auto

 INPUTS:
 	name	Simbad-resolvable object name or coordinates
 KEYWORDS:
 	radius=	Radius around that object to search; same as on the
 			Vizier query page. In units of arcseconds.
 	/stop	Stop at a breakpoint after doing the query
 	/auto	Return after an error. By default, it stops after an error.
 OUTPUTS:
 	J,H,Ks				Magnitudes, from 2MASS, for the object with 
 						the closest location to the requested name.
 	Jerr,Herr,Kserr		Errors in Magnitudes

 HISTORY:
 	Began 2005-10-07 04:00:19 by Marshall Perrin 
 		Based on Keck's 'findttref.pro'
 		2006-06-26	Added checks for flux## instead of fnu_## because
 			sometimes (for no apparent reason) that's what gets returned.
 			And for "IRAS" versus "NAME" for the IRAS ID.

(See sources/query_iras.pro)


QUERY_USNOB

[Previous Routine] [List of Routines]
(See sources/query_usnob.pro)

 NAME: query_usnob 
NOTES:
 	Requires the 'queryvizier' procedure from Goddard IDLAstro, and others.

 USAGE:
   query_usnob,name,Bmag,Rmag,Imag,radius=radius,stop=stop,auto=auto


 INPUTS:
 	name	Simbad-resolvable object name or coordinates
 KEYWORDS:
 	id=		2MASS object ID (used instead of name)
 	radius=	Radius around that object to search; same as on the
 			Vizier query page. In units of arcseconds.
 	/stop	Stop at a breakpoint after doing the query
 	/auto	Return after an error. By default, it stops after an error.
 OUTPUTS:

 HISTORY:
 	Began 2005-10-07 11:31:32 by Marshall Perrin 
 			based on Keck's findttref.pro

(See sources/query_usnob.pro)


Category: I/O

[List of Routines]


APRINT

[Next Routine] [List of Routines]
(See sources/aprint.pro)

 NAME: aprint

 PURPOSE:
 	print something out formatted as an IDL array (i.e. in IDL source code syntax)
 NOTES:

 	This is useful if you want to take some variable and embed
 	it as a constant into an IDL routine.

 	CAUTION: Does not work properly on multidimensional arrays yet.

 INPUTS:
 KEYWORDS:
 OUTPUTS:

 HISTORY:
 	Began 2005-07-22 10:12:01 by Marshall Perrin 

(See sources/aprint.pro)


TEXPRINT

[Previous Routine] [Next Routine] [List of Routines]
(See sources/texprint.pro)

 NAME: texprint
 PURPOSE:

 print out an IDL array in LaTeX table syntax, suitable for pasting
 into your paper. 


 INPUTS:
 		table	some 2d array
 KEYWORDS:
 		labels	string array of labels. Goes into the first row
 		/labelrows	use labels for rows (default is columns
 		/longtable	use longtable instead of deluxetable
 OUTPUTS:

 HISTORY:
 	Began 2006-04-14 14:51:09 by Marshall Perrin 

(See sources/texprint.pro)


READTEXT

[Previous Routine] [Next Routine] [List of Routines]
(See sources/readtext.pro)

 NAME:  readtext
 
 PURPOSE:
 	read in a text file in its entirety into an array

 NOTES: 
 	lines should be < 300 chars long.

 INPUTS:
 KEYWORDS:
 OUTPUTS:

 HISTORY:
 	Began 2007-04-15 01:28:20 by Marshall Perrin 

(See sources/readtext.pro)


FITSLOADER

[Previous Routine] [Next Routine] [List of Routines]
(See sources/fitsloader.pro)

 fitsloader,range,out,hdrout,instrument=instrument,$
	fdir=fdir,caldir=caldir,currdir=currdir,silent=silent,$
	numlist=numlist,imlist=imlist, $
	dobias=dobias,doflat=doflat,domask=domask,scaletime=scaletime,calib=calib,$
	firstheader=firstheader,$
	badpixmask=badpixmask


 NAME: fitsloader
 PURPOSE: 
 	Loads a specified set of FITS files, locates appropriate bias and
 	flat field files for them, applies these to calibrate them, and
 	optionally scales the whole set to a fixed exposure time.

 NOTES:

 	This is meant to be a robust and flexible FITS loading routine
 	for the IRCAL reduction pipeline, capable of taking heterogenous
 	sets of exposures and coadds and doing the right thing with them.

 	You can specify the files to load via either range (now) or via
 	numlist or filelist parameters (still to be implemented)

 INPUTS:
 		range	Range is a flexible list of filenumbers. It should be a
 				intarr(2,n) list of integers or the equivalent. 
 				range[0,*] are taken as the starts of the various sets of
 				files to load, and range[1,*] are the ends. Rudimentary 
 				error checking is performed on range. It is internally
 				expanded into a 1D array of the same form as numlist and
 				handled via the same code.
 KEYWORDS:
 		numlist		a list of integer file numbers to open
 		imlist		a list of file names ot open. If present when called,
 					this is an input. Otherwise it's an output.
 		instrument	name of the instrument. Affects how file names
 					are generated and coadds found.
 		dobias		do bias subtraction
 		doflat		do flat fielding
 		domask		mask out bad pixels
 		scaletime	scale all exposures to this exposure time
 		calib		same as /dobias,/doflat,/scaletime
 		firsthdr	only output fits header for first file.
 		flatfilename	override the auto-flat-finding code and use this
 						specific flatfield
 		saturation	value above which pixels are considerd saturated
 		/headersonly	don't load data; just load headers
 OUTPUTS:
 		out			3d image array
 		hdroud		2d header array
 		badpixmask	optional bad pixel mask for the images. (1=good,0=bad)
 		error_images [optional] uncertainty images for each of the arrays in out
 					These are read from the first extension of each FITS file.
 		mask_images	[optional] mask images for each of the arrays in our.
 					These are read from the second extension of each FITS file.

 HISTORY:
 	Began 2002-11-18 17:23:11 by Marshall Perrin 
 	Modified to automatically find either .fits or .fits.gz files.
 		2003-10-29 MP
  ...
  2006-03-23   Added error_images option. (for OSIRIS data)
  2006-11-24	added separator character (sep_char) option for Windows. 
  			    (MDP, courtesy of C Hansen)

(See sources/fitsloader.pro)


HDRCONCAT

[Previous Routine] [Next Routine] [List of Routines]
(See sources/hdrconcat.pro)

 NAME: hdrconcat
 PURPOSE:
 	Concatenates FITS headers into a 2D string array, doing intelligent
 	things with axes sizes if needed.

 NOTES:
 	The format for multidimensional FITS headers is that axis 0 is
 	the various keywords in a header, and axis 1 lets you select
 	which header you want.

 	It's *nice* if all the keywords line up between headers, but by
 	no means required and this software does not attempt to enforce
 	that. 

 	You should use sxpararr to get parameters from a FITS header array.

 INPUTS:
 	hdrarr	either a single fits header or a 2D array of strings
 			this gets modified to contain hdr.
 	hdr		a fits header you want to append to hdrarr.

 HISTORY:
 	Began 2002-11-19 20:16:08 by Marshall Perrin 

(See sources/hdrconcat.pro)


STRC

[Previous Routine] [Next Routine] [List of Routines]
(See sources/strc.pro)

 function Strc, thing,print=print,join=join
 PURPOSE: 
 Formats something as a string, 
 removing the extra spaces and unnecessary zeros. 
 Works on scalars or arrays.

KEYWORDS:
	print=		the print argument for string. See IDL help for string
	/join		if argument is an array, contatenate the output into
				a single string, using a space as delimiter.
	delimiter=  When /join is set, use this to join the strings instead
				of just a space.

HISTORY:
 will choke on arrays, only works on scalars
 June 1994, M. Liu (UCB)

 added chopping of unneeded zeros on the end of floats/doubles
 (beware if numbers are too long, will be chopped off - this is
 and IDL feature of the 'string' command, not due to this function)
 11/05/96 MCL

 Added ability to pass the "print" argument to string
 2001-07-09 MDP

 Added /join
 2003-07-01 MDP

 2004-04-06	Fixed horrible, horrible bug with scientific notation
 				How did I ever not notice this before now?!?? MDP
 2005-07-22	Added /delimiter

(See sources/strc.pro)


SXPARARR

[Previous Routine] [Next Routine] [List of Routines]
(See sources/sxpararr.pro)

 NAME: sxpararr
 PURPOSE:
 	Like sxparr, but for an array of fits headers.

 NOTES:
 	This isn't necessarily the fastest way to do this, but it
 	works fine for me.

 INPUTS:
 	hdrs	an array of fits headers. (i.e. a 2D string array)
 	name	string name of the parameter to return.
 KEYWORDS:
 OUTPUTS:
 	valid	(optional) an array specifying where the keyword was
 			found (valid=1) or not (valid=0)
 	/silent	Ignore the case where a keyword is not found at all.

 HISTORY:
 	Began 2002-11-19 20:34:57 by Marshall Perrin 
 	2005-06-01   Added error handling for the case where the first
 				 header lacks the keyword in question.

(See sources/sxpararr.pro)


HDRCOPY

[Previous Routine] [Next Routine] [List of Routines]
(See sources/hdrcopy.pro)

 NAME: hdrcopy
 PURPOSE:
 	copy keys from one header to another

 INPUTS:
 KEYWORDS:
 OUTPUTS:

 HISTORY:
 	Began 2005-05-15 05:14:16 by Marshall Perrin 

(See sources/hdrcopy.pro)


PICKFITS

[Previous Routine] [Next Routine] [List of Routines]
(See sources/pickfits.pro)

 function pickfits,header,instrument=instrument,filenames=filesnames
 
 NAME: pickfits
 PURPOSE:
 	pick one or more fits files using the GUI and then load them.
 NOTES:
 	returns the images and headers as multidimensional arrays, if
 	you select more than one file.

 	This is basically just a GUI frontend to fitsloader.pro, which handles
 	any scaling rules for coadds or nreads for different images.

 INPUTS:
       filenames	a list of filenames to load. If not supplied, then
       			you will be prompted with a file selection dialog box
       
 KEYWORDS:
       instrument	the name of the instrument these files are from; passed 
               	to fitsloader.pro
       
 OUTPUTS:
       returns the selected image(s) as a 2d image or 3d cube, as appropriate
       
       headers		returns the fits headers for the image(s) as a 1d 
       			or 2d string array, as appropriate.

 HISTORY:
   Began 2002-10-30 23:02:46 by Marshall Perrin 

(See sources/pickfits.pro)


SELECTFITS

[Previous Routine] [Next Routine] [List of Routines]
(See sources/selectfits.pro)

 NAME:
   SELECTFITS

 PURPOSE:

   The purpose of this program is to allow the user to select
   a FITS image file for reading. The image data is returned as the
   result of the function. The best feature of this program is
   the opportunity to browse the image before reading it.

 AUTHOR:

   SELECTFITS is by Marshall Perrin at UC Berkeley, but is based heavily
   upon SELECTIMAGE.PRO by David Fanning:

   FANNING SOFTWARE CONSULTING
   David Fanning, Ph.D.
   1645 Sheely Drive
   Fort Collins, CO 80526 USA
   Phone: 970-221-0438
   E-mail: davidf@dfanning.com
   Coyote's Guide to IDL Programming: http://www.dfanning.com/


 CALLING SEQUENCE:

   image = SelectFITS()

 INPUT PARAMETERS:

   None. All input is via keywords.

 INPUT KEYWORDS:

   DIRECTORY -- The initial input directory name. The current directory by default.

   FILENAME -- The initial filename. If the initial directory has image files of the
               correct type, the default is to display the first of these files. Otherwise, blank.

   FLIPIMAGE -- Set this keyword if you wish to flip the image from its current orientation. Setting
                this keyword reverses the Y dimension of the image.

   _EXTRA -- This keyword is used to collect and pass keywords on to the FSC_FILESELECT object. See
             the code for FSC_FILESELECT for details.

   GROUP_LEADER -- Set this keyword to a widget identifier group leader. This keyword MUST be
                   set when calling this program from another widget program to guarantee modal operation.


   ONLY2D -- Set this keyword if you only want the user to be able to select 2D images. Note
             that the user will be able to browse all images, but the Accept button will only
             be sensitive for 2D images.

   ONLY3D -- Set this keyword if you only want the user to be able to select 3D or true-color images.
             Note that the user will be able to browse all images, but the Accept button will only
             be sensitive for 3D or true-color images.


   PREVIEWSIZE -- Set this keyword to the maximum size (in pixels) of the preview window. Default is 150.

   TITLE -- Set this keyword to the text to display as the title of the main image selection window.

 OUTPUT KEYWORDS:

   CANCEL -- This keyword is set to 1 if the user exits the program in any way except hitting the ACCEPT button.
             The ACCEPT button will set this keyword to 0.

   FILEINFO -- This keyword returns information about the selected file. Obtained from the QUERY_**** functions.

   OUTDIRECTORY -- The directory where the selected file is found.

   OUTFILENAME -- The short filename of the selected file.

   PALETTE -- The current color table palette returned as a 256-by-3 byte array.

 COMMON BLOCKS:

   None.

 RESTRICTIONS:

   Probably doesn't work correctly on VMS systems :-( If you can help, please
   contact me. I don't have a VMS system to test on.

 OTHER COYOTE LIBRARY FILES REQUIRED:

  http://www.dfanning.com/programs/error_message.pro
  http://www.dfanning.com/programs/fsc_fileselect.pro
  http://www.dfanning.com/programs/tvimage.pro


 MODIFICATION HISTORY:

	2004-05-01 	Split from David Fanning's SELECTIMAGE.PRO function. See
	that file for modification history prior to this date.

(See sources/selectfits.pro)


SIGDISP

[Previous Routine] [Next Routine] [List of Routines]
(See sources/sigdisp.pro)

 NAME: sigdisp
 PURPOSE:
 	Like the IRCAL sigdisp, does a rough n-sigma linear stretch of an image.
 NOTES:
 	If the values guessed for the top and bottom limits are in fact 
 	outside of the actual range of image values, the display range is
 	truncated to the max or min as appropriate.

 INPUTS:
 KEYWORDS:
 OUTPUTS:

 HISTORY:
 	Began 2003-02-14 11:15:58 by Marshall Perrin 

(See sources/sigdisp.pro)


SIXTY_STRING

[Previous Routine] [Next Routine] [List of Routines]
(See sources/sixty_string.pro)

 NAME: sixty_string
 PURPOSE:
 	Like the Goddard library's "sixty" but it returns strings of the
 	format "DD:MM:SS". 

 	This is the inverse of ten_string.

 INPUTS: one can provide input in two ways:
 
    output = sixty_string( deg, min, sec)
 		in which case the inputs are just concatenated and 
 		printed out as a string   	
    	
    output = sixty_string( decimal_degrees )
    	in which case the input is passed to sixty(), and
    	the output is concatenated and printed
 	
 KEYWORDS:
 	delim=			Delimiter. Default is space
 	/ROUND			round seconds to an integer value
 	/sign			always print + or - (for declination)
 OUTPUTS:

 HISTORY:
 	Began 2004-06-05 02:40:25 by Marshall Perrin 
 	2004-07-01		Output format cleaned up slightly
 	2006-04-27		Default is now space as a delimiter, not colon
 	2006-05-30		Format hours/degrees with a leading 0 for single digits
 	2006-06-26		Added extra format code for negatives

(See sources/sixty_string.pro)


TEN_STRING

[Previous Routine] [List of Routines]
(See sources/ten_string.pro)

 NAME: ten_string
 PURPOSE:
 	Does the same thing as the goddard IDL astro library's "ten" procedure
 	(converts sexagesimal coords into decimal) but works on string arguments
 	of the form "DD:MM:SS" or "DD MM SS".

 INPUTS:
 	sixty_string	a sexagesimal string, possibly with sign.
 KEYWORDS:
 OUTPUTS:	
   tenv			a decimal value representing degrees or hours

 HISTORY:
 	Began 2002-08-14 21:01:48 by Marshall Perrin 
 	2004-07-25	sixty_string may now be an array of strings.

(See sources/ten_string.pro)


Category: Image Display

[List of Routines]


ALOGSCALE

[Next Routine] [List of Routines]
(See sources/alogscale.pro)

 NAME: alogscale.pro
 PURPOSE:
 	intelligently logarithmicly scale an image for 
	display. 
 NOTES:
	Based on the log scale code from ATV.pro

 INPUTS:
 KEYWORDS:
 	/print
 	/auto	like ATV's autoscale
 OUTPUTS:

 HISTORY:
 	Began 2003-10-20 01:23:02 by Marshall Perrin 
 	2004-09-15		Made NaN-aware		MDP

(See sources/alogscale.pro)


ASINH_DEMO

[Previous Routine] [Next Routine] [List of Routines]
(See sources/asinh_demo.pro)

 NAME:  asinh_demo
 PURPOSE:
 	demonstrate use of asinh scaling routines

 INPUTS:
 KEYWORDS:
 OUTPUTS:

 HISTORY:
 	Began 2006-12-18 14:52:01 by Marshall Perrin 

(See sources/asinh_demo.pro)


ASINHSCL_COLOR

[Previous Routine] [Next Routine] [List of Routines]
(See sources/asinhscl_color.pro)

 NAME: asinhscl_color 
 PURPOSE:
	RGB asinh scaling, in the manner of Lupton et al.
	
 INPUTS:
 	image	data cube, in RGB order.
 KEYWORDS:
 OUTPUTS:

 HISTORY:
 	Began 2006-07-11 19:57:05 by Marshall Perrin 

(See sources/asinhscl_color.pro)


ASINHSCL_CONTOURS

[Previous Routine] [List of Routines]
(See sources/asinhscl_contours.pro)

 NAME: asinhscl_contours
 PURPoSE:
 	create contour colors for overplotting.

 INPUTS:
 KEYWORDS:
 OUTPUTS:

 HISTORY:
 	Began 2006-08-19 09:58:07 by Marshall Perrin 

(See sources/asinhscl_contours.pro)


Category: Image Processing

[List of Routines]


CROP_BADMASK

[Next Routine] [List of Routines]
(See sources/crop_badmask.pro)

 NAME: crop_badpix

 PURPOSE:
 	Given an image and a mask, crop the image to the minimum size which contains
 	the mask.

 USAGE:
	PRO crop_badmask,data,badmask,cropped_data,cropped_badmask

 	Given an image and a bad pixel mask (which may well make up
 	a large portion of the image), crop the image to the minimum
 	size which contains all good pixels. That is, throw away any
 	border rows/columns which are all bad pixels.

 INPUTS:
 	data	an image or an image cube
 	badpix	a bad pixel mask; 0=bad, 1=good.
 			the bad mask must be 2D; for image cubes the whole thing
 			gets cropped the same way.
 KEYWORDS:
 RETURNS:
 	cropped_image	a cropped version of the image
	cropped_badmask	a cropped version of the badmask

 HISTORY:
 	Began 2002-09-03 16:21:49 by Marshall Perrin 

(See sources/crop_badmask.pro)


INDICES

[Previous Routine] [Next Routine] [List of Routines]
(See sources/indices.pro)

 NAME: indices

 PURPOSE:
  like Python's indices command, returns coordinate indices for an array

 NOTES:

 Unlike Python's indices, there are options for moving the origin, getting
 spherical coordinates back, setting the pixels scale, etc.

 INPUTS:
 KEYWORDS:
 	center=		optional coords of center
 	pixelscale=	optional multiplicative pixel scale factor
 OUTPUTS:
 	x,y,z	indices
 	r=		optional radial coord
 	theta=	optional azimuthal coord


 HISTORY:
 	Began 2008-06-12 20:04:55 by Marshall Perrin 
 	2012-06-06 doc header update

(See sources/indices.pro)


HIMCUT

[Previous Routine] [Next Routine] [List of Routines]
(See sources/himcut.pro)

 NAME:  HIMCUT
 PURPOSE:
 	Like 'IMCUT', cut out a subregion from an image, and update FITS header.

 	Very similar to HEXTRACT, but with different arguments

 INPUTS:
 KEYWORDS:
	/center		use center
	/method2	different coords computation, good for getting out odd-sized
				boxes. See code
 OUTPUTS:

 HISTORY:
 	Began 2007-04-23 15:06:10 by Marshall Perrin 

(See sources/himcut.pro)


STDDEVARR

[Previous Routine] [Next Routine] [List of Routines]
(See sources/stddevarr.pro)

 NAME: stddevarr
 PURPOSE: compute the standard deviation for each pixel in a cube

NOTES:
	sd = stddevarr(array,/badval,alsobad=<>)
 
 	Just as medarr returns the median at each pixel of an image cube,
 	this routine returns the standard deviation for each pixel in a
 	cube. This is useful when combining a stack of images if you want
 	an estimate of the error at a given pixel. 

   You can specify a badval which is used to mask out all pixels
   in the cube that have that value and only take the standard deviation
   of the remaining ones. This is useful if the images do not overlap
   completely and there are blank regions on some of the layers - just set 
   the blank regions to BADVAL and set the badval keyword likewise.

 INPUTS:
 	cube	an image cube, M*N*K
 KEYWORDS:
 	BADVAL	set this equal to the pixel value of pixels to ignore.
 	ALSOBAD	in case you have a second bad pixel value.
 	DIM=	which dimension to take the stddev over. Default=3
 	/DIVSQRT	Divide by the square root of the number of good valuse at
 				each pixel. In other words, return the standard deviation of
 				the mean, instead of just the standard deviation of the data
 				set.
 				NOTE: If you want to compute the population standard deviation
 				you should instead divide by the sqrt(n-1), but that's usually
 				not what you want in image analysis contexts.
  /MEDIAN	Compute Std. Dev. around the median, not the mean.
 OUTPUTS:
 	returns an M*N array containing the stddev at each pixel

 HISTORY:
 	Began 2002-06-21 14:51:12 by Marshall Perrin, based on
 		errmap_neg.pro by Erik Rosolowsky
 	2003-07-16  Modifed keyword checking to allow '0' to be specified
 		as a bad value.
 	2006-04-17	added dim= keyword; can now work on 2D images.
 	2006-06-01	Added recursive chunking of large cubes

(See sources/stddevarr.pro)


STDDEVS

[Previous Routine] [Next Routine] [List of Routines]
(See sources/stddevs.pro)

 NAME: meds
 PURPOSE:
 	return the standard deviations for a stack of images
 USAGE:
      function meds,imgs,help=help, skymode = skymode, masks = masks

 INPUTS:
 	imgs		a stack of images
 KEYWORDS:
 	masks		Bad pixel mask. 0=bad, 1=good
 	skymode		uses skymode.pro to find stddevs; disabled, not sure why
 RETURNS:
 		an array containing the stddev for each image in the stack.
 		That is, it computes the stddev for each image individually and
 		returns all of those, rather than stddevning across images.

 HISTORY:
 2004-10-6		split from meds.pro	MDP

(See sources/stddevs.pro)


SUBMEDIAN

[Previous Routine] [Next Routine] [List of Routines]
(See sources/submedian.pro)

 NAME: submedian
 PURPOSE:
 		subtract the median from each slice of a data cube

 INPUTS:
 KEYWORDS:
 OUTPUTS:

 HISTORY:
 	Began 2005-09-05 17:07:01 by Marshall Perrin 

(See sources/submedian.pro)


BIAS

[Previous Routine] [Next Routine] [List of Routines]
(See sources/bias.pro)

 PURPOSE:
 quick script for making a bias frame and displaying useful info
 
 USAGE:
 default is median-scaled median averaging to combine frames
   (which is not appropropriate for correlated double sampling
   images, which will have the bias level subtracted: better to use
   med-averaging *w/o* any weighting (/noweight): see 12/12/97 notes.
   For CTIO data, procedure automatically sets /noweight)

 default filename format is Keck

 see MKBIAS.IDL for a wrapper to do multiple bias sets

 HISTORY: Written by M. Liu (UCB) 01/29/97 
 02/24/97 (MCL): converted from BIAS.IDL script to BIAS.PRO
                 saves 1st image header to final image
                 uses SXADDHIST add history lines to header
 05/04/97 (MCL): added /lick and /gemini
 12/11/97 (MCL): added /avgclip option (must give the readnoise)
 01/24/99 (MCL): checks if all images have same # of coadds
                 (useful to ensure input list is correct)
 06/07/99 (MCL): checks if output directory exists
 07/07/99 (MCL): added /ircal
 2003-07-21 MDP: Added /auto

(See sources/bias.pro)


MKDOMEFLAT

[Previous Routine] [Next Routine] [List of Routines]
(See sources/mkdomeflat.pro)

 NAME: mkdomeflat
 	based on mktwiflat, but simpler
 PURPOSE:
 	makes a dome flat by loading a bunch of images, summing them, 
 	and then flattening. Optionally deals with polarization issues.


 INPUTS:
 KEYWORDS:
   infile	name of a text file containing a list of files.
   		if present, this overrides istart and iend
 	fdir	file directory
 	noflag	don't try to flag negative pixels with BADVAL.
 	/polarimetry	handle polarimetry subregions
 	/auto	run automatically without asking for user intervention or
 			confirmation
 	
 OUTPUTS:

 HISTORY:
 
 2002-04-11 18:35:45 started based on mktwiflat.pro
 2003-02-24 		  polarimetry code added. Converted to use fitsloader.

(See sources/mkdomeflat.pro)


MKSKYFLAT

[Previous Routine] [Next Routine] [List of Routines]
(See sources/mkskyflat.pro)

 NAME: mktwiflat
 PURPOSE:
  Median-combine a number of sky flat images into one master sky flat.

 INPUTS:
 KEYWORDS:
 	fdir	file directory
 	
 OUTPUTS:

 HISTORY:
 
 2002-04-29 14:40:55 split off from mktwiflat.pro by MDP
 2004-05-12  Merged in some updates from mktwiflat.pro
 2005-12-14  Don't set bad pixels in the flat to NaN; just
 				mark the appropriate pixel in the bad pixel mask.

(See sources/mkskyflat.pro)


MKTWIFLAT

[Previous Routine] [Next Routine] [List of Routines]
(See sources/mktwiflat.pro)

 NAME: mktwiflat
 PURPOSE:
 makes a flatfield from a series of images of the twilight sky
 	using a iterative fitting technique for each pixels to measure
 	the relative flatfield and to account for any constant (i.e. thermal)
 	component. to be used for making infrared twiflats.
 

 INPUTS:
 KEYWORDS:
   infile	name of a text file containing a list of files.
   		if present, this overrides istart and iend
 	datadir	file directory
 	sort_em	sort 'em! Necessary if files are not in order.
 	noflag	don't try to flag negative pixels with BADVAL.
 	
 OUTPUTS:

 HISTORY:
 -
 flags pixels with <0.001 as BADVAL too
 11/12/98 MCL

 small big fix: did not properly flag pixels with
   too few fittable pixels as BADVAL 
 now prints (c0,c1) on plots
 11/23/98 MCL

 displays stack of fitting masks (can see if there were stars)
 01/27/99 MCL

 add flag for IRCAL
 ** placed under RCS, version 1.0 **
 08/04/99 MCL

 plots the residuals to the fit in a 2nd window
 only overplots the final fitted line (instead of each iteration,
   which was basically indistinguishable)
 only prints info for pixels which go through >= 2 iterations
   (used to be >= 1 iteration)
 08/04/99 MCL

 2002-03-30 23:24:25 Converted to .pro by Marshall Perrin
 	only works with IRCAL files for now.
 2002-04-11 15:33:59 added images keyword to allow passing
 	in images directly. Also head0 for header.
 2002-07-04 15:46:49. Converted to use mloadims
 	added "auto" keyword to allow fully automatic execution.
 2002-12-03 12:21:13. Updated to use fitsloader.
 2004-04-16 MDP. Changed bad mask code to use 4 sigma for hot pixels
 	instead of 3 sigma, which tended to mark too many pixels as bad.
 2004-05-24 MDP.   Added /MPFIT and GAIN= keywords.
 

(See sources/mktwiflat.pro)


NEWSKYFLAT

[Previous Routine] [Next Routine] [List of Routines]
(See sources/newskyflat.pro)

 NAME: mktwiflat
PURPOSE:
  Median-combine a number of sky flat images into one master sky flat.

 INPUTS:
 KEYWORDS:
 	datadir	file directory
 	
 OUTPUTS:

 HISTORY:
 
 2002-04-29 14:40:55 split off from mktwiflat.pro by MDP
 2004-05-12  Merged in some updates from mktwiflat.pro
 2005-12-14  Don't set bad pixels in the flat to NaN; just
 				mark the appropriate pixel in the bad pixel mask.
 2005-12-22	Split off as 'newskyflat' for development branch.

(See sources/newskyflat.pro)


AORADNORM

[Previous Routine] [Next Routine] [List of Routines]
(See sources/aoradnorm.pro)

 PURPOSE:
 Given an image (presumably an AO image), create an unsharp masked
 image. then compute a radial noise profile for it and divide by the
 profile.

 NOTES:
 This is a quick & dirty way to "flatten" the image and
 make the speckle noise look constant at all radii.

 uses /iterstat for RADPLOTF.PRO to avoid effect of bad pixels
 still need to be careful in the center as things don't work so well
 there (few numbers of pixels)

 INPUTS
  img     original mosaic

 OUTPUTS
  outimg  radial noise-normalized image
  medimg  unsharp masked mosaic
  radimg  image with radial profile used
 KEYWORDS
  auto		don't ask the user any questions
    
 uses RADPLOTF.PRO

 HISTORY: Written by M. Liu (IfA/UH) 05/21/01
 06/11/01 MCL: now uses ITERSTAT.PRO to compute std dev
 2002-07-02 MDP: Added /auto

(See sources/aoradnorm.pro)


APPHOT

[Previous Routine] [Next Routine] [List of Routines]
(See sources/apphot.pro)

 PURPOSE:
 program to do circular aperture photometry on an image
  given aperture location, size, and inner and outer radius for
  sky subtraction annulus. 
NOTES:
  Calculates sky by median.
  Returns the net flux.

 to disable sky subtraction, just set inskyrad = outskyrad
 can input a constant sky value, if set this disables the sky annulus also

 writing to img, photimg, and skyimg as debugging checks

 out(0) = total flux
 out(1) = number of pixel in flux aperture
 out(2) = median sky level
 out(3) = number of pixel in sky annulus
 out(4) = net flux
 out(5) = zpt - 2.5*log10(netflux))  (magnitude)
 out(6) = sigma in sky annulus
 out(7) = fwhm calculated by finding the std dev of pixels (w/o sky)
 out(8) = pa
 out(9) = ellipticity
 out(10) = error in net flux (from sky error alone)
 out(11) = error in mags
 out(12) = # of bad pixels in phot aperture

 7/01/94 MCL - pretty certain this works right

 added 'zpt' = magnitude of a 1 count source (24.0 default)
 2/18/95 MCL

 if pass it a bad pixel mask, will use 'fixpix'
 routine to interpolate for bad pixels before doing photometry,

 photometry is reproducible to 0.2% to that produced by IRAF's
 'imexam' task; eliminated coordinate rounding to reduce the scatter
 7/26/95 MCL

 added fwhm output -> seems to give overestimates 
 8/1/95 MCL

 modified bad pixel handling: bad pixels are masked out, not
 interpolated (using FIXPIX) as was the case before
 2/1/96 MCL

 by default bad pixels are excluded from the photometry
 (corrupting the total flux, but not the measured radial profile)
 but if set /fixpix, use 'FIXPIX' to interpolate bad pixels
 04/22/96 MCL

 now does separate checks to see if phot & sky apertures are off image
 09/16/98 MCL

 added /overplot: will show location of phot radii
   if the image has already been shown with DISPLAY.PRO
 02/14/99 MCL

 there is this issue of label pixels at their half pixel center,
   which I haven't bothered with yet - means photometry may be off be
   +/- 0.5 pixel

 does not handle pixels which are partially inside the flux aperture,
   either pixels are in or not. Preferably, we'd like to use a simple
   weighting scheme for these pixels (like in IRAF) by taking a fraction
   of the pixel value equal to its fraction inside the aperture.
 would be slightly nicer if output was in form out a structure, instead
   of having to know which numbers correspond to what

(See sources/apphot.pro)


AVGMED

[Previous Routine] [Next Routine] [List of Routines]
(See sources/avgmed.pro)

 PURPOSE:
 Median average a stack of FITS images, with optional median weighting.

 NOTES:
 All frames are weighted by their medians, unless /noweight is set.
 If /log, then writes weights to a file as well and the options chosen.

 5/20/94 M. Liu (UCB)

 All frames read from file are normalized by their # of coadds 
 unless /nocoadd is set

 6/27/94 MCL

 Added ability to read images from IDL array (in a very inelegant way)
   if want to work with IDL array, just call avgmed like:
	IDL> avgmed, out, array
   to read stuff from a file, just define the 'filename' parameter:
	IDL> avgmed, out, filename='file.list'
 7/01/94

 significant modifications:

   1. 	modified median averaging so images are scaled to the average
    	of all the medians, instead of the median of the first image
   	-> this bombs if an image has a median = 0

   2. 	when median filtering if have <= 6 images, will take the mean
	of the middle 2 images when there is an even (2,4,6) number of images
	(only if /evenmed set since this can be quite S-L-O-W); this probably
	make little difference in practice

   3.  added 'minrej' and 'maxrej': will toss these number of values
	out before median averaging (no effect for arithmatic avg)
	note: this is done AFTER any weighting.

   4.  major editing of program to make it nicer

 12/13/94

 added minrej/maxrej option for arithmatic averaging as well
 and modified to toss more than one pixel

 6/2/95 MCL

 don't make a copy of the original images, instead doing scaling
 when do median filtering - runs about 10% faster for
 a stack of 30 images with simple median averaging

 7/2/95 MCL

 corrected error in calculating the proper image weights
 (was incorrectly scaling the weights to 1.0 by multiplying by the
   average value instead of dividing by it!)
 12/17/96 MCL

 the above bug fix was wrong - no idea why I thought it was right!
 01/29/97

 new algorithm for /evenmed - may be faster, but untested
 05/04/97 MCL

 added if/then for /noweight so avoids multiplying by array of 1's
   clumsier code but maybe faster operation
 used temporary() function when getting medians (does this help?)
 02/16/01 MCL

 cleaned up comments & tabs
 minor bug fix to get code running (odd, since I don't remember
 hacking it lately, but whatever ...)
 05/08/01 MCL

 **--> should rewrite /evenmed using the new /even flag in MEDIAN!!

(See sources/avgmed.pro)


CALCPHOTNOISE

[Previous Routine] [Next Routine] [List of Routines]
(See sources/calcphotnoise.pro)

 NAME: calcphotnoise
 PURPOSE:
 	Given an image, and a map of the exposure times for that image,
 	compute the photon noise as a function of position.

 INPUTS:
 	image		an image (normalized to units of DN/1 s)
 	expmap		an exposure map, in seconds
 KEYWORDS:
 	gain		Gain in photons/ADU. Default is 10 (for IRCAL)
 	/readnoise	include read noise too
 OUTPUTS:
 	Noise map, in the same scaled units as the supplied image.

 HISTORY:
 	Began 2004-04-08 11:55:45 by Marshall Perrin 
 	2004-05-12 	Added sky level option

(See sources/calcphotnoise.pro)


CENPSFSUB

[Previous Routine] [Next Routine] [List of Routines]
(See sources/cenpsfsub.pro)


 FUNCTION: cenpsfsub
 PURPOSE:
	centroiding psf subtraction routine. 
 NOTES:
	Registers images using the
	subreg procedure, then uses Powell minimization to find the bias offset
	and scale factors which result in the best PSF subtraction, as measured
	by minimizing the sum of the absolute value of the difference image.
	
 INPUTS:
 	im1,im2		2D images
 	
 KEYWORDS:
 	silent		supress printed output
 	method		Registration method. See subreg.pro for documentation
 	interp_type	interpolation method; see StarFinder image_shift.pro
 	boxsize		radius of square box around star to be used
 	ftol		tolerance for POWELL optimization
 OUTPUTS:
 	output		subtracted overlap region and originals
 		output[*,*,0] = subtracted (  = im1 - scale&shift(im2))
 		output[*,*,1] = image 1
 		output[*,*,2] = scaled and shifted image 2
 	
 	params		a float array containing the parameters of the subtraction fit.

 HISTORY:
 	August 2001		Marshall Perrin

(See sources/cenpsfsub.pro)


FINDMAXSTAR

[Previous Routine] [Next Routine] [List of Routines]
(See sources/findmaxstar.pro)

  FUNCTION: findmaxstar
  PURPOSE:
  		given an image, finds the x,y coords of the brightest object present.
  DESCRIPTION:
  		Uses simple binning as a rough CR rejection routine.
  		Can do more detailed rejection of CRs using qzap

  		This is intended to be used for the automatic registration of images for
  		mosaicing.
  		Empirical evidence is that this routine is negliglbly slower than
  		just using whereismax, but is much more robust against hot pixels
  		or CRs which are still in the data. Has not been tested on crowded 
  		fields, where source confusion would probably make it break down.

  		It also automatically interpolates values for any bad (NaN) pixels
  		in the image; NaNs will be set to the image median so that the code
 		won't choke.

  INPUTS:
  		img		an image
  		/silent		whether to print any messages or not
  OUTPUTS:

  REQUIREMENTS:
  		needs whereismax.pro and findlocalmax.pro
  
  HISTORY:
  		Started July 2001 by Marshall Perrin
  		2002-12-05	Added check for NaN pixels.

(See sources/findmaxstar.pro)


FITPLANE

[Previous Routine] [Next Routine] [List of Routines]
(See sources/fitplane.pro)


 FUNCTION: fitplane
 PURPOSE:

		Fits a plane to an image
	
 INPUTS:
 	im1		2D images
 	
 KEYWORDS:
 	silent		supress printed output
 	method		Registration method. See subreg.pro for documentation
 	interp_type	interpolation method; see StarFinder image_shift.pro
 	ftol		tolerance for POWELL optimization
 OUTPUTS:
 	
 	params		a float array containing the parameters of the subtraction fit.
	scale		divide im2 by this for best subtraction.

 HISTORY:
 	August 2001		Marshall Perrin

(See sources/fitplane.pro)


FIXNANS

[Previous Routine] [Next Routine] [List of Routines]
(See sources/fixnans.pro)

 NAME: fixnans
 PURPOSE:
 	fix NANs in an image, e.g. before cross correlating or something.

 INPUTS:
 	imgs	an image or image cube
 KEYWORDS:
 	/quick	just set NANs to 0, rather than interpolating.
 OUTPUTS:

 HISTORY:
 	Documentation added 2005-06-07 10:16:36 by Marshall Perrin

(See sources/fixnans.pro)


FIXPIX

[Previous Routine] [Next Routine] [List of Routines]
(See sources/fixpix.pro)

 NAME:
 		fixpix
 PURPOSE:
 given a image or stack of images and a bad pixel
 mask, will fill in bad pixels by finding the NPIX nearest
 good pixels, toss the highest and lowest ones of the bunch,
 and then arithmatically average. 

 NOTES:

		pro fixpix,imgs,badpix,outimgs, $
		   npix=npix,weight=weight, $
		   noise=noise,sigma=sigma,dc=dc, $
		   silent=silent,badvalmask=badvalmask,NaN=NaN
		   
 bad pixel list is processed in order array is stored in
 memory, i.e. row by row, and is defined by:
	 0 = bad pixel
    not 0 = good pixel

 If /badval is set, badpix is ignored and the procedure determines
 	a new bad pixel list by examining the image for pixels set to BADVAL.
 Alternatively, if /NaN is set, any IEEE Not-a-Number values are 
   considered to be bad pixels and fixed.

 NPIX = # of adjacent pixels used for correction (default = 8)
 /weight: weight adjacent pixels by inverse of their distances
	   in averaging process

 checks to see if some pixels are equidistant; if so,
 use all of them, even if the total # of pixels then exceeds NPIX

 WARNINGS:
  - will work for entire bad columns/rows, but 
    may not be the most sensible thing to use
  - do not pass it the same array for input & output as this
    might corrupt the correction algorithm

 7/3/95 MCL

 added /noise: replace bad pixels with random noise with
 user defined sigma and dc level                9/24/95 MCL
 badpix can now be a 2d or 3d array             4/18/96 MCL
 uses MESSAGE now instead of regular PRINT     04/25/01 MCL
 Added /badval keyword                       08/27/2001 MDP
 Added /NaN keyword						  2003-04-12 MDP
 Added /Quick keyword						  2004-07-04 MDP
 Made /quick work with arbitrary size imgs	  2004-09-15 MDP
 Made /quick sense left and right sides independently
 											  2005-03-16 MDP

(See sources/fixpix.pro)


IMAGE_SHIFT_MASKEDGES

[Previous Routine] [Next Routine] [List of Routines]
(See sources/image_shift_maskedges.pro)

 NAME: image_shift_maskedges
 PURPOSE:
 	When shifting an image, manipulate the bad pixel mask
 	appropriately such that the correct edges of the shifted 
 	image are declared bad. 
 NOTES:
 	This doesn't worry about bad pixels in the interior of the image - 
 	for now. This relies on rounding the shift such that it's only the
 	fractional part and thus using the bad pixel mask for the nearest integer
 	pixel is not such a bad idea. You still should have fixed via interpolation
 	all bad pixels before any subpixel shifting, of course.

 INPUTS:
 	badpix				bad pixel mask
 	xshift, yshift		x and y image shifts
 						This code assumes |x| < 1, |y| < 1
 KEYWORDS:
 OUTPUTS:
 	Modifies the supplied badpix mask.

 HISTORY:
 	Began 2004-10-21 20:27:33 by Marshall Perrin 

(See sources/image_shift_maskedges.pro)


IMCENTERF

[Previous Routine] [Next Routine] [List of Routines]
(See sources/imcenterf.pro)

 PURPOSE:
 program to calculate the center of mass of an image around
 the point (x,y), return the answer in (xcen,ycen).

Usage:
		pro imcenterf, img, x, y, xcen, ycen, error,  $
              badpix = badpix,  $
              bigbox = bigbox, cbox = cbox, iter = iter,  $
              maxpix = maxpix, nomaxpix = nomaxpix,  $
              maxshift = MAXSHIFT,  $
              silent = silent

 can roughly correct for the effect of bad pixels

 ALGORITHM:
   1. first finds max pixel value in
	   a 'bigbox' box around the cursor
   2. then calculates centroid around the object 
   3. iterates, recalculating the center of mass 
      around centroid until the shifts become smaller 
      than MINSHIFT (0.3 pixels) or until it does 
      this MAXITER number of times 
      (** iteration is currently disabled/untested **)

 INPUTS:
   img		image
   x,y		initial guess for center

 OUTPUTS:
   xcen,ycen	derived centers
   error	error code for overshifting (0=no,1=yes)

 CAVEATS:
   - works on an integer pixel basis
   - maxpix algorithm will fail if a hot pixel is nearby
   - iteration scheme actually seems to lead to larger 
     differences than not iterating (by about 0.01 pixel) when
     compared to the results of the Goddard package's CNTRD


 KEYWORDS:
   badpix	bad pixel mask; any bad pixels inside centering
		boxes will be corrected with 'fixpix' routine
 		before centering
   bigbox	size of box for max pixel finding (default=11)
   cbox	size of box for centroiding (default=11)
   iter	max number of iterations (default=1)
   /maxpix	return location of max pixel value in the box only,
		instead of then also finding centroid
   /nomaxpix	don't find max pixel before finding centroid
   maxshift    if shift btwn input & output centroid is larger 
                 then this, will give an error message and set error=1
   /silent	don't print out error message


 Written by : M. Liu  12/12/94
 06/02/95 (MCL): corrected bug (x and y reversed), 
	          implemented two step algorithm & maxpix feature
 07/14/95 (MCL): added iteration scheme 
 07/26/95 (MCL): added bad pixel fixing option
 04/16/96 (MCL): if /maxpix and find >1 max pixel, will find centroid
 12/01/96 (MCL): fixed error in checking if cbox and bigbox are odd 
 05/26/99 (MCL): big fix - round CBOX and BIGBOX to integers
                   may screw up the centroiding via BIGBOX step
                   (b/c may lead to 1 pixel shift?)
                 changed default 'bigbox' from 11 pix to 1.5*CBOX
 12/04/99 (MCL): made MAXSHIFT a keyword parm
 2003-11-20:  Treats NaNs as missing values. (MDP)
 2004-04-08:  Added errors option (MDP)

(See sources/imcenterf.pro)


IMCUT

[Previous Routine] [Next Routine] [List of Routines]
(See sources/imcut.pro)

 PURPOSE:
 Function to cut out a square subsection out of an image,
 with the user specifying the center of the subsection.

 NOTES: 
 Will return a non-square image if the specified center is
 too close to the edges.


 function Imcut, image, imsize, xc, yc, xc1, yc1, $
                help=help, fixsize=fixsize, $
                peak = peak, $
                silent=silent, pad=pad, mask=mask,
                center=center,newcenter=newcenter,
                method2=method2,
                x0=x0,y0=y0, x1=x1, y1=y1


 INPUTS
   image	original image

 OPTIONAL INPUTS
   imsize	size of the subsection (256 default)
               can be a scalar or a 2-element vector (x,y)
   xc,yc	center location of the subsection 
		(default is center)
 
 OPTIONAL OUTPUTS
  xc1,yc1      if too close to edge, returns the coords
               of the original point (xc,yc) in the new subarray
  x0,y0		coordinates of the corner of the new subarray

 KEYWORD PARAMETERS
   /fixsize    will adjust center so return an image of desired size
               (by default it trims the output image size keeping
                the desired center fixed) 

   /pad		instead of just trimming an image near the edge, pad it
   			with zeros to get it to the correct size. Return a mask
   			of good (=1) and bad (=0) pixels in the 'mask' variable.
   /peak       use peak pixel value for central coordinate
               then no need to pass (xc,yc)

 RETURNS
	the image subsection

 HISTORY
 Written by MCL(UCB): 10/01/95
 02/10/96 (MCL): changed order of parameters (imsize,xc,yc)
 04/23/96 (MCL): allowed imcut to be 2d 
 05/04/96 (MCL): added /fixsize
 03/04/98 (MCL): returns (xc1,yc1), useful for image labelling
   -> working?
 10/20/00 (MCL): gives warning if uses default values for imsize,xc,yc
 06/11/01 (MCL): added /peak
 2004-10-21  MDP: Added /pad and mask keywords. 
 2006-04-20 MDP: Made xc1 and yc1 actually work properly.

 -> need to check if handling odd numbered sizes properly

(See sources/imcut.pro)


MEDARR2

[Previous Routine] [Next Routine] [List of Routines]
(See sources/medarr2.pro)

 NAME: medarr2

 PURPOSE:
 	Like medarr, except you can specify a set of exposure times to scale
 	the images by before taking their medians.

 INPUTS:
 	inarr,outarr,mask,output_mask	same as for medarr.
 KEYWORDS:
 	exptimes	array of exposure times
 	/minimum	return min at each pixel, not median
 	threshhold=		mask out all values above this number of counts per second.
 					(to block out stars)
 OUTPUTS:
 	If exptimes not set, returns the median image.
 	If exptimes is set, returns the median image scaled to a 1 second exposure.

 HISTORY:
 	Began 2004-04-13 20:28:15 by Marshall Perrin 
 	2006-06-20	added /minimum

(See sources/medarr2.pro)


MOSF

[Previous Routine] [Next Routine] [List of Routines]
(See sources/mosf.pro)

 PURPOSE:
 routine to shift and stack a set of images to create a final mosaic,
 using masks to exclude bad pixels or cosmic rays

 INPUTS:
       imgs            3d array of images (all the same size)
       xobj, yobj      position of registration object in each frame
       				subpixel positions will be handled via
       				interpolated shifts. (MDP Aug 2001)

 OUTPUTS:
       out             resulting mosaic
       outexp          exposure map for resulting mosaic
       sky             sky values determined for each frame by /setsky
       xf              lower + upper x coords for each image's position 
                         in the mosiac (2 by N array where N is number 
                         of images) -> for debugging
       yf              y coords for each image's position in the mosaic
       pieces          indiv shifted (and maybe trimmed) images
                         which go into the mosiac - buffered by BADVAL, 
                         bad pixels are turned either to BADVAL,
                         and with sky offset from /setsky added

 KEYWORD INPUTS:
       badpix          badpix 2d image (0=bad, not 0=good) (optional)
       masks           masks for each individual image (like badpix, but a 3d array)
       wtmap           map of weights for combining images (3-d array)
                         final mosaic will be scaled to wtmap=1.0
                         (for images of diff int. times, optimal
                         weights are the int. times)
       expmap          map of exposure times for combining images (3-d array)
                         final mosaic will be scaled to expmap=1.0
       exptimes        1-d array of exp times for combining images
                         final mosaic will be scaled to expmap=1.0
       /trim           only mosaic the overlapping regions
       /setsky         iteratively adds a constant to frames to
                         minimize the 'seams' of the mosaic
                         (adds considerable time but often necessary,
                         will crash unless ALL the images overlap)
       nrej            number of images to reject at high/low ends
                         at a given pixel location before combining,
                         i.e., a quick cosmic ray deterrent
                         (if not enough images at a gievn pixel, 
                         then just averages)
       /median         take the median value of the good images
                         at each pixel
       minval          min values to stop iterations of /setsky 
                         (0.001 default)
       /submed         set median of each image to zero before
                         combining 
       goodlist        logical list of which images to use (0=bad,!0=good)
                       very useful if passing a large number of
                       images so don't have to pass, eg, imgs[*,*,10:150]
       /subpixel		Perform subpixel shifts on the images before
       				registering. Requires Nyquist sampled images or better!
            
 CAVEATS:
   - due to crappy programming, need to be VERY CAREFUL with
       variables.  most of the working variables used to make the
       mosaic (e.g. xobj, yobj, sky) can have fewer entries than the
       input variables (e.g. imgs, xobj0, yobj0, exptimes0, etc.).  
       this occurs when some images are flagged as bad, via
       'goodlist' or shifts=-999.
     the mapping btwn the two is kept in the 'wg' index
       variable. when doing FOR loops, the 'i' index loops over only the
       good subset while the 'ii' index loops over all images

 HISTORY:
 Written by M. C. Liu (UCB): 12/14/94 (spun off of 'ireg.pro')
 06/05/95 (MCL): added high/low pixel rejection ability
 07/27/95 (MCL): improved bad pixel treatment, 
                 corrected bug in pixel rejection scheme
 08/20/95 (MCL): adjusted algorithm for greater speed,
                 made sure rounding of offsets is done properly
 04/16/96 (MCL): able to pass masks for the individual frames
                 badpix and masks set to BYTE type
                 exposure map (outexp) set to INT type
                 changed the assignment of BADVAL to blank areas and
                   also 'eq BADVAL' to 'le/gt BADVAL' (round-off worries)
                 made sky offsets total up to 0
                 added /submed
                 changed /setsky so it uses the median of the
                   overlapping regions instead of the average
                   to reduce sensitivity to unflagged bad pixels
 11/30/96 (MCL): corrected subtle error in determining final image
                 size using rounding when the max image offset ends
                 in 0.5 (only when using /trim)
 12/04/96 (MCL): big changes from MOSF.PRO - less memory intensive!
                   developed under the name MOSFQUICK.PRO
                   eliminated the 'pieces' variable 
                 disabled (for now) all the filtering schemes (nrej, etc)
                   for combining the mosaic
                 added 'goodlist' feature
                 changed 'le/gt BADVAL' back to 'ne BADVAL'
                 increased MINSKY from 1e-5 (excessive) to 1e-3 DN
                 checked against MOSF.PRO, ok to w/in roundoff errors
 02/10/97 (MCL): added /silent
 02/28/97 (MCL): replaced existing version of MOSF.PRO with MOSFQUICK.PRO
                 previous version renamed MOSF_SLOW.PRO (still useful)
 04/24/98 (MCL): added 'expmap', a 3d-array of pixel exposure time
                   for int time weighting when combining diff mosaics
                   final mosaic will be normalized to expmap=1.0
                 NOTE: /setsky doesn't handle the expmap (yet)
 10/25/98 (MCL): renamed 'expmap' parm into 'wtmap' (map of weights)
                   b/c this is treated like weights, not diff int. times
                  *NOTE: therefore, past use of 'expmap' gave *WRONG*
                     phot, but did do exposure time (variance) wts!
                 added new 'expmap' variable which does behave right
                 small bug fix: /submed wouldn't work if no /setsky
 01/29/99 (MCL): added MAXSIZE limit on output array size (sanity check)


 03/13/99 (MCL): added 'exptimes' - untested!!!
 09/29/00 (MCL): added kludge fix for /setsky if some images don't overlap
                 now identifies images to be ignored (shift=-999)
                   very convenient, should have done this earlier
                 *** placed under RCS, version 1.1 ***
 10/02/00 (MCL): bug fix - wasn't using masks when some shifts=-999
                 *** RCS, version 1.2 (05/10/01) ***
 05/10/01 (MCL): better memory management for 'wtmap' and 'expmap'
                 (code is slightly uglier, but takes less memory)
                 *** RCS, version 1.3 ***
 05/12/01 (MCL): MAJOR CHANGES
       1. much better memory usage, no longer makes extra
            copies of the input images & masks! however, the coding
            is slightly uglier (use of both 'i' and 'ii' indicies!)
       2. recognizes BADVAL pixels in input images, no need to pass masks!
    fairly extensive testing against previous version 1.3 (at least for
      most commonly used options: didn't test /trim, /submed)
    minor changes: increased use of MESSSAGE, instead of PRINT
 05/13/01 (MCL): found bug - I think "shifts=-999" doesn't work when user
                   doesn't pass 'goodlist'.  never encountered this before!
                 tried to fix bug, but got bogged down, then tried to 
                   return to previous tested version.  think I did this
                   successfully (re-ran tests from yesterday)
                 for now, temporarily disable use of 'shifts=-999'
                 -> still good to be cautious with this ... <-
                *** RCS version 1.4 ***
 05/13/01 (MCL): above bug is more extensive than I thought -
                   previous version can't use 'goodlist' at all!
                 fixed implementation of 'goodlist' (should *always*
                   use this instead of passing arrays like im[*,*,10:20])
                 disabled shifts=-999 for now
 05/24/01 (MCL): adjusted disabling of shifts=-999, still turned off
                   but now routine will run if 'goodlist' is passed
 08/15/2001 (MDP): Added sub-pixel interpolation with keyword SUBPIXEL
 06/25/2002 (MDP): Re-added the pieces variable, for measurement of
 					noise at each pixel for polarimetry.
 08/06/2002 (MDP): Made median keyword work again.
 2004-3-16 (MDP):  Fixed bug with exptimes vs exptimes0
 2004-4-12 (MDP):  Fixed bug introduced in previous bugfix; made /setsky work
 					with exposure times. Fixed bug in subpixel code when 
 					some images are marked not good.

 -> modify /setsky so will take information in the weight map (wtmap)

(See sources/mosf.pro)


OPTPSFSUB

[Previous Routine] [Next Routine] [List of Routines]
(See sources/optpsfsub.pro)


PRO optpsfsub,filename1,filename2,unsharp=unsharp,cbox=cbox,$
	output=output,nosave=nosave,savecube=savecube,$
	oversample=oversample
 PURPOSE:
  Optimizing PSF subtraction routine.

 INPUTS: filename1,filename2	filenames of the two fits files to 
 	subtract. Assumes suffix ".ks_mos.fits"
 OUTPUTS: 
 	output		This keyword returns the subtracted image, or
 				an image cube if /savecube is set.
 KEYWORDS:
 	unsharp=	do unsharp masking with this radius
 	cbox=		size of box around star to evaluate
 	oversample=	do oversampling of this amount
 	/nosave		don't save to disk, just keep in memory.
 	/qzap		use qzap to kill CRs
 Interpolation:
 	/fft 		use fft interpolation
 	/cubic		use cubic splines for subpixel interpolation
 	/interp		use bilinear interpolation
 	/sinc		use sinc interpolation
 	
 	If multiple interpolation flags are passed, the highest one in the
 	list above is honored.
 	
 HISTORY: Began by MDP on 2001-07-09 as a wrapper for psfpowell
 2001-08-22	Subpixel interpolation options added.

 

(See sources/optpsfsub.pro)


OPTSUB

[Previous Routine] [Next Routine] [List of Routines]
(See sources/optsub.pro)


 FUNCTION: optsub
 PURPOSE:

 	PSF Subtraction optimizer. Given two images already aligned, 
 	what scale factor optimizes their subtraction?
	
 INPUTS:
 	im1,im2		2D images
 	
 KEYWORDS:
 	silent		supress printed output
 	method		Registration method. See subreg.pro for documentation
 	interp_type	interpolation method; see StarFinder image_shift.pro
 	boxsize		radius of square box around star to be used
 	ftol		tolerance for POWELL optimization
 	/show		display on screen the two images
 	/all		use the whole image, not a subimage, for the optimization
 OUTPUTS:
 	output		subtracted overlap region and originals
 		output[*,*,0] = subtracted (  = im1 - scale&shift(im2))
 		output[*,*,1] = image 1
 		output[*,*,2] = scaled and shifted image 2
 	
 	params		a float array containing the parameters of the subtraction fit.
	scale		divide im2 by this for best subtraction.

 HISTORY:
 	August 2001		Marshall Perrin

(See sources/optsub.pro)


OPTSUBWITHOFFSET

[Previous Routine] [Next Routine] [List of Routines]
(See sources/optsubwithoffset.pro)


 FUNCTION: optsubwithoffset
 PURPOSE:
 	PSF Subtraction optimizer. Given two images already aligned, 
 	what scale factor optimizes their subtraction?

 	This version also solves for a constant shift between the two images.
	
 INPUTS:
 	im1,im2		2D images
 	
 KEYWORDS:
 	silent		supress printed output
 	method		Registration method. See subreg.pro for documentation
 	interp_type	interpolation method; see StarFinder image_shift.pro
 	boxsize		radius of square box around star to be used
 	ftol		tolerance for POWELL optimization
 	/show		display on screen the two images
 	/all		use the whole image, not a subimage, for the optimization
 OUTPUTS:
 	output		subtracted overlap region and originals
 		output[*,*,0] = subtracted (  = im1 - scale&shift(im2))
 		output[*,*,1] = image 1
 		output[*,*,2] = scaled and shifted image 2
 	
 	params		a float array containing the parameters of the subtraction fit.
	scale=		Divide im2 by this for best subtraction.
	offset=		Add this to im2 for best subtraction.

 HISTORY:
 	August 2001		Marshall Perrin

	2006-05-25		Added /show and /all

(See sources/optsubwithoffset.pro)


RADGEN

[Previous Routine] [Next Routine] [List of Routines]
(See sources/radgen.pro)

 PURPOSE:
 Program to generate a 2-d image given 1-d profile
 (radial or elliptical) with a specified center and radial extent.

 NOTES:
 The radial profile is interpolated in log space either by
  (1) a 5th order polynomial function, or
  (2) spline interpolation (default)
 Be sure to inspect to insure the fit is sensible (esp. at outer edges).

 If the psf is very strongly peaked, set bin > 1 to ensure 
 pixellation is not a problem

 To get the profile from the original image, one can use RADPLOTF

 INPUTS
	radx	radial profile: radial distances (in units of pixels)
	rady	radial profile: fluxes

 OPTIONAL INPUTS
	x,y	center location 

 OUTPUTS
	outimg	2-d image 

 KEYWORD INPUTS {defaults}
       imsize  size of output image; may be a two element vector {64}
       bin     binning factor for making the psf - should be odd {1}
       rmin    min radius for image {0}
       rmax    max radius for image {imsize}
	ellratio  for elliptical phot, ratio of major to minor axes 
	ellpa	for elliptical phot, position angle CCW from up
	        (with elliptical phot, all the radii become
		the semi major axis)
       /poly use poly interpolation for the radial profile
	/plot	plot the interpolated fit to the radial profile
	/silent	
	center=		alternate way of setting xcen and ycen

 NOTES
 - This program developed by modifying RADSUB.PRO:
   changed profile interpolation options and removed
   sky subtraction option.
 - 1st half of code is nearly identical to RADPLOTF

 HISTORY: Written by M. Liu (UCB) 06/19/96
 08/11/98 (MCL): fixed bug with using 'bin' - put obj in wrong place
 08/18/00 (MCL): 'imsize' can now be a 2-element vector
 2003-11-28 MDP: Fixed apparent bug with "bin" where xsize,ysize where
 	multiplied by bin twice.

(See sources/radgen.pro)


RADNOISE

[Previous Routine] [Next Routine] [List of Routines]
(See sources/radnoise.pro)


 FUNCTION: radnoise
 PURPOSE:
		plot radial noise profile
 INPUTS:
 	imgstack	a 3-deep image cube of sub,star,psfstar as produced by 
 				optpsfsub or cenpsfsub
 KEYWORDS:
 OUTPUTS:

 HISTORY:

(See sources/radnoise.pro)


RADPLOTF

[Previous Routine] [Next Routine] [List of Routines]
(See sources/radplotf.pro)

 PURPOSE:
 Program to calculate radial/elliptical profile of an image
 given aperture location, range of sizes, and inner and 
 outer radius for sky subtraction annulus. 
 NOTES:
 Calculates sky by
 median or user can specify a value.  Can extract profile
 from only a restricted range of angles (i.e. a sector) as well.

 User can enter a bad pixel mask; if so, bad pixels are
 excluded (not interpolated); total flux and differential
 flux are scaled from the fraction of pixels used, though
 the number of pixels is not.

 INPUTS
  	image	
	x,y	center location 

 OUTPUTS
	out	output array for radial profile (see below)
	fwhm	FWHM as determined by spline fit to radial profile
	radpts

 KEYWORD INPUTS {defaults}
 	/struct	format output as structure array.
 	inrad	inner radius for photometry {0.5}
	outrad	outer radius for photometry {20}
	drad	radial increment for photometry {1.0}
	insky	inner radius for sky annulus {outrad+drad}
	outsky	outer radius for sky annulues {insky+20}
	sky	user specified constant sky value 
	ellratio  for elliptical phot, ratio of major to minor axes 
	ellpa	for elliptical phot, position angle CCW from up
	        (with elliptical phot, all the radii become
		the semi major axis)
	ang1	starting angle for profile, measured CCW from up
	ang2 	ending angle for profile (going CCW)
       zpt     zeropoint (DN/sec from a 0 mag star) - for output file
       pixscl  pixel scale (units/pixel) - for output file
               (used only if 'zpt' is set)
	badpix	bad pixel mask (0=bad, !0=good)
	/silent	say nothing
	/verbose print complete listing of results
	/nosky	 don't do sky subtraction at all.

 OUTPUT FORMAT
 out(i,0) = radius (measured from middle of radial bin)
 within each radius:
 	out(i,1)  = total flux 
	out(i,2)  = net flux
 	out(i,3)  = number of pixels (integrated)
	out(i,4)  = differential flux (in radial bin bounded by out(0))
	out(i,5)  = number of pixels (in radial bin)
	out(i,6)  = average value in radial bin (sky subtracted)
	out(i,7)  = stddev of pixel values in bin
	out(i,8)  = median sky level
	out(i,9)  = number of pixel in sky annulus
	out(i,10) = stddev in sky annulus
	out(i,11) = stddev of avg pixel values in radial bin
		    (quadrature sum of out(7) and out(10))
   if the user passes a zeropoint & pixel scale:
       out(i,12)= radius in pixel scale units
       out(i,13)= integrated magnitude
       out(i,14)= avg surface brightness in radial bin (mag/units^2)

 radpts is a 2 x n array with the pixel values and distances for every
   point inside the largest aperture (unsorted) where
   radpts(0,*) are the distances and radpts(1,*) are the pixel values

 NOTES
 - to disable sky subtraction, set the /nosky keyword
 - implicitly assumes all noise is sky noise and gaussian
 - sector photometry is done only for the object, all flux in 
   the sky annulus is assumed to be useable

 USES
	inarc, splinefwhm

 HISTORY
 Written by M. C. Liu (UCB) 08/13/94
 09/25/95 (MCL): added badpixel mask capability
 10/25/95 (MCL): added elliptical photometry ability and
	          ability to extract profile from a sector
 10/06/98 (MCL): radii with no good pixels now return 0 flux in out array
 10/22/98 (MCL): added /fixpix
 02/01/99 (MCL): *** placed under RCS, version 1.0 ***
 02/01/99 (MCL): can write results to 'outfile' w/explanatory header 
 02/22/99 (MCL): adjusted output format of radial profile plot
                 added 'zpt' and 'pixscl' keywords (used in output file)
 03/15/99 (MCL): now uses ITERSTAT.PRO to determine median value in
                   sky annulus, instead of ordinary MEDIAN
 06/11/01 (MCL): added /iterstat for computing std dev in annuli
 05/07/02 (MDP): added /nosky for use with simulations w/ no sky.
 2002-12-05 (MDP): Added checks to ignore NaN pixels. NEEDS TO BE TESTED
 2006-08-03 MDP: Added /MEDIAN option to compute median in each annulus.
 					This is stored into out[*,5], in place of # of pixels.
 					WARNING - potentially very very slow.

 

 UNRESOLVED ISSUES
 - what are the proper values for inrad and drad?
 - would be slightly nicer if output was in form out a structure, instead
   of having to know which numbers correspond to what
 - no accomodation for pixels which are partially in aperture; preferably
   would like to use a simple weighting scheme (like in IRAF) to 
   handle this (treats pixel coords at pixel corners, may be
   preferable to work with pixel centers, i.e. (0,0) ->
   (0.5,0.5), when accomodating fractional pixels)
 - output array should store # of bad pixels in aperture & radial
   bins
 -> does not check for BADVAL pixels, but it should!

(See sources/radplotf.pro)


RECENTER

[Previous Routine] [Next Routine] [List of Routines]
(See sources/recenter.pro)

pro recenter, imgs, xold, yold, xnew, ynew, $
              cbox = cbox, maxpix = maxpix, $
              badpix = badpix, mask = mask,  $
              wait = wait, nodisplay = nodisplay, silent = silent


 PURPOSE:
 given an array of images and initial guesses for registration, 
 calculate final offsets using IMCENTERF

 HISTORY:
 05/04/97 MCL

 old coordinates can be scalars or vectors
 07/08/97 MCL

 added /maxpix option
 07/07/98 MCL

 prints stats for shifts
 08/10/98 MCL

 set /fix for imcut, so objects near the edge are displayed ok
 10/09/98 MCL

 added 'wait' parm - can specify delay between frames
 07/07/99 MCL

 draws the centering box on the displayed zoom area
 09/29/00 MCL

 worked for 1 image
 added /silent
 06/11/01 MCL

 Fixed return-without-stop on incorrect arguments. That's dangerous.
   06/21/02 MDP

 Added errors parameter. 2004-04-08 MDP  

(See sources/recenter.pro)


REGISTER_DEMO

[Previous Routine] [Next Routine] [List of Routines]
(See sources/register_demo.pro)

 NAME: 
 	register_demo
 PURPOSE:
 Demonstrate how to use subreg.pro and mosf.pro to register and mosaic images

 NOTES:
	Note that this just shows off the basics of how to use this code. 
	subreg and mosf both have many, many options. You should take a look
	at the documentation for each of those to find out more.  ;	Frankly, they've grown
	a little crufty over time. None of this code is very clean! But it
	works well enough in practice...

 
 INPUTS:
 	imgs			an array of images.
 OUTPUTS:
 	mosaic			the final mosaic of the images
 	mosaic_exp		an array showing how many original images (exposures) 
 					contributed to each pixel of the output mosaic.
 KEYWORDS:

 HISTORY:
 	Began 2003-07-30 21:44:38 by Marshall Perrin 

(See sources/register_demo.pro)


SKYSUB

[Previous Routine] [Next Routine] [List of Routines]
(See sources/skysub.pro)

pro Skysub, imgs, sky, imgsub,  $
            badpix = badpix, $
            scale = scale,  $
            save = save,  $
            silent = silent

 PURPOSE:
 subtract a 2d sky frame (or bias frame) from a 3d array of images
 by default, it will delete the input images unless /save

 KEYWORDS:

 /scale  match the median of sky image with the object before subtraction
 /save   preserve the input images (default is to delete them)
 exptimes	array of exposure times for the images. If set, the sky frame
 			is assumed to be for exptime=1 and is scaled appropriately
 			before being subtracted from each image.

 NOTES
 to save memory when subtracting large/numerous images, 
 should call this routine with the TEMPORARY() function, i.e.:
       IDL> skysub, temporary(imgs), skyimg, imgsub

 HISTORY: Written by M. Liu 07/07/94
 09/27/95 MCL: added /scale
 10/25/96 MCL: added badpix option
 07/11/98 MCL: copies BADVAL in input obj & sky images to output images
 02/16/01 MCL: significant improvements in memory & some in speed
                * default is to delete input images unless /save
                - grouped scalar operations
                - more careful use of memory
               now ignores BADVAL pix when using /scale
               added & organized comments
 06/11/01 MCL: if only a single frame is passed, then /save
 2004-04-13 MDP:  Added exptimes option. Don't overwrite by default!
 2005-05-03 MDP:  Now is /save by default, unless /nosave.
 2005-10-13 MDP:  Removed horrible evil 'retall on any error' code!

(See sources/skysub.pro)


STAT

[Previous Routine] [Next Routine] [List of Routines]
(See sources/stat.pro)

 PURPOSE:
 gives median, mean, min, max, and std deviation for a given image

 NOTES:
 able to specify lower and upper boundaries to image
 program uses IDL's median function so if there are an even number of pixels,
   it will take the value just above the median location

 checked against IRAF "imstat" and everything looks good
   but runs somewhat slower than IRAF imstat

 Now this ignores any NaN values.

 INPUTS
   data     the data (any IDL array)

 OUTPUTS
   out(0) = number of pixels
   out(1) = mean
   out(2) = median
   out(3) = standard deviation
   out(4) = minimum pixel
   out(5) = maximum pixel

 KEYWORD PARAMETERS
   lower    lower limit of data to find stats
   upper    lower limit of data to find stats
   nolabel  output results w/o the column headings
   nobadval exclude BADVAL pixels from calculation of min pixel value
   silent

 HISTORY 
 Written by M. Liu (UCB): 06/22/94
 05/30/97 (MCL): added /nobadval
 2002-12-05: Added check to ignore NaNs  - M. Perrin

 Please send comments/questions to 

(See sources/stat.pro)


SUBREG

[Previous Routine] [Next Routine] [List of Routines]
(See sources/subreg.pro)


 FUNCTION: subreg
 PURPOSE:
	subpixel registration of images

 NOTES:

	Registers multiple images against a reference image based one one of
	four methods for determining the shift between the two images at a subpixel
	level. Returns the offsets for each image relative to the first.

 PRO subreg,ref,imgs0,shifts,badpix=badpix,silent=silent,$
 	goodlist=goodlist0,method=method,boxsize=boxsize

 INPUTS:
 		ref		Reference image to which all other images are registered.
 		imgs0	array of images. Should be bias corrected and flat-fielded.
 				must have same x and y dimensions as ref.
 KEYWORDS:
 		badpix		bad pixel mask
 		goodlist	List of which images in the cube are good (=1)
 					Only these are registered against the first good one.
 		headers		an array of FITS headers, used for the "H" alignment
 		method		Which method to use for the subpixel registration?
 						"X"		Fourier cross-correlation, centroided
 						"F"		Fourier cross-correlation, fit by gaussian
 						"FHP"	Fourier cross-correlation, with high pass filter, fit by gaussian
 						"C"		center-of-mass centroid
 						"O"		Goddard astro library CNTRD routine
 						"G"		Gaussian fitting iteratively
 						"R"		Mike Liu's recenter.pro centroid
 						"N"		no shifts; degenerate case: just return 0
 						"M"		maximum pixel intensity
 						"H"		read shifts from FITS headers. Currently shifts
 								are relative to the absolute zero point of the
 								FITS headers; ref0 is ignored in this case.
 						"HF"    Hybrid: use Fourier, but let header values
 								override if they're wildly different.
 					Default is "F"

			Based on empirical evidence, usually "X" or F works best, 
			but which one is best for any specific case
			will depend on the details of your data in that specific instance.
 					
 		boxsize 	box size for fit to cross correlation
 		whichref=	Which header to use for the reference image? (only used for	HF)
 OUTPUTS:
 		shifts		2d array of [x,y] shifts of each image relative to the first

 HISTORY:
	Marshall Perrin, starting Aug 2001. Based on pixel-level registration
	code by Mike Liu
	2001-08-22		Merged code from pxc.pro
	2001-08-27		Split ref into a seperate input, added error checking.
	2002-12-05      Added code to handle if NaNs are present in the images
	2003-11-25		Added "H" option.
	2004-04-07		Renamed Goddard cntrd to "O". Added Gaussian option.
	2005-10-16	    Changed all gauss2dfits to mpfit2dpeak.
	and lots of other stuff I haven't kept track of.

(See sources/subreg.pro)


SUBREG_SHIFTSTOPEAKS

[Previous Routine] [Next Routine] [List of Routines]
(See sources/subreg_shiftstopeaks.pro)

 NAME: subreg_shiftstopeaks
 PURPOSE:
 	Given a shifts array created by subreg, convert this to 
 	an array of peak pixel locations in an image, as needed
 	for input to the mosf function.

 INPUTS:
 KEYWORDS:
 OUTPUTS:

 HISTORY:
 	Began 2003-11-25 17:55:53 by Marshall Perrin 
 	2006-08-18 - no recenter!

(See sources/subreg_shiftstopeaks.pro)


AUTOREGISTER

[Previous Routine] [Next Routine] [List of Routines]
(See sources/autoregister.pro)

 NAME: autoregister
 PURPOSE:
 	Automagically register a bunch of images.

USAGE:
 	This accepts either an image stack datacube or an array of pointers to 
 	images, and registers and mosaics them together via cross correlation.
 	This is mostly just a convenient driver function for subreg and mosf,
 	in other words. 

 INPUTS:
 		array	either an array of images, or a ptrarray pointing to
 				a bunch of images of different size. if the latter,
 				autoregister pads as necessary, then registers.
 KEYWORDS:
 		/nantozero	set NaNs to 0 before registering. This saves a lot of time
 					versus running fixpix in subreg.
		/justpad	Given an ptrarry, just pad them and concatenate into
					one variable, returned as 'padded'

		padded=		output variable for padded array
		mosaic= 	output variable for the mosaiced sum

		shifts=		use these shifts instead of registering

 		use _extra to pass keywords to subreg or mosf.
 		
 OUTPUTS:

 HISTORY:
 	Began 2005-04-08 00:33:48 by Marshall Perrin 
 	2005-06-30: Subpixel registration now the default
 	2006-04-27: Can now pass shifts in as an argument

(See sources/autoregister.pro)


FFT_FILT

[Previous Routine] [Next Routine] [List of Routines]
(See sources/fft_filt.pro)

 NAME: fft_filt.pro 
 PURPOSE:
	High- or Low-pass filter an image in Fourier space.

 INPUTS:
 KEYWORDS:
 	/highpass	do highpass filter
 	/lowpass	do lowpass filter
 	cutoff		the frequency to filter at (units?!?)
 OUTPUTS:

 HISTORY:
 	Began 2005-12-14 00:51:11 by Marshall Perrin 

(See sources/fft_filt.pro)


FFTREBIN

[Previous Routine] [Next Routine] [List of Routines]
(See sources/fftrebin.pro)


 FUNCTION: fftrebin
 PURPOSE:
 	Rebins an image by adding zeros in between the FFT components as
 	necessary. 
 NOTES:
 	Right now it only upsamples, so don't try to use this
 	for shrinking images. But it does seem like it does a really nice job
 	at upsampling things. 

 INPUTS:
 	img		an image
 	scale	a scale factor. Can be any real number greater than 1.
 KEYWORDS:
 OUTPUTS:
 	the enlarged version of the image

 HISTORY:
   2001-08-03 - Marshall Perrin, based on an idea by JRG, and building
    			on code from fouriershift.
   

(See sources/fftrebin.pro)


FFTSHIFT

[Previous Routine] [Next Routine] [List of Routines]
(See sources/fftshift.pro)


 FUNCTION: fouriershift
 PURPOSE:
   shifts an image by (dx,dy) pixels using fourier transforms. 
 NOTES:
   if
   dx and dy are both nonzero, shifts in 2 dimensions. If dy is zero or not
   present, the shift is performed in only the x dimension. 

   Thus, calling fouriershift,img,dx will perform a 1d shift of either 
   a 1d series or a 2d image. Calling fouriershift,img,dx,dy will perform
   a 2d shift of a 2d image. 

   based on the fourier transform shift theorem:
   	f(x-dx,y-dy) <==> exp(-2pi i(u*dx+v*dy)) F(u,v)

 INPUTS:
 	img		an image
 	dx,dy	pixel shifts. Can be fractional. dy is optional.
 KEYWORDS:
 OUTPUTS:
 	the shifted version of the image

 HISTORY:
   2001-07-27 - Marshall Perrin

(See sources/fftshift.pro)


FFTSHIFTCUBE

[Previous Routine] [Next Routine] [List of Routines]
(See sources/fftshiftcube.pro)


 FUNCTION: fouriershift
   shifts an image by (dx,dy) pixels using fourier transforms. if
   dx and dy are both nonzero, shifts in 2 dimensions. If dy is zero or not
   present, the shift is performed in only the x dimension. 

   Thus, calling fouriershift,cube,dx will perform a 1d shift of either 
   a 1d series or a 2d image. Calling fouriershift,cube,dx,dy will perform
   a 2d shift of a 2d image. 

   based on the fourier transform shift theorem:
   	f(x-dx,y-dy) <==> exp(-2pi i(u*dx+v*dy)) F(u,v)

 INPUTS:
 	cube		an image
 	dx,dy	pixel shifts. Can be fractional. dy is optional.
 KEYWORDS:
 OUTPUTS:
 	the shifted version of the image

 HISTORY:
   2001-07-27 - Marshall Perrin

(See sources/fftshiftcube.pro)


FIXNANFITS

[Previous Routine] [Next Routine] [List of Routines]
(See sources/fixnanfits.pro)

 NAME: fixnanfits
 PURPOSE:
 	given the name of a fits file, open that file, fix all the NaN pixels
 	in it by interpolating from the nearest neighbors, then re-save the file

 INPUTS:
 	fitsname	a filename of a FITS image
 KEYWORDS:
 OUTPUTS:

 HISTORY:
 	Began 2003-03-10 11:04:26 by Marshall Perrin 

(See sources/fixnanfits.pro)


MATCH_FILTER

[Previous Routine] [Next Routine] [List of Routines]
(See sources/match_filter.pro)

 NAME: match_filter
 PURPOSE:
 	Convolve an image with a normalized version of itself.

 	Quick and dirty...

 INPUTS:
 KEYWORDS:
 OUTPUTS:

 HISTORY:
 	Began 2005-09-05 20:00:40 by Marshall Perrin 

(See sources/match_filter.pro)


MEANS

[Previous Routine] [Next Routine] [List of Routines]
(See sources/means.pro)

 NAME: means
 PURPOSE:
 	return the means for a stack of images

 NOTES:
	[See also: meds.pro]

      function means,imgs,help=help, skymode = skymode, masks = masks

 INPUTS:
 	imgs		a stack of images
 KEYWORDS:
 	masks		Bad pixel mask. 0=bad, 1=good
 	skymode		uses skymode.pro to find medians; disabled, not sure why
 RETURNS:
 		an array containing the median for each image in the stack.
 		That is, it computes the median for each image individually and
 		returns all of those, rather than medianning across images.

 HISTORY:
   2005-05-03 mperrin: started, based on meds.pro
   2005-11-14 mperrin: calls mean with /NAN

(See sources/means.pro)


SETSKY

[Previous Routine] [Next Routine] [List of Routines]
(See sources/setsky.pro)

 NAME: setsky
 PURPOSE:
 	Add offsets to images to make the background sky level equal
 	to the background of the first image.

 INPUTS:
 KEYWORDS:
 	/mean	subtract mean from each slice (old default)
 			new default is to subtract the output of 'sky' for each.
   smooth=	smooth this many pixels before computing sky values.
   /zero	set sky levels to zero instead of making them all match.
 OUTPUTS:

 HISTORY:
 	Began 2005-11-14 15:36:18 by Marshall Perrin 

(See sources/setsky.pro)


TUNEREGISTER

[Previous Routine] [Next Routine] [List of Routines]
(See sources/tuneregister.pro)

 NAME: tuneregister
 PURPOSE:
 	Tune up image registration.

 	Takes an already-registered stack of images (possibly done by hand)
 	then cuts out a subregion in it and runs subreg on that subregion.

 INPUTS:
 KEYWORDS:
 OUTPUTS:

 HISTORY:
 	Began 2005-11-13 11:20:44 by Marshall Perrin 

(See sources/tuneregister.pro)


MATRIX_DFT

[Previous Routine] [Next Routine] [List of Routines]
(See sources/matrix_dft.pro)

 NAME:  matrix_dft

 PURPOSE:
 	Matrix Discrete Fourier Transform, following Soummer et al. 2007. 
 	This is not as fast as an FFT, but allows you to arbitrarily choose the
 	sampling and range covered in the Fourier domain.

 NOTES:
  	 This is an IDL translation of the Python code in SFT.py.

    Compute an adjustible-center matrix fourier transform.

    For an output array with ODD size n,
    the PSF center will be at the center of pixel (n-1)/2

    For an output array with EVEN size n,
    the PSF center will be in the corner between pixel (n/2-1,n/2-1) and (n/2,n/2)

    Those coordinates all assume Python/IDL style pixel coordinates running from
    (0,0) up to (n-1, n-1).


    This version supports rectangular, non-square arrays,
    in which case nlamD and npix should be 2-element
    tuples or lists, using the usual Pythonic order (Y,X)

 INPUTS:


 KEYWORDS:
    Parameters
    ----------
    pupil : array
        pupil array (n by n)
    nlamD : float or tuple
        size of focal plane array, in units of lam/D
        (corresponds to 'm' in Soummer et al. 2007 4.2)
    npix : float or tuple
        number of pixels per side side of focal plane array
        (corresponds to 'N_B' in Soummer et al. 2007 4.2)
    offset: tuple
        an offset in pixels relative to the above

 OUTPUTS:

 HISTORY:
 	Began 2011-08-16 18:47:19 by Marshall Perrin based on SFT.py
 	Benchmarked against SFT & agreement achieved. 

(See sources/matrix_dft.pro)


FWCENTROID

[Previous Routine] [List of Routines]
(See sources/fwcentroid.pro)

 NAME: fwcentroid

 PURPOSE:
  Implements the robust floating-window centroid algorithm
  adopted for JWST target acquisitions.

 NOTES:
  See JWST-STScI-001117 and JWST-STScI-001134 for details.


    """ Implement the Floating-window first moment centroid algorithm
        chosen for JWST target acquisition.

        See JWST-STScI-001117 and JWST-STScI-001134 for details.

        This code makes no attempt to vectorize or optimize for speed;
        it's pretty much just a straight verbatim implementation of the
        pseudocode provided in JWST-STScI-001117


        Parameters
        ----------
        image : array_like
            image to centroid
        checkbox : int
            size of moving checkbox for initial peak pixel guess. Default 1
        halfwidth : int
            Half width of the centroid box size (less 1). Specify as a scalar, or a tuple Xhalfwidth, Yhalfwidth.
            Empirical tests suggest this parameter should be at *least* the PSF FWHM for convergence,
            preferably some small factor larger
        maxiterations : int
            Max number of loops. Default 5
        threshold : float
            Position threshold for convergence

        Returns
        --------
        (ycen, xcen) : float tuple
            Measured centroid position. Note that this is returned in Pythonic
            Y,X order for use as array indices, etc.




M. Perrin, 2011-02-17
2011-08-16  Back-ported from Python to IDL

(See sources/fwcentroid.pro)


Category: IRCAL Pipeline

[List of Routines]


IRCAL_BADPIXELS

[Next Routine] [List of Routines]
(See sources/ircal_badpixels.pro)

 NAME:  ircal_badpixels
 PURPOSE:
 	Mark persistently bad ircal pixels as NANs

 	usage: ircal_badpixels,imgs


 	This isn't ALL the bad pixels, just ones that I can tell are bad
 	but the automated stuff doesn't pick up for some reason.

 INPUTS:
 KEYWORDS:
 OUTPUTS:

 HISTORY:
 	Began 2006-05-26 00:30:44 by Marshall Perrin 

(See sources/ircal_badpixels.pro)


IRCAL_BADPIXFROMLIST

[Previous Routine] [Next Routine] [List of Routines]
(See sources/ircal_badpixfromlist.pro)

 NAME:  ircal_badpixfromlist
 PURPOSE: Read bad pixel list from file and apply to an image stack

 INPUTS:
 KEYWORDS:
 	/fixlater	just mark the pixels with NaNs, don't fix them
 OUTPUTS:

 HISTORY:
 	Began 2006-06-21 15:01:44 by Marshall Perrin 

(See sources/ircal_badpixfromlist.pro)


IRCAL_DEGHOST

[Previous Routine] [Next Routine] [List of Routines]
(See sources/ircal_deghost.pro)

 NAME: ircal_deghost
 PURPOSE:
 	remove annoying negative ghosts caused by channel crosstalk.

 USAGE:
	**** NOTE: This is mostly a cosmetic improvement **** 
	If you're trying to do science on faint objects inside the
	crosstalk region, you're on your own! 

 	This seems to work sort of OK. It could probably improved in
 	various ways, but I'm not entirely sure how useful this will be,
 	so for now I'm not going to worry about it. 



 INPUTS:
 KEYWORDS:
 OUTPUTS:

 HISTORY:
 	Began 2004-10-21 21:45:07 by Marshall Perrin 
 	2006-06-12	code cleanup for unused option ,m=m to imcut.

(See sources/ircal_deghost.pro)


IRCAL_DEWARP

[Previous Routine] [Next Routine] [List of Routines]
(See sources/ircal_dewarp.pro)

 NAME: ircal_dewarp 
 PURPOSE:
 	Remove distortion from an IRCAL image

 NOTES:
 	Right now this is -incredibly- basic and just handles the anisomorphic
 	magnification term, and nothing higher order than that. 

 INPUTS:
 		image0			an image or stack of images.
 KEYWORDS:
 		/NOFLUXSCALE	Don't rescale image counts to preserve total flux.
 						(default is to do scaling)
 		pixelscale=		new pixelscale to use. Default is 0.040 arcsec
 		CUBIC=			use cubic resampling. See docs for INTERPOLATE.
 		/BYTE			return a byte image, not float. Useful for dewarping
 						masks
 		/CROPTOP		Drop the top 5 rows of the IRCAL detector. These are the
 						rows full of many bad pixels and sometimes it's just
 						easiest to get rid of them.
 OUTPUTS:

 HISTORY:
 	Began 2005-11-07 15:24:51 by Marshall Perrin 
 	2006-05-09	Actually got it working finally. Major code updates.
 	2006-06-09	Added /croptop option

(See sources/ircal_dewarp.pro)


IRCAL_DEWARP_SHIFTS

[Previous Routine] [Next Routine] [List of Routines]
(See sources/ircal_dewarp_shifts.pro)

 NAME: ircal_dewarp_shifts 
 PURPOSE:
		convert a list of image shifts from raw IRCAL coords
		to dewarped coords
 INPUTS:
 KEYWORDS:
 OUTPUTS:

 HISTORY:
 	Began 2006-06-21 15:28:58 by Marshall Perrin 

(See sources/ircal_dewarp_shifts.pro)


IRCAL_GETJ2000

[Previous Routine] [Next Routine] [List of Routines]
(See sources/ircal_getj2000.pro)

 NAME: ircal_getj2000 
 PURPOSE:
	Convert the current-epoch IRCAL coords into J2000 coords

 INPUTS:
 	hdr			a FITS header
 KEYWORDS:
 OUTPUTS:
 	ra, dec		J2000 coords.

 HISTORY:
 	Began 2006-06-21 01:33:34 by Marshall Perrin 

(See sources/ircal_getj2000.pro)


IRCAL_REGRID

[Previous Routine] [Next Routine] [List of Routines]
(See sources/ircal_regrid.pro)

 NAME: ircal_regrid
 PURPOSE: resample IRCAL images to compensate for anamorphic magnification
 USAGE:
 		IRCAL is anamorphic, so images have different plate scales in
 		X and Y. Congrid the data in order to fix that. 

 		This routine doesn't do a perfect job of it since it's constrained
 		to deal with integer pixels...

 INPUTS:
 KEYWORDS:
 OUTPUTS:

 HISTORY:
 	Began 2005-07-26 02:57:29 by Marshall Perrin 
 	2006-05-09	Some updates

(See sources/ircal_regrid.pro)


IRCAL_ZEROPT

[Previous Routine] [Next Routine] [List of Routines]
(See sources/ircal_zeropt.pro)

 NAME: ircal_zeropt
 PURPOSE:
 	front-end routine for photometric calibration of IRCAL data

 INPUTS:
 KEYWORDS:
 OUTPUTS:

 HISTORY:
 	Began 2005-08-03 00:39:38 by Marshall Perrin 

(See sources/ircal_zeropt.pro)


IRCALSTREHL

[Previous Routine] [Next Routine] [List of Routines]
(See sources/ircalstrehl.pro)

 NAME: ircalstrehl
 PURPOSE:
 	Compute Strehl for an IRCAL image.

 USAGE:
   ircalstrehl,image,strehl,wavelength=wavelength,_extra=_extra

	
 INPUTS:
 KEYWORDS:
 OUTPUTS:

 HISTORY:
 	Began 2005-07-26 03:27:45 by Marshall Perrin 

(See sources/ircalstrehl.pro)


GETIRCALFILTER

[Previous Routine] [Next Routine] [List of Routines]
(See sources/getircalfilter.pro)

 NAME: getircalfilter
 PURPOSE:
 	Given a FITS header, returns a string describing the current IRCAL filter.

 NOTES:
 	This could be *either* the FILTER1 or FILTER2 FITS keyword, depending.

 INPUTS:afits header
 KEYWORDS:
 OUTPUTS: a string

 HISTORY:
 	Began 2005-03-03 12:16:34 by Marshall Perrin 

(See sources/getircalfilter.pro)


IRCAL_FIXPIX

[Previous Routine] [Next Routine] [List of Routines]
(See sources/ircal_fixpix.pro)

 NAME: ircal_fixpix
 PURPOSE:
 	This is a front-end to ns_fixpix.pro which knows about the
 	IRCAL bad corners and preserves them in the bad pixel mask.

 INPUTS:
 KEYWORDS:
 		/maskcorners	if set, the bad corners as found in the input
						will be set to NaN in the output as well.

		/stars			Ignore areas around bright stars. This prevents
						identifying undersampled PSFs as bad pixels
						WARNING! This has not really been well tested yet.
 OUTPUTS:

 HISTORY:
 	Began 2003-11-25 18:19:40 by Marshall Perrin 
 	2006-05-25	Added /stars option
 	2006-06-09	reworked /stars option to use label_regions, and
 				other algorithm improvements. Added starmask=.

(See sources/ircal_fixpix.pro)


IRCAL_SATMASK

[Previous Routine] [Next Routine] [List of Routines]
(See sources/ircal_satmask.pro)

 NAME: ircal_satmask
 PURPOSE:
 	Determine saturated regions in IRCAL data and mask to NaN
 		Also handles IRCAM and NIRC2 images.

 NOTES:
	we define as saturated:
		1. 	All pixels > 28000 counts per read
		2.  Pixels > 25000 counts per read which are contiguous with
			other saturated pixels.
		3.  Optionally, pixels remain saturated for some number of exposures
			after they were first saturated. This is to account for persistent
			afterglow seen in heavily saturated regions of the chip.
 	

 INPUTS:
 	images	an array of images
 	headers	an array of FITS headers
 KEYWORDS:
 	after=	saturated pixels may remain hot due to trapped charge even
 			after the star has been moved away. If after=N, then pixels
 			will be considered bad for the N exposures following saturation.
 			default is 0.
 	/maskonly	Don't set saturated pixels to NANs, just mark their position
 				in the satmask variable
 OUTPUTS:
	satmask	pixel mask indicating which pixels are saturated.
 HISTORY:
 	Began 2003-11-20 14:49:07 by Marshall Perrin 

(See sources/ircal_satmask.pro)


IRCALADDWCS

[Previous Routine] [Next Routine] [List of Routines]
(See sources/ircaladdwcs.pro)

 NAME: ircaladdwcs
 PURPOSE:
 	Add WCS coordinates to a FITS header for IRCAL

 INPUTS:
 	header	a FITS header which is to be modified
 KEYWORDS:
 	/USEMAX		use brightest star in image for CRPIX
 	IMAGE=		image array for finding brightest star

 	OBJNAME=	look up coords for this object from database for CRVAL

 	pixelscale=	pixelscale for the data. If not present, assumes IRCAL default.
 OUTPUTS:

 HISTORY:
 	Began 2003-09-11 07:05:23 by Marshall Perrin 
 	2004-05-12	Fixed equinox to be the epoch at time of
 				observations, which is what's actually
 				used for the coordinates.

   2006-05-10 added objname,usemax,image,pixelscale, plus
   		updating of header history.

(See sources/ircaladdwcs.pro)


REDIRCALSKY

[Previous Routine] [Next Routine] [List of Routines]
(See sources/redircalsky.pro)


 FUNCTION: redircalsky
 PURPOSE:
 	Version of IRCAL code for making sky files to input to redircalsub.
 	
 NOTES:
 	After the standard bias subtraction and flat fielding steps,
 	this procedure uses cross-correlations to register any arbitrary dither
 	together and combines the images into a final mosaic. 

 INPUTS:
 	objn	Object Name
 	istart	file name index start
 	iend	file name index end
 	pclip	percentage of best images to keep after FWHM cut
 	
 KEYWORDS:
 	fdir=	data directory
 	flatf=	flat field to use
 	badpixf=	bad pixel mask file
 	outdir=		output data directory (must already exist)
 	/subpixel	do subpixel registration
 	subshift=	subpixel shift method (see mosf.pro)
 	submethod=	subpixel registration method (see subreg.pro)
 	auto		Perform all tasks automatically without prompting the user.
 	/medsky		create median frame for sky and subtract it from all frames.
 	/median		use median combining, not averaging.
 	nan			fix nans before registering, the quick way.
 	scaletime	for fitsloader. scale images of different exposure times
 				to this exposure time. 
 	saturation	also for fitsloader. what value (for an unscaled image) is saturated? mask as NaNs
 	/satmask	use ircal_satmask function to mask saturated pixels
 	
 OUTPUTS:

 HISTORY:

 quick redux of Lick AO data
 06/11/01 M. Liu
 06/13/01 mods by JPL to add flatfield
 2001-07-17 turned into a procedure by mperrin
 2001-08	subpixel stuff added
 2002-04-09  dark frame subtraction added by mperrin
 2002-07-04  nstack parameter removed - not used by the subpixel code
 			  added auto keyword.
 2002-08-06  added medsky keyword
 2002-08-06  added median keyword
 2002-12-05  Converted to use fitsloader. NEEDS TO BE TESTED

(See sources/redircalsky.pro)


REDIRCALSUB

[Previous Routine] [List of Routines]
(See sources/redircalsub.pro)


 FUNCTION: redircalsub
 PURPOSE:
 	Reduction of IRCAL data with subpixel registration and mosaicing.
 	NOTES:
 	After the standard bias subtraction and flat fielding steps,
 	this procedure uses cross-correlations to register any arbitrary dither
 	together and combines the images into a final mosaic. 

 INPUTS:
 	objn	Object Name
 	istart	file name index start
 	iend	file name index end
 	pclip	percentage of best images to keep after FWHM cut
 	
 KEYWORDS:
 	datadir=	data directory
 	flatf=	flat field to use
 	badpixf=	bad pixel mask file
 	outdir=		output data directory (must already exist)
 	/subpixel	do subpixel registration
 	subshift=	subpixel shift method (see mosf.pro)
 	submethod=	subpixel registration method (see subreg.pro)
 	auto		Perform all tasks automatically without prompting the user.
 	/medsky		create median frame for sky and subtract it from all frames.
 	/median		use median combining, not averaging.
 	nan			fix nans before registering, the quick way.
 	scaletime	for fitsloader. scale images of different exposure times
 				to this exposure time. 
 	saturation	also for fitsloader. what value (for an unscaled image) is saturated? mask as NaNs
 	/satmask	use ircal_satmask function to mask saturated pixels
 	/verbosename	Put the expose time and istart into the output file name
 	
 OUTPUTS:

 HISTORY:

 quick redux of Lick AO data
 06/11/01 M. Liu
 06/13/01 mods by JPL to add flatfield
 2001-07-17 turned into a procedure by mperrin
 2001-08	subpixel stuff added
 2002-04-09  dark frame subtraction added by mperrin
 2002-07-04  nstack parameter removed - not used by the subpixel code
 			  added auto keyword.
 2002-08-06  added medsky keyword
 2002-08-06  added median keyword
 2002-12-05  Converted to use fitsloader.

(See sources/redircalsub.pro)


Category: Mathematics

[List of Routines]


GAUSSIAN2D

[Next Routine] [List of Routines]
(See sources/gaussian2d.pro)

 NAME:
       GAUSSIAN2d
 PURPOSE:
       Compute the 2-d Gaussian function and optionally the derivative

	based on Goddard IDL Astro's "Gaussian.pro"

	RESTRICTION: Right now only circularly symmetric gaussians
       
 EXPLANATION:
       Compute the 2-D Gaussian function and optionally the derivative 
       at an array of points.

 CALLING SEQUENCE:
       y = gaussian( x, y, parms,[ pderiv ])

 INPUTS:
       x,y = arrays, independent variable of Gaussian function.

       parms = parameters of Gaussian, 2, 3 or 4 element array:
               parms[0] = maximum value (factor) of Gaussian,
               parms[1] = mean value (center) of Gaussian in X,
               parms[2] = mean value (center) of Gaussian in Y,
               parms[3] = standard deviation (sigma) of Gaussian.
               (if parms has only 2 elements then sigma taken from previous
               call to gaussian(), which is stored in a  common block).
               parms[4] = optional, constant offset added to Gaussian.
 OUTPUT:
       y -  Function returns array of Gaussian evaluated at xi.    Values will
            be floating pt. (even if xi is double) unless the /DOUBLE keyword
            is set.

 OPTIONAL INPUT:
       /DOUBLE - set this keyword to return double precision for both
             the function values and (optionally) the partial derivatives.
 OPTIONAL OUTPUT:
       pderiv = [N,3] or [N,4] output array of partial derivatives,
               computed only if parameter is present in call.

               pderiv[*,i] = partial derivative at all xi absisca values
               with respect to parms[i], i=0,1,2,[3].


 EXAMPLE:
       Evaulate a Gaussian centered at x=0, with sigma=1, and a peak value
       of 10 at the points 0.5 and 1.5.   Also compute the derivative

       IDL> f = gaussian( [0.5,1.5], [10,0,1], DERIV )
       ==> f= [8.825,3.25].   DERIV will be a 2 x 3 array containing the
       numerical derivative at the two points with respect to the 3 parameters.
 
 COMMON BLOCKS:
       gaussian    ; why is this here??
 HISTORY:
 		2005-May-06 Forked from gaussian.pro by Marshall Perrin
       

(See sources/gaussian2d.pro)


GRIDEVAL

[Previous Routine] [Next Routine] [List of Routines]
(See sources/grideval.pro)

 NAME:  grideval
 PURPOSE:
Evaluates a function, supplied as a string, for all points of a supplied
 grid in x and y.

 INPUTS:
 KEYWORDS:
 OUTPUTS:

 HISTORY:
 	Began 2007-07-27 09:19:56 by Marshall Perrin 

(See sources/grideval.pro)


MAXES

[Previous Routine] [Next Routine] [List of Routines]
(See sources/maxes.pro)

 NAME: maxes
 PURPOSE:
 	return the maximums of each image for a stack of images

 USAGE:
      function maxes,imgs,help=help, skymode = skymode, masks = masks

 INPUTS:
 	imgs		a stack of images
 KEYWORDS:
 	masks		Bad pixel mask. 0=bad, 1=good
 	skymode		uses skymode.pro to find medians; disabled, not sure why
 RETURNS:
 		an array containing the maximum for each image in the stack.
 		That is, it computes the maximum for each image individually and
 		returns all of those, rather than maximum-ing across images.

 HISTORY:
 	2005-07-12		split from meds.pro by M Perrin

(See sources/maxes.pro)


MODE

[Previous Routine] [Next Routine] [List of Routines]
(See sources/mode.pro)

 NAME: mode
 PURPOSE:
 	Calculate the mode (most common element in an array)
 	optionally with binning

 INPUTS:
 KEYWORDS:
 OUTPUTS:

 HISTORY:
 	Began 2004-04-23 17:48:23 by Marshall Perrin 

(See sources/mode.pro)


POISS

[Previous Routine] [Next Routine] [List of Routines]
(See sources/poiss.pro)

 NAME: poiss
 PURPOSE:
 	Computes the Poisson distribution as
 	a function of X and M.

 INPUTS:
 	X	Independent variable. Can be an array, can have fractions.
 	M	Rate for the Poisson distribution. Must be scalar
 KEYWORDS:
 OUTPUTS:

 HISTORY:
 	Began 2004-09 by Marshall Perrin 

(See sources/poiss.pro)


MONTECARLO_MEAN

[Previous Routine] [Next Routine] [List of Routines]
(See sources/montecarlo_mean.pro)

 NAME: montecarlo_mean
 PURPOSE:
 	given a set of numbers, uses monte-carlo methods to determine
 	both the mean and the standard deviation of the mean.

 INPUTS:
 	data	a set of data
 KEYWORDS:
 	ntrials number of monte carlo trials [default = 100]
 OUTPUTS:
 	mean		mean of the data
 	medstddev	stddev of the mean

 HISTORY:
 	Began 2002-08-16 15:17:37 by Marshall Perrin 

(See sources/montecarlo_mean.pro)


MONTECARLO_MEDIAN

[Previous Routine] [Next Routine] [List of Routines]
(See sources/montecarlo_median.pro)

 NAME: montecarlo_median
 PURPOSE:
 	given a set of numbers, uses monte-carlo methods to determine
 	both the median and the standard deviation of the median.

 INPUTS:
 	data	a set of data
 KEYWORDS:
 	ntrials number of monte carlo trials [default = 100]
 OUTPUTS:
 	median		median of the data
 	medstddev	stddev of the median

 HISTORY:
 	Began 2002-08-16 15:17:37 by Marshall Perrin 

(See sources/montecarlo_median.pro)


PRODUCT_ERRPROP

[Previous Routine] [List of Routines]
(See sources/product_errprop.pro)

 NAME: product_errprop.pro
 PURPOSE:
 	Implements the error propagation formula for the product of two
 	numbers, assumed to have no correlation

 INPUTS:
 KEYWORDS:
 OUTPUTS:

 HISTORY:
 	Began 2002-10-15 17:33:28 by Marshall Perrin 

(See sources/product_errprop.pro)


Category: Misc

[List of Routines]


FIND_CLOSEST

[Next Routine] [List of Routines]
(See sources/find_closest.pro)

 NAME: find_closest

 PURPOSE:
 	Given an array, find the index whose value in that
 	array is closest to a given number.

 INPUTS:
 KEYWORDS:
 	range=		2 element array. Restrict the search to this range of values.
 	/value		don't return the index, return the actual closest value.
 OUTPUTS:

 HISTORY:
 	Began 2005-04-20 14:04:49 by Marshall Perrin 
 	2008-10-24 added value= keyword

(See sources/find_closest.pro)


FIND_FWXM

[Previous Routine] [Next Routine] [List of Routines]
(See sources/find_fwxm.pro)

 NAME: find_fwXm

 PURPOSE:
 	Find the full width at X*max. 
 	i.e. X = 0.5 for FWHM.

 INPUTS:
 KEYWORDS:
	/plot		Make a convenient plot showing the curve and
				the points which are found
 OUTPUTS:

 HISTORY:
 	Began 2005-05-04 14:24:42 by Marshall Perrin 
 	2008-02-15	Added /plot option

(See sources/find_fwxm.pro)


FINDLOCALMAX

[Previous Routine] [Next Routine] [List of Routines]
(See sources/findlocalmax.pro)

 NAME:
   findlocalmax

 PURPOSE:
   Find local maximum near given position in image

 CALLING SEQUENCE:
   maxind = findlocalmax(im, ind, boxsize=)

 INPUTS:
   im      - image 
   ind     - 1-D index of pixel in image

 KEYWORD PARAMETERS:
   boxsize - size of box in which to explore, in pixels.  (default 15)

 OUTPUTS:
   returns maxind, 1-D index of local max near input ind

 COMMENTS:
   Uses 1-D index of a 2-D array, i.e. 0 < ind < N*M-1 for NxM image.
   This algorithm searches a box of size boxsize x boxsize centered
   on pixel ind, finding the max within that box.  This iterates
   until the maximum pixel no longer moves.  Boxsize should be bigger
   than the typical cosmic ray size, but much smaller than the
   typical distance between cosmic rays (and other objects). 

 MODIFICATION HISTORY:
   2000 Oct 4 - written by D. Finkbeiner
   2001 07 25 - keyword silent added. MDP
   2001 07 26 - modified to accept x,y instead of 1-d index by default. MDP

(See sources/findlocalmax.pro)


MRECENTER

[Previous Routine] [Next Routine] [List of Routines]
(See sources/mrecenter.pro)

 NAME: mrecenter 

 PURPOSE:
	Find precise center for a star, like RECENTER, but using
	MPFITPEAK to do the peak fitting.

 INPUTS:
 KEYWORDS:
 	/moffat, /lorentz, /gauss		what type of function to fit?
 									see MPFIT2DPEAK for details
 	/silent
 	/nodisp
 OUTPUTS:

 HISTORY:
 	Began 2006-08-03 16:41:26 by Marshall Perrin 

(See sources/mrecenter.pro)


WHEREISMAX

[Previous Routine] [Next Routine] [List of Routines]
(See sources/whereismax.pro)

 NAME:  whereismax

 PURPOSE: 
 	Given an array, returns location and value of max pixel

 INPUTS:

 	pro Whereismax, image, x, y, maxv, mark=mark, silent=silent,single=single


 note that this will return a long integer if there is
 a unique max pixel, otherwise it will return an long array
 which may be a problem for some routines

 10/31/94 MCL

 added mark feature, which will draw a cross at the max
 pixel on the current window
 8/19/96 MCL

 uses a square instead of a circle for /mark
 06/22/00 MCL
 Added "single" keyword to always return only one value. If multiple
  points have the same max, return only the first
 2001-07-06 MDP

 2003-03-04 MDP 	added /NaN keyword to max

(See sources/whereismax.pro)


WHEREIS

[Previous Routine] [Next Routine] [List of Routines]
(See sources/whereis.pro)

 NAME: whereis

 PURPOSE:
   Given the 1-d index of a pixel in an array, return the
   x and y coordinates corresponding to that pixel.


 NOTES:
  pro whereis,image,w,x,y

 given the index of a pixel in an array return the
 x and y value

 jrg/ucb 94/8/16
 
 if only one pixel, then return scalars rather than vectors
 4/16/96 MCL

(See sources/whereis.pro)


ATV

[Previous Routine] [Next Routine] [List of Routines]
(See sources/atv.pro)


 NAME:
       ATV
 
 PURPOSE: 
       Interactive display of 2-D or 3-D images.

 CATEGORY: 
       Image display.

 CALLING SEQUENCE:
       atv [,array_name OR fits_file] [,min = min_value] [,max=max_value] 
           [,/linear] [,/log] [,/histeq] [,/asinh] [,/block]
           [,/align] [,/stretch] [,header = header]

 REQUIRED INPUTS:
       None.  If atv is run with no inputs, the window widgets
       are realized and images can subsequently be passed to atv
       from the command line or from the pull-down file menu.

 OPTIONAL INPUTS:
       array_name: a 2-D or 3-D data array to display
          OR
       fits_file:  a fits file name, enclosed in single quotes

 KEYWORDS:
       min:        minimum data value to be mapped to the color table
       max:        maximum data value to be mapped to the color table
       linear:     use linear stretch
       log:        use log stretch 
       histeq:     use histogram equalization
       asinh:      use asinh stretch
       block:      block IDL command line until ATV terminates
       align:      align image with previously displayed image
       stretch:    keep same min and max as previous image
       header:     FITS image header (string array) for use with data array
       
 OUTPUTS:
       None.  
 
 COMMON BLOCKS:
       atv_state:  contains variables describing the display state
       atv_images: contains the internal copies of the display image
       atv_color:  contains colormap vectors
       atv_pdata:  contains plot and text annotation information

 RESTRICTIONS:
       Requires IDL version 6.0 or greater.
       Requires Craig Markwardt's cmps_form.pro routine.
       Requires the GSFC IDL astronomy user's library routines.
       Some features may not work under all operating systems.

 EXAMPLE:
       To start atv running, just enter the command 'atv' at the idl
       prompt, either with or without an array name or fits file name 
       as an input.  Only one atv window will be created at a time,
       so if one already exists and another image is passed to atv
       from the idl command line, the new image will be displayed in 
       the pre-existing atv window.

 MODIFICATION HISTORY:
       Written by Aaron J. Barth, with contributions by 
       Douglas Finkbeiner, Michael Liu, David Schlegel,
       Wesley Colley, Jim Brauher, and Marshall Perrin.  
       First released 17 December 1998.

		 ***** DISCLAIMER ***** DISCLAIMER ***** DISCLAIMER *****

			This is a highly modified version of atv! It's probably
			buggy, and you use it at your own risk. Questions, comments
			and complaints should go to Marshall Perrin,
			mperrin@astro.berkeley.edu, and NOT to Aaron Barth.

		 ***** DISCLAIMER ***** DISCLAIMER ***** DISCLAIMER *****


       This version is 2.0pre1-MP, which contain's Marshall Perrin and Henry
       Roe's modifications to ATV 1.3, merged into Aaron Barth's 
       release 1.5 of 11 Aug 2004, and then with Jim Brauher's version 2.0.
       2006-12-17: And then *again* partially merged with Aaron Barth's 2.0pre1
       	(but not entirely...)
       2008-10-06: Partial merge with Aaron Barth's 2.0pre4
      
      	The most notable additions by Marshall Perrin:
      		- Preserves users colormap and !p.multi for external windows
      		- Polarimetry vector field overplotting
      		- 'Measure' mouse mode to measure distances
      		- Better support for NaNs to indicate missing pixels
      		- FITS reading code allows loading multiple files from disk to a
      		  datacube (files must all be the same size)
      		- Option for having a different title extra ("name") for each image
      		  in a cube. Set via names= keyword argument.
      		- Image blinking also blinks the titles.
      		- Added SQRT, ASINH stretches. 
      			See Lupton et al. AJ 118, 1406-1410	for more info on ASINH
      			stretch
      			WARNING - ASINH implementation is different from the ATV 2.0b4
      			version
   	    - Added code to preserve user's device decomposition setting.
   	    - Additional / modified keyboard shortcuts
   	    - keyboard shortcuts work while mouse button down (i.e. during
   	       vector mode) 
   	    - Can save image to IDL main-level variable (code due to D. Fanning)

       For the most current version, revision history, instructions,
       list of known bugs, and further information, go to:
              http://www.physics.uci.edu/~barth/atv
 

(See sources/atv.pro)


ATVMAKEMOVIE

[Previous Routine] [List of Routines]
(See sources/atvmakemovie.pro)

 NAME: atvmakemovie
 PURPOSE:
   create a movie from an image stack in ATV. 

 USAGE:
 	Load a 3d data cube into ATV. get the color table set the way you want it.
 	This command will iterate through every frame of the data cube and write
 	it to disk as a PNG file, suitable for combining into an animation via
 	'convert' or the like.

 INPUTS:
 KEYWORDS:
 OUTPUTS:

 HISTORY:
 	Began 2004-08-27 16:45:51 by Marshall Perrin 

(See sources/atvmakemovie.pro)


Category: Plotting

[List of Routines]


DRDPIX

[Next Routine] [List of Routines]
(See sources/drdpix.pro)

 NAME:
	DRDPIX

	Exactly like rdpix, except uses data coordinates rather than device
	coordinates.

 PURPOSE:
	Interactively display the X position, Y position, and pixel value
	of the cursor.

 CATEGORY:
	Image display.

 CALLING SEQUENCE:
	RDPIX, Image [, X0, Y0]

 INPUTS:
	Image:	The array that represents the image being displayed.  This
		array may be of any type.  Rather reading pixel values from
		the display, they are taken from this parameter, avoiding
		scaling difficulties.

 OPTIONAL INPUT PARAMETERS:
	X0, Y0:	The location of the lower-left corner of the image area on
		screen.  If these parameters are not supplied, they are
		assumed to be zero.

 OUTPUTS:
	None.

 COMMON BLOCKS:
	None.

 SIDE EFFECTS:
	The X, Y, and value of the pixel under the cursor are continuously
	displayed.

 RESTRICTIONS:
	None.

 PROCEDURE:
	Instructions are printed and the pixel values are printed as the
	cursor is moved over the image.

	Press the left or center mouse button to create a new line of output,
	saving the previous line.

	Press the right mouse button to exit the procedure.

 MODIFICATION HISTORY:
	DMS, Dec, 1987.
	Rob Montgomery (rob@hao.ucar.edu), 9/21/92;
		Correct indices for case of !order = 1
	2002-04-19 Marshall Perrin. Renamed to DRDPIX (for "display" read pix)
		and modified to use normalized coordinates.
		

(See sources/drdpix.pro)


HOR

[Previous Routine] [Next Routine] [List of Routines]
(See sources/hor.pro)

 NAME:
       HOR
 PURPOSE:
       Plot a horizontal line on a graph at specified y value.
 CATEGORY:
 CALLING SEQUENCE:
       hor, y
 INPUTS:
       y = Y value of horizontal line.  Scalar or array.    in
 KEYWORD PARAMETERS:
       Keywords:
         /DEVICE means work in device coordinates.
         /NORMALIZED means work in normalized coordinates.
           Default is data coordinates.
         LINESTYLE=s.  Linestyle (def=!p.linestyle).
         COLOR=c.      Line color (def=!p.color).
         THICKNESS=t   Line thickness (def=!p.thick).
         FILL=clr        Optional color to fill between line pairs.
           Fills between lines 0 and 1, 2 and 3, and so on.
         POINTER=pt      Draw arrowhead pointers at left and right
           instead of lines.  Arrowhead dimensions may be given as
           fraction of screen or plot window size, the value of
           pt is height, or [height, width].  For /pointer the
           default used is [.03,.03].
         /LEFT  used with POINTER to plot left pointers only.
         /RIGHT  used with POINTER to plot right pointers only.
 OUTPUTS:
 COMMON BLOCKS:
 NOTES:
       Notes: see ver.
 MODIFICATION HISTORY:
       R. Sterner, 2 Aug, 1989.
       R. Sterner, 21 May, 1992 --- fixed for log X axes.
       R. Sterner,  3 Nov, 1992 --- Added /device.
       R. Sterner, 20 Jun, 1993 --- Added /normalized.
       R. Sterner,  1994 Feb  2 --- Added THICK.
       R. Sterner, 1994 Jun 3 --- Added FILL.
       R. Sterner, 1994 Jun 16 --- Added POINTER, /TOP, /BOTTOM.

 Copyright (C) 1989, Johns Hopkins University/Applied Physics Laboratory
 This software may be used, copied, or redistributed as long as it is not
 sold and this copyright notice is reproduced on each copy made.  This
 routine is provided as is without any express or implied warranties
 whatsoever.  Other limitations apply as described in the file disclaimer.txt.

(See sources/hor.pro)


LABELOPLOT

[Previous Routine] [Next Routine] [List of Routines]
(See sources/labeloplot.pro)

 NAME:  labeloplot

PURPOSE:
 	Like oplot, but labels the plot with some text string as well.
 USAGE:
 	labeloplot, x,y,label,_extra=_extra,xoffset=xoffset,yoffset=yoffset

 INPUTS:
 	x,y			X and Y values of the line to plot
 	label0		label text to annotate it with
 KEYWORDS:
 	xoffset=, yoffset=	X and Y offset for the label text, relative to the line.
 						default is 1/50 of the total size of the plot. 
 						NOTE: this default won't work well for log plots, 
 						due to how IDL handles the !x.crange for logs, so set
 						the offset manually for log plots.
 	label=		another way of specifying the label text. Redundant, but
 				included for back-compatibility.
 	xlocation=	X value for overplotting the label. Default is the maximum
 				of the line.
 
 OUTPUTS:

 HISTORY:
 	Began summer 2005 by Marshall Perrin 
 	Documentation added 2007-01-16.

(See sources/labeloplot.pro)


LOGHIST2D

[Previous Routine] [Next Routine] [List of Routines]
(See sources/loghist2d.pro)

 NAME: loghist2d 
 PURPOSE:
	Wrapper for hist2d which allows logarithmic bins and some other options

 INPUTS:
 	v1, v2				two arrays.
 KEYWORDS:
 	/log1, /log2		use log scaling
 	bin1=, bin2=		bin size
 	nbins1=, nbins2=	number of bins
 OUTPUTS:
 	binval1=, binval2=		return the bin values.

 HISTORY:
 	Began 2007-03-21 11:15:44 by Marshall Perrin 

(See sources/loghist2d.pro)


SAVEPLOT

[Previous Routine] [Next Routine] [List of Routines]
(See sources/saveplot.pro)

 NAME: saveplot
PURPOSE:
 	save a plot to disk in PNG format

 INPUTS:
 KEYWORDS:
 OUTPUTS:

 HISTORY:
 	Began 2004-05-14 13:52:06 by Marshall Perrin 

(See sources/saveplot.pro)


VER

[Previous Routine] [Next Routine] [List of Routines]
(See sources/ver.pro)

 NAME:
       VER
 PURPOSE:
       Plot a vertical line on a graph at specified x value.
 CATEGORY:
 CALLING SEQUENCE:
       ver, x
 INPUTS:
       x = X value of vertical line. Scalar or array.    in
 KEYWORD PARAMETERS:
       Keywords:
         /DEVICE means work in device coordinates.
         /NORMALIZED means work in normalized coordinates.
           Default is data coordinates.
         LINESTYLE=s.    Linestyle (def=!p.linestyle).
         COLOR=c.        Line Color (def=!p.color).
         THICKNESS=thk   Line thickness (def=!p.thick).
         FILL=clr        Optional color to fill between line pairs.
           Fills between lines 0 and 1, 2 and 3, and so on.
         POINTER=pt      Draw arrowhead pointers at top and bottom
           instead of lines.  Arrowhead dimensions may be given as
           fraction of screen or plot window size, the value of
           pt is height, or [height, width].  For /pointer the
           default used is [.03,.03].
         /BOTTOM  used with POINTER to plot bottom pointers only.
         /TOP  used with POINTER to plot top pointers only.
 OUTPUTS:
 COMMON BLOCKS:
 NOTES:
       Note: see hor.
 MODIFICATION HISTORY:
       R. Sterner, 2 Aug, 1989.
       R. Sterner, 21 May, 1992 --- fixed for log Y axes.
       R. Sterner,  3 Nov, 1992 --- Added /device.
       R. Sterner, 27 Jan, 1993 --- dropped reference to array.
       R. Sterner 20 Jun, 1993 --- added /norm.
       R. Sterner 1994 Feb 2 --- Add THICK.
       R. Sterner, 1994 Jun 3 --- Added FILL.
       R. Sterner, 1994 Jun 16 --- Added POINTER.

 Copyright (C) 1989, Johns Hopkins University/Applied Physics Laboratory
 This software may be used, copied, or redistributed as long as it is not
 sold and this copyright notice is reproduced on each copy made.  This
 routine is provided as is without any express or implied warranties
 whatsoever.  Other limitations apply as described in the file disclaimer.txt.

(See sources/ver.pro)


ALLSKYPLOT

[Previous Routine] [Next Routine] [List of Routines]
(See sources/allskyplot.pro)

 NAME: allskyplot
 PURPOSE:
 	plot some points on the whole sky

 INPUTS:
 KEYWORDS:
 	/usecolor	read another column from the database and use this to set
 				the color for each object. Use this for plotting survey
 				completion status!
 	color=		use this specific color
				if both /usecolor and color= are set, then /usecolor takes
				priority.
 	
 	/overplot	Just overplot the stars
 	/ps			plot to a postscript file
 	/label		Write the star names next to the stars as labels. 
 	declimit=	Declination limit. Default = -30 (Lick)
 OUTPUTS:

 HISTORY:
 	Began 2004-08-26 17:34:39 by Marshall Perrin 
 	2005-07-11  /overplot option added.
 	2005-07-12	color handling improved

(See sources/allskyplot.pro)


RADECGRID

[Previous Routine] [Next Routine] [List of Routines]
(See sources/radecgrid.pro)

 NAME:
       radecgrid
 PURPOSE:
 		 draw a grid of lines of constant RA and Dec.
 EXPLANATION:

 		Based on imcontour.pro from the Goddard library, this routine will
 		draw a grid of lines at constant RA and dec across the image. 

       The type of coordinate display is controlled by the keyword TYPE
       Set TYPE=0 (default) to measure distances from the center of the image
       (IMCONTOUR will decide whether the plotting units will be in
       arc seconds, arc minutes, or degrees depending on image size.)
       Set /TYPE for standard RA and Dec labeling

 CALLING SEQUENCE
       IMCONTOUR, im, hdr,[ /TYPE, /PUTINFO, XDELTA = , YDELTA =, _EXTRA = 
                            XMID=, YMID= ]

 INPUTS:
       IM - 2-dimensional image array
       HDR - FITS header associated with IM, string array, must include
               astrometry keywords.   IMCONTOUR will also look for the
               OBJECT and IMAGE keywords, and print these if found and the 
               PUTINFO keyword is set.

 OPTIONAL PLOTTING KEYWORDS:
       /TYPE - the type of astronomical labeling to be displayed.   Either set
               TYPE = 0 (default), distance to center of the image is
               marked in units of Arc seconds, arc minutes, or degrees

               TYPE = 1 astronomical labeling with Right ascension and 
               declination.

       XDELTA, YDELTA - Integer scalars giving spacing of labels for TYPE=1.  
               Default is to label every major tick (XDELTA=1) but if 
               crowding occurs, then the user might wish to label every other
               tick (XDELTA=2) or every third tick (XDELTA=3)

       XMID, YMID - Scalars giving the X,Y position from which offset distances
               will be measured when TYPE=0.   By default, offset distances 
               are measured from the center of the image.

 NOTES:
       (1) The contour plot will have the same dimensional ratio as the input
               image array
 EXAMPLE:
       Overlay the contour of an image, im2, with FITS header, h2, on top
       of the display of a different image, im1.   Use RA, Dec labeling, and
       seven equally spaced contour levels.    The use of a program like
       David Fanning's TVIMAGE  http://www.dfanning.com/programs/tvimage.pro
       is suggested to properly overlay plotting and image coordinates.  The
       /Keep_aspect_ratio keyword must be used.

       IDL> tvimage,im1,/keep_aspect, position = pos
       IDL> imcontour,im2,h2,nlevels=7,/Noerase,/TYPE,position = pos

 PROCEDURES USED:
       CHECK_FITS, EXTAST, GETROT, TICPOS, TICLABEL, TIC_ONE, TICS, XYAD
       CONS_RA(), CONS_DEC(), ADSTRING()

 REVISION HISTORY:
 		Split from May 2003 version of imcontour.pro
 				M. Perrin								July 2003
       

(See sources/radecgrid.pro)


WIN

[Previous Routine] [Next Routine] [List of Routines]
(See sources/win.pro)

 PURPOSE: 
 create IDL plot windows displayed in rows in a nice tiled fashion.
 NOTES:
 default size is 256 x 256

 program is optimized for my workstation & monitor!
 
 INPUTS
  num    window number to open
 
 OPTIONAL KEYWORD INPUTS
  title  title string for the window
  xsize  xsize
  ysize  ysize
  xpos,ypos	position of the window.
  sz     edge size for a square window
  /small  adjusted for 17" monitor (20" is default)
  /land	Landscape mode
  /keep	If a window with this number is already open,
  			just use it rather than opening a new one.
 /max		open up a really large window
 /external	open the really large window on the external monitor, and
 			make it even larger

 USES
   strc
 
 Written by M. Liu (UCB): 1995?
 12/22/99 MCL: added /land (nice size for plots)
 04/16/00 MCL: can now pass 'sz' as parameter also
 10/11/02 MDP: Added /keep parameter
 2003-12-13 MDP: Don't do a retall if called incorrectly, goddamit!
 2006-08-22 MDP: added /MAX

(See sources/win.pro)


MULTIPLOT

[Previous Routine] [Next Routine] [List of Routines]
(See sources/multiplot.pro)

 NAME:
	MULTIPLOT
 PURPOSE:
	Create multiple plots with shared axes.
 EXPLANATION:
	This procedure makes a matrix of plots with *SHARED AXES*, either using
	parameters passed to multiplot or !p.multi in a non-standard way.
	It is good for data with one or two shared axes and retains all the
	versatility of the plot commands (e.g. all keywords and log scaling).
	The plots are connected with the shared axes, which saves space by
	omitting redundant ticklabels and titles.  Multiplot does this by
	setting !p.position, !x.tickname and !y.tickname automatically.
	A call (multiplot,/reset) restores original values.

	New: The COLSPACING and ROWSPACING parameters allow you to join plots
		 along one axis while leaving space along the other axis. Labels are
		 still suppressed as usual, even if space is left.

	Note: This method may be superseded by future improvements in !p.multi
	by RSI.  For now, it's a good way to gang plots together.
 CALLING SEQUENCE:
	multiplot[pmulti][,/help][,/initialize][,/reset][,/rowmajor]
 EXAMPLES:
	multiplot,/help			; print this header.
	; Then copy & paste, from your xterm, the following lines to test:

	x = findgen(100)		;	   MULTIPLOT
	t=exp(-(x-50)^2/300)		;	 -------------------------
	erase				;	 |           |           |
	u=exp(-x/30)			;	 |           |           |
	y = sin(x)			;	 |  UL plot  |  UR plot  |
	r = reverse(y*u)		;	 |           |           |
	!p.multi=[0,2,2,0,0]		;	 |           |           |
	multiplot 	 		;	y-------------------------
	plot,x,y*u,title='MULTIPLOT'	;	l|           |           |
	multiplot & plot,x,r 		;	a|           |           |
	multiplot 			;	b|  LL plot  |  LR plot  |
	plot,x,y*t,ytit='ylabels'	;	e|           |           |
	multiplot 			;	l|           |           |
	plot,x,y*t,xtit='xlabels'	;	s-------------------------
	multiplot,/reset		;		        xlabels
					 
	wait,2 & erase			;		 TEST
	multiplot,[1,3]			;	H------------------------
	plot,x,y*u,title='TEST'		;	E|	plot #1		|
	multiplot			;	I------------------------
	plot,x,y*t,ytit='HEIGHT'	;	G|	plot #2 	|
	multiplot			;	H------------------------
	plot,x,r,xtit='PHASE'		;	T|	plot #3		|
	multiplot,/reset		;	 ------------------------
					;		 PHASE

	multiplot,[1,1],/init,/verbose	; one way to return to single plot
	% MULTIPLOT: Initialized for 1x1, plotted across then down (column major).
 OPTIONAL INPUTS:
	pmulti = 2-element or 5-element vector giving number of plots, e.g.,
	  multiplot,[1,6]		; 6 plots vertically
	  multiplot,[0,4,2,0,0]		; 4 plots along x and 2 along y
	  multiplot,[0,4,2,0,1]		; ditto, except rowmajor (down 1st)
	  multiplot,[4,2],/rowmajor 	; identical to previous line
 OPTIONAL KEYWORDS:
	help = flag to print header
	initialize = flag to begin only---no plotting, just setup,
	  e.g., multiplot,[4,2],/init,/verbose & multiplot & plot,x,y
	reset = flag to reset system variables to values prior to /init
	default = flag to restore IDL's default value for system variables
	rowmajor = flag to number plots down column first (D=columnmajor)
	verbose = flag to output informational messages
	colspacing, rowspacing = set margins betweel columns and rows. 
		These should be fractions between 0 (the default) and 1, and
		indicate how much space to leave between columns and rows, 
		defined as a fraction of the size of a column or row.
 Outputs:
	!p.position = 4-element vector to place a plot
	!x.tickname = either '' or else 30 ' ' to suppress ticknames
	!y.tickname = either '' or else 30 ' ' to suppress ticknames
	!p.noerase = 1
 Common blocks:
	multiplot---to hold saved variables and plot counter.  See code.
 Side Effects:
	Multiplot sets a number of system variables: !p.position, !p.multi,
	!x.tickname, !y.tickname, !P.noerase---but all can be reset with
	the call: multiplot,/reset
 RESTRICTIONS:
	1. If you use !p.multi as the method of telling how many plots
	are present, you have to set !p.multi at the beginning each time you
	use multiplot or call multiplot with the /reset keyword.
	2. There's no way to make an xtitle or ytitle span more than one plot,
	except by adding spaces to shift it or to add it manually with xyouts.
	3. There is no way to make plots of different sizes; each plot
	covers the same area on the screen or paper.
 PROCEDURE:
	This routine makes a matrix of plots with common axes, as opposed to
	the method of !p.multi where axes are separated to allow labels.
	Here the plots are joined and labels are suppressed, except at the
	left edge and the bottom.  You tell multiplot how many plots to make
	using either !p.multi (which is then reset) or the parameter pmulti.
	However, multiplot keeps track of the position by itself because
	!p.multi interacts poorly with !p.position.
 MODIFICATION HISTORY:
	write, 21-23 Mar 94, Fred Knight (knight@ll.mit.edu)
	alter plot command that sets !x.window, etc. per suggestion of
	  Mark Hadfield (hadfield@storm.greta.cri.nz), 7 Apr 94, FKK
	add a /default keyword restore IDL's default values of system vars,
	  7 Apr 94, FKK
	modify two more sys vars !x(y).tickformat to suppress user-formatted
	  ticknames, per suggestion of Mark Hadfield (qv), 8 Apr 94, FKK
	Converted to IDL V5.0   W. Landsman   September 1997
   Added colspacing, rowspacing keywords.    M. Perrin		2003 October
   Added extramargins keyword 				  M. Perrin 	2007 June
	

(See sources/multiplot.pro)


ARROWS2

[Previous Routine] [Next Routine] [List of Routines]
(See sources/arrows2.pro)

 NAME:
      ARROWS2
 PURPOSE:
   overplot an arrow on an image at a given position and angle.
 NOTES:
	Like Goddard's ARROWS.PRO, except this takes a user-specified angle
	rather than a FITS astrometry header. Modified from ARROWS.PRO by
	Marshall Perrin. 2004-09-29
      
 PURPOSE:
      To display "weathervane" directional arrows on an astronomical image 
 EXPLANATION:
      Overlays a graphic showing orientation of North and East.

 CALLING SEQUENCE:
      ARROWS,h, [ xcen, ycen, ARROWLEN= , CHARSIZE=  COLOR= , /DATA
                              FONT=, /NORMAL, /NOTVERTEX, THICK=  ]

 INPUTS:
       h - FITS or STSDAS header array, must include astrometry

 OPTIONAL INPUTS:
       xcen,ycen - numeric scalars, specifying the center position of
		arrows.   Position in device units unless the /NORMALIZED 
		keyword is specified.   If not supplied, then ARROWS
		will prompt for xcen and ycen

 OPTIONAL KEYWORD INPUTS:
       arrowlen  - length of arrows in terms of normal Y size of vector-drawn
                     character,  default  = 3.5, floating point scalar
       charsize  - character size, default = 2.0, floating point scalar
       color     - color that the arrows and NE letters should be.  Default
                    value is !P.COLOR
       Data - if this keyword is set and nonzero, the input center (xcen,
                 ycen) is understood to be in data coordinates
       font - IDL vector font number (1-20) to use to display NE letters.
                 For example, set font=13 to use complex italic font.
       NotVertex - Normally (historically) the specified xcen,ycen indicated
                   the position of the vertex of the figure.  If this
                   keyword is set, the xcen,ycen coordinates refer to a sort
                   of 'center of mass' of the figure.  This allows the
                   figure to always appear with the area irregardless of
                   the rotation angle.
       Normal - if this keyword is set and nonzero, the input center 
                (xcen,ycen) is taken to be in normalized coordinates.   The
                default is device coordinates.
       thick     - line thickness, default = 2.0, floating point scalar
 OUTPUTS:
       none
 EXAMPLE:
       Draw a weathervane at (400,100) on the currently active window, 
       showing the orientation of the image associated with a FITS header, hdr

       IDL> arrows, hdr, 400, 100

 METHOD:
       Uses EXTAST to EXTract ASTrometry from the FITS header.   The 
       directions of North and East are computed and the procedure
       ONE_ARROW called to create the "weathervane".

 PROCEDURES USED:
       GETROT - Computes rotation from the FITS header
       ONE_ARROW - Draw a labeled arrow	
       ZPARCHECK
 REVISON HISTORY:
       written by B. Boothman 2/5/86 
       Recoded with new procedures ONE_ARROW, ONE_RAY.  R.S.Hill,HSTX,5/20/92
       Added separate determination for N and E arrow to properly display
         arrows irregardless of handedness or other peculiarities and added
         /NotVertex keyword to improve positioning of figure. E.Deutsch 1/10/93
       Added /DATA and /NORMAL keywords W. Landsman      July 1993
       Recognize GSSS header    W. Landsman       June 1993
       Added /FONT keyword W. Landsman           April 1995
       Modified to work correctly for COLOR=0  J.Wm.Parker, HITC   1995 May 25
       Work correctly for negative CDELT values   W. Landsman   Feb. 1996
       Converted to IDL V5.0   W. Landsman   September 1997
       Use GETROT to compute rotation   W. Landsman    June 2003
       Restored /NotVertex keyword which was not working after June 2003 change
                  W. Landsman  January 2004


      --- Split out to arrows2.pro by M. Perrin ---
      2006-03-23 default charsize is now !p.charsize, not 2.

(See sources/arrows2.pro)


DRAWSCALEBAR

[Previous Routine] [Next Routine] [List of Routines]
(See sources/drawscalebar.pro)

 NAME: drawscalebar
 PURPOSE:
 	Draw a scalebar on an image.
 NOTES:
	Requires the data coordinates to be set up in ARCSECONDS for this 
	to work properly

 INPUTS:
 	au		how many AU long the scale bar should be
 	distance	distance to the source (sets AU to arcsec conversion)
 KEYWORDS:
 OUTPUTS:

 HISTORY:
 	Began 2004-5-24 by Marshall Perrin 
 	Documentation added long after the fact, 2005-04-19

(See sources/drawscalebar.pro)


GETWHITE

[Previous Routine] [Next Routine] [List of Routines]
(See sources/getwhite.pro)

 NAME: getwhite 
 PURPOSE:
 	return color table index for white, in either X or postscript mode.
 INPUTS:
 KEYWORDS:
 OUTPUTS:

 HISTORY:
 	Began 2005-10-06 20:34:30 by Marshall Perrin 

(See sources/getwhite.pro)


IMCONTOUR

[Previous Routine] [Next Routine] [List of Routines]
(See sources/imcontour.pro)

 NAME:
       IMCONTOUR
 PURPOSE:
       Make a contour plot labeled with astronomical coordinates.
 EXPLANATION:
       The type of coordinate display is controlled by the keyword TYPE
       Set TYPE=0 (default) to measure distances from the center of the image
       (IMCONTOUR will decide whether the plotting units will be in
       arc seconds, arc minutes, or degrees depending on image size.)
       Set /TYPE for standard RA and Dec labeling

       By using the /NODATA keyword, IMCONTOUR can also be used to simply
       provide astronomical labeling of a previously displayed image.
 CALLING SEQUENCE
       IMCONTOUR, im, hdr,[ /TYPE, /PUTINFO, XDELTA = , YDELTA =, _EXTRA = 
                            XMID=, YMID= ]

 INPUTS:
       IM - 2-dimensional image array
       HDR - FITS header associated with IM, string array, must include
               astrometry keywords.   IMCONTOUR will also look for the
               OBJECT and IMAGE keywords, and print these if found and the 
               PUTINFO keyword is set.

 OPTIONAL PLOTTING KEYWORDS:
       /TYPE - the type of astronomical labeling to be displayed.   Either set
               TYPE = 0 (default), distance to center of the image is
               marked in units of Arc seconds, arc minutes, or degrees

               TYPE = 1 astronomical labeling with Right ascension and 
               declination.

       /PUTINFO - If set, then IMCONTOUR will add information about the image
               to the right of the contour plot.  Information includes image
               name, object, image center, image center, contour levels, and
               date plot was made

       XDELTA, YDELTA - Integer scalars giving spacing of labels for TYPE=1.  
               Default is to label every major tick (XDELTA=1) but if 
               crowding occurs, then the user might wish to label every other
               tick (XDELTA=2) or every third tick (XDELTA=3)

       XMID, YMID - Scalars giving the X,Y position from which offset distances
               will be measured when TYPE=0.   By default, offset distances 
               are measured from the center of the image.

       /SKYCOORDS - If set, define DATA coordinates using the FITS header
               astrometry information (i.e in arcseconds). By default, 
               DATA coordinates are set in units of pixels.

       Any keyword accepted by CONTOUR may also be passed through IMCONTOUR
       since IMCONTOUR uses the _EXTRA facility.     IMCONTOUR uses its own
       defaults for the XTITLE, YTITLE XMINOR, YMINOR, and SUBTITLE keywords
       but these may be overridden.

 NOTES:
       (1) The contour plot will have the same dimensional ratio as the input
           image array
       (2) To contour a subimage, use HEXTRACT before calling IMCONTOUR
       (3) Use the /NODATA keyword to simply provide astronomical labeling
           of a previously displayed image.
       (4) The IMCONTOUR display currently does not indicate the image 
           rotation in any way, but only specifies coordinates along the 
           edges of the image 

 EXAMPLE:
       Overlay the contour of an image, im2, with FITS header, h2, on top
       of the display of a different image, im1.   Use RA, Dec labeling, and
       seven equally spaced contour levels.    The use of a program like
       David Fanning's TVIMAGE  http://www.dfanning.com/programs/tvimage.pro
       is suggested to properly overlay plotting and image coordinates.  The
       /Keep_aspect_ratio keyword must be used.

       IDL> tvimage,im1,/keep_aspect, position = pos
       IDL> imcontour,im2,h2,nlevels=7,/Noerase,/TYPE,position = pos

 PROCEDURES USED:
       CHECK_FITS, EXTAST, GETROT, TICPOS, TICLABEL, TIC_ONE, TICS, XYAD
       CONS_RA(), CONS_DEC(), ADSTRING()

 REVISION HISTORY:
       Written   W. Landsman   STX                    May, 1989
       Fixed RA,Dec labeling  W. Landsman             November, 1991
       Fix plottting keywords  W.Landsman             July, 1992
       Recognize GSSS headers  W. Landsman            July, 1994
       Removed Channel keyword for V4.0 compatibility June, 1995
       Add _EXTRA CONTOUR plotting keywords  W. Landsman  August, 1995
       Add XDELTA, YDELTA keywords  W. Landsman   November, 1995
       Use SYSTIME() instead of !STIME                August, 1997
       Remove obsolete !ERR system variable W. Landsman   May 2000 
       Added XMID, YMID keywords to specify central position (default is still
          center of image)  W. Landsman               March 2002     
       Recognize Galactic coordinates, fix Levels display when /PUTINFO set
           W. Landsman                May 2003
       Correct conversion from seconds of RA to arcmin is 4 not 15.
       	M. Perrin					July 2003
       Fix integer truncation which appears with tiny images WL  July 2004
       Set up data coordinates properly after plotting. M. Perrin Sept 2005
       

(See sources/imcontour.pro)


IMDISP_GETAXES

[Previous Routine] [Next Routine] [List of Routines]
(See sources/imdisp_getaxes.pro)

 NAME: imdisp_getaxes 
 PURPOSE:
	create arrays with axes values for use with IMDISP 
 NOTES:

	By default, if the axes span more than 120 units, they are divided
	by 60 (i.e. converted into arcmin instead of arcsec)

 INPUTS:
 	image		an image
 INPUT KEYWORDS:
 	/center		if set, forces the axes origin to be the exact center, OR ELSE
 	center=		2d array containing the pixel coords for the axes zero point
 				(if not present, default is brightest pixel in the image)
 	platescale=		platescale for the image. Can be 1 element or a 2d array
 					for differing x and y scales. Default assumption is arcsec
 	pixelscale=	synonym for platscale.
 			

 	/reversex	flip x axis sign (e.g. for RA)
	/arcsec		display output in arcsec
	/arcmin		display output in arcmin (i.e. divide by 60)
 	
 OUTPUTS:
 	xr=			xrange array suitable for using with imdisp
 	yr=			yrange array suitable for using with imdisp
 	x=			array of x axis coords converted to arcsec
 	y=			array of y axis coords converted to arcsec

 HISTORY:
 	Began 2005-10-22 17:24:51 by Marshall Perrin 
 	2006-06-07		Added documentation

(See sources/imdisp_getaxes.pro)


IMDISP_WITH_CONTOURS

[Previous Routine] [Next Routine] [List of Routines]
(See sources/imdisp_with_contours.pro)

 NAME:  imdisp_with_contours
 PURPOSE:
 		imdisp an image, and overplot contours using subtle colors a la Tufte

 INPUTS:
 	image
 REQUIRED KEYWORDS: (unless you use the pixelscale= keyword)
	xrange,yrange	X and Y range for whole array
	xvals,yvals		X and Y for each pixel
	contourlevels	array giving levels for contours 

 OPTIONAL KEYWORDS
 	/axis			draw axis
 	
	/alog, /asinh	what scaling to use?
	/noscale		display image exactly as provided
	min=, max=		min and max for scaling
	nonlinearity=	for asinh
	/negative		black-on-white display 

	contourcolors	colors for contours
 	contour_step	offset between regular plot colors and contour colors
 					default = 40
 	contour_image	plot contours of this image instead of main image
 					(useful for overplots or smoothed versions)
 	contoursmooth=  median-smooth the image by this much before contouring.
	/nocontours		don't plot contours! (kind of silly give the routine name, 
					but sometimes useful...)

	force_contourcolors=	numerical color value override (can be array)
	contourstring=			string to call fsc_color with 
							(useful for pstscript due to IDL brokenness
							requiring fsc_color call *after* image display)


 OUTPUTS:
 	out_position	output position used to plot (see imdisp.pro)

 HISTORY:
 	Began 2007-01-04 14:59:55 by Marshall Perrin 
 	2007-06025	all the bugs out.
 	2009-04-16  added ccols_out keyword

(See sources/imdisp_with_contours.pro)


PLOT_DRAWZOOMBOX

[Previous Routine] [Next Routine] [List of Routines]
(See sources/plot_drawzoombox.pro)

 NAME:  plot_drawzoombox
 PURPOSE:
 	Draw zoom-in lines for a plot cutout.

 INPUTS:
 	pixelx, pixely		center of zoomed in box in image pixels
 	pixelw				size of zoomed-in box in image pixels
 KEYWORDS:
 	xvals,yvals			x and y value per pixel, such as from imdisp_getaxes
 OUTPUTS:

 HISTORY:
 	Began 2007-06-02 23:18:26 by Marshall Perrin 

(See sources/plot_drawzoombox.pro)


PLOT_RECTANGLE

[Previous Routine] [Next Routine] [List of Routines]
(See sources/plot_rectangle.pro)

 NAME: plot_rectangle
 PURPOSE:
 	Draws a rectangle in data coordinates, optionally rotated

 INPUTS:
 KEYWORDS:
 	rot		rotation angle in DEGREES
 OUTPUTS:

 HISTORY:
 	Began 2005-03-08 14:04:11 by Marshall Perrin 

(See sources/plot_rectangle.pro)


PLOT_RESTORECOORDS

[Previous Routine] [Next Routine] [List of Routines]
(See sources/plot_restorecoords.pro)

 NAME:  plot_restorecoords
 PURPOSE:
 	counterpart to plot_savecoords

 INPUTS:
 KEYWORDS:
 OUTPUTS:

 HISTORY:
 	Began 2007-06-02 23:37:25 by Marshall Perrin 

(See sources/plot_restorecoords.pro)


PLOT_SAVECOORDS

[Previous Routine] [Next Routine] [List of Routines]
(See sources/plot_savecoords.pro)

 NAME:  plot_savecoords
 PURPOSE:
 	Save the current axis setup.

 INPUTS:
 KEYWORDS:
 OUTPUTS:

 HISTORY:
 	Began 2007-06-02 23:36:17 by Marshall Perrin 

(See sources/plot_savecoords.pro)


PPLOT

[Previous Routine] [Next Routine] [List of Routines]
(See sources/pplot.pro)

 NAME: pplot
 PURPOSE:
 	produce a pretty plot for postscript. 
 NOTES:
 	This is a semi-intelligent wrapper for PLOT, intended to handle displaying
 	dark images (where you want white axis tick marks) with axis labels
 	(either white text on a black screen, or black text on white paper).


 	By default, this assumes the image is mostly black, so :
 	Screen:		everything's white
 	Postscript:	black titles and labels outside the image, white ticks inside

 	If you set 'negative' then it assumes the image is mostly white:

 	Screen:		white titles and labels outside the image, black ticks inside.
 	Postscript:	everything's black


 CAUTIONS:
 		This code assumes that
 			!p.background = WHITE (or the actual paper color)
 			!p.color = BLACK (or something which shows up on your actual paper
 			                color)

 		If you have mucked around with color tables such that the above is not
 		true, this probably won't do what you want...


 INPUTS:
 KEYWORDS:
 OUTPUTS:

 HISTORY:
 	Began 2003-10-24 14:09:39 by Marshall Perrin 
 	2005-10-06 20:01:22 added /negative

(See sources/pplot.pro)


RAINBOW

[Previous Routine] [List of Routines]
(See sources/rainbow.pro)

 NAME: rainbow
 PURPOSE:
 	Return a vector of color indices, from fsc_color.
 NOTES:
 	requires Dave Fanning's FSC_COLOR.pro

 	Note that for output to file you need to call this AFTER you call
 	psopen.

 INPUTS:
 KEYWORDS:
 	n=n		how many colors do you want? this will repeat the rainbow enough
 			times that you have at least n colors.
 	/more	Return more colors (16 elements to the rainbow, versus
 			the default 10)
 	/pale	return a pastel rainbow instead of the usual vibrant colors.
 	/dim	make any of the above color tables half as bright
 	/light	inverse of dim: make any of the above twice as bright.
 OUTPUTS:
 	a vector of color indices

 HISTORY:
 	Began 2005-04-20 14:50:34 by Marshall Perrin 

(See sources/rainbow.pro)


Category: Programming

[List of Routines]


CHECKDIR

[Next Routine] [List of Routines]
(See sources/checkdir.pro)

 NAME: checkdir

 PURPOSE: Check whether a given directory exists

 NOTES:
   Given a string supposedly naming a directory, checks whether it
       (a) corresponds to a valid directory
       (b) has a trailing slash present
	If (a) fails, the routine stops and gives an error. 
	if (b) fails, the routine silently adds a slash.

	If called with /expand, it will expand any ~usernames in the
	given string to the full directory path needed by IDL.

	If called with /make, it will create the directory if needed. 

 USAGE:
 	checkdir, dir

 INPUTS: dir	String containing a directory
 KEYWORDS:
 	expand		expand ~'s in the path.
 	fallback	if dir doesn't exist, try using this one instead

 HISTORY:
	Aug 21, 2001	MDP
	2003 June 25	Added fallback option. MDP
	2005 Sept 21	Added /make   MDP
	2009 Oct 15     Switched to path_sep() instead of just /. MDP

(See sources/checkdir.pro)


GETMYNAME

[Previous Routine] [Next Routine] [List of Routines]
(See sources/getmyname.pro)

 FUNCTION: getmyname

 PURPOSE:
		Returns the name and file path to the source code of the calling
		procedure
	NOTES:
		In other words, if you're executing FOO from /some/path/foo.pro
		then 
			getmyname, name,path
		sets name="FOO" and path="/some/path/foo.pro"
		
 INPUTS:
 KEYWORDS:
 	dir		outputs directory not including file name
 OUTPUTS:
 	name	name of calling procedure
 	path	path to file containing calling procedure

 HISTORY:

(See sources/getmyname.pro)


STACKPOP

[Previous Routine] [Next Routine] [List of Routines]
(See sources/stackpop.pro)

 NAME: stackpop

 PURPOSE:
 	pops a variable off of a stack. 
 NOTE
 	If the stack only contains one item
 	it becomes undefined after the item is popped off.

		see also stackpush.pro
		
 INPUTS:
 	stack	an array functioning as a stack
 KEYWORDS:
 OUTPUTS:
 	returns the last element of the stack, and shortens the stack 
 	accordingly.

 HISTORY:
 	Began 2002-04-01 00:48:36 by Marshall Perrin 

(See sources/stackpop.pro)


STACKPUSH

[Previous Routine] [Next Routine] [List of Routines]
(See sources/stackpush.pro)

 NAME: stackpush

 PURPOSE: 
	pushes a variable onto a stack. If the stack is undefined, it is
	created.
 NOTES:
            stackpush,stack,var
		see also stackpop.pro
		
 INPUTS:
 KEYWORDS:
 OUTPUTS:

 HISTORY:
 	Began 2002-04-01 00:48:36 by Marshall Perrin 

(See sources/stackpush.pro)


STRUCT_MERGE

[Previous Routine] [Next Routine] [List of Routines]
(See sources/struct_merge.pro)

 NAME: struct_merge
 PURPOSE: 
 	Given two structures, A and B, each of which may be an array, and
 	which may have different tag names, create a new structure C
 	which is the union of both A and B. 

 NOTES:

	Fields present in each of A and B will be copied into C. Fields present
	in one but not the other will be copied from that one where present, 
	and filled with blanks or zeros for the one where not present.

 	i.e. if one = {name: 'one', value=4}
 		    two = {name: 'two', something="test"}

 		  then struct_merge(one,two) is the array:
 		  	    [{name: 'one', value=4, something=''}, 
 		  	     {name: 'two', value=0, something='test'}]

	This is sort of like Dave Schlegel's 'struct_append.pro', but it
	handles gracefully the case where the structures have partially-overlapping
	lists of tag names, and also appends the second structure onto the first
	to build an array.


 INPUTS:
 		two structures
 OUTPUTS:	
 		the merged structure, as described above

 WARNINGS:

 	This will fail if structures A and B have conflicting types for the
 	same tag name.

 	This will also fail if either of the structures themselves contain a
 	substructure as a member.

 HISTORY:
 	Began 2006-04-20 20:55:24 by Marshall Perrin
 	2009-01-25	If either struct is a proper superset of the other, preserve the
 				tag order of the superset in the combined structures.

(See sources/struct_merge.pro)


TIMEIT

[Previous Routine] [Next Routine] [List of Routines]
(See sources/timeit.pro)

 timeit

 PURPOSE:
    test how long a given IDL command takes to execute. 

 NOTES:

 takes a string specifying an idl command. Executes it some number of times
 (default=5) and prints the mean execution time.

 This actually has to be implemented as a batch file so that it executes at 
 the same level of IDL rather than going inside of a procedure or function
 call, since then none of your variables would be accessible and the
 statement you want to time would presumably not work.

 USAGE:

  IDL> cmdstr="some string of commands"
  [optional:  IDL> timeitloops=]
  IDL> @timeit
  
 HISTORY:
    2001-07-25 by Marshall Perrin

(See sources/timeit.pro)


WHICH

[Previous Routine] [Next Routine] [List of Routines]
(See sources/which.pro)

 NAME:
 	which


 CATGEORY: General utility

 PURPOSE:
Prints full filenames in IDL !path search order for a particular routine.
 NOTES:
 proname (input string) procedure name (.pro will be appended) to find
24-Aug-92 JAV	Create.
10-Mar-93 JAV	Fixed bug; last directory in !path ignored; pad with ': '

(See sources/which.pro)


GETNUM

[Previous Routine] [Next Routine] [List of Routines]
(See sources/getnum.pro)

 PURPOSE:
 print a string and then let user enter a number
 just like READ command, except can enter  to choose default
 and will re-prompt if user doesn't enter a number



 INPUTS
   prompt  string to print (no colon)
   defval  default value 

 KEYWORD
 	/noquery	don't actually ask user, just return the default value
 				This is useful for making an "automatic" mode.

 USES
   strc, isnumber (JHU/APL)

 05/12/99 MCL
 05/31/00 MCL: bug fix - returned value was a string, now it's a float
 2003-11-25	MDP: added /noquery

(See sources/getnum.pro)


GETYN

[Previous Routine] [Next Routine] [List of Routines]
(See sources/getyn.pro)

 PURPOSE:
 get a reply to a yes/no question,
 allowing the user to hit  to select the default respone

 Usage: 
 		getyn, qstr, def, noquery = noquery, help=help

 INPUT
   qstr  string to be printed (the question)

 OPTIONAL INPUT
   def   default answer (0=no, not 0=yes; yes is default)

 KEYWORD PARM
   noquery  if this is set, then returns the default answer
            w/o asking any question (seems useless, but
            actually useful for some programs, particularly 
            when you want to have an automated mode that skips
            asking the questions.)

 RETURNS
   0 = no
   1 = yes

 EXAMPLE
  if getyn('print something?') then print,'something'

 HISTORY: Written by M. Liu (UCB) 09/04/96 
 06/27/00: added /noquery		M.Liu
 10/09/00: Documentation cleaned up. 	M.Perrin
 
 Please send comments/questions to 

(See sources/getyn.pro)


HASNANS

[Previous Routine] [List of Routines]
(See sources/hasnans.pro)

 NAME: hasnans
 PURPOSE: does an array have NaNs in it?

 INPUTS:
 KEYWORDS:
 OUTPUTS:

 HISTORY:
 	Began 2007-07-27 09:39:40 by Marshall Perrin 

(See sources/hasnans.pro)