September 2002

This directory (and its subdirectories) contains all the Astronomy Library
procedures as individual ASCII files.    Each procedure is located in one
of the following subdirectories:

/astro -  Astronomy utility procedures
/astrom - Procedures that utilize the astrometry info in a FITS header
/database - IDL database routines created by D. Lindler
/disk_io - Procedures to access different disk formats including those used 
          by MIDAS and IRAF
/fits -    Procedures that access disk FITS files
/fits_bintable - Procedures to read or write a binary FITS table
/fits_table - Procedures to read ASCII or binary FITS tables 
/idlphot - Procedures that emulate an early version of DAOPHOT PSF-fitting
 	  photometry
/image - Procedures useful for image processing
/jhuapl - Procedures duplicated from the Johns Hopkins APL IDL Library
/math -  Procedures for math and statistics (often from "Numerical Recipes")
/misc  - Miscellaneous IDL procedures not directly related to astronomy
/plot - Procedures for making or controling plots
/sdas  - Procedures for accessing files created by STSDAS (Hubble Space 
         Telescope format)
/sdas_table - Procedures for accessing tables files created by STSDAS
/sockets - Procedures using IDL SOCKET command to access Web servers
/structure -  Procedures for manipulating IDL structures
/tv -	 Procedures for manipulating the image display

        Contents of IDL Astronomy User's Library              October, 2003
        (also see http://idlastro.gsfc.nasa.gov/contents.html)

Astronomical Utilities    in pro/astro
________
--------
A_b() - Compute B band interstellar extinction as a function of Galactic coords.
ADSTRING() - Format RA and DEC as a character string
AIRTOVAC - Convert air wavelengths to vacuum wavelengths
AITOFF - Convert longitude,latitude to X,Y using Aitoff equal-area projection
AITOFF_GRID - Create an overlay grid using the AITOFF projection 
ALTAZ2HADEC - Convert Horizon (Alt-Az) coordinates to Hour Angle and Declination
ARCBAR - Draw an arcbar over an image showing the astronomical plate scale
ARROWS - Given a FITS header, display a "weathervane" showing N-E orientation 
ASTDISP - Display formatter for pixel + astronomical coordinates
ASTRO - Interactive driver to compute astronomical precession,
        or coordinate conversions (calls EULER and PRECESS).
BARYVEL - Compute components of barycentric Earth velocity, given Julian date
BPRECESS - Precess coordinates, proper motion from J2000 to B1950
CALZ_UNRED - Deredden a galaxy spectrum using the Calzetti et al. (2000) formula
CCM_UNRED - Deredden a spectrum using the Cardelli, Clayton and Mathis (1989)
         parameterization.
CO_ABERRATION - Calculate changes to Ra and Dec due to aberration effects
CO_NUTATE - Calculate changes in RA and Dec due to nutation of the Earth's rotation
CO_REFRACT() - Calculate correction to altitude due to atmospheric refraction
COSMO_PARAM - Derive a full set of cosmological parameters given a subset
CT2LST- Convert from civil time to local sidereal time
DATE()  - Convert day of year to a DY-MON-CCYY string (FITS standard)
DATE_CONV() - Function to perform various date format conversions
DAYCNV- Convert from Julian Date to calendar date.
DEREDD- Deredden Stromgren indices (called by UVBYBETA)
ECI2GEO() - Convert Earth-centered inertial coordinates to geographic  coords
EQ2HOR - Convert celestial  (ra-dec) coords to local horizon coords (alt-az).
EQPOLE - Convert longitude,latitude to X,Y using polar equal-area projection
EQPOLE_GRID - Create overlay grid using polar equal-area projection
EULER - Astronomical coordinate system conversions
FLUX2MAG() - Convert from flux units to magnitudes
FM_UNRED - Deredden a spectrum using the Fitzpatrick & Massa (1998)
         parameterization.
GAL_UVW - Calculate the Galactic space velocity (U,V,W) of a star
GAL_FLAT()  - Correct a galaxy image for inclination effects.
GALAGE - Derive a galaxy age as a function of redshift for a cosmological model
GCIRC - Compute rigorous great circle distance
GEO2ECI() - Convert geographic coordinates to Earth-centered inertial coords 
GEO2GEODETIC() - Convert from geographic to geodetic coordinates
GEO2MAG() - Convert from geographic to geomagnetic coordinates
GEODETIC2GEO() - Convert from geodetic to geographic coordinates
GET_COORDS - Read in angular input in decimal or sexigesimal format
GET_DATE - Get the current date in CCYY-MM-DD format (FITS standard)
GET_JULDATE - Get the current Julian date as a double precision scalar
GLACTC- Convert between Galactic (or SuperGalactic) and equatorial coordinates
HADEC2ALTAZ -  Converts Hour Angle and Declination to Horizon (alt-az) coordinates                                 
HELIO - Compute (low-precision) heliocentric coordinates of the planets 
HELIO_JD() - Convert geocentric (reduced) Julian date to heliocentric Julian date
HELIO_RV() - Compute radial velocity given binary star orbit parameters
HOR2EQ - Convert local horizon coords (alt-az) to equatorial (ra-dec).
IMCONTOUR - Contour plots with astronomical labeling (either RA,Dec or 
            arc distance from the image center
IMF() - Return values for a multi-component power law initial mass function
ISMEUV() - Compute EUV optical depth due to photoionization of HI, HeI and HeII
JDCNV - Convert from calendar date to Julian date.
JPLEPHINTERP - Interpolate position and motion of planetary bodies (JPL Ephemeris)
JPLEPHREAD - Open and read JPL DE200 or DE405 Ephemeride FITS File
JPRECESS - Precess positions & proper motions from B1950 to J2000
JULDATE-Convert from calendar date to reduced Julian date. 
LSF_ROTATE - Create a 1-d convolution kernel to broaden a spectrum from a rotating star
LUMDIST - Return luminosity distance for a given redshift & cosmological model
MAG2GEO() - Convert from geomagnetic to geographic coordinates
MAG2FLUX() - Convert from magnitudes to flux units
MONTH_CNV() Convert a month name to the equivalent number or vice-versa 
MOONPOS- Compute the RA and Dec (and distance) of the Moon at a given date
MPHASE - Compute illuminated fraction of the Moon's disk for given Julian dates
NUTATE - Compute the nutation in longitude and latitude for given Julian date(s)
OBSERVATORY - Return coordinates, altitude & time zones of an observatory
PLANCK() - Returns a blackbody flux for a given effective temperature
PLANET_COORDS - Return low-precision RA and Dec of planets give a date(s)
POSANG - Compute the position angle between sources of specified RA and Dec
PRECESS - Precess RA and Dec to a new equinox
PRECESS_CD - Precess the PC (or CD) matrix in a FITS header to a new equinox
PRECESS_XYZ - Precess equatorial geocentric rectangular coordinates
PREMAT() - Returns precession matrix from equinox 1 to equinox 2
QDCB_GRID - Create overlay grid using COBE quad cube database coordinates
RADEC - Format RA, Dec as Hours,Min,Sec,Deg,Min,Sec
REDSHIFT - Interactively convert between redshift, distance, and velocity
           (in /jhuapl)
SIXTY - Convert decimal number to sexigesimal                 
SPHDIST() - Find angular distance on a sphere (in /jhuapl)
SUNPOS - Compute the RA and Dec of the Sun at a given date
TDB2TDT() - Relativistic clock corrections due to Earth motion in solar system
TEN() - Convert sexigesimal number to decimal             
TENV() -  Like TEN but will work on a vector of sexigesimal numbers.
TICPOS - Specify distance between tic marks for astronomical coordinates
TICLABELS - Create labels for astronomical coordinate tick marks 
TICS - Compute the optimum distance between tic marks for astronomical labeling
TIC_ONE - Determine optimum position of the first tic in astronomical labeling  
UVBYBETA - Use Stromgren indices to derive dereddened colors, metallicity,
        and effective Temperature.
VACTOAIR - Convert vacuum wavelengths to air wavelengths.
XYZ - Compute heliocentric rectangular coordinates at given Julian date.
YMD2DN() - Convert year,month,day to day number of the year (in /jhuapl)
YDN2MD - Convert day number of the year to year, month,day
ZANG() - Compute angular size as a function of redshift in a Friedman cosmology
ZENPOS - Compute the RA and Dec of the local zenith at a given date

----------------------------------------------------------------------------
DAOPHOT-Type Photometry Procedures    in pro/idlphot (see text/daophot.tex)
________
--------
APER -   Circular APERture photometry
CNTRD - Obtain the centroid of a star in an image array, using the FIND algorithm
DAOERF - Calculate the intensity, (and optionally, the derivatives) of
         a bivariate Gaussian, integrated over pixels.  Called by DAO_VALUE
DAO_VALUE -  Obtain the value of a DAOPHOT PSF function at a given set of points
FIND -   FIND point sources within an image
GETPSF - Obtain a PSF (Gaussian + residuals) from isolated stars.
GROUP -  Place stars with non-overlapping PSF's in distinct groups
MMM -    (Mean, Median, Mode) sophisticated sky background computation
NSTAR -  Simultaneous PSF fitting of a group of stars 
PIXWT -  Compute the area of the intersection of a circle on a rectangle
PKFIT -  Fit a Gaussian + residuals to a isolated star (called by GETPSF)
RDPSF -  Read a PSF file that was created by GETPSF into an IDL array.
RINTER - Cubic Interpolation at a set of reference points, optionally
         obtain derivatives.  (in /image)
SKY -    Compute image sky level using MMM
SRCOR -  Correlate the source positions in two different lists
SUBSTAR- Subtract a scaled PSF at specified star positions
T_APER - Driver procedure for  APER with I/O to a disk FITS ASCII table
T_FIND - Driver procedure for FIND with I/O to a disk FITS ASCII table
T_GROUP- Driver procedure for GROUP with I/O to a disk FITS ASCII table
T_GETPSF - Driver procedure for GETPSF with I/O to a disk FITS ASCII table
T_NSTAR -  Driver procedure for NSTAR with I/O to a disk FITS ASCII table
T_SUBSTAR - Driver procedure for SUBSTAR with I/O to a disk FITS ASCII table

-----------------------------------------------------------------------
Database Procedures   in pro/database  (see text/database.tex)
____________
------------
DBBUILD - Load or append a database with new entry values.
DBCIRCLE() - Find entries within a specified circular area.
DBCLOSE - Close a database
DBCOMPARE - Display the values of two database entries side by side   
DBCOMPRESS - Compress a .dbf database file, following a call to DBDELETE 
DBCREATE - Create a new database data, index and/or format file.
DBDELETE - Delete an entry from a database
DBEDIT - Interactively edit the entries in a database 
DBEXT - Extract items from a database into IDL variables 
DBFIND() - Find entries meeting specified criteria in an IDL database
DBGET() - Use instead of DBFIND when search values are in an IDL vector
DBHELP - List names of databases, or entries within a database
DB_INFO() - Lower level routine to obtain information on an opened database 
DBINDEX - Update the IDL database index file.
DB_ITEM_INFO() - Lower level routine to obtain information on specified item(s)
DB_ITEM - Lower level routine to return item number and other information
DBMATCH() - Match database entries one-to-one to specified item values
DBOPEN - Open a IDL database  
DBPRINT - Print specified fields about specified entries in an IDL database
DBPUT - Lower level routine to place new value for specified item into an entry
DBRD - Lower level routine to read an entry from a database
DBSORT() - Sort entries in an IDL database 
DBTARGET() - Find entries within specified distance of an astronomical target 
DBUPDATE -  Update an IDL database with new item values.
DB_OR() - Combine two catalog entry lists, removing duplicate values
DBVAL - Lower level routine to extract value of specified item from an entry
DBXVAL - Lower level routine to extract values of specified item from an entry
DBWRT - Lower level routine to update or add a new entry to a database
IMDBASE - Find all catalog sources within the field of an astronomical image 
DB_ENT2EXT,DB_ENT2HOST,DBEXT_DBF,DBEXT_IND,DBXPUT,DBFPARSE,DBFIND_ENTRY,
DBFIND_SORT,DBSEARCH,DBTITLE,DB_TITLE() - Lower level database procedures

----------------------------------------------------------------------------
Disk I/O (MIDAS, IRAF files)    in pro/disk_io
_________
---------
IRAFDIR - Describe IRAF images on specified directory
IRAFRD -  Read a disk IRAF image file into IDL variables.  
IRAFWRT - Write IDL image and header to an IRAF (.pix & .imh) file
MID_RD_IMAGE - Read a MIDAS image (.BDF) file into IDL variables
MID_UP_IMAGE - Update the contents of a MIDAS image file
MID_RD_TABLE - Read a MIDAS table (.TBL) file into IDL variables
MID_UP_TABLE - Update the contents of a MIDAS table file.
MID_RD_DIRDSC - Lower level procedure to read MIDAS directory descriptor 
WFPC2_READ - Read a Wide Field/Planetary Camera 2 (WFPC2) image

-----------------------------------------------------------------------
FITS Astrometry and Calibration  in pro/astrom (see text/astrom.tex)
________
--------
ABSCAL() - Apply the BSCALE and BZERO FITS keywords values to a data array
AD2XY - Use astrometry structure to convert celestial to pixel coordinates 
ADXY  - Use FITS header to convert celestial (RA,Dec) to pixel coordinates
CONS_DEC() - Obtain the X and Y coordinates of a line of constant 
        declination
CONS_RA() - Obtain the X and Y coordinates of a line of constant right
        ascension
EXTAST- EXTract ASTrometry parameters from a FITS header into an IDL structure
FITS_CD_FIX - Update obsolete representations of the CD matrix in a FITS header
GET_EQUINOX() - Return a numeric equinox value from a FITS header
GETROT - GET ROTation and plate scale from a FITS header
GSSS_STDAST - Insert the closest tangent projection astrometry into an STScI
         Guidestar Survey Image
GSSSADXY - Convert RA, Dec to pixel coordinates for an STScI survey image
GSSSEXTAST - Extract astrometry parameters from an STScI Survey Image
GSSSXYAD - Convert pixel coordinates to RA, Dec for an STScI survey image
HASTROM - Rotate, Congrid, and/or shift an image until astrometry matches
        that in a reference FITS header.  Used to align images.
HBOXAVE - Boxaverage an image and update astrometry in a FITS header
HCONGRID - CONGRID an image and update astrometry in a FITS header
HEULER - Convert between Galactic, celestial and ecliptic coordinates in FITS a
header
HEXTRACT - Extract a subimage and update astrometry in a FITS header
HPRECESS - Precess the astrometry in a FITS header to a new equinox.
HREBIN - REBIN an image and update the astrometry in a FITS header
HREVERSE - Reverse an image about either dimension and update astrometry
        in a FITS header                                    
HROT  - Rotate an image and update astrometry in a FITS header.
HROTATE - Apply IDL ROTATE function and update astrometry in a FITS header
MAKE_ASTR - Build an astrometry structure from input parameter values
PRECESS_CD - Precess coordinate description (CD) matrix in a FITS header 
          to a new equinox.   Called by HPRECESS
PUTAST - Put astrometry parameters (e.g. rotation, plate scale) into a FITS header. 
STARAST - Obtain an exact astrometry solution given the coordinates and
        plate position of 2 or 3 stars.
WCS_GETPOLE -  Compute the coordinates of the native pole for non-polar projection
WCSSPH2XY - Convert between longitude,latitude to X,Y angular coordinates for
        25 different map projection types
WCSXY2SPH - Inverse of WCSSPH2XY
WCS_DEMO - Demo program for WCSSPH2XY and WCSXY2SPH
WCS_ROTATE - Rotate between standard (e.g. celestial) and native coordinates
XYAD  - Use FITS header to convert pixel (X,Y) to celestial(RA, Dec) coordinates
XY2AD - Use astrometry structure to convert pixel to celestial coordinates
XYXY -  Convert X,Y values on one image to X,Y values in another image
         using astrometry in the FITS headers

----------------------------------------------------------------------------
STSDAS Image manipulation         in pro/sdas
________
--------
ASTRMFIX - Update an HST WF/PC or FOC header with rough astrometry
CONV_STSDAS - Convert internal format of .hhd file to that of the host machine.
EXTGRP - Extract group parameter values and place them in a header
IMGREAD - Like STRD but supports group format and tailored to WF/PC, FOC files
ST_DISKREAD - Read an HST FITS file and reconstruct a GEIS (STSDAS) file
STRD - Combine SXOPEN and SXREAD to read STSDAS disk files into IDL variables
STSUBIM - Like STRD but allows reading a subimage
STWRT - Combine SXOPEN and SXWRITE to write IDL variables to a STSDAS disk file
SXGINFO -  Return info on all group parameters in a FITS header
SXGPAR() - Obtain group parameter values from a FITS header and parameter block
SXGREAD() -  Read group parameters from an STSDAS file
SXHCOPY -  Copy a selected portion of one header into another
SXHEDIT -  Interactively edit a STSDAS header using the OS editor            
SXHMAKE -  Create a basic STSDAS header file from an IDL data array
SXHREAD -  Read a STSDAS header from disk
SXHWRITE - Write a STSDAS header to disk
SXMAKE -   Make a basic STSDAS header from an IDL array
SXOPEN -   Open an STSDAS disk file for subsequent I/O
SXREAD() -   Read an STSDAS image from disk
SXWRITE -  Write an image to STSDAS  format
WFPCREAD - Read an HST WFPC or FOC STSDAS group image

----------------------------------------------------------------------------
FITS ASCII & Binary Table I/O      in pro/fits_table      ( see text/ft.tex )
________
--------
FTAB_DELROW - Delete specified rows in a FITS table extension
FTAB_EXT - Extract specified columns of a FITS table extension into IDL vectors
FTAB_HELP - Print info about the fields in a FITS table extension
FTAB_PRINT - Print specified columns and rows of a FITS table extension
FTADDCOL - Add a new column to a FITS ASCII table
FTCREATE - Create an empty FITS ASCII table header and data array
FTDELCOL - Delete specified column from a FITS ASCII table data array
FTDELROW - Delete specified row(s) from a FITS ASCII table data array
FTGET() - Extract a specified field from a column in a FITS ASCII table array
FTHELP - Display the fields in a FITS ASCII table header
FTHMOD - Modify the attributes of a field in a FITS ASCII table
FTINFO - Return an informational structure from a FITS ASCII table header
FTKEEPROW - Subscript (and reorder) a FITS ASCII table array
FTPRINT - Print specified columns and rows in a FITS ASCII table array
FTPUT - Update or add data to a field in a FITS ASCII table array
FTSIZE - Return the size and number of fields in a FITS ASCII table  array
FTSORT - Sort a FITS ASCII table according to the values in a specified field.
TBDELCOL - Delete specified column from a FITS Binary table array
TBDELROW - Delete specified row(s) from a FITS Binary table array
TBGET() - Extract a specified field from a column in a FITS Binary table
TBHELP - Display the fields in a FITS Binary table header
TBINFO - Return an informational structure from a FITS Binary table header
TBPRINT - Print specified columns and rows in a FITS Binary table array
TBSIZE - Return the size and number of fields in a FITS Binary table array

-------------------------------------------------------------------------
FITS Binary Table Extensions I/O    in pro/fits_bintable
_________ 
---------
FXADDPAR          - Add or modify a parameter in a FITS header array.
FXBADDCOL         - Adds a column to a binary table extension.
FXBCLOSE          - Close a FITS binary table extension opened for read.
FXBCOLNUM()       - Returns a binary table column number.
FXBCREATE         - Open a new binary table at the end of a FITS file.
FXBDIMEN()	  - Returns the dimensions for a column in a FITS binary table.
FXBFIND           - Find column keywords in a FITS binary table header.
FXBFINDLUN()      - Find logical unit number UNIT in FXBINTABLE common block.
FXBFINISH         - Close a FITS binary table extension file opened for write.
FXBGROW           - Increase the number of rows in a binary table
FXBHEADER()       - Returns the header of an open FITS binary table.
FXBHELP           - Prints short description of columns in a FITS binary table.
FXBHMAKE          - Create basic FITS binary table extension (BINTABLE) header.
FXBINTABLE        - Common block FXBINTABLE used by "FXB" routines.
FXBISOPEN()       - Returns true if UNIT points to an open FITS binary table.
FXBOPEN           - Open binary table extension in a disk FITS file for reading
FXBPARSE          - Parse the binary table extension header.
FXBREAD           - Read a data array from a disk FITS binary table file.
FXBREADM          - Read multiple columns/rows from a FITS binary table file.
FXBSTATE()        - Returns the state of a FITS binary table.
FXBTDIM()         - Parse TDIM-like keywords.
FXBTFORM          - Returns information about FITS binary table columns.
FXBWRITE          - Write a binary data array to a disk FITS binary table file.
FXBWRITM          - Write multiple columns/rows to a FITS binary table file
FXFINDEND         - Find the end of a FITS file.
FXHCLEAN          - Removes required keywords from FITS header.
FXHMAKE           - Create a basic FITS header array.
FXHMODIFY         - Modify a FITS header in a file on disk.
FXHREAD           - Reads a FITS header from an opened disk file.
FXPAR()           - Obtain the value of a parameter in a FITS header.
FXPARPOS()        - Finds position to insert record into FITS header.
FXREAD            - Read basic FITS files.
FXWRITE           - Write a disk FITS file.

-------------------------------------------------------------------------
FITS I/O        in pro/fits
_________
---------
CHECK_FITS - Check that array agrees with NAXISi, BITPIX keywords of FITS header
FITSDIR - Display info about primary FITS header(s) on disk
FITSRGB_to_TIFF - Combine separate red, green, blue FITS files into TIFF format
FITS_ADD_CHECKSUM - Add/update the CHECKSUM/DATASUM keywords in a FITS header
FITS_ASCII_ENCODE() - Encode an unsigned longword as an ASCII string
FITS_CLOSE - Close a FITS file defined by a FITS Control Block (see FITS_OPEN)
FITS_HELP - Summarize the primary data units and extensions in a FITS file
FITS_OPEN - Open a FITS file and define a FITS Control Block (FCB)
FITS_READ - Read a FITS file specified by name or FITS Control Block (FCB)
FITS_TEST_CHECKSUM() - Verify the values of the CHECKSUM/DATASUM FITS keywords
FITS_WRITE - Write a FITS primary data unit or extension
FITS_INFO - Display info about disk FITS file(s) at a terminal or in Common 
FXMOVE() - Skip a specified number of extensions in a FITS file
FXPOSIT() - Open a FITS file positioned to beginning of a specified extension
HEADFITS() - Read a FITS header from a disk FITS file.
MKHDR - Make a minimal FITS header for an image array.
MODFITS - Modify the header or data in a FITS array (without changing the size)
MRDFITS() -  Read FITS file mapping table columns into IDL structure tags
MRD_HREAD -  Like FXHREAD but can also read a FITS header from a Unix pipe
MWRFITS - Write a FITS file from a IDL array or structure
RDFITS_STRUCT - Read an entire disk FITS file into an IDL structure
READFITS() - Read a disk FITS file into an IDL data and header array.
SXADDHIST - Add a history record to a FITS header
SXADDPAR -  Add or modify a parameter in a FITS header
SXDELPAR -  Delete a keyword from a FITS header
SXPAR()  -   Obtain the value of a keyword in a FITS  header
WRITEFITS - Write IDL data and header array to a disk FITS file.

-----------------------------------------------------------------------------
Image Manipulation       in pro/image
_______
-------
BOXAVE() - Boxave an image, always using at least REAL*4 arithmetic
CONVOLVE() - Convolve an image with a PSF using the product of Fourier Transforms
CORREL_IMAGES() - Correlation of two images.   Called by CORREL_OPTIMIZE
CORREL_OPTIMIZE - Compute the optimal pixel offset of one image relative
         to another by maximizing the correlation function.
CORRMAT_ANALYZE - Analyze the correlation function made by CORREL_IMAGE
CR_REJECT - General iterative cosmic ray rejection for 2 or more images
DIST_CIRCLE - Create a mask array useful for circular aperture photometry.
DIST_ELLIPSE - Create a mask array useful for elliptical aperture photometry.
FILTER_IMAGE() - Like MEDIAN or SMOOTH but handles edges & allows iteration
FREBIN - Expand or contract an image while conserving flux
IMLIST - Display image pixel values around a specified center
MAX_ENTROPY - Deconvolution by Maximum Entropy, given a PSF
MAX_LIKELIHOOD - Deconvolution by maximum likelihood, given a PSF
MEDARR - Median filter across a set of images (e.g. for cosmic ray removal)
POSITIVITY() - Map an image uniquely and smoothly into all positive values
PSF_GAUSSIAN() - Create a 1-d, 2-d, or 3-d Gaussian with specified FWHM, center
SIGMA_FILTER() - Replaces pixels deviant by more than a specified sigma from
    its neighbors.   Useful for cosmic ray removal.
SKYADJ_CUBE - Remove the sky level from individual images of a data cube
XMEDSKY - Compute the median sky as a 1-d function of X (for slitless spectra) 

----------------------------------------------------------------------------
Math and Statistics    in pro/math
_________
---------
ASINH() - Return the inverse hyperbolic sine of its argument
AVG() - Return the average value of an array or 1 dimension of an array.
CIC - Cloud In Cell interpolation of irregularly gridded data
CSPLINE() - Interpolate using the Numerical Recipes natural cubic spline
FACTOR - Find the prime factors of a given number (in /jhuapl)
FITEXY - Best straight-line fit to data with errors in both coordinates
FLEGENDRE() - Compute the first M terms in a Legendre polynomial expansion
GAUSSIAN() - Evaluate a 1-d Gaussian and optionally its derivative
HERMITE() - Interpolate a tabulated function using a Hermite spline
KSONE -  Compute the one-sided Kolmogorov-Smirnov statistic
KSTWO -  Compute the two-sided Kolmogorov-Smirnov statistic
LINTERP - Linearly interpolate X,Y vectors onto a new X grid      
MEANCLIP - Compute an iteratively sigma-clipped mean on a data set
MINF_BRACKET - Find 3 points which bracket the minimum of a function
MINF_CONJ_GRAD - Find local minimum of a scalar valued function of several
        variables using conjugate gradient method 
MINF_PARABOLIC - Minimize a function using Brent's method with parabolic interpolation 
MINF_PARABOL_D - Minimize a function using Brent's method with derivatives
NGP - Nearest Grid Point interpolation of irregularly gridded data
PCA - Perform a principal component analysis (Karhunen-Loeve expansion)
PENT() - Return the information entropy S of time-series data for a set of trial periods
POIDEV() - Generate a Poisson random deviate 
POLINT - Polynomial interpolation of an (X,Y) pair 
POLYLEG() - Evaluate a Legendre polynomial with specified coefficients
POLY_SMOOTH() - Apply a least-squares (Savitzky-Golay) polynomial smoothing filter
PROB_KS - Return the significance of a Kolmogorov-Smirnov statistic
QSIMP - Integrate using Simpson's rule to specified accuracy
QTRAP - Integrate using trapezoidal rule to specified accuracy.  
QUADTERP - Quadratic interpolation of X,Y vectors onto a new X grid
RANDOMP - Create a vector of random numbers distributed as a power-law
SIXLIN - Compute linear regression by 6 different methods.
SPLINE_SMOOTH - Compute cubic smoothing spline to (weighted) data
TABINV - Find the effective index of a function value.                          
TRAPZD - Compute Nth iteration of trapezoidal rule.  Called by QSIMP, QTRAP
TSC - Triangular Shaped Cloud interpolation of irregularly gridded data onto a regular grid
TSUM() - Trapezoidal integration of the area under a curve
VALUE_LOCATE() - Emulate V5.3 intrinsic function to find an effective index
ZBRENT() - Find the root of a function known to lie between specified limits

----------------------------------------------------------------------------
Plotting Procedures    in pro/plot
------------
------------
CLEANPLOT - Reset all plotting system variables to their default (X) values
LEGEND - Create an annotation legend for a plot
LEGENDTEST - Demo program demonstrating the capabilities of LEGEND
LINEID_PLOT - Annotate the identified lines in a spectrum
MULTIPLOT - Create multiple plots with shared axes
OPLOTERROR - Overplot Y vs. X with optional X and Y error bars
PARTVELVEC - Plot the velocity vectors of a set of particles
PLOTERROR - Plot Y vs. X with optional X and Y error bars
PLOTHIST - Plot the histogram of an array
PLOTSYM - Define useful plotting symbols not in the standard PSYM definition
RDPLOT - Like intrinsic CURSOR procedure but with a full-screen cursor
SUNSYMBOL() - Return the character string to plot a subscripted Sun symbol
VSYM - Create "Mongo"-like plotting symbols, rotationally symmetric polygons

----------------------------------------------------------------------------
Robust Statistics procedures    in pro/robust
___________
-----------
AUTOHIST  - Draw a histogram using automatic bin-sizing.
BIWEIGHT_MEAN()  -  Iterative biweighted determination of mean and standard deviation
HISTOGAUSS  -  Outlier-resistant autoscaled histogram drawing
MEDSMOOTH() - Median smoothing including the points at the ends
RESISTANT_MEAN -  Outlier-resistant determination of  mean and std. deviation.
ROB_CHECKFIT() - Utility to determine quality of a fit and return biweights
ROBUST_LINEFIT() - Robust fit of Y vs X (or bisector of Y vs X and X vs Y)
ROBUST_POLY_FIT() - Robust polynomial fit
ROBUST_SIGMA()  -   Robust analog of the standard deviation
----------------------------------------------------------------------------
IDL Structure procedures    in pro/structure
___________
-----------
COMPARE_STRUCT() - Compare all matching Tag names and return differences
COPY_STRUCT - Copy Fields with matching Tag names from one structure to another
CREATE_STRUCT - Create an IDL structure from a list of tag types and dimensions
MRD_STRUCT() - Like CREATE_STRUCT but tag values can be specified in a string
N_STRUCT() - Return number of elements in a structure array and number of tags
PRINT_STRUCT - Print specified tags from structure (to LUN if given)
SIZE_STRUCT() - Obtain the size in bytes of an IDL structure definition
TAG_EXIST() - Determine if a tag exists in a given structure
WHERE_TAG() - Like WHERE but works on a structure tag names

----------------------------------------------------------------------------
STSDAS (Binary) Table I/O    in pro/sdas_table
____________
------------
TAB_ADDCOL  - Add a new column to a STSDAS table
TAB_COL - Extract column info from a table control block.  Called by TAB_READ
TAB_CREATE - Create an empty STSDAS table on disk
TAB_DEL  - Delete specified row(s) from an STSDAS table
TAB_EXPAND - Expand the size of an STSDAS table.  Called by TABLE_APPEND
TAB_FORTOSPP - Convert a FORTRAN print format to SPP. Called by TAB_MODCOL
TAB_MODCOL - Modify a column name, format or units in an STSDAS table.
TAB_NULL() - Locate null values in a STSDAS table.  Called by TAB_PUT
TAB_NULLROW - Place null values into a STSDAS table.  Called by TAB_PUT
TAB_PRINT - Print the contents of an STSDAS table in tabular form
TAB_PUT - Put new values into a column of an STSDAS table
TAB_READ - Read table control block and data array from a disk STSDAS table. 
TAB_SIZE - Return the size of a STSDAS table.  Called by TABLE_LIST
TAB_SORT - Sort a STSDAS table according to the specified column
TAB_SPPTOFOR - Convert SPP print format to FORTRAN.  Called by TAB_PRINT
TAB_VAL() - Extract values from a single column of an STSDAS table
TAB_WRITE - Write a STSDAS table to a disk file
TABLE_APPEND - Append a list of STSDAS tables to create a single table.
TABLE_CALC - Add a new table column from an expression using existing columns.
TABLE_CONV - Convert an STSDAS table into the host machine architecture
TABLE_DELETE - Delete specified rows from an STSDAS table
TABLE_EXT - Extract column(s) of data from an STSDAS table to IDL variable(s)
TABLE_HELP  - Describe an STSDAS table.
TABLE_LIST  - List the contents of an STSDAS table
TABLE_PRINT - Print a disk STSDAS table in tabular form
TABLE_SORT  - Order the contents of an STSDAS table by the specified column
----------------------------------------------------------------------------
Web Socket Procedures                    in pro/sockets                   
___________
-----------
WEBGET() - Use the IDL SOCKET procedure to get data from http servers
QUERYGSC() - Query the Guide Star Catalog (GSC V2.2) at STScI by position  
QUERYDSS - Query the digital sky survey (DSS) online at the ESO or STSCI servers
QUERYSIMBAD - Query the SIMBAD or NED name resolver to obtain J2000 coordinates
QUERYUSNO() - Query the USNO-A2.0 Catalog at the ESO/ST-ECF Archive by position
QUERYVIZIER() - Positional query of any catalog in the VIZIER database.

----------------------------------------------------------------------------
TV Display Procedures                    in pro/tv                   
___________
-----------
BLINK - Blink two or more windows in an image display
CURS - Change the shape of the (X windows only) cursor
CURVAL - Interactive display of image intensities and astronomical coordinates
PIXCOLOR - Set specified pixel values to a specified color
SIGRANGE() - Find range of pixel values which contain 90% of the image values
TVBOX - Draw a box of specified size on the image display
TVCIRCLE - Draw a circle of specified radius on the image display
TVELLIPSE - Draw an ellipse of specified axes on the image display
TVLASER - Write an image to postscript file with annotation from a FITS header
TVLIST - Display intensity values surrounding the cursor position
UNZOOM_XY - Convert from window coordinates to image coordinates
ZOOM_XY - Convert from image coordinates to window coordinates

-----------------------------------------------------------------------------
Miscellaneous (Non-Astronomy) Procedures         in pro/misc
________
--------
ASTROLIB - Add the non-standard system variables used in the IDL Astronomy User's Library
BLKSHIFT - Shift a block of data to a new (possibly overlapping) position in a 
          file
BOOST_ARRAY - Append one array onto another, adjusting dimensions if necessary
BREAK_PATH() - break up a !PATH-like string into individual directories
BSORT() - Like the IDL SORT function but subscript order is maintained when
        value are equal -- like a bubble sort.
CHECKSUM32 - Compute the 32bit checksum of an array (ones-complement arithmetic)
CIRRANGE - Force an angle to be in the range 0 to 360 (or 0 to 2*!PI).
CONCAT_DIR - concatenate directory and file name for current OS
CONV_UNIX_VAX - Convert IEEE datatype to VMS datatypes
CONV_VAX_UNIX() - Convert VMS datatypes to Unix using proper byteswapping
DATATYPE() - Return the datatype of an IDL variable as a string
DEF_DIRLIST - Define a directory list using SETENV or SETLOG
DELVARX - Delete an IDL variable; like DELVAR but works at any calling level
DETABIFY() - Replace tabs in a character string by equivalent number of spaces
EXPAND_TILDE() - Expand tilde in UNIX directory names
F_FORMAT() - Find the "best" F format to display an array of REAL*4 numbers.
FDECOMP - Decompose a file name (Disk + Directory + Name + Extension + Version)
FINDPRO - Find all occurrences of a procedure in one's !PATH
FIND_ALL_DIR - Find all directories under a specified directory
FIND_WITH_DEF - Search for files with default path and extension
FORPRINT -Print a set of vectors by looping over each index value
FSTRING - Wrapper to STRING function to get around 1024 element formatted limit 
GETFILES -Interactively specify a list of file numbers.
GETLOG() - Format the input name as a logical directory in the host OS
GETOPT() -  Parse a user supplied string into numeric value(s).
GETPRO -  Search !PATH directory for a procedure and copy into user's directory
GETTOK() -  Extract a string up to a specified character.
GETWRD() -  Get specified item (word) from a string (in /jhuapl)
HGREP - Find a substring in a FITS header or other string array
HOST_TO_IEEE - Convert IDL variable from host machine bit order to IEEE
HPRINT -  Pretty terminal display of a FITS header (or other string array)
IDL_VALIDNAME - Emulate intrinsic IDL_VALIDNAME() function for V5.6 and earlier
IEEE_TO_HOST - Convert IDL variable from IEEE bit order to host machine
ISARRAY() - Determine if an IDL variable is an array (in /jhuapl)
IS_IEEE_BIG() - Determine if the host machine is IEEE big endian 
LIST_WITH_PATH() - Search for files within specified directory path
MAKE_2D - Change from 1-D indexing to 2-D indexing
MATCH -   Find the subscripts where the values of two vectors match.
MRD_SKIP - Skip a number of bytes from current location in a file or a Unix pipe
MINMAX() -  Return the min and max of an array in an 2 element vector
N_BYTES() - Return the number of bytes in an IDL variable
NINT() - Like intrinsic ROUND() function but returns integer instead of long
NULLTRIM() -Delete all characters after, and including, the the first null
          byte(0).  Called by TAB_PUT.
NUMLINES() - Return the number of lines in a file
ONE_ARROW - Draw an arrow labeled with a single character
ONE_RAY - Draw a ray by specifying starting point, angle, and length
ORDINAL() - Return the English equivalent of ordinal numbers, i.e. '1st','2nd'
OSFCNVRT() - Format the input as a logical name in the host operating system
POLREC - Convert from polar to rectangular coordinates (in /jhuapl)
PRODUCT() - Return the product of all the elements of an array.
QGET_STRING() - Read a string (eg. password) from the keyboard without echoing it
RDFLOAT - Quickly read an ASCII file with columns of data into IDL vectors
READCOL - Read a file of free-format  ASCII columns into IDL vectors
READFMT - Quickly read a file of fixed-format ASCII columns into IDL vectors
READ_KEY() - Like GET_KBRD but returns a code for escape sequences.
RECPOL - Convert from rectangular to polar coordinates (in /jhuapl)
REMCHAR - Remove all appearances of a character from a string.
REM_DUP() - Remove duplicate values from a vector.
REMOVE -  Contract a vector or up to 8 vectors by removing specified elements
REPCHR() -  Replace all occurrences of one character by another (in /jhuapl)
REPSTR() -  Replace all occurrences of one substring in a string by another.
SCREEN_SELECT - Allow user to interactively select from a list of strings
SELECT_O - VT100 terminal branch of SCREEN_SELECT
SELECT_W - IDL widget branch of SCREEN_SELECT.
SPEC_DIR() - Complete specification of a file name using default disk & directory
STORE_ARRAY - Insert one array into another, adjusting dimensions if necessary
STRN() - Convert a number to a string and remove padded blanks.
STRNUMBER()- Determine whether a string is a valid numeric value.
TEXTOPEN - Open a file for text output as specified by TEXTOUT keyword
TEXTCLOSE - Close a file that had been opened by TEXTOPEN.
TO_HEX()    - Translate a decimal integer to a hex string.  Called by AIPSNAME.
VALID_NUM() - Determine if a string is a valid number (cf. STRNUMBER)
VALUE_LOCATE() - Emulate intrinsic VALUE_LOCATE function for V5.2 & earlier
VECT() - Display a set of numbers to a string with delimiters
WHERENAN() - Find points equal to IEEE NaN (not a number) values
WHERE_NEGZERO() - Find locations of IEEE -0.0 values
ZPARCHECK - Check the type and size of a parameter

8-Oct-2003:  ASINH() - Now works again for scalar input.
             QUERYVIZIER() - Positional query of any catalog in the VIZIER
                       database.   Popular catalogs include the 2MASS point
                      source catalog, the USNO-B1 astrometric catalog, and
                      GSC2.2 guide star surveu.

06-Oct-2003: IDL_VALIDNAME() - Modify a scalar string, if necessary, so that
                  it can be used as tagname.    Meant for pre-V6.0 compatibility
                  with the V6.0 function with the same name.

30-Sep-2003: WCSXY2SPH - Preserve size of 2-d array inputs

26-Sep-2003: PRECESS - Now works with 2-d or higher input arrays

21-Sep-2003: EXTAST - Further fix from 27-Aug if no comment slash present
                      and values are longer than 20 characters
             WCSSPH2XY, WCSXY2SPH - CTYPE keyword no longer required to be 
                      exactly 8 characters
             MRDFITS(), MRD_SKIP - Use 64bit longword for skipping in very 
                      large files

10-Sep-2003: MWRFITS - Exit gracefully if write privileges unavailable 

8-Sep-2003: WCSXY2SPH - Check for possible divide by zero for tangent projection

5-Sep-2003: STARAST - Fix bug where CD matrix was incorrectly transposed with
                  3 star solution.   Also added projection keyword to allow use
                  with non-tangent projections.

28-Aug-2003: REPSTR() - Fix bug where 3rd parameter was no longer optional

27-Aug-2003: EXTAST - Fixed bug introduced June 2003 where FITS keyword values
                  with more than 20 characters were truncated

26-Aug-2003: MODFITS - Now works for arbitary sizes of the new FITS header or 
                data array
             CHECKSUM32 - Work for arrays with byte sizes that are not a multiple
                of four (pad with zeros)

19-Aug-2003: WCSSPH2XY, WCSXY2SPH - Fixed bug (1 element vector) introduced 
                15-Jul which would fail in pre-V5.5 IDL 

12-Aug-2003: TBGET() - Force a 1 element vector to be scalar prior to
                       subscripting a structure for V6.0 compatibility

25-Jul-2003: GLACTC - Fix a serious bug when the year is not 2000 and /FK4 is
                      not set

24-Jul-2003: MRDFITS() - Added ROWS keyword to read only user-specified rows.

23-Jul-2003: AUTOHIST - Added NOCLIP keyword for POLYFILL call

18-Jul-2003: MAKE_ASTR - Corrected two typos introduced 15-Jul

15-Jul-2003: Astrometry routines updated to better support the Greisen &
                  Calabretta (2002, A&A, 395, 1061) standard
             EXTAST, MAKE_ASTR, PUTAST - Standard astrometry structure modified
                   to include LATPOLE keyword
             XYAD, ADXY - Alternate WCS astrometry keywords supported
             HEULER - Convert  FITS WCS astrometry between celestial, Galactic
                   and ecliptic coordinates
             WCS_GETPOLE - Compute the coordinates of the native pole for a 
                   non-polar projection
             WCS_ROTATE - Now calls WCS_GETPOLE to correctly work with 
                   non-zenithal projections
             SXADDPAR -- Added /SAVECOMMENT keyword to only modify comment
                   field if none previously exists
             WCSSPH2XY, WCSXY2SPHY, WCS_DEMO - Update conversions for conic 
                   projections
             FITS_CD_FIX - Only support projections in Greisen & Calabretta

14-Jul-2003: HROTATE - Update CDELT when transposing with AIP-style coordinates
             IMCONTOUR - Correct conversion of seconds to minute of time
             HISTOGAUSS - Correct computation of 95% confidence interval
             APER - Removed limitation on maximum sky radius

10-Jul-2003: SELECT_W -- Added SELECTIN keyword to pre-select specified items

27-Jun-2003: MEDARR - Change an ARG_PRESENT that should have been a KEYWORD_SET

18-Jun-2003: XY2AD, AD2XY - No more special treatment of tangent projection
             SRCOR - Changed an inner loop variable to type Long.

12-Jun-2003: GETROT - Preserve sign in CDELT output, added /SILENT keyword
             ARROWS - Now uses GETROT to give correct angle 

11-Jun-2003: DEREDD - Now has /UPDATE keyword to update input parameters
             HROT, HROTATE - Update CROTA2 astrometry correctly

5-Jun-2003:  MATCH - Work for scalar integer input parameters

3-Jun-2003:  QUERYDSS - Don't abort if SIMBAD can't translate the name.

19-May-2003: DB_ENT2HOST, DBRD, DBEXT_DBF, DBXVAL - fixed occasional problem 
                with byte swapping on Linux machines

12-May-2003: READFITS() - Now has a /CHECKSUM keyword to verify the value (if 
                    any) of the CHECKSUM keyword in the FITS header.
             FITS_TEST_CHECKSUM -  Return quietly if CHECKSUM keyword not found

             FXHMODIFY - FITS header can now be changed to arbitary size
             FXBREADM - Fix problem when using numeric columns

             IMCONTOUR - Accept Galactic coordinates, fix display of levels 

             Each procedure directory now includes a .idlwave_catalog file
             for use with the IDLWAVE Emacs mode.

5-May-2003:  CONS_RA, CONS_DEC - now work for the CARee' projection

2-May-2003:  SELECT_W - Now properly supports group leaders

30-Apr-2003: TBINFO - Store .tscal and .tzero tags as pointers, so as to  
                   preserve type information for each column
             TBGET() - Support unsigned integers, new pointer types of TSCAL
                    and TZERO returned by TBINFO

24-Apr-2003: REPSTR() - Fixed problem when multiple replacements extend the 
             string length

22-Apr-2003: QUERYSIMBAD - Added ERRMSG output keyword

18-Apr-2003: PUTAST - Don't assume celestial coordinates

16-Apr-2003: CURVAL -- Allow for non-celestial (e.g. Galactic) coordinates

09-Apr-2003: QUERYDSS - New OUTFILE keyword to write DSS image directly to disk
                        /NED keyword to use NED instead of SIMBAD name resolver

08-Apr-2003: QUERYSIMBAD - Turn off the extended name server when using /NED
                           Fix problem with negative declinations

07-Apr-2003: WEBGET() - Less restrictive search on Content-Type, work for
                    V5.6 on MacOS

03-Apr-2003: FDECOMP - Fixed bug in version parameter introduced October 2002

28-Mar-2003: QUERYSIMBAD - Added option to use the NED nameserver, better 
                 parsing of object names such as IRAS F10190+5349

17-Mar-2003: MWRFITS - Modified to reflect Jul-2002 change in FXADDPAR, to again
                       allow creation of a dummy dataset from undefined data
                     
14-Mar-2003: XYAD - Option to return results in Galactic or ecliptic coordinates
             EULER - Selection parameter now also available as a keyword

06-Mar-2003: WFPC2_METRIC -  Compute the distortion in a WFPC2 image and 
                             optionally return coordinates

03-Mar-2003: FXBREADM - Now correctly handle case where TSCAL/TZERO changes type

28-Feb-2003  FTAB_DELROW - Use COPY_LUN internally if V5.6 or later 

25-Feb-2003: FITS_INFO,FXMOVE - Improve speed by reading only first 36 lines of the
                     FITS header.
             MRD_HREAD - /FIRSTBLOCK option to read only the first 36 lines of
                     FITS header
             READFITS() - New HBUFFER keyword available to speed up the reading
                     of very large FITS headers. 

13-Feb-2003: TBINFO, TBGET() - Now recognize the unofficial "K" format for 
                     64 bit integers in FITS binary tables

06-Feb-2003: TBPRINT - Wasn't always printing the final row.

05-Feb-2003: HOST_TO_IEEE, IEEE_TO_HOST - now use /SWAP_IF_LITTLE_ENDIAN keyword
                    for 64 bit data types

04-Feb-2003: SXDELPAR - Work with headers with more than 32767 lines
             READFITS() - Improve speed by only reading entire header when
                        needed

29-Jan-2003: FITS_OPEN, FITS_READ - updated to allow reading gzip compressed 
                        files, (although there is a performance penalty)
             FITS_HELP & RDFITS_STRUCT now also work with compressed files.

21-Jan-2003: Library now requires at least V5.2.    New V5.1 directory contains
             the (frozen) tar files for V5.1 or later.   Procedures updated for
             V5.2 (recognizing unsigned integers) include FITS_OPEN, DBHELP,  
             DBINDEX, DBINDEX_BLK, DBFIND_SORT, DBEXT_IND and READFITS().

16-Jan-2003: FITS_INFO - Now works with gzip compressed files (if V5.3 or later)

14-Jan-2003: REPSTR() - Fix case where object and input string lengths are 
                        identical

27-Dec-2002: WRITEFITS - /CHECKSUM keyword to write checksum values in header
             MODFITS - Automatically update checksum keywords, (if present) adds
                       padding if new data size is smaller than the old

23-Dec-2002: New procedures for working with FITS checksums (data integrity)
            FITS_ADD_CHECKSUM -  Add or update the CHECKSUM and DATASUM 
                                  keywords in a FITS header
            FITS_ASCII_ENCODE() - Encode an unsigned longword as an ASCII string 
                                  to insert in a FITS header
            FITS_TEST_CHECKSUM() - Verify the values of the CHECKSUM and DATASUM 
                                  keywords in a FITS header

18-Dec-2002: PLANET_COORDS - Allow vector Julian Dates when using the /JPL
                             keyword.

15-Dec-2002: STARAST - Now include CTYPE keyword when writing FITS header

13-Dec-2002: FXBGROW - Can now be used to increase the number of rows in any
                       FITS binary table extension (formerly restricted to the
                       last extension)
             BLKSHIFT - Shift a block of data to a new (possibly overlapping) 
                  position in a file 
             FXBPARSE -  now explicitly parses the THEAP keyword        
             FXBCREATE - now has an optimization for the case where there are a
                large number of rows in a table, especially ones with small
                number of bytes.

             WRITEFITS - Fixed problem when using /APPEND and not supplying a 
                     header

11-Dec-2002: FXBWRITM - Allow more than 50 output columns when using pointers

23-Nov-2002: TEXTOPEN - Return calling sequence if no parameters supplied

22-Nov-2002: MEDARR - Use DIMEN keyword to MEDIAN in V5.6 or later
             PRODUCT() - Added /NAN keyword, documentation about V5.6 emulation
             RDFLOAT, READCOL - Use SKIP_LUN if V5.6 or later
             PSF_GAUSSIAN() - Now allows use of the ST_DEV keyword

21-Nov-2002: FITS_WRITE, FITS_READ - Removed NaNValue keyword, as NAN is 
                     recognized on all IDL machines since V5.1

20-Nov-2002: TBGET() - Bypass IEEE_TO_HOST call for improved speed

11-Nov-2002: CHECKSUM32 - Now works correctly on non- big endian machines

04-Nov-2002: FITSDIR - Major rewrite, no truncation of keyword display, option
                       to select displayed FITS keywords and alternates

18-Oct-2002: FDECOMP - Now accepts vector filenames
             DBHELP - Use vectorized version of FDECOMP internally

10-Oct-2002: FIND - Fix problem when PRINT= 'filename'

26-Sep-2002: ZBRENT() - Use MACHAR() to define machine precision

24-Sep-2002: GLACTC - Now has /SuperGalactic keyword to convert between 
                     celestial and SuperGalactic coordinates

             DBTARGET() - Find database entries within specified radius of 
                     supplied astronomical target name.
                   
20-Sep-2002: DBPRINT - New /AdjustFormat will adjust the format length for 
                string items to the maximum length for the entries to be 
                printed.    

13-Sep-2002: QueryUSNO - Query the USNO-A2.0 astrometric catalog by position

12-Sep-2002: LEGEND - Don't change scalar input keywords (THICK, PSYM) to 
                      vectors

             ADSTRING() - Now has /TRUNCATE keyword to truncate rather than
                     round the least significant digit.   Useful for creating 
                     IAU names from coordinates.

10-Sep-2002: RDFITS_STRUCT - Major rewrite to use FITS_OPEN and CREATE_STRUCT()
                 and avoid use of temporary files.

6-Sep-2002: QueryGSC() - Fix parsing of input RA and Dec coordinates

3-Sep-2002:  MRDFITS() - Fix possible problem with conflicting data structures
                      under V5.5 when reading variable length arrays

             WRITEFITS - Create a minimal primary header if supplied file 
                       name does not exist and /APPEND is set 
             FTPUT - Fix problem when existing table header contains no columns

             FINDPRO - Force lowercase extension to fix VMS problem

30-Aug-2002: New /SOCKETS directory contains procedures using the IDL SOCKET
             command to access Web servers.   These procedures require IDL
             V5.4 or later on either Unix or Windows machines

           WEBGET() - Use the IDL SOCKET procedure to get data from http servers
           QUERYGSC() - Query the Guide Star Catalog (GSC V2.2) at the Space
               Telescope Science Institute by position  
           QUERYDSS - Query the digital sky survey (DSS) on-line at the European
               Space Observatory (ESO) or STSCI servers
           QUERYSIMBAD - Query the SIMBAD name resolver at ESO to obtain J2000
               coordinates

           RADEC - Now has /HOURS keyword to input RA in hours 

13-Aug-2002: ASINH() - Now works for multidimensional arrays 

31-Jul-2002: DB_ITEM, TBPRINT, FTPRINT, FTAB_EXT, CREATE_STRUCT - Use 
                 STRSPLIT() instead of STR_SEP() for V5.3 or later

24-Jul-2002: FXADDPAR - Now forces EXTEND keyword to appear immediately after
                        last NAXISi keyword, per FITS rules

19-Jul-2002: PARTVELVEC - Added /OVER keyword to not erase previous plot

16-Jul-2002: BREAK_PATH(), FIND_WITH_DEF() - Use STRSPLIT instead of STR_SEP() 
                    for V5.3 or later

12-Jul-2002: CNTRD - Check if more than 1 pixel achieves the maximum value

28-Jun-2002: TSUM() - Fix problem (IMAX undefined) if only 1 parameter supplied

27-Jun-2002: TEXTOPEN - Now has a /SILENT keyword
             FORPRINT - Now has a /NoCOMMENT keyword.   The /SILENT keyword
                  is now used only to suppress informational messages.

26-Jun-2002: PUTAST - Allow direct specification of CTYPE keywords

24-Jun-2002: WCS_ROTATE - Ensure argument of ASIN() is -1 < x < 1 after roundoff

14-Jun-2002: MODFITS - Work for FITS extension headers using the STScI 
                       inheritance convention
                     
12-Jun-2002: EQ2HOR, HOR2EQ - Convert between equatorial (RA-Dec) and horizon
                 (alt-az) coordinates, including the effects of precession,
                 nutation, aberration, and refraction

             CO_ABERRATION - Calculate change in RA and Dec due to aberration

11-Jun-2002: ALTAZ2HADEC - Convert Horizon (Alt-Az) coordinates to Hour Angle 
                            and Declination
             HADEC2ALTAZ -  Converts Hour Angle and Declination to Horizon 
                            (alt-az) coordinates

07-Jun-2002: REPSTR() - Make loop long integer, vectorize STRLEN call

05-Jun-2002: RESISTANT_MEAN - Improve sigma determination  (conditional test
                    was done on the wrong variable, higher order correction)

04-Jun-2002: PLOTERROR, OPLOTERROR - Fix Jan 2002 speed update to work with 
                       logarithmic plots

03-Jun-2002: Two new contributions from Chris O'Dell in pro/astro
             CO_NUTATE - Calculate changes in RA and Dec due to nutation of the
                          Earth's rotation
             CO_REFRACT() - Calculate correction to altitude due to atmospheric
                          refraction

30-May-2002: PLOTHIST - don't plot out of range with /FILL, added HALFBIN 
         keyword, and made half bin shift default for integer data only 

28-May-2002: RDFLOAT - Now has COLUMNS keyword to read only selected columns

             STREBCASC has been removed the Library, though it is still 
             available in the ftp://idlastro.gsfc.nasa.gov/pub/obsolete
             directory.

20-May-2002 -GEO2GEODETIC(), GEO2GEODETIC() - new EQUATORIAL_RADIUS and
                 POLAR_RADIUS keywords
                

17-May-2002 -GEO2GEODETIC(), GEO2GEODETIC() - new PLANET keyword to convert
                 between planetographic and planetodetic coordinates

             READCOL - Faster algorithm, now use STRSPLIT if V5.3 or later
         
15-May-2002: New procedures for converting between geographic and geodetic, 
             geomagnetic & Earth-centered inertial coordinates from  
             Pascal Saint-Hilaire (ETH).

 ECI2GEO() - Convert Earth-centered inertial coordinates to geographic coords
 GEO2ECI() - Convert geographic coordinates to Earth-centered inertial coords 
 GEO2GEODETIC() - Convert from geographic to geodetic coordinates
 GEO2MAG() - Convert from geographic to geomagnetic coordinates
 GEODETIC2GEO() - Convert from geodetic to geographic coordinates
 MAG2GEO() - Convert from geomagnetic to geographic coordinates

 trim.pro has been removed from the Library.   It is still available in 
  ftp://idlastro.gsfc.nasa.gov/pub/obsolete or in the SolarSoft directory 
  http://sohowww.nascom.nasa.gov/solarsoft/gen/idl/ 

10-May-2002: Robust statistics procedures in contrib/freudenreich are being
             transferred to the main library in the new /pro/robust directory.
             The first 8 procedures to be transferred are 
              
   AUTOHIST  - Draw a histogram using automatic bin-sizing.
   BIWEIGHT_MEAN()  -  Iterative biweighted determination of mean and std. dev.
   HISTOGAUSS  -  Outlier-resistant autoscaled histogram drawing
   RESISTANT_MEAN -  Outlier-resistant determination of  mean and std. deviation.
   ROB_CHECKFIT() - Utility to determine quality of a fit and return biweights
   ROBUST_LINEFIT() - Robust fit of Y vs X (or bisector of Y vs X and X vs Y)
   ROBUST_POLY_FIT() - Robust polynomial fit
   ROBUST_SIGMA()  -   Robust analog of the standard deviation
              
07-May-2002: HREBIN - Fix astrometry update problem when contracting by an 
          exact integral factor

30-Apr-2002: FXPOSIT - Now recognize file names with internal spaces
             WRITEFITS, FITS_INFO - Use FILE_SEARCH() instead of FINDFILE()
                       if V5.5 or later

24-Apr-2002: FIND_ALL_DIR - Now follows Unix logical links
             FITS_READ - Don't erase error message when closing the file

17-Apr-2002: ADSTRING() - Fix possible error in seconds display when the 
                   precision parameter is zero.

11-Apr-2002: GLACTC - Major rewrite, now assumes FK5 coordinates by default,
                   added /FK4 keyword, use external precession routines

10-Apr-2002: CLEANPLOT - Now has /ShowOnly keyword to display but not reset
                  plotting keywords with nondefault values

04-Apr-2002: AVG() - Return NAN if all input values to be averaged are NAN

27-Mar-2002: READFITS - Fixed (again) for compressed files on little endian 
                         machines

25-Mar-2002: HROT - Correct astrometry when /PIVOT keyword is set
             IMCONTOUR -  Added XMID, YMID keywords to specify offset position 
                 for labeling (default is still center of image)

21-Mar-2002: AVG() -- Always use double precision computations internally

12-Mar-2002: SXPAR() - Make sure extracted vectors of mixed data type are
                       returned with the highest type.

11-Mar-2002: PSF_GAUSSIAN() - Suppress floating underflow messages, added
                     /DOUBLE keyword, integer centroid now defined as the center
                      of a pixel.

02-Mar-2002: DBMATCH() - Fix typo when searching on sorted items

22-Feb-2002: DBFIND_ENTRY - better checking of out of range entry numbers

20-Feb-2002: MRDFITS/MWRFITS - Fix major bug in the processing of unsigned 
                        integers

03-Feb-2002: MRDFITS() - Fix problem when both the first and the last character
                      in a TTYPEnn value are invalid structure tag characters

28-Jan-2002: UVBYBETA - Major rewrite, *slightly modified calling sequence*

24-Jan-2002: PLOTERROR, EXTAST, HROTATE- Fixed dumb typos recently introduced

22-Jan-2002: SXADDPAR  - BEFORE and AFTER keywords now apply to (FITS) 
                        COMMENT keyword (behavior already in FXADDPAR). 

16-Jan-2002: PLOTERROR, OPLOTERROR - Only draw error bars with in !X.CRANGE 
                       (to improve speed)

15-Jan-2002: EXTAST  - Recognize CTYPE1 = 'GSS--RA' keyword in FITS header
             TVELLIPSE -  Negative XC, YC values allowed noninteractively  
                         if /DATA is set

12-Jan-2002: AITOFF_GRID - Several tweaks, plot only hours not minutes for  
                          LABEL=2 
             PLANCK() - Improve precision of constants, use MACHAR for overflow

11-Jan-2002: MINMAX() - Now has DIMEN keyword (V5.5 only) to work over 1 
                        dimension of an array
             DBPRINT - Don't write an initial page eject

01-Jan-2002: FSTRING() - Check if version is V5.4 or later (when 1024 element
                         string formatting limit was removed) 

31-Dec-2001: FREBIN() - Improve speed by addressing arrays in memory order
                         (bug fixed 14-jan-2002)

30-Dec-2001: SXPAR() - Added /SILENT keyword to suppress warning messages

16-Dec-2001: *.doc files in the /text directory have been renamed to *.readme

             EXTAST, HROT, HROTATE, HCONGRID, HBOXAVE, HREBIN, HREVERSE - 
             Recognize PC00m00n (pixel coordinate matrix) keywords for FITS 
             astrometry  (sigh...) 

15-Dec-2001: MRDFITS() - Major upgrade (V2.5) now supports unsigned integer
             types (/UNSIGNED), aliases between FITS column names and structure
             tag names, 64 bit integers, and /POINTER_VAL option to map
             variable length binary tables into IDL pointers

             MWRFITS - Major upgrade (V1.0) to support unsigned integer types,
             64 bit integers, aliases, and writing of variable length binary 
             table arrays.

10-Dec-2001: DBEDIT - Work for entry numbers greater than 32767 

9-Dec-2001:  LSF_ROTATE - Create a 1-d convolution kernel to broaden a spectrum from 
             a rotating star

7-Dec-2001:  FITS_OPEN - Now uses 64 bit pointers in the file control block to
                 allow access to very large FITS files

26-Nov-2001: FORPRINT - Bug introduced August 2001 would skip first data point 
                  when printing to a file.
             AVG() - Now accepts a scalar input value
             EXPAND_TILDE() - Can now parse a directory such as '~landsman'

25-Nov-2001: MMM - Avoid possible integer overflow for 16 bit arrays

23-Nov-2001: DBPRINT - No page eject for TEXTOUT=5
             DBHELP - Fix display of multiple valued items with /SORT

20-Nov-2001: CLEANPLOT - Now sets !P.color correctly for 16 bit TRUECOLOR 

             New contrib/maskinterp directory contains procedures by Joe
             Harrington (Cornell) and students for 2-d interpolation using 
             a choice of 2-d fitting functions, given a bad pixel mask.
             
18-Nov-2001: GAUSSIAN() - Use machar() to avoid underflows, output double
                 precision, if input is double precision

11-Nov-2001: PRODUCT() - Use internal vector algorithm from  C. Markwardt

8-Nov-2001:  MODFITS - Major internal rewrite to use FITS_OPEN.   Now works 
                    with unsigned integers, and allows file control block unit
                    instead of filename.

             Tape I/O procedures have been removed from the Library.   They 
             are still available in ftp://idlastro.gsfc.nasa.gov/pub/obsolete
             or in the SolarSoft directory 
             http://sohowww.nascom.nasa.gov/solarsoft/gen/idl/

6-Nov-2001:  TVLASER - /TRUE now also applies when reading from truecolor 
                display (formerly applied only when an image array was supplied) 

29-Oct-2001: STR_INDEX(), NINT(), FORPRINT, EXPAND_TILDE(), BREAK_PATH(), 
             TBDELCOL, TAG_EXIST(), MODFITS, - 
             Now use SIZE(/TNAME) rather than DATATYPE()  

19-Oct-2001: JPLEPHINTERP - Fixed minor bug to now recognize "NUTATIONS" and 
                            "LIBRATIONS" object names
             READFITS()/HEADFITS() - One can now supply a file unit number 
                        instead of a file name

17-Oct-2001: LINTERP - Work for unsigned, 64bit integers
             FTCREATE - Work for one row tables, option to create just header

16-Oct-2001: SXADDPAR - Treat COMMENT or blank keywords like HISTORY keywords
             SXADDHIST - Can now also be used for COMMENT or blank keywords 
             MKHDR - Added COMMENTS giving FITS definition in primary header

14-Oct-2001: DBBUILD - Fix error display message for incorrect data type

13-Oct-2001: PLOTHIST - Now has /NAN keyword to check for NAN values
             APER - Set bad fluxes to !VALUES.F_NAN if /FLUX is set

11-Oct-2001: KSTWO - Fixed problem when supplied (integer) arrays with equal 
                     values

1-Oct-2001:  GET_DATE - Can now convert systime() format to FITS date format
             MRD_SKIP - More forgiving when reading compressed FITS files with
                        incorrect byte padding

25-Sep-2001: FILTER_IMAGE() - Now has PSF keyword to allow reuse of the Gaussian
                           convolution kernel

19-Sep-2001: TABINV, QUADTERP, YDN2MD - Now use VALUE_LOCATE internally
             FREBIN, GCIRC, CLEANPLOT - Updated to V5.1 features, e.g. 
                    size(tname)

14-Sep-2001: READFITS() - Support (unofficial) 64bit integer format

30-Aug-2001: FORPRINT - Much faster printing to a file, added COMMENT keyword
             TEXTOPEN - filepath(/TERMINAL) not allowed with IDLDE under V5.4

8-Aug-2001:  EXTAST - Don't choke on headers with only one CTYPE keyword

6-Aug-2001:  ARCBAR - Use device-independent label offset positioning  

31-Jul-2001: FXBWRITM - Added ability to pass columns using pointers
             FXBREADM - Can now read variable length binary tables, ability
                        to read unlimited number of columns via POINTER keyword

29-Jul-2001: IDL Version 5.1 or greater is now assumed default for Astro Library
             This means that (Size,/tname), !ERROR_STATE, NAN values and 
             /SWAP_IF_LITTLE keyword to OPENR are recognized. 
             Updated procedures READFITS(), IMF(), IEEE_TO_HOST, WRITEFITS

27-Jul-2001: TDB2TDT() - Compute relativistic timing correction from geocentric 
                       (TT) to solar system barycentric (TDB) coordinates
             BARYVEL, PLANET_COORDS - Now have a /JPL keyword to use JPL 
                        ephemeris files

             ASTROLIB - Now check if system variable exists before defining it

26-Jul-2001: IDL Database routines can now handle longword and unsigned integer 
                datatypes (for IDL V5.2 and later).   Modified routines are
                DBCREATE, DBXVAL(), DBFIND(), DBFIND_SORT(), DBINDEX_BLK and
                DBBUILD. 

24-Jul-2001: READCOL -- Added COMMENT keyword

22-Jul-2001: FXBWRITM - Fixed bug when column numbers specified instead of names

             JPL Ephemeris routines developed by C. Markwardt now available for
             high precision planetary positions and velocities 
             
             JPLEPHINTERP - Interpolate position and motion of planetary bodies
               using a JPL Ephemeris
             JPLEPHREAD - Open and read JPL DE200 or DE405 Ephemeride FITS File

9-Jul-2001:  astron.html file now includes one-line descriptions

13-Jun-2001: RDFLOAT - No integer overflow when skipping more than 32767 lines

8-Jun-2001:  PRECESS_XYZ - Use two parameter call to ATAN (major bug fix)

5-Jun-2001:  CHECKSUM32 - Compute the 32bit checksum of an array 
                         (ones-complement arithmetic)
             N_BYTES() - Return the number of bytes in an IDL variable

4-Jun-2001:  FILTER_IMAGE - Recognize NaN values for SMOOTH, use /EVEN for
                  MEDIAN

23-May-2001: MEDARR - V5.4 fix for new SIZE() definition of undefined variable 

4-May-2001   COPY_STRUCT, COPY_STRUCT_INX - Use long integers internally

3-May-2001:  MRDFITS() - Added a strtrim when parsing binary format string
             FTAB_HELP, FTAB_EXT - Don't call fits_close if a FITS control block
                         supplied
             FTAB_PRINT - Don't leave any open files

26-Apr-2001: TCTOOL - in /contrib/malumuth has new annotation capabilities

25-Apr-2001: FITS_READ - Ensure EXTEND keyword is in primary header if 
                 extensions are present 

11-Apr-2001: TSUM() - Now work for non-integer values of IMIN, IMAX parameters

6-Apr-2001: MWRFITS - Now recognize '~' symbol in Unix directory name

31-Mar-2001: FITS_WRITE - Ensure required table extension keywords are in the
                      correct order

28-Mar-2001: PLOTSYM - Improved star symbol, added COLOR keyword

21-Mar-2001: OPLOTERROR - Removed bug introduced Jan. 2001 (NSUM keyword)
             CLEANPLOT - Mac specific fix for 32 bit (?)  visual depth

17-Mar-2001: ASINH() - Return the inverse hyperbolic sine of its argument

12-Mar-2001: RDPLOT - Use !MOUSE.BUTTON instead of !ERR, skip translation table
                      for 24bit color.

9-Mar-2001:  DBEXT_IND - Fix for extraction of indexed multiple-valued items

             FACTOR, GETWRD, POLREC - Upgraded to match latest version of 
                         JHUAPL library (major upgrade for FACTOR) 

6-Mar-2001:  AITOFF_GRID, EQPOLE_GRID - Now uses _EXTRA facility to control 
                  grid lines.   Added CHARSIZE, CHARGRID keywords

13-Feb-2001: HERMITE - Now use VALUE_LOCATE instead of TABINV
             TVLASER - Fix problem with /NOCLOSE and unequal X,Y axes

08-Feb-2001: APER - No bad pixel check if badpix[0] = badpix[1]

02-Feb-2001: FIND_ALL_DIR - In Windows OS, use EXPAND_PATH(/ALL, /ARRAY) if 
                   since V5.3

30-Jan-2001: The contrib/bhill directory now has the following object-oriented
             display widgets:
             XCTVN - Displays a series of images for examination and comparison
             XINSPECT, XINSPECT2 - Browse a big FITS image (or two of them) 
                without having to read the entire image into memory.  

29-Jan-2001: PLOTERROR - Fix logic when NSUM keyword or !P.NSUM is set

23-Jan-2001: VALUE_LOCATE - Emulate the intrinsic IDL function introduced in
                  V5.3  (bracket search values in a monotonic vector)
             CNTRD - Avoid integer wraparound for unsigned integers
             PUTAST - Use GET_EQUINOX to get the equinox value

19-Jan-2001: EXTAST - Signal that if CTYPE = 'PIXEL' then there is no astrometry
             CURVAL - Replace !ERR calls with !MOUSE.BUTTON

15-Jan-2001: IRAFRD - No longer read past end of file for V5.4 compatibility
             MRD_SKIP - Direct check for gzip compressed files under V5.4

29-Dec-2000: MRD_STRUCT - Fix concatenation of temporary directory & file name
                          under Windows

26-Dec-2000: XMEDSKY - Fixed conditional WHERE, added NSIG keyword 

23-Dec-2000: CALZ_UNRED - Deredden a galaxy spectrum using the Calzetti et al.
                          (2000) parameterization

             JPRECESS - Make sure proper motions are (at least) floating pt.

22-Dec-2000: CHECK_FITS - Fixed bug when updating DATATYPE keyword

18-Dec-2000: GAL_UVW - Compute the Galactic space velocity (U,V,W) of a star

16-Dec-2000: HEADFITS(), FXPOSIT, FXMOVE, MRD_HREAD - Now have a /SILENT keyword
            to suppress warning messages about invalid characters in a FITS file

             FITSDIR - Now has /EXTEN keyword to display info on extensions, 
            now works with compressed files, additional alternate keywords

8-Dec-2000:  MODFITS - Improved check for incompatible input/output sizes

7-Dec-2000:  NUTATE - Corrected minor typos in d_lng term

4-Dec-2000:  PLOTERROR, OPLOTERROR - Now ignore data points with NAN values

2-Dec-2000:  DBINDEX, DBEXT_IND - Now allow multiple-valued index items

28-Nov-2000: DATE_CONV() - Added FITS input/output format YYYY-MM-DDTHH:MM:SS.SS

17-Nov-2000: DBFIND, DBFIND_ENTRY, DBFIND_SORT, DBSEARCH, IMDBASE - Now
                have a Count keyword; deprecate use of !ERR

16-Nov-2000: MWRFITS - Fix scaling and missing keywords in image extensions

10-Nov-2000: MOONPOS - Now uses improved expressions for the elongation, 
               & mean anomaly (very small change in output results).

09-Nov-2000: HASTROM - Fixed bug if two FITS headers were not at the same 
                       equinox.

03-Nov-2000: CLEANPLOT - Also reset negative !X values

28-Oct-2000: AD2XY, EXTAST, GETROT, HROT, HROTATE, PUTAST, XY2AD - Now use a  
             consistent conversion between CROTA and CD matrix notation

25-Oct-2000: LEGEND - Added an option (LINESTYLE=-99) to left-justify text

11-Oct-2000: DBXVAL - Work for multiple-valued strings

9-Oct-2000:  CNTRD - Better checking if centroid is at edge of image

3-Oct-2000:  FITS_WRITE - Now pad data (except ASCII Tables) with zero bytes
                          per FITS standard.

29-Sep-2000: XCTV, XCTV2 - Image display widgets in contrib/bhill directory 
                 now allow aperture photometry and entire image statistics

27-Sep-2000: EXPAND_TILDE - Made more robust

22-Sep-2000: STARAST - Added /RightHanded to indicate a right-handed coordinate
                system, and HDR input-output keyword to update FITS astrometry        

21-Sep-2000: TVLIST - Removed broken call to !TEXTUNIT when no image supplied


; NAME:
;       ABSCAL
; PURPOSE:
;       Apply the FITS BZERO and BSCALE keyword values to a data array
;
; CALLING SEQUENCE:
;       RESULT = ABSCAL( Value, Header, /DEBUG)
;
; INPUTS:
;       VALUE -  Any scalar, vector, or array (usually an integer type giving a
;               relative intensity).
;       HEADER - A FITS  header array containing the absolute calibration
;               keyword BSCALE, and optionally BZERO and BUNIT.
;
; OUTPUT:
;       RESULT = BSCALE*VALUE + BZERO, where the BSCALE and BZERO scalars
;               are taken from the FITS header.  
;               If the absolute calibration keywords do not exist, then
;               RESULT = VALUE, and !ERR = -1.
;
; OPTIONAL INPUT KEYWORD:
;       /DEBUG - If DEBUG is set, then ABSCAL will print the
;               calibration units given by the BUNIT keyword.
;
; REVISION HISTORY:
;       Written W. Landsman, STX Corporation     January 1987
;       Use DEBUG keyword instead of !DEBUG      September 1995
;       Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;     AD2XY
; PURPOSE:
;     Compute X and Y from  RA and DEC and a FITS  astrometry structure
; EXPLANATION:
;     The procedure WCSXY2SPH is used to compute native coordinates, and the 
;     inverse of the CD matrix is applied to obtain X and Y. AD2XY is meant to
;     be used internal to other procedures.   For interactive purposes, use ADXY.
;
; CALLING SEQUENCE:
;     AD2XY, a ,d, astr, x, y   
;
; INPUTS:
;     A -     R.A. in DEGREES, scalar or vector
;     D -     Dec. in DEGREES, scalar or vector
;     ASTR - astrometry structure, output from EXTAST procedure containing:
;        .CD   -  2 x 2 array containing the astrometry parameters CD1_1 CD1_2
;               in DEGREES/PIXEL                                   CD2_1 CD2_2
;        .CDELT - 2 element vector giving increment at reference point in
;               DEGREES/PIXEL
;        .CRPIX - 2 element vector giving X and Y coordinates of reference pixel
;               (def = NAXIS/2) in FITS convention (first pixel is 1,1)
;        .CRVAL - 2 element vector giving R.A. and DEC of reference pixel 
;               in DEGREES
;        .CTYPE - 2 element vector giving projection types 
;        .LONGPOLE - scalar longitude of north pole (default = 180) 
;        .PROJP1 - Scalar parameter needed in some projections
;        .PROJP2 - Scalar parameter needed in some projections
;;
; OUTPUTS:
;     X     - row position in pixels, scalar or vector
;     Y     - column position in pixels, scalar or vector
;
;     X,Y will be in the standard IDL convention (first pixel is 0), and
;     *not* the FITS convention (first pixel is 1)         
; REVISION HISTORY:
;     Converted to IDL by B. Boothman, SASC Tech, 4/21/86
;     Use astrometry structure,  W. Landsman      Jan. 1994   
;     Do computation correctly in degrees  W. Landsman       Dec. 1994
;     Only pass 2 CRVAL values to WCSSPH2XY   W. Landsman      June 1995
;     Don't subscript CTYPE      W. Landsman       August 1995        
;     Converted to IDL V5.0   W. Landsman   September 1997
;     Understand reversed X,Y (X-Dec, Y-RA) axes,   W. Landsman  October 1998
;     Consistent conversion between CROTA and CD matrix W. Landsman October 2000
;     No special case for tangent projection W. Landsman June 2003

; NAME:
;       ADSTRING
; PURPOSE:
;       Return RA and Dec as character string(s) in sexigesimal format.
; EXPLANATION:
;       RA and Dec may be entered as either a 2 element vector or as
;       two separate vectors (or scalars).  One can also specify the precision 
;       of the declination in digits after the decimal point.
;
; CALLING SEQUENCE
;       result = ADSTRING( ra_dec, precision, /TRUNCATE )           
;               or
;       result = ADSTRING( ra,dec,[ precision, /TRUNCATE ] )
;
; INPUTS:
;       RA_DEC - 2 element vector giving the Right Ascension and declination
;               in decimal degrees.
;                     or
;       RA     - Right ascension in decimal degrees, numeric scalar or vector
;       DEC    - Declination in decimal degrees, numeric scalar or vector
;
; OPTIONAL INPUT:
;       PRECISION  - Integer scalar (0-4) giving the number of digits after the 
;               decimal of DEClination.   The RA is automatically 1 digit more.
;               This parameter may either be the third parameter after RA,DEC 
;               or the second parameter after [RA,DEC].  It is not available 
;               for just DEC.   If no PRECISION parameter is passed, a 
;               precision of 1 for both RA and DEC is returned to maintain 
;               compatibility with past ADSTRING functions.    Values of 
;               precision larger than 4 will be truncated to 4.    If
;               PRECISION is 3 or 4, then RA and Dec should be input as 
;               double precision.
; OPTIONAL INPUT KEYWORD:
;       /TRUNCATE - if set, then the last displayed digit in the output is 
;               truncated in precision rather than rounded.   This option is
;               useful if ADSTRING() is used to form an official IAU name 
;               (see http://vizier.u-strasbg.fr/Dic/iau-spec.htx) with 
;               coordinate specification.   The IAU name will typically be
;               be created by applying STRCOMPRESS/REMOVE) after the ADSTRING()
;               call, e.g. 
;              strcompress( adstring(ra,dec,0,/truncate), /remove)   ;IAU format
; OUTPUT:
;       RESULT - Character string(s) containing HR,MIN,SEC,DEC,MIN,SEC formatted
;               as ( 2I3,F5.(p+1),2I3,F4.p ) where p is the PRECISION 
;               parameter.    If only a single scalar is supplied it is 
;               converted to a sexigesimal string (2I3,F5.1).
;
; EXAMPLE:
;       (1) Display CRVAL coordinates in a FITS header, H
;
;       IDL> crval = sxpar(h,'CRVAL*')  ;Extract 2 element CRVAL vector (degs)
;       IDL> print, adstring(crval)     ;Print CRVAL vector sexigesimal format
;
;       (2)  print,adstring(30.42,-1.23,1)  ==>  ' 02 01 40.80  -01 13 48.0'
;            print,adstring(30.42,+0.23)    ==>  ' 02 01 40.8   +00 13 48.0'    
;            print,adstring(+0.23)          ==>  '+00 13 48.0'
;
;       (3) The first two calls in (2) can be combined in a single call using
;           vector input
;              print,adstring([30.42,30.42],[-1.23,0.23], 1)
; PROCEDURES CALLED:
;       FSTRING(), RADEC, SIXTY()
;
; REVISION HISTORY:
;       Written   W. Landsman                      June 1988
;       Addition of variable precision and DEC seconds precision fix. 
;       ver.  Aug. 1990 [E. Deutsch]
;       Output formatting spiffed up       October 1991 [W. Landsman]
;       Remove ZPARCHECK call, accept 1 element vector  April 1992 [W. Landsman]
;       Call ROUND() instead of NINT()    February 1996  [W. Landsman]
;       Check roundoff past 60s           October 1997   [W. Landsman]
;       Work for Precision =4             November 1997  [W. Landsman]
;       Converted to IDL V5.0   W. Landsman 24-Nov-1997
;       Major rewrite to allow vector inputs   W. Landsman  February 2000
;       Fix possible error in seconds display when Precision=0 
;                               P. Broos/W. Landsman April 2002
;       Added /TRUNCATE keyword, put leading zeros in seconds display
;                               P. Broos/W. Landsman September 2002
;       Hours values always less than 24   W. Landsman September 2002

; NAME:
;	ADXY
; PURPOSE:
;	Use a FITS header to convert celestial (RA,Dec) to pixel coordinates
; EXPLANATION:
;	Use an image header to compute X and Y positions, given the
;	RA and Dec in decimal degrees.  
;
; CALLING SEQUENCE:
;	ADXY, HDR		;Prompt for Ra and DEC 
;	ADXY, hdr, a, d, x, y, [ /PRINT ]
;
; INPUTS:
;	HDR - FITS Image header containing astrometry parameters
;
; OPTIONAL INPUTS:
;	A - Right ascension in decimal DEGREES, scalar or vector
;	D - Declination in decimal DEGREES, scalar or vector        
;
;	If A and D are not supplied, user will be prompted to supply
;	them in either decimal degrees or HR,MIN,SEC,DEG,MN,SC format.
;
; OPTIONAL OUTPUT:
;	X     - row position in pixels, same number of elements as A and D
;	Y     - column position in pixels
;
;       X and Y will be in standard IDL convention (first pixel is 0) and not
;       the FITS convention (first pixel is 1).
; OPTIONAL KEYWORD INPUT:
;	/PRINT - If this keyword is set and non-zero, then results are displayed
;		at the terminal.
;
; OPERATIONAL NOTES:
;	If less than 5 parameters are supplied, or if the /PRINT keyword is
;	set, then the X and Y positions are displayed at the terminal.
;
;	If the procedure is to be used repeatedly with the same header,
; 	then it would be faster to use AD2XY.
;
; PROCEDURES CALLED:
;	AD2XY, ADSTRING(), EXTAST, GETOPT()
;
; REVISION HISTORY:
;	W. Landsman                 HSTX          January, 1988
;	Use astrometry structure   W. Landsman   January, 1994	
;	Changed default ADSTRING format   W. Landsman    September, 1995
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;      AFhread
; PURPOSE:
;      Subroutine of WFPCREAD to read a GEIS header from an HST STSDAS image.
; EXPLANATION:
;       This procedure reads a GEIS header from an HST image.   It then looks
;       if a .SHH file is present for FOC images to calculate better 
;       astrometry by getting the current PSANGLV3 from this file.   Called by
;        WFPCREAD.PRO
;
; CALLING SEQUENCE:
;       AFhread, HdrFile, hdr
;
; INPUTS:
;       HdrFile - scalar string giving name of STSDAS header for an FOC image   
;
; OUTPUTS:
;       hdr - string array, FITS header for the FOC image.    The position
;               angle of the V3 axis of HST (PSANGLV3) is added, if it could 
;               be found in the .SHH file       
; PROCEDURE CALLS:
;       STRN(), SXADDPAR, SXHREAD, SXPAR()
; REVISION HISTORY:
;       Written         Eric W. Deutsch  (U. of Washington)    June, 1994
;       Documentation update   W. Landsman  (HSTX)             July, 1994
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Removed call to EXIST() function   W. Landsman        April 1999

; NAME:
;       AIRTOVAC
; PURPOSE:
;       Convert air wavelengths to vacuum wavelengths 
; EXPLANATION:
;       Wavelengths are corrected for the index of refraction of air under 
;       standard conditions.  Wavelength values below 2000 A will not be 
;       altered.  Uses the IAU standard for conversion given in Morton 
;       (1991 Ap.J. Suppl. 77, 119)
;
; CALLING SEQUENCE:
;       AIRTOVAC, WAVE
;
; INPUT/OUTPUT:
;       WAVE - Wavelength in Angstroms, scalar or vector
;               WAVE should be input as air wavelength(s), it will be
;               returned as vacuum wavelength(s).  WAVE is always converted to
;               double precision upon return.
;
; EXAMPLE:
;       If the air wavelength is  W = 6056.125 (a Krypton line), then 
;       AIRTOVAC, W yields an vacuum wavelength of W = 6057.8019
;
; METHOD:
;       See Morton (Ap. J. Suppl. 77, 119) for the formula used
;
; REVISION HISTORY
;       Written W. Landsman                November 1991
;       Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;       AITOFF
; PURPOSE:
;       Convert longitude, latitude to X,Y using an AITOFF projection.
; EXPLANATION:
;       This procedure can be used to create an all-sky map in Galactic 
;       coordinates with an equal-area Aitoff projection.  Output map 
;       coordinates are zero longitude centered.
;
; CALLING SEQUENCE:
;       AITOFF, L, B, X, Y 
;
; INPUTS:
;       L - longitude - scalar or vector, in degrees
;       B - latitude - same number of elements as L, in degrees
;
; OUTPUTS:
;       X - X coordinate, same number of elements as L.   X is normalized to
;               be between -180 and 180
;       Y - Y coordinate, same number of elements as L.  Y is normalized to
;               be between -90 and 90.
;
; NOTES:
;       See AIPS memo No. 46, page 4, for details of the algorithm.  This
;       version of AITOFF assumes the projection is centered at b=0 degrees.
;
; REVISION HISTORY:
;       Written  W.B. Landsman  STX          December 1989
;       Modified for Unix:
;               J. Bloch        LANL SST-9      5/16/91 1.1
;       Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;       AITOFF_GRID
;
; PURPOSE:
;       Produce an overlay of latitude and longitude lines over a plot or image
; EXPLANATION:
;       The grid is plotted on the current graphics device. AITOFF_GRID 
;       assumes that the ouput plot coordinates span the x-range of 
;       -180 to 180 and the y-range goes from -90 to 90.
;
; CALLING SEQUENCE:
;
;       AITOFF_GRID [,DLONG,DLAT, LABEL=, /NEW, CHARTHICK=, CHARSIZE=, _EXTRA=]
;
; OPTIONAL INPUTS:
;
;       DLONG   = Optional input longitude line spacing in degrees. If left
;                 out, defaults to 30.
;       DLAT    = Optional input latitude line spacing in degrees. If left
;                 out, defaults to 30.
;
; OPTIONAL INPUT KEYWORDS:
;
;       LABEL           = Optional keyword specifying that the latitude and
;                         longitude lines on the prime meridian and the
;                         equator should be labeled in degrees. If LABELS is
;                         given a value of 2, i.e. LABELS=2, then the longitude
;                         labels will be in hours instead of degrees.
;        CHARSIZE       = If /LABEL is set, then CHARSIZE specifies the size
;                         of the label characters (passed to XYOUTS)
;        CHARTHICK     =  If /LABEL is set, then CHARTHICK specifies the 
;                         thickness of the label characters (passed to XYOUTS)
;       /NEW          =   If this keyword is set, then AITOFF_GRID will create
;                         a new plot grid, rather than overlay an existing plot.
;
;       Any valid keyword to OPLOT such as COLOR, LINESTYLE, THICK can be 
;       passed to AITOFF_GRID (though the _EXTRA facility) to to specify the
;       color, style, or thickness of the grid lines.
; OUTPUTS:
;       Draws grid lines on current graphics device.
;
; EXAMPLE:
;       Create a labeled Aitoff grid of the Galaxy, and overlay stars at 
;       specified Galactic longitudes, glong and latitudes, glat
;
;       IDL> aitoff_grid,/label,/new        ;Create labeled grid
;       IDL> aitoff, glong, glat, x,y      ;Convert to X,Y coordinates
;       IDL> plots,x,y,psym=2              ;Overlay "star" positions
;
; PROCEDURES USED:
;       AITOFF
; NOTES:
;       If labeling in hours (LABEL=2) then the longitude spacing should be
;       a multiple of 15 degrees
;
; AUTHOR AND MODIFICATIONS:
;
;       J. Bloch        1.2     6/2/91
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Create default plotting coords, if needed   W. Landsman  August 2000
;       Added _EXTRA, CHARTHICK, CHARSIZE keywords  W. Landsman  March 2001
;       Several tweaks, plot only hours not minutes W. Landsman January 2002

; NAME:
;      APER
; PURPOSE:
;      Compute concentric aperture photometry (adapted from DAOPHOT) 
; EXPLANATION:
;     APER can compute photometry in several user-specified aperture radii.  
;     A separate sky value is computed for each source using specified inner 
;     and outer sky radii.   
;
; CALLING SEQUENCE:
;     APER, image, xc, yc, [ mags, errap, sky, skyerr, phpadu, apr, skyrad, 
;                       badpix, /EXACT, /FLUX, PRINT = , /SILENT, SETSKYVAL = ]
; INPUTS:
;     IMAGE -  input image array
;     XC     - vector of x coordinates. 
;     YC     - vector of y coordinates
;
; OPTIONAL INPUTS:
;     PHPADU - Photons per Analog Digital Units, numeric scalar.  Converts
;               the data numbers in IMAGE to photon units.  (APER assumes
;               Poisson statistics.)  
;     APR    - Vector of up to 12 REAL photometry aperture radii.
;     SKYRAD - Two element vector giving the inner and outer radii
;               to be used for the sky annulus.   Ignored if the SETSKYVAL
;              keyword is set.
;     BADPIX - Two element vector giving the minimum and maximum value
;               of a good pix (Default [-32765,32767]).    If BADPIX[0] is
;               equal to BADPIX[1] then it is assumed that there are no bad
;               pixels.
;
; OPTIONAL KEYWORD INPUTS:
;     /EXACT -  By default, APER counts subpixels, but uses a polygon 
;             approximation for the intersection of a circular aperture with
;             a square pixel (and normalize the total area of the sum of the
;             pixels to exactly match the circular area).   If the /EXACT 
;             keyword, then the intersection of the circular aperture with a
;             square pixel is computed exactly.    The /EXACT keyword is much
;             slower and is only needed when small (~2 pixels) apertures are
;             used with very undersampled data.    
;     /FLUX - By default, APER uses a magnitude system where a magnitude of
;               25 corresponds to 1 flux unit.   If set, then APER will keep
;              results in flux units instead of magnitudes.
;     PRINT - if set and non-zero then APER will also write its results to
;               a file aper.prt.   One can specify the output file name by
;               setting PRINT = 'filename'.
;     /SILENT -  If supplied and non-zero then no output is displayed to the
;               terminal.
;     SETSKYVAL - Use this keyword to force the sky to a specified value 
;               rather than have APER compute a sky value.    SETSKYVAL 
;               can either be a scalar specifying the sky value to use for 
;               all sources, or a 3 element vector specifying the sky value, 
;               the sigma of the sky value, and the number of elements used 
;               to compute a sky value.   The 3 element form of SETSKYVAL
;               is needed for accurate error budgeting.
;
; OUTPUTS:
;     MAGS   -  NAPER by NSTAR array giving the magnitude for each star in
;               each aperture.  (NAPER is the number of apertures, and NSTAR
;               is the number of stars).   If the /FLUX keyword is not set, then
;               a flux of 1 digital unit is assigned a zero point magnitude of 
;               25.
;     ERRAP  -  NAPER by NSTAR array giving error for each star.  If a 
;               magnitude could not be determined then  ERRAP = 9.99 (if in 
;                magnitudes) or ERRAP = !VALUES.F_NAN (if /FLUX is set).
;     SKY  -    NSTAR element vector giving sky value for each star in 
;               flux units
;     SKYERR -  NSTAR element vector giving error in sky values
;
; EXAMPLE:
;       Determine the flux and error for photometry radii of 3 and 5 pixels
;       surrounding the position 234.2,344.3 on an image array, im.   Compute
;       the partial pixel area exactly.    Assume that the flux units are in
;       Poisson counts, so that PHPADU = 1, and the sky value is already known
;       to be 1.3, and that the range [-32767,80000] for bad low and bad high
;       pixels
;      
;
;       IDL> aper, im, 234.2, 344.3, flux, eflux, sky,skyerr, 1, [3,5], -1, $
;            [-32767,80000],/exact, /flux, setsky = 1.3
;       
; PROCEDURES USED:
;       GETOPT, MMM, PIXWT(), STRN(), STRNUMBER()
; NOTES:
;       Reasons that a valid magnitude cannot be computed include the following:
;      (1) Star position is too close (within 0.5 pixels) to edge of the frame
;      (2) Less than 20 valid pixels available for computing sky
;      (3) Modal value of sky could not be computed by the procedure MMM
;      (4) *Any* pixel within the aperture radius is a "bad" pixel
;      (5) The total computed flux is negative
;
;       APER was modified in June 2000 in two ways: (1) the /EXACT keyword was
;       added (2) the approximation of the intersection of a circular aperture
;       with square pixels was improved (i.e. when /EXACT is not used) 
; REVISON HISTORY:
;       Adapted to IDL from DAOPHOT June, 1989   B. Pfarr, STX
;       Adapted for IDL Version 2,               J. Isensee, July, 1990
;       Code, documentation spiffed up           W. Landsman   August 1991
;       TEXTOUT may be a string                  W. Landsman September 1995
;       FLUX keyword added                       J. E. Hollis, February, 1996
;       SETSKYVAL keyword, increase maxsky       W. Landsman, May 1997
;       Work for more than 32767 stars           W. Landsman, August 1997
;       Converted to IDL V5.0                    W. Landsman   September 1997
;       Don't abort for insufficient sky pixels  W. Landsman  May 2000
;       Added /EXACT keyword                     W. Landsman  June 2000 
;       Allow SETSKYVAL = 0                      W. Landsman  December 2000 
;       Set BADPIX[0] = BADPIX[1] to ignore bad pixels W. L.  January 2001     
;       Fix chk_badpixel problem introduced Jan 01 C. Ishida/W.L. February 2001
;       Set bad fluxes and error to NAN if /FLUX is set  W. Landsman Oct. 2001 
;       Remove restrictions on maximum sky radius W. Landsman  July 2003

; NAME:
;       ARCBAR
; PURPOSE:
;       Draw an arc bar on an image showing the astronomical plate scale
;
; CALLING SEQUENCE:
;       ARCBAR, hdr, arclen,[  COLOR= , /DATA, LABEL= , /NORMAL, POSITION =, 
;                              /SECONDS, SIZE=, THICK= ]
;
; INPUTS:
;       hdr - image FITS header with astrometry, string array
;       arclen - numeric scalar giving length of bar in arcminutes (default)
;               or arcseconds (if /SECONDS is set) 
;
; OPTIONAL KEYWORD INPUTS:
;       COLOR - integer scalar specifying the color to draw the arcbar (using
;               PLOTS), default = !P.COLOR
;       /DATA - if set and non-zero, then the POSITION keyword is given in data
;              units
;       LABEL - string giving user defined label for bar.  Default label is size
;               of bar in arcminutes
;       /NORMAL - if this keyword is set and non-zero, then POSITION is given in
;               normalized units
;       POSITION - 2 element vector giving the (X,Y) position in device units 
;               (or normalized units if /NORMAL is set, or data units if /DATA
;               is set) at which to place the  scale bar.   If not supplied, 
;               then the user will be prompted to place the cursor at the 
;               desired position
;       SIZE  - scalar specifying character size of label, default = 1.0
;       THICK -  Character thickness of the label, default = !P.THICK
;
; EXAMPLE:
;       Place a 3' arc minute scale bar, at position 300,200 of the current
;       image window, (which is associated with a FITS header, HDR)
;
;       IDL> arcbar, HDR, 3, pos = [300,200]
;
; RESTRICTIONS:
;       When using using a device with scalable pixels (e.g. postscript)
;       the data coordinate system must be established before calling ARCBAR.
;       If data coordinates are not set, then ARCBAR assumes that the displayed
;       image size is given by the NAXIS1 keyword in the FITS header.
; PROCEDURE CALLS:
;       AD2XY, EXTAST, GSSSADXY, SXPAR()
; REVISON HISTORY:
;       written by L. Taylor (STX) from ARCBOX (Boothman)
;       modified for Version 2 IDL,                     B. Pfarr, STX, 4/91
;       New ASTROMETRY structures               W.Landsman,  HSTX, Jan 94
;       Recognize a GSSS header                 W. Landsman June 94
;       Added /NORMAL keyword                   W. Landsman Feb. 96
;       Use NAXIS1 for postscript if data coords not set,  W. Landsman Aug 96
;       Fixed typo for postscript W. Landsman   Oct. 96
;       Account for zeropoint offset in postscript  W. Landsman   Apr 97
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Added /DATA, /SECONDS keywords   W. Landsman    July 1998
;       Use device-independent label offset  W. Landsman   August 2001

; NAME:
;      ARROWS
; 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

; NAME:
;     ASINH
; PURPOSE:
;     Return the inverse hyperbolic sine of the argument
; EXPLANATION:
;     The inverse hyperbolic sine is used for the calculation of asinh 
;     magnitudes, see Lupton et al. (1999, AJ, 118, 1406)
;
; CALLING SEQUENCE
;     result = asinh( x) 
; INPUTS:
;     X - hyperbolic sine, numeric scalar or vector or multidimensional array 
;        (not complex) 
;
; OUTPUT:
;     result - inverse hyperbolic sine, same number of elements as X
;              double precision if X is double, otherwise floating pt.
;
; METHOD:
;     Expression given in  Numerical Recipes, Press et al. (1992), eq. 5.6.7 
;     Note that asinh(-x) = -asinh(x) and that asinh(0) = 0. and that
;     if y = asinh(x) then x = sinh(y).     
;
; REVISION HISTORY:
;     Written W. Landsman                 February, 2001
;     Work for multi-dimensional arrays  W. Landsman    August 2002
;     Simplify coding, and work for scalars again  W. Landsman October 2003

; NAME:
;	ASTDISP
;
; PURPOSE:
;	Print astronomical and pixel coordinates in a standard format
; EXPLANATION:
;	This procedure (ASTrometry DISPlay) prints the astronomical and
;	pixel coordinates in a standard format.  X,Y must be supplied.  RA,DEC
;	may also be supplied, and a data number (DN) may also be 
;	supplied.   With use of the Coords= keyword, a string containing the 
;	formatted data can be returned in addition or instead (with /silent) 
;	of printing.
;
; CALLING SEQUENCE:
;	ASTDISP, x, y, [Ra, Dec, DN, COORD = , /SILENT ]
;
; INPUT:
;	X  - The X pixel coordinate(s), scalar or vector
;	Y  - The Y pixel coordinate(s), scalar or vector
;
; OPTIONAL INPUTS:
;	RA -  Right Ascention in *degrees*, scalar or vector
;	DEC - DEClination in *degrees*, scalar or vector (if RA is supplied, DEC must also be supplied)
;	DN -  Data Number or Flux values
;
;	Each of the inputs X,Y, RA, DEC, DN should have the same number of 
;		elements
; OPTIONAL INPUT KEYWORDS:
;	SILENT    Prevents printing.  Only useful when used with Coords=
; OUTPUT:
;	Printed positions in both degrees and sexigesimal format
;	All passed variables remain unchanged
; OPTIONAL KEYWORD OUTPUT:
;	COORDS    Returns the formatted coordinates in a string
; PROCEDURES CALLED:
;	ADSTRING - used to format the RA and Dec
; HISTORY:
;	10-AUG-90 Version 1 written by Eric W. Deutsch
;	20-AUG-91 Converted to standard header.  Vectorized Code.  E. Deutsch
;	20-NOV-92 Added Coords= and /silent.  E.Deutsch
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;       ASTRMFIX
; PURPOSE:
;       Calculate a rough HST WFPC or FOC astrometry solution
; EXPLANATION:
;       This program will calculate a rough HST WFPC or FOC astrometry solution
;       using the keyword PSANGLEV3 which gives the angle of the V3 axis of
;       HST.    Called by WFPCREAD.
;
; CALLING SEQUENCE:
;       AstrmFix, hdr, chip
;
; INPUT - OUTPUT:
;       hdr - FITS header (string array) from either WFPC or FOC.   Header will
;               be updated with rough astrometry 
;
; INPUT:        
;       chip - Scalar (typically 0-3) giving the WFPC chip to read.
;
; PROCEDURES CALLED:
;       EXTAST, SXPAR(), SXADDPAR
; HISTORY:
;       ??-???-???? Written by Eric W. Deutsch
;       22-OCT-1992 Changed all calculations to double precision. (E. Deutsch)
;       22-OCT-1992 Updated PC Pixel size of 0.04389 from WFPC IDT OV/SV manual(EWD)
;       22-OCT-1992 Updated WF Pixel size of 0.1016 from WFPC IDT OV/SV manual(EWD)
;       11-JAN-1993 Added warning message and changed CD001001... to CD1_1... (EWD)
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Remove calls to obsolete !ERR variable  W. Landsman   December 2000

; NAME:
;     ASTRO
; PURPOSE:
;     Interactive utility for precession and coordinate conversion.
;
; CALLING SEQUENCE:
;     ASTRO, [ selection, EQUINOX =, /FK4]
;
; OPTIONAL INPUT:
;      SELECTION - Scalar Integer (0-6) giving the the particular astronomical
;              utility to be used.  (0) Precession, (1) RA, Dec (2000) to Galactic 
;              coordinates, (2) Galactic to RA,Dec (2000) (3) RA,Dec (2000) to 
;              Ecliptic, (4) Ecliptic to RA, Dec, (5) Ecliptic to Galactic, (6) Galactic
;              to Ecliptic.   Program will prompt for SELECTION if this 
;              parameter is omitted.
;
; OPTIONAL KEYWORD INPUT:
;       EQUINOX - numeric scalar specifying the equinox to use when converting 
;               between celestial and other coordinates.    If not supplied, 
;               then the RA and Dec will be assumed to be in EQUINOX J2000.   
;               This keyword is ignored by the precession utility.   For 
;               example, to convert from RA and DEC (J1975) to Galactic 
;               coordinates:
;
;               IDL> astro, 1, E=1975
;       /FK4 - If this keyword is set and nonzero, then calculations are done
;              in the FK4 system.    For example, to convert from RA and Dec
;              (B1975) to Galactic coordinates
;
;               IDL> astro,1, E=1975,/FK4 
; METHOD:
;      ASTRO uses PRECESS to compute precession, and EULER to compute
;      coordinate conversions.   The procedure GET_COORDS is used to
;      read the coordinates, and ADSTRING to format the RA,Dec output.
;
; NOTES:
;      (1) ASTRO temporarily sets !QUIET to suppress compilation messages and
;      keep a pretty screen display.   
;
;      (2) ASTRO was changed in December 1998 to use J2000 as the default 
;      equinox, **and may be incompatible with earlier calls.***
;      
;      (3) A nice online page for coordinate conversions is available at
;       http://heasarc.gsfc.nasa.gov/cgi-bin/Tools/convcoord/convcoord.pl   
; PROCEDURES USED:
;      Procedures: GET_COORDS, EULER       Function: ADSTRING
; REVISION HISTORY
;      Written, W. Landsman November 1987
;      Code cleaned up       W. Landsman   October 1991
;      Added Equinox keyword, call to GET_COORDS, W. Landsman   April, 1992
;      Allow floating point equinox input J. Parker/W. Landsman  July 1996
;      Make FK5 the default, add FK4 keyword

; NAME:
;       ASTROLIB
; PURPOSE:
;       Add the non-standard system variables used by the IDL Astronomy Library
; EXPLANATION: 
;       Also defines the environment variable or VMS 
;       logical ASTRO_DATA pointing to the directory containing data files 
;       associated with the IDL Astronomy library (system dependent).
;
; CALLING SEQUENCE:
;       ASTROLIB
;
; INPUTS:
;       None.
;
; OUTPUTS:
;       None.
;
; METHOD:
;       The non-standard system variables !PRIV, !DEBUG, !TEXTUNIT, and 
;       !TEXTOUT are added using DEFSYSV.
;
; REVISION HISTORY:
;       Written, Wayne Landsman, July 1986.
;       Use DEFSYSV instead of ADDSYSVAR           December 1990
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Test for system variable existence before definition    July 2001

; NAME:
;       AUTOHIST
;
; PURPOSE:
;       Draw a histogram using automatic bin-sizing.
; EXPLANATION
;       AUTOHIST chooses a number of bins (initially, SQRT(2*N). If this leads 
;       to a histogram in which > 1/5 of the central 50% of the bins are empty,
;       it decreases the number of bins and tries again. The minimum # bins is 
;       5. The max=199.     Called by HISTOGAUSS and HALFAGAUSS.
;
; CALLING SEQUENCE:
;       AUTOHIST, Sample, XLines, Ylines, XCenters, YCenters, [/NOPLOT, ]
;                             ...Plotting Keywords
; INPUT:
;       Sample = the vector to be histogrammed
;
; OUTPUT:
;       XLINES = vector of x coordinates of the points that trace the rectangular 
;               histogram bins
;       YLINES = vector of y coordinates. To draw the histogram plot YLINES vs 
;                 XLINES
;       XCENTERS = the x values of the bin centers
;       YCENTERS = the corresponding y values
;
; OPTIONAL INPUT KEYWORDS:
;       /NOPLOT  If set, nothing is drawn
;
;       Any plotting keywords (e.g. XTITLE) may be supplied to AUTOHIST through
;       the _EXTRA facility. 
; REVISION HISTORY:
;       Written,   H. Freudenreich, STX, 1/91
;       1998 March 17 - Changed shading of histogram.  RSH, RSTX
;       V5.0 update, _EXTRA keywords  W. Landsman    April 2002
;       Added NOCLIP keyword for POLYFILL call C. Paxson/W. Landsman July 2003

; NAME:
;       AVG
; PURPOSE:
;       Return the average value of an array, or 1 dimension of an array
; EXPLANATION:
;       Calculate the average value of an array (in which case AVG is identical
;       to the RSI procedure mean.pro), or calculate the average
;       value over one dimension of an array as a function of all the other
;       dimensions.
;
; CALLING SEQUENCE:
;       RESULT = AVG( ARRAY, [ DIMENSION, /NAN, /DOUBLE ] )
;
; INPUTS:
;       ARRAY = Input array.  May be any type except string.
;
; OPTIONAL INPUT PARAMETERS:
;       DIMENSION = Optional dimension to do average over, integer scalar
;
; OPTIONAL KEYWORD INPUT:
;      /NAN - Set this keyword to cause the routine to check for occurrences of
;            the IEEE floating-point value NaN in the input data.  Elements with
;            the value NaN are treated as missing data.
;      /DOUBLE - By default, if the input Array is double-precision, complex, 
;                or double complex, the result is of the same type;  64 bit
;                integers are also returned as double.   Otherwise the result
;                the  result is floating-point.   Use of the /DOUBLE keyword 
;                forces a double precision output.   Note that internal 
;                computations are always done in double precision.
; OUTPUTS:
;       The average value of the array when called with one parameter.
;
;       If DIMENSION is passed, then the result is an array with all the
;       dimensions of the input array except for the dimension specified,
;       each element of which is the average of the corresponding vector
;       in the input array.
;
;       For example, if A is an array with dimensions of (3,4,5), then the
;       command B = AVG(A,1) is equivalent to
;
;                       B = FLTARR(3,5)
;                       FOR J = 0,4 DO BEGIN
;                               FOR I = 0,2 DO BEGIN
;                                       B[I,J] = TOTAL( A[I,*,J] ) / 4.
;                               ENDFOR
;                       ENDFOR
;
; RESTRICTIONS:
;       Dimension specified must be valid for the array passed; otherwise the
;       input array is returned as the output array.
; PROCEDURE:
;       AVG(ARRAY) = TOTAL(ARRAY, /DOUBLE)/N_ELEMENTS(ARRAY) when called with 
;       one parameter.
; MODIFICATION HISTORY:
;       William Thompson        Applied Research Corporation
;       July, 1986              8201 Corporate Drive
;                               Landover, MD  20785
;       Converted to Version 2      July, 1990
;       Replace SUM call with TOTAL    W. Landsman    May, 1992
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Added /NAN keyword   W. Landsman      July 2000
;       Accept a scalar input value    W. Landsman/jimm@berkeley   November 2000
;       Internal calculations always in double precision W. Landsman March 2002
;       Return NAN if all values in array are NAN  W. Landsman April 2002

; NAME:
;     A_b
; PURPOSE:
;     Compute B band interstellar extinction according to the RC2.
; EXPLANATION:
;     The predicted B band extinction is computed as a function of  
;     Galactic position  using the 21 parameter function given by
;     deVaucouleurs in the 2nd Reference Catalog of Galaxies (RC2).   Note 
;     that this formula was not used for the RC3 and that reddenings
;     were instead obtained from the Burstein-Heiles 21 cm maps.
;
; CALLING SEQUENCE:
;     result = A_b( l2, b2)
;
; INPUT PARAMETERS
;     l2 = Galactic longitude (degrees), scalar or vector
;     b2 = Galactic latitude  (degrees), scalar or vector
;
; OUTPUT PARAMETERS
;     RESULT - Interstellar extinction Ab in magnitudes, same number of 
;             elements as input l2 and b2 parameters
;
; NOTES:
;     The controversial aspect of the deVaucouleurs reddening curve
;     is that it predicts an extinction of about 0.2 at the poles 
;
;     The parameters used here differ from the ones printed in the RC2
;     but are the ones actually used for entries in the catalog
;     (see Rowan-Robinson 1985) 
;
;     This procedure is mainly of historical interest only, and reddening
;     is now better determined using dust maps, such as those available at
;     http://astro.berkeley.edu/davis/dust/index.html
; REVISION HISTORY
;     Written by R. Cornett and W. Landsman, STX October 1987
;     Vectorized code      W. Landsman   STX    December 1992
;     Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;       BARYVEL
; PURPOSE:
;       Calculates heliocentric and barycentric velocity components of Earth.
;
; EXPLANATION:
;       BARYVEL takes into account the Earth-Moon motion, and is useful for 
;       radial velocity work to an accuracy of  ~1 m/s.
;
; CALLING SEQUENCE:
;       BARYVEL, dje, deq, dvelh, dvelb, [ JPL =  ] 
;
; INPUTS:
;       DJE - (scalar) Julian ephemeris date.
;       DEQ - (scalar) epoch of mean equinox of dvelh and dvelb. If deq=0
;               then deq is assumed to be equal to dje.
; OUTPUTS: 
;       DVELH: (vector(3)) heliocentric velocity component. in km/s 
;       DVELB: (vector(3)) barycentric velocity component. in km/s
;
;       The 3-vectors DVELH and DVELB are given in a right-handed coordinate 
;       system with the +X axis toward the Vernal Equinox, and +Z axis 
;       toward the celestial pole.      
;
; OPTIONAL KEYWORD SET:
;       JPL - if /JPL set, then BARYVEL will call the procedure JPLEPHINTERP
;             to compute the Earth velocity using the full JPL ephemeris.   
;             The JPL ephemeris FITS file JPLEPH.405 must exist in either the 
;             current directory, or in the directory specified by the 
;             environment variable ASTRO_DATA.   Alternatively, the JPL keyword
;             can be set to the full path and name of the ephemeris file.
;             A copy of the JPL ephemeris FITS file is available in
;                 http://idlastro.gsfc.nasa.gov/ftp/data/         
; PROCEDURES CALLED:
;       Function PREMAT() -- computes precession matrix
;       JPLEPHREAD, JPLEPHINTERP, TDB2TDT - if /JPL keyword is set
; NOTES:
;       Algorithm taken from FORTRAN program of Stumpff (1980, A&A Suppl, 41,1)
;       Stumpf claimed an accuracy of 42 cm/s for the velocity.    A 
;       comparison with the JPL FORTRAN planetary ephemeris program PLEPH
;       found agreement to within about 65 cm/s between 1986 and 1994
;
;       If /JPL is set (using JPLEPH.405 ephemeris file) then velocities are 
;       given in the ICRS system; otherwise in the FK4 system.   
; EXAMPLE:
;       Compute the radial velocity of the Earth toward Altair on 15-Feb-1994
;          using both the original Stumpf algorithm and the JPL ephemeris
;
;       IDL> jdcnv, 1994, 2, 15, 0, jd          ;==> JD = 2449398.5
;       IDL> baryvel, jd, 2000, vh, vb          ;Original algorithm
;               ==> vh = [-17.07809, -22.80063, -9.885281]  ;Heliocentric km/s
;               ==> vb = [-17.08083, -22.80471, -9.886582]  ;Barycentric km/s
;       IDL> baryvel, jd, 20000, vh, vb, /jpl   ;JPL ephemeris
;               ==> vh = [-17.10746, -22.78912, -9.879800]  ;Heliocentric km/s
;               ==> vb = [-17.11591, -22.78269, -9.876785]  ;Barycentric km/s
;
;       IDL> ra = ten(19,50,46.77)*15/!RADEG    ;RA  in radians
;       IDL> dec = ten(08,52,3.5)/!RADEG        ;Dec in radians
;       IDL> v = vb(0)*cos(dec)*cos(ra) + $   ;Project velocity toward star
;               vb(1)*cos(dec)*sin(ra) + vb(2)*sin(dec) 
;
; REVISION HISTORY:
;       Jeff Valenti,  U.C. Berkeley    Translated BARVEL.FOR to IDL.
;       W. Landsman, Cleaned up program sent by Chris McCarthy (SfSU) June 1994
;       Converted to IDL V5.0   W. Landsman   September 1997
;        Added /JPL keyword  W. Landsman   July 2001

; NAME:
;	BIWEIGHT_MEAN 
;
; PURPOSE:
;	Calculate the center and dispersion (like mean and sigma) of a 
;	distribution using bisquare weighting.
;
; CALLING SEQUENCE:
;	Mean = BIWEIGHT_MEAN( Vector, [ Sigma, Weights ] ) 
;
; INPUTS:
;	Vector = Distribution in vector form
;
; OUTPUT:
;	Mean - The location of the center.
;
; OPTIONAL OUTPUT ARGUMENTS:
;
;	Sigma = An outlier-resistant measure of the dispersion about the 
;	      center, analogous to the standard deviation. 
;
;	Weights = The weights applied to the data in the last iteration, 
;                 floating point vector
;
; NOTES:
;       Since a sample mean  scaled by sigma/sqrt(N), has a Student's T 
;       distribution, the half-width of the  95% confidence interval for 
;       the sample mean  can be determined as follows: 
;          ABS( T_CVF( .975, .7*(N-1) )*SIGMA/SQRT(N) ) 
;       where N = number of  points, and  0.975 = 1 - (1 - 0.95)/2. 
; PROCEDURES USED:
;       ROBUST_SIGMA()
; REVISION HISTORY
;	Written,  H. Freudenreich, STX, 12/89
;	Modified 2/94, H.T.F.: use a biweighted standard deviation rather than
;		median absolute deviation.
;	Modified 2/94, H.T.F.: use the fractional change in SIGMA as the 
;		convergence criterion rather than the change in center/SIGMA.
;       Modified May 2002  Use MEDIAN(/EVEN)
;       Modified October 2002, Faster computation of weights 
;       Corrected documentation on 95% confidence interval of mean 
;                 P.Broos/W. Landsman   July 2003 

; NAME:
;	BLINK
; PURPOSE:
;	To allow the user to alternatively examine two or more windows within
;	a single window.
;
; CALLING SEQUENCE:
;	BLINK, Wndw [, T]
;
; INPUTS:
;	Wndw  A vector containing the indices of the windows to blink.
;	T     The time to wait, in seconds, between blinks.  This is optional
;	      and set to 1 if not present.  
;
; OUTPUTS:
;	None.
;
; PROCEDURE:
;	The images contained in the windows given are written to a pixmap.
;	The contents of the the windows are copied to a display window, in 
;	order, until a key is struck.
;
; EXAMPLE:
;	Blink windows 0 and 2 with a wait time of 3 seconds
;
;	IDL> blink, [0,2], 3 
;
; MODIFICATION HISTORY:
;	Written by Michael R. Greason, STX, 2 May 1990.
;	Allow different size windows   Wayne Landsman    August, 1991
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;   BLKSHIFT
;
; AUTHOR:
;   Craig B. Markwardt, NASA/GSFC Code 662, Greenbelt, MD 20770
;   craigm@lheamail.gsfc.nasa.gov
;
; PURPOSE:
;   Shift a block of data to a new position in a file (possibly overlapping)
;
; MAJOR TOPICS:
;   File I/O
;
; CALLING SEQUENCE:
;
;   BLKSHIFT, UNIT, POS, [ DELTA, TO=TO, /NOZERO, ERRMSG=ERRMSG, 
;             BUFFERSIZE=BUFFERSIZE ]
;
; DESCRIPTION:
;
;  BLKSHIFT moves a block of data forward or backward, to a new
;  position in a data file.  The old and new positions of the block
;  can overlap safely.
;
;  The new position can be specified with either the DELTA parameter,
;  which gives the number of bytes to move forward (positive delta) or
;  backward (negative delta); or the TO keyword, which give the new
;  absolute starting position of the block.
;
;  The block can be moved beyond the current end of file point, in
;  which case the intervening gap is filled with zeros (optionally).
;  The gap left at the old position of the block is also optionally
;  zero-filled.
;
; INPUTS:
;
;   UNIT - a logical unit number, opened for reading and writing.
;
;   POS - POS(0) is the position of the block in the file, in bytes,
;         before moving.  POS(1), if present, is the size of the block
;         in bytes.  If POS(1) is not given, then the block is from
;         POS(0) to the end of the file.
;
;   DELTA - the (optional) offset in bytes between the old and new
;           positions, from the start of the block.  Positive values
;           indicate moving the data forward (toward the end of file),
;           and negative values indicate moving the data backward
;           (toward the beginning of the file).  One of DELTA and TO
;           must be specified; DELTA overrides the TO keyword.
;
;           Attempts to move the block beyond the end of the file will
;           succeed.  A block can never be moved beyond the beginning
;           of the file; it will be moved to the beginning instead.
;
; KEYWORD PARAMETERS:
;
;   TO - the absolute file offset in bytes for the new start of the
;        block.  One of DELTA and TO must be specified; DELTA
;        overrides the TO keyword.
;
;   NOZERO - if set, then newly created gaps will not be explicitly
;            zeroed.  However, for some operating systems (Mac and
;            VMS), zeroing is required and will be done anyway.
;
;   ERRMSG - If defined and passed, then any error messages will be
;            returned to the user in this parameter rather than
;            depending on the MESSAGE routine in IDL.  If no errors
;            are encountered, then a null string is returned.  In
;            order to use this feature, ERRMSG must be defined first,
;            e.g.
;			ERRMSG = ''
;			FXBGROW, ERRMSG=ERRMSG, ...
;			IF ERRMSG NE '' THEN ...
;
;   BUFFERSIZE - the maximum buffer size for transfers, in bytes.
;                Larger values of this keyword impose larger memory
;                requirements on the application; smaller values will
;                lead to more transfer operations.
;                Default: 32768 (bytes)
;
; MODIFICATION HISTORY:
;
;   Written, CM, Apr 2000
;   Documented and re-written, CM, 20 Jul 2000
;   Renamed from FXSHIFT to BLKSHIFT, CM, 21 Jul 2000
;   Documentation, CM, 12 Dec 2002
;

; NAME:
;	BOOST_ARRAY
; PURPOSE:
;	Append one array onto a destination array
; EXPLANATION:
;	Add array APPEND to array DESTINATION, allowing the dimensions of
;	DESTINATION to adjust to accomodate it.  If both input arrays have the
;	same number of dimensions, then the output array will have one
;	additional dimension.  Otherwise, the last dimension of DESTINATION
;	will be incremented by one.
; CATEGORY:
;	Utility
; CALLING SEQUENCE:
;	BOOST_ARRAY, DESTINATION, APPEND
; INPUT:
;	DESTINATION	= Array to be expanded.
;	APPEND		= Array to append to DESTINATION.
; OUTPUTS:
;	DESTINATION	= Expanded output array.
; RESTRICTIONS:
;	DESTINATION and APPEND have to be either both of type string or both of
;	numerical types.
;
;	APPEND cannot have more dimensions than DESTINATION.
;
; MODIFICATION HISTOBY:
;	Written Aug'88 (DMZ, ARC)
;	Modified Sep'89 to handle byte arrays (DMZ)
;	Modifed to version 2, Paul Hick (ARC), Feb 1991
;	Removed restriction to 2D arrays, William Thompson (ARC), Feb 1992.
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;       BOXAVE
; PURPOSE:
;       Box-average a 1 or 2 dimensional array.
; EXPLANATION:   
;       This procedure differs from the intrinsic REBIN function in the 
;       following 2 ways: 
;
;       (1) the box size parameter is specified rather than the output 
;               array size
;       (2) for INTEGER arrays, BOXAVE computes intermediate steps using REAL*4 
;               arithmetic.   This is considerably slower than REBIN but avoids 
;               integer truncation
;
;       A version of BOXAVE() that supports 64 bit integers is available for
;       V5.4 or later in http://idlastro.gsfc.nasa.gov/ftp/v54/
; CALLING SEQUENCE:
;       result = BOXAVE( Array, Xsize,[ Ysize ] )     
;
; INPUTS:
;       ARRAY - Two dimensional input Array to be box-averaged.  Array may be 
;               one or 2 dimensions and of any type except character.   
;
; OPTIONAL INPUTS:
;       XSIZE - Size of box in the X direction, over which the array is to
;               be averaged.  If omitted, program will prompt for this 
;               parameter.  
;       YSIZE - For 2 dimensional arrays, the box size in the Y direction.
;               If omitted, then the box size in the X and Y directions are 
;               assumed to be equal
;
; OUTPUT:
;       RESULT - Output array after box averaging.  If the input array has 
;               dimensions XDIM by YDIM, then RESULT has dimensions
;               XDIM/NBOX by YDIM/NBOX.  The type of RESULT is the same as
;               the input array.  However, the averaging is always computed
;               using REAL arithmetic, so that the calculation should be exact.
;               If the box size did not exactly divide the input array, then
;               then not all of the input array will be boxaveraged.
;
; PROCEDURE:
;       BOXAVE boxaverages all points simultaneously using vector subscripting
;
; NOTES:
;       If im_int is a 512 x 512 integer array, then the two statements
;
;               IDL> im = fix(round(rebin(float(im_int), 128, 128)))
;               IDL> im  = boxave( im_int,4)
;
;       give equivalent results.   The use of REBIN is faster, but BOXAVE is
;       is less demanding on virtual memory, since one does not need to make
;       a floating point copy of the entire array.      
;
; REVISION HISTORY:
;       Written, W. Landsman, October 1986
;       Call REBIN for REAL*4 and REAL*8 input arrays, W. Landsman Jan, 1992
;       Removed /NOZERO in output array definition     W. Landsman 1995
;       Fixed occasional integer overflow problem      W. Landsman Sep. 1995
;       Allow unsigned data types                      W. Landsman Jan. 2000

; NAME:
;       BPRECESS
; PURPOSE:
;       Precess positions from J2000.0 (FK5) to B1950.0 (FK4)
; EXPLANATION:
;       Calculates the mean place of a star at B1950.0 on the FK4 system from
;       the mean place at J2000.0 on the FK5 system.    
;
; CALLING SEQUENCE:
;       bprecess, ra, dec, ra_1950, dec_1950, [ MU_RADEC = , PARALLAX = 
;                                       RAD_VEL =, EPOCH =   ]
;
; INPUTS:
;       RA,DEC - Input J2000 right ascension and declination in *degrees*.
;               Scalar or N element vector
;
; OUTPUTS:
;       RA_1950, DEC_1950 - The corresponding B1950 right ascension and 
;               declination in *degrees*.    Same number of elements as
;               RA,DEC but always double precision.
;
; OPTIONAL INPUT-OUTPUT KEYWORDS
;       MU_RADEC - 2xN element double precision vector containing the proper 
;                  motion in seconds of arc per tropical *century* in right 
;                  ascension and declination.
;       PARALLAX - N_element vector giving stellar parallax (seconds of arc)
;       RAD_VEL  - N_element vector giving radial velocity in km/s
;
;       The values of MU_RADEC, PARALLAX, and RADVEL will all be modified
;       upon output to contain the values of these quantities in the
;       B1950 system.  The parallax and radial velocity will have a very 
;       minor influence on the B1950 position.   
;
;       EPOCH - scalar giving epoch of original observations, default 2000.0d
;           This keyword value is only used if the MU_RADEC keyword is not set.
; NOTES:
;       The algorithm is taken from the Explanatory Supplement to the 
;       Astronomical Almanac 1992, page 186.
;       Also see Aoki et al (1983), A&A, 128,263
;
;       BPRECESS distinguishes between the following two cases:
;       (1) The proper motion is known and non-zero
;       (2) the proper motion is unknown or known to be exactly zero (i.e.
;               extragalactic radio sources).   In this case, the reverse of 
;               the algorithm in Appendix 2 of Aoki et al. (1983) is used to 
;               ensure that the output proper motion is  exactly zero. Better 
;               precision can be achieved in this case by inputting the EPOCH 
;               of the original observations.
;
;       The error in using the IDL procedure PRECESS for converting between
;       B1950 and J1950 can be up to 1.5", mainly in right ascension.   If
;       better accuracy than this is needed then BPRECESS should be used.
;
;       An unsystematic comparison of BPRECESS with the IPAC precession 
;       routine (http://nedwww.ipac.caltech.edu/forms/calculator.html) always 
;       gives differences less than 0.15".
; EXAMPLE:
;       The SAO2000 catalogue gives the J2000 position and proper motion for
;       the star HD 119288.   Find the B1950 position. 
;
;       RA(2000) = 13h 42m 12.740s      Dec(2000) = 8d 23' 17.69''  
;       Mu(RA) = -.0257 s/yr      Mu(Dec) = -.090 ''/yr
;
;       IDL> mu_radec = 100D* [ -15D*.0257, -0.090 ]
;       IDL> ra = ten(13, 42, 12.740)*15.D 
;       IDL> dec = ten(8, 23, 17.69)
;       IDL> bprecess, ra, dec, ra1950, dec1950, mu_radec = mu_radec
;       IDL> print, adstring(ra1950, dec1950,2)
;               ===> 13h 39m 44.526s    +08d 38' 28.63"
;
; REVISION HISTORY:
;       Written,    W. Landsman                October, 1992
;       Vectorized, W. Landsman                February, 1994
;       Treat case where proper motion not known or exactly zero  November 1994
;       Handling of arrays larger than 32767   Lars L. Christensen, march, 1995
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Fixed bug where A term not initialized for vector input 
;            W. Landsman        February 2000
;       

; NAME: 
;    BREAK_PATH()
;
; PURPOSE: 
;     Breaks up a path string into its component directories.
;
; CALLING SEQUENCE: 
;     Result = BREAK_PATH( PATHS [ /NoCurrent])
;
; INPUTS: 
;     PATHS   = A string containing one or more directory paths.  The
;               individual paths are separated by commas, although in UNIX, 
;               colons can also be used.  In other words, PATHS has the same 
;               format as !PATH, except that commas can be used as a separator 
;               regardless of operating system.
;
;               A leading $ can be used in any path to signal that what follows 
;               is an environmental variable, but the $ is not necessary.  (In 
;               VMS the $ can either be part of the path, or can signal logical
;               names for compatibility with Unix.)  Environmental variables
;               can themselves contain multiple paths.
;
; OUTPUT: 
;      The result of the function is a string array of directories.
;      Unless the NOCURRENT keyword is set, the first element of the array is 
;      always the null string, representing the current directory.  All the 
;      other directories will end in the correct separator character for the 
;      current operating system.
;
; OPTIONAL INPUT KEYWORD:
;      /NOCURRENT = If set, then the current directory (represented by
;               the null string) will not automatically be prepended to the
;               output.
;
; PROCEDURE CALLS:
;      Functions:  STR_SEP() V5.3 or earlier
;
; REVISION HISTORY:
;       Version 1, William Thompson, GSFC, 6 May 1993.
;               Added IDL for Windows compatibility.
;       Version 2, William Thompson, GSFC, 16 May 1995
;               Added keyword NOCURRENT
;       Version 3, William Thompson, GSFC, 29 August 1995
;               Modified to use OS_FAMILY
;       Version 4, Zarro, GSFC, 4 August 1997
;               Added trim to input
;       Converted to IDL V5.0   W. Landsman 25-Nov-1997
;       Fix directory character on Macintosh system   A. Ferro   February 2000
;       Use STRSPLIT instead of STR_SEP  W. Landsman   July 2002

; NAME:
;       BSORT
; PURPOSE:
;       Function to sort data into ascending order, like a simple bubble sort.
; EXPLANATION:
;       Original subscript order is maintained when values are equal (FIFO).
;       (This differs from the IDL SORT routine alone, which may rearrange 
;       order for equal values)
;
; CALLING SEQUENCE:  
;       result = bsort( array, [ asort, /INFO, /REVERSE ] )
;
; INPUT:
;       Array - array to be sorted
;
; OUTPUT:
;       result - sort subscripts are returned as function value
;
; OPTIONAL OUTPUT:
;       Asort - sorted array
;
; OPTIONAL KEYWORD INPUTS:
;       /REVERSE - if this keyword is set, and non-zero, then data is sorted
;                 in descending order instead of ascending order.
;       /INFO = optional keyword to cause brief message about # equal values.
;
; HISTORY
;       written by F. Varosi Oct.90:
;       uses WHERE to find equal clumps, instead of looping with IF ( EQ ).
;       compatible with string arrays, test for degenerate array 
;       20-MAY-1991     JKF/ACC via T AKE- return indexes if the array to 
;                       be sorted has all equal values.
;       Aug - 91  Added  REVERSE keyword   W. Landsman      
;       Always return type LONG    W. Landsman     August 1994
;       Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;     CALZ_UNRED
; PURPOSE:
;     Deredden a galaxy spectrum using the Calzetti et al. (2000) recipe
; EXPLANATION:
;     Calzetti et al.  (2000, ApJ 533, 682) developed a recipe for dereddening 
;     the spectra of galaxies where massive stars dominate the radiation output,
;     valid between 0.12 to 2.2 microns.     (CALZ_UNRED extrapolates between
;     0.12 and 0.0912 microns.)   
;
; CALLING SEQUENCE:
;     CALZ_UNRED, wave, flux, ebv, [ funred, R_V = ]
; INPUT:
;      WAVE - wavelength vector (Angstroms)
;      FLUX - calibrated flux vector, same number of elements as WAVE
;               If only 3 parameters are supplied, then this vector will
;               updated on output to contain the dereddened flux.
;      EBV  - color excess E(B-V), scalar.  If a negative EBV is supplied,
;               then fluxes will be reddened rather than deredenned.
;               Note that the supplied color excess should be that derived for 
;               the stellar  continuum, EBV(stars), which is related to the 
;               reddening derived from the gas, EBV(gas), via the Balmer 
;               decrement by EBV(stars) = 0.44*EBV(gas)
;
; OUTPUT:
;      FUNRED - unreddened flux vector, same units and number of elements
;               as FLUX.   FUNRED values will be zeroed outside valid domain
;               Calz_unred (0.0912 - 2.2 microns).
;           
; OPTIONAL INPUT KEYWORD:
;       R_V - Ratio of total to selective extinction, default = 4.05.  
;             Calzetti et al. (2000) estimate R_V = 4.05 +/- 0.80 from optical
;             -IR observations of 4 starbursts.
; EXAMPLE:
;       Estimate how a flat galaxy spectrum (in wavelength) between 1200 A 
;       and 3200 A is altered by a reddening of E(B-V) = 0.1.   
;
;       IDL> w = 1200 + findgen(40)*50      ;Create a wavelength vector
;       IDL> f = w*0 + 1                    ;Create a "flat" flux vector
;       IDL> calz_unred, w, f, -0.1, fnew  ;Redden (negative E(B-V)) flux vector
;       IDL> plot,w,fnew                   
;
; NOTES:
;       Use the 4 parameter calling sequence if you wish to save the 
;               original flux vector.
; PROCEDURE CALLS:
;      POLY()
; REVISION HISTORY:
;       Written   W. Landsman        Raytheon  ITSS   December, 2000

; NAME:
;     CCM_UNRED
; PURPOSE:
;     Deredden a flux vector using the CCM 1989 parameterization 
; EXPLANATION:
;     The reddening curve is that of Cardelli, Clayton, and Mathis (1989 ApJ.
;     345, 245), including the update for the near-UV given by O'Donnell 
;     (1994, ApJ, 422, 158).   Parameterization is valid from the IR to the 
;     far-UV (3.5 microns to 0.1 microns).    
;
;     Users might wish to consider using the alternate procedure FM_UNRED
;     which uses the extinction curve of Fitzpatrick (1999).
; CALLING SEQUENCE:
;     CCM_UNRED, wave, flux, ebv, funred, [ R_V = ]      
;             or 
;     CCM_UNRED, wave, flux, ebv, [ R_V = ]      
; INPUT:
;     WAVE - wavelength vector (Angstroms)
;     FLUX - calibrated flux vector, same number of elements as WAVE
;             If only 3 parameters are supplied, then this vector will
;             updated on output to contain the dereddened flux.
;     EBV  - color excess E(B-V), scalar.  If a negative EBV is supplied,
;             then fluxes will be reddened rather than deredenned.
;
; OUTPUT:
;     FUNRED - unreddened flux vector, same units and number of elements
;             as FLUX
;
; OPTIONAL INPUT KEYWORD
;     R_V - scalar specifying the ratio of total selective extinction
;             R(V) = A(V) / E(B - V).    If not specified, then R_V = 3.1
;             Extreme values of R(V) range from 2.75 to 5.3
;
; EXAMPLE:
;     Determine how a flat spectrum (in wavelength) between 1200 A and 3200 A
;     is altered by a reddening of E(B-V) = 0.1.   Assume an "average"
;     reddening for the diffuse interstellar medium (R(V) = 3.1)
;
;       IDL> w = 1200 + findgen(40)*50      ;Create a wavelength vector
;       IDL> f = w*0 + 1                    ;Create a "flat" flux vector
;       IDL> ccm_unred, w, f, -0.1, fnew  ;Redden (negative E(B-V)) flux vector
;       IDL> plot,w,fnew                   
;
; NOTES:
;     (1) The CCM curve shows good agreement with the Savage & Mathis (1979)
;             ultraviolet curve shortward of 1400 A, but is probably
;             preferable between 1200 and 1400 A.
;     (2)  Many sightlines with peculiar ultraviolet interstellar extinction 
;             can be represented with a CCM curve, if the proper value of 
;             R(V) is supplied.
;     (3)  Curve is extrapolated between 912 and 1000 A as suggested by
;             Longo et al. (1989, ApJ, 339,474)
;     (4) Use the 4 parameter calling sequence if you wish to save the 
;               original flux vector.
;
; REVISION HISTORY:
;       Written   W. Landsman        Hughes/STX   January, 1992
;       Extrapolate curve for wavelengths between 900 and 1000 A   Dec. 1993
;       Use updated coefficients for near-UV from O'Donnell   Feb 1994
;       Allow 3 parameter calling sequence      April 1998
;       Converted to IDLV5.0                    April 1998

; NAME:
;       CHECKSUM32
;
; PURPOSE:
;       To compute the 32bit checksum of an array (ones-complement arithmetic)
;
; EXPLANATION:
;       The 32bit checksum is adopted in the FITS Checksum convention
;       http://heasarc.gsfc.nasa.gov/docs/heasarc/fits/checksum.html
;
; CALLING SEQUENCE:
;       CHECKSUM32, array, checksum, [/FROM_IEEE, /NoSAVE]
;
; INPUTS:
;       array - any numeric idl array.  If the number of bytes in the array is 
;               not a multiple of four then it is padded with zeros internally
;               (the array is returned unchanged).   Convert a string array 
;               (e.g. a FITS header) to bytes prior to calling CHECKSUM32.
;
; OUTPUTS:
;       checksum - unsigned long scalar, giving sum of array elements using 
;                  ones-complement arithmetic
; OPTIONAL INPUT KEYWORD:
;      The following two keywords only have an effect on little endian machines
;      (e.g. Linux boxes)
;
;      /FROM_IEEE - If this keyword is set, then the input is assumed to be in
;           big endian format (e.g. an untranslated FITS array)
;      /NoSAVE - if set, then the input array is not restored to its original
;          byte ordering upon exiting.   Use the NoSave keyword to save time
;           if the input array is not needed in further computations. 
; METHOD:
;       Uses TOTAL() to sum the array into a double precision variable.  The
;       overflow bits beyond 2^32 are then shifted back to the least significant
;       bits.    Due to the limited precision of a DOUBLE variable, the summing
;       is done in chunks determined by MACHAR(). Adapted from FORTRAN code in
;      heasarc.gsfc.nasa.gov/docs/heasarc/ofwg/docs/general/checksum/node30.html
;
;      Could probably be done in a cleverer way (similar to the C
;      implementation) but then the array-oriented TOTAL() function could not 
;      be used.
; RESTRICTIONS:
;       (1) Requires V5.2 or later (uses unsigned integers)
;       (2) Not valid for object or pointer data types
; EXAMPLE:
;       Find the 32 bit checksum of the array x = findgen(35)
;
;       IDL> checksum32, x, s    ===> s =  2920022024
; FUNCTION CALLED:
;       IS_IEEE_BIG(), N_BYTES()
; MODIFICATION HISTORY:
;       Written    W. Landsman          June 2001
;       Work correctly on little endian machines, added /FROM_IEEE and /NoSave
;                  W. Landsman          November 2002
;       Pad with zeros when array size not a multiple of 4 W.Landsman Aug 2003

; NAME:
;       CHECK_FITS
; PURPOSE:
;       Check that keywords in a FITS header array match the associated data  
; EXPLANATION:
;       Given a FITS array IM, and a associated FITS or STSDAS header HDR, this
;       procedure will check that
;               (1) HDR is a string array, and IM is defined and numeric   
;               (2) The NAXISi values in HDR are appropriate to the dimensions 
;                   of IM
;               (3) The BITPIX value in HDR is appropriate to the datatype of IM
;       If HDR contains a DATATYPE keyword (as in STSDAS headers), then this is 
;       also checked against the datatype of of IM
;       If the /UPDATE keyword is present, then the FITS header will be 
;       modified, if necessary, to force agreement with the image array
;
; CALLING SEQUENCE:
;       check_FITS, im, hdr, [ dimen, idltype, /UPDATE, /NOTYPE, /SDAS, /SILENT
;                              ERRMSG = ]'
;
; INPUT PARAMETERS:
;       IM -  FITS (or STSDAS) array, e.g. as read by READFITS
;       HDR - FITS (or STSDAS) header (string array) associated with IM
;
; OPTIONAL OUTPUTS:
;       dimen - vector containing actual array dimensions
;       idltype- data type of the FITS array as specified in the IDL SIZE
;               function (1 for BYTE, 2 for INTEGER*2, 3 for INTEGER*4, etc.)
;
; OPTIONAL KEYWORD INPUTS:
;       /NOTYPE - If this keyword is set, then only agreement of the array
;               dimensions with the FITS header are checked, and not the 
;               data type.
;       /UPDATE - If this keyword is set then the BITPIX, NAXIS and DATATYPE
;               FITS keywords will be updated to agree with the array
;       /SDAS - If this keyword is set then the header is assumed to be from
;               an SDAS (.hhh) file.    CHECK_FITS will then ensure that (1)
;               a DATATYPE keyword is included in the header and (2) BITPIX
;               is always written with positive values.
;       /FITS -  If this keyword is present then CHECK_FITS assumes that it is
;               dealing with a FITS header and not an SDAS header, see notes
;               below.
;       /SILENT - If keyword is set and nonzero, the informational messages 
;               will not be printed
; OPTIONAL KEYWORD OUTPUT:
;       ERRMSG	= If this keyword is present, then any error messages will be
;                 returned to the user in this parameter rather than
;                 depending on the MESSAGE routine in IDL.  If no errors are
;                 encountered, then a null string is returned.  
;
; SYSTEM VARIABLE:
;       For consistency with previous versions, CHECK_FITS sets the obsolete
;       !ERR keyword, although its use is discouraged in favor of the ERRMSG
;       keyword.   If there is a fatal problem with the FITS array or header 
;       then !ERR is set to -1.   ( If the UPDATE keyword was supplied, and the
;       header could be fixed, then !ERR = 0.)    
;
; PROCEDURE:
;       Program checks the NAXIS1 and NAXIS2 parameters in the header to
;       see if they match the image array dimensions.
;
; NOTES:
;       An important distinction between an STSDAS header and a FITS header
;       is that the BITPIX value in an STSDAS header is always positive, 
;       e.g. BITPIX=32 for REAL*4 data.    Users should use either the /SDAS 
;       or the /FITS keyword if it is important whether the STSDAS or FITS 
;       convention for REAL*4 data is used.     Otherwise, CHECK_FITS assumes 
;       that if a DATATYPE keyword is present then it is dealing with an 
;       STSDAS header.
;
; PROCEDURE CALLS:
;       STRN(),FXADDPAR, fxpar() 
; MODIFICATION HISTORY:
;       Written, December 1991  W. Landsman Hughes/STX to replace CHKIMHD
;       No error returned if NAXIS=0 and IM is a scalar   W. Landsman  Feb 93
;       Fixed bug for REAL*8 STSDAS data W. Landsman July 93
;       Make sure NAXIS agrees with NAXISi  W. Landsman  October 93
;        Converted to IDL V5.0   W. Landsman   September 1997
;       Allow unsigned data types   W. Landsman December 1999
;       Allow BZERO = 0 for unsigned data types   W. Landsman January 2000
;       Added ERRMSG keyword, W. Landsman February 2000
;       Use FXADDPAR to put NAXISi in proper order   W. Landsman August 2000
;       Improper FXADDPAR call for DATATYPE keyword  W. Landsman December 2000

; NAME:
;       CIC
;
; PURPOSE:
;       Interpolate an irregularly sampled field using Cloud in Cell method
;
; EXPLANATION:
;       This function interpolates an irregularly sampled field to a
;       regular grid using Cloud In Cell (nearest grid point gets
;       weight 1-dngp, point on other side gets weight dngp, where
;       dngp is the distance to the nearest grid point in units of the
;       cell size).
;
; CATEGORY:
;       Mathematical functions, Interpolation
;
; CALLING SEQUENCE:
;       Result = CIC, VALUE, POSX, NX[, POSY, NY, POSZ, NZ, 
;                     AVERAGE = average, WRAPAROUND =  wraparound,
;                     ISOLATED = isolated, NO_MESSAGE = no_message]
;
; INPUTS:
;       VALUE: Array of sample weights (field values). For e.g. a
;              temperature field this would be the temperature and the
;              keyword AVERAGE should be set. For e.g. a density field
;              this could be either the particle mass (AVERAGE should
;              not be set) or the density (AVERAGE should be set).
;       POSX:  Array of X coordinates of field samples, unit indices: [0,NX>.
;       NX:    Desired number of grid points in X-direction.
;       
; OPTIONAL INPUTS:
;      POSY: Array of Y coordinates of field samples, unit indices: [0,NY>.
;      NY:   Desired number of grid points in Y-direction.
;      POSZ: Array of Z coordinates of field samples, unit indices: [0,NZ>.
;      NZ:   Desired number of grid points in Z-direction.
;
; KEYWORD PARAMETERS:
;       AVERAGE:    Set this keyword if the nodes contain field samples
;                   (e.g. a temperature field). The value at each grid
;                   point will then be the weighted average of all the
;                   samples allocated to it. If this keyword is not
;                   set, the value at each grid point will be the
;                   weighted sum of all the nodes allocated to it
;                   (e.g. for a density field from a distribution of
;                   particles). (D=0). 
;       WRAPAROUND: Set this keyword if you want the first grid point
;                   to contain samples of both sides of the volume
;                   (see below).
;       ISOLATED:   Set this keyword if the data is isolated, i.e. not
;                   periodic. In that case total `mass' is not conserved.
;                   This keyword cannot be used in combination with the
;                   keyword WRAPAROUND.
;       NO_MESSAGE: Suppress informational messages.
;
; Example of default allocation of nearest grid points: n0=4, *=gridpoint.
;
;     0   1   2   3     Index of gridpoints
;     *   *   *   *     Grid points
;   |---|---|---|---|   Range allocated to gridpoints ([0.0,1.0> --> 0, etc.)
;   0   1   2   3   4   posx
;
; Example of ngp allocation for WRAPAROUND: n0=4, *=gridpoint.
;
;   0   1   2   3         Index of gridpoints
;   *   *   *   *         Grid points
; |---|---|---|---|--     Range allocated to gridpoints ([0.5,1.5> --> 1, etc.)
;   0   1   2   3   4=0   posx
;
;
; OUTPUTS:
;       Prints that a CIC interpolation is being performed of x
;       samples to y grid points, unless NO_MESSAGE is set. 
;
; RESTRICTIONS:
;       Field data is assumed to be periodic with the sampled volume
;       the basic cell, unless ISOLATED is set.
;       All input arrays must have the same dimensions.
;       Postition coordinates should be in `index units' of the
;       desired grid: POSX=[0,NX>, etc.
;       Keywords ISOLATED and WRAPAROUND cannot both be set.
;
; PROCEDURE:
;       Nearest grid point is determined for each sample.
;       CIC weights are computed for each sample.
;       Samples are interpolated to the grid.
;       Grid point values are computed (sum or average of samples).
; NOTES:
;       Use tsc.pro for a higher-order interpolation scheme, ngp.pro for a lower
;       order interpolation scheme.    A standard reference for these 
;       interpolation methods is:   R.W. Hockney and J.W. Eastwood, Computer 
;       Simulations Using Particles (New York: McGraw-Hill, 1981).
; EXAMPLE:
;       nx=20
;       ny=10
;       posx=randomu(s,1000)
;       posy=randomu(s,1000)
;       value=posx^2+posy^2
;       field=cic(value,posx*nx,nx,posy*ny,ny,/average)
;       surface,field,/lego
;
; MODIFICATION HISTORY:
;       Written by Joop Schaye, Feb 1999.
;       Avoid integer overflow for large dimensions P.Riley/W.Landsman Dec. 1999

; NAME:
;       CIRRANGE
; PURPOSE:
;       To force an angle into the range 0 <= ang < 360.
; CALLING SEQUENCE:
;       CIRRANGE, ang, [/RADIANS]
;
; INPUTS/OUTPUT:
;       ang     - The angle to modify, in degrees.  This parameter is
;                 changed by this procedure.  Can be a scalar or vector.
;                 The type of ANG is always converted to double precision
;                 on output.
;
; OPTIONAL INPUT KEYWORDS:
;       /RADIANS - If present and non-zero, the angle is specified in
;                 radians rather than degrees.  It is forced into the range
;                 0 <= ang < 2 PI.
; PROCEDURE:
;       The angle is transformed between -360 and 360 using the MOD operator.   
;       Negative values (if any) are then transformed between 0 and 360
; MODIFICATION HISTORY:
;       Written by Michael R. Greason, Hughes STX, 10 February 1994.
;       Get rid of WHILE loop, W. Landsman, Hughex STX, May 1996
;       Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;       CLEANPLOT
; PURPOSE:
;       Reset all plotting system variables (!P,!X,!Y,!Z) to their default values
; EXPLANATION:
;       Reset all system variables (!P,!X,!Y,!Z) which are set by the user
;       and which affect plotting to their default values.
;
; CALLING SEQUENCE:
;       Cleanplot, [ /Silent, /ShowOnly]
;
; INPUTS:       
;       None
;
; OPTIONAL KEYWORD INPUT:
;       /SHOWONLY - If set, then CLEANPLOT will display the plotting system
;                 variables with nondefault values, but it will not reset them.
;               
;       /SILENT - If set, then CLEANPLOT will not display a message giving the 
;                 the system variables tags being reset.    One cannot set 
;                  both /SILENT and /SHOWONLY
; OUTPUTS:      
;       None
;
; SIDE EFFECTS: 
;       The system variables that concern plotting are reset to their default
;       values.  A message is output for each variable changed.
;       The !P.CLIP and CRANGE, S, WINDOW, and REGION fields of the
;       !X, !Y, and !Z system variables are not checked since these are
;       set by the graphics device and not by the user.   
;
; PROCEDURE:
;       This does NOT reset the plotting device.
;       This does not change any system variables that don't control plotting.
;
; RESTRICTIONS:
;       If user default values for !P, !X, !Y and !Z are different from
;       the defaults adopted below, user should change P_old etc accordingly
;
; MODIFICATION HISTORY:
;       Written IDL Version 2.3.0  W. Landsman & K. Venkatakrishna May '92
;       Handle new system variables in V3.0.0     W. Landsman   Dec 92
;       Assume user has at least V3.0.0           W. Landsman   August 95
;       V5.0 has 60 instead of 30 TICKV values    W. Landsman   Sep. 97
;       Change !D.N_COLORS to !D.TABLE_SIZE for 24 bit displays
;               W. Landsman  April 1998
;       Added silent keyword to supress output & modified X_old to
;       handle the new !X and !Y tags in IDL 5.4   S. Penton     July 2000
;       Test for visual depth if > V5.1   W. Landsman     July 2000
;       Macs can report a visual depth of 32  W. Landsman  March 2001
;       Call device,get_visual_depth only for device which allow it 
;                W. Landsman  June 2001
;       Default !P.color is 16777215 for 16 bit systems 
;                       W. Landsman/M. Hadfield   November 2001 
;       Added ShowOnly keyword   W. Landsman      April 2002
;       

;  NAME: 
;       CNTRD
;  PURPOSE:
;       Compute the centroid coordinates of a stellar object 
; EXPLANATION:
;       CNTRD uses the DAOPHOT "FIND" centroid algorithm by locating the 
;       position where the X and Y derivatives go to zero.   This is usually a 
;       more "robust"  determination than a "center of mass" or fitting a 2d 
;       Gaussian  if the wings in one direction are affected by the presence
;       of a neighboring star .
;
;  CALLING SEQUENCE: 
;       CNTRD, img, x, y, xcen, ycen, [ fwhm , /SILENT, /DEBUG]
;
;  INPUTS:     
;       IMG - Two dimensional image array
;       X,Y - Scalar or vector integers giving approximate stellar center
;
;  OPTIONAL INPUT:
;       FWHM - floating scalar; Centroid is computed using a box of half
;               width equal to 1.5 sigma = 0.637* FWHM.  CNTRD will prompt
;               for FWHM if not supplied
;
;  OUTPUTS:   
;       XCEN - the computed X centroid position, same number of points as X
;       YCEN - computed Y centroid position, same number of points as Y
;
;       Values for XCEN and YCEN will not be computed if the computed
;       centroid falls outside of the box, or if the computed derivatives
;       are non-decreasing.   If the centroid cannot be computed, then a 
;       message is displayed and XCEN and YCEN are set to -1.
;
;  OPTIONAL OUTPUT KEYWORDS:
;       /SILENT - Normally CNTRD prints an error message if it is unable
;               to compute the centroid.   Set /SILENT to suppress this.
;       /DEBUG - If this keyword is set, then CNTRD will display the subarray
;               it is using to compute the centroid.
;
;  PROCEDURE: 
;       Maximum pixel within distance from input pixel X, Y  determined 
;       from FHWM is found and used as the center of a square, within 
;       which the centroid is computed as the value (XCEN,YCEN) at which 
;       the derivatives of the partial sums of the input image over (y,x)
;       with respect to (x,y) = 0.
;
;  MODIFICATION HISTORY:
;       Written 2/25/86, by J. K. Hill, S.A.S.C., following
;       algorithm used by P. Stetson in DAOPHOT.
;       Allowed input vectors        G. Hennessy       April,  1992
;       Fixed to prevent wrong answer if floating pt. X & Y supplied
;               W. Landsman        March, 1993
;       Convert byte, integer subimages to float  W. Landsman  May 1995
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Better checking of edge of frame David Hogg October 2000
;       Avoid integer wraparound for unsigned arrays W.Landsman January 2001
;       Handle case where more than 1 pixel has maximum value W.L. July 2002

; NAME:
;	COMPARE_STRUCT  
; PURPOSE:
;	Compare all matching tag names and return differences
;
; EXPLANATION:
; 	Compare all matching Tags names (except for "except_Tags")
;	between two structure arrays (may have different struct.definitions),
;	and return a structured List of fields found different.
;
; CALLING SEQUENCE:
;	diff_List = compare_struct( struct_A, struct_B [ EXCEPT=, /BRIEF,
;                                    /FULL, RECUR_A, RECUR_B )
; INPUTS:
;	struct_A, struct_B : the two structure arrays to compare.
;	Struct_Name : for internal recursion use only.
; OPTIONAL INPUT KEYWORDS:
;		EXCEPT = string array of Tag names to ignore (NOT to compare).
;		/BRIEF = number of differences found for each matching field
;						of two structures is printed.
;		/FULL = option to print even if zero differences found.
;		/RECUR_A = option to search for Tag names
;				in sub-structures of struct_A,
;				and then call compare_struct recursively
;				for those nested sub-structures.
;		/RECUR_B = search for sub-structures of struct_B,
;				and then call compare_struct recursively
;				for those nested sub-structures.
;	Note:
;		compare_struct is automatically called recursively
;		for those nested sub-structures in both	struct_A and struct_B
;		(otherwise cannot take difference)
; OUTPUT:
;	Returns a structure array describing differences found,
;	which can be examined using print,diff_List or help,/st,diff_List.
; PROCEDURE:
;	Match Tag names and then use where function on tags.
; EXAMPLE:
;       Find the tags in the !X system variable which are changed after a 
;       simple plot.
;       IDL> x = !X              ;Save original values
;       IDL> plot, indgen(25)    ;Make a simple plot
;       IDL> help,/str,compare_struct(x,!X)    ;See how structure has changed
;
;            and one will see that the tags  !X.crange and !X.S are changed
;            by the plot.
; MODIFICATION HISTORY:
;	written 1990 Frank Varosi STX @ NASA/GSFC (using copy_struct)
;	modif Aug.90 by F.V. to check and compare same # of elements only.
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:   
;       CONCAT_DIR
;               
; PURPOSE:     
;       To concatenate directory and file names for current OS.
; EXPLANATION:
;       The given file name is appended to the given directory name with the 
;       format appropriate to the current operating system.
;
; CALLING SEQUENCE:               
;       result = concat_dir( directory, file) 
;
; INPUTS:
;       directory  - the directory path (string)
;       file       - the basic file name and extension (string)
;                                   can be an array of filenames.
;
; OUTPUTS:     
;       The function returns the concatenated string.  If the file input
;       is a string array then the output will be a string array also.
;               
; EXAMPLES:         
;       IDL> pixfile = concat_dir('$DIR_GIS_MODEL','pixels.dat')
;
;       IDL> file = ['f1.dat','f2.dat','f3.dat']
;       IDL> dir = '$DIR_NIS_CAL'
;       IDL> f = concat_dir(dir,file)
;
; RESTRICTIONS: 
;       Assumes Unix type format if os is not vms, MacOS or Windows.
;               
;       The version of CONCAT_DIR available at 
;       http://sohowww.nascom.nasa.gov/solarsoft/gen/idl/system/concat_dir.pro
;       includes (mostly) additional VMS-specific keywords.
;
; CATEGORY    
;        Utilities, Strings
;               
; REVISION HISTORY:
;       Prev Hist. : Yohkoh routine by M. Morrison
;       Written     : CDS version by C D Pike, RAL, 19/3/93
;       Version     : Version 1  19/3/93
;       Documentation modified Nov-94   W. Landsman 
;       Add V4.0 support for Windows    W. Landsman   Aug 95
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Changed loops to long integer   W. Landsman   December 1998
;       Added Mac support, translate Windows environment variables, 
;       & treat case where dirname ends in '/' W. Landsman  Feb. 2000

; NAME:
;       CONS_DEC
; PURPOSE:
;       Obtain the X and Y coordinates of a line of constant declination
; EXPLANATION:
;       Returns a set of Y pixels values, given an image with astrometry, and 
;            either
;       (1)  A set of X pixel values, and a scalar declination value, or
;       (2)  A set of declination values, and a scalar X value
;
;       Form (1) can be used to find the (X,Y) values of a line of constant
;       declination.  Form (2) can be used to find the Y positions of a set
;       declinations, along a line of constant X.
;
; CALLING SEQUENCE:
;       Y = CONS_DEC( DEC, X, ASTR, [ ALPHA ])
;
; INPUTS:
;       DEC - Declination value(s) in DEGREES (-!PI/2 < DEC < !PI/2).  
;               If X is a vector, then DEC must be a scalar.
;       X -   Specified X pixel value(s) for line of constant declination 
;               If DEC is a vector, then X must be a scalar.
;       ASTR - Astrometry structure, as extracted from a FITS header by the
;               procedure EXTAST
; OUTPUT:
;       Y   - Computed set of Y pixel values.  The number of Y values is the
;               same as either DEC or X, whichever is greater.
;
; OPTIONAL OUTPUT:
;       ALPHA - the right ascensions (DEGREES) associated with the (X,Y) points
;
; RESTRICTIONS:
;       Implemented only for the TANgent, SIN and CAR projections
;
; NOTES:
;       The algorithm (and notation) is based on AIPS Memo 27 by Eric Greisen,
;       with modifications for a coordinate description (CD) matrix as 
;       described in Paper II of Greisen & Calabretta (2002, A&A, 395, 1077).
;       These documents are available from 
;       http://www.cv.nrao.edu/fits/documents/wcs/wcs.html
;
; REVISION HISTORY:
;       Written, Wayne Landsman  STX Co.                          April 1988
;       Use new astrometry structure,     W. Landsman    HSTX     Jan. 1994
;       Use CD matrix, add SIN projection   W. Landsman  HSTX     April, 1996
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Fix case where DEC is scalar, X is vector   W. Landsman RITSS Feb. 2000
;       Fix possible sign error introduced Jan. 2000   W. Landsman  May 2000
;       Work for the CARee' projection W. Landsman   May 2003

; NAME:
;       CONS_RA
; PURPOSE:
;       Obtain the X and Y coordinates of a line of constant right ascension
; EXPLANATION:
;       Return a set of X pixel values given an image with astrometry, 
;       and either
;       (1) a set of Y pixel values, and a scalar right ascension (or 
;           longitude), or
;       (2) a set of right ascension values, and a scalar Y value.
;
;       In usage (1), CONS_RA can be used to determine the (X,Y) values
;       of a line of constant right ascension.  In usage (2), CONS_RA can
;       used to determine the X positions of specified RA values, along a
;       line of constant Y.
;
; CALLING SEQUENCE:
;       X = CONS_RA( RA, Y, ASTR, [ DEC] )
;
; INPUTS:         
;       RA -  Right Ascension value in DEGREES (0 < RA < 360.).  If Y is a
;               vector, then RA must be a scalar
;       Y -   Specified Y pixel value(s) for line of constant right ascension
;               If RA is a vector, then Y must be a scalar
;       ASTR - Astrometry structure as extracted from a FITS header by the 
;               procedure EXTAST
; OUTPUTS
;       X   - Computed set of X pixel values.   The number of elements of X
;               is the maximum of the number of elements of RA and Y.
; OPTIONAL OUTPUT:
;       DEC - Computed set of declinations (in DEGREES) for X,Y, coordinates
; NOTES:
;       The algorithm (and notation) is based on AIPS Memo 27 by Eric Greisen,
;       with modifications for a coordinate description (CD) matrix as 
;       described in Paper II of Calabretta & Greisen (2002, A&A, 395, 1077).
;       These documents are available from 
;       http://www.cv.nrao.edu/fits/documents/wcs/wcs.html
;
; RESTRICTIONS:
;       Implemented only for the TANgent, SIN and CARtesian projections 
;
; REVISION HISTORY:
;       Written, Wayne Landsman  STX Co.        April, 1988
;       Algorithm adapted from AIPS memo No. 27 by Eric Griessen
;       New astrometry structure
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Added SIN projection    W. Landsman   January 2000
;       Fix possible sign error introduced Jan. 2000   W. Landsman  May 2000
;       Work for the CARee' projection W. Landsman   May 2003

; NAME:
;	CONVOLVE
; PURPOSE:
;	Convolution of an image with a Point Spread Function (PSF)
; EXPLANATION:
;	The default is to compute the convolution using a product of 
;	Fourier transforms (for speed).
;
; CALLING SEQUENCE:
;
;	imconv = convolve( image1, psf, FT_PSF = psf_FT )
;  or:
;	correl = convolve( image1, image2, /CORREL )
;  or:
;	correl = convolve( image, /AUTO )
;
; INPUTS:
;	image = 2-D array (matrix) to be convolved with psf
;	psf = the Point Spread Function, (size < or = to size of image).
;
; OPTIONAL INPUT KEYWORDS:
;
;	FT_PSF = passes out/in the Fourier transform of the PSF,
;		(so that it can be re-used the next time function is called).
;	FT_IMAGE = passes out/in the Fourier transform of image.
;
;	/CORRELATE uses the conjugate of the Fourier transform of PSF,
;		to compute the cross-correlation of image and PSF,
;		(equivalent to IDL function convol() with NO rotation of PSF)
;
;	/AUTO_CORR computes the auto-correlation function of image using FFT.
;
;	/NO_FT overrides the use of FFT, using IDL function convol() instead.
;		(then PSF is rotated by 180 degrees to give same result)
; METHOD:
;	When using FFT, PSF is centered & expanded to size of image.
; HISTORY:
;	written, Frank Varosi, NASA/GSFC 1992.
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;       CONV_STSDAS
; PURPOSE:
;       Convert internal format of an STSDAS image to host machine architecture
; EXPLANATION:
;       Converts the internal format of an STSDAS image (.hhh and .hhd file)
;       to the host machine architecture.     Useful for copying STSDAS files
;       between different machines.     If the host is not a VMS machine, then
;       by default CONV_STSDAS assumes the image originated on VMS.   If the
;       host is VMS, then CONV_STSDAS assumes that the image originated on
;       an IEEE machine (e.g. SparcStation).
;
; CALLING SEQUENCE:
;       CONV_STSDAS, sdas_name, [ /FROM_IEEE]
;
; INPUTS:
;       sdas_name - scalar string giving name of the STSDAS image
;               CONV_STSDAS assumes a default header extension of .hhh -- 
;               otherwise the header extension should be included in sdas_name.
;               The internal format of the file will be modified by CONV_STSDAS.
;
; OPTIONAL KEYWORD INPUT:
;       /FROM_IEEE - On little endian machines (OSF, windows) this keyword
;               indicates that the STSDAS file originated on an IEEE machine
;               (e.g SparcStation) rather than a VMS machine
;
; EXAMPLE:
;       Suppose files test.hhd and test.hhh have been copied with FTP from
;       a Vax to a Sparcstation.   Convert these files to the SparcStation
;       internal format.
;
;       IDL> conv_stsdas, 'test'
;
; METHOD:
;       CONV_STSDAS reads each group image and parameter block and uses 
;       IEEE_TO_HOST or CONV_VAX_UNIX to convert the internal format.   The
;       converted images and parameter blocks are written back to the orginal
;       file.
;
; PROCEDURE CALLS
;       sxopen, fdecomp, sxgpar(), sxpar(), ieee_to_host, conv_vax_unix()
;
; NOTES:
;       (1)  When copying STSDAS files to VMS, be sure the .hhh file is 
;               formatted as fixed block 80 byte.
;       (2)  CONV_STSDAS has no way of knowing if a file really came from
;               a different machine architecture.    If it is applied to a file
;               that already has the correct internal format, then CONV_STSDAS
;               will "convert" this file and corrupt the internal format.
;       (3)  Note that CONV_STSDAS currently does not support conversion *from*
;               a little-endian machine (OSF, windows)          
;
; REVISION HISTORY:
;       Written   W. Landsman                     January, 1993
;       Don't require .hhh extension            April, 1993
;       Increase speed by calling SXGINFO       May, 1993
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Replace DATATYPE() with size(/TNAME)  W. Landsman   November 2001

; NAME:
;      CONV_UNIX_VAX
; PURPOSE:
;      To convert Unix IDL data types to Vax IDL data types. 
; EXPLANATION:
;      CONV_UNIX_VAX assumes the Unix IDL data type is IEEE standard in either
;      big-endian or little-endian format.
;
; CALLING SEQUENCE:
;      CONV_UNIX_VAX, variable, [ SOURCE_ARCH = ]
;
; PARAMETERS:
;      variable - The data variable to be converted.  This may be a scalar
;            or an array.  Valid datatypes are integer, longword,
;            floating point, and double precision. The result of the 
;            conversion is passed back in the original variable.
; OPTIONAL INPUT KEYWORD:  
;      SOURCE_ARCH = name (string) of source architecture
;            if using this function on a VAX, otherwise
;            !VERSION.ARCH is used to determine the conversion.
;            **If run on a VAX, the default is to assume the source to be
;            a little-endian machine with IEEE floating point
;            (e.g. MIPSEL or Alpha***).
; RESTRICTIONS:
;      Requires that data be from IEEE standard Unix machines
;      (e.g. SUN, MIPSEL, or Alpha).
; EXAMPLE:
;      Read a 100 by 100 matrix of floating point numbers from a data
;      file created on a Sun.  Then convert the matrix values into
;      VAX format.
;
;      IDL> openr,1,'vax_float.dat
;      IDL> data = fltarr(100,100)
;      IDL> forrd,1,data
;      IDL> CONV_UNIX_VAX,data,SOURCE_ARCH='sparc'
;
; MODIFICATION HISTORY:
;      Version 1      By John Hoegy            13-Jun-88
;      04-May-90 - WTT:  Created CONV_UNIX_VAX from VAX2SUN,
;                         reversing floating point procedure.
;       Modified  P. Keegstra             September 1994
;           Implemented MIPSEL and ALPHA architecture,
;           distinguishing VMS and OSF
;       Modified  P. Keegstra             February 1995
;           Added 386 PC based architectures
;       If since V5.1 then VMS is always little endian    June 1998
;       Convert to IDL V5.0   W. Landsman                 June 1998

; NAME:
;      CONV_VAX_UNIX     
; PURPOSE:
;      To convert VAX IDL data types to UNIX (Sun,MIPS,etc.) IDL data types.
; EXPLANTION:
;      Generally used on non-Vax machines to parse data created on Vaxes.
;      The architecture is obtained from IDL sys.var. !VERSION.ARCH.   
;
; CALLING SEQUENCE:
;      var_unix = conv_vax_unix( var_vax, [TARGET_ARCH = ] )
;
; INPUT PARAMETER:
;      var_vax - The data variable to be converted.  This may be a scalar
;            or an array.  All IDL datatypes are valid (including 
;            structures).   The result of the conversion is returned by the
;            function.
;
; OPTIONAL INPUT KEYWORD:  
;      TARGET_ARCH = name (string) of desired target architecture
;            (e.g. 'sparc' or 'mipsel').    If not supplied, then 
;            !VERSION.ARCH is used to determine the target architecture.
;            Note that CONV_VAX_UNIX will leave variables unchanged on a
;            VMS machine, unless the TARGET_ARCH keyword is set.
;            
; EXAMPLE:
;      Read a 100 by 100 matrix of floating point numbers from a data
;      file created on a VAX.  Then convert the matrix values into Sun format.
;
;      IDL> openr,1,'vax_float.dat'
;      IDL> data = fltarr(100,100)
;      IDL> readu,1,data
;      IDL> data = conv_vax_unix( data )
; NOTE:
;       Prior to IDL V5.1, the architecture "alpha" was ambiguous, since VMS 
;       alpha IDL used VAX D-float while OSF/1 alpha IDL uses little-endian 
;       IEEE.    The program uses !VERSION.OS to do the right thing when
;       converting to a representation appropriate for the current
;       platform.  To convert to a representation appropriate for
;       an OSF/1 alpha on a VAX or (pre V5.1) VMS alpha, please specify
;       the "mipsel" (or "i386") architecture.      
;
; MODIFICATION HISTORY:
;       Written   F. Varosi               August 1990
;       Modified  P. Keegstra             April 1992
;           Implemented MIPSEL architecture
;       Modified  P. Keegstra             July 1994
;           Implemented ALPHA architecture, distinguishing VMS and OSF
;       Modified  P. Keegstra             February 1995
;           Added 386 PC based architectures
;       Modified  P. Keegstra             March 1995
;           Added note, restored and fixed old specifiers 
;           for 386 PC based architectures
;      Modified W. Landsman for VAX problems in V4.0        August 1995
;      Work for double complex variables                    August 1995
;      Remove informational messages under VMS              August 1997
;      Since V5.1, IDL VMS uses little endian IEEE          June 1998
;      Convert to IDL V5.0                                  June 1998

; NAME:
;	COPY_STRUCT
; PURPOSE:
; 	Copy all fields with matching tag names from one structure to another
; EXPLANATION:
;       COPY_STRUCT is similar to the intrinisc STRUCT_ASSIGN procedure but 
;       has optional keywords to exclude or specify specific tags.
;  
;	Fields with matching tag names are copied from one structure array to 
;	another structure array of different type.
;	This allows copying of tag values when equating the structures of
;	different types is not allowed, or when not all tags are to be copied.
;	Can also recursively copy from/to structures nested within structures.
;	Note that the number of elements in the output structure array
;	is automatically adjusted to equal the length of input structure array.
;	If this not desired then use pro copy_struct_inx which allows
;	specifying via subscripts which elements are copied where in the arrays.
;
; CALLING SEQUENCE:
;
;	copy_struct, struct_From, struct_To, NT_copied
;	copy_struct, struct_From, struct_To, EXCEPT=["image","misc"]
;	copy_struct, struct_From, struct_To, /RECUR_TANDEM
;
; INPUTS:
;	struct_From = structure array to copy from.
;	struct_To = structure array to copy values to.
;
; KEYWORDS:
;
;	EXCEPT_TAGS = string array of tag names to ignore (to NOT copy).
;		Used at all levels of recursion.
;
;	SELECT_TAGS = tag names to copy (takes priority over EXCEPT).
;		This keyword is not passed to recursive calls in order
;		to avoid the confusion of not copying tags in sub-structures.
;
;	/RECUR_FROM = search for sub-structures in struct_From, and then
;		call copy_struct recursively for those nested structures.
;
;	/RECUR_TO = search for sub-structures of struct_To, and then
;		call copy_struct recursively for those nested structures.
;
;	/RECUR_TANDEM = call copy_struct recursively for the sub-structures
;		with matching Tag names in struct_From and struct_To
;		(for use when Tag names match but sub-structure types differ).
;
; OUTPUTS:
;	struct_To = structure array to which new tag values are copied.
;	NT_copied = incremented by total # of tags copied (optional)
;
; INTERNAL:
;	Recur_Level = # of times copy_struct calls itself.
;		This argument is for internal recursive execution only.
;		The user call is 1, subsequent recursive calls increment it,
;		and the counter is decremented before returning.
;		The counter is used just to find out if argument checking
;		should be performed, and to set NT_copied = 0 first call.
; EXTERNAL CALLS:
;	pro match	(when keyword SELECT_TAGS is specified)
; PROCEDURE:
;	Match Tag names and then use corresponding Tag numbers.
; HISTORY:
;	written 1989 Frank Varosi STX @ NASA/GSFC
; 	mod Jul.90 by F.V. added option to copy sub-structures RECURSIVELY.
;	mod Aug.90 by F.V. adjust # elements in TO (output) to equal
;			# elements in FROM (input) & count # of fields copied.
;	mod Jan.91 by F.V. added Recur_Level as internal argument so that
;			argument checking done just once, to avoid confusion.
;			Checked against Except_Tags in RECUR_FROM option.
;	mod Oct.91 by F.V. added option SELECT_TAGS= selected field names.
;	mod Aug.95 by W. Landsman to fix match of a single selected tag.
;	mod Mar.97 by F.V. do not pass the SELECT_TAGS keyword in recursion.
;	Converted to IDL V5.0   W. Landsman   September 1997
;       mod May 01 by D. Schlegel use long integers

; NAME:
;	COPY_STRUCT_INX
; PURPOSE:
;	Copy matching tags & specified indices from one structure to another
; EXPLANATION:
; 	Copy all fields with matching tag names (except for "except_Tags")
;	from one structure array to another structure array of different type.
;	This allows copying of tag values when equating the structures of
;	different types is not allowed, or when not all tags are to be copied.
;	Can also recursively copy from/to structures nested within structures.
;	This procedure is same as copy_struct with option to
;	specify indices (subscripts) of which array elements to copy from/to.
; CALLING SEQUENCE:
;
;	copy_struct_inx, struct_From, struct_To, NT_copied, INDEX_FROM=subf
;
;	copy_struct_inx, struct_From, struct_To, INDEX_FROM=subf, INDEX_TO=subto
;
; INPUTS:
;	struct_From = structure array to copy from.
;	struct_To = structure array to copy values to.
;
; KEYWORDS:
;
;	INDEX_FROM = indices (subscripts) of which elements of array to copy.
;		(default is all elements of input structure array)
;
;	INDEX_TO = indices (subscripts) of which elements to copy to.
;		(default is all elements of output structure array)
;
;	EXCEPT_TAGS = string array of Tag names to ignore (to NOT copy).
;		Used at all levels of recursion.
;
;	SELECT_TAGS = Tag names to copy (takes priority over EXCEPT).
;		This keyword is not passed to recursive calls in order
;		to avoid the confusion of not copying tags in sub-structures.
;
;	/RECUR_FROM = search for sub-structures in struct_From, and then
;		call copy_struct recursively for those nested structures.
;
;	/RECUR_TO = search for sub-structures of struct_To, and then
;		call copy_struct recursively for those nested structures.
;
;	/RECUR_TANDEM = call copy_struct recursively for the sub-structures
;		with matching Tag names in struct_From and struct_To
;		(for use when Tag names match but sub-structure types differ).
;
; OUTPUTS:
;	struct_To = structure array to which new tag values are copied.
;	NT_copied = incremented by total # of tags copied (optional)
;
; INTERNAL:
;	Recur_Level = # of times copy_struct_inx calls itself.
;		This argument is for internal recursive execution only.
;		The user call is 1, subsequent recursive calls increment it,
;		and the counter is decremented before returning.
;		The counter is used just to find out if argument checking
;		should be performed, and to set NT_copied = 0 first call.
; EXTERNAL CALLS:
;	pro match	(when keyword SELECT_TAGS is specified)
; PROCEDURE:
;	Match Tag names and then use corresponding Tag numbers,
;	apply the sub-indices during = and recursion.
; HISTORY:
;	adapted from copy_struct: 1991 Frank Varosi STX @ NASA/GSFC
;	mod Aug.95 by F.V. to fix match of a single selected tag.
;	mod Mar.97 by F.V. do not pass the SELECT_TAGS keyword in recursion,
;		and check validity of INDEX_FROM and INDEX_TO in more detail.
;	Converted to IDL V5.0   W. Landsman   September 1997
;       Use long integers W. Landsman May 2001  

; NAME:
;	CORREL_IMAGES
; PURPOSE:
;       Compute the 2-D cross-correlation function of two images
; EXPLANATION:
;       Computes the 2-D cross-correlation function of two images for
;       a range of (x,y) shifting by pixels of one image relative to the other.
;
; CALLING SEQUENCE:
;       Result = CORREL_IMAGES( image_A, image_B, 
;                        [XSHIFT=, YSHIFT=, XOFFSET_B=, YOFFSET_B=, REDUCTION=, 
;                        MAGNIFICATION=, /NUMPIX, /MONITOR  )
;
; INPUTS:
;       image_A, image_B = the two images of interest.
;
; OPTIONAL INPUT KEYWORDS:
;       XSHIFT = the + & - shift to be applied in X direction, default=7.
;       YSHIFT = the Y direction + & - shifting, default=7.
;
;       XOFFSET_B = initial X pixel offset of image_B relative to image_A.
;       YOFFSET_B = Y pixel offset, defaults are (0,0).
;
;       REDUCTION = optional reduction factor causes computation of
;                       Low resolution correlation of bin averaged images,
;                       thus faster. Can be used to get approximate optimal
;                       (x,y) offset of images, and then called for successive
;                       lower reductions in conjunction with CorrMat_Analyze
;                       until REDUCTION=1, getting offset up to single pixel.
;
;       MAGNIFICATION = option causes computation of high resolution correlation
;                       of magnified images, thus much slower.
;                       Shifting distance is automatically = 2 + Magnification,
;                       and optimal pixel offset should be known and specified.
;                       Optimal offset can then be found to fractional pixels
;                       using CorrMat_Analyze( correl_images( ) ).
;
;       /NUMPIX - if set, causes the number of pixels for each correlation
;                       to be saved in a second image, concatenated to the
;                       correlation image, so Result is fltarr( Nx, Ny, 2 ).
;       /MONITOR causes the progress of computation to be briefly printed.
;
; OUTPUTS:
;       Result is the cross-correlation function, given as a matrix.
;
; PROCEDURE:
;       Loop over all possible (x,y) shifts, compute overlap and correlation
;       for each shift. Correlation set to zero when there is no overlap.
;
; MODIFICATION HISTORY:
;       Written, July,1991, Frank Varosi, STX @ NASA/GSFC
;       Use ROUND instead of NINT, June 1995, Wayne Landsman HSTX
;       Avoid divide by zero errors, W. Landsman HSTX April 1996
;	Remove use of !DEBUG    W. Landsman   June 1997
;       Subtract mean of entire image before computing correlation, not just 
;          mean of overlap region   H. Ebeling/W. Landsman   June 1998
;       

; NAME:
;	CORREL_OPTIMIZE
;
; PURPOSE:
;	Find the optimal (x,y) pixel offset of image_B relative to image_A
; EXPLANATION"
;	Optimal offset is computed by means of maximizing the correlation 
;	function of the two images.
;
; CALLING SEQUENCE:
;	CORREL_OPTIMIZE, image_A, image_B, xoffset_optimum, yoffset_optimum 
;		[ XOFF_INIT=, YOFF_INIT=, MAGNIFICATION=, /PRINT, /NUMPIX, 
;		  /MONITOR, PLATEAU_THRESH=  ]
;
; INPUTS:
;	image_A, image_B = the two images of interest.
;
; OPTIONAL INPUT KEYWORDS:
;	XOFF_INIT = initial X pixel offset of image_B relative to image_A,
;	YOFF_INIT = Y pixel offset, (default offsets are 0 and 0).
;	MAGNIFICATION = option to determine offsets up to fractional pixels,
;			(example: MAG=2 means 1/2 pixel accuracy, default=1).
;	/NUMPIX: sqrt( sqrt( # pixels )) used as correlation weighting factor.
;	/MONITOR causes the progress of computation to be briefly printed.
;	/PRINT causes the results of analysis to be printed.
;	PLATEAU_THRESH = threshold used for detecting plateaus in 
;		the cross-correlation matrix near maximum, (default=0.01),
;		used only if MAGNIFICATION > 1.    Decrease this value for
;		high signal-to-noise data
;
; OUTPUTS:
;	xoffset_optimum = optimal X pixel offset of image_B relative to image_A.
;	yoffset_optimum = optimal Y pixel offset.
;
; CALLS:
;	function  correl_images( image_A, image_B )
;	pro  corrmat_analyze
;
; PROCEDURE:
;	The combination of function correl_images( image_A, image_B ) and
;	corrmat_analyze of the result is used to obtain the (x,y) offset
;	yielding maximal correlation. The combination is first executed at
;	large REDUCTION factors to speed up computation, then zooming in 
;	recursively on the optimal (x,y) offset by factors of 2.
;	Finally, the MAGNIFICATION option (if specified)
;	is executed to determine the (x,y) offset up to fractional pixels.
;	
; MODIFICATION HISTORY:
;	Written, July,1991, Frank Varosi, STX @ NASA/GSFC
;	Added PLATEAU_THRESH keyword  June 1997,  Wayne Landsman  STX   
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	CORRMAT_ANALYZE 
; PURPOSE:
;	Find the optimal (x,y) offset to maximize correlation of 2 images
; EXPLANATION:
;	Analyzes the 2-D cross-correlation function of two images
;	and finds the optimal(x,y) pixel offsets.
;	Intended for use with function CORREL_IMAGES.
;
; CALLING SEQUENCE:
;	corrmat_analyze, correl_mat, xoffset_optimum, yoffset_optimum, 
;		max_corr, edge, plateau, [XOFF_INIT=, YOFF_INIT=, REDUCTION=, 
;		MAGNIFICATION=, PLATEAU_THRESH=, /PRINT]
;
; INPUTS:
;	correl_mat = the cross-correlation matrix of 2 images.
;			(as computed by function CORREL_IMAGES( imA, imB ) ).
;
; NOTE:
;	If correl_mat(*,*,1) is the number of pixels for each correlation,
;	(the case when /NUMPIX was specified in call to CORREL_IMAGES)
;	then sqrt( sqrt( # pixels )) is used as correlation weighting factor.
;
; OPTIONAL INPUT KEYWORDS:
;	XOFF_INIT = initial X pixel offset of image_B relative to image_A.
;	YOFF_INIT = Y pixel offset, (both as specified to correl_images).
;	REDUCTION = reduction factor used in call to CORREL_IMAGES.
;	MAGNIFICATION = magnification factor used in call to CORREL_IMAGES,
;		this allows determination of offsets up to fractions of a pixel.
;	PLATEAU_THRESH = threshold used for detecting plateaus in 
;		the cross-correlation matrix near maximum, (default=0.01),
;		used only if MAGNIFICATION > 1
;	/PRINT causes the result of analysis to be printed.
;
; OUTPUTS:
;	xoffset_optimum = optimal X pixel offset of image_B relative to image_A.
;	yoffset_optimum = optimal Y pixel offset.
;	max_corr = the maximal correlation corresponding to optimal offset.
;	edge = 1 if maximum is at edge of correlation domain, otherwise=0.
;	plateau = 1 if maximum is in a plateua of correlation function, else=0.
;
; PROCEDURE:
;	Find point of maximum cross-correlation and calc. corresponding offsets.
;	If MAGNIFICATION > 1:
;	the  correl_mat is checked for plateau near maximum, and if found,
;	the center of plateau is taken as point of maximum cross-correlation.
;
; MODIFICATION HISTORY:
;	Written, July-1991, Frank Varosi, STX @ NASA/GSFC
;	Use ROUND instead of NINT, June 1995 Wayne Landsman HSTX
;	Remove use of non-standard !DEBUG system variable   W.L. HSTX 
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;     COSMO_PARAM
; PURPOSE:
;     Derive full set of cosmological density parameters from a partial set
; EXPLANATION:
;     This procedure is called by LUMDIST and GALAGE to allow the user a choice
;     in defining any two of four cosmological density parameters.
;
;     Given any two of the four input parameters -- (1) the normalized matter 
;     density Omega_m (2) the normalized cosmolgical constant, Omega_lambda (2) the normalized 
;     curvature term, Omega_k and (4) the deceleration parameter q0 --  this 
;     program will derive the remaining two.     Here "normalized" means divided by the closure
;     density so that Omega_m + Omega_lambda + Omega_k = 1.    For a more
;     precise definition see Caroll, Press, & Turner (1992, ArAA, 30, 499).     
;
;     If less than two parameters are defined, this procedure sets default 
;     values of Omega_k=0 (flat space), Omega_lambda = 0.7, Omega_m = 0.3
;     and q0 = -0.5
; CALLING SEQUENCE:
;       COSMO_PARAM, Omega_m, Omega_lambda, Omega_k, q0
;
; INPUT-OUTPUTS:
;     Omega_M - normalized matter energy density, non-negative numeric scalar
;     Omega_Lambda - Normalized cosmological constant, numeric scalar
;     Omega_k - normalized curvature parmeter, numeric scalar.   This is zero
;               for a flat universe
;     q0 - Deceleration parameter, numeric scalar = -R*(R'')/(R')^2
;          = 0.5*Omega_m - Omega_lambda
; NOTES:
;     If more than two parameters are defined upon input (overspecification), 
;     then the first two defined parameters in the ordered list Omega_m, 
;     Omega_lambda, Omega_k, q0 are used to define the cosmology.
; EXAMPLE:
;     Suppose one has Omega_m = 0.3, and Omega_k = 0.5 then to determine
;     Omega_lambda and q0
;    
;       IDL> cosmo_param, 0.3, omega_lambda, 0.5, q0
;   
;       which will return omega_lambda = 0.2 and q0 = -2.45
; REVISION HISTORY:
;       W. Landsman         Raytheon ITSS         April 2000

;  NAME:
;     CO_ABERRATION
; PURPOSE:
;     Calculate changes to Ra and Dec due to "the effect of aberration", 
; EXPLANATION:
;      as described in Meeus, Chap 23.
; CALLING SEQUENCE:
;      co_aberration, jd, ra, dec, d_ra, d_dec, [EPS = ]
; INPUTS
;       jd      : Julian Date [scalar or vector]
;       ra, dec : Arrays (or scalars) of the ra  and dec's in degrees
;   Note: if jd is a vector, ra and dec MUST be vectors of the same length.
;
; OUTPUTS
;       d_ra, d_dec: the corrections to ra and dec due to aberration (must then
;                     be added to ra and dec to get corrected values).
; OPTIONAL INPUT KEYWORD:
;       eps : set this to the true obliquity of the ecliptic (in radians), or
;         it will be set for you if you don't know it (in that case, set it to
;                 an empty variable).
; EXAMPLE:
;   Compute the change in RA and Dec of Theta Persei (RA = 2h46m,11.331s, Dec =
;   49d20',54.54" on 2028 Nov 13.19 TD
;
;      IDL> jdcnv,2028,11,13,.19*24,jd      ;Get Julian date
;      IDL> co_aberration,jd,ten(2,46,11.331)*15,ten(49,20,54.54),d_ra,d_dec
;
;      ==> d_ra = 30.045"    d_dec = 6.697"
; NOTES:
;  These formula are from Meeus, Chapters 23.  Accuracy is much better than 1 
;   arcsecond.
;
; REVISION HISTORY:
;   Written, June 2002,      Chris O'Dell, U. of Wisconsin

;  NAME:
;     CO_NUTATE
;  PURPOSE:
;     Calculate changes in RA and Dec due to nutation of the Earth's rotation
; EXPLANATION:
;     Calculates necessary changes to ra and dec due to
;     the nutation of the Earth's rotation axis, as described in Meeus, Chap 23.
;     Uses formulae from Astronomical Almanac, 1984, and does the calculations
;     in equatorial rectangular coordinates to avoid singularities at the
;     celestial poles.
;
; CALLING SEQUENCE:
;     CO_NUTATE, jd, ra, dec, d_ra, d_dec, [EPS=, D_PSI =, D_EPS = ]
; INPUTS
;    JD: Julian Date [scalar or vector]
;    RA, DEC : Arrays (or scalars) of the ra and dec's of interest
;
;   Note: if jd is a vector, ra and dec MUST be vectors of the same length.
;
; OUTPUTS:
;    d_ra, d_dec: the corrections to ra and dec due to nutation (must then
;                                be added to ra and dec to get corrected values).
; OPTIONAL OUTPUT KEYWORDS:
;    EPS: set this to a named variable that will contain the obliquity of the 
;             ecliptic.
;    D_PSI: set this to a named variable that will contain the nutation in the
;           longitude of the ecliptic
;    D_EPS: set this to a named variable that will contain the nutation in the
;                       obliquity of the ecliptic
; EXAMPLE:
;    (1) Example 23a in Meeus: On 2028 Nov 13.19 TD the mean position of Theta
;        Persei is 2h 46m 11.331s 49d 20' 54.54".    Determine the shift in 
;        position due to the Earth's nutation.
;    
;        IDL> jd = JULDAY(11,13,2028,.19*24)       ;Get Julian date
;        IDL> CO_NUTATE, jd,ten(2,46,11.331)*15.,ten(49,20,54.54),d_ra,d_dec    
;
;              ====> d_ra = 15.843"   d_dec = 6.217"
; PROCEDURES USED:
;    NUTATE 
; REVISION HISTORY:
;    Written  Chris O'Dell, 2002
;    Vector call to NUTATE   W. Landsman   June 2002

; NAME:
;   CO_REFRACT()      
;
; PURPOSE:
;   Calculate correction to altitude due to atmospheric refraction.
;
; DESCRIPTION:
;   CO_REFRACT can calculate both apparent altitude from observed altitude and 
;   vice-versa.
;
; CALLING SEQUENCE:
;   new_alt  = CO_REFRACT(old_alt, [ ALTITUDE= , PRESSURE= , $
;                                  TEMPERATURE= , /TO_OBSERVED , EPSILON= ])
;
; INPUT:
;   old_alt - Observed (apparent) altitude, in DEGREES.  (apparent if keyword 
;             /TO_OBSERVED set).    May be scalar or vector.
;
; OUTPUT: 
;     Function returns apparent (observed) altitude, in DEGREES. (observed if 
;         keyword /TO_OBSERVED set).    Will be of same type as input 
;         altitude(s).
;
; OPTIONAL KEYWORD INPUTS:
;      ALTITUDE :  The height of the observing location, in meters.  This is 
;             only used to determine an approximate temperature and pressure, 
;             if these are not specified separately. [default=0, i.e. sea level]
;      PRESSURE :  The pressure at the observing location, in millibars.
;      TEMPERATURE:    The temperature at the observing location, in Kelvin.
;      EPSILON:  When keyword /TO_OBSERVED has been set, this is the accuracy 
;               to  obtain via the iteration, in arcseconds [default = 0.25 
;                arcseconds].
;      /TO_OBSERVED:  Set this keyword to go from Apparent->Observed altitude, 
;                 using the iterative technique.
;
;       Note, if altitude is set, but temperature or pressure are not, the 
;       program will make an intelligent guess for the temperature and pressure.
;
; DESCRIPTION:
;
;   Because the index of refraction of air is not precisely 1.0, the atmosphere
;   bends all incoming light, making a star or other celestial object appear at
;   a slightly different altitude (or elevation) than it really is.  It is 
;   important to understand the following definitions:
;
;   Observed Altitude:  The altitude that a star is SEEN to BE, with a telescope.
;                       This is where it appears in the sky.  This is always 
;                       GREATER than the apparent altitude.
;
;   Apparent Altitude:  The altitude that a star would be at, if *there were no
;                     atmosphere* (sometimes called "true" altitude). This is 
;                     usually calculated from an object's celestial coordinates.
;                     Apparent altitude is always LOWER than the observed 
;                     altitude.
;
;   Thus, for example, the Sun's apparent altitude when you see it right on the
;   horizon is actually -34 arcminutes.
;
;   This program uses couple simple formulae to estimate the effect for most 
;   optical and radio wavelengths.  Typically, you know your observed altitude 
;   (from an observation), and want the apparent altitude.  To go the other way,
;   this program uses an iterative approach.
;
; EXAMPLE:
;    The lower limb of the Sun is observed to have altitude of 0d 30'.   
;    Calculate the the true (=apparent) altitude of the Sun's lower limb using 
;    mean  conditions of air pressure and temperature
;
;    IDL> print, co_refract(0.5)     ===>  0.025degrees (1.55')
; WAVELENGTH DEPENDENCE:
;    This correction is 0 at zenith, about 1 arcminute at 45 degrees, and 34 
;    arcminutes at the horizon FOR OPTICAL WAVELENGTHS.  The correction is 
;    NON-NEGLIGIBLE at all wavelengths, but is not very easily calculable.  
;    These formulae assume a wavelength of 550 nm, and will be accurate to 
;    about 4 arcseconds for all visible wavelengths, for elevations of 10 
;    degrees and higher.    Amazingly, they are also ACCURATE FOR RADIO 
;    FREQUENCIES LESS THAN ~ 100 GHz.
;
;    It is important to understand that these formulae really can't do better 
;    than about 30 arcseconds of accuracy very close to the horizon, as 
;    variable atmospheric effects become very important.
;
; REFERENCES:
;    1.  Meeus, Astronomical Algorithms, Chapter 15.
;    2.  Explanatory Supplement to the Astronomical Almanac, 1992.
;    3.  Methods of Experimental Physics, Vol 12 Part B, Astrophysics, 
;        Radio Telescopes, Chapter 2.5, "Refraction Effects in the Neutral 
;        Atmosphere", by R.K. Crane.
;
;
; DEPENDENCIES:
;    CO_REFRACT_FORWARD (contained in this file and automatically compiled).
;
; AUTHOR:
;   Chris O'Dell
;       Univ. of Wisconsin-Madison
;   Observational Cosmology Laboratory
;   Email: odell@cmb.physics.wisc.edu
;
; REVISION HISTORY:
;    version 1 (May 31, 2002)
;    Update iteration formula,   W. Landsman    June 2002
;    Corrected slight bug associated with scalar vs. vector temperature and 
;               pressure inputs. 6/10/2002

; NAME:
;       CREATE_STRUCT
; PURPOSE:
;       Create an IDL structure from a list of tag names and dimensions
; EXPLANATION:
;       Dynamically create an IDL structure variable from list of tag names 
;       and data types of arbitrary dimensions.   Useful when the type of
;       structure needed is not known until run time.
;
;       Unlike the intrinsic function CREATE_STRUCT(), this procedure does not
;       require the user to know the number of tags before run time.   (Note
;       there is no name conflict since the intrinsic CREATE_STRUCT is a 
;       function, and this file contains a procedure.)
; CALLING SEQUENCE:
;       CREATE_STRUCT, STRUCT, strname, tagnames, tag_descript, 
;                             [ DIMEN = , /CHATTER, /NODELETE ]
;
; INPUTS:
;       STRNAME -   name to be associated with structure (string)
;               Must be unique for each structure created.   Set
;               STRNAME = '' to create an anonymous structure
;
;       TAGNAMES -  tag names for structure elements
;               (string or string array)
;
;       TAG_DESCRIPT -  String descriptor for the structure, containing the
;               tag type and dimensions.  For example, 'A(2),F(3),I', would
;               be the descriptor for a structure with 3 tags, strarr(2), 
;               fltarr(3) and Integer scalar, respectively.
;               Allowed types are 'A' for strings, 'B' or 'L' for unsigned byte 
;               integers, 'I' for integers, 'J' for longword integers, 
;               'F' or 'E' for floating point, 'D' for double precision
;               'C' for complex, and 'M' for double complex
;               Uninterpretable characters in a format field are ignored.
;
;               For vectors, the tag description can also be specified by
;               a repeat count.  For example, '16E,2J' would specify a 
;               structure with two tags, fltarr(16), and lonarr(2)
;
; OPTIONAL KEYWORD INPUTS:
;       DIMEN -    number of dimensions of structure array (default is 1)
;
;       CHATTER -  If /CHATTER is set, then CREATE_STRUCT will display
;                  the dimensions of the structure to be created, and prompt
;                  the user whether to continue.  Default is no prompt.
;
;       NODELETE - If /NODELETE is set, then the temporary file created
;                  CREATE_STRUCT will not be deleted upon exiting.   See below
;
; OUTPUTS:
;       STRUCT -   IDL structure, created according to specifications 
;
; EXAMPLES: 
;
;       IDL> create_struct, new, 'name',['tag1','tag2','tag3'], 'D(2),F,A(1)'
;
;       will create a structure variable new, with structure name NAME
;
;       To see the structure of new:
;
;       IDL> help,new,/struc
;       ** Structure NAME, 3 tags, 20 length:
;          TAG1            DOUBLE         Array(2)
;          TAG2            FLOAT          0.0
;          TAG3            STRING         Array(1)
;
; PROCEDURE:
;       Generates a temporary procedure file using input information with
;       the desired structure data types and dimensions hard-coded.
;       This file is then executed with CALL_PROCEDURE.
;
; NOTES:
;       If CREATE_STRUCT cannot write a temporary .pro file in the current 
;       directory, then it will write the temporary file in the getenv('HOME')
;       directory.
;
;       At present, can fail if a tag_name cannot be used as a proper
;       structure component definition, e.g., '0.10' will not
;       work, but a typical string like 'RA' or 'DEC' will.
;       A partial workaround checks for characters '\' and '/'
;       and '.' and converts them to '_'. in a tag_name.
;
;       Note that 'L' now specifies a LOGICAL (byte) data type and not a
;       a LONG data type for consistency with FITS binary tables
;
; RESTRICTIONS:
;       The name of the structure must be unique, for each structure created.
;       Otherwise, the new variable will have the same structure as the 
;       previous definition (because the temporary procedure will not be
;       recompiled).  ** No error message will be generated  ***
;
; SUBROUTINES CALLED:
;       FDECOMP, REPCHR() 
;
; MODIFICATION HISTORY:
;       Version 1.0 RAS January 1992
;       Modified 26 Feb 1992 for Rosat IDL Library (GAR)
;       Modified Jun 1992 to accept arrays for tag elements -- KLV, Hughes STX
;       Accept anonymous structures W. Landsman  HSTX    Sep. 92
;       Accept 'E' and 'J' format specifications   W. Landsman Jan 93
;       'L' format now stands for logical and not long array
;       Accept repeat format for vectors        W. Landsman Feb 93
;       Accept complex and double complex (for V4.0)   W. Landsman Jul 95
;       Work for long structure definitions  W. Landsman Aug 97
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Write temporary file in HOME directory if necessary  W. Landsman Jul 98
;       Use OPENR,/DELETE for OS-independent file removal W. Landsman Jan 99
;       Use STRSPLIT() instead of GETTOK() W. Landsman  July 2002

; NAME:
;     CR_REJECT
;
; PURPOSE:
;     General, iterative cosmic ray rejection using two or more input images.
;
; EXPLANATION:
;     Uses a noise model input by the user, rather than
;     determining noise empirically from the images themselves.
;
;     The image returned has the combined exposure time of all the input
;     images, unless the bias flag is set, in which case the mean is
;     returned.  This image is computed by summation (or taking mean)
;     regardless of loop and initialization options (see below).
;
; CALLING SEQUENCE:
;     cr_reject, input_cube, rd_noise_dn, dark_dn, gain, mult_noise, $
;        combined_image, combined_npix, combined_noise
;
; MODIFIED ARGUMENT:
;     input_cube - Cube in which each plane is an input image.
;                  If the noise model is used (rd_noise_dn, dark_dn,
;                  gain), then input_cube must be in units of DN.
;                  If an input noise cube is supplied (rd_noise_dn
;                  <0), then the units of input_cube and noise_cube
;                  merely need to be consistent.  
;
;                  This array is used as a buffer and its contents 
;                  are not guaranteed on output (although for now, 
;                  weighting=0 with /restore_sky should give you back 
;                  your input unaltered).
;
; INPUT ARGUMENTS:
;     rd_noise_dn - Read noise per pixel.  Units are DN.
;                   If negative, then the user supplies an error cube
;                   via the keyword noise_cube.  In the latter case,
;                   mult_noise still applies, since it is basically a fudge.
;     dark_dn     - Dark rate in DN per pixel per s.  This can be a scalar,
;                   or it can be a dark image divided by the exposure
;                   time.
;     gain        - Electrons per DN.
;     mult_noise  - Coefficient for multiplicative noise term -- helps
;                   account for differing PSFs or subpixel image shifts.
;
; INPUT KEYWORDS:
;     exptime    - If the images have different exposure times, pass
;                  them in a vector.  You can leave this off for 
;                  frames with the same exposure time, but dark counts
;                  won't be treated correctly.
;     verbose    - If set, lots of output.
;     nsig       - Rejection limit in units of pixel-to-pixel noise
;                  (sigma) on each input image.  Can be specified as
;                  an array, in which case the dimension gives the
;                  maximum number of iterations to run.  (Default = 
;                  [8, 6, 4]
;     dilation   - With dfactor, provides functionality similar to the
;                  expansion of the CR with pfactor and radius in STSDAS 
;                  crrej.  Dilate gives the size of the border to be
;                  tested around each initially detected CR pixel.
;                  E.g., dilate=1 searches a 9 X 9 area centered on the
;                  original pixel.  If dfactor is set, the default is 1.
;     dfactor    - See dilation.  This parameter is equivalent to pfactor
;                  in STSDAS crrej.  The current threshold for rejection
;                  is multiplied by this factor when doing the search
;                  with the dilated mask.  If dilation is set, the default
;                  for this parameter is 0.5.
;     bias       - Set if combining biases (divides through by number
;                  of images at end, since exposure time is 0).
;     tracking_set - Subscripts of pixels to be followed through the 
;                    computation.
;     noskyadjust  - Sky not to be subtracted before rejection tests.  Default
;                  is to do the subtraction.
;     xmedsky    - Flag.  If set, the sky is computed as a 1-d array
;                  which is a column-by-column median.  This is intended
;                  for STIS slitless spectra.  If sky adjustment is
;                  disabled, this keyword has no effect.
;     input_mask - Mask cube input by the user.  Should be byte data
;                  because it's boolean.  1 means use the pixel,
;                  and 0 means reject the pixel - these rejections
;                  are in addition to those done by the CR rejection
;                  algorithm as such.
;
;     The following keywords control how the current guess at a CR-free
;     "check image" is recomputed on each iteration:
;
;     median_loop  - If set, the check image for each iteration is
;                    the pixel-by-pixel median. THE MEAN IS
;                    RETURNED in combined_image even if you set
;                    this option.  (Default is mean_loop.)
;     minimum_loop - If set, the check image for each iteration is
;                    the pixel-by-pixel minimum. THE MEAN IS
;                    RETURNED in combined_image even if you set
;                    this option.  (Default is mean_loop.)
;     mean_loop    - If set, the check image for each iteration is
;                    the pixel-by-pixel mean.  (Same as the default.)
;     noclearmask  - By default, the mask of CR flags is reset before
;                    every iteration, and a pixel that has been
;                    rejected has a chance to get back in the game
;                    if the average migrates toward its value.  If this
;                    keyword is set, then any rejected pixel stays 
;                    rejected in subsequent iterations.  Note that what 
;                    stsdas.hst_calib.wfpc.crrej does is the same
;                    as the default.  For this procedure, the default
;                    was NOT to clear the flags, until 20 Oct. 1997.
;     restore_sky  - Flag.  If set, the routine adds the sky back into
;                    input_cube before returning.  Works only if
;                    weighting=0.
;     null_value   - Value to be used for output pixels to which no
;                    input pixels contribute.  Default=0
;     weighting    - Selects weighting scheme in final image
;                    combination:
;                     0 (default) - Poissonian weighting - co-add
;                         detected DN from non-CR pixels.  (Pixel-by-
;                         pixel scaling up to total exposure time,
;                         for pixels in stack where some rejected.)
;                         Equivalent to exptime weighting of rates.
;                     1 or more - Sky and read noise weighting of rates.
;                         Computed as weighted average of DN rates,
;                         with total exp time multiplied back in
;                         afterward.
;
;                    In all cases, the image is returned as a sum in
;                    DN with the total exposure time of the image 
;                    stack, and with total sky added back in.
;
;     The following keywords allow the initial guess at a CR-free "check
;     image" to be of a different kind from the iterative guesses:
;
;     init_med  - If set, the initial check image is
;                 the pixel-by-pixel median.  (Not permitted if
;                 input_cube has fewer than 3 planes; default is minimum.)
;     init_mean - If set, the initial check image is
;                 the pixel-by-pixel mean.  (Default is minimum.)    
;     init_min  - If set, the initial check image is
;                 the pixel-by-pixel minimum.  (Same as the default.)    
;  
; OUTPUT ARGUMENTS::
;     combined_image - Mean image with CRs removed.
;     combined_npix  - Byte (or integer) image of same dimensions as
;                      combined_image, with each element containing
;                      the number of non-CR stacked pixels that
;                      went into the  result.
;     combined_noise - Noise in combined image according to noise model
;                      or supplied noise cube.
;
; OUTPUT KEYWORDS:
;     mask_cube      - CR masks for each input image.  1 means
;                      good pixel; 0 means CR pixel.
;     skyvals        - Sky value array.  For an image cube with N planes,
;                      this array is fltarr(N) if the sky is a scalar per
;                      image plane, and fltarr(XDIM, N), is the XMEDSKY
;                      is set.
;
; INPUT/OUTPUT KEYWORD:
;     noise_cube     - Estimated noise in each pixel of input_cube as
;                      returned (if rd_noise_dn ge 0), or input noise
;                      per pixel of image_cube (if rd_noise_dn lt 0).
;     skybox         - X0, X1, Y0, Y1 bounds of image section used
;                      to compute sky.  If supplied by user, this 
;                      region is used.  If not supplied, the
;                      image bounds are returned.  This parameter might
;                      be used (for instance) if the imaging area
;                      doesn't include the whole chip.
;
; COMMON BLOCKS:  none
;
; SIDE EFFECTS:  none
;
; METHOD: 
;     
;     COMPARISON WITH STSDAS
;
;     Cr_reject emulates the crrej routine in stsdas.hst_calib.wfpc.
;     The two routines have been verified to give identical results
;     (except for some pixels along the edge of the image) under the 
;     following conditions:
;
;          no sky adjustment
;          no dilation of CRs
;          initialization of trial image with minimum
;          taking mean for each trial image after first (no choice
;             in crrej)
;     
;     Dilation introduces a difference between crrej and this routine
;     around the very edge of the image, because the IDL mask
;     manipulation routines don't handle the edge the same way as crrej
;     does.  Away from the edge, crrej and cr_reject are the same with
;     respect to dilation.
;
;     The main difference between crrej and cr_reject is in the sky
;     computation.  Cr_reject does a DAOPHOT I sky computation on a 
;     subset of pixels grabbed from the image, whereas crrej searches
;     for a histogram mode.
;
;     REMARKS ON USAGE
;
;     The default is that the initial guess at a CR-free image is the
;     pixel-by-pixel minimum of all the input images.  The pixels
;     cut from each component image are the ones more than nsig(0) sigma
;     from this minimum image.  The next iteration is based on the
;     mean of the cleaned-up component images, and the cut is taken
;     at nsig(1) sigma.  The next iteration is also based on the mean with
;     the cut taken at nsig(2) sigma.
;
;     The user can specify an arbitrary sequence of sigma cuts, e.g.,
;     nsig=[6,2] or nsig=[10,9,8,7].  The user can also specify that
;     the initial guess is the median (/init_med) rather than the
;     minimum, or even the mean.  The iterated cleaned_up images after
;     the first guess can be computed as the mean or the median
;     (/mean_loop or /median_loop).  The minimum_loop option is also
;     specified, but this is a trivial case, and you wouldn't want
;     to use it except perhaps for testing.
;
;     The routine takes into account exposure time if you want it to, 
;     i.e., if the pieces of the CR-split aren't exactly the same.
;     For bias frames (exposure time 0), set /bias to return the mean
;     rather than the total of the cleaned-up component images.
;
;     The crrej pfactor and radius to propagate the detected CRs
;     outward from their initial locations have been implemented
;     in slightly different form using the IDL DILATE function.
;
;     It is possible to end up with output pixels to which no valid
;     input pixels contribute.  These end up with the value
;     NULL_VALUE, and the corresponding pixels of combined_npix are
;     also returned as 0.  This result can occur when the pixel is
;     very noisy across the whole image stack, i.e., if all the
;     values are, at any step of the process, far from the stack
;     average at that position even after rejecting the real
;     outliers.  Because  pixels are flagged symmetrically N sigma
;     above and below the  current combined image (see code), all
;     the pixels at a given  position can end up getting flagged.
;     (At least, that's how I think it happens.)
;
; MODIFICATION HISTORY:
;      5 Mar. 1997 - Written.  R. S. Hill
;     14 Mar. 1997 - Changed to masking approach to keep better
;                    statistics and return CR-affected pixels to user.
;                    Option to track subset of pixels added.
;                    Dilation of initially detected CRs added.
;                    Other small changes.  RSH
;     17 Mar. 1997 - Arglist and treatment of exposure times fiddled
;                    to mesh better with stis_cr.  RSH
;     25 Mar. 1997 - Fixed bug if dilation finds nothing.  RSH
;      4 Apr. 1997 - Changed name to cr_reject.  RSH
;     15 Apr. 1997 - Restyled with emacs, nothing else done.  RSH
;     18 Jun. 1997 - Input noise cube allowed.  RSH
;     19 Jun. 1997 - Multiplicative noise deleted from final error.  RSH
;     20 Jun. 1997 - Fixed error in using input noise cube.  RSH
;     12 July 1997 - Sky adjustment option.  RSH
;     27 Aug. 1997 - Dilation kernel made round, not square, and
;                    floating-point radius allowed.  RSH
;     16 Sep. 1997 - Clearmask added.  Intermediate as well as final
;                    mean is exptime weighted.  RSH
;     17 Sep. 1997 - Redundant zeroes around dilation kernel trimmed.  RSH
;      1 Oct. 1997 - Bugfix in preceding.  RSH
;     21 Oct. 1997 - Clearmask changed to noclearmask.  Bug in robust
;                    array division fixed (misplaced parens).  Sky as
;                    a function of X (option).  RSH
;     30 Jan. 1998 - Restore_sky keyword added.  RSH
;      5 Feb. 1998 - Quick help corrected and updated.  RSH
;      6 Feb. 1998 - Fixed bug in execution sequence for tracking_set 
;                    option.  RSH
;     18 Mar. 1998 - Eliminated confusing maxiter spec.  Added
;                    null_value keyword.  RSH
;     15 May  1998 - Input_mask keyword.  RSH
;     27 May  1998 - Initialization of minimum image corrected. NRC, RSH
;      9 June 1998 - Input mask cube processing corrected.  RSH
;     21 Sep. 1998 - Weighting keyword added.  RSH
;      7 Oct. 1998 - Fixed bug in input_mask processing (introduced
;                    in preceding update).  Input_mask passed to
;                    skyadj_cube.  RSH
;      5 Mar. 1999 - Force init_min for 2 planes.  RSH
;      1 Oct. 1999 - Make sure weighting=1 not given with noise cube.  RSH
;      1 Dec. 1999 - Corrections to doc; restore_sky needs weighting=0.  RSH
;     17 Mar. 2000 - SKYBOX added.  RSH

; NAME:
;      CSPLINE
;
; PURPOSE:
;      Function to evaluate a natural cubic spline at specified data points
; EXPLANATION:
;      Combines the Numerical Recipes functions SPL_INIT and SPL_INTERP
;
; CALLING SEQUENCE:
;      result = cspline( x, y, t, [ DERIV = ])
;
; INPUTS:
;      x - vector of spline node positions, must be monotonic increasing or
;          decreasing
;      y - vector of node values
;      t - x-positions at which to evaluate the spline, scalar or vector
;
; INPUT-OUTPUT KEYWORD:
;      DERIV - values of the second derivatives of the interpolating function 
;               at the node points.   This is an intermediate step in the 
;               computation of the natural spline that requires only the X and 
;               Y vectors.    If repeated interpolation is to be applied to 
;               the same (X,Y) pair, then some computation time can be saved 
;               by supplying the DERIV keyword on each call.   On the first call
;               DERIV will be computed and returned on output.    
;
; OUTPUT:
;       the values for positions t are returned as the function value
;       If any of the input variables are double precision, then the output will
;       also be double precision; otherwise the output is floating point.
;
; EXAMPLE:                               
;       The following uses the example vectors from the SPL_INTERP documentation
;
;       IDL> x = (findgen(21)/20.0)*2.0*!PI ;X vector
;       IDL> y = sin(x)                     ;Y vector
;       IDL> t = (findgen(11)/11.0)*!PI     ;Values at which to interpolate 
;       IDL> plot,x,y,psym=1                ;Plot original grid
;       IDL> oplot, t,cspline(x,y,t),psym=2 ;Overplot interpolated values
;
; METHOD:
;      The "Numerical Recipes" implementation of the natural cubic spline is 
;      used, by calling the intrinsic IDL functions SPL_INIT and SPL_INTERP.
;
; HISTORY:
;      version 1  D. Lindler  May, 1989
;      version 2  W. Landsman April, 1997
;      Rewrite using the intrinsic SPL_INIT & SPL_INTERP functions
;      Converted to IDL V5.0   W. Landsman   September 1997
;      Work for monotonic decreasing X vector    W. Landsman   February 1999

; NAME:
;     CT2LST
; PURPOSE:
;     To convert from Local Civil Time to Local Mean Sidereal Time.
;
; CALLING SEQUENCE:
;     CT2LST, Lst, Lng, Tz, Time, [Day, Mon, Year] 
;                       or
;     CT2LST, Lst, Lng, dummy, JD
;
; INPUTS:
;     Lng  - The longitude in degrees (east of Greenwich) of the place for 
;            which the local sidereal time is desired, scalar.   The Greenwich 
;            mean sidereal time (GMST) can be found by setting Lng = 0.
;     Tz  - The time zone of the site in hours.  Use this to easily account 
;            for Daylight Savings time (e.g. 4=EDT, 5 = EST/CDT), scalar
;            This parameter is not needed (and ignored) if Julian date is 
;            supplied.
;     Time or JD  - If more than four parameters are specified, then this is 
;               the time of day of the specified date in decimal hours.  If 
;               exactly four parameters are specified, then this is the 
;               Julian date of time in question, scalar or vector
;
; OPTIONAL INPUTS:
;      Day -  The day of the month (1-31),integer scalar or vector
;      Mon -  The month, in numerical format (1-12), integer scalar or 
;      Year - The year (e.g. 1987)
;
; OUTPUTS:
;       Lst   The Local Sidereal Time for the date/time specified in hours.
;
; RESTRICTIONS:
;       If specified, the date should be in numerical form.  The year should
;       appear as yyyy.
;
; PROCEDURE:
;       The Julian date of the day and time is question is used to determine
;       the number of days to have passed since 0 Jan 2000.  This is used
;       in conjunction with the GST of that date to extrapolate to the current
;       GST; this is then used to get the LST.    See Astronomical Algorithms
;       by Jean Meeus, p. 84 (Eq. 11-4) for the constants used.
;
; EXAMPLE:
;       Find the Greenwich mean sidereal time (GMST) on 1987 April 10, 19h21m UT
;
;       For GMST, we set lng=0, and for UT we set Tz = 0
;
;       IDL> CT2LST, lst, 0, 0,ten(19,21), 10, 4, 1987
;
;               ==> lst =  8.5825249 hours  (= 8h 34m 57.0896s)
;
;       The Web site  http://tycho.usno.navy.mil/sidereal.html contains more
;       info on sidereal time, as well as an interactive calculator.
; PROCEDURES USED:
;       jdcnv - Convert from year, month, day, hour to julian date
;
; MODIFICATION HISTORY:
;     Adapted from the FORTRAN program GETSD by Michael R. Greason, STX, 
;               27 October 1988.
;     Use IAU 1984 constants Wayne Landsman, HSTX, April 1995, results 
;               differ by about 0.1 seconds  
;     Converted to IDL V5.0   W. Landsman   September 1997
;     Longitudes measured *east* of Greenwich   W. Landsman    December 1998

; NAME:
;       CURS
; PURPOSE:
;       Selects an X windows cursor shape
; CALLING SEQUENCE:
;       curs            ;Interactively select a cursor shape.
;       curs, sel       ;Make the given CURSOR_STANDARD value the cursor
;                        shape.
; OPTIONAL INPUT:
;       sel  -  Either an integer giving the CURSOR_STANDARD value (usually an 
;               even value between 0 and 152) indicating the cursor shape, or 
;               a string from the following menu
;       a -- Up arrow              
;       b -- Left-angled arrow
;       c -- Right-angled arrow
;       d -- Crosshair
;       e -- Finger pointing left 
;       f -- Finger pointing right
;       g -- Narrow crosshair
;       h -- Cycle through all possible standard cursor shapes
; OUTPUTS:
;       None.
; RESTRICTIONS:
;       Uses the CURSOR_STANDARD keyword of the DEVICE procedure.  Although 
;       this keyword is available under Macintosh and Windows IDL, the values
;       used by this procedure are specific to the X windows device.
;
; PROCEDURE:
;       If the user supplies a valid cursor shape value, it is set.  Otherwise,
;       an interactive command loop is entered; it will continue until a valid
;       value is given.
; MODIFICATION HISTORY:
;       Converted to VAX 3100 workstations / IDL V2.  M. Greason, STX, May 1990.
;       Avoid bad cursor parameter values  W. Landsman   February, 1991
;       Don't change value of input param        W. Landsman   August 1995
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Use SIZE(/TNAME) instead of DATATYPE()   W. Landsman  October 2001

; NAME:
;       CURVAL
; PURPOSE:   
;       Cursor controlled display of image intensities and astronomical coords
; EXPLANATION
;       CURVAL displays different information depending whether the user 
;       supplied an image array, and/or a FITS header array
;
; CALLING SEQUENCE(S):
;       curval          ;Display x,y and byte intensity (inten)
;       
;       curval, im   ;Display x,y,inten, and also pixel value (from image array)
;       
;       curval, hdr, [ im, OFFSET = , ZOOM =, FILEIMAGE =]        
;
; OPTIONAL INPUTS:
;       Hdr  = FITS Header array
;       Im  = Array containing values that are displayed.  Any type.
;
; OPTIONAL KEYWORD INPUTS:
;      OFFSET - 2 element vector giving the location of the image pixel (0,0) 
;               on the window display.   OFFSET can be positive (e.g if the 
;               image is centered in a larger window) or negative (e.g. if the
;               only the central region of an image much larger than the window
;               is being displayed. 
;               Default value is [0,0], or no offset.
;       ZOOM - Scalar specifying the magnification of the window with respect
;               to the image variable.    Use, for example, if image has been
;               REBINed before display.
;       FILENAME  = name of file to where CURVAL data can be saved.
;               Data will only be saved if left or center mouse button
;               are pressed.
;
; OUTPUTS:
;       None.
;
; SIDE EFFECTS:
;       X and Y values, etc., of the pixel under the cursor are constantly
;       displayed.  
;       Pressing left or center mouse button prints a line of output, and 
;       starts a new line.
;       Pressing right mouse button exits the procedure.
;       If the keyword FILENAME is defined, the date and time, and a heading 
;       will be printed in the file before the data.
;
; MINIMUM IDL VERSION:
;       V5.0   (uses !MOUSE, square brackets)
; PROCEDURES CALLED:
;       ADSTRING(), EXTAST, GSSSXYAD, RADEC, SXPAR(), UNZOOM_XY, XY2AD
; REVISION HISTORY:
;       Written,  K. Rhode,  STX  May 1990
;       Added keyword FILENAME  D. Alexander  June 1991
;       Don't write to Journal file   W. Landsman    March 1993
;       Use astrometry structure  W. Landsman      Feb 1994
;       Modified for Mac IDL          I.   Freedman     April 1994
;       Allow for zoomed or offset image  W. Landsman      Mar 1996
;       Proper rounding of zoomed pixel values   W. Landsman/R. Hurt  Dec. 1997
;       Converted to IDL V5.0   W. Landsman 10-Dec-1997
;       Remove unneeded calls to obsolete !ERR   W. Landsman   December 2000
;       Replace remaining !ERR calls with !MOUSE.BUTTON W. Landsman Jan 2001
;       Allow for non-celestial (e.g. Galactic) coordinates W. Landsman Apr 2003

; NAME:
;	DAOERF
; PURPOSE:         
;	Calulates the intensity, and derivatives, of a 2-d Gaussian PSF
; EXPLANATION:
;	Corrects for the finite size of a pixel by integrating the Gaussian
;	over the size of the pixel.    Used in the IDL-DAOPHOT sequence.   
;
; CALLING SEQUENCE:
;	DAOERF, XIN, YIN, A, F, [ PDER ] 
;
; INPUTS:
;	XIN - input scalar, vector or array, giving X coordinate values
;	YIN - input scalar, vector or array, giving Y coordinate values, must 
;		have same number of elements as XIN.
;	A - 5 element parameter array describing the Gaussian
;		A(0) - peak intensity
;		A(1) - X position of peak intensity (centroid)
;		A(2) - Y position of peak intensity (centroid)
;		A(3) - X sigma of the gaussian (=FWHM/2.345)         
;		A(4) - Y sigma of gaussian
;
; OUTPUTS:
;	F - array containing value of the function at each (XIN,YIN) 
;	    The number of output elements in F and PDER is identical with
;		the number of elements in X and Y
;
; OPTIONAL OUTPUTS:
;	PDER - 2 dimensional array of size (NPTS,5) giving the analytic
;		derivative at each value of F with respect to each parameter A.
;
; REVISION HISTORY:
;	Written: W. Landsman                October, 1987
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	DAO_VALUE
; PURPOSE:
;	Returns the value of a DAOPHOT point-spread function at a set of points.
; EXPLANATION:
;	The value of the point-spread function is the sum of a
;	two-dimensional integral under a bivariate Gaussian function, and 
;	a value obtained by interpolation in a look-up table.  DAO_VALUE will
;	optionally compute the derivatives wrt X and Y
;
; CALLING SEQUENCE:
;	Result = DAO_VALUE( xx, yy, gauss, psf, [ dvdx, dvdy ] )
;
; INPUTS:
;	XX,YY   - the real coordinates of the desired point relative 
;		to the centroid of the point-spread function.
;	GAUSS  -  5 element vector describing the bivariate Gaussian
;	GAUSS(0)- the peak height of the best-fitting Gaussian profile.
;	GAUSS(1,2) - x and y offsets from the centroid of the point-spread 
;		function to the center of the best-fitting Gaussian.
;	GAUSS(3,4) - the x and y sigmas of the best-fitting Gaussian.
;	PSF  -  a NPSF by NPSF array containing the look-up table.
;
; OUTPUTS:
;    RESULT - the computed value of the point-spread function at
;             a position XX, YY relative to its centroid (which 
;             coincides with the center of the central pixel of the
;             look-up table).
;
; OPTIONAL OUTPUTS:
;       DVDX,DVDY - the first derivatives of the composite point-spread
;             function with respect to x and y.
;
; NOTES
; 	although the arguments XX,YY of the function DAO_VALUE
;	are relative to the centroid of the PSF, the function RINTER which
;	DAO_VALUE calls requires coordinates relative to the corner of the 
;	array (see code).
;
; PROCEDURES CALLED:
;	DAOERF, RINTER()
; REVISON HISTORY:
;	Adapted to IDL by B. Pfarr, STX, 11/17/87 from 1986 STSDAS version
;	of DAOPHOT
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	DATE
; PURPOSE:
;	Convert day-of-year to a DD-MMM-YYYY string
;
; CALLING SEQUENCE:
;	D_String = DATE(Year, day )
;
; INPUTS:
;	Year - Integer scalar specifying the year.   If the year contains only
;		two digits, then it is assumed to indicate the number of 
;		years after 1900. 
;
;	Day - Integer scalar giving number of days after Jan 0 of the 
;		specified year.    Can be larger than 366     
;
; OUTPUTS:
;	D_String - String giving date in format '13-MAR-1986'
;
; RESTRICTIONS:
;	Will not work for years before 100 AD 
; EXAMPLE:
;	IDL> print, date(1997,279)
;		'6-Oct-1997'
;
; MODIFICATION HISTORY:
;       D.M. fecit  24 October,1983
;	Work for years outside of the 19th century  W. Landsman  September 1997
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;     DATE_CONV
; PURPOSE:
;     Procedure to perform conversion of dates to one of three possible formats.
;
; EXPLANATION:
;     The following date formats are allowed
;
;       format 1: real*8 scalar encoded as:
;               year*1000 + day + hour/24. + min/24./60 + sec/24./60/60
;               where day is the day of year (1 to 366)
;       format 2: Vector encoded as:
;               date[0] = year (eg. 1987)
;               date[1] = day of year (1 to 366)
;               date[2] = hour
;               date[3] = minute
;               date[4] = second
;       format 3: string (ascii text) encoded as
;               DD-MON-YEAR HH:MM:SS.SS
;               (eg.  14-JUL-1987 15:25:44.23)
;            OR
;               YYYY-MM-DD HH:MM:SS.SS  (ISO standard)
;               (eg.  1987-07-14 15:25:44.23 or 1987-07-14T15:25:44.23)
;	            
;       format 4: three element vector giving spacecraft time words
;       from a Hubble Space Telescope (HST) telemetry packet.
;
; CALLING SEQUENCE
;       results = DATE_CONV( DATE, TYPE )
;
; INPUTS:
;       DATE - input date in one of the three possible formats.
;       TYPE - type of output format desired.  If not supplied then
;               format 3 (real*8 scalar) is used.
;                       valid values:
;                       'REAL'  - format 1
;                       'VECTOR' - format 2
;                       'STRING' - format 3
;			'FITS' - YYYY-MM-DDTHH:MM:SS.SS'
;               TYPE can be abbreviated to the single character strings 'R',
;               'V', 'S' and 'F'.
;               Nobody wants to convert TO spacecraft time (I hope!)
; OUTPUTS:
;       The converted date is returned as the function value.
;
; NOTES:
;      Prior to Oct 1998, the returned real*8 date (format 1) was given as
;      (year-1900)*1000 + day + hour/24. + min/24./60 + sec/24./60/60 
;      This output is ambiguous with respect to the year 2000.   Note that the
;      current version of DATE_CONV() may not be backwards compatible with 
;      versions prior to Oct 1998.
;
; HISTORY:
;      version 1  D. Lindler  July, 1987
;      adapted for IDL version 2  J. Isensee  May, 1990
;      Made year 2000 compliant; allow ISO format input  jls/acc Oct 1998
;      DJL/ACC Jan 1998, Modified to work with dates such as 6-JAN-1996 where
;		day of month has only one digit.
;      DJL, Nov. 2000, Added input/output format YYYY-MM-DDTHH:MM:SS.SS

; NAME:
;       DAYCNV
; PURPOSE:
;       Converts Julian dates to Gregorian calendar dates
;
; CALLING SEQUENCE:
;       DAYCNV, XJD, YR, MN, DAY, HR
;
; INPUTS:
;       XJD = Julian date, positive double precision scalar or vector
;
; OUTPUTS:
;       YR = Year (Integer)
;       MN = Month (Integer)
;       DAY = Day (Integer)
;       HR = Hours and fractional hours (Real).   If XJD is a vector,
;               then YR,MN,DAY and HR will be vectors of the same length.
;
; EXAMPLE:
;       IDL> DAYCNV, 2440000.D, yr, mn, day, hr    
;
;       yields yr = 1968, mn =5, day = 23, hr =12.   
;
; WARNING:
;       Be sure that the Julian date is specified as double precision to
;       maintain accuracy at the fractional hour level.
;
; METHOD:
;       Uses the algorithm of Fliegel and Van Falndern (1968) as reported in
;       the "Explanatory Supplement to the Astronomical Almanac" (1992), p. 604
;       Works for all Gregorian calendar dates with XJD > 0, i.e., dates after
;       -4713 November 23.
; REVISION HISTORY:
;       Converted to IDL from Yeoman's Comet Ephemeris Generator, 
;       B. Pfarr, STX, 6/16/88
;       Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	DBBUILD
; PURPOSE:
;	Build a database by appending new values for every item.  
; EXPLANATION:
;	The database must be opened for update (with DBOPEN) before calling 
;	DBBUILD.
;
; CALLING SEQUENCE:
;	DBBUILD, [ v1, v2, v3, v4......v30, /NOINDEX, /SILENT, STATUS =  ]
;
; INPUTS:
;	v1,v2....v30 - vectors containing values for all items in the database.
;         V1 contains values for the first item, V2 for the second, etc.
;         The number of vectors supplied must equal the number of items
;         (excluding entry number) in the database.  The number of elements 
;         in each vector should be the same.   A multiple valued item
;         should be dimensioned NVALUE by NENTRY, where NVALUE is the number
;         of values, and NENTRY is the number of entries.
;
; OPTIONAL INPUT KEYWORDS:
;	NOINDEX - If this keyword is supplied and non-zero then DBBUILD will
;             *not* create an indexed file.    Useful to save time if
;             DBBUILD is to be called several times and the indexed file need
;             only be created on the last call
;
;	SILENT  - If the keyword SILENT is set and non-zero, then DBBUILD
;	      will not print a message when the index files are generated
;
; OPTIONAL OUTPUT KEYWORD:
;	STATUS - Returns a status code denoting whether the operation was
;	      successful (1) or unsuccessful (0).  Useful when DBBUILD is
;	      called from within other applications.
;
; EXAMPLE:
;	Suppose a database named STARS contains the four items NAME,RA,DEC, and 
;	FLUX.   Assume that one already has the four vectors containing the
;	values, and that the database definition (.DBD) file already exists.
;
;	IDL> !PRIV=2                  ;Writing to database requires !PRIV=2
;	IDL> dbcreate,'stars',1,1   ;Create database (.DBF) & index (.DBX) file
;	IDL> dbopen,'stars',1         ;Open database for update
;	IDL> dbbuild,name,ra,dec,flux ;Write 4 vectors into the database
;
; NOTES:
;	Do not call DBCREATE before DBBUILD if you want to append entries to
;	an existing database
;
;	DBBUILD checks that each value vector matches the idl type given in the
;	database definition (.DBD) file, and that character strings are the 
;	proper length. 
; REVISION HISTORY:
;	Written          W. Landsman           March, 1989
;	Added /NOINDEX keyword           W. Landsman        November, 1992
;	User no longer need supply all items   W. Landsman  December, 1992 
;	Added STATUS keyword, William Thompson, GSFC, 1 April 1994
;	Added /SILENT keyword, William Thompson, GSFC, October 1995
;	Allow up to 30 items, fix problem if first item was multiple value
;				  W. Landsman    GSFC, July 1996
;	Faster build of external databases on big endian machines 
;				  W. Landsman    GSFC, November 1997  
;	Converted to IDL V5.0   W. Landsman 24-Nov-1997
;       Use SIZE(/TNAME) for error mesage display  W.Landsman   July 2001
;       Fix message display error introduced July 2001  W. Landsman   Oct. 2001 

; NAME:
;      DBCIRCLE
; PURPOSE:
;      Find sources in a database within specified radius of specified center
; EXPLANATION:
;      Database must include items named 'RA' (in hours) and 'DEC' (in degrees)
;      and must have previously been opened with DBOPEN
;
; CALLING SEQUENCE:
;     list = DBCIRCLE( ra_cen, dec_cen, [radius, dis, sublist, /SILENT, 
;                                          TO_B1950, /TO_J2000 ] )   
;
; INPUTS:
;       RA_CEN - Right ascension of the search center in decimal HOURS, scalar
;       DEC_CEN - Declination of the search center in decimal DEGREES, scalar
;               RA_CEN and DEC_CEN should be in the same equinox as the 
;               currently opened catalog.
;
; OPTIONAL INPUT:
;       RADIUS - Radius of the search field in arc minutes, scalar.
;               DBCIRCLE prompts for RADIUS if not supplied.
;       SUBLIST - Vector giving entry numbers in currently opened database
;               to be searched.  Default is to search all entries
;
; OUTPUTS:
;     LIST - Vector giving entry numbers in the currently opened catalog
;            which have positions within the specified search circle
;            LIST is set to -1 if no sources fall within the search circle
;            !ERR is set to the number sources found.
;
; OPTIONAL OUTPUT
;       DIS -  The distance in arcminutes of each entry specified by LIST
;               to the search center (given by RA_CEN and DEC_CEN)
;
; OPTIONAL KEYWORD INPUT:
;       /SILENT - If this keyword is set, then DBCIRCLE will not print the 
;               number of entries found at the terminal
;       /TO_J2000 - If this keyword is set, then the entered coordinates are
;               assumed to be in equinox B1950, and will be converted to
;               J2000 before searching the database
;       /TO_B1950 - If this keyword is set, then the entered coordinates are
;               assumed to be in equinox J2000, and will be converted to
;               B1950 before searching the database
;               NOTE: The user must determine on his own whether the database
;               is in B1950 or J2000 coordinates.
;
; METHOD:
;       A DBFIND search is first performed on a square area of given radius.
;       The list is the restricted to a circular area by using GCIRC to 
;       compute the distance of each object to the field center.
;
; EXAMPLE:
;       Find all Hipparcos stars within 40' of the nucleus of M33
;       (at J2000 1h 33m 50.9s 30d 39' 36.7'')
;
;       IDL> dbopen,'hipparcos'
;       IDL> list = dbcircle( ten(1,33,50.9), ten(3,39,36.7), 40)
;
; PROCEDURE CALLS:
;       BPRECESS, DBFIND(), DBEXT, DB_INFO(), GCIRC, JPRECESS
; REVISION HISTORY:
;      Written W. Landsman     STX           January 1990
;      Fixed search when crossing 0h         July 1990
;      Spiffed up code a bit     October, 1991
;      Converted to IDL V5.0   W. Landsman   September 1997
;      Leave DIS vector unchanged if no entries found W. Landsman July 1999
;      Use maximum declination, rather than declination at field center to
;      correct RA for latitude effect    W. Landsman   September 1999

; NAME:
;       DBCLOSE
; PURPOSE:
;       procedure to close a data base file
;
; CALLING SEQUENCE:  
;       dbclose
;
; INPUTS:
;       None
;
; OUTPUTS
;       None
;
; SIDE EFFECTS:
;       the data base files currently opened are closed
;
; PROCEDURE CALLS:
;       DB_INFO(), HOST_TO_IEEE
; HISTORY:
;       version 2  D. Lindler  Oct. 1987
;       For IDL version 2      August 1990
;       William Thompson, GSFC/CDS (ARC), 30 May 1994
;                Added support for external (IEEE) data format
;       Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;     DBCOMPARE
; PURPOSE:
;     Display two entries in an IDL database side by side in a column format
;
; CALLING SEQUENCE:     
;     dbcompare, list1, list2, [items, TEXTOUT= , /DIFF]  
;
; INPUTS:
;     list1 - Integer scalar giving first entry number to be compared.
;     list2 - Integer scalar giving second entry number to be compared.
;
; OPTIONAL INPUT-OUTPUT:
;     items - items to be compared, if not supplied then all items will be
;          compared.    The items can be specified in any of the following ways:
;
;             form 1  scalar string giving item(s) as list of names
;                     separated by commas
;             form 2  string array giving list of item names
;             form 3  string of form '$filename' giving name
;                     of text file containing items (one item per line)                      line)
;             form 4  integer scalar giving single item number or
;                     integer vector list of item numbers
;             form 5  Null string specifying interactive selection.   This
;                     is the default if 'items' is not supplied
;             form 6  '*'     select all items (= default)
;
;            If items was undefined or a null string on input, then
;            on output it will contain the items interactively selected.
;
; OPTIONAL INPUT KEYWORDS:
;     /DIFF - If this keyword is set and non-zero, then only the items 
;             in the database that differ will be printed
;
;     TEXTOUT -  Scalar Integer (1-7) Used to determine output device.   See
;               TEXTOPEN for more info.
;
; SYSTEM VARIABLES:
;     Output device controlled by non-standard system variable !TEXTOUT, if 
;     TEXTOUT keyword is not used.    
;
; EXAMPLE:
;     Display entries 3624 and 3625 in column form showing only the items
;     that differ.
;               IDL> dbcompare,3624,3625,/diff
;
; PROCEDURES USED:
;     DB_INFO(), DB_ITEM, DB_ITEM_INFO(), DBRD, DBXVAL()
;     TEXTOPEN, TEXTCLOSE
; HISTORY:
;     Written,  W. Landsman            July 1996
;     Converted to IDL V5.0   W. Landsman   September 1997
;     Fix documentation, add Syntax display    W. Landsman   November 1998   
;     Replace DATATYPE() with size(/TNAME)   W. Landsman    November 2001

; NAME:
;       DBCOMPRESS
; PURPOSE:
;       Compress a .dbf database file after a call to DBDELETE
; EXPLANATION:
;       The procedure DBDELETE will remove specified entries from a database
;       but it will not free the unused space.     DBCOMPRESS will compress
;       the .dbf file so that it only contains valid entries.   
; CALLING SEQUENCE:
;       DBCOMPRESS, dbname
; INPUT PARAMETERS: 
;       dbname - Name of the database to be compressed, scalar string
; NOTES:
;       (1) Will not compress the index (.dbx) file.   The size of the .dbx file
;       is controlled by the MaxEntries value in the database definition 
;       (.dbd) file
;       (2) The updated .dbf file is written in the current directory.
;       This may need to be moved into the ZDBASE directory.
; PROCEDURE CALLS:
;       DBOPEN, DB_INFO(), FIND_WITH_DEF()
; REVISION HISTORY:
;       Written, W. Landsman      Raytheon STX        May 1998 
;       Converted to IDL V5.0 June 1998

; NAME: 
;       DBCREATE
; PURPOSE:      
;       Create a new data base (.dbf), index (.dbx) or description (.dbh) file
; EXPLANATION:
;       A database definition (.dbd) file must already exist.
;       The default directory must be a ZDBASE: directory.
;
; CALLING SEQUENCE:     
;       dbcreate, name,[ newindex, newdb, maxitems]  [,/EXTERNAL]  
;
; INPUTS:       
;       name- name of the data base (with no qualifier), scalar string. 
;               The description will be read from the file "NAME".dbd 
;
; OPTIONAL INPUTS:      
;       newindex - if non-zero then a new index file is created,
;               otherwise it is assumed that changes do not affect the
;               index file. (default=0)
;       newdb - if non-zero then a new data base file (.dbf) will
;               be created. Otherwise changes are assumed not to affect
;               the file's present format.
;       maxitems - maximum number of items in data base.
;               If not supplied then the number of items is
;               limited to 200.
;
; OUTPUTS:
;       NONE.
;
; OPTIONAL INPUT KEYWORD:       
;
;       external - If set, then the database is written with an external data
;               representation.  This allows the database files to be used on
;               any computer platform, e.g. through NFS mounts, but some
;               overhead is added to reading the files.  The default is to
;               write the data in the native format of the computer being used.
;
;               This keyword is only paid attention to if NEWDB or NEWINDEX
;               are nonzero.  Otherwise, the database is opened to find
;               out if it uses external representation or not.
;
;               Extreme caution should be used if this keyword is used with
;               only NEWINDEX set to a nonzero value.  This mode is allowed so
;               that databases written on machines which already use the
;               external data representation format, e.g. Sun workstations, to
;               be marked external so that other machines can read them.
;
; PROCEDURE CALLS:      
;       GETTOK(), FIND_WITH_DEF(), HOST_TO_IEEE, ZPARCHECK
;
; RESTRICTIONS: 
;       If newdb=0 is not specified, the changes to the .dbd file can
;       not alter the length of the records in the data base file.
;       and may not alter positions of current fields in the file.
;       permissible changes are:
;               1) utilization of spares to create a item or field
;               2) change in field name(s)
;               3) respecification of index items
;               4) changes in default print formats
;               5) change in data base title
;               6) changes in pointer specification to other data
;                       data bases
;
;       !priv must be 2 or greater to execute this routine.
;
; SIDE EFFECTS:  
;       data base description file ZDBASE:name.dbh is created
;       and optionally ZDBASE:name.dbf (data file) and
;       ZDBASE.dbx (index file) if it is a new data base.
;
; REVISION HISTORY:     
;       D. Lindler, GSFC/HRS, October 1987
;       Modified:  Version 1, William Thompson, GSFC, 29 March 1994
;                  Version 2, William Thompson, GSFC/CDS (ARC), 28 May 1994
;                  Added EXTERNAL keyword.
;       Version 4, William Thompson, GSFC, 3 November 1994
;                       Modified to allow ZDBASE to be a path string.
;       8/14/95  JKF/ACC - allow EXTERNAL data for newindex OR newdb modes.
;       Make sure all databases closed before starting W. Landsman June 1997
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Added new unsigned and 64 bit integer datatypes W. Landsman July 2001

; NAME:
;	DBDELETE
; PURPOSE:
;	Deletes specified entries from data base
;
; CALLING SEQUENCE:
;	DBDELETE, list, [ name, /DEBUG ]   
;
; INPUTS:
;	list - list of entries to be deleted, scalar or vector
;	name - optional name of data base, scalar string.  If not specified
;		then the data base file must be previously opened for update 
;               by DBOPEN.
;
; OPERATIONAL NOTES:
;	!PRIV must be at least 3 to execute.
;
; SIDE EFFECTS:
;	The data base file (ZDBASE:name.DBF) is modified by removing the
;	specified entries and reordering the remaining entry numbers
;       accordingly (ie. if you delete entry 100, it will be replaced
;       by entry 101 and the database will contain 1 less entry.
;
; EXAMPLE:
;        Delete entries in a database STARS where RA=DEC = 0.0
;
;        IDL> !PRIV= 3                           ;Set privileges
;        IDL> dbopen,'STARS',1                   ;Open for update
;        IDL> list = dbfind('ra=0.0,dec=0.0')    ;Obtain LIST vector
;        IDL> dbdelete, list             ;Delete specified entries from db
;
; NOTES:
;       The procedure is rather slow because the entire database is re-
;       created with the specified entries deleted.
; OPTIONAL KEYWORD INPUT:
;        DEBUG - if this keyword is set and non-zero, then additional 
;		diagnostics will be printed as each entry is deleted.
; COMMON BLOCKS:
;	DBCOM
; PROCEDURE CALLS:
;	DBINDEX, DB_INFO(), DBOPEN, DBPUT, ZPARCHECK
; HISTORY
;	Version 2  D. Lindler  July, 1989
;       Updated documentation   W. Landsman    December 1992
;	William Thompson, GSFC, 28 February 1995
;			Fixed bug when external representation used.
;	Fixed for case where second parameter supplied W. Landsman April 1996
;	Use keyword DEBUG rather than !DEBUG   W. Landsman    May 1997
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;      DBEDIT
;
; PURPOSE:
;       Interactively edit specified fields in a database. 
; EXPLANATION:
;       The value of each field is displayed, and the user has the option
;       of changing or keeping the value.  Widgets will be used if they
;       are available.
;
; CALLING SEQUENCE:
;       dbedit, list, [ items ]
;
; INPUTS:
;       list - scalar or vector of database entry numbers.  Set list = 0 to 
;       interactively add a new entry to a database.  Set list = -1 to edit 
;       all entries.
;
; OPTIONAL INPUTS:
;       items - list of items to be edited.  If omitted, all fields can be 
;               edited.      
;
; COMMON BLOCKS:
;       DB_COM -- contains information about the opened database.
;       DBW_C -- contains information intrinsic to this program.
;
; SIDE EFFECTS:
;       Will update the database files.
;
; RESTRICTIIONS:
;       Database must be opened for update prior to running
;       this program.  User must be running DBEDIT from an 
;       account that has write privileges to the databases.  
;
;       If one is editing an indexed item, then after all edits are complete,
;       DBINDEX will be called to reindex the entire item.    This may
;       be time consuming.
;
;       Cannot be used to edit items with multiple values
;
; EXAMPLE:
;       Suppose one had new parallaxes for all stars fainter than 5th magnitude
;       in the Yale Bright Star Catalog and wanted to update the PRLAX and
;       PRLAX_CODE fields with these new numbers
;
;       IDL> !priv=2                    
;       IDL> dbopen, 'yale_bs', 1            ;Open catalog for update
;       IDL> list = dbfind( 'v>5')     ;Find fainter than 5th magnitude
;       IDL> dbedit, list, 'prlax, prlax_code'   ;Manual entry of new values
;
; PROCEDURE:
;       (1) Use the cursor and point to the value you want to edit.   
;       (2) Type the new field value over the old field value.
;       (3) When you are done changing all of the field values for each entry
;       save the entry to the databases by pressing 'SAVE ENTRY TO DATABASES'.
;       Here all of the values will be checked to see if they are the correct
;       data type.  If a field value is not of the correct data type, it will
;       not be saved.  
;
;       Use the buttons "PREV ENTRY" and "NEXT ENTRY" to move between entry 
;       numbers.  You must save each entry before going on to another entry in 
;       order for your changes to be saved.
;
;       Pressing "RESET THIS ENTRY" will remove any unsaved changes to the 
;       current entry.
;
;REVISION HISTORY:
;       Adapted from Landsman's DBEDIT
;       added widgets,  Melissa Marsh, HSTX, August 1993
;       do not need to press return after entering each entry,
;                       fixed layout problem on SUN,
;                       Melissa Marsh, HSTX, January 1994
;       Only updates the fields which are changed. Joel Offenberg, HSTX, Mar 94
;       Corrected test for changed fields  Wayne Landsman  HSTX, Mar 94
;       Removed a couple of redundant statements W. Landsman HSTX Jan 96
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Replace DATAYPE() with size(/TNAME)   W. Landsman   November 2001
;       Work for entry numbers > 32767     W. Landsman   December 2001

; NAME:
;       DBEDIT_BASIC
; PURPOSE:
;       Subroutine of DBEDIT_BASIC to edit a database on a dumb terminal.
; EXPLANATION:
;       Interactively edit specified fields in a database.  The
;       value of each field is displayed, and the user has the option
;       of changing or keeping the value.
;
; CALLING SEQUENCE:
;       dbedit_basic, list, [ items ]
;
; INPUTS:
;       list - scalar or vector of database entry numbers.  Set LIST=0
;               to interactively add a new entry to a database.
;
; OPTIONAL INPUTS
;       items - list of items to be edited.  If not supplied, then the
;               value of every field will be displayed.
;
; NOTES:
;       (1) Database must be opened for update (dbopen,,1) before
;       calling DBEDIT_BASIC.  User must have write privileges on the database
;       files.
;       (2) User gets a second chance to look at edited values, before
;       they are actually written to the database
;
; PROMPTS:
;       The item values for each entry to be edited are first displayed
;       User is the asked "EDIT VALUES IN THIS ENTRY (Y(es), N(o), or Q(uit))?
;       If user answers 'Y' or hits RETURN, then each item is displayed
;       with its current value, which the user can update.  If user answered
;       'N' then DBEDIT_BASIC skips to the next  entry.   If user answers 'Q'
;       then DBEDIT will exit, saving all previous changes.
;
; EXAMPLE:
;       Suppose V magnitudes (V_MAG) in a database STARS with unknown values 
;       were assigned a value of 99.9.  Once the true values become known, the
;       database can be edited
;
;       IDL> !PRIV=2 & dbopen,'STARS',1         ;Open database for update
;       IDL> list =  dbfind('V_MAG=99.9')       ;Get list of bad V_MAG values
;       IDL> dbedit,list,'V_MAG'       ;Interactively insert good V_MAG values
;
; REVISION HISTORY:
;       Written  W. Landsman     STX        April, 1989
;       Rename DBEDIT_BASIC from DBEDIT            July, 1993
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Change DATATYPE() to size(/TNAME)  W. Landsman   November 2001

; NAME:
;       DBEXT
; PURPOSE:
;       Extract values of up to 12 items from an IDL database 
; EXPLANATION:
;       Procedure to extract values of up to 12 items from
;       data base file, and place into IDL variables
;
; CALLING SEQUENCE:
;       dbext,list,items,v1,[v2,v3,v4,v5,v6,v7,v8,v9,v10,v11,v12]
;
; INPUTS:
;       list - list of entry numbers to be printed, vector or scalar
;               If list = -1, then all entries will be extracted.
;               list may be converted to a vector by DBEXT 
;       items - standard item list specification.  See DBPRINT for 
;               the 6 different ways that items may be specified. 
;
; OUTPUTS:
;       v1...v12 - the vectors of values for up to 12 items.
;
; EXAMPLE:
;       Extract all RA and DEC values from the currently opened database, and
;       place into the IDL vectors, IDLRA and IDLDEC.
;
;               IDL> DBEXT,-1,'RA,DEC',idlra,idldec
;
; HISTORY
;       version 2  D. Lindler  NOV. 1987
;       check for INDEXED items   W. Landsman   Feb. 1989
;       Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;       DBEXT_DBF
; PURPOSE:
;       Subroutine of DBEXT to extract values of up to 18 items from a database 
; EXPLANATION:
;       This is a subroutine of DBEXT, which is the routine a user should 
;       normally use.
;
; CALLING SEQUENCE:
;       dbext_dbf,list,dbno,sbyte,nbytes,idltype,nval,v1,[ v2,v3,v4,v5,v6,v7,
;                  v8,v9,v10,v11,v12,v13,v14,v15,v16,v17,v18 ITEM_DBNO = ]
;
; INPUTS:
;       list - list of entry numbers to extract desired items.   It is the 
;               entry numbers in the primary data base unless dbno is greater 
;               than or equal to -1.  In that case it is the entry number in 
;               the specified data base.
;       dbno - number of the opened db file
;               if set to -1 then all data bases are included
;       sbyte - starting byte in the entry.  If single data base then it must 
;               be the starting byte for that data base only and not the 
;               concatenation of db records 
;       nbytes - number of bytes in the entry
;       idltype - idl data type of each item to be extracted
;       nval - number of values per entry of each item to be extracted
;
; OUTPUTS:
;       v1...v18 - the vectors of values for up to 18 items
;
; OPTIONAL INPUT KEYWORD:
;       item_dbno - A vector of the individual database numbers for each item.
;               Simplifies the code for linked databases
; PROCEDURE CALLS:
;       DB_INFO(), DB_ITEM_INFO(), DBRD, DBXVAL(), IS_IEEE_BIG(), IEEE_TO_HOST
; HISTORY
;       version 1  D. Lindler  Nov. 1987
;       Extract multiple valued entries    W. Landsman   May 1989
;       William Thompson, GSFC/CDS (ARC), 1 June 1994
;               Added support for external (IEEE) representation.
;       Work with multiple element string items  W. Landsman  August 1995
;       Increase speed for external databases on IEEE machines WBL August 1996
;       IEEE conversion implemented on blocks of entries using BIG
;       Added keyword ITEM_DBNO     R. Schwartz, GSFC/SDAC, August 1996
;       Return a vector even if only 1 value W. Thompson  October 1996
;       Change variable name of BYTESWAP to BSWAP  W. Thompson Mar 1997
;       Use /OVERWRITE with reform   W. Landsman   May 1997
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Increase maximum number of items to 18  W. Landsman  November 1999
;       2 May 2003, W. Thompson, Use DBXVAL with BSWAP instead of IEEE_TO_HOST.

; NAME:
;       DBEXT_IND
; PURPOSE:
;       routine to read a indexed item values from index file
;
; CALLING SEQUENCE:  
;       dbext_ind,list,item,dbno,values
;
; INPUTS:
;       list - list of entry numbers to extract values for
;               (if it is a scalar, values for all entries are extracted)
;       item - item to extract
;       dbno - number of the opened data base
;
; OUTPUT:
;       values - vector of values returned as function value
; HISTORY:
;       version 1  D. Lindler  Feb 88
;       Faster processing of string values    W. Landsman   April, 1992
;       William Thompson, GSFC/CDS (ARC), 30 May 1994
;               Added support for external (IEEE) data format
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Allow multiple valued (nonstring) index items W. Landsman  November 2000      
;       Use 64bit integer index for large databases W. Landsman  February 2001
;       Fix sublisting of multiple valued index items W. Landsamn  March 2001

; NAME: 
;    DBFIND()
; PURPOSE:      
;     Search data base for entries with specified characteristics
; EXPLANATION:  
;     Function to search data base for entries with specified
;     search characteristics.
;
; CALLING SEQUENCE:     
;     result = dbfind(spar,[ listin, /SILENT, /FULLSTRING, ERRMSG=, Count = ])
;
; INPUTS:       
;     spar - search_parameters (string)...each search parameter 
;               is of the form:
;
;               option 1) min_val < item_name < max_val
;               option 2) item_name = value
;               option 3) item_name = [value_1, value_10]
;                       Note: option 3 is also the slowest.
;               option 4) item_name > value
;               option 5) item_name < value
;               option 6) item_name = value(tolerance) ;eg. temp=25.0(5.2)
;               option 7) item_name                     ;must be non-zero
;
;               Multiple search parameters are separated by a comma.
;               eg.     'cam_no=2,14 is interpreted as greater than or equal.
;       
;               RA and DEC keyfields are stored as floating point numbers 
;               in the data base may be entered as HH:MM:SEC and
;               DEG:MIN:SEC. Where:
;
;                       HH:MM:SEC   equals  HH + MM/60.0  + SEC/3600.
;                       DEG:MIN:SEC equals DEG + MIN/60.0 + SEC/3600.
;                       
;               For example:
;                       40:34:10.5 < dec < 43:25:19 , 8:22:1.0 < ra < 8:23:23.0
;
;               Specially encoded date/time in the data base may
;               be entered by  CCYY/DAY:hr:min:sec which is
;               interpreted as  
;                       CCYY*1000+DAY+hr/24.0+min/24.0/60.+sec/24.0/3600.
;               If a two digit year is supplied and YY GE 40 then it is 
;               understood to refer to year 1900 +YY;  if YY LT 40 then it is 
;               understood to refer to year 2000 +YY

;               For example
;                       1985/201:10:35:30
; NAME:
;       DBFIND_ENTRY
; PURPOSE:
;       Subroutine of DBFIND to perform an entry number search 
; EXPLANATION:
;       This is a subroutine of dbfind and is not a standalone procedure
;       It performs a entry number search.
;
; CALLING SEQUENCE:
;       dbfind_entry, type, svals, nentries, values, [COUNT = ]
;
; INPUTS: 
;       type - type of search (output from dbfparse)
;       svals - search values (output from dbfparse)
;       values - array of values to search
; OUTPUT:
;       good - indices of good values
; OPTIONAL OUTPUT KEYWORD:
;       Count - integer scalar giving the number of valid matches
; SIDE EFFECTS"
;       The obsolete system variable !err is set to number of good values
;
; REVISION HISTORY:
;       D. Lindler  July,1987
;       Fixed test for final entry number  W. Landsman    Sept. 95       
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Added COUNT keyword, deprecate !ERR  W. Landsman   March 2000
;       Better checking of out of range values  W. Landsman February 2002

; NAME:
;       DBFIND_SORT   
; PURPOSE:
;       Subroutine of DBFIND to perform a search using sorted values 
; EXPLANATION:
;       This is a subroutine of dbfind and is not a standalone procedure
;       It is used to limit the search using sorted values  V5.2 or later!
;
; CALLING SEQUENCE:
;       dbfind_sort, it, type, svals, list, [/FULLSTRING, COUNT = ]
;
; INPUT: 
;       it - item number, scalar
;       type - type of search (output from dbfparse)
;       svals - search values (output from dbfparse)
;
; INPUT/OUTPUT:
;       list - found entries
;
; OPTIONAL INPUT KEYWORD:
;       /FULLSTRING - By default, one has a match if a search string is 
;               included in any part of a database value (substring match).   
;               But if /FULLSTRING is set, then all characters in the database
;               value must match the search string (excluding leading and 
;               trailing blanks).    Both types of string searches are case
;               insensitive.
; OPTIONAL OUTPUT KEYWORD
;       Count - Integer scalar giving the number of matches found
; SYSTEM VARIABLES:
;       The obsolete system variable !err is set to number of good values
;       !ERR = -2 for an invalid search
; REVISION HISTORY:
;       D. Lindler  July,1987
;       William Thompson, GSFC/CDS (ARC), 30 May 1994
;               Added support for external (IEEE) data format
;       William Thompson, GSFC, 14 March 1995 Added keyword FULLSTRING
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Minimize use of obsolete !ERR variable   W. Landsman  February 2000
;       Added COUNT keyword, deprecate !ERR W. Landsman  March 2000
;       Use 64 bit integers V5.2 or later
;       Include new IDL unsigned & 64 bit integer datatypes W.Landsman July 2001
;       Make sure returned list vector is LONG  W. Landsman August 2001

; NAME:
;     DBFPARSE
; PURPOSE:
;     Parse the search string supplied to DBFIND.   Not a standalone routine
;
; CALLING SEQUENCE:
;     DBFPARSE, [ spar, items, stype, values ]
;
; INPUTS:
;     spar - search parameter specification, scalar string
;
; OUTPUTS:
;     items - list of items to search on
;     stype - search type, numeric scalar
;               0    item=values(j,0)
;               -1   item>values(j,0)
;               -2   item
; NAME:
;       DBGET
; PURPOSE:
;       Find entry numbers which contain specified values of a given item.
; EXPLANATION:
;       DBGET() is useful as an alternative to DBFIND() when the desired 
;       search values are not easily expressed as a string.  
;
; CALLING SEQUENCE:
;       list = dbget( item, values, [ listin ], /SILENT, /FULLSTRING )
;
; INPUTS:
;       item - Item name or number
;       values -  scalar or vector containing item values to search for.
;
; OPTIONAL INPUTS:
;       listin - list of entries to be searched.  If not supplied, or
;               set to -1, then all entries are searched
;
; OUTPUT:
;       list - vector giving the entry number of entries containing desired
;               item values.  The number of elements in  LIST may be different 
;               from that of VALUE, since a value might be located zero, once, 
;               or many times in the database.  Use the function DBMATCH if a 
;               one to one correspondence is desired between VALUES and LIST. 
; OPTIONAL INPUT KEYWORDS:
;       /SILENT - If this keyword is set, then DBGET will not display
;               the number of entries found
;       /FULLSTRING - By default, one has a match if a search string is 
;               included in any part of a database value (substring match).   
;               But if /FULLSTRING is set, then all characters in the database
;               value must match the search string (excluding leading and 
;               trailing blanks).    Both types of string searches are case
;               insensitive.
; OPTIONAL OUTPUT KEYWORD:
;       COUNT - Integer scalar giving the number of valid matches
;
; RESTRICTIONS:
;       When linked databases are opened together, DBGET can only be used to
;       search on items in the primary database.
; EXAMPLE:
;       Get info on selected HD stars in Bright Star catalogue
;
;       IDL> dbopen, 'YALE_BS' 
;       IDL> hdno = [1141,2363,3574,4128,6192,6314,6668]    ;Desired HD numbers
;       IDL> list = dbget( 'HD', hdno )        ;Get corresponding entry numbers
;
; SYSTEM VARIABLES:
;       The obsolete system variable !ERR is set to number of entries found
; REVISION HISTORY:
;       Written,    W. Landsman      STX     February, 1989
;       William Thompson, GSFC, 14 March 1995 Added keyword FULLSTRING
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Added COUNT keyword, deprecate !ERR        W. Landsman March 2000
;       Fix bug introduced March 2000              W. Landsman November 2000

; NAME:
;     DBHELP
; PURPOSE:
;     List available databases or items in the currently open database
; EXPLANATION:
;     Procedure to either list available databases (if no database is 
;     currently open) or the items in the currently open database.
;
; CALLING SEQUENCE:  
;     dbhelp, [ flag , TEXTOUT=, /SORT ]
;
; INPUT:
;     flag - (optional) if set to nonzero then item or database
;             descriptions are also printed
;             default=0
;             If flag is a string, then it is interpreted as the
;             name of a data base (if no data base is opened) or a name 
;             of an item in the opened data base.   In this case, help
;             is displayed only for the particular item or database
;
; OUTPUTS:
;      None
; OPTIONAL INPUT KEYWORDS:
;      TEXTOUT  - Used to determine output device.  If not present, the
;                value of !TEXTOUT system variable is used (see TEXTOPEN )
;
;               textout=0       Nowhere
;               textout=1       if a TTY then TERMINAL using /more option
;                                   otherwise standard (Unit=-1) output
;               textout=2       if a TTY then TERMINAL without /more option
;                                   otherwise standard (Unit=-1) output
;               textout=3       .prt
;               textout=4       laser.tmp
;               textout=5      user must open file
;               textout=7      same as 3 but text is appended to .prt
;                               file if it already exists.
;               textout = filename (default extension of .prt)
;
;        /SORT - If set and non-zero, then the help items will be displayed
;               sorted alphabetically.    If more than one database is open,
;               then this keyword does nothing.
; METHOD:
;       If no data base is opened then a list of data bases are
;       printed, otherwise the items in the open data base are printed.
;
;       If a string is supplied for flag and a data base is opened
;       flag is assumed to be an item name.  The information for that
;       item is printed along with contents in a optional file
;       zdbase:dbname_itemname.hlp
;       if a string is supplied for flag and no data base is opened,
;       then string is assumed to be the name of a data base file.
;       only information for that file is printed along with an
;       optional file zdbase:dbname.hlp.
; PROCEDURES USED:
;       DB_INFO(),DB_ITEM_INFO(),FIND_WITH_DEF(), TEXTOPEN, TEXTCLOSE, UNIQ()
; IDL VERSION:
;       V5.3 or later (uses vectorized FDECOMP)
; HISTORY:
;       Version 2  D. Lindler  Nov 1987 (new db format)
;       Faster printing of title desc. W. Landsman  May 1989 
;       Keyword textout added, J. Isensee, July, 1990
;       Modified to work on Unix, D. Neill, ACC, Feb 1991.
;       William Thompson, GSFC/CDS (ARC), 1 June 1994
;               Added support for external (IEEE) representation.
;       William Thompson, GSFC, 3 November 1994
;               Modified to allow ZDBASE to be a path string.
;       Remove duplicate database names  Wayne Landsman    December 1994
;       8/17/95 jkf/acc - force lowercase filenames for .hlp files.
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Added /SORT keyword  J. Sandoval/W. Landsman     October 1998
;       V5.3 version use vectorized FDECOMP   W. Landsman   February 2001
;       Recognize 64 bit, unsigned integer datatypes W. Landsman September 2001
;       Fix display of number of bytes with /SORT W. Landsman February 2002
;       Assume since V5.2                 W. Landsman February 2002  

; NAME:
;       DBINDEX
; PURPOSE:
;       Procedure to create index file for data base (V5.2 or later)
;
; CALLING SEQUENCE:     
;       dbindex, [ items ]
;
; OPTIONAL INPUT:
;       items - names or numbers of items to be index -- if not supplied,
;               then all indexed fields will be processed.  
;
; OUTPUT:
;       Index file .dbx is created on disk location ZDBASE:
;
; OPERATIONAL NOTES:
;       (1) Data base must have been previously opened for update
;       by DBOPEN 
;
;       (2) Only 18 items can be indexed at one time.   If the database has
;       more than 18 items, then two separate calls to DBINDEX are needed.
; PROCEDURES CALLED:
;       DBINDEX_BLK, DB_INFO(), DB_ITEM, DB_ITEM_INFO(), IEEE_TO_HOST, 
;       IS_IEEE_BIG()
; HISTORY:
;       version 2  D. Lindler  Nov 1987 (new db format)
;       W. Landsman    added optional items parameter Feb 1989 
;       M. Greason     converted to IDL version 2.  June 1990.
;       William Thompson, GSFC/CDS (ARC), 30 May 1994
;               Added support for external (IEEE) data format
;       Test if machine is bigendian  W. Landsman     May, 1996
;       Change variable name of BYTESWAP to BSWAP  W. Thompson  Mar, 1997
;       Increased number of fields to 15   W. Landsman   June, 1997
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Increase number of items to 18     W. Landsman  November 1999
;       Allow multiple valued (nonstring) index items W. Landsman November 2000
;       Use 64 bit integers for V5.2 or later  W. Landsman February 2001

; NAME:
;       DBINDEX_BLK
; PURPOSE:
;       Subroutine of DBINDEX to create associated variable of correct datatype
; EXPLANATION:
;       DBINDEX_BLK will offset into the file by a specified amount in 
;       preparation for writing to the file.   V5.2 or later
;
; CALLING SEQUENCE:
;       res = dbindex_blk(unit, nb, bsz, ofb, dtype)
;
; INPUTS:
;       unit   The unit number assigned to the file.
;       nb     The number of blocks to offset into the file.
;       bsz    The size of each block, in bytes, to offset into the file.
;       ofb    The offset into the block, in bytes.
;       dtype  The IDL datatype as defined in the SIZE function
;
; OUTPUTS:
;       res    The returned variable.  This is an associated variable.
;
; RESTRICTIONS:
;       The file must have been previously opened.
;
; MODIFICATION HISTORY:
;       Written by Michael R. Greason, STX, 14 June 1990.
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Use 64 bit integer for very large databases  W. Landsman February 2001
;       Added new unsigned & 64bit integer datatypes    W. Landsman July 2001

; NAME:
;       DBMATCH
; PURPOSE:
;       Find the entry number in a database for each element of item values
; EXPLANATION:
;       DBMATCH() is especially useful for finding a one-to-one 
;       correspondence between entries in different databases, and thus to 
;       create the vector needed for database pointers.
;
; CALLING SEQUENCE:
;       list = DBMATCH( item, values, [ listin, /FULLSTRING ] )
;
; INPUTS:
;       ITEM - Item name or number, scalar
;       VALUES -  scalar or vector containing item values to search for.
;
; OPTIONAL INPUTS:
;       LISTIN - list of entries to be searched.  If not supplied, or
;               set to -1, then all entries are searched
; OUTPUT:
;       LIST - vector of entry numbers with the same number of elements as 
;               VALUES.  Contains a value of 0 wherever the corresponding item
;               value was not found.
;
; OPTIONAL INPUT:
;       /FULLSTRING - By default, one has a match if a search string is 
;               included in any part of a database value (substring match).   
;               But if /FULLSTRING is set, then all characters in the database
;               value must match the search string (excluding leading and 
;               trailing blanks).    Both types of string searches are case
;               insensitive.
;
; NOTES:
;       DBMATCH is meant to be used for items which do not have duplicate values
;       in a database (e.g. catalog numbers).  If more than one entry is found
;       for a particular item value, then only the first one is stored in LIST.
;
;       When linked databases are opened together, DBMATCH can only be 
;       used to search on items in the primary database.
;
; EXAMPLE:
;       Make a vector which points from entries in the Yale Bright Star catalog
;       to those in the Hipparcos catalog, using the HD number
;
;       IDL> dbopen, 'yale_bs'            ;Open the Yale Bright star catalog
;       IDL> dbext, -1, 'HD', hd          ;Get the HD numbers
;       IDL> dbopen, 'hipparcos'          ;Open the Hipparcos catalog
;       IDL> list = dbmatch( 'HD', HD)    ;Get entries in Hipparcos catalog 
;                                         ;corresponding to each HD number.
; PROCEDURE CALLS:
;       DB_ITEM, DB_ITEM_INFO(), DBEXT, DBFIND_SORT()
; REVISION HISTORY:
;       Written,    W. Landsman      STX     February, 1990
;       Fixed error when list in parameter used May, 1992
;       Faster algorithm with sorted item when listin parameter supplied 
;       Added keyword FULLSTRING,check for empty database, William Thompson, 
;               GSFC, 15 March 1995
;       Work for more than 32767 values, added CATCH W. Landsman   July 1997
;       Converted to IDL V5.0   W. Landsman 25-Nov-1997
;       Change some loop variables to type LONG,  W. Landsman  July 1999
;       Remove loop for substring searches (faster)  W. landsman August 1999
;       Replace DATATYPE() with size(/TNAME)  W. Landsman  November 2001
;       Fixed typo when search on sorted items W. Landsman February 2002

; NAME:
;	DBOPEN
; PURPOSE:
;	Routine to open an IDL database
;
; CALLING SEQUENCE:
;	dbopen, name, update
;
; INPUTS:
;	name - (Optional) name or names of the data base files to open.
;		It has one of the following forms:
;
;		'name'		-open single data base file
;		'name1,name2,...,nameN' - open N files which are
;				connected via pointers.
;		'name,*'	-Open the data base with all data
;				bases connected via pointers
;		''		-Interactively allow selection of
;				the data base files.
;
;		If not supplied then '' is assumed.
;		name may optionally be a string array with one name
;		per element.
;
;	update - (Optional) Integer flag specifing openning for update.
;		0 	- Open for read only
;		1	- Open for update
;		2	- Open index file for update only
;		!PRIV must be 2 or greater to open a file for update.
;		If a file is opened for update only a single data base
;		can be specified.
;
; OUTPUTS:
;	none
;
; KEYWORDS:
;	UNAVAIL - If present, a "database doesn't exit" flag is returned
;	          through it.  0 = the database exists and was opened (if
;	          no other errors arose).  1 = the database doesn't exist.
;	          Also if present, the error message for non-existent databases
;	          is suppressed.  The action, however, remains the same.  If
;	          specifiying this, be sure that the variable passed exists
;	          before the call to DBOPEN.
; SIDE EFFECTS:
;	The .DBF and .dbx files are opened using unit numbers obtained by
; 	GET_LUN.  Descriptions of the files are placed in the common block
; 	DB_COM.
;
; HISTORY:
;	Version 2, D. Lindler, Nov. 1987
;       For IDL Version 2  W. Landsman May 1990 -- Will require further 
;           modfication once SCREEN_SELECT is working
;	Modified to work under Unix, D. Neill, ACC, Feb 1991.
;	UNAVAIL keyword added.  M. Greason, Hughes STX, Feb 1993.
;	William Thompson, GSFC/CDS (ARC), 1 June 1994
;		Added support for external (IEEE) representation.
;	William Thompson, GSFC, 3 November 1994
;			Modified to allow ZDBASE to be a path string.
;	8/29/95	JKF/ACC	- forces lowercase for input database names.
;	W. Landsman, Use CATCH to catch errors    July, 1997
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;     DBPRINT
; PURPOSE:
;     Procedure to print specified items from a list of database entries
;
; CALLING SEQUENCE:     
;     dbprint, list, [items, FORMS= , TEXTOUT= , /AdjustFormat, /NoHeader]  
;
; INPUTS:
;     list  - list of entry numbers to be printed, vector or scalar 
;               if list = -1, then all entries will be printed.
;               An error message is returned if any entry number is larger
;               than the number of entries in the database
;
; OPTIONAL INPUT-OUTPUT:
;     items - items to be printed, specified in any of the following ways:
;
;               form 1  scalar string giving item(s) as list of names
;                       separated by commas
;               form 2  string array giving list of item names
;               form 3  string of form '$filename' giving name
;                       of text file containing items (one item per
;                       line)
;               form 4  integer scalar giving single item number or
;                         integer vector list of item numbers
;               form 5  Null string specifying interactive selection.   This
;                       is the default if 'items' is not supplied
;               form 6  '*'     select all items, printout will be in
;                       table format. 
;
;            If items was undefined or a null string on input, then
;            on output it will contain the items interactively selected.
;
; OPTIONAL INPUT KEYWORDS:
;       /ADJUSTFORMAT -  If set, then the format length for string items will
;               be adjusted to the maximum length for the entries to be printed.
;               This option will slow down DBPRINT because it requires the 
;               string items be extracted and their maximum length determined 
;               prior to any printing.   However, it enables the display of
;               string items without any truncation or wasted space. 
;
;       FORMS - The number of printed lines per page. If forms is not 
;               present, output assumed to be in PORTRAIT form, and 
;               a heading and 47 lines are printed on each page, with
;               a page eject between each page.  For LANDSCAPE form with
;               headings on each page, and a page eject between pages, set 
;               forms = 34.  For a heading only on the first page, and no
;               page eject, set forms = 0.   This is the default for output
;               to the terminal.
;
;       TEXTOUT - Integer (0-7) or string used to determine output device (see 
;               TEXTOPEN for more info).  If not present, the !TEXTOUT system 
;               variable is used.
;               textout=0       Nowhere
;               textout=1       if a TTY then TERMINAL using /more option
;                                   otherwise standard (Unit=-1) output
;               textout=2       if a TTY then TERMINAL without /more option
;                                   otherwise standard (Unit=-1) output
;               textout=3       dbprint.prt (file)
;               textout=4       laser.tmp
;               textout=5       user must open file
;               textout=7      same as 3 but text is appended to .prt
;               textout = filename   (default extension of .prt)
;
;       /NOHEADER - If this keyword is set, then the column headers will not
;               be printed
;
; EXAMPLE:
;       The following example shows how a multiple valued item DATAMAX can be 
;       printed as separate columns.   In the WFPC2 target database, DATAMAX
;       is an item with 4 values, one for each of the 4 chips
;
;       IDL> dbopen,'wflog'
;       IDL> dbprint,list,'entry,datamax(0),datamax(1),datamax(2),datamax(3)'
;
; SYSTEM VARIABLES:
;       Output device controlled by non-standard system varaible !TEXTOUT, if 
;       TEXTOUT keyword is not used.    
;
; NOTES:
;       Users may want to adjust the default lines_per_page value given at
;       the beginning of the program for their own particular printer.
; PROCEDURE CALLS:
;       db_info(), db_item_info(), dbtitle(), dbxval(), textopen, textclose
;       zparcheck
; HISTORY:
;       version 2  D. Lindler  Nov. 1987 (new db format)
;       Test if user pressed 'Q' in response to /MORE W. Landsman  Sep 1991
;       Apply STRTRIM to free form (table) output    W. Landsman   Dec 1992
;       Test for string value of TEXTOUT         W. Landsman   Feb 1994
;       William Thompson, GSFC, 3 November 1994
;                       Modified to allow ZDBASE to be a path string.
;       W. Landsman, GSFC, July, 1997, Use CATCH to catch errors
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Removed STRTRIM in table format output to handle byte values April 1999
;       Fixed occasional problem when /NOHEADER is supplied   Sep. 1999
;       Only byteswap when necessary for improved performance  Feb. 2000
;       Change loop index for table listing to type LONG  W. Landsman Aug 2000
;       Entry vector can be any integer type   W. Landsman Aug. 2001
;       Replace DATATYPE() with size(/TNAME)   W. Landsman  Nov. 2001
;       No page eject for TEXTOUT =5           W. Landsman  Nov. 2001
;       No initial page eject                  W. Landsman  Jan. 2002
;       Added AdjustFormat keyword             W. Landsman  Sep. 2002

; NAME:
;	DBPUT
; PURPOSE:
;	Procedure to place a new value for a specified item into
;	a data base file entry.  
;
; CALLING SEQUENCE:	
;	dbput, item, val, entry
;
; INPUTS:
;	item - item name or number
;	val - item value(s)
;
; INPUT/OUTPUT:
;	entry - entry (byte array) or scalar entry number.
;	        if entry is a scalar entry number then the data
;	        base file will be updated.  Otherwise the change
;	        will be only made to the entry array which must
;	        be written latter using DBWRT.
;
; OPERATIONAL NOTES:
;	If entry is a scalar entry number or the input file name
;	is supplied, the entry in the data base will be updated
;	instead of a supplied entry variable.  In this case, !priv
;	must be greater than 1.
; EXAMPLE:
;       IDL> dbput,'WAVELEN',1215.6,entry
; PROCEDURES USED:
;       DB_ITEM, DBRD, DBXPUT, DBWRT
; HISTORY:
;	version 2  D. Lindler  Feb 1988 (new db formats)
;	modified to convert blanks into zeros correctly D. Neill Jan 1991
;	Converted to IDL V5.0   W. Landsman   September 1997
;       V5.2 version support unsigned, 64bit integers W. Landsman  Sep. 2001

; NAME:
;	DBRD
; PURPOSE:
;	procedure to read an entry from a data base file or from
;	linked multiple databases.
;
; CALLING SEQUENCE:
;	dbrd, enum, entry, [available, dbno, /NoConvert]
;
; INPUTS:
;	enum - entry number to read, integer scalar
;
; OUTPUT:
;	entry - byte array containing the entry
;
; OPTIONAL OUTPUT:
;	available - byte array with length equal to number of data
;		bases opened.  available(i) eq 1 if an entry (pointed
;		to) is available.  It always equals 1 for the first 
;		data base, otherwise it is an error condition.
;
; OPTIONAL  INPUT:
;	dbno - specification of the data base number to return.  If
;		supplied, only the record for the requested data base
;		number is returned in entry.  Normally this input should
;		not be supplied.  dbno is numbered for 0 to n-1 and gives
;		the number of the data base opened.  The data bases are 
;		numbered in the order supplied to dbopen.  If dbno is supplied 
;		then the entry number refers to that data base and not the
;		primary or first data base. If set to -1, then it means all
;		data bases opened (same as not supplying it)
; OPTIONAL INPUT KEYWORD:
;	noconvert - if set then don't convert external to host format.
;		Assumes that calling program will take care of this
;		requirement.
; OPERATIONAL NOTES:
;	If multiple data base files are opened, the records are
;	concatenated with each other
; HISTORY
;	version 2  D. Lindler  Nov. 1987
;	William Thompson, GSFC/CDS (ARC), 1 June 1994
;		Added support for external (IEEE) representation.
;	Version 3, Richard Schwartz, GSFC/SDAC, 23-Aug-1996
;			Add noconvert keyword
;
;	Converted to IDL V5.0   W. Landsman   September 1997
;       Version 4, 2 May 2003, W. Thompson
;               Use BSWAP keyword to DBXVAL instead of calling IEEE_TO_HOST.

; NAME:
;	DBSEARCH
; PURPOSE:
;	Subroutine of DBFIND() to search a vector for specified values
;
; CALLING SEQUENCE:
;	dbsearch, type, svals, values, good, [ /FULLSTRING, COUNT = ] 
;
; INPUT: 
;	type - type of search (output from dbfparse)
;	svals - search values (output from dbfparse)
;	values - array of values to search
;
; OUTPUT:
;	good - indices of good values
;
; OPTIONAL INPUT KEYWORD:
;	/FULLSTRING - By default, one has a match if a search string is 
;		included in any part of a database value (substring match).   
;		But if /FULLSTRING is set, then all characters in the database
;		value must match the search string (excluding leading and 
;		trailing blanks).    Both types of string searches are case
;		insensitive.
; OPTIONAL OUTPUT KEYWORD:
;       COUNT  - Integer scalar giving the number of valid matches
;  SIDE EFFECTS:
;	The obsolete system variable !ERR is set to number of good values
; REVISION HISTORY:
;	D. Lindler  July,1987
;	Converted to IDL V5.0   W. Landsman   September 1997
;       Added COUNT keyword, deprecate !ERR   W. Landsman   March 2000

; NAME:
;	DBSORT
; PURPOSE:
;	Routine to sort list of entries in data base
;
; CALLING SEQUENCE: 
;	result = dbsort( list, items , [ REVERSE = ])
;
; INPUTS:
;	list - list of entry numbers to sort
;		-1 to sort all entries
;	items - list of items to sort (up to 9 items)
;
; OUTPUT:
;	result - numeric vector giving input list sorted by items
;
; OPTIONAL KEYWORD INPUT:
;	REVERSE - scalar or vector with the same number of elements as the
;	  the number of items to sort.  If the corresponding element of REVERSE 
;	  is non-zero then that item is sorted in descending rather than 
;	  ascending order.
;
; EXAMPLE:
;	Sort an astronomical catalog with RA as primary sort, and declination
;	as secondary sort (used when RA values are equal)
;
;	   IDL> NEWLIST = DBSORT( -1, 'RA,DEC' )
;
;	If for some reason, one wanted the DEC sorted in descending order, but
;	the RA in ascending order
;
;	   IDL> NEWLIST = DBSORT( -1, 'RA,DEC', REV = [ 0, 1 ] )
;
; METHOD:
;	The list is sorted such that each item is sorted into
;	asscending order starting with the last item.
; COMMON BLOCKS:
;	DBCOM
; PROCEDURES USED:
;	ZPARCHECK, BSORT, DB_ITEM
; HISTORY
;	VERSION 1  D. Lindler  Oct. 86
;       Added REVERSE keyword   W. Landsman        August, 1991
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;      DBTARGET
; PURPOSE:
;      Find sources in a database within specified radius of specified target
; EXPLANATION:
;      Uses QuerySimbad to translate target name to RA and Dec, and then uses
;      DBCIRCLE() to find any entries within specified radius.   Database must 
;      include items named 'RA' (in hours) and 'DEC' (in degrees) and must 
;      have previously been opened with DBOPEN
;
;      Requires IDL V5.4 or later, Unix and Windows only
; CALLING SEQUENCE:
;     list = DBTARGET(target, [radius, sublist, /SILENT, DIS= ,/TO_B1950 ] )   
;
; INPUTS:
;      TARGET - A scalar string giving an astronomical target name, which 
;          will be  translated into J2000 celestial coordinates by QuerySimbad 
;
; OPTIONAL INPUT:
;       RADIUS - Radius of the search field in arc minutes, scalar.
;                Default is 5 arc minutes
;       SUBLIST - Vector giving entry numbers in currently opened database
;               to be searched.  Default is to search all entries
;
; OUTPUTS:
;     LIST - Vector giving entry numbers in the currently opened catalog
;            which have positions within the specified search circle
;            LIST is set to -1 if no sources fall within the search circle
;            !ERR is set to the number sources found.
;
; OPTIONAL OUTPUT
;       DIS -  The distance in arcminutes of each entry specified by LIST
;               to the search center specified by the target.
;
; OPTIONAL KEYWORD INPUT:
;       /SILENT - If this keyword is set, then DBTARGET will not print the 
;               number of entries found at the terminal
;       /TO_B1950 - If this keyword is set, then the SIMBAD J2000 coordinates 
;               are converted to B1950 before searching the database
;               NOTE: The user must determine on his own whether the database
;               is in B1950 or J2000 coordinates.
;
; EXAMPLE:
;       (1) Use the HST_CATALOG database to find all  HST observations within 
;           5' (the default) of M33
;
;       IDL> dbopen,'hst_catalog'
;       IDL> list = dbtarget('M33')
;
;      (2) As above but restrict targets within 2' of the nucleus using the
;          WFPC2 camara
;
;       IDL> dbopen,'hst_catalog'
;       IDL> sublist = dbfind('config=WFPC2')
;       IDL> list = dbtarget('M33',2,sublist)
;
;
; PROCEDURE CALLS:
;       QuerySimbad, DBCIRCLE()
; REVISION HISTORY:
;      Written W. Landsman     SSAI          September 2002

; NAME:
;	DBTITLE
; PURPOSE:
;	function to create title line for routine dbprint
;
; CALLING SEQUENCE:
;	result = dbtitle( c, f )
;
; INPUTS:
;	c = string array of titles for each item
;	f = field length of each item
;
; OUTPUT:
;	header string returned as function value
;
; OPERATIONAL NOTES:
;	this is a subroutine of DBPRINT.
;
; HISTORY:
;	version 1  D. Lindler  Sept 86
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	DBUPDATE
; PURPOSE:
;	Update columns of data in a database  -- inverse of DBEXT
; EXPLANATION:
;	Database must be open for update before calling DBUPDATE
;
; CALLING SEQUENCE:
;	dbupdate, list, items, v1, [ v2, v3, v4......v14 ]
;
; INPUTS:
;	list - entries in database to be updated, scalar or vector
;		If list=-1 then all entries will be updated
;	items -standard list of items that will be updated.  
;	v1,v2....v14 - vectors containing values for specified items.  The
;		number of vectors supplied must equal the number of items
;		specified.   The number of elements in each vector should be
;		the same.
;
; OPTIONAL KEYWORD INPUT:
;       /NOINDEX - If set, then DBUPDATE will not update the index file.   This
;               keyword is useful to save if additional updates will occur,
;               and the index file need only be updated on the last call.
;            
; EXAMPLES:
;	A database STAR contains RA and DEC in radians, convert to degrees
;
;	IDL> !PRIV=2 & dbopen,'STAR',1          ;Open database for update
;	IDL> dbext,-1,'RA,DEC',ra,dec          ;Extract RA and DEC, all entries 
;	IDL> ra = ra*!RADEG & dec=dec*!RADEG    ;Convert to degrees
;	IDL> dbupdate,-1,'RA,DEC',ra,dec        ;Update database with new values
;
; NOTES:
;	It is quicker to update several items simultaneously rather than use
;	repeated calls to DBUPDATE.  
; 
;	It is possible to update multiple valued items.  In this case, the
;	input vector should be of dimension (NVAL,NLIST) where NVAL is the
;	number of values per item, and NLIST is the number of entries to be
;	updated.  This vector will be temporarily transposed by DBUPDATE but
;	will be restored before DBUPDATE exits.
;
; REVISION HISTORY
;	Written W. Landsman      STX       March, 1989
;	Work for multiple valued items     May, 1991
;	String arrays no longer need to be fixed length      December 1992
;	Transpose multiple array items back on output        December 1993
;	Faster update of external databases on big endian machines November 1997
;	Converted to IDL V5.0   W. Landsman 24-Nov-1997
;       Added /NOINDEX keyword  W. Landsman  July 2001

; NAME:
;	DBVAL
; PURPOSE:
;	procedure to extract value(s) of the specified item from
;	a data base file entry.
;
; CALLING SEQUENCE:
;	result = dbval( entry, item )
;
; INPUTS:
;	entry - byte array containing the entry, or a scalar entry number
;	item - name (string) or number (integer) of the item
;
; OUTPUT:
;	the value(s) will be returned as the function value
;
; EXAMPLE:
;	Extract a flux vector from entry 28 of the database FARUV
;	==> flux = dbval(28,'FLUX')
;
; HISTORY:
;   version 2  D. Lindler Nov, 1987	(new db format)
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	DBWRT
; PURPOSE:
;	procedure to update or add a new entry to a data base
;
; CALLING SEQUENCE:
;	dbwrt, entry, [ index, append, /NoConvert ]
;
; INPUTS:
;	entry - entry record to be updated or added if first
;		item (entry number=0)
;
; OPTIONAL INPUTS:
;	index - optional integer flag,  if set to non zero then index
;		file is  updated. (default=0, do not update index file)
;		(Updating the index file is time-consuming, and should
;		normally be done after all changes have been made.
;	append - optional integer flag, if set to non-zero the record
;		is appended as a new entry, regardless of what the
;		entry number in the record is.  The entry number will
;		be reset to the next entry number in the file.
; OUTPUTS:
;	data base file is updated.                    
;	If index is non-zero then the index file is updated.
; OPTIONAL INPUT KEYWORD:
;	NoConvert - If set then don't convert to host format with an external
;		database.    Useful when the calling program decides that
;		conversion isn't needed (i.e. on a big-endian machine), or 
;		takes care of the conversion itself.
; OPERATIONAL NOTES:
;	!PRIV must be greater than 1 to execute
; HISTORY:
;	version 2  D. Lindler  Feb. 1988 (new db format)
;	converted to IDL Version 2.  M. Greason, STX, June 1990.
;	William Thompson, GSFC/CDS (ARC), 28 May 1994
;		Added support for external (IEEE) representation.
;	Converted to IDL V5.0   W. Landsman 24-Nov-1997

; NAME:
;	DBXPUT
; PURPOSE:
;	routine to replace value of an item in a data base entry
;
; CALLING SEQUENCE:	
;	dbxput, val, entry, idltype, sbyte, nbytes
;
; INPUT:
;	val - value(s) to be placed into entry, string values might be
;		truncated to fit number of allowed bytes in item
;	entry - entry or entries to be updated
;	idltype - idl data type for item (1-7)
;	sbyte - starting byte in record
;	nbytes - total number of bytes in value added
;
; OUTPUT:
;	entry - (updated)
;
; OPERATIONAL NOTES:
;	This routine assumes that the calling procedure or user knows what he 
;	or she is doing.  String items are truncated or padded to the fixed 
;	size specified by the database but otherwise no validity checks are 
;	made.
;
; HISTORY:
;	version 1, D. Lindler   Aug, 1986
;	converted to IDL Version 2.  M. Greason, STX, June 1990.
;	Work with multiple element string items   W. Landsman  August 1995
;	Really work with multiple element string items   
;			R. Bergman/W. Landsman  July 1996
;	Work with multiple entries, R. Schwartz, GSFC/SDAC August 1996
;	Use /overwrite with REFORM() W. Landsman May 1997
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME: 
;       DBXVAL
;
; PURPOSE:      
;       Quickly return a value of the specified item number     
; EXPLANATION:
;       Procedure to quickly return a value of the specified item number
;       from the entry.
;
; CALLING SEQUENCE:     
;       result = dbxval( entry, idltype, nvalues, sbyte, nbytes )
;
; INPUTS        
;       entry - entry or entries from data base (bytarr) 
;       idltype - idl data type (obtained with db_item_info)
;       nvalues - number of values to return (obtained with db_item)
;       sbyte - starting byte in the entry (obtained with db_item)
;       nbytes - number of bytes (needed only for string type)
;                       (obtained with db_item)
;
; OUTPUTS:      
;       function value is value of the specified item in entry
;
; KEYWORDS:
;       bswap - If set, then IEEE_TO_HOST is called.
;
; RESTRICTIONS: 
;       To increase speed the routine assumes that entry and item are
;       valid and that the data base is already opened using dbopen.
;
; REVISION HISTORY:     
;       version 0  D. Lindler Nov. 1987  (for new db format)
;       Version 1, William Thompson, GSFC, 28 March 1994.
;                       Incorporated into CDS library.
;       Version 2, Richard Schwartz, GSFC/SDAC, 23 August 1996
;                       Allowed Entry to have 2 dimensions
;       Version 2.1, 22 Feb 1997, JK Feggans, 
;                               avoid reform for strings arrays.
;       Version 2.2     Use overwrite with REFORM(),  W. Landsman,  May 1997
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Work for multiple-valued strings   W. Landsman   October 2000
;       Add new 64bit & unsigned integer datatypes W.Landsman   July 2001
;       Version 3, 2-May-2003, JK Feggans/Sigma, W.T. Thompson
;           Added BSWAP keyword to avoid floating errors on some platforms.

; NAME:
;	DB_ENT2EXT
; PURPOSE:
;	Convert a database entry to external (IEEE) data format
; EXPLANATION: 
;	Converts a database entry to external (IEEE) data format prior to
;	writing it.  Called from DBWRT.
;
; CALLING SEQUENCE:
;	DB_ENT2EXT, ENTRY
;
; INPUTS:
;	ENTRY	= Byte array containing a single record to be written to the
;		  database file.
;
; OUTPUTS:
;	ENTRY	= The converted array is returned in place of the input array.
;
; COMMON BLOCKS:
;	DB_COM
;
; HISTORY:
;	Version 1, William Thompson, GSFC/CDS (ARC), 1 June 1994
;	Version 2, William Thompson, GSFC/CDS (ARC), 15 September 1995
;			Fixed bug where only the first element in a
;			multidimensional array was converted.
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	DB_ENT2HOST
; PURPOSE:
;	Converts a database entry from external data format to host format.
; EXPLANATION:
;	All items are extracted from the entry, and then converted to host 
;	format, and placed back into the entry.  Called from DBRD and DBEXT_DBF.
;
; CALLING SEQUENCE:
;	DB_ENT2HOST, ENTRY, DBNO
;
; INPUTS:
;	ENTRY	= Byte array containing a single record read from the
;		  database file.
;	DBNO	= Number of the opened database file.
;
; OUTPUTS:
;	ENTRY	= The converted array is returned in place of the input array.
;
; COMMON BLOCKS:
;	DB_COM
;
; HISTORY:
;	Version 1, William Thompson, GSFC/CDS (ARC), 1 June 1994
;	Version 2, William Thompson, GSFC/CDS (ARC), 15 September 1995
;			Fixed bug where only the first element in a
;			multidimensional array was converted.
;	Version 3, Richard Schwartz, GSFC/SDAC, 23 August 1996
;		Allow 2 dimensional byte arrays for entries to facilitate 
;		multiple entry processing.    Pass IDLTYPE onto IEEE_TO_HOST
;	Converted to IDL V5.0   W. Landsman   September 1997
;       Version 4, 2 May 2003, W. Thompson
;               Use BSWAP keyword to DBXVAL instead of calling IEEE_TO_HOST.

; NAME:
;	DB_INFO
; PURPOSE:
;	Function to obtain information on opened data base file(s)
;
; CALLING SEQUENCES:
;	1)  result = db_info(request)
;	2)  result = db_info(request,dbname)
; INPUTS (calling sequence 1):
;
;	request - string specifying requested value(s)
;		value of request	  value returned in result
;			'open'		Flag set to 1 if data base(s) are opened
;			'number'	Number of data base files opened
;			'items'		Total number of items (all db's opened)
;			'update'	update flag (1 if opened for update)
;			'unit_dbf'	Unit number of the .dbf files
;			'unit_dbx'	Unit number of the .dbx files
;			'entries'	Number of entries in the db's
;			'length'	Record lengths for the db's
;			'external'	True if the db's are in external format
;
; INPUTS (calling sequence 2):
;
;	request - string specifying requested value(s)
;		   value of request	  value returned in result
;			'name'		Name of the data base
;			'number'	Sequential number of the db
;			'items'		Number of items for this db
;			'item1'		Position of item1 for this db
;					in item list for all db's
;			'item2'		Position of last item for this db.
;			'pointer'	Number of the item which points
;					to this db. 0 for first or primary
;					db.  -1 if link file pointers.
;			'length'	Record length for this db.
;			'title'		Title of the data base
;			'unit_dbf'	Unit number of the .dbf file
;			'unit_dbx'	Unit number of the .dbx file
;	    		'entries'	Number of entries in the db
;			'seqnum'	Last sequence number used
;			'alloc'		Allocated space (# entries)
;			'update'	1 if data base opened for update
;			'external'	True if data base in external format
;
;	dbname - data base name or number
; OUTPUTS:
;	Requested value(s) are returned as the function value.
;
; HISTORY:
;	version 1  D. Lindler    Oct. 1987
;       changed type from 1 to 7 for IDLV2, J. Isensee, Nov., 1990
;	William Thompson, GSFC/CDS (ARC), 30 May 1994
;		Added EXTERNAL request type.
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME: 
;       DB_ITEM
; PURPOSE:      
;       Returns the item numbers and other info. for an item name.
; EXPLANATION:  
;       Procedure to return the item numbers and other information
;       of a specified item name
;
; CALLING SEQUENCE:     
;       db_item, items, itnum, ivalnum, idltype, sbyte, numvals, nbytes
;
; INPUTS:       
;       items - item name or number
;               form 1  scalar string giving item(s) as list of names
;                       separated by commas
;               form 2  string array giving list of item names
;               form 3  string of form '$filename' giving name
;                       of text file containing items (one item per
;                       line)
;               form 4  integer scalar giving single item number or
;                         integer vector list of item numbers
;               form 5  Null string specifying interactive selection
;                       Upon return items will contain selected items
;                       in form 1
;               form 6  '*'     select all items
;
; OUTPUTS:      
;       itnum - item number
;       ivalnum - value(s) number from multiple valued item
;       idltype - data type(s) (1=string,2=byte,4=i*4,...)
;       sbyte - starting byte(s) in entry
;       numvals - number of data values for item(s)
;               It is the full length of a vector item unless
;               a subscript was supplied
;       nbytes - number of bytes for each value
;    All outputs are vectors even if a single item is requested
;
; OPTIONAL INPUT KEYWORDS:      
;       ERRMSG   = If defined and passed, then any error messages will
;               be returned to the user in this parameter rather than depending
;               on the MESSAGE routine in IDL.  If no errors are encountered, 
;               then a null string is returned.  In order to use this feature, 
;               ERRMSG must be defined first, e.g.
;
;                               ERRMSG = ''
;                               DB_ITEM, ERRMSG=ERRMSG, ...
;                               IF ERRMSG NE '' THEN ...
;
; PROCEDURE CALLS:
;       DB_INFO, GETTOK, SCREEN_SELECT, SPEC_DIR
;
; REVISION HISTORY:
;       Written:   D. Lindler, GSFC/HRS, October 1987
;       Version 2, William Thompson, GSFC, 17-Mar-1997
;                       Added keyword ERRMSG
;       Converted to IDL V5.0   W. Landsman   October 1997
;       Use STRSPLIT instead of GETTOK to parse form 1, W. Landsman July 2002
;	Fixed bug in pre-5.3 support, William Thompson, 22 May 2003

; NAME:
;	DB_ITEM_INFO
; PURPOSE:
;	routine to return information on selected item(s) in the opened
;	data bases.
;
; CALLING SEQUENCE:
;	result = db_item_info( request, itnums)
; INPUTS:
;	request - string giving the requested information.
;		'name'		- item names
;		'idltype'	- IDL data type (integers)
;				  see documentation of intrinsic SIZE funtion
;		'nvalues'	- vector item length (1 for scalar)
;		'sbyte'		- starting byte in .dbf record (use bytepos
;				  to get starting byte in record returned by
;				  dbrd)
;		'nbytes'	- bytes per data value
;		'index'		- index types
;		'description'	- description of the item
;		'pflag'		- pointer item flags
;		'pointer'	- data bases the items point to
;		'format'	- print formats
;		'flen'		- print field length
;		'headers'	- print headers
;		'bytepos'	- starting byte in dbrd record for the items
;		'dbnumber'	- number of the opened data base
;		'pnumber'	- number of db it points to (if the db is
;					opened)
;		'itemnumber'	- item number in the file
;
;	itnums -(optional) Item numbers.  If not supplied info on all items
;		are returned.
; OUTPUT:
;	Requested information is returned as a vector.  Its type depends
;	on the item requested.
; HISTORY:
;	version 1  D. Lindler  Nov. 1987
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	DB_OR
; PURPOSE:
;	Combine two vectors of entry numbers, removing duplicate values.
; EXPLANATION:
;	DB_OR can also be used to remove duplicate values from any longword 
;	vector
;
; CALLING SEQUENCE:
;	LIST = DB_OR( LIST1 )          ;Remove duplicate values from LIST1
;		or
;	LIST = DB_OR( LIST1, LIST2 )   ;Concatenate LIST1 and LIST2, remove dups
;
; INPUTS:
;	LIST1, LIST2 - Vectors containing entry numbers, must be non-negative
;			integers or longwords.
; OUTPUT:
;	LIST - Vector containing entry numbers in either LIST1 or LIST2
;  
; METHOD
;	DB_OR returns where the histogram of the entry vectors is non-zero
;
; PROCEDURE CALLS
;	ZPARCHECK - checks parameters  
; REVISION HISTORY:
;	Written,     W. Landsman             February, 1989
;	Check for degenerate values  W.L.    February, 1993
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	DB_TITLES
;
; PURPOSE:
;	Print database name and title.  Called by DBHELP
;
; CALLING SEQUENCE:
;	db_titles, fnames, titles
;
; INPUT:
;	fnames - string array of data base names
;
; SIDE EFFECT:
;	Database name is printed along with the description in the .dbh file
;
; HISTORY:
;	version 2  W. Landsman May, 1989
;	modified to work under Unix, D. Neill, ACC, Feb 1991.
;	William Thompson, GSFC/CDS (ARC), 1 June 1994
;		Added support for external (IEEE) representation.
;	William Thompson, GSFC, 3 November 1994
;			Modified to allow ZDBASE to be a path string.
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:	
;       DEF_DIRLIST
;
; PURPOSE:
;       Define directory list using setenv or setlog
;
; EXPLANATION:	
;       Environment variables which point to a list of directories can
;       end up to be very long.  In VMS this can be a problem, because logical 
;       names cannot be longer than 256 characters.  However, it is possible to
;       get around this in VMS by assigning multiple values to a single logical
;       name--a facility that does not exist in Unix.
;
;       This routine will define the environment variable as either a delimited
;       string, or as a series of values, whichever is most appropriate.
;
; CALLING SEQUENCE:	
;       DEF_DIRLIST, EVAR, VALUE
; INPUTD:	
;       EVAR = The name of the environment variable to define.
;       VALUE = The value to give to EVAR.  This can be either a single, 
;               delimited string, or it can be an array of directory names.
;               The routine will choose for itself how to use this to define the 
;               environment variable.
;
; EXAMPLES:	
;       DIRS = FIND_ALL_DIR('+/data/fits')
;       DEF_DIRLIST, 'FITS_DATA', DIRS
;
; PROCEDURE CALLS:
;       SETENV, STR_SEP()
;	Note: The intrinsic SETENV command is available under Unix & Windows
;	only.   However, it is available as a Library procedure for VMS.
;
; REVISION HISTORY:	
;	Version 1, 06-Aug-1996, William Thompson, GSFC
;       Converted to IDL V5.0   June 1998    W. Landsman
;       Use STRSPLIT instead of STR_SEP if V5.3 or later W.L.  July 2002

; NAME: 
;	DELVARX
; PURPOSE: 
; 	Delete variables for memory management (can call from routines) 
; EXPLANATION:
;	Like intrinsic DELVAR function, but can be used from any calling level
;
; CALLING SEQUENCE:
; 	DELVARX,  a [,b,c,d,e,f,g,h,i,j]
;
; INPUTS: 
;	p0, p1...p9 - variables to delete
;
; RESTRICTIONS: 
;	Can't use recursively due to EXECUTE function
;
; METHOD: 
;	Uses EXECUTE and TEMPORARY function   
;
; REVISION HISTORY:
;	Copied from the Solar library, written by slf, 25-Feb-1993
;	Added to Astronomy Library,  September 1995
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;     DEREDD
;
; PURPOSE:
;     Deredden stellar Stromgren parameters given for a value of E(b-y)
; EXPLANATION:
;     See the procedure UVBYBETA for more info.
;
;  CALLING SEQUENCE:
;     deredd, eby, by, m1, c1, ub, by0, m0, c0, ub0, /UPDATE
;
;  INPUTS:
;     Eby - color index E(b-y),scalar  (E(b-y) = 0.73*E(B-V) )
;     by - b-y color (observed)
;     m1 - Stromgren line blanketing parameter (observed)
;     c1 - Stromgren Balmer discontinuity parameter (observed)
;     ub - u-b color (observed)
;
;     These input values are unaltered unless the /UPDATE keyword is set
;  OUTPUTS:
;     by0 - b-y color (dereddened)
;     m0 - Line blanketing index (dereddened)
;     c0 - Balmer discontinuity parameter (dereddened)
;     ub0 - u-b color (dereddened)
;
;  OPTIONAL INPUT KEYWORDS:
;     /UPDATE - If set, then input parameters are updated with the dereddened
;           values (and output parameters are not used).
;  REVISION HISTORY:
;     Adapted from FORTRAN routine DEREDD by T.T. Moon 
;     W. Landsman          STX Co.        April, 1988
;     Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	DETABIFY
; PURPOSE:
;	Replaces tabs in character strings with appropriate number of spaces
; EXPLANATION:
;	The number of space characters inserted is calculated to space
;	out to the next effective tab stop, each of which is eight characters
;	apart.
;
; CALLING SEQUENCE:
;	Result = DETABIFY( CHAR_STR )
;
; INPUT PARAMETERS:
;	CHAR_STR = Character string variable (or array) to remove tabs from.
;
; OUTPUT:
;	Result of function is CHAR_STR with tabs replaced by spaces.
;
; RESTRICTIONS:
;	CHAR_STR must be a character string variable.
;
; MODIFICATION HISTORY:
;	William Thompson, Feb. 1992.
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	DFITSRD
; PURPOSE:
;	Convert true disk FITS formatted file(s) into STSDAS formatted file(s).
;	Disk FITS refers to files (that can be created by IRAF or AIPS) that
;	keep the exact format (e.g. 2880 byte record length) of a FITS tape.  
;	STSDAS files have a detached header and 512 byte record length. 
;
; CALLING SEQUNCE: 
;	DFITSRD, infile, outname, [ /NOPROMPT ]
;
; INPUTS:
;	INFILE = input FITS file name (default extension .DAT), scalar string
;	OUTNAME = output file name (ALWAYS has extensions .hhh for header and 
;		.hhd for data; user supplied extensions are ignored.   Scalar
;		string
;
; INTERACTIVE INPUT:
;	User will be prompted if INFILE or OUTNAME are undefined or integers.
;
; NOTES:
;	Output files are always created with the extensions .hhh (header) and 
;	.hhd (data).     DFITSRD is a shell for the procedure DFITSREAD which
;	does the actual processing of the FITS file.
;
; INPUT KEYWORD PARAMETERS:
;	NOPROMPT - If this keyword is set then DFITSRD will not prompt for 
;		another file name to be processed.  This keyword is useful 
;		when DFITSRD is called from a driver procedure.
;
; SIDE EFFECTS:
;	For each FITS disk file STSDAS disk files will be created
;	with names:
;		name.hhh and name.hhd
;	Fits extension files will have names:
;		name_x.HHH and name_x.HHD
;	where x runs from 1 to the number of extensions.
;
; EXAMPLES:
;	(1) Prompt for input and output file names
;		IDL> dfitsrd,1
;  
;	(2) Write FITS image, ngc598.fits to an STSDAS files m33.hhh/d 
;		IDL> dfitsrd,'ngc598.fits','m33'
;
; PROCEDURES USED:
;	dfitsread, fdecomp, datatype
;
; MODIFICATION HISTORY:
;	B. Pfarr - adapted from FITSRD, modified to read from disk 8/88
;	W. Lansdman - display calling sequence if no params suplied Sep. 92

; NAME:
;   DFITSRD_LARGE
; PURPOSE:
;   Convert true disk FITS formatted file(s) into STSDAS formatted file(s).
;   Disk FITS refers to files (that can be created by IRAF or AIPS) that
;   keep the exact format (e.g. 2880 byte record length) of a FITS tape.  
;   STSDAS files have a detached header and 512 byte record length. 
; CALLING SEQUNCE: 
;   DFITSRD_LARGE,infile,outname
; OPTIONAL INPUTS:
;   INFILE = string, input file name (default extension .DAT)
;   OUTNAME = string, output file name (ALWAYS has extensions 
;      	       .hhh for header and .hhd for data; user supplied extensions
;              are ignored.
; INTERACTIVE INPUT:
;   If user does not pass infile and/or outname in as parameters,
;   user will be prompted for input file names (default extension .DAT),
;   and output file names.   Output files are always created with the
;   extensions .hhh (header) and .hhd (data).
; INPUT KEYWORD PARAMETERS:
;   NOPROMPT - If this keyword is set then DFITSRD_LARGE will not prompt for
;              another file name to be processed.  This keyword is useful when
;              DFITSRD_LARGE is called from a driver procedure.
; SIDE NOTES:
;    Use DFITSRD instead of DFITSRD_LARGE for small to moderately sized
;    files.  It is much faster.  Use DFITSRD_LARGE if you do not have a
;    large enough dynamic memory allocation to read the file with DFITSRD.
; SIDE EFFECTS:
;	For each FITS disk file STSDAS disk files will be created
;	with names:
;		name.hhh and name.hhd
;	Fits extension files will have names:
;		name_x.HHH and name_x.HHD
;	where x runs from 1 to the number of extensions.
; MODIFICATION HISTORY:
;       B. Pfarr - adapted from FITSRD, modified to read from disk 8/88
;	W. Thompson - changed call to DFITSREAD to DFITSREAD_LARGE, 4/91

; NAME:
;	DFITSREAD
; PURPOSE:
;	Procedure will read a disk FITS file and write to a STSDAS disk file.
;	The header is placed in .HHH and the data is placed in the file 
;	.HHD.  This procedure is called by DFITSRD which is the procedure
;	that an interactive user would normally use.
;
; CALLING SEQUENCE: 
;	dfitsread, unit, name, [ EXTEN= , NBTYES = ]
;
; INPUTs:
;	unit - unit number of opened input file
;	name - file name (without an extension)
;
; OPTIONAL OUTPUT KEYWORDS:
;	EXTEN = This keyword is set to 1 if the FITS header contains the 
;		keyword EXTEND = T,  otherwise, exten = 0
;		NOTE: exten = 1 does NOT gaurantee extensions are present
;	NBYTES - Contains the number of bytes written to disk, integer scalar
;
; OUTPUT:
;	name - name of file if input keyword parameter is supplied
; SIDE EFFECTS:
;	files name.hhh and name.hhd are created
; HISTORY:                               
;	B. Pfarr - adapted from FITSREAD to handle disk files
;	Converted to Version 2 IDL,  K. Bhagat,  August 1990
;	Added call to IEEE_TO_HOST, single I/O calls, W. Landsman   Jan, 1992
;	Force SIMPLE = 'F' in STSDAS file    W. Landsman Aug 1993

; NAME:
;   DFITSREAD_LARGE
; PURPOSE:
;   Procedure will read a disk FITS file 
;   The header is placed in .HHH and the data is
;   placed in the file .HHD.  Called by DFITSRD_LARGE
; CALLING SEQUENCE: 
;   dfitsread_large,unit,name,exten=exten
; INPUTs:
;   unit - unit number of opened input file
;   name - file name (without an extension)
; KEYWORD:
;   exten = exten - 
;	    If header keyword EXTEND = T, exten = 1, otherwise, exten = 0
;      	    exten = 1 does NOT gaurantee extensions are present
; OUTPUT:
;	name - name of file if input keyword parameter is supplied
; SIDE NOTES:
;    Use DFITSREAD instead of DFITSREAD_LARGE for small to moderately sized
;    files.  It is much faster.  Use DFITSREAD_LARGE if you do not have a
;    large enough dynamic memory allocation to read the file with DFITSREAD.
; SIDE EFFECTS:
;	files name.hhh and name.hhd are created
; HISTORY:                               
;    B. Pfarr - adapted from FITSREAD to handle disk files
;    Converted to Version 2 IDL,  K. Bhagat,  August 1990
;    W. T. Thompson  May, 1990, changed to write data to
;		disk in pieces rather than all at once at the end
;		of a group.

; NAME:   
;	DFITSWRITE
; PURPOSE:
;	Procedure will write an internal SDAS file to a FITS file on disk.
;	Note: Called by DFITSWRT
;
; CALLING SEQUENCE:
;	DFITSWRITE, unit, file [, KEYWORD]
;
; INPUTS:
;	unit - IDL logical unit number
;	file - internal FITS file name without extension (extension
;		is assumed to be .HHH and .HHD)
;
; OPTIONAL INPUT:
;	keyword - FITS keyword to place file name into.  if not supplied
;		or equals '' then the file name is not put into the
;		header before writing it to disk FITS file.
;
; SIDE EFFECT:
;	A FITS file is written to disk.
;
; PROCEDURE CALLS:
;	remchar, sxhread, sxpar, fdecomp, sxaddpar, host_to_ieee
;
; HISTORY:
;	version 3  D. Lindler   Nov. 1986                
;	version 5  B. Pfarr  modified from FITSWRITE
;	Added HOST_TO_IEEE call W. Landsman            January, 1992
;	Remove dummy SDAS group parameters             February, 1992
;	Work for Alpha OpenVMS                         October, 1994

; NAME:	
;	DFITSWRT
; PURPOSE: 
;	Convert ST/SDAS formatted files to true disk FITS formatted file(s).
;	D(isk) fits: refers to files (that can be created by IRAF or AIPS) that
;	keep the exact format (e.g. 2880 byte record length) of a FITS tape.  
;	ST/SDAS files: has detached header and 512 byte record length. 
;
; CALLING SEQUENCE:
;	DFITSWRT , iname, oname, [ EXTEND =  ]
;
; INPUT:
;	iname  - name of existing ST/SDAS formatted file to be converted.
;		if iname is set to 1, then user will be prompted for file names.
;	oname - output file name for to disk FITS file [default DFITS]
;		note: user may also specify extension for filename...default
;		is .FITS (i.e. DFITS.FITS).
;
; KEYWORD:
;	EXTEND  - Set this keyword nonzero if you want DFITSWRT to include 
;		any SDAS table extensions files into the disk FITS output.
;		The table extensions must be of the form iname_extnumber 
;		(see example).  
; EXAMPLES:
;	(1)   Run DFITSWRT interactively
;
;	IDL> dfitswrt,1
;
;	(2)    You have files SDAS.HHH and SDAS.HHD plus additional SDAS tables 
;		or other groups:
;
;		DFITSWRT,'SDAS','SDAS',/EXTEND
;
;		Note: as the disk FITS file is created, it will look for
;		the SDAS group (or tables) named:
;			sdas_1.hhh  and sdas_1.hhd
;			sdas_2.hhh  and sdas_2.hhd
;                             .
;                             :
;           Note: the number of group(or table) files depends on the
;               number of existing SDAS group(or table) input files.
;           The output file will be named SDAS.FITS
;
; NOTES:
;	DFITSWRT does not do any validity checking on the FITS header
;	In particular, be sure that the FITS header has EXTEND = 'T'
;	if extensions are included.     
;
; MODIFICATION HISTORY:
;	version 3  D. Lindler  Nov 86
;       Fixed use of /EXTEND keyword, cleaned up documentation 
;                                      W. Landsman  ST Systems  October 91

; NAME: 
;      DIST_CIRCLE
; PURPOSE:      
;      Form a square array where each value is its distance to a given center.
; EXPLANATION:
;      Returns a square array in which the value of each element is its 
;      distance to a specified center. Useful for circular aperture photometry.
;
; CALLING SEQUENCE:
;      DIST_CIRCLE, IM, N, [ XCEN, YCEN,  /DOUBLE ]
;
; INPUTS:
;      N = either  a scalar specifying the size of the N x N square output
;               array, or a 2 element vector specifying the size of the
;               N x M rectangular output array.
;
; OPTIONAL INPUTS:
;      XCEN,YCEN = Scalars designating the X,Y pixel center.  These need
;               not be integers, and need not be located within the
;               output image.   If not supplied then the center of the output
;               image is used (XCEN = YCEN = (N-1)/2.).
;
; OUTPUTS:
;       IM  - N by N (or M x N) floating array in which the value of each 
;               pixel is equal to its distance to XCEN,YCEN
;
; OPTIONAL INPUT KEYWORD:
;       /DOUBLE - If this keyword is set and nonzero, the output array will
;               be of type DOUBLE rather than floating point.
;
; EXAMPLE:
;       Total the flux in a circular aperture within 3' of a specified RA
;       and DEC on an 512 x 512 image IM, with a header H.
;
;       IDL> adxy, H, RA, DEC, x, y       ;Convert RA and DEC to X,Y
;       IDL> getrot, H, rot, cdelt        ;CDELT gives plate scale deg/pixel
;       IDL> cdelt = cdelt*3600.          ;Convert to arc sec/pixel
;       IDL> dist_circle, circle, 512, x, y  ;Create a distance circle image
;       IDL> circle = circle*abs(cdelt[0])   ;Distances now given in arcseconds
;       IDL> good = where(circle LT 180)  ;Within 3 arc minutes
;       IDL> print,total( IM[good] )      ;Total pixel values within 3'
;
; RESTRICTIONS:
;       The speed of DIST_CIRCLE decreases and the the demands on virtual
;       increase as the square of the output dimensions.   Users should
;       dimension the output array as small as possible, and re-use the
;       array rather than re-calling DIST_CIRCLE
;
; MODIFICATION HISTORY:
;       Adapted from DIST    W. Landsman            March 1991
;       Allow a rectangular output array   W. Landsman     June 1994
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Add /DOUBLE keyword, make XCEN,YCEN optional  W. Landsman Jun 1998

; NAME:
;       DIST_ELLIPSE
; PURPOSE:
;       Create a mask array useful for elliptical aperture photemetry
; EXPLANATION:
;       Form an array in which the value of each element is equal to the
;       semi-major axis of the ellipse of specified center, axial ratio, and 
;       position  angle, which passes through that element.  Useful for 
;       elliptical aperture photometry.
;
; CALLING SEQUENCE:
;       DIST_ELLIPSE, IM, N, XC, YC, RATIO, POS_ANG, /DOUBLE
;
; INPUTS:
;       N = either  a scalar specifying the size of the N x N square output
;               array, or a 2 element vector specifying the size of the
;               M x N rectangular output array.
;       XC,YC - Scalars giving the position of the ellipse center.   This does
;               not necessarily have to be within the image
;       RATIO - Scalar giving the ratio of the major to minor axis.   This 
;               should be greater than 1 for postion angle to have its 
;               standard meaning.
;
; OPTIONAL INPUTS:
;       POS_ANG - Position angle of the major axis, measured counter-clockwise
;               from the Y axis.  For an image in standard orientation 
;               (North up, East left) this is the astronomical position angle.
;
; OPTIONAL INPUT KEYWORD:
;       /DOUBLE - If this keyword is set and nonzero, the output array will
;               be of type DOUBLE rather than floating point.
;
; OUTPUT:
;       IM - REAL*4 elliptical mask array, of size M x N.  THe value of each 
;               pixel is equal to the semi-major axis of the ellipse of center
;                XC,YC, axial ratio RATIO, and position angle POS_ANG, which 
;               passes through the pixel.
;
; EXAMPLE:
;       Total the flux in a elliptical aperture with a major axis of 3', an
;       axial ratio of 2.3, and a position angle of 25 degrees centered on 
;       a specified RA and DEC.   The image array, IM is 200 x 200, and has 
;       an associated FITS header H.
;
;       ADXY, H, ra, dec, x, y       ;Get X and Y corresponding to RA and Dec
;       GETROT, H, rot, cdelt        ;CDELT gives plate scale degrees/pixel
;       cdelt = abs( cdelt)*3600.    ;CDELT now in arc seconds/pixel
;       DIST_ELLIPSE, ell, 200, x, y, 2.3, 25  ;Create a elliptical image mask
;       ell = ell*cdelt(0)           ;Distances now given in arcseconds
;       good = where( ell lt 180 )   ;Within 3 arc minutes
;       print,total( im(good) )      ;Total pixel values within 3'
;
; RESTRICTIONS:
;       The speed of DIST_ELLIPSE decreases and the the demands on virtual
;       increase as the square of the output dimensions.   Users should
;       dimension the output array as small as possible, and re-use the
;       array rather than re-calling DIST_ELLIPSE
;
; REVISION HISTORY:
;       Written    W. Landsman             April, 1991
;       Somewhat faster algorithm          August, 1992
;       Allow rectangular output array     June, 1994
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Added /DOUBLE keyword   W. Landsman   July 2000

; NAME:
;     ECI2GEO
;
; PURPOSE:
;     Convert Earth-centered inertial coordinates to geographic spherical coords
; EXPLANATION:
;     Converts from ECI (Earth-Centered Inertial) (X,Y,Z) rectangular 
;     coordinates to geographic spherical coordinates (latitude, longitude, 
;     altitude).    JD time is also needed as input.
;
;     ECI coordinates are in km from Earth center.
;     Geographic coordinates are in degrees/degrees/km
;     Geographic coordinates assume the Earth is a perfect sphere, with radius 
;     equal to its equatorial radius.
;
; CALLING SEQUENCE:
;     gcoord=eci2geo(ECI_XYZ,JDtime)
;
; INPUT:
;       ECI_XYZ : the ECI [X,Y,Z] coordinates (in km), can be an array [3,n] 
;                 of n such coordinates.
;       JDtime: the Julian Day time, double precision. Can be a 1-D array of n 
;                 such times.
;
; KEYWORD INPUTS:
;       None
;
; OUTPUT:
;       a 3-element array of geographic [latitude,longitude,altitude], or an 
;         array [3,n] of n such coordinates, double precision  
;
; COMMON BLOCKS:
;       None
;
; PROCEDURES USED:
;       CT2LST - Convert Local Civil Time to Local Mean Sidereal Time
;
; EXAMPLE:
;       IDL> gcoord=eci2geo([6378.137+600,0,0], 2452343.38982663D)
;       IDL> print,gcoord
;       0.0000000       232.27096       600.00000
;
;       (The above is the geographic direction of the vernal point on 
;       2002/03/09 21:21:21.021, in geographic coordinates. The chosen 
;       altitude was 600 km.)
;
;       gcoord can be further transformed into geodetic coordinates (using 
;       geo2geodetic.pro) or into geomagnetic coordinates (using geo2mag.pro)
;
; MODIFICATION HISTORY:
;       Written by Pascal Saint-Hilaire (Saint-Hilaire@astro.phys.ethz.ch) on 
;              2001/05/13
;       Modified on 2002/05/13, PSH : vectorization + use of JD times          

; NAME:
;   EQ2HOR
;
; PURPOSE:
;    Convert celestial  (ra-dec) coords to local horizon coords (alt-az).
;
; CALLING SEQUENCE:
;
;    eq2hor, ra, dec, jd, alt, az, [ha, LAT= , LON= , /WS, OBSNAME= , $
;                       /B1950 , PRECESS_= 0, NUTATE_= 0, REFRACT_= 0, $
;                       ABERRATION_= 0, ALTITUDE= , /VERBOSE, _EXTRA= ]
;
; DESCRIPTION:
;  This is a nice code to calculate horizon (alt,az) coordinates from equatorial
;  (ra,dec) coords.   It is typically accurate to about 1 arcsecond or better (I
;  have checked the output against the publicly available XEPHEM software). It
;  performs precession, nutation, aberration, and refraction corrections.  The
;  perhaps best thing about it is that it can take arrays as inputs, in all
;  variables and keywords EXCEPT Lat, lon, and Altitude (the code assumes these
;  aren't changing), and uses vector arithmetic in every calculation except
;  when calculating the precession matrices.
;
; INPUT VARIABLES:
;       RA   : Right Ascension of object  (J2000) in degrees (FK5); scalar or
;              vector.
;       Dec  : Declination of object (J2000) in degrees (FK5), scalar or vector.
;       JD   : Julian Date [scalar or vector]
;
;       Note: if RA and DEC are arrays, then alt and az will also be arrays.
;             If RA and DEC are arrays, JD may be a scalar OR an array of the
;             same dimensionality.
;
; OPTIONAL INPUT KEYWORDS:
;       lat   : north geodetic latitude of location in degrees
;       lon   : EAST longitude of location in degrees (Specify west longitude
;               with a negative sign.)
;       /WS    : Set this to get the azimuth measured westward from south (not
;               East of North).
;       obsname: Set this to a valid observatory name to be used by the
;              astrolib OBSERVATORY procedure, which will return the latitude
;              and longitude to be used by this program.
;       /B1950 : Set this if your ra and dec are specified in B1950, FK4
;              coordinates (instead of J2000, FK5)
;       precess_ : Set this to 1 to force precession [default], 0 for no
;               precession correction
;       nutate_  : Set this to 1 to force nutation [default], 0 for no nutation.
;       aberration_ : Set this to 1 to force aberration correction [default],
;                     0 for no correction.
;       refract_ : Set to 1 to force refraction correction [default], 0 for no
;                     correction.
;       altitude: The altitude of the observing location, in meters. [default=0].
;       verbose: Set this for verbose output.  The default is verbose=0.
;       _extra: This is for setting TEMPERATURE or PRESSURE explicity, which are
;               used by CO_REFRACT to calculate the refraction effect of the
;               atmosphere. If you don't set these, the program will make an
;               intelligent guess as to what they are (taking into account your
;               altitude).  See CO_REFRACT for more details.
;
; OUTPUT VARIABLES: (all double precision)
;       alt    : altitude (in degrees)
;       az     : azimuth angle (in degrees, measured EAST from NORTH, but see
;                keyword WS above.)
;       ha     : hour angle (in degrees) (optional)
;
; DEPENDENCIES:
;       NUTATE, PRECESS, OBSERVATORY, SUNPOS, ADSTRING() (from the astrolib)
;       CO_NUTATE, CO_ABERRATION, CO_REFRACT, ALTAZ2HADEC
;
; BASIC STEPS
;   Apply refraction correction to find apparent Alt.
;   Calculate Local Mean Sidereal Time
;   Calculate Local Apparent Sidereal Time
;   Do Spherical Trig to find apparent hour angle, declination.
;   Calculate Right Ascension from hour angle and local sidereal time.
;   Nutation Correction to Ra-Dec
;   Aberration correction to Ra-Dec
;       Precess Ra-Dec to current equinox.
;
;
;CORRECTIONS I DO NOT MAKE:
;   *  Deflection of Light by the sun due to GR. (typically milliarcseconds,
;        can be arseconds within one degree of the sun)
;   *  The Effect of Annual Parallax (typically < 1 arcsecond)
;   *  and more (see below)
;
; TO DO
;    * Better Refraction Correction.  Need to put in wavelength dependence,
;    and integrate through the atmosphere.
;        * Topocentric Parallax Correction (will take into account elevation of
;          the observatory)
;    * Proper Motion (but this will require crazy lookup tables or something).
;        * Difference between UTC and UT1 in determining LAST -- is this
;          important?
;        * Effect of Annual Parallax (is this the same as topocentric Parallax?)
;    * Polar Motion
;        * Better connection to Julian Date Calculator.
;
; EXAMPLE
;
;  Find the position of the open cluster NGC 2264 at the Effelsburg Radio
;  Telescope in Germany, on June 11, 2023, at local time 22:00 (METDST).
;  The inputs will then be:
;
;       Julian Date = 2460107.250
;       Latitude = 50d 31m 36s
;       Longitude = 06h 51m 18s
;       Altitude = 369 meters
;       RA (J2000) = 06h 40m 58.2s
;       Dec(J2000) = 09d 53m 44.0s
;
;  IDL> eq2hor, ten(6,40,58.2)*15., ten(9,53,44), 2460107.250d, alt, az, $
;               lat=ten(50,31,36), lon=ten(6,51,18), altitude=369.0, /verb, $
;                pres=980.0, temp=283.0
;
; The program produces this output (because the VERBOSE keyword was set)
;
; Latitude = +50 31 36.0   Longitude = +06 51 18.0
; Julian Date =  2460107.250000
; Ra, Dec:  06 40 58.2  +09 53 44.0   (J2000)
; Ra, Dec:  06 42 15.7  +09 52 19.2   (J2023.4422)
; Ra, Dec:  06 42 13.8  +09 52 26.9   (fully corrected)
; LMST = +11 46 42.0
; LAST = +11 46 41.4
; Hour Angle = +05 04 27.6  (hh:mm:ss)
; Az, El =  17 42 25.6  +16 25 10.3   (Apparent Coords)
; Az, El =  17 42 25.6  +16 28 22.8   (Observer Coords)
;
; Compare this with the result from XEPHEM:
; Az, El =  17h 42m 25.6s +16d 28m 21s
;
; This 1.8 arcsecond discrepancy in elevation arises primarily from slight
; differences in the way I calculate the refraction correction from XEPHEM, and
; is pretty typical.
;
; AUTHOR:
;   Chris O'Dell
;       Univ. of Wisconsin-Madison
;   Observational Cosmology Laboratory
;   Email: odell@cmb.physics.wisc.edu

; NAME:
;       EQPOLE
; PURPOSE:
;       Convert RA and Dec to X,Y using an equal-area polar projection.
; EXPLANATION:
;       The output X and Y coordinates are scaled to be between
;       -90 and +90 to go from equator to pole to equator. Output map points 
;       can be centered on the north pole or south pole.
;
; CALLING SEQUENCE:
;       EQPOLE, L, B, X, Y, [ /SOUTHPOLE ]
;
; INPUTS:
;       L - longitude - scalar or vector, in degrees
;       B - latitude - same number of elements as RA, in degrees
;
; OUTPUTS:
;       X - X coordinate, same number of elements as RA.   X is normalized to
;               be between -90 and 90.
;       Y - Y coordinate, same number of elements as DEC.  Y is normalized to
;               be between -90 and 90.
;
; KEYWORDS:
;
;       /SOUTHPOLE      - Keyword to indicate that the plot is to be centered 
;               on the south pole instead of the north pole.
;
; REVISION HISTORY:
;       J. Bloch        LANL, SST-9     1.1     5/16/91
;       Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;       EQPOLE_GRID
;
; PURPOSE:
;       Produce an equal area polar projection grid overlay
; EXPLANATION:
;       Grid is written on the current graphics device using the equal area 
;       polar projection.   EQPOLE_GRID assumes that the output plot 
;       coordinates span the x and y ranges of -90 to 90 for a region that 
;       covers the equator to the chosen pole. The grid is assumed to go from 
;       the equator to the chosen pole.
;
; CALLING SEQUENCE:
;
;       EQPOLE_GRID[,DLONG,DLAT,[/SOUTHPOLE, LABEL = , /NEW, _EXTRA=]
;
; INPUTS:
;
;       DLONG   = Optional input longitude line spacing in degrees. If left
;                 out, defaults to 30.
;       DLAT    = Optional input lattitude line spacing in degrees. If left
;                 out, defaults to 30.
;
; INPUT KEYWORDS:
;
;       /SOUTHPOLE       = Optional flag indicating that the output plot is
;                         to be centered on the south rather than the north
;                         pole.
;       LABEL           = Optional flag for creating labels on the output
;                         grid on the prime meridian and the equator for
;                         lattitude and longitude lines. If set =2, then
;                         the longitude lines are labeled in hours and minutes.
;       CHARSIZE       = If /LABEL is set, then CHARSIZE specifies the size
;                         of the label characters (passed to XYOUTS)
;       CHARTHICK     =  If /LABEL is set, then CHARTHICK specifies the 
;                         thickness of the label characters (passed to XYOUTS)
;       /NEW          =   If this keyword is set, then EQPOLE_GRID will create
;                         a new plot, rather than overlay an existing plot.
;
;       Any valid keyword to OPLOT such as COLOR, LINESTYLE, THICK can be 
;       passed to AITOFF_GRID (though the _EXTRA facility) to to specify the
;       color, style, or thickness of the grid lines.
; OUTPUTS:
;       Draws grid lines on current graphics device.
;
; EXAMPLE:
;       Create a labeled equal area projection grid of the Galaxy, centered on
;       the South pole, and overlay stars at specified Galactic longitudes, 
;       glong and latitudes, glat
;
;       IDL> eqpole_grid,/label,/new,/south       ;Create labeled grid
;       IDL> eqpole, glong, glat, x,y      ;Convert to X,Y coordinates
;       IDL> plots,x,y,psym=2              ;Overplot "star" positions.
;
;
; COPYRIGHT NOTICE:
;
;       Copyright 1992, The Regents of the University of California. This
;       software was produced under U.S. Government contract (W-7405-ENG-36)
;       by Los Alamos National Laboratory, which is operated by the
;       University of California for the U.S. Department of Energy.
;       The U.S. Government is licensed to use, reproduce, and distribute
;       this software. Neither the Government nor the University makes
;       any warranty, express or implied, or assumes any liability or
;       responsibility for the use of this software.
;
; AUTHOR AND MODIFICATIONS:
;
;       J. Bloch        1.4     10/28/92
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Create default plotting coords, if needed   W. Landsman  August 2000
;       Added _EXTRA, CHARTHICK, CHARSIZE keywords  W. Landsman  March 2001

; NAME:
;     EULER
; PURPOSE:
;     Transform between Galactic, celestial, and ecliptic coordinates.
; EXPLANATION:
;     Use the procedure ASTRO to use this routine interactively
;
; CALLING SEQUENCE:
;      EULER, AI, BI, AO, BO, [ SELECT, /FK4, SELECT = ] 
;
; INPUTS:
;       AI - Input Longitude in DEGREES, scalar or vector.  If only two 
;               parameters are supplied, then  AI and BI will be modified to 
;               contain the output longitude and latitude.
;       BI - Input Latitude in DEGREES
;
; OPTIONAL INPUT:
;       SELECT - Integer (1-6) specifying type of coordinate transformation.  
;
;      SELECT   From          To        |   SELECT      From            To
;       1     RA-Dec (2000)  Galactic   |     4       Ecliptic      RA-Dec    
;       2     Galactic       RA-DEC     |     5       Ecliptic      Galactic  
;       3     RA-Dec         Ecliptic   |     6       Galactic      Ecliptic  
;
;      If not supplied as a parameter or keyword, then EULER will prompt for 
;      the value of SELECT
;      Celestial coordinates (RA, Dec) should be given in equinox J2000 
;      unless the /FK4 keyword is set.
; OUTPUTS:
;       AO - Output Longitude in DEGREES
;       BO - Output Latitude in DEGREES
;
; INPUT KEYWORD:
;       /FK4 - If this keyword is set and non-zero, then input and output 
;             celestial and ecliptic coordinates should be given in equinox 
;             B1950.
;       /SELECT  - The coordinate conversion integer (1-6) may alternatively be 
;              specified as a keyword
; NOTES:
;       EULER was changed in December 1998 to use J2000 coordinates as the 
;       default, ** and may be incompatible with earlier versions***.
; REVISION HISTORY:
;       Written W. Landsman,  February 1987
;       Adapted from Fortran by Daryl Yentis NRL
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Made J2000 the default, added /FK4 keyword  W. Landsman December 1998
;       Add option to specify SELECT as a keyword W. Landsman March 2003

; NAME:
;      EXPAND_TILDE()
;               
; PURPOSE: 
;       Expand tilde in UNIX directory names
;               
; CALLING SEQUENCE: 
;       IDL> output=expand_tilde(input)
;    
; INPUTS: 
;       INPUT = input file or directory name, scalar string
;
; OUTPUT:
;       Returns expanded filename, scalar string
;               
; EXAMPLES: 
;       output=expand_tilde('~zarro/test.doc')
;               ---> output='/usr/users/zarro'
;
; NOTES:
;       This version of EXPAND_TILDE differs from the version in the Solar
;       Library in that it does not call the functions EXIST and IDL_RELEASE.
;       However, it should work identically.
; PROCEDURE CALLS:
;       None.
; REVISION HISTORY: 
;       Version 1,  17-Feb-1997,  D M Zarro.  Written
;       Transfered from Solar Library   W. Landsman   Sep. 1997
;       Made more robust  D. Zarro/W. Landsman  Sep. 2000
;       Made even more robust (since things like ~zarro weren't being expanded)
;       Zarro (EITI/GSFC, Mar 2001)

; NAME:
;     EXTAST
; PURPOSE:
;     Extract ASTrometry parameters from a FITS image header.
; EXPLANATION:
;     The astrometry in the header can be in either CD (Coordinate
;     description) format, or CROTA and CDELT (AIPS-type) format.
;     However, the output astrometry will always be in CD format.
;
; 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)
;      .CD   -  2 x 2 array containing the astrometry parameters CD1_1 CD1_2
;               in DEGREES/PIXEL                                 CD2_1 CD2_2
;      .CDELT - 2 element vector giving physical increment at reference pixel
;      .CRPIX - 2 element vector giving X and Y coordinates of reference pixel
;               (def = NAXIS/2) in FITS convention (first pixel is 1,1)
;      .CRVAL - 2 element double precision vector giving R.A. and DEC of 
;             reference pixel in DEGREES
;      .CTYPE - 2 element string vector giving projection types, default
;             ['RA---TAN','DEC--TAN']
;      .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)
;      .PROJP1 - Scalar parameter needed in some projections, FITS keyword PV2_1
;      .PROJP2 - Scalar parameter needed in some projections, FITS keyword PV2_2
;
;       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.    
;             3 = Success - Header contains PCn_m + CDELT astrometry. As of
;                           December 2001, this is the recommended format 
;             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.
; 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 Griesen 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
;      Written by B. Boothman 4/15/86
;      Accept CD001001 keywords               1-3-88
;      Accept CD1_1, CD2_1... keywords    W. Landsman    Nov. 92
;      Recognize GSSS FITS header         W. Landsman    June 94
;      Converted to IDL V5.0   W. Landsman   September 1997
;      Get correct sign, when converting CDELT* to CD matrix for right-handed
;      coordinate system                  W. Landsman   November 1998
;      Consistent conversion between CROTA and CD matrix  October 2000
;      CTYPE = 'PIXEL' means no astrometry params  W. Landsman January 2001
;      Don't choke if only 1 CTYPE value given W. Landsman  August 2001
;      Recognize PC00n00m keywords again (sigh...)  W. Landsman December 2001
;      Recognize GSSS in ctype also       D. Finkbeiner Jan 2002
;      Introduce ALT keyword              W. Landsman June 2003
;      Fix error introduced June 2003 where free-format values would be
;      truncated if more than 20 characters.  W. Landsman Aug 2003
;      Further fix to free-format values -- slash need not be present Sep 2003

; NAME:
;	EXTGRP
; PURPOSE:
;	Extract the group parameter information out of SXREAD output
; EXPLANATION:
;	This procedure extracts the group parameter information out of a 
;	header and parameter variable obtained from SXREAD.  This allows 
;	astrometry, photometry and other parameters to be easily SXPARed by 
;	conventional methods and allows the image and header to be saved in 
;	a SIMPLE format.
;
; CALLING SEQUENCE:
;	ExtGrp, hdr, par
;
; INPUT:
;	HDR - The header which is to be converted (input and output)
;	PAR - The Parameter string returned from a call to SXREAD
;
; OUTPUT:
;	HDR -  The converted header, string array
;
; OTHER PROCEDURES CALLED:
;	SXPAR(), SXADDPAR, SXGPAR(), STRN()
;
; HISTORY:
;	25-JUN-90 Version 1 written
;	13-JUL-92 Header finally added to this ancient procedure, code spiffed up
;	a bit.  Now 3 times faster.  Added PTYPE comment inclusion.  E. Deutsch
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;       FACTOR
; PURPOSE:
;       Find prime factors of a given number.
; CATEGORY:
; CALLING SEQUENCE:
;       factor, x, p, n
; INPUTS:
;       x = Number to factor (>1).       in
; KEYWORD PARAMETERS:
;       Keywords:
;         /QUIET  means do not print factors.
;         /DEBUG  Means list steps as they happen.
;         /TRY    Go beyond 20000 primes.
; OUTPUTS:
;       p = Array of prime numbers.      out
;       n = Count of each element of p.  out
; COMMON BLOCKS:
; NOTES:
;       Note: see also prime, numfactors, print_fact.
; MODIFICATION HISTORY:
;       R. Sterner.  4 Oct, 1988.
;       RES 25 Oct, 1990 --- converted to IDL V2.
;       R. Sterner, 1999 Jun 30 --- Improved (faster, bigger).
;       R. Sterner, 1999 Jul  7 --- Bigger values (used unsigned).
;       R. Sterner, 1999 Jul  9 --- Tried to make backward compatable.
;       R. Sterner, 2000 Jan 06 --- Fixed to ignore non-positive numbers.
;       Johns Hopkins University Applied Physics Laboratory.
;
; Copyright (C) 1988, 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.

; NAME:
;     FDECOMP
; PURPOSE:
;     Routine to decompose file name(s) for any operating system
; EXPLANATION:
;     A faster version of this procedure for V5.3 or later is available in 
;     http://idlastro.gsfc.nasa.gov/ftp/v53/fdecomp.pro
;
; CALLING SEQUENCE:
;     FDECOMP, filename, disk, dir, name, qual, version, [OSFamily = ]
;
; INPUT:
;     filename - string file name(s), scalar or vector
;
; OUTPUTS:
;     All the output parameters will have the same number of elements as 
;       input filename 
;
;       disk - disk name, always '' on a Unix machine, scalar or vector string
;       dir - directory name, scalar or vector string
;       name - file name, scalar or vector string 
;       qual - qualifier, set equal to the characters beyond the last "."
;       version - version number, always '' on a non-VMS machine
;
; OPTIONAL INPUT KEYWORD:
;     OSFamily - one of the four scalar strings specifying the operating 
;             system:  'vms','Windows','MacOS' or 'unix'.    If not supplied,
;             then !VERSION.OS_FAMILY is used to determine the OS.
; EXAMPLES:
;     Consider the following file names 
;
;     Unix:    file = '/rsi/idl40/avg.pro' 
;     VMS:     file = '$1$dua5:[rsi.idl40]avg.pro;3
;     Mac:     file = 'Macintosh HD:Programs:avg.pro'
;     Windows: file =  'd:\rsi\idl40\avg.pro'
;       
;     then IDL> FDECOMP,  file, disk, dir, name, qual, version
;       will return the following
;
;                 Disk             Dir          Name        Qual     Version
;       Unix:      ''            '/rsi/idl40/'  'avg'       'pro'       ''
;       VMS:     '$1$dua5'       '[RSI.IDL40]'  'avg'       'pro'       '3'
;       Mac:     'Macintosh HD'  ':Programs:'   'avg'       'pro'       ''
;       Windows:    'd:'         \rsi\idl40\    'avg'       'pro'       ''
;
; NOTES:
;     (1) All tokens are removed between
;           1) name and qual  (i.e period is removed)
;           2) qual and ver   (i.e. VMS semicolon is removed)
;     (2) On VMS the filenames "MOTD" and "MOTD." are distinguished by the 
;         fact that qual = '' for the former and qual = ' ' for the latter.
;
;     A faster version of this procedure for V5.3 or later is available in 
;     http://idlastro.gsfc.nasa.gov/ftp/v53/fdecomp.pro
; ROUTINES CALLED:
;     Function GETTOK()
; HISTORY
;     version 1  D. Lindler  Oct 1986
;     Include VMS DECNET machine name in disk    W. Landsman  HSTX  Feb. 94
;     Converted to Mac IDL, I. Freedman HSTX March 1994          
;     Converted to IDL V5.0   W. Landsman   September 1997
;     Allow vector file name input    W. Landsman   October 2002
;     Fixed bug in version parameter introduced October 2002 W. Landsman April03

; NAME:
;       FILTER_IMAGE
;
; PURPOSE:
;       Identical to MEDIAN or SMOOTH but handle edges and allow iterations.
; EXPLANATION:
;       Computes the average and/or median of pixels in moving box,
;       replacing center pixel with the computed average and/or median,
;       (using the IDL SMOOTH() or MEDIAN() functions).
;       The main reason for using this function is the options to
;       also process the pixels at edges and corners of image, and,
;       to apply iterative smoothing simulating convolution with Gaussian,
;       and/or to convolve image with a Gaussian kernel.
;
; CALLING SEQUENCE:
;       Result = filter_image( image, SMOOTH=width, MEDIAN = width, /ALL_PIXELS
;                               /ITERATE, FWHM =,  /NO_FT_CONVOL)
;
; INPUT:
;       image = 2-D array (matrix)
;
; OPTIONAL INPUT KEYWORDS:
;       SMOOTH = scalar (odd) integer specifying the width of a square box 
;               for moving average, in # pixels.  /SMOOTH  means use box 
;               width = 3 pixels for smoothing.
;
;        MEDIAN = scalar (usually odd) integer specifying the width of square 
;               moving box for median filter, in # pixels.   /MEDIAN  means use
;               box width = 3 pixels for median filter.
;   
;       /ALL_PIXELS causes the edges of image to be filtered as well.   This
;               is accomplished by reflecting pixels adjacent to edges outward
;               (similar to the /EDGE_WRAP keyword in CONVOL).
;               Note that this is a different algorithm from the /EDGE_TRUCATE 
;               keyword to SMOOTH or CONVOL, which duplicates the nearest pixel.   
;
;       /ITERATE means apply smooth(image,3) iteratively for a count of
;               (box_width-1)/2 times (=radius), when box_width >= 5.
;               This is equivalent to convolution with a Gaussian PSF
;               of FWHM = 2 * sqrt( radius ) as radius gets large.
;               Note that /ALL_PIXELS is automatically applied,
;               giving better results in the iteration limit.
;               (also, MEDIAN keyword is ignored when /ITER is specified).
;
;       FWHM_GAUSSIAN = Full-width half-max of Gaussian to convolve with image. 
;                       FWHM can be a single number (circular beam),
;                       or 2 numbers giving axes of elliptical beam.
;
;       /NO_FT_CONVOL causes the convolution to be computed directly,
;               with intrinsic IDL CONVOL function.   The default is to use 
;               FFT when factors of size are all LE 13.   Note that 
;               external function convolve.pro handles both cases)
;
; OPTIONAL INPUT/OUTPUT KEYWORD:
;     PSF = Array containing the PSF used during the convolution.   This 
;           keyword is only active if the FWHM_GAUSSIAN keyword is also 
;           specified.     If PSF is undefined on input, then upon output it
;           contains the Gaussian convolution specified by the FWHM_GAUSSIAN
;           keyword.    If the PSF array is defined on input then it is used 
;           as the convolution kernel,  the value of the  FWHM_GAUSSIAN keyword
;           is ignored.      Typically, on a first call set PSF to an undefined
;           variable, which can be reused for subsequent calls to prevent 
;           recalculation of the Gaussian PSF.
; RESULT:
;       Function returns the smoothed, median filtered, or convolved image.
;       If both SMOOTH and MEDIAN are specified, median filter is applied first.
;
; EXAMPLES:
;       To apply 3x3 moving median filter and
;       then 3x3 moving average, both applied to all pixels:
;
;               Result = filter_image( image, /SMOOTH, /MEDIAN, /ALL )
;
;       To iteratively apply 3x3 moving average filter for 4 = (9-1)/2 times,
;       thus approximating convolution with Gaussian of FWHM = 2*sqrt(4) = 4 :
;
;               Result = filter_image( image, SMOOTH=9, /ITER )
;
;       To convolve all pixels with Gaussian of FWHM = 3.7 x 5.2 pixels:
;
;               Result = filter_image( image, FWHM=[3.7,5.2], /ALL )
;
; EXTERNAL CALLS:
;       function psf_gaussian
;       function convolve
;       pro factor
;       function prime          ;all these called only if FWHM is specified
;
; PROCEDURE:
;       If both /ALL_PIXELS (or /ITERATE)  keywords are set then
;       create a larger image by reflecting the edges outward, then call the 
;       IDL MEDIAN() or SMOOTH() function on the larger image, and just return 
;       the central part (the original size image).
;
;       NAN values are recognized during calls to MEDIAN() or SMOOTH(), but 
;       not for convolution with a Gaussian (FWHM keyword supplied). 
; HISTORY:
;       Written, 1991, Frank Varosi, NASA/GSFC.
;       FV, 1992, added /ITERATE option.
;       FV, 1993, added FWHM_GAUSSIAN= option.
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Use /EVEN call to median, recognize NAN values in SMOOTH 
;                  W. Landsman   June 2001
;       Added PSF keyword,   Bjorn Heijligers/WL, September 2001

; NAME:
;	FIND
; PURPOSE:
;	Find positive brightness perturbations (i.e stars) in an image 
; EXPLANATION:
;	Also returns centroids and shape parameters (roundness & sharpness).
;	Adapted from 1986 STSDAS version of DAOPHOT.
;
; CALLING SEQUENCE:
;	FIND, image, [ x, y, flux, sharp, round, hmin, fwhm, roundlim, sharplim 
;		PRINT= , /SILENT ]
;
; INPUTS:
;	image - 2 dimensional image array (integer or real) for which one
;		wishes to identify the stars present
;
; OPTIONAL INPUTS:
;	FIND will prompt for these parameters if not supplied
;
;	hmin -  Threshold intensity for a point source - should generally 
;		be 3 or 4 sigma above background
;	fwhm  - FWHM to be used in the convolve filter
;	sharplim - 2 element vector giving low and high cutoff for the
;		sharpness statistic (Default: [0.2,1.0] ).   Change this
;		default only if the stars have siginificantly larger or 
;		or smaller concentration than a Gaussian
;	roundlim - 2 element vector giving low and high cutoff for the
;		roundness statistic (Default: [-1.0,1.0] ).   Change this 
;		default only if the stars are significantly elongated.
;
; OPTIONAL INPUT KEYWORDS:
;	SILENT - Normally, FIND will write out each star that meets all
;		selection criteria.   If the SILENT keyword is set and 
;		non-zero, then this printout is suppressed.
;	PRINT - if set and non-zero then T_FIND will also write its results to
;		a file find.prt.   Also one can specify a different output file 
;		name by setting PRINT = 'filename'.
;
; OPTIONAL OUTPUTS:
;	x - vector containing x position of all stars identified by FIND
;	y-  vector containing y position of all stars identified by FIND
;	flux - vector containing flux of identified stars as determined
;		by a gaussian fit.  Fluxes are NOT converted to magnitudes.
;	sharp - vector containing sharpness statistic for identified stars
;	round - vector containing roundness statistic for identified stars
;
; NOTES:
;	The sharpness statistic compares the central pixel to the mean of the
;	surrounding pixels.   If this difference is greater than the originally
;	estimated height of the Gaussian or less than 0.2 the height of the
;	Gaussian (for the default values of SHARPLIM) then the star will be
;	rejected. 
;
; PROCEDURE CALLS:
;	GETOPT
; REVISION HISTORY:
;	Written W. Landsman, STX  February, 1987
;	ROUND now an internal function in V3.1   W. Landsman July 1993
;	Change variable name DERIV to DERIVAT    W. Landsman Feb. 1996
;	Use /PRINT keyword instead of TEXTOUT    W. Landsman May  1996
;	Changed loop indices to type LONG       W. Landsman Aug. 1997
;	Converted to IDL V5.0   W. Landsman   September 1997
;       Replace DATATYPE() with size(/TNAME)   W. Landsman Nov. 2001
;       Fix problem when PRINT= filename   W. Landsman   October 2002

; NAME:
;     FINDPRO
; PURPOSE:
;     Find all locations of a procedure in the IDL !PATH
; EXPLANATION:
;     FINDPRO searces for the procedure name (as a .pro or a .sav file) in all 
;     IDL libraries or directories given in the !PATH system variable.  
;               
; CALLING SEQUENCE:
;    FINDPRO, [ Proc_Name, /NoPrint, DirList = , ProList = ]
;
; OPTIONAL INPUT:
;     Proc_Name - Character string giving the name of the IDL procedure or 
;             function. Do not include the ".pro" extension. If Proc_Name is
;             omitted, the program will prompt for PROC_NAME.  "*" wildcards
;             are permitted.

; OPTINAL KEYWORD INPUT:
;     /NoPrint - if set, then the file's path is not printed on the screen and
;             absolutely no error messages are printed on the screen.  If not
;             set, then - since the MESSAGE routine is used - error messages 
;             will be printed but the printing of informational messages
;             depends on the value of the !Quiet variable.
;
; OPTIONAL KEYWORD OUTPUTS:
;     DirList - The directories in which the file is located are returned in
;             the keyword as a string array.
;             If the procedure was found in a VMS text library, then the
;             full path and name of that library is returned and is prefixed
;             by an "@" sign as a flag that it is a library, not a directory.
;             If the procedure is an intrinsic IDL procedure, then the 
;             value of DirList = ['INTRINSIC'].
;             If the procedure is not found, the value of DirList = [''].
;     ProList - The list (full pathnames) of procedures found.  Useful if you
;             are looking for the name of a procedure using wildcards.
;
;     The order of the names in DirList and ProList is identical to the order
;     in which the procedure name appears in the !PATH
; PROCEDURE:
;     The system variable !PATH is parsed using EXPAND_PATH into individual 
;     libraries or directories.   Each library or directory is then 
;     searched for the procedure name.  If not found in !PATH, then the 
;     the name is compared with the list of intrinsic IDL procedures given
;     by the ROUTINE_INFO function. 
;
; EXAMPLE:
;     (1) Find the procedure CURVEFIT.  Assume for this example that the user
;     also has a copy of the CURVEFIT.PRO procedure in her home directory
;     on a Unix machine.
;
;       IDL> findpro, 'curvefit', DIRLIST=DirList
;       Procedure curvefit.pro found in directory  .
;       Procedure curvefit.pro found in directory  /home/idl/lib/userlib 
;       IDL> help, DirList
;       DIRLIST         STRING    = Array(2) 
;       IDL> help, DirList(0), DirList(1)
;           STRING    = '.'
;           STRING    = '/home/idl/lib/userlib' 
;
;     (2) Find all procedures in one's !path containing the characters "zoom" 
;
;       IDL> findpro,'*zoom*'
; RESTRICTIONS:
;       User will be unable to find a path for a native IDL function
;       or procedure, or for a FORTRAN or C routine added with CALL_EXTERNAL.
;       Remember that Unix is case sensitive, and most procedures will be in
;       lower case.
;
; PROCEDURES USED:
;       ZPARCHECK, FDECOMP, UNIQ()
; REVISION HISTORY:
;       Based on code extracted from the GETPRO procedure, J. Parker 1994
;       Use the intrinsic EXPAND_PATH function    W. Landsman Nov. 1994
;       Use ROUTINE_NAMES() to check for intrinsic procs   W. Landsman Jul 95
;       Added Macintosh, WINDOWS compatibility    W. Landsman   Sep. 95
;       Removed spurious first element in PROLIST  W. Landsman  March 1997
;       Don't include duplicate directories  in !PATH  WL   May 1997
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Use ROUTINE_INFO instead of undocumented ROUTINE_NAMES W.L. October 1998
;       Also check for save sets   W. Landsman  October 1999 
;       Force lower case check for VMS  W. Landsman January 2000 
;       Only return .pro or .sav files in PROLIST   W. Landsman  January 2002 
;       Force lower case check for .pro and .sav    D. Swain  September 2002 
;

; NAME:
;       FIND_ALL_DIR()
; PURPOSE:
;       Finds all directories under a specified directory.
; EXPLANATION:
;       This routine finds all the directories in a directory tree when the
;       root of the tree is specified.  This provides the same functionality as
;       having a directory with a plus in front of it in the environment
;       variable IDL_PATH.
;
;       Users with Windows OS and V5.2 or earlier should see the warning below.
; CALLING SEQUENCE:
;       Result = FIND_ALL_DIR( PATH )
;
;               PATHS = FIND_ALL_DIR('+mypath', /PATH_FORMAT)
;               PATHS = FIND_ALL_DIR('+mypath1:+mypath2')
;
; INPUTS:
;       PATH    = The path specification for the top directory in the tree.
;               Optionally this may begin with the '+' character but the action
;               is the same unless the PLUS_REQUIRED keyword is set.
;
;               One can also path a series of directories separated
;               by the correct character ("," for VMS, ":" for Unix)
;
; OUTPUTS:
;       The result of the function is a list of directories starting from the
;       top directory passed and working downward from there.   Normally, this
;       will be a string array with one directory per array element, but if
;       the PATH_FORMAT keyword is set, then a single string will be returned,
;       in the correct format to be incorporated into !PATH.
;
; OPTIONAL INPUT KEYWORDS:
;       PATH_FORMAT     = If set, then a single string is returned, in
;                                 the format of !PATH.
;
;       PLUS_REQUIRED   = If set, then a leading plus sign is required
;                       in order to expand out a directory tree.
;                       This is especially useful if the input is a
;                       series of directories, where some components
;                       should be expanded, but others shouldn't.
;
;       RESET   = Often FIND_ALL_DIR is used with logical names.  It
;               can be rather slow to search through these subdirectories.
;               The /RESET keyword can be used to redefine an environment
;               variable so that subsequent calls don't need to look for the
;               subdirectories.
;
;               To use /RESET, the PATH parameter must contain the name of a
;               *single* environment variable.  For example
;
;                               setenv,'FITS_DATA=+/datadisk/fits'
;                               dir = find_all_dir('FITS_DATA',/reset,/plus)
;
;               The /RESET keyword is usually combined with /PLUS_REQUIRED.
;
; PROCEDURE CALLS:
;       DEF_DIRLIST, FIND_WITH_DEF(), BREAK_PATH()
;
; RESTRICTIONS:
;       PATH must point to a directory that actually exists.
;
;       On VMS computers this routine calls a command file, FIND_ALL_DIR.COM
;       (available only on VMS distribution) to find the directories.  This
;       command file must be in one of the directories in IDL's standard search
;       path, !PATH.
;
;       In order to use this procedure on Windows in IDL V5.2 or earlier, you 
;       must obtain the procedure find_wind_dir.pro and supporting procedures
;       from the Solar library 
;
; REVISION HISTORY:
;               Version 11, Zarro (SM&A/GSFC), 23-March-00
;                       Removed all calls to IS_DIR
;		Version 12, William Thompson, GSFC, 02-Feb-2001
;			In Windows, use built-in expand_path if able.
;		Version 13, William Thompson, GSFC, 23-Apr-2002
;			Follow logical links in Unix
;			(Suggested by Pascal Saint-Hilaire)
;
; Version     :	Version 13

; NAME: 
;     FIND_WITH_DEF()
; PURPOSE: 
;     Searches for files with a default path and extension.
; EXPLANATION:
;     Finds files using default paths and extensions, similar to using the
;     DEFAULT keyword with the OPEN statement in VMS.  Using this routine
;     together with environment variables allows an OS-independent approach
;     to finding files.
; CALLING SEQUENCE: 
;     Result = FIND_WITH_DEF( FILENAME, PATHS  [, EXTENSIONS ] )
;
; INPUTS: 
;     FILENAME   = Name of file to be searched for.  It may either be a
;                    complete filename, or the path or extension could be left
;                    off, in which case the routine will attempt to find the
;                    file using the default paths and extensions.
;
;     PATHS      = One or more default paths to use in the search in case
;                    FILENAME does not contain a path itself.  The individual
;                    paths are separated by commas, although in UNIX, colons
;                    can also be used.  In other words, PATHS has the same
;                    format as !PATH, except that commas can be used as a
;                    separator regardless of operating system.  The current
;                    directory is always searched first, unless the keyword
;                    NOCURRENT is set.
;
;                    A leading $ can be used in any path to signal that what
;                    follows is an environmental variable, but the $ is not
;                    necessary.  (In VMS the $ can either be part of the path,
;                    or can signal logical names for compatibility with Unix.)
;                    Environmental variables can themselves contain multiple
;                    paths.
;
; OPTIONAL INPUTS: 
;     EXTENSIONS = One or more extensions to append to end of filename if the
;                    filename does not contain one (e.g. ".dat").  The period
;                    is optional.  Multiple extensions can be separated by
;                    commas or colons.
; OUTPUTS: 
;     The result of the function is the name of the file if successful, or
;     the null string if unsuccessful.
; OPTIONAL INPUT KEYWORDS: 
;     NOCURRENT = If set, then the current directory is not searched.
;
;      RESET      = The FIND_WITH_DEF routine supports paths which are
;                    preceeded with the plus sign to signal that all
;                    subdirectories should also be searched.  Often this is
;                    used with logical names.  It can be rather slow to search
;                    through these subdirectories.  The /RESET keyword can be
;                    used to redefine an environment variable so that
;                    subsequent calls don't need to look for the
;                    subdirectories.
;
;                    To use /RESET, the PATHS parameter must contain the name
;                    of a *single* environment variable.  For example
;
;                     setenv,'FITS_DATA=+/datadisk/fits'
;                     file = find_with_def('test.fits','FITS_DATA',/reset)
;
; EXAMPLE:
;
;       FILENAME = ''
;       READ, 'File to open: ', FILENAME
;       FILE = FIND_WITH_DEF( FILENAME, 'SERTS_DATA', '.fix' )
;       IF FILE NE '' THEN ...
;
;
; PROCEDURE CALLS: 
;       BREAK_PATH(), FIND_ALL_DIR()
; REVISION HISTORY: 
;       Version 1, William Thompson, GSFC, 3 May 1993.
;               Removed trailing / and : characters.
;               Fixed bugs
;               Allow for commas within values of logical names.
;               Added keyword NOCURRENT.
;               Changed to call BREAK_PATH
;       Version 2, William Thompson, GSFC, 3 November 1994
;               Made EXTENSIONS optional.
;       Version 3, William Thompson, GSFC, 30 April 1996
;               Call FIND_ALL_DIR to resolve any plus signs.
;       Version 4, S.V. Haugan, UiO, 5 June 1996
;               Using OPENR,..,ERROR=ERROR to avoid an IDL 3.6
;               internal nesting error.
;       Version 5, R.A. Schwartz, GSFC, 11 July 1996
;               Use SPEC_DIR to interpret PATH under VMS
;       Version 6, William Thompson, GSFC, 5 August 1996
;               Took out call to SPEC_DIR (i.e., reverted to version 4).  The
;               use of SPEC_DIR was required to support logical names defined
;               via SETLOG,/CONFINE.  However, it conflicted with the ability
;               to use logical names with multiple values.  Removing the
;               /CONFINE made it unnecessary to call SPEC_DIR in this routine.
;       Version 7, William Thompson, GSFC, 6 August 1996
;               Added keyword RESET
;       Converted to IDL V5.0   W. Landsman   October 1997
;       Use STRTRIM instead of TRIM,   W. Landsman   November 1998
;       Use STRSPLIT instead of STR_SEP(), V5.3 or later W.L.   July 2002

; NAME:
;       FITEXY
; PURPOSE:
;       Best straight-line fit to data with errors in both coordinates
; EXPLANATION:
;       Linear Least-squares approximation in one-dimension (y = a + b*x),
;               when both x and y data have errors
;
; CALLING EXAMPLE:
;       FITEXY, x, y, A, B, X_SIG= , Y_SIG= , [sigma_A_B, chi_sq, q, TOL=]
;
; INPUTS:
;       x = array of values for independent variable.
;       y = array of data values assumed to be linearly dependent on x.
;
; REQUIRED INPUT KEYWORDS:
;       X_SIGMA = scalar or array specifying the standard deviation of x data.
;       Y_SIGMA = scalar or array specifying the standard deviation of y data.
;
; OPTIONAL INPUT KEYWORD:
;       TOLERANCE = desired accuracy of minimum & zero location, default=1.e-3.
;
; OUTPUTS:
;       A_intercept = constant parameter result of linear fit,
;       B_slope = slope parameter, so that:
;                       ( A_intercept + B_slope * x ) approximates the y data.
; OPTIONAL OUTPUT:
;       sigma_A_B = two element array giving standard deviation of 
;                A_intercept and B_slope parameters, respectively.
;                The standard deviations are not meaningful if (i) the
;                fit is poor (see parameter q), or (ii) b is so large that
;                the data are consistent with a vertical (infinite b) line.
;                If the data are consistent with *all* values of b, then
;                sigma_A_B = [1e33,e33]  
;       chi_sq = resulting minimum Chi-Square of Linear fit, scalar
;       q - chi-sq probability, scalar (0-1) giving the probability that
;              a correct model would give a value equal or larger than the
;              observed chi squared.   A small value of q indicates a poor
;              fit, perhaps because the errors are underestimated.
;
; COMMON:
;       common fitexy, communicates the data for computation of chi-square.
;
; PROCEDURE CALLS:
;       CHISQ_FITEXY()            ;Included in this file
;       MINF_BRACKET, MINF_PARABOLIC, ZBRENT    ;In IDL Astronomy Library 
;       MOMENT(), CHISQR_PDF()     ;In standard IDL distribution
;
; PROCEDURE:
;       From "Numerical Recipes" column by Press and Teukolsky: 
;       in "Computer in Physics",  May, 1992 Vol.6 No.3
;       Also see the 2nd edition of the book "Numerical Recipes" by Press et al.
; MODIFICATION HISTORY:
;       Written, Frank Varosi NASA/GSFC  September 1992.
;       Now returns q rather than 1-q   W. Landsman  December 1992
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Use CHISQR_PDF, MOMENT instead of STDEV,CHI_SQR1 W. Landsman April 1998
;       Fixed typo for initial guess of slope, this error was nearly
;             always insignificant          W. Landsman   March 2000

; NAME:
;     FITSDIR 
; PURPOSE:
;     Display selected FITS keywords from the headers of FITS files.  
; EXPLANATION:
;     The values of either user-specified or default FITS keywords are 
;     displayed in either the primary header and/or the first extension header.
;     Unless the /NOSIZE keyword is set, the data size is also displayed.
;     The default keywords are as follows (with keywords in 2nd row used if
;     those in the first row not found, and the 3rd row if neither the keywords
;     in the first or second rows found:)
;
;     DATE-OBS     TELESCOP   OBJECT    EXPTIME       
;     TDATEOBS     TELNAME    TARGNAME  INTEG        ;First Alternative
;     DATE         OBSERVAT             EXPOSURE     ;Second Alternative
;                  INSTRUME             EXPTIM       ;Third Alternative
;
;      FITSDIR will also recognize gzip compressed files (must have a .gz 
;      extension).
; CALLING SEQUENCE:
;     FITSDIR , [ directory, TEXTOUT =, /FLAT, KEYWORDS=, /NOSIZE, /NoTELESCOPE
;                            ALT1_KEYWORDS= ,ALT2_KEYWORDS = ,ALT3_KEYWORDS =  
;
; OPTIONAL INPUT PARAMETERS:
;     DIRECTORY - Scalar string giving file name, disk or directory to be 
;             searched.   Wildcard file names are allowed.    Examples of 
;             valid names include 'iraf/*.fits' (Unix), d:\myfiles\f*.fits',
;             (Windows) or 'Macintosh HD:Files:*c0f.fits' (Macintosh).  
;            
; OPTIONAL KEYWORD INPUT PARAMETER
;      KEYWORDS - FITS keywords to display, as either a vector of strings or as
;                 a comma delimited scalar string, e.g.'testname,dewar,filter'
;                 If not supplied, then the default keywords are 'DATE-OBS',
;                 'TELESCOP','OBJECT','EXPTIME'
;      ALT1_KEYWORDS - A list (either a vector of strings or a comma delimited
;                 strings of alternative keywords to use if the default 
;                 KEYWORDS cannot be found.   By default, 'TDATEOBS', is the 
;                 alternative to DATE-OBS, 'TELNAME' for 'TELESCOP','TARGNAME'
;                 for 'OBJECT', and 'INTEG' for EXPTIME
;      ALT2_KEYWORDS - A list (either a vector of strings or a comma delimited
;                 strings of alternative keywords to use if neither KEYWORDS 
;                 nor ALT1_KEYWORDS can be found.    
;      ALT3_KEYWORDS - A list (either a vector of strings or a comma delimited
;                 strings of alternative keywords to use if neither KEYWORDS 
;                 nor ALT1_KEYWORDS nor ALT2_KEYWORDS can be found.    
;      /NOSIZE - if set then information about the image size is not displayed  
;      TEXTOUT - Controls output device as described in TEXTOPEN procedure
;               textout=1       TERMINAL using /more option
;               textout=2       TERMINAL without /more option
;               textout=3       .prt
;               textout=4       laser.tmp
;               textout=5       user must open file
;               textout=7       Append to existing .prt file
;               textout = filename (default extension of .prt)
;       /EXTEN - If set, then the first FITS extension is also checked for the
;                desired keywords.    
;       /NOTELESCOPE - If set, then if the default keywords are used, then the
;                TELESCOPE (or TELNAME, OBSERVAT, INSTRUME) keywords are omitted
;                to give more room for display other keywords.   The /NOTELESCOP
;                 keyword has no effect if the default keywords are not used.
; OUTPUT PARAMETERS:
;       None.
;
; EXAMPLES:  
;  (1) Print info on all'*.fits' files in the current  directory using default
;          keywords.   Include information from the extension header     
;       IDL> fitsdir,/exten
;
;  (2) Write a driver program to display selected keywords in HST/ACS drizzled
;       (*drz) images
;         pro acsdir
;        keywords = 'date-obs,targname,detector,filter1,filter2,exptime'
;        fitsdir,'*drz.fits',key=keywords,/exten
;        return & end
;
;   (3)  Write info on all *.fits files in the Unix directory /usr2/smith, to a 
;        file 'smith.txt' using the default keywords, but do not display the 
;        value of the TELESCOPE keyword
;
;       IDL> fitsdir ,'/usr2/smith/*.fits',t='smith.txt', /NoTel 
;
; PROCEDURE:
;       FINDFILE (or FILE_SEARCH if since V5.5) is used to find the specified 
;       FITS files.   The header of each file is read, and the selected 
;       keywords are extracted.   The formatting is adjusted so that no value 
;       is truncated on display.        
;
; SYSTEM VARIABLES:
;       TEXTOPEN (called by FITSDIR) will automatically define the following 
;       non-standard system variables if they are not previously defined:
;
;       DEFSYSV,'!TEXTOUT',1
;       DEFSYSV,'!TEXTUNIT',0
;
; PROCEDURES USED:
;       FDECOMP, FXMOVE, MRD_HREAD, REMCHAR,  SPEC_DIR(), 
;       TEXTOPEN, TEXTCLOSE
; MODIFICATION HISTORY:
;       Written, W. Landsman,  HSTX    February, 1993
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Search alternate keyword names    W.Landsman    October 1998
;       Avoid integer truncation for NAXISi >32767  W. Landsman  July 2000
;       Don't leave open unit    W. Landsman  July 2000 
;       Added EXTEN keyword, work with compressed files, additional alternate
;       keywords W. Landsman     December 2000
;       Don't assume floating pt. exposure time W. Landsman   September 2001
;       Major rewrite, KEYWORD & ALT*_KEYWORDS keywords, no truncation, 
;             /NOSIZE keyword     W. Landsman,  SSAI   August 2002
;       NAXIS* values must be integers W. Landsman SSAI  June 2003

; NAME:
;       FITSRGB_to_TIFF
; PURPOSE:
;       Combine separate red, green, and blue FITS images into TIFF format
; EXPLANATION:
;       The output TIFF (class R) file can have colors interleaved either
;       by pixel or image.  The colour mix is also adjustable.
;
; CALLING SEQUENCE:
;       FITSRGB_to_TIFF, path, rgb_files, tiff_name [,/BY_PIXEL, /PREVIEW,
;                         RED= , GREEN =, BLUE =]
;
; INPUTS:
;       path = file system directory path to the RGB files required.
;       rgb_files = string array with three components - the red FITS file
;                   filename, the blue FITS file filename and the green FITS
;                   file filename
;
; OUTPUTS:
;       tiff_name = string containing name of tiff file to be produced
;
; OPTIONAL OUTPUT:
;       Header = String array containing the header from the FITS file.
;
; OPTIONAL INPUT KEYWORDS:
;       BY_PIXEL = This causes TIFF file RGB to be interleaved by pixel
;                  rather than the default of by image.
;       PREVIEW  = Allows a 24 bit image to be displayed on the screen
;                  to check the colour mix.
;       RED = Real number containing the fractional mix of red
;       GREEN = Real number containing the fractional mix of green
;       BLUE = Real number containing the fractional mix of blue
;
; EXAMPLE:
;       Read three FITS files, 'red.fits', 'blue.fits' and 'green.fits' from
;       the directory '/data/images/space' and output a TIFF file named
;       'colour.tiff'
;
;               IDL> FITSRGB_to_TIFF, '/data/images/space', ['red.fits', $
;                    'blue.fits', 'green.fits'], 'colour.tiff'
;
;       Read three FITS files, 'red.fits', 'blue.fits' and 'green.fits' from
;       the current directory and output a TIFF file named '/images/out.tiff'
;       In this case, the red image is twice as strong as the green and the
;       blue is a third more intense.  A preview on screen is also wanted.
;
;               IDL> FITSRGB_to_TIFF, '.', ['red.fits', $
;                    'blue.fits', 'green.fits'], '/images/out.tiff', $
;                    /PREVIEW, RED=0.5, GREEN=1.0, BLUE=0.666
;
;
; RESTRICTIONS:
;       (1) Limited to the ability of the routine READFITS
;
; NOTES:
;       None
;
; PROCEDURES USED:
;     Functions:   READFITS, CONCAT_DIR
;     Procedures:  WRITE_TIFF
;
; MODIFICATION HISTORY:
;     16th January 1995 - Written by Carl Shaw, Queen's University Belfast
;	27 Jan 1995 - W. Landsman, Add CONCAT_DIR for VMS, Windows compatibility
;	Converted to IDL V5.0   W. Landsman   September 1997
;    Use WRITE_TIFF instead of obsolete TIFF_WRITE  W. Landsman  December 1998
;    Cosmetic changes  W. Landsman    February 2000

; NAME:
;    FITS_ADD_CHECKSUM
; PURPOSE:
;    Add or update the CHECKSUM and DATASUM keywords in a FITS header
; EXPLANATION: 
;     Follows the 23 May 2002 version of the FITS checksum proposal at 
;     http://heasarc.gsfc.nasa.gov/docs/heasarc/fits/checksum.html  
; CALLING SEQUENCE:
;     FITS_ADD_CHECKSUM, Hdr, [ Data, /No_TIMESTAMP, /FROM_IEEE ]
; INPUT-OUTPUT:
;     Hdr - FITS header (string array), it will be updated with new 
;           (or modfied) CHECKSUM and DATASUM keywords 
; OPTIONAL INPUT:
;     Data - data array associated with the FITS header.   If not supplied, or
;           set to a scalar, then the program checks whether there is a 
;           DATASUM keyword already in the FITS header containing the 32bit
;           checksum for the data.   if there is no such keyword then ther 
;           assumed to be no data array 
;           associated with the FITS header.
; OPTIONAL INPUT KEYWORDS:
;    /FROM_IEEE - If this keyword is set, then the input is assumed to be in 
;             big endian format (e.g. an untranslated FITS array).    This 
;             keyword only has an effect on little endian machines (e.g. 
;             a Linux box).
;    /No_TIMESTAMP - If set, then a time stamp is not included in the comment
;             field of the CHECKSUM and DATASUM keywords.   Unless the 
;             /No_TIMESTAMP keyword is set, repeated calls to FITS_ADD_CHECKSUM
;             with the same header and data will yield different values of 
;             CHECKSUM (as the date stamp always changes).   However, use of the
;             date stamp is recommended in the checksum proposal. 
; PROCEDURES USED:
;     CHECKSUM32, FITS_ASCII_ENCODE(), GET_DATE, SXADDPAR, SXPAR()
; REVISION HISTORY:
;     W. Landsman    SSAI    December 2002

; NAME:
;    FITS_ASCII_ENCODE()
; PURPOSE:
;    Encode an unsigned longword as an ASCII string to insert in a FITS header
; EXPLANATION:
;     Follows the 23 May 2002 version of the FITS checksum proposal at 
;     http://heasarc.gsfc.nasa.gov/docs/heasarc/fits/checksum.html   
; CALLING SEQUENCE:
;     result = FITS_ASCII_ENCODE( sum32)
; INPUTS:
;     sum32 - 32bit *unsigned longword* (e.g. as returned by CHECKSUM32)
; RESULT:
;     A 16 character scalar string suitable for the CHECKSUM keyword
; EXAMPLE:
;      A FITS header/data unit has a checksum of 868229149.  Encode the 
;      complement of this value (3426738146) into an ASCII string
;
;      IDL> print,FITS_ASCII_ENCODE(3426738146U)
;           ===> "hcHjjc9ghcEghc9g"
;
; METHOD:
;      The 32bit value is interpreted as a sequence of 4 unsigned 8 bit 
;      integers, and divided by 4.    Add an offset of 48b (ASCII '0'). 
;      Remove non-alphanumeric ASCII characters (byte values 58-64 and 91-96)
;      by simultaneously incrementing and decrementing the values in pairs.
;      Cyclicly shift the string one place to the right.
;                  
; REVISION HISTORY:
;     Written  W. Landsman  SSAI              December 2002

; NAME:
;    FITS_CD_FIX
;
; PURPOSE:
;    Update obsolete representations of the CD matrix in a FITS header   
;
; EXPLANATION:
;    According the paper, "Representations of Celestial Coordinates in FITS"
;    by Calabretta & Greisen (2002, A&A, 395, 1077, available at 
;    http://www.aoc.nrao.edu/~egreisen/) the rotation of an image from 
;    standard coordinates is represented by a coordinate description (CD) 
;    matrix.    The standard representation of the CD matrix are PCn_m 
;    keywords, but CDn_m keywords (which include the scale factors) are
;    also allowed.    However, earliers drafts of the standard allowed the
;    keywords forms CD00n00m and PC00n00m.      This procedure will convert
;    FITS CD matrix keywords containing zeros into the standard forms 
;    CDn_m and PCn_m containing only underscores.
;
; CALLING SEQUENCE:
;    FITS_CD_FIX, Hdr
;
; INPUT-OUTPUT: 
;       HDR - FITS header, 80 x N string array.   If the header does not
;           contain 'CD00n00m' or 'PC00n00m' keywords then it is left 
;           unmodified.  Otherwise, the keywords containing integers are
;           replaced with those containing underscores.
;   
; OPTIONAL KEYWORD INPUT
;      /REVERSE - this keyword does nothing, but is kept for compatiblity with
;            earlier versions.
; PROCEDURES USED:
;    SXADDPAR, SXDELPAR, SXPAR()
; REVISION HISTORY:
;    Written   W. Landsman             Feb 1990
;    Major rewrite                     Feb 1994
;    Converted to IDL V5.0   W. Landsman   September 1997
;    Use double precision formatting of CD matrix   W. Landsman  April 2000
;    Major rewrite to convert only to forms recognized by the Greisen
;       & Calabretta standard   W. Landsman   July 2003

; NAME:
;      FITS_CLOSE
;
;*PURPOSE:
;       Close a FITS data file
;
;*CATEGORY:
;       INPUT/OUTPUT
;
;*CALLING SEQUENCE:
;       FITS_CLOSE,fcb
;
;*INPUTS:
;       FCB: FITS control block returned by FITS_OPEN.
;
;*KEYWORD PARAMETERS:
;       /NO_ABORT: Set to return to calling program instead of a RETALL
;               when an I/O error is encountered.  If set, the routine will
;               return  a non-null string (containing the error message) in the
;               keyword MESSAGE.    (For backward compatibility, the obsolete 
;               system variable !ERR is also set to -1 in case of an error.)   
;               If /NO_ABORT not set, then FITS_CLOSE will print the message and
;               issue a RETALL
;       MESSAGE = value: Output error message
;       
;*EXAMPLES:
;       Open a FITS file, read some data, and close it with FITS_CLOSE
;
;               FITS_OPEN,'infile',fcb
;               FITS_READ,fcb,data
;               FITS_READ,fcb,moredata
;               FITS_CLOSE,fcb
;
;*HISTORY:
;       Written by:     D. Lindler      August, 1995
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Do nothing if fcb an invalid structure D. Schlegel/W. Landsman Oct. 2000
;       Return Message='' for to signal normal operation W. Landsman Nov. 2000

; NAME:
;	FITS_HELP
;
;*PURPOSE:
;	To print a summary of the primary data units and extensions in a
;	FITS file.
;
;*CATEGORY:
;	INPUT/OUTPUT
;
;*CALLING SEQUENCE:
;	FITS_HELP,filename_or_fcb
;
;*INPUTS:
;	FILENAME_OR_FCB - name of the fits file or the FITS Control Block (FCB)
;		returned by FITS_OPEN.     For versions since V5.3, the 
;               file name is allowed to be gzip compressed (with a .gz 
;               extension)
;
;*OUTPUTS:
;	a summary of the fits file is printed.	
;
;*EXAMPLES:
;	FITS_HELP,'myfile.fits'
;
;	FITS_OPEN,'anotherfile.fits',fcb
;	FITS_HELP,fcb
;
;*PROCEDURES USED:
;	FITS_OPEN, FITS_CLOSE
;*HISTORY:
;	Written by:	D. Lindler	August, 1995
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;     FITS_INFO
; PURPOSE:
;     Provide information about the contents of a FITS file
; EXPLANATION:
;     Information includes number of header records and size of data array.
;     Applies to primary header and all extensions.    Information can be 
;     printed at the terminal and/or stored in a common block
;
; CALLING SEQUENCE:
;     FITS_INFO, Filename, [ /SILENT , TEXTOUT = , N_ext = ]
;
; INPUT:
;     Filename - Scalar string giving the name of the FITS file(s)
;               Can include wildcards such as '*.fits'.   In IDL V5.5 one can
;               use the regular expressions allowed by the FILE_SEARCH()
;               function.     Since V5.3 one can also search gzip compressed 
;               FITS files.
; OPTIONAL INPUT KEYWORDS:
;     /SILENT - If set, then the display of the file description on the 
;                terminal will be suppressed
;
;      TEXTOUT - specifies output device.
;               textout=1        TERMINAL using /more option
;               textout=2        TERMINAL without /more option
;               textout=3        .prt
;               textout=4        laser.tmp
;               textout=5        user must open file, see TEXTOPEN
;               textout=7       append to existing  file
;               textout = filename (default extension of .prt)
;
;               If TEXTOUT is not supplied, then !TEXTOUT is used
; OPTIONAL OUTPUT KEYWORD:
;       N_ext - Returns an integer scalar giving the number of extensions in
;               the FITS file
;
; COMMON BLOCKS
;       DESCRIPTOR =  File descriptor string of the form N_hdrrec Naxis IDL_type
;               Naxis1 Naxis2 ... Naxisn [N_hdrrec table_type Naxis
;               IDL_type Naxis1 ... Naxisn] (repeated for each extension) 
;               See the procedure RDFITS_STRUCT for an example of the
;               use of this common block
;
; EXAMPLE:
;       Display info about all FITS files of the form '*.fit' in the current
;               directory
;
;               IDL> fits_info, '*.fit'
;
;       Any time a *.fit file is found which is *not* in FITS format, an error 
;       message is displayed at the terminal and the program continues
;
; PROCEDURES USED:
;       GETTOK(), MRD_SKIP, STRN(), SXPAR(), TEXTOPEN, TEXTCLOSE 
;
; SYSTEM VARIABLES:
;       The non-standard system variables !TEXTOUT and !TEXTUNIT will be  
;       created by FITS_INFO if they are not previously defined.   
;
;       DEFSYSV,'!TEXTOUT',1
;       DEFSYSV,'!TEXTUNIT',0
;
;       See TEXTOPEN.PRO for more info
; MODIFICATION HISTORY:
;       Written, K. Venkatakrishna, Hughes STX, May 1992
;       Added N_ext keyword, and table_name info, G. Reichert
;       Work on *very* large FITS files   October 92
;       More checks to recognize corrupted FITS files     February, 1993
;       Proper check for END keyword    December 1994
;       Correctly size variable length binary tables  WBL December 1994
;       EXTNAME keyword can be anywhere in extension header WBL  January 1998
;       Correctly skip past extensions with no data   WBL   April 1998
;       Converted to IDL V5.0, W. Landsman, April 1998
;       No need for !TEXTOUT if /SILENT D.Finkbeiner   February 2002
;	Define !TEXTOUT if needed.  R. Sterner, 2002 Aug 27
;       Work on gzip compressed files for V5.3 or later  W. Landsman 2003 Jan
;       Improve speed by only reading first 36 lines of header 
;       Count headers with more than 32767 lines         W. Landsman Feb. 2003

; NAME:
;       FITS_OPEN
;
;*PURPOSE:
;       Opens a FITS (Flexible Image Transport System) data file.
;
;*CATEGORY:
;       INPUT/OUTPUT
;
;*CALLING SEQUENCE:
;       FITS_OPEN, filename, fcb
;
;*INPUTS:
;       filename : name of the FITS file to open, scalar string
;                  FITS_OPEN can also open gzip compressed (.gz) file *for 
;                  reading only*, in IDL V5.3 or later, although there is a 
;                  performance penalty 
;*OUTPUTS:
;       fcb : (FITS Control Block) a IDL structure containing information
;               concerning the file.  It is an input to FITS_READ, FITS_WRITE
;               and FITS_CLOSE
;
; INPUT KEYWORD PARAMETERS:
;       /APPEND: Set to append to an existing file.
;       /HPRINT - print headers with routine HPRINT as they are read.
;               (useful for debugging a strange file)
;       /NO_ABORT: Set to return to calling program instead of a RETALL
;               when an I/O error is encountered.  If set, the routine will
;               return  a non-null string (containing the error message) in the
;               keyword MESSAGE.    (For backward compatibility, the obsolete 
;               system variable !ERR is also set to -1 in case of an error.)   
;               If /NO_ABORT not set, then FITS_OPEN will print the message and
;               issue a RETALL
;       /UPDATE Set this keyword to open an existing file for update
;       /WRITE: Set this keyword to open a new file for writing. 
;
; OUTPUT KEYWORD PARAMETERS:
;       MESSAGE = value: Output error message.    If the FITS file was opened
;               successfully, then message = ''.
;       
;*NOTES:
;       The output FCB should be passed to the other FITS routines (FITS_OPEN,
;       FITS_READ, FITS_HELP, and FITS_WRITE).  It has the following structure
;       when FITS_OPEN is called without /WRITE or /APPEND keywords set.
;
;           FCB.FILENAME - name of the input file
;               .UNIT - unit number the file is opened to
;               .NEXTEND - number of extensions in the file.
;               .XTENSION - string array giving the extension type for each
;                       extension.
;               .EXTNAME - string array giving the extension name for each
;                       extension. (null string if not defined the extension)
;               .EXTVER - vector of extension version numbers (0 if not
;                       defined)
;               .EXTLEVEL - vector of extension levels (0 if not defined)
;               .GCOUNT - vector with the number of groups in each extension.
;               .PCOUNT - vector with parameter count for each group
;               .BITPIX - BITPIX for each extension with values
;                                  8    byte data
;                                16     short word integers
;                                32     long word integers
;                               -32     IEEE floating point
;                               -64     IEEE double precision floating point
;               .NAXIS - number of axes for each extension.  (0 for null data
;                       units)
;               .AXIS - 2-D array where axis(*,N) gives the size of each axes
;                       for extension N
;               .START_HEADER - vector giving the starting byte in the file
;                               where each extension header begins
;               .START_DATA - vector giving the starting byte in the file
;                               where the data for each extension begins
;
;               .HMAIN - keyword parameters (less standard required FITS
;                               keywords) for the primary data unit.
;               .OPEN_FOR_WRITE - flag (0= open for read, 1=open for write, 
;                                                2=open for update)
;               .LAST_EXTENSION - last extension number read.
;               .RANDOM_GROUPS - 1 if the PDU is random groups format,
;                               0 otherwise
;               .NBYTES - total number of (uncompressed) bytes in the FITS file
;
;       When FITS open is called with the /WRITE or /APPEND option, FCB
;       contains:
;
;           FCB.FILENAME - name of the input file
;               .UNIT - unit number the file is opened to
;               .NEXTEND - number of extensions in the file.
;               .OPEN_FOR_WRITE - flag (1=open for write, 2=open for append
;                                       3=open for update)
;
;
;*EXAMPLES:
;       Open a FITS file for reading:
;               FITS_OPEN,'myfile.fits',fcb
;
;       Open a new FITS file for output:
;               FITS_OPEN,'newfile.fits',fcb,/write
; PROCEDURES USED:
;       HPRINT, SXDELPAR, SXPAR()
;*HISTORY:
;       Written by:     D. Lindler      August, 1995
;       July, 1996      NICMOS  Modified to allow open for overwrite
;                               to allow primary header to be modified
;       DJL Oct. 15, 1996   corrected to properly extend AXIS when more
;                       than 100 extensions present
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Use Message = '' rather than !ERR =1 as preferred signal of normal
;           operation   W. Landsman  November 2000
;     	Lindler, Dec, 2001, Modified to use 64 bit words for storing byte
;             positions within the file to allow support for very large
;             files 
;       Work with gzip compressed files W. Landsman    January 2003

; NAME:
;       FITS_READ
;*PURPOSE:
;       To read a FITS file.
;
;*CATEGORY:
;       INPUT/OUTPUT
;
;*CALLING SEQUENCE:
;       FITS_READ, filename_or_fcb, data [,header, group_par]
;
;*INPUTS:
;       FILENAME_OR_FCB - this parameter can be the FITS Control Block (FCB)
;               returned by FITS_OPEN or the file name of the FITS file.  If
;               a file name is supplied, FITS_READ will open the file with
;               FITS_OPEN and close the file with FITS_CLOSE before exiting.
;               When multiple extensions are to be read from the file, it is
;               more efficient for the user to call FITS_OPEN and leave the
;               file open until all extensions are read.
;
;*OUTPUTS:
;       DATA - data array.  If /NOSCALE is specified, BSCALE and BZERO
;               (if present in the header) will not be used to scale the data.
;               If Keywords FIRST and LAST are used to read a portion of the
;               data or the heap portion of an extension, no scaling is done
;               and data is returned as a 1-D vector. The user can use the IDL
;               function REFORM to convert the data to the correct dimensions
;               if desired.  If /DATA_ONLY is specified, no scaling is done.
;       HEADER - FITS Header.  If an extension is read, and the /NO_PDU keyword
;               parameter is not supplied, the primary data unit header
;               and the extension header will be combined.  The header will have
;               the form:
;
;                       
;                       BEGIN MAIN HEADER --------------------------------
;                       
;                       BEGIN EXTENSION HEADER ---------------------------
;                       1.  (Default=0, the first group)
;       
;*OUTPUT KEYWORD PARAMETERS:
;       ENUM - Output extension number that was read.  
;       MESSAGE = value: Output error message
;
;*NOTES:
;       Determination or which extension to read.
;               case 1: EXTEN_NO specified. EXTEN_NO will give the number of the
;                       extension to read.  The primary data unit is refered
;                       to as extension 0. If EXTEN_NO is specified, XTENSION,
;                       EXTNAME, EXTVER, and EXTLEVEL parameters are ignored.
;               case 2: if EXTEN_NO is not specified, the first extension
;                       with the specified XTENSION, EXTNAME, EXTVER, and
;                       EXTLEVEL will be read.  If any of the 4 parameters
;                       are not specified, they will not be used in the search.
;                       Setting EXTLEVEL=0, EXTVER=0, EXTNAME='', or
;                       XTENSION='' is the same as not supplying them.
;               case 3: if none of the keyword parameters, EXTEN_NO, XTENSION,
;                       EXTNAME, EXTVER, or EXTLEVEL are supplied.  FITS_READ
;                       will read the next extension in the file.  If the
;                       primary data unit (PDU), extension 0, is null, the
;                       first call to FITS_READ will read the first extension
;                       of the file.
;
;               The only way to read a null PDU is to use EXTEN_NO = 0.
;
;       If FIRST and LAST are specified, the data is returned without applying
;       any scale factors (BSCALE and BZERO) and the data is returned in a
;       1-D vector.  This will allow you to read any portion of a multiple
;       dimension data set.  Once returned, the IDL function REFORM can be
;       used to place the correct dimensions on the data.
;
;       IMPLICIT IMAGES: FITS_READ will construct an implicit image
;               for cases where NAXIS=0 and the NPIX1, NPIX2, and PIXVALUE
;               keywords are present.  The output image will be:
;                       image = replicate(PIXVALUE,NPIX1,NPIX2)
;
;*EXAMPLES:
;       Read the primary data unit of a FITS file, if it is null read the
;       first extension:
;               FITS_READ, 'myfile.fits', data, header
;
;       Read the first two extensions of a FITS file and the extension with
;       EXTNAME = 'FLUX' and EXTVER = 4
;               FITS_OPEN, 'myfile.fits', fcb
;               FITS_READ, fcb,data1, header2, exten_no = 1
;               FITS_READ, fcb,data1, header2, exten_no = 2
;               FITS_READ, fcb,data3, header3, extname='flux', extver=4
;               FITS_CLOSE, fcb
;       
;       Read the sixth image in a data cube for the fourth extension.
;
;               FITS_OPEN, 'myfile.fits', fcb
;               image_number = 6
;               ns = fcb.axis(0,4)
;               nl = fcb.axis(1,4)
;               i1 = (ns*nl)*(image_number-1)
;               i2 = i2 + ns*nl-1
;               FITS_READ,fcb,image,header,first=i1,last=i2
;               image = reform(image,ns,nl,/overwrite)
;               FITS_CLOSE
;
;*PROCEDURES USED:
;       FITS_CLOSE, FITS_OPEN, IEEE_TO_HOST, IS_IEEE_BIG() 
;       SXADDPAR, SXDELPAR, SXPAR()
;*HISTORY:
;       Written by:     D. Lindler, August 1995
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Avoid use of !ERR       W. Landsman   August 1999
;       Read unsigned datatypes, added /no_unsigned   W. Landsman December 1999
;       Don't call FITS_CLOSE unless fcb is defined   W. Landsman January 2000
;       Set BZERO = 0 for unsigned integer data   W. Landsman  January 2000
;       Only call IEEE_TO_HOST if needed          W. Landsman February 2000
;       Ensure EXTEND keyword in primary header   W. Landsman April 2001
;       Don't erase ERROR message when closing file  W. Landsman April 2002
;       Assume at least V5.1 remove NANValue keyword  W. Landsman November 2002
;       Work with compress files (read file size from fcb),
;       requires updated (Jan 2003) version of FITS_OPEN W. Landsman Jan 2003

; NAME:
;    FITS_TEST_CHECKSUM()
; PURPOSE:
;    Verify the values of the CHECKSUM and DATASUM keywords in a FITS header 
; EXPLANATION: 
;     Follows the 23 May 2002 version of the FITS checksum proposal at 
;     http://heasarc.gsfc.nasa.gov/docs/heasarc/fits/checksum.html   
; 
; CALLING SEQUENCE:
;    result = FITS_TEST_CHECKSUM(HDR, [ DATA, ERRMSG=, /FROM_IEEE ])
; INPUTS:
;    HDR - FITS header (vector string)
; OPTIONAL DATA:
;    DATA - data array associated with the FITS header.   If not supplied, or
;           set to a scalar, then there is assumed to be no data array 
;           associated with the FITS header.
; RESULT:
;     An integer -1, 0 or 1 indicating the following conditions:
;           1 - CHECKSUM (and DATASUM) keywords are present with correct values
;           0 - CHECKSUM keyword is not present
;          -1 - CHECKSUM or DATASUM keyword does not have the correct value
;               indicating possible data corruption.
; OPTIONAL INPUT KEYWORD:
;    /FROM_IEEE - If this keyword is set, then the input is assumed to be in 
;             big endian format (e.g. an untranslated FITS array).    This 
;             keyword only has an effect on little endian machines (e.g. 
;             a Linux box).
; OPTIONAL OUTPUT KEYWORD:
;     ERRMSG - will contain a scalar string giving the error condition.   If
;              RESULT = 1 then ERRMSG will be an empty string.   If this 
;              output keyword is not supplied, then the error message will be
;              printed at the terminal.
; NOTES:
;     The header and data must be *exactly* as originally written in the FITS 
;     file.  By default, some FITS readers may alter keyword values (e.g. 
;     BSCALE) or append information (e.g. HISTORY or an inherited primary 
;     header) and this will alter the checksum value.           
; PROCEDURES USED:
;    CHECKSUM32, FITS_ASCII_ENCODE(), SXPAR()
; EXAMPLE:
;     Verify the CHECKSUM keywords in the primary header/data unit of a FITS 
;     file 'test.fits'
;
;     FITS_READ,'test.fits',data,hdr,/no_PDU,/NoSCALE
;     print,FITS_TEST_CHECKSUM(hdr,data)
;
;     Note the use of the /No_PDU and /NoSCALE keywords to avoid any alteration 
;     of the FITS header
; REVISION HISTORY:
;     W. Landsman  SSAI               December 2002
;     Return quietly if CHECKSUM keywords not found W. Landsman May 2003

; NAME:
;	FITS_WRITE
;
;*PURPOSE:
;	To write a FITS primary data unit or extension.
;
;*CATEGORY:
;	INPUT/OUTPUT
;
;*CALLING SEQUENCE:
;	FITS_WRITE, filename_or_fcb, data, [header_in]
;
;*INPUTS:
;	FILENAME_OR_FCB: name of the output data file or the FITS control
;		block returned by FITS_OPEN (called with the /WRITE or
;		/APPEND) parameters.
;
;*OPTIONAL INPUTS:
;	DATA: data array to write.  If not supplied or set to a scalar, a
;		null image is written.
;	HEADER_IN: FITS header keyword.  If not supplied, a minimal basic
;		header will be created.  Required FITS keywords, SIMPLE,
;		BITPIX, XTENSION, NAXIS, ... are added by FITS_WRITE and
;		do not need to be supplied with the header.  If supplied,
;		their values will be updated as necessary to reflect DATA.
;
;*INPUT KEYWORD PARAMETERS:
;
;	XTENSION: type of extension to write (Default="IMAGE"). If not
;		supplied, it will be taken from HEADER_IN.  If not in either
;		place, the default is "IMAGE".  This parameter is ignored
;		when writing the primary data unit.
;	EXTNAME: EXTNAME for the extension.  If not supplied, it will be taken
;		from HEADER_IN.  If not supplied and not in HEADER_IN, no
;		EXTNAME will be written into the output extension.
;	EXTVER: EXTVER for the extension.  If not supplied, it will be taken
;               from HEADER_IN.  If not supplied and not in HEADER_IN, no
;               EXTVER will be written into the output extension.
;	EXTLEVEL: EXTLEVEL for the extension.  If not supplied, it will be taken
;               from HEADER_IN.  If not supplied and not in HEADER_IN, no
;               EXTLEVEL will be written into the output extension.
;       /NO_ABORT: Set to return to calling program instead of a RETALL
;               when an I/O error is encountered.  If set, the routine will
;               return  a non-null string (containing the error message) in the
;               keyword MESSAGE.    (For backward compatibility, the obsolete 
;               system variable !ERR is also set to -1 in case of an error.)   
;               If /NO_ABORT not set, then FITS_WRITE will print the message and
;               issue a RETALL
;	/NO_DATA: Set if you only want FITS_WRITE to write a header.  The
;		header supplied will be written without modification and
;		the user is expected to write the data using WRITEU to unit
;		FCB.UNIT. When FITS_WRITE is called with /NO_DATA, the user is
;		responsible for the validity of the header, and must write
;		the correct amount and format of the data.  When FITS_WRITE
;		is used in this fashion, it will pad the data from a previously
;		written extension to 2880 blocks before writting the header.
;
;*OUTPUT KEYWORD PARAMETERS:
;       MESSAGE: value of the error message for use with /NO_ABORT
;	HEADER: actual output header written to the FITS file.
;
;*NOTES:
;	If the first call to FITS_WRITE is an extension, FITS_WRITE will
;	automatically write a null image as the primary data unit.
;
;	Keywords and history in the input header will be properly separated
;	into the primary data unit and extension portions when constructing
;	the output header (See FITS_READ for information on the internal
;	Header format which separates the extension and PDU header portions).
;	
;*EXAMPLES:
;	Write an IDL variable to a FITS file with the minimal required header.
;		FITS_WRITE,'newfile.fits',ARRAY
;
;	Write the same array as an image extension, with a null Primary data
;	unit.
;		FITS_WRITE,'newfile.fits',ARRAY,xtension='IMAGE'
;
;	Write 4 additional image extensions to the same file.
;		FITS_OPEN,'newfile.fits',fcb
;		FITS_WRITE,fcb,data1,extname='FLUX',extver=1
;		FITS_WRITE,fcb,err1,extname'ERR',extver=1
;		FITS_WRITE,fcb,data2,extname='FLUX',extver=2
;		FITS_WRITE,fcb,err2,extname='ERR',extver=2
;		FITS_CLOSE,FCB
;		
;*PROCEDURES USED:
;	FITS_OPEN, SXADDPAR, SXDELPAR, SXPAR()
;*HISTORY:
;	Written by:	D. Lindler	August, 1995
;	Work for variable length extensions  W. Landsman   August 1997
;	Converted to IDL V5.0   W. Landsman   September 1997
;	PCOUNT and GCOUNT added for IMAGE extensions   J. Graham  October 1999
;       Write unsigned data types      W. Landsman   December 1999
;       Pad data area with zeros not blanks  W. McCann/W. Landsman October 2000
;       Return Message='' to signal normal operation W. Landsman Nov. 2000
;       Ensure that required extension table keywords are in proper order
;             W.V. Dixon/W. Landsman          March 2001
;       Assume since V5.1, remove NaNValue keyword   W. Landsman Nov. 2002

; NAME:
;        FLEGENDRE
; PURPOSE:
;       Compute the first M terms in a Legendre polynomial expansion.  
; EXPLANATION:
;       Meant to be used as a supplied function to SVDFIT.
;
;       This procedure became partially obsolete in IDL V5.0 with the 
;       introduction of the /LEGENDRE keyword to SVDFIT and the associated 
;       SVDLEG function.    However, note that, unlike SVDLEG, FLEGENDRE works
;       on vector values of X.     
; CALLING SEQUENCE:
;       result = FLEGENDRE( X, M)
;
; INPUTS:
;       X - the value of the independent variable, scalar or vector
;       M - number of term of the Legendre expansion to compute, integer scalar 
;
; OUTPUTS:
;       result - (N,M) array, where N is the number of elements in X and M
;               is the order.   Contains the value of each Legendre term for
;               each value of X
; EXAMPLE:
;       (1) If x = 2.88 and M = 3 then 
;       IDL> print, flegendre(x,3)   ==>   [1.00, 2.88, 11.9416]
;
;       This result can be checked by explicitly computing the first 3 Legendre
;       terms, 1.0, x, 0.5*( 3*x^2 -1)
;
;       (2) Find the coefficients to an M term Legendre polynomial that gives
;               the best least-squares fit to a dataset (x,y)
;               IDL> coeff = SVDFIT( x,y,M,func='flegendre')
;       
;           The coefficients can then be supplied to the function POLYLEG to 
;               compute the best YFIT values for any X. 
; METHOD:
;       The recurrence relation for the Legendre polynomials is used to compute
;       each term.   Compare with the function FLEG in "Numerical Recipes"
;       by Press et al. (1992), p. 674
;
; REVISION HISTORY:
;       Written     Wayne Landsman    Hughes STX      April 1995                
;       Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;     FLUX2MAG
; PURPOSE:
;     Convert from flux (ergs/s/cm^2/A) to magnitudes.
; EXPLANATION:
;     Use MAG2FLUX() for the opposite direction.
;
; CALLING SEQUENCE:
;     mag = flux2mag( flux, [ zero_pt, ABwave=  ] )
;
; INPUTS:
;     flux - scalar or vector flux vector, in erg cm-2 s-1 A-1
;
; OPTIONAL INPUT:
;     zero_pt - scalar giving the zero point level of the magnitude.
;               If not supplied then zero_pt = 21.1 (Code et al 1976)
;               Ignored if the ABwave keyword is supplied
;
; OPTIONAL KEYWORD INPUT:
;     ABwave - wavelength scalar or vector in Angstroms.   If supplied, then 
;           FLUX2MAG() returns Oke AB magnitudes (Oke & Gunn 1983, ApJ, 266,
;           713).
;
; OUTPUT:
;     mag - magnitude vector.   If the ABwave keyword is set then mag
;           is given by the expression 
;           ABMAG = -2.5*alog10(f) - 5*alog10(ABwave) - 2.406 
;             
;           Otherwise, mag is given by the expression  
;           mag = -2.5*alog10(flux) - zero_pt
; EXAMPLE:
;       Suppose one is given wavelength and flux vectors, w (in Angstroms) and 
;       f (in erg cm-2 s-1 A-1).   Plot the spectrum in AB magnitudes
;
;       IDL> plot, w, flux2mag(f,ABwave = w), /nozero
;
; REVISION HISTORY:
;       Written    J. Hill        STX Co.       1988
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Added ABwave keyword    W. Landsman   September 1998

; NAME:
;     FM_UNRED
; PURPOSE:
;     Deredden a flux vector using the Fitzpatrick (1999) parameterization
; EXPLANATION:
;     The R-dependent Galactic extinction curve is that of Fitzpatrick & Massa 
;     (Fitzpatrick, 1999, PASP, 111, 63; astro-ph/9809387 ).    
;     Parameterization is valid from the IR to the far-UV (3.5 microns to 0.1 
;     microns).    UV extinction curve is extrapolated down to 912 Angstroms.
;
; CALLING SEQUENCE:
;     FM_UNRED, wave, flux, ebv, [ funred, R_V = , /LMC2, /AVGLMC, ExtCurve= 
;                       gamma =, x0=, c1=, c2=, c3=, c4= ]
; INPUT:
;      WAVE - wavelength vector (Angstroms)
;      FLUX - calibrated flux vector, same number of elements as WAVE
;               If only 3 parameters are supplied, then this vector will
;               updated on output to contain the dereddened flux.
;      EBV  - color excess E(B-V), scalar.  If a negative EBV is supplied,
;               then fluxes will be reddened rather than deredenned.
;
; OUTPUT:
;      FUNRED - unreddened flux vector, same units and number of elements
;               as FLUX
;
; OPTIONAL INPUT KEYWORDS
;      R_V - scalar specifying the ratio of total to selective extinction
;               R(V) = A(V) / E(B - V).    If not specified, then R = 3.1
;               Extreme values of R(V) range from 2.3 to 5.3
;
;      /AVGLMC - if set, then the default fit parameters c1,c2,c3,c4,gamma,x0 
;             are set to the average values determined for reddening in the 
;             general Large Magellanic Cloud (LMC) field by Misselt et al. 
;            (1999, ApJ, 515, 128)
;      /LMC2 - if set, then the fit parameters are set to the values determined
;             for the LMC2 field (including 30 Dor) by Misselt et al.
;             Note that neither /AVGLMC or /LMC2 will alter the default value 
;             of R_V which is poorly known for the LMC. 
;             
;      The following five input keyword parameters allow the user to customize
;      the adopted extinction curve.    For example, see Clayton et al. (2003,
;      ApJ, 588, 871) for examples of these parameters in different interstellar
;      environments.
;
;      x0 - Centroid of 2200 A bump in microns (default = 4.596)
;      gamma - Width of 2200 A bump in microns (default  =0.99)
;      c3 - Strength of the 2200 A bump (default = 3.23)
;      c4 - FUV curvature (default = 0.41)
;      c2 - Slope of the linear UV extinction component 
;           (default = -0.824 + 4.717/R)
;      c1 - Intercept of the linear UV extinction component 
;           (default = 2.030 - 3.007*c2
;            
; OPTIONAL OUTPUT KEYWORD:
;      ExtCurve - Returns the E(wave-V)/E(B-V) extinction curve, interpolated
;                 onto the input wavelength vector
;
; EXAMPLE:
;       Determine how a flat spectrum (in wavelength) between 1200 A and 3200 A
;       is altered by a reddening of E(B-V) = 0.1.   Assume an "average"
;       reddening for the diffuse interstellar medium (R(V) = 3.1)
;
;       IDL> w = 1200 + findgen(40)*50      ;Create a wavelength vector
;       IDL> f = w*0 + 1                    ;Create a "flat" flux vector
;       IDL> fm_unred, w, f, -0.1, fnew  ;Redden (negative E(B-V)) flux vector
;       IDL> plot,w,fnew                   
;
; NOTES:
;       (1) The following comparisons between the FM curve and that of Cardelli, 
;           Clayton, & Mathis (1989), (see ccm_unred.pro):
;           (a) - In the UV, the FM and CCM curves are similar for R < 4.0, but
;                 diverge for larger R
;           (b) - In the optical region, the FM more closely matches the
;                 monochromatic extinction, especially near the R band.
;       (2)  Many sightlines with peculiar ultraviolet interstellar extinction 
;               can be represented with the FM curve, if the proper value of 
;               R(V) is supplied.
;       (3) Use the 4 parameter calling sequence if you wish to save the 
;               original flux vector.
; PROCEDURE CALLS:
;       CSPLINE(), POLY()
; REVISION HISTORY:
;       Written   W. Landsman        Raytheon  STX   October, 1998
;       Based on FMRCurve by E. Fitzpatrick (Villanova)
;       Added /LMC2 and /AVGLMC keywords,  W. Landsman   August 2000
;       Added ExtCurve keyword, J. Wm. Parker   August 2000
;

; NAME:
;       FORPRINT
; PURPOSE:
;       Print a set of vectors by looping over each index value.
;
; EXPLANATION:
;       If W and F are equal length vectors, then the statement
;               IDL> forprint, w, f   
;       is equivalent to 
;               IDL> for i = 0L, N_elements(w)-1 do print,w[i],f[i]    
;
; CALLING SEQUENCE:
;       forprint, v1,[ v2, v3, v4,....v18, FORMAT = , TEXTOUT = ,STARTLINE =,
;                                          NUMLINE =, /SILENT, COMMENT= ] 
;
; INPUTS:
;       V1,V2,...V18 - Arbitary IDL vectors.  If the vectors are not of
;               equal length then the number of rows printed will be equal
;               to the length of the smallest vector.   Up to 18 vectors
;               can be supplied.
;
; OPTIONAL KEYWORD INPUTS:
;
;       TEXTOUT - Controls print output device, defaults to !TEXTOUT
;
;               textout=1       TERMINAL using /more option if available
;               textout=2       TERMINAL without /more option
;               textout=3       file 'forprint.prt'
;               textout=4       file 'laser.tmp' 
;               textout=5      user must open file
;               textout =      filename (default extension of .prt)
;               textout=7       Append to .prt file if it exists
;
;       COMMENT - String to write as the first line of output file if 
;                TEXTOUT > 2.    By default, FORPRINT will write a time stamp
;                on the first line.   Use /NOCOMMENT if you don't want FORPRINT
;                to write anything in the output file.
;       FORMAT - Scalar format string as in the PRINT procedure.  The use
;               of outer parenthesis is optional.   Ex. - format="(F10.3,I7)"
;               This program will automatically remove a leading "$" from
;               incoming format statments. Ex. - "$(I4)" would become "(I4)".
;               If omitted, then IDL default formats are used.
;       /NOCOMMENT  - Set this keyword if you don't want any comment line
;               line written as the first line in a harcopy output file.
;       /SILENT - Normally, with a hardcopy output (TEXTOUT > 2), FORPRINT will
;                print an informational message.    If the SILENT keyword
;               is set and non-zero, then this message is suppressed.
;       STARTLINE - Integer scalar specifying the first line in the arrays
;               to print.   Default is STARTLINE = 1, i.e. start at the
;               beginning of the arrays.
; OUTPUTS:
;       None
; SYSTEM VARIABLES:
;       If keyword TEXTOUT is not used, the default is the nonstandard 
;       keyword !TEXTOUT.    If you want to use FORPRINT to write more than 
;       once to the same file, or use a different file name then set 
;       TEXTOUT=5, and open and close then file yourself (see documentation 
;       of TEXTOPEN for more info).
;       
;       One way to add the non-standard system variables !TEXTOUT and !TEXTUNIT
;       is to use the procedure ASTROLIB
; EXAMPLE:
;       Suppose W,F, and E are the wavelength, flux, and epsilon vectors for
;       a spectrum.   Print these values to a file 'output.dat' in a nice 
;       format.
;
;       IDL> fmt = '(F10.3,1PE12.2,I7)'
;       IDL> forprint, F = fmt, w, f, e, TEXT = 'output.dat'
;
; PROCEDURES CALLED:
;       TEXTOPEN, TEXTCLOSE
; REVISION HISTORY:
;       Written    W. Landsman             April, 1989
;       Keywords textout and format added, J. Isensee, July, 1990
;       Made use of parenthesis in FORMAT optional  W. Landsman  May 1992
;       Added STARTLINE keyword W. Landsman    November 1992
;       Set up so can handle 18 input vectors. J. Isensee, HSTX Corp. July 1993
;       Handle string value of TEXTOUT   W. Landsman, HSTX September 1993
;       Added NUMLINE keyword            W. Landsman, HSTX February 1996
;       Added SILENT keyword             W. Landsman, RSTX, April 1998
;       Converted to IDL V5.0            W. Landsman, RSTX, April, 1998
;       Much faster printing to a file   W. Landsman, RITSS, August, 2001
;       Use SIZE(/TNAME) instead of DATATYPE() W. Landsman SSAI October 2001
;       Fix skipping of first line bug introduced Aug 2001  W. Landsman Nov2001
;       Added /NOCOMMENT keyword, the SILENT keyword now controls only 
;       the display of informational messages.  W. Landsman June 2002

; NAME:
;   FREBIN
;
; PURPOSE:
;   Shrink or expand the size of an array an arbitary amount using interpolation
;
; EXPLANATION: 
;   FREBIN is an alternative to CONGRID or REBIN.    Like CONGRID it
;   allows expansion or contraction by an arbitary amount. ( REBIN requires 
;   integral factors of the original image size.)    Like REBIN it conserves 
;   flux by ensuring that each input pixel is equally represented in the output
;   array.       
;
; CALLING SEQUENCE:
;   result = FREBIN( image, nsout, nlout, [ /TOTAL] )
;
; INPUTS:
;    image - input image, 1-d or 2-d numeric array
;    nsout - number of samples in the output image, numeric scalar
;
; OPTIONAL INPUT:
;    nlout - number of lines in the output image, numeric scalar
;            If not supplied, then set equal to 1
;
; OPTIONAL KEYWORD INPUTS:
;   /total - if set, the output pixels will be the sum of pixels within
;          the appropriate box of the input image.  Otherwise they will
;          be the average.    Use of the /TOTAL keyword conserves surface flux.
; 
; OUTPUTS:
;    The resized image is returned as the function result.    If the input
;    image is of type DOUBLE or FLOAT then the resized image is of the same
;    type.     If the input image is BYTE, INTEGER or LONG then the output
;    image is usually of type FLOAT.   The one exception is expansion by
;    integral amount (pixel duplication), when the output image is the same
;    type as the input image.  
;     
; EXAMPLE:
;     Suppose one has an 800 x 800 image array, im, that must be expanded to
;     a size 850 x 900 while conserving surface flux:
;
;     IDL> im1 = frebin(im,850,900,/total) 
;
;     im1 will be a 850 x 900 array, and total(im1) = total(im)
; NOTES:
;    If the input image sizes are a multiple of the output image sizes
;    then FREBIN is equivalent to the IDL REBIN function for compression,
;    and simple pixel duplication on expansion.
;
;    If the number of output pixels are not integers, the output image
;    size will be truncated to an integer.  The platescale, however, will
;    reflect the non-integer number of pixels.  For example, if you want to
;    bin a 100 x 100 integer image such that each output pixel is 3.1
;    input pixels in each direction use:
;           n = 100/3.1   ; 32.2581
;          image_out = frebin(image,n,n)
;
;     The output image will be 32 x 32 and a small portion at the trailing
;     edges of the input image will be ignored.
; 
; PROCEDURE CALLS:
;    None.
; HISTORY:
;    Adapted from May 1998 STIS  version, written D. Lindler, ACC
;    Added /NOZERO, use INTERPOLATE instead of CONGRID, June 98 W. Landsman  
;    Fixed for nsout non-integral but a multiple of image size  Aug 98 D.Lindler
;    DJL, Oct 20, 1998, Modified to work for floating point image sizes when
;		expanding the image. 
;    Improve speed by addressing arrays in memory order W.Landsman Dec/Jan 2001

; NAME: 
;    FSTRING
; PURPOSE:
;    Wrapper around STRING function to fix pre-V5.4 1024 formatting size limit
; EXPLANATION:
;    Prior to V5.4, the intrinsic STRING() function had a size limit of 1024 
;    elements. FSTRING() works around this by breaking a larger array into 1024 element
;    element chunks.
;
; CALLING SEQUENCE:
;    new = fstring(old, [ format, FORMAT = )
;
; INPUTS:
;    OLD = string or number to format, scalar, vector or array
;
; OPTIONAL STRING:
;    FORMAT = scalar string giving format to pass to the STRING() function
;             See restrictions on possible formats below.
; OPTIONAL KEYWORD INPUT:
;    FORMAT  = Format string can alternatively be called as keyword
;
; OUTPUT:
;    FSTRING will return a string with the same dimensions 
;
; RESTRICTIONS:
;    Because FSTRING breaks up the formatting into 1024 element chunks, problems
;    can arise if the number of formatting elements does not evenly divide
;    into 1024.    For example, if format = '(i6,f6.2,e12.6)', (i.e. three
;    formatting elements)  then both the 1023rd and 1024th element will be 
;    formatted as I6.
; EXAMPLE:
;    Create a string array of 10000 uniform random numbers formatted as F6.2
;
;    IDL> a = fstring( randomu(seed,10000), '(f6.2)') 
; REVISION HISTORY:
;     Written W. Landsman (based on program by D. Zarro)  February 2000
;     Check if VERSION is V5.4 or later   W. Landsman     January 2002

; NAME:
;       FTAB_DELROW
; PURPOSE:
;       Delete rows of data from a FITS ASCII or binary table extension
;
; CALLING SEQUENCE:
;       ftab_delrow, filename, rows, EXTEN_NO =, NEWFILE = ] 
;
; INPUTS-OUPUTS
;       filename - scalar string giving name of the FITS file containing an
;               ASCII or binary table extension. 
; 
;       rows  -  scalar or vector, specifying the row numbers to delete
;               First row has index 0.   If a vector, it will be sorted and
;               duplicates will be removed
;
; OPTIONAL KEYWORD INPUTS:
;       EXTEN_NO - scalar integer specifying which extension number to process
;               Default is to process the first extension
;       NEWFILE - scalar string specifying the name of the new output FITS file
;               FTAB_DELROW will prompt for this parameter if not supplied
;
; EXAMPLE:
;       Compress the first extension of a FITS file 'test.fits' to include 
;       only non-negative values in the 'FLUX' column
;
;       ftab_ext,'test.fits','flux',flux       ;Obtain original flux vector
;       bad = where(flux lt 0)                 ;Find negative fluxes
;       ftab_delrow,'test.fits',bad,new='test1.fits'  ;Delete specified rows
;
; RESTRICTIONS:
;       Does not work for variable length binary tables
;
; PROCEDURES USED:
;       FITS_CLOSE, FITS_OPEN, FITS_READ, FITS_WRITE, FTDELROW, TBDELROW        
;
; REVISION HISTORY:                                           
;       Written   W. Landsman        STX Co.     August, 1997
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Use COPY_LUN if V5.6 or later     W. Landsman   February 2003

; NAME:
;       FTAB_EXT
; PURPOSE:
;       Routine to extract columns from a FITS (binary or ASCII) table
;
; CALLING SEQUENCE:
;       FTAB_EXT, name_or_fcb, columns, v1, [v2,..,v9, ROWS=, EXTEN_NO= ]
; INPUTS:
;       name_or_fcb - either a scalar string giving the name of a FITS file 
;               containing a (binary or ASCII) table, or an IDL structure 
;               containing as file control block (FCB) returned by FITS_OPEN 
;               If FTAB_EXT is to be called repeatedly on the same file, then
;               it is quicker to first open the file with FITS_OPEN, and then
;               pass the FCB structure to FTAB_EXT
;       columns - table columns to extract.  Can be either 
;               (1) String with names separated by commas
;               (2) Scalar or vector of column numbers
;
; OUTPUTS:
;       v1,...,v9 - values for the columns.   Up to 9 columns can be extracted
;
; OPTIONAL INPUT KEYWORDS:
;       ROWS -  scalar or vector giving row number(s) to extract
;               Row numbers start at 0.  If not supplied or set to
;               -1 then values for all rows are returned
;       EXTEN_NO - Extension number to process.   If not set, then data is
;               extracted from the first extension in the file (EXTEN_NO=1)
;
; EXAMPLES:
;       Read wavelength and flux vectors from the first extension of a 
;       FITS file, 'spec.fit'.   Using FTAB_HELP,'spec.fit' we find that this
;       information is in columns named 'WAVELENGTH' and 'FLUX' (in columns 1
;       and 2).   To read the data
;
;       IDL> ftab_ext,'spec.fit','wavelength,flux',w,f
;               or
;       IDL> ftab_ext,'spec.fit',[1,2],w,f
;       
; PROCEDURES CALLED:
;       FITS_READ, FITS_CLOSE, FTINFO, FTGET(), TBINFO, TBGET()
; HISTORY:
;       version 1        W.   Landsman         August 1997
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Improve speed processing binary tables  W. Landsman   March 2000
;       Use new FTINFO calling sequence  W. Landsman   May 2000  
;       Don't call fits_close if fcb supplied W. Landsman May 2001 
;       Use STRSPLIT to parse column string  W. Landsman July 2002 

; NAME:
;       FTAB_HELP
; PURPOSE:
;       Describe the columns of a FITS binary or ASCII table extension.
;
; CALLING SEQUENCE:
;       FTAB_HELP, filename, [ EXTEN_No = , TEXTOUT= ]
;               or
;       FTAB_HELP, fcb, [EXTEN_No=, TEXTOUT= ]
;
; INPUTS:
;       filename - scalar string giving name of the FITS file.  
;       fcb - FITS control block returned by a previous call to FITS_OPEN
;
; OPTIONAL KEYWORD INPUTS:
;       EXTEN_NO - integer scalar specifying which FITS extension to read.
;               Default is to display the first FITS extension.
;       TEXTOUT - scalar number (0-7) or string (file name) determining
;               output device (see TEXTOPEN).  Default is TEXTOUT=1, output 
;               to the user's terminal    
;
; EXAMPLE:
;       Describe the columns in the second extension of a FITS file spec.fits
;       and write the results to a file 'spec2.lis'
;
;       IDL> ftab_help,'spec.fits',exten=2,t='spec2.lis'
;
; SYSTEM VARIABLES:
;       Uses the non-standard system variables !TEXTOUT and !TEXTUNIT
;       which must be defined (e.g. with ASTROLIB) before compilation
; PROCEDURES USED:
;       FITS_READ, FITS_CLOSE, FITS_OPEN, FTHELP, TBHELP, TEXTOPEN, TEXTCLOSE
; HISTORY:
;       version 1  W. Landsman    August 1997
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Corrected documentation W. Landsman   September 1997
;       Don't call fits_close if fcb supplied W. Landsman May 2001 

; NAME:
;       FTAB_PRINT
; PURPOSE:
;       Print the contents of a FITS (binary or ASCII) table extension.
; EXPLANATION:
;       User can specify which rows or columns to print
;
; CALLING SEQUENCE:
;       FTAB_PRINT, filename, columns, rows, [ TEXTOUT=, FMT=, EXTEN_NO=]
;
; INPUTS:
;       filename - scalar string giving name of a FITS file containing a 
;               binary or ASCII table
;       columns - string giving column names, or vector giving
;               column numbers (beginning with 1).  If string 
;               supplied then column names should be separated by comma's.
;       rows - (optional) vector of row numbers to print (beginning with 0).  
;               If not supplied or set to scalar, -1, then all rows
;               are printed.
; OPTIONAL KEYWORD INPUT:
;       EXTEN_NO - Extension number to read.   If not set, then the first 
;               extension is printed (EXTEN_NO=1)
;       TEXTOUT - scalar number (0-7) or string (file name) determining
;               output device (see TEXTOPEN).  Default is TEXTOUT=1, output 
;               to the user's terminal    
;       FMT = Format string for print display (binary tables only).   If not
;               supplied, then any formats in the TDISP keyword fields will be
;               used, otherwise IDL default formats.    For ASCII tables, the
;               format used is always as stored in the FITS table.
; EXAMPLE:
;       Print all rows of the first 5 columns of the first extension of the
;       file 'wfpc.fits'
;               IDL> ftab_print,'wfpc.fits',indgen(5)+1
;       
; SYSTEM VARIABLES:
;       Uses the non-standard system variables !TEXTOUT and !TEXTUNIT
;       which must be defined (e.g. with ASTROLIB) prior to compilation.
; PROCEDURES USED:
;       FITS_OPEN, FITS_READ, FTPRINT, TBPRINT
; HISTORY:
;       version 1  W. Landsman    August 1997
;       Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;      FTADDCOL
; PURPOSE:
;      Routine to add a field to a FITS ASCII table
;
; CALLING SEQUENCE:
;      ftaddcol, h, tab, name, idltype, [ tform, tunit, tscal, tzero, tnull ]
;
; INPUTS:
;      h - FITS table header.  It will be updated as appropriate
;      tab - FITS table array.  Number of columns will be increased if
;               neccessary.
;      name - field name, scalar string
;      idltype - idl data type (as returned by SIZE function) for field,
;               For string data (type=7) use minus the string length.
;
; OPTIONAL INPUTS:
;       tform - format specification 'qww.dd' where q = A, I, E, or D
;       tunit - string giving physical units for the column.
;       tscal - scale factor
;       tzero - zero point for field
;       tnull - null value for field
;
;       Use '' as the value of tform,tunit,tscal,tzero,tnull if you want
;       the default or no specification of them in the table header.
;
; OUTPUTS:
;       h,tab - updated to allow new column of data
;
; PROCEDURES USED:
;       FTINFO, FTSIZE, GETTOK(), SXADDPAR
; HISTORY:
;       version 1  D. Lindler   July, 1987
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Updated call to new FTINFO   W. Landsman   April 2000

; NAME:
;       FTCREATE
; PURPOSE:
;       Create a new (blank) FITS ASCII table and header with specified size.
;
; CALLING SEQUENCE:
;       ftcreate, maxcols, maxrows, h, tab
;
; INPUTS:
;       maxcols - number of character columns allocated, integer scalar
;       maxrows - maximum number of rows allocated, integer scalar
;
; OUTPUTS:
;       h - minimal FITS Table extension header, string array
; OPTIONAL OUTPUT:
;       tab - empty table, byte array 
; HISTORY:
;       version 1  D. Lindler   July. 87
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Make table creation optional, allow 1 row table, add comments to 
;       required FITS keywords    W. Landsman    October 2001  

; NAME:
;	FTDELCOL
; PURPOSE:
;	Delete a column of data from a FITS table
;
; CALLING SEQUENCE:
;	ftdelcol, h, tab, name
;
; INPUTS-OUPUTS
;	h,tab - FITS table header and data array.  H and TAB will
;		be updated with the specified column deleted
;
; INPUTS:
;	name - Either (1) a string giving the name of the column to delete
;		or (2) a scalar giving the column number to delete
;
; EXAMPLE:
;	Suppose it has been determined that the F7.2 format used for a field
;	FLUX in a FITS table is insufficient.  The old column must first be 
;	deleted before a new column can be written with a new format.
;
;	flux = FTGET(h,tab,'FLUX')       ;Save the existing values
;	FTDELCOL,h,tab,'FLUX'            ;Delete the existing column            
;	FTADDCOL,h,tab,'FLUX',8,'F9.2'   ;Create a new column with larger format
;	FTPUT,h,tab,'FLUX',0,flux        ;Put back the original values
;
; REVISION HISTORY:                                           
;	Written   W. Landsman        STX Co.     August, 1988
;	Adapted for IDL Version 2, J. Isensee, July, 1990
;	Converted to IDL V5.0   W. Landsman   September 1997
;       Updated call to new FTINFO   W. Landsman  May 2000

; NAME:
;	FTDELROW
; PURPOSE:
;	Delete a row of data from a FITS table
;
; CALLING SEQUENCE:
;	ftdelrow, h, tab, rows
;
; INPUTS-OUPUTS
;	h,tab - FITS table header and data array.  H and TAB will
;		be updated on output with the specified row(s) deleted.
;	rows  -  scalar or vector, specifying the row numbers to delete
;		This vector will be sorted and duplicates removed by FTDELROW
;
; EXAMPLE:
;	Compress a table to include only non-negative flux values
;
;	flux = FTGET(h,tab,'FLUX')       ;Obtain original flux vector
;	bad = where(flux lt 0)           ;Find negative fluxes
;	FTDELROW,h,tab,bad               ;Delete rows with negative fluxes
;
; PROCEDURE:
;	Specified rows are deleted from the data array, TAB.  The NAXIS2
;	keyword in the header is updated.
;
; REVISION HISTORY:                                           
;	Written   W. Landsman        STX Co.     August, 1988
;	Checked for IDL Version 2, J. Isensee, July, 1990
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;      FTGET 
; PURPOSE:
;      Function to return value(s) from specified column in a FITS ASCII table
;
; CALLING SEQUENCE
;      values = FTGET( h, tab, field, [ rows, nulls ] )
;                    or
;      values = FTGET( ft_str, tab, field. [rows, nulls]
; INPUTS:
;      h - FITS ASCII extension header (e.g. as returned by FITS_READ)
;                            or
;      ft_str - FITS table structure extracted from FITS header by FTINFO
;                Use of the IDL structure will improve processing speed
;      tab - FITS ASCII table array (e.g. as returned by FITS_READ)
;      field - field name or number
;
; OPTIONAL INPUTS:
;      rows -  scalar or vector giving row number(s)
;               Row numbers start at 0.  If not supplied or set to
;               -1 then values for all rows are returned
;
; OUTPUTS:
;       the values for the row are returned as the function value.
;       Null values are set to 0 or blanks for strings.
;
; OPTIONAL OUTPUT:
;       nulls - null value flag of same length as the returned data.
;               It is set to 1 at null value positions and 0 elsewhere.
;               If supplied then the optional input, rows, must also 
;               be supplied.
;
; EXAMPLE:
;       Read the columns labeled 'WAVELENGTH' and 'FLUX' from the second
;       (ASCII table) extension of a FITS file 'spectra.fit'
;
;       IDL> fits_read,'spectra.fit',tab,htab,exten=2     ;Read 2nd extension
;       IDL> w = ftget( htab, tab,'wavelength')      ;Wavelength vector
;       IDL> f = ftget( htab, tab,'flux')            ;Flux vector
;
;       Slightly more efficient would be to first call FTINFO
;       IDL> ftinfo, htab, ft_str                     ;Extract structure
;       IDL> w = ftget(ft_str, tab,'wavelength')      ;Wavelength vector
;       IDL> f = ftget(ft_str, tab,'flux')            ;Flux vector
;
; NOTES:
;       (1) Use the higher-level procedure FTAB_EXT to extract vectors 
;               directly from the FITS file.
;       (2) Use FTAB_HELP or FTHELP to determine the columns in a particular
;               ASCII table.
; HISTORY:
;       coded by D. Lindler  July, 1987
;       Always check for null values    W. Landsman          August 1990
;       More informative error message  W. Landsman          Feb. 1996
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Allow structure rather than FITS header  W. Landsman   May 2000
;       No case sensitivity in TTYPE name      W. Landsman   February 2002

; NAME:
;       FTHELP
; PURPOSE:
;       Routine to print a description of a FITS ASCII table extension
;
; CALLING SEQUENCE:
;       FTHELP, H, [ TEXTOUT = ]
;
; INPUTS:
;       H - FITS header for ASCII table extension, string array
;
; OPTIONAL INPUT KEYWORD
;       TEXTOUT - scalar number (0-7) or string (file name) determining
;               output device (see TEXTOPEN).  Default is TEXTOUT=1, output 
;               to the user's terminal    
;
; NOTES:
;       FTHELP checks that the keyword XTENSION  equals 'TABLE' in the FITS
;               header.
;
; SYSTEM VARIABLES:
;       Uses the non-standard system variables !TEXTOUT and !TEXTUNIT
;       which must be defined (e.g. with ASTROLIB) prior to compilation.
; PROCEDURES USED:
;       REMCHAR, SXPAR(), TEXTOPEN, TEXTCLOSE, ZPARCHECK
;
; HISTORY:
;       version 1  W. Landsman  Jan. 1988
;       Add TEXTOUT option, cleaner format  W. Landsman   September 1991
;       TTYPE value can be longer than 8 chars,  W. Landsman  August 1995
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Remove calls to !ERR, some vectorization  W. Landsman  February 2000 

; NAME:
;       FTHMOD
; PURPOSE:
;       Procedure to modify header information for a specified field
;       in a FITS table.
;
; CALLING SEQUENCE:
;       fthmod, h, field, parameter, value
;       
; INPUT:
;       h - FITS header for the table
;       field - field name or number
;       parameter - string name of the parameter to modify.  Choices
;               include:
;                       TTYPE - field name
;                       TUNIT - physical units for field (eg. 'ANGSTROMS')
;                       TNULL - null value (string) for field, (eg. '***')
;                       TFORM - format specification for the field
;                       TSCAL - scale factor
;                       TZERO - zero offset
;               User should be aware that the validity of the change is
;               not checked.  Unless you really know what you are doing,
;               this routine should only be used to change field names,
;               units, or another user specified parameter.
;       value - new value for the parameter.  Refer to the FITS table
;               standards documentation for valid values.
;
; EXAMPLE:
;      Change the units for a field name "FLUX" to "Janskys" in a FITS table
;        header,h
;
;      IDL> FTHMOD, h, 'FLUX', 'TUNIT','Janskys' 
; METHOD:
;       The header keyword  is modified
;       with the new value.
; HISTORY:
;       version 1, D. Lindler  July 1987
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Major rewrite to use new FTINFO call   W. Landsman   May 2000

; NAME:
;       FTINFO
; PURPOSE:
;       Return an informational structure from a FITS ASCII table header.
; CALLING SEQUENCE:
;       ftinfo,h,ft_str, [Count = ]
;
; INPUTS:
;       h - FITS ASCII table header, string array
;
; OUTPUTS:
;       ft_str - IDL structure with extracted info from the FITS ASCII table
;                header.   Tags include
;        .tbcol - starting column position in bytes
;        .width - width of the field in bytes
;        .idltype - idltype of field.
;                       7 - string, 4- real*4, 3-integer, 5-real*8
;        .tunit - string unit numbers
;        .tscal - scale factor
;        .tzero - zero point for field
;        .tnull - null value for the field
;        .tform - format for the field
;        .ttype - field name
;
; OPTIONAL OUTPUT KEYWORD:
;       Count - Integer scalar giving number of fields in the table
; PROCEDURES USED:
;       GETTOK(), SXPAR()
; NOTES:
;       This procedure underwent a major revision in May 2000, and **THE
;       NEW CALLING SEQUENCE IS INCOMPATIBLE WITH THE OLD ONE **
; HISTORY:
;       D. Lindler  July, 1987
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Major rewrite, return structure   W. Landsman   April 2000

; NAME:
;	FTKEEPROW
; PURPOSE:
;	Subscripts (and reorders) a FITS table.  A companion piece to FTDELROW.
;
; CALLING SEQUENCE:
;	ftkeeprow, h, tab, subs
;
; INPUT PARAMETERS:
;	h    = FITS table header array
;	tab  = FITS table data array
;	subs = subscript array of FITS table rows.  Works like any other IDL
;		subscript array (0 based, of course).
;
; OUTPUT PARAMETERS:
;	h and tab are modified
;
; MODIFICATION HISTORY:
;	Written by R. S. Hill, ST Sys. Corp., 2 May 1991.
;	Converted to IDL V5.0   W. Landsman   September 1997

;  NAME:
;      FTPRINT
;  PURPOSE:
;       Procedure to print specified columns and rows of a FITS table
;
; CALLING SEQUENCE:
;       FTPRINT, h, tab, columns, [ rows, TEXTOUT = ]
;
; INPUTS:
;       h - Fits header for table, string array
;       tab - table array 
;       columns - string giving column names, or vector giving
;               column numbers (beginning with 1).  If string 
;               supplied then column names should be separated by comma's.
;       rows - (optional) vector of row numbers to print.  If
;               not supplied or set to scalar, -1, then all rows
;               are printed.
;
; OUTPUTS:
;       None
;
; OPTIONAL INPUT KEYWORDS:
;       TEXTOUT controls the output device; see the procedure TEXTOPEN
;
; SYSTEM VARIABLES:
;       Uses nonstandard system variables !TEXTOUT and !TEXTOPEN
;       These will be defined (using ASTROLIB) if not already present.
;       Set !TEXTOUT = 3 to direct output to a disk file.   The system
;       variable is overriden by the value of the keyword TEXTOUT
;
; EXAMPLES:
;
;       ftprint,h,tab,'STAR ID,RA,DEC'    ;print id,ra,dec for all stars
;       ftprint,h,tab,[2,3,4],indgen(100) ;print columns 2-4 for 
;                                         ;first 100 stars
;       ftprint,h,tab,text="stars.dat"    ;Convert entire FITS table to
;                                         ;an ASCII file named STARS.DAT
;
; PROCEDURES USED:
;       FTSIZE, FTINFO, TEXTOPEN, TEXTCLOSE
;
; RESTRICTIONS: 
;       (1) Program does not check whether output length exceeds output
;               device capacity (e.g. 80 or 132).
;       (2) Column heading may be truncated to fit in space defined by
;               the FORMAT specified for the column
;       (3) Program does not check for null values
;
; HISTORY:
;       version 1  D. Lindler Feb. 1987
;       Accept undefined values of rows, columns   W. Landsman August 1997
;       Converted to IDL V5.0   W. Landsman   September 1997
;       New FTINFO calling sequence    W. Landsman   May 2000
;       Parse scalar string with STRSPLIT   W. Landsman  July 2002
;       Fix format display of row number  W. Landsman March 2003
;       Fix format display of row number again  W. Landsman May 2003

; NAME:
;       FTPUT
; PURPOSE:
;       Procedure to add or update a field in an FITS ASCII table
;
; CALLING SEQUENCE:
;       FTPUT, htab, tab, field, row, values, [ nulls ]
;
; INPUTS:
;       htab - FITS ASCII table header string array
;       tab - FITS ASCII table array (e.g. as read by READFITS)
;       field - string field name or integer field number
;       row -  either a non-negative integer scalar giving starting row to 
;               update, or a non-negative integer vector specifying rows to 
;               update.   FTPUT will append a new row to a table if the value 
;               of 'row' exceeds the number of rows in the tab array    
;       values - value(s) to add or update.   If row is a vector
;               then values must contain the same number of elements.
;
; OPTIONAL INPUT:
;       nulls - null value flag of same length as values.
;               It should be set to 1 at null value positions
;               and 0 elsewhere.
;
; OUTPUTS:
;       htab,tab will be updated as specified.
;
; EXAMPLE:
;       One has a NAME and RA  and Dec vectors for 500 stars with formats A6,
;       F9.5 and F9.5 respectively.   Write this information to an ASCII table 
;       named 'star.fits'.
;
;       IDL> FTCREATE,24,500,h,tab       ;Create table header and (empty) data
;       IDL> FTADDCOL,h,tab,'RA',8,'F9.5','DEGREES'   ;Explicity define the
;       IDL> FTADDCOL,h,tab,'DEC',8,'F9.5','DEGREES'  ;RA and Dec columns
;       IDL> FTPUT,h,tab,'RA',0,ra       ;Insert RA vector into table
;       IDL> FTPUT,h,tab,'DEC',0,dec       ;Insert DEC vector into table
;       IDL> FTPUT, h,tab, 'NAME',0,name   ;Insert NAME vector with default
;       IDL> WRITEFITS,'stars.fits',tab,h ;Write to a file
;   
;      Note that (1) explicit formatting has been supplied for the (numeric)
;      RA and Dec vectors, but was not needed for the NAME vector, (2) A width
;      of 24 was supplied in FTCREATE based on the expected formats (6+9+9),
;      though the FT* will adjust this value as necessary, and (3) WRITEFITS
;      will create a minimal primary header  
; NOTES:
;       (1) If the specified field is not already in the table, then FTPUT will
;       create a new column for that field using default formatting.   However,
;        FTADDCOL should be called prior to FTPUT for explicit formatting.
;
; PROCEDURES CALLED
;       FSTRING(), FTADDCOL, FTINFO, FTSIZE, SXADDPAR, SXPAR()
; HISTORY:
;       version 1  D. Lindler July, 1987
;       Allow E format         W. Landsman          March 1992
;       Write in F format if E format will overflow    April 1994
;       Update documentation W. Landsman   January 1996
;       Allow 1 element vector  W. Landsman   March 1996
;       Adjust string length to maximum of input string array   June 1997
;       Work for more than 32767 elements August 1997
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Updated call to the new FTINFO   W. Landsman   May 2000
;       Fix case where header does not have any columns yet W.Landsman Sep 2002

; NAME:
;       FTSIZE
; PURPOSE:
;       Procedure to return the size of a FITS ASCII table.
;
; CALLING SEQUENCE:
;       ftsize,h,tab,ncols,rows,tfields,ncols_all,nrows_all, [ERRMSG = ]
;
; INPUTS:
;       h - FITS ASCII table header, string array
;       tab - FITS table array, 2-d byte array
;
; OUTPUTS:
;       ncols - number of characters per row in table
;       nrows - number of rows in table
;       tfields - number of fields per row
;       ncols_all - number of characters/row allocated (size of tab)
;       nrows_all - number of rows allocated
;
; OPTIONAL OUTPUT KEYWORD:
;       ERRMSG  = If this keyword is present, then any error messages will be
;                 returned to the user in this parameter rather than
;                 depending on the MESSAGE routine in IDL.  If no errors are
;                 encountered, then a null string is returned.  
; HISTORY
;       D. Lindler  July, 1987
;       Fix for 1-row table,  W. Landsman    HSTX,     June 1994
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Added ERRMSG keyword   W. Landsman   May 2000
;       

; NAME:
;      FTSORT
; PURPOSE:
;      Sort a FITS ASCII table according to a specified field
;
; CALLING SEQUENCE:
;      FTSORT,h,tab,[field, REVERSE = ]               ;Sort original table header and array
;               or
;      FTSORT,h,tab,hnew,tabnew,[field, REVERSE =]   ;Create new sorted header
;
; INPUTS:
;      H - FITS header (string array)
;      TAB - FITS table (byte array) associated with H.  If less than 4
;               parameters are supplied, then H and TAB will be updated to 
;               contain the sorted table
;
; OPTIONAL INPUTS:
;      FIELD - Field name(s) or number(s) used to sort the entire table.  
;              If FIELD is a vector then the first element is used for the 
;              primary sort, the second element is used for the secondary
;              sort, and so forth.   (A secondary sort only takes effect when
;              values in the primary sort  field are equal.)  Character fields
;              are sorted using the ASCII collating sequence.  If omitted,
;              the user will be prompted for the field name.
;
; OPTIONAL OUTPUTS:
;      HNEW,TABNEW - Header and table containing the sorted tables
;
; EXAMPLE:
;      Sort a FITS ASCII table by the 'DECLINATION' field in descending order
;      Assume that the table header htab, and array, tab, have already been
;      read (e.g. with READFITS or FITS_READ):

;      IDL> FTSORT, htab, tab,'DECLINATION',/REVERSE
; OPTIONAL INPUT KEYWORD:
;       REVERSE - If set then the table is sorted in reverse order (maximum
;              to minimum.    If FIELD is a vector, then REVERSE can also be
;              a vector.   For example, REVERSE = [1,0] indicates that the
;              primary sort should be in descending order, and the secondary
;              sort should be in ascending order.
;
; EXAMPLE:
; SIDE EFFECTS:
;       A HISTORY record is added to the table header.
; REVISION HISTORY:
;      Written W. Landsman                         June, 1988
;      Converted to IDL V5.0   W. Landsman   September 1997
;      New FTINFO calling sequence, added REVERSE keyword, allow secondary sorts
;                  W. Landsman   May 2000

; NAME: 
;       FXADDPAR
; Purpose     : 
;       Add or modify a parameter in a FITS header array.
; Explanation : 
;       This version of FXADDPAR will write string values longer than 68 
;       characters using the FITS continuation convention described at 
;       http://heasarc.gsfc.nasa.gov/docs/heasarc/ofwg/docs/ofwg_recomm/r13.html
; Use         : 
;       FXADDPAR, HEADER, NAME, VALUE, COMMENT
; Inputs      : 
;       HEADER  = String array containing FITS header.  The maximum string
;                 length must be equal to 80.  If not defined, then FXADDPAR
;                 will create an empty FITS header array.
;
;       NAME    = Name of parameter.  If NAME is already in the header the
;                 value and possibly comment fields are modified. Otherwise a
;                 new record is added to the header.  If NAME is equal to
;                 either "COMMENT" or "HISTORY" then the value will be added to
;                 the record without replacement.  In this case the comment
;                 parameter is ignored.
;
;       VALUE   = Value for parameter.  The value expression must be of the
;                 correct type, e.g. integer, floating or string.
;                 String values of 'T' or 'F' are considered logical
;                 values.  If the value is a string and is "long"
;                 (more than 69 characters), then it may be continued
;                 over more than one line using the OGIP CONTINUE
;                 standard.
;
; Opt. Inputs : 
;       COMMENT = String field.  The '/' is added by this routine.  Added
;                 starting in position 31.  If not supplied, or set equal to ''
;                 (the null string), then any previous comment field in the
;                 header for that keyword is retained (when found).
; Outputs     : 
;       HEADER  = Updated header array.
; Opt. Outputs: 
;       None.
; Keywords    : 
;       BEFORE  = Keyword string name.  The parameter will be placed before the
;                 location of this keyword.  For example, if BEFORE='HISTORY'
;                 then the parameter will be placed before the first history
;                 location.  This applies only when adding a new keyword;
;                 keywords already in the header are kept in the same position.
;
;       AFTER   = Same as BEFORE, but the parameter will be placed after the
;                 location of this keyword.  This keyword takes precedence over
;                 BEFORE.
;
;       FORMAT  = Specifies FORTRAN-like format for parameter, e.g. "F7.3".  A
;                 scalar string should be used.  For complex numbers the format
;                 should be defined so that it can be applied separately to the
;                 real and imaginary parts.
;
;       /NOCONTINUE = By default, FXADDPAR will break strings longer than 68 
;                characters into multiple lines using the continuation
;                convention.    If this keyword is set, then the line will
;                instead be truncated to 68 characters.    This was the default
;                behaviour of FXADDPAR prior to December 1999.  
; Calls       : 
;       DETABIFY(), FXPAR(), FXPARPOS()
; Common      : 
;       None.
; Restrictions: 
;       Warning -- Parameters and names are not checked against valid FITS
;       parameter names, values and types.
;
;       The required FITS keywords SIMPLE (or XTENSION), BITPIX, NAXIS, NAXIS1,
;       NAXIS2, etc., must be entered in order.  The actual values of these
;       keywords are not checked for legality and consistency, however.
;
; Side effects: 
;       All HISTORY records are inserted in order at the end of the header.
;
;       All COMMENT records are also inserted in order at the end of the
;       header, but before the HISTORY records.  The BEFORE and AFTER keywords
;       can override this.
;
;       All records with no keyword (blank) are inserted in order at the end of
;       the header, but before the COMMENT and HISTORY records.  The BEFORE and
;       AFTER keywords can override this.
;
;       All other records are inserted before any of the HISTORY, COMMENT, or
;       "blank" records.  The BEFORE and AFTER keywords can override this.
;
;       String values longer than 68 characters will be split into multiple
;       lines using the OGIP CONTINUE convention, unless the /NOCONTINUE keyword
;       is set.    For a description of the CONTINUE convention see    
;       http://heasarc.gsfc.nasa.gov/docs/heasarc/ofwg/docs/ofwg_recomm/r13.htm
; Category    : 
;       Data Handling, I/O, FITS, Generic.
; Prev. Hist. : 
;       William Thompson, Jan 1992, from SXADDPAR by D. Lindler and J. Isensee.
;       Differences include:
;
;               * LOCATION parameter replaced with keywords BEFORE and AFTER.
;               * Support for COMMENT and "blank" FITS keywords.
;               * Better support for standard FITS formatting of string and
;                 complex values.
;               * Built-in knowledge of the proper position of required
;                 keywords in FITS (although not necessarily SDAS/Geis) primary
;                 headers, and in TABLE and BINTABLE extension headers.
;
;       William Thompson, May 1992, fixed bug when extending length of header,
;       and new record is COMMENT, HISTORY, or blank.
; Written     : 
;       William Thompson, GSFC, January 1992.
; Modified    : 
;       Version 1, William Thompson, GSFC, 12 April 1993.
;               Incorporated into CDS library.
;       Version 2, William Thompson, GSFC, 5 September 1997
;               Fixed bug replacing strings that contain "/" character--it
;               interpreted the following characters as a comment.
;       Version 3, Craig Markwardt, GSFC,  December 1997
;               Allow long values to extend over multiple lines
;	Version 4, D. Lindler, March 2000, modified to use capital E instead
;		of a lower case e for exponential format.
;       Version 4.1 W. Landsman April 2000, make user-supplied format uppercase
;       Version 4.2 W. Landsman July 2002, positioning of EXTEND keyword
; Version     : 
;       Version 4.2, July 2002

; NAME: 
;	FXBADDCOL
; Purpose     : 
;	Adds a column to a binary table extension.
; Explanation : 
;	Modify a basic FITS binary table extension (BINTABLE) header array to
;	define a column.
; Use         : 
;	FXBADDCOL, INDEX, HEADER, ARRAY  [, TTYPE [, COMMENT ]]
; Inputs      : 
;	HEADER	= String array containing FITS extension header.
;	ARRAY	= IDL variable used to determine the data size and type
;		  associated with the column.  If the column is defined as
;		  containing variable length arrays, then ARRAY must be of the
;		  maximum size to be stored in the column.
; Opt. Inputs : 
;	TTYPE	= Column label.
;	COMMENT = Comment for TTYPE
; Outputs     : 
;	INDEX	= Index (1-999) of the created column.
;	HEADER	= The header is modified to reflect the added column.
; Opt. Outputs: 
;	None.
; Keywords    : 
;	VARIABLE= If set, then the column is defined to contain pointers to
;		  variable length arrays in the heap area.
;	DCOMPLEX= If set, and ARRAY is complex, with the first dimension being
;		  two (real and imaginary parts), then the column is defined as
;		  double-precision complex (type "M").     This keyword is
;		  only needed prior to IDL Version 4.0, when the double 
;		  double complex datatype was unavailable in IDL
;	BIT	= If passed, and ARRAY is of type byte, then the column is
;		  defined as containg bit mask arrays (type "X"), with the
;		  value of BIT being equal to the number of mask bits.
;	LOGICAL	= If set, and array is of type byte, then the column is defined
;		  as containing logical arrays (type "L").
;	NO_TDIM	= If set, then the TDIMn keyword is not written out to the
;		  header.  No TDIMn keywords are written for columns containing
;		  variable length arrays.
;	TUNIT	= If passed, then corresponding keyword is added to header.
;	TSCAL	= Same.
;	TZERO	= Same.
;	TNULL	= Same.
;	TDISP	= Same.
;	TDMIN	= Same.
;	TDMAX	= Same.
;	TDESC	= Same.
;	TCUNI	= Same.
;	TROTA	= Same.
;	TRPIX	= Same.
;	TRVAL	= Same.
;	TDELT	= Same.
;	ERRMSG	= If defined and passed, then any error messages will be
;		  returned to the user in this parameter rather than
;		  depending on the MESSAGE routine in IDL.  If no errors are
;		  encountered, then a null string is returned.  In order to
;		  use this feature, ERRMSG must be defined first, e.g.
;
;			ERRMSG = ''
;			FXBADDCOL, ERRMSG=ERRMSG, ...
;			IF ERRMSG NE '' THEN ...
;
; Calls       : 
;	FXADDPAR, FXPAR
; Common      : 
;	None.
; Restrictions: 
;	Warning: No checking is done of any of the parameters defining the
;	values of optional FITS keywords.
;
;	FXBHMAKE must first be called to initialize the header.
;
;	If ARRAY is of type character, then it must be of the maximum length
;	expected for this column.  If a character string array, then the
;	largest string in the array is used to determine the maximum length.
;
;	The DCOMPLEX keyword is ignored if ARRAY is not double-precision.
;	ARRAY must also have a first dimension of two representing the real and
;	imaginary parts.
;
;	The BIT and LOGICAL keywords are ignored if ARRAY is not of type byte.
;	BIT takes precedence over LOGICAL.
;
; Side effects: 
;	If the data array is multidimensional, then a TDIM keyword is added to
;	the header, unless either NO_TDIM or VARIABLE is set.
;
;	No TDIMn keywords are written out for bit arrays (format 'X'), since
;	the dimensions would refer to bits, not bytes.
;
; Category    : 
;	Data Handling, I/O, FITS, Generic.
; Prev. Hist. : 
;	William Thompson, Jan 1992.
;	W. Thompson, Feb 1992, changed from function to procedure.
;	W. Thompson, Feb 1992, modified to support variable length arrays.
; Written     : 
;	William Thompson, GSFC, January 1992.
; Modified    : 
;	Version 1, William Thompson, GSFC, 12 April 1993.
;		Incorporated into CDS library.
;	Version 2, William Thompson, GSFC, 31 May 1994
;		Added ERRMSG keyword.
;       Version 3, William Thompson, GSFC, 23 June 1994
;               Modified so that ERRMSG is not touched if not defined.
;	Version 4, William Thompson, GSFC, 30 December 1994
;		Added keyword TCUNI.
;	Version 5, Wayne Landsman, GSFC, 12 Aug 1997
;		Recognize double complex IDL datatype
; Version     :
;       Version 5, 12 Aug 1997
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME: 
;	FXBCLOSE
; Purpose     : 
;	Close a FITS binary table extension opened for read.
; Explanation : 
;	Closes a FITS binary table extension that had been opened for read by
;	FXBOPEN.
; Use         : 
;	FXBCLOSE, UNIT
; Inputs      : 
;	UNIT	= Logical unit number of the file.
; Opt. Inputs : 
;	None.
; Outputs     : 
;	None.
; Opt. Outputs: 
;	None.
; Keywords    : 
;	ERRMSG	  = If defined and passed, then any error messages will be
;		    returned to the user in this parameter rather than
;		    depending on the MESSAGE routine in IDL.  If no errors are
;		    encountered, then a null string is returned.  In order to
;		    use this feature, ERRMSG must be defined first, e.g.
;
;			ERRMSG = ''
;			FXBCLOSE, ERRMSG=ERRMSG, ...
;			IF ERRMSG NE '' THEN ...
;
; Calls       : 
;	None.
; Common      : 
;	Uses common block FXBINTABLE--see "fxbintable.pro" for more
;	information.
; Restrictions: 
;	The file must have been opened with FXBOPEN.
; Side effects: 
;	None.
; Category    : 
;	Data Handling, I/O, FITS, Generic.
; Prev. Hist. : 
;	W. Thompson, Feb. 1992.
; Written     : 
;	William Thompson, GSFC, February 1992.
; Modified    : 
;	Version 1, William Thompson, GSFC, 12 April 1993.
;		Incorporated into CDS library.
;	Version 2, William Thompson, GSFC, 21 June 1994
;		Added ERRMSG keyword.
;       Version 3, William Thompson, GSFC, 23 June 1994
;               Modified so that ERRMSG is not touched if not defined.
; Version     :
;       Version 3, 23 June 1994
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME: 
;	FXBCOLNUM()
; Purpose     : 
;	Returns a binary table column number.
; Explanation : 
;	Given a column specified either by number or name, this routine will
;	return the appropriate column number.
; Use         : 
;	Result = FXBCOLNUM( UNIT, COL )
; Inputs      : 
;	UNIT	= Logical unit number corresponding to the file containing the
;		  binary table.
;	COL	= Column in the binary table, given either as a character
;		  string containing a column label (TTYPE), or as a numerical
;		  column index starting from column one.
; Opt. Inputs : 
;	None.
; Outputs     : 
;	The result of the function is the number of the column specified, or
;	zero if no column is found (when passed by name).
; Opt. Outputs: 
;	None.
; Keywords    : 
;	ERRMSG	  = If defined and passed, then any error messages will be
;		    returned to the user in this parameter rather than
;		    depending on the MESSAGE routine in IDL.  If no errors are
;		    encountered, then a null string is returned.  In order to
;		    use this feature, ERRMSG must be defined first, e.g.
;
;			ERRMSG = ''
;			Result = FXBCOLNUM( ERRMSG=ERRMSG, ... )
;			IF ERRMSG NE '' THEN ...
;
; Calls       : 
;	None.
; Common      : 
;	Uses common block FXBINTABLE--see "fxbintable.pro" for more
;	information.
; Restrictions: 
;	The binary table file must have been opened with FXBOPEN.
;
;	If COL is passed as a number, rather than as a name, then it must be
;	consistent with the number of columns in the table.
;
; Side effects: 
;	None.
; Category    : 
;	Data Handling, I/O, FITS, Generic.
; Prev. Hist. : 
;	None.
; Written     : 
;	William Thompson, GSFC, 2 July 1993.
; Modified    : 
;	Version 1, William Thompson, GSFC, 2 July 1993.
;	Version 2, William Thompson, GSFC, 29 October 1993.
;		Added error message for not finding column by name.
;	Version 3, William Thompson, GSFC, 21 June 1994
;		Added ERRMSG keyword.
;       Version 4, William Thompson, GSFC, 23 June 1994
;               Modified so that ERRMSG is not touched if not defined.
; Version     :
;       Version 4, 23 June 1994
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME: 
;	FXBCREATE
; Purpose     : 
;	Open a new binary table at the end of a FITS file.
; Explanation : 
;	Write a binary table extension header to the end of a disk FITS file,
;	and leave it open to receive the data.
;
;	The FITS file is opened, and the pointer is positioned just after the
;	last 2880 byte record.  Then the binary header is appended.  Calls to
;	FXBWRITE will append the binary data to this file, and then FXBFINISH
;	will close the file.
;
; Use         : 
;	FXBCREATE, UNIT, FILENAME, HEADER
; Inputs      : 
;	FILENAME = Name of FITS file to be opened.
;	HEADER	 = String array containing the FITS binary table extension
;		   header.
; Opt. Inputs : 
;	None.
; Outputs     : 
;	UNIT	 = Logical unit number of the opened file.
;       EXTENSION= Extension number of newly created extension.
; Opt. Outputs: 
;	None.
; Keywords    : 
;	ERRMSG	  = If defined and passed, then any error messages will be
;		    returned to the user in this parameter rather than
;		    depending on the MESSAGE routine in IDL.  If no errors are
;		    encountered, then a null string is returned.  In order to
;		    use this feature, ERRMSG must be defined first, e.g.
;
;			ERRMSG = ''
;			FXBCREATE, ERRMSG=ERRMSG, ...
;			IF ERRMSG NE '' THEN ...
;
; Calls       : 
;	FXADDPAR, FXBFINDLUN, FXBPARSE, FXFINDEND
; Common      : 
;	Uses common block FXBINTABLE--see "fxbintable.pro" for more
;	information.
; Restrictions: 
;	The primary FITS data unit must already be written to a file.  The
;	binary table extension header must already be defined (FXBHMAKE), and
;	must match the data that will be written to the file.
; Side effects: 
;	None.
; Category    : 
;	Data Handling, I/O, FITS, Generic.
; Prev. Hist. : 
;	W. Thompson, Jan 1992, based on WRITEFITS by J. Woffard and W. Landsman.
;	W. Thompson, Feb 1992, changed from function to procedure.
;	W. Thompson, Feb 1992, removed all references to temporary files.
; Written     : 
;	William Thompson, GSFC, January 1992.
; Modified    : 
;	Version 1, William Thompson, GSFC, 12 April 1993.
;		Incorporated into CDS library.
;	Version 2, William Thompson, GSFC, 21 July 1993.
;		Fixed bug with variable length arrays.
;	Version 3, William Thompson, GSFC, 21 June 1994
;		Added ERRMSG keyword.
;	Version 4, William Thompson, GSFC, 23 June 1994
;               Modified so that ERRMSG is not touched if not defined.
;	Version 5, Antony Bird, Southampton, 25 June 1997
;		Modified to allow very long tables 
; Version     :
;	Version 5, 25 June 1997
;	Converted to IDL V5.0   W. Landsman   September 1997
;       Added EXTENSION parameter, C. Markwardt 1999 Jul 15
;       More efficient zeroing of file, C. Markwardt, 26 Feb 2001

; NAME:
;     FXBDIMEN()
;
; PURPOSE:      
;      Returns the dimensions for a column in a FITS binary table.
;
; Explanation : This procedure returns the dimensions associated with a column
;               in a binary table opened for read with the command FXBOPEN.
;
; Use         : Result = FXBDIMEN(UNIT,COL)
;
; Inputs      : UNIT    = Logical unit number returned by FXBOPEN routine.
;                         Must be a scalar integer.
;
;               COL     = Column in the binary table to read data from, either
;                         as a character string containing a column label
;                         (TTYPE), or as a numerical column index starting from
;                         column one.
;
; Opt. Inputs : None.
;
; Outputs     : The result of the function is an array containing the
;               dimensions for the specified column in the FITS binary table
;               that UNIT points to.
;
; Opt. Outputs: None.
;
; Keywords :    ERRMSG  = If defined and passed, then any error messages will
;                         be returned to the user in this parameter rather than
;                         depending on the MESSAGE routine in IDL.  If no
;                         errors are encountered, then a null string is
;                         returned.  In order to use this feature, ERRMSG must
;                         be defined first, e.g.
;
;                               ERRMSG = ''
;                               Result = FXBDIMEN( ERRMSG=ERRMSG, ... )
;                               IF ERRMSG NE '' THEN ...
;
; Calls       : FXBCOLNUM, FXBFINDLUN
;
; Common      : Uses common block FXBINTABLE--see "fxbintable.pro" for more
;               information.
;
; Restrictions: None.
;
; Side effects: The dimensions will be returned whether or not the table is
;               still open or not.
;
;               If UNIT does not point to a binary table, then 0 is returned.
;
;               If UNIT is an undefined variable, then 0 is returned.
;
; Category    : Data Handling, I/O, FITS, Generic.
;
; Prev. Hist. : None.
;
; Written     : William Thompson, GSFC, 4 March 1994.
;
; Modified    : Version 1, William Thompson, GSFC, 4 March 1994.
;               Version 2, William Thompson, GSFC, 21 June 1994
;                       Added ERRMSG keyword.
;               Version 3, William Thompson, GSFC, 23 June 1994
;                       Modified so that ERRMSG is not touched if not defined.
;
; Version     : Version 3, 23 June 1994
;       Converted to IDL V5.0   W. Landsman   September 1997

; NAME: 
;	FXBFIND
; Purpose     : 
;	Find column keywords in a FITS binary table header.
; Explanation : 
;	Finds the value of a column keyword for all the columns in the binary
;	table for which it is set.  For example,
;
;		FXBFIND, UNIT, 'TTYPE', COLUMNS, VALUES, N_FOUND
;
;	Would find all instances of the keywords TTYPE1, TTYPE2, etc.  The
;	array COLUMNS would contain the column numbers for which a TTYPEn
;	keyword was found, and VALUES would contain the values.  N_FOUND would
;	contain the total number of instances found.
;
; Use         : 
;	FXBFIND, [UNIT or HEADER], KEYWORD, COLUMNS, VALUES, N_FOUND
;		[, DEFAULT ]
; Inputs      : 
;	Either UNIT or HEADER must be passed.
;
;	UNIT	= Logical unit number of file opened by FXBOPEN.
;	HEADER	= FITS binary table header.
;	KEYWORD	= Prefix to a series of FITS binary table column keywords.  The
;		  keywords to be searched for are formed by combining this
;		  prefix with the numbers 1 through the value of TFIELDS in the
;		  header.
; Opt. Inputs : 
;	DEFAULT	= Default value to use for any column keywords that aren't
;		  found.  If passed, then COLUMNS and VALUES will contain
;		  entries for every column.  Otherwise, COLUMNS and VALUES only
;		  contain entries for columns where values were found.
; Outputs     : 
;	COLUMNS	= Array containing the column numbers for which values of the
;		  requested keyword series were found.
;	VALUES	= Array containing the found values.
;	N_FOUND	= Number of values found.  The value of this parameter is
;		  unaffected by whether or not DEFAULT is passed.
; Opt. Outputs: 
;	None.
; Keywords    : 
;	None.
; Calls       : 
;	FXBFINDLUN, FXPAR
; Common      : 
;	Uses common block FXBINTABLE--see "fxbintable.pro" for more
;	information.
; Restrictions: 
;	If UNIT is passed, then the file must have been opened with FXBOPEN.
;	If HEADER is passed, then it must be a legal FITS binary table header.
;
;	The type of DEFAULT must be consistent with the values of the requested
;	keywords, i.e. both most be either of string or numerical type.
;
;	The KEYWORD prefix must not have more than five characters to leave
;	room for the three digits allowed for the column numbers.
;
; Side effects: 
;	None.
; Category    : 
;	Data Handling, I/O, FITS, Generic.
; Prev. Hist. : 
;	William Thompson, Feb. 1992.
; Written     : 
;	William Thompson, GSFC, February 1992.
; Modified    : 
;	Version 1, William Thompson, GSFC, 12 April 1993.
;		Incorporated into CDS library.
; Version     : 
;	Version 1, 12 April 1993.
;       Vectorized implementation improves performance, CM 18 Nov 1999

; NAME: 
;	FXBFINDLUN()
; Purpose     : 
;	Find logical unit number UNIT in FXBINTABLE common block.
; Explanation : 
;	Finds the proper index to use for getting information about the logical
;	unit number UNIT in the arrays stored in the FXBINTABLE common block.
;	Called from FXBCREATE and FXBOPEN.
; Use         : 
;	Result = FXBFINDLUN( UNIT )
; Inputs      : 
;	UNIT	= Logical unit number.
; Opt. Inputs : 
;	None.
; Outputs     : 
;	The result of the function is an index into the FXBINTABLE common
;	block.
; Opt. Outputs: 
;	None.
; Keywords    : 
;	None.
; Calls       : 
;	None.
; Common      : 
;	Uses common block FXBINTABLE--see "fxbintable.pro" for more
;	information.
; Restrictions: 
;	None.
; Side effects: 
;	If UNIT is not found in the common block, then it is added to the
;	common block.
; Category    : 
;	Data Handling, I/O, FITS, Generic.
; Prev. Hist. : 
;	William Thompson, Feb. 1992.
; Written     : 
;	William Thompson, GSFC, February 1992.
; Modified    : 
;	Version 1, William Thompson, GSFC, 12 April 1993.
;		Incorporated into CDS library.
;	Version 2, William Thompson, GSFC, 21 July 1993.
;		Added DHEAP variable to fix bug with variable length arrays.
;	Version 3, Michael Schubnell, University of Michigan, 22 May 1996
;		Change N_DIMS from short to long integer.
; Version     : 
;	Version 3, 22 May 1996
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME: 
;	FXBFINISH
; Purpose     : 
;	Close a FITS binary table extension file opened for write.
; Explanation : 
;	Closes a FITS binary table extension file that had been opened for
;	write by FXBCREATE.
; Use         : 
;	FXBFINISH, UNIT
; Inputs      : 
;	UNIT	= Logical unit number of the file.
; Opt. Inputs : 
;	None.
; Outputs     : 
;	None.
; Opt. Outputs: 
;	None.
; Keywords    : 
;	ERRMSG	= If defined and passed, then any error messages will be
;		  returned to the user in this parameter rather than
;		  depending on the MESSAGE routine in IDL.  If no errors are
;		  encountered, then a null string is returned.  In order to
;		  use this feature, ERRMSG must be defined first, e.g.
;
;			ERRMSG = ''
;			FXBFINISH, ERRMSG=ERRMSG, ...
;			IF ERRMSG NE '' THEN ...
;
; Calls       : 
;	None.
; Common      : 
;	Uses common block FXBINTABLE--see "fxbintable.pro" for more
;	information.
; Restrictions: 
;	The file must have been opened with FXBCREATE, and written with
;	FXBWRITE.
; Side effects: 
;	Any bytes needed to pad the file out to an integral multiple of 2880
;	bytes are written out to the file.  Then, the file is closed.
; Category    : 
;	Data Handling, I/O, FITS, Generic.
; Prev. Hist. : 
;	W. Thompson, Jan 1992.
;	W. Thompson, Feb 1992, modified to support variable length arrays.
;	W. Thompson, Feb 1992, removed all references to temporary files.
; Written     : 
;	William Thompson, GSFC, January 1992.
; Modified    : 
;	Version 1, William Thompson, GSFC, 12 April 1993.
;		Incorporated into CDS library.
;	Version 2, William Thompson, GSFC, 21 July 1993.
;		Fixed bug with variable length arrays.
;	Version 3, William Thompson, GSFC, 31 May 1994
;		Added ERRMSG keyword.
;       Version 4, William Thompson, GSFC, 23 June 1994
;               Modified so that ERRMSG is not touched if not defined.
; Version     :
;       Version 4, 23 June 1994
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME: 
;	FXBGROW
; PURPOSE     : 
;	Increase the number of rows in a binary table.
; EXPLANATION : 
;       Call FXBGROW to increase the size of an already-existing FITS
;       binary table.  The number of rows increases to NROWS; however
;       the table cannot shrink by this operation.  This procedure is
;       useful when a table with an unknown number of rows must be
;       created.  The caller would then call FXBCREATE to construct a
;       table of some base size, and follow with calls to FXBGROW to
;       lengthen the table as needed.  The extension being enlarged
;       need not be the last extension in the file.  If subsequent
;       extensions exist in the file, they will be shifted properly.
;
; CALLING SEQUENCE :
;	FXBGROW, UNIT, HEADER, NROWS[, ERRMSG=ERRMSG, NOZERO=NOZERO]
;
; INPUT PARAMETERS :
;	UNIT     = Logical unit number of an already-opened file.
;	HEADER	 = String array containing the FITS binary table extension
;		   header.  The header is modified in place.
;       NROWS    = New number of rows, always more than the previous
;                  number.
;
; OPTIONAL INPUT KEYWORDS:
;       NOZERO   = when set, FXBGROW will not zero-pad the new data if
;                  it doesn't have to.
;	ERRMSG	  = If defined and passed, then any error messages will be
;		    returned to the user in this parameter rather than
;		    depending on the MESSAGE routine in IDL.  If no errors are
;		    encountered, then a null string is returned.  In order to
;		    use this feature, ERRMSG must be defined first, e.g.
;
;			ERRMSG = ''
;			FXBGROW, ERRMSG=ERRMSG, ...
;			IF ERRMSG NE '' THEN ...
;
; Calls       : 
;	FXADDPAR, FXHREAD, BLKSHIFT
; Common      : 
;	Uses common block FXBINTABLE--see "fxbintable.pro" for more
;	information.
; Restrictions: 
;       The file must be open with write permission.
;
;       The binary table extension in question must already by written
;       to the file (using FXBCREATE).
;
;       A table can never shrink via this operation.
;
; SIDE EFFECTS: 
;	The FITS file will grow in size, and heap areas are
;	preserved by moving them to the end of the file.
;
;       The header is modified to reflect the new number of rows.
; CATEGORY    : 
;	Data Handling, I/O, FITS, Generic.
;       Initially written, C. Markwardt, GSFC, Nov 1998
;       Added ability to enlarge arbitrary extensions and tables with
;         variable sized rows, not just the last extension in a file,
;         CM, April 2000
;

; NAME: 
;       FXBHEADER()
;
; PURPOSE: 
;       Returns the header of an open FITS binary table.
;
; Explanation : This procedure returns the FITS extension header of a FITS
;               binary table opened for read with the command FXBOPEN.
;
; Use         : Result = FXBHEADER(UNIT)
;
; Inputs      : UNIT    = Logical unit number returned by FXBOPEN routine.
;                         Must be a scalar integer.
;
; Opt. Inputs : None.
;
; Outputs     : The result of the function is a string array containing the
;               header for the FITS binary table that UNIT points to.
;
; Opt. Outputs: None.
;
; Keywords    : None.
;
; Calls       : FXBFINDLUN
;
; Common      : Uses common block FXBINTABLE--see "fxbintable.pro" for more
;               information.
;
; Restrictions: None.
;
; Side effects: The string array returned always has as many elements as the
;               largest header read by FXBOPEN.  Any extra elements beyond the
;               true header are blank or null strings.
;
;               The header will be returned whether or not the table is still
;               open or not.
;
;               If UNIT does not point to a binary table, then a string array
;               of nulls is returned.
;
;               If UNIT is an undefined variable, then the null string is
;               returned.
;
; Category    : Data Handling, I/O, FITS, Generic.
;
; Prev. Hist. : None.
;
; Written     : William Thompson, GSFC, 1 July 1993.
;
; Modified    : Version 1, William Thompson, GSFC, 1 July 1993.
;
; Version     : Version 1, 1 July 1993.
;       Converted to IDL V5.0   W. Landsman   September 1997

; NAME: 
;	FXBHELP
; Purpose     : 
;	Prints short description of columns in a FITS binary table.
; Explanation : 
;	Prints a short description of the columns in a FITS binary table to the
;	terminal screen.
; Use         : 
;	FXBHELP, UNIT
; Inputs      : 
;	UNIT	= Logical unit number of file opened by FXBOPEN.
; Opt. Inputs : 
;	None.
; Outputs     : 
;	None.
; Opt. Outputs: 
;	None.
; Keywords    : 
;	None.
; Calls       : 
;	FXBFIND, FXBFINDLUN, FXPAR
; Common      : 
;	Uses common block FXBINTABLE--see "fxbintable.pro" for more
;	information.
; Restrictions: 
;	The file must have been opened with FXBOPEN.
; Side effects: 
;	Certain fields may be truncated in the display.
; Category    : 
;	Data Handling, I/O, FITS, Generic.
; Prev. Hist. : 
;	William Thompson, Feb. 1992, from TBHELP by W. Landsman.
; Written     : 
;	William Thompson, GSFC, February 1992.
; Modified    : 
;	Version 1, William Thompson, GSFC, 12 April 1993.
;		Incorporated into CDS library.
;	Version 2, William Thompson, GSFC, 12 May 1993.
;		Modified to not write to a logical unit number assigned to the
;		terminal.  This makes it compatible with IDL for Windows.
; Version     : 
;	Version 2, 12 May 1993.
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME: 
;	FXBHMAKE
; Purpose     : 
;	Create basic FITS binary table extension (BINTABLE) header.
; Explanation : 
;	Creates a basic header array with all the required keywords, but with
;	none of the table columns defined.  This defines a basic structure
;	which can then be added to or modified by other routines.
; Use         : 
;	FXBHMAKE, HEADER, NROWS  [, EXTNAME  [, COMMENT ]]
; Inputs      : 
;	NROWS	= Number of rows in the binary table.
; Opt. Inputs : 
;	EXTNAME	= If passed, then the EXTNAME record is added with this value.
;	COMMENT = Comment to go along with EXTNAME.
; Outputs     : 
;	HEADER = String array containing FITS extension header.
; Opt. Outputs: 
;	None.
; Keywords    : 
;	INITIALIZE = If set, then the header is completely initialized, and any
;		     previous entries are lost.
;	DATE	   = If set, then the DATE keyword is added to the header.
;	EXTVER	   = Extension version number (integer).
;	EXTLEVEL   = Extension level number (integer).
;	ERRMSG	   = If defined and passed, then any error messages will be
;		     returned to the user in this parameter rather than
;		     depending on the MESSAGE routine in IDL.  If no errors are
;		     encountered, then a null string is returned.  In order to
;		     use this feature, ERRMSG must be defined first, e.g.
;
;			ERRMSG = ''
;			FXBHMAKE, ERRMSG=ERRMSG, ...
;			IF ERRMSG NE '' THEN ...
;
; Calls       : 
;	GET_DATE, FXADDPAR, FXHCLEAN
; Common      : 
;	None.
; Restrictions: 
;	Warning:  No checking is done of any of the parameters.
; Side effects: 
;	None.
; Category    : 
;	Data Handling, I/O, FITS, Generic.
; Prev. Hist. : 
;	William Thompson, Jan 1992.
;	William Thompson, Sep 1992, added EXTVER and EXTLEVEL keywords.
; Written     : 
;	William Thompson, GSFC, January 1992.
; Modified    : 
;	Version 1, William Thompson, GSFC, 12 April 1993.
;		Incorporated into CDS library.
;	Version 2, William Thompson, GSFC, 21 June 1994
;		Added ERRMSG keyword.
;       Version 3, William Thompson, GSFC, 23 June 1994
;               Modified so that ERRMSG is not touched if not defined.
; Version     :
;       Version 3, 23 June 1994
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME: 
;	FXBINTABLE
; Purpose     : 
;	Common block FXBINTABLE used by "FXB" routines.
; Explanation : 
;	This is not an IDL routine as such, but contains the definition of the
;	common block FXBINTABLE for inclusion into other routines.  By defining
;	the common block in one place, the problem of conflicting definitions
;	is avoided.
;
;	This file is included into routines that need this common block with
;	the single line (left justified)
;
;				  @fxbintable
;
;	FXBINTABLE contains the following arrays:
;
;		LUN	= An array of logical unit numbers of currently (or
;			  previously) opened binary table files.
;		STATE	= Array containing the state of the FITS files
;			  associated with the logical unit numbers, where
;			  0=closed, 1=open for read, and 2=open for write.
;		HEAD	= FITS binary table headers.
;		MHEADER	= Array containing the positions of the first data byte
;			  of the header for each file referenced by array LUN.
;		NHEADER	= Array containing the positions of the first data byte
;			  after the header for each file referenced by array
;			  LUN.
;		NAXIS1	= Values of NAXIS1 from the binary table headers.
;		NAXIS2	= Values of NAXIS2 from the binary table headers.
;		TFIELDS	= Values of TFIELDS from the binary table headers.
;		HEAP	= The start of the first byte of the heap area
;			  for variable length arrays.
;		DHEAP	= The start of the first byte of the next variable
;			  length array, if writing.
;		BYTOFF	= Byte offset from the beginning of the row for each
;			  column in the binary table headers.
;		TTYPE	= Values of TTYPE for each column in the binary table
;			  headers.
;		FORMAT	= Character code formats of the various columns.
;		IDLTYPE	= IDL type code for each column in the binary table
;			  headers.
;		N_ELEM	= Number of elements for each column in the binary
;			  table headers.
;		TSCAL	= Scale factors for the individual columns.
;		TZERO	= Zero offsets for the individual columns.
;		MAXVAL	= For variable length arrays, contains the maximum
;			  number of elements for each column in the binary
;			  table headers.
;		N_DIMS	= Number of dimensions, and array of dimensions for
;			  each column of type string in the binary table
;			  headers.
; Category    : 
;	Data Handling, I/O, FITS, Generic.
; Prev. Hist. : 
;	William Thompson, Feb 1992.
; Written     : 
;	William Thompson, GSFC, February 1992.
; Modified    : 
;	Version 1, William Thompson, GSFC, 12 April 1993.
;		Incorporated into CDS library.
;	Version 2, William Thompson, GSFC, 21 July 1993.
;		Added DHEAP variable to fix bug with variable length arrays.
; Version     : 
;	Version 2, 21 July 1993.

; NAME: 
;       FXBISOPEN()
;
; PURPOSE: 
;       Returns true if UNIT points to an open FITS binary table.
;
; Explanation : This procedure checks to see if the logical unit number given
;               by the variable UNIT corresponds to a FITS binary table opened
;               for read with the command FXBOPEN, and which has not yet been
;               closed with FXBCLOSE.
;
; Use         : Result = FXBISOPEN(UNIT)
;
;               If FXBISOPEN(UNIT) THEN ...
;
; Inputs      : UNIT    = Logical unit number returned by FXBOPEN routine.
;                         Must be a scalar integer.
;
; Opt. Inputs : None.
;
; Outputs     : The result of the function is either True (1) or False (0),
;               depending on whether UNIT points to an open binary table or
;               not.
;
; Opt. Outputs: None.
;
; Keywords    : None.
;
; Calls       : FXBFINDLUN
;
; Common      : Uses common block FXBINTABLE--see "fxbintable.pro" for more
;               information.
;
; Restrictions: None.
;
; Side effects: If UNIT is an undefined variable, then False (0) is returned.
;
;               If UNIT points to a FITS binary table file that is opened for
;               write, then False (0) is returned.
;
; Category    : Data Handling, I/O, FITS, Generic.
;
; Prev. Hist. : None.
;
; Written     : William Thompson, GSFC, 1 July 1993.
;
; Modified    : Version 1, William Thompson, GSFC, 1 July 1993.
;
; Version     : Version 1, 1 July 1993.
;       Converted to IDL V5.0   W. Landsman   September 1997

; NAME: 
;	FXBOPEN
; Purpose     : 
;	Open binary table extension in a disk FITS file for reading.
; Explanation : 
;	Opens a binary table extension in a disk FITS file for reading.  The
;	columns are then read using FXBREAD, and the file is closed when done
;	with FXBCLOSE.
; Use         : 
;	FXBOPEN, UNIT, FILENAME, EXTENSION  [, HEADER ]
; Inputs      : 
;       FILENAME  = Name of FITS file to be opened.  Optional
;                   extension *number* may be specified, in either of
;                   the following formats (using the FTOOLS
;                   convention): FILENAME[EXT] or FILENAME+EXT, where
;                   EXT is 1 or higher.  Such an extension
;                   specification takes priority over EXTENSION.
;                
;	EXTENSION = Either the number of the FITS extension, starting with the
;		    first extension after the primary data unit being one; or a
;		    character string containing the value of EXTNAME to search
;		    for.
; Opt. Inputs : 
;	None.
; Outputs     : 
;	UNIT	  = Logical unit number of the opened file.
; Opt. Outputs: 
;	HEADER	  = String array containing the FITS binary table extension
;		    header.
; Keywords    : 
;	NO_TDIM	  = If set, then any TDIMn keywords found in the header are
;		    ignored.
;
;       ACCESS    = A scalar string describing access privileges as
;                   one of READ ('R') or UPDATE ('RW').
;                   DEFAULT: 'R'
;
;       REOPEN    = If set, UNIT must be an already-opened file unit.
;                   FXBOPEN will treat the file as a FITS file.
;
;	ERRMSG	  = If defined and passed, then any error messages will be
;		    returned to the user in this parameter rather than
;		    depending on the MESSAGE routine in IDL.  If no errors are
;		    encountered, then a null string is returned.  In order to
;		    use this feature, ERRMSG must be defined first, e.g.
;
;			ERRMSG = ''
;			FXBOPEN, ERRMSG=ERRMSG, ...
;			IF ERRMSG NE '' THEN ...
;
; Calls       : 
;	FXBFINDLUN, FXBPARSE, FXHREAD, FXPAR
; Common      : 
;	Uses common block FXBINTABLE--see "fxbintable.pro" for more
;	information.
; Restrictions: 
;	The file must be a valid FITS file.
; Side effects: 
;	None.
; Category    : 
;	Data Handling, I/O, FITS, Generic.
; Prev. Hist. : 
;	W. Thompson, Feb 1992, based on READFITS by J. Woffard and W. Landsman.
;	W. Thompson, Feb 1992, changed from function to procedure.
;	W. Thompson, June 1992, fixed up error handling.
; Written     : 
;	William Thompson, GSFC, February 1992.
; Modified    : 
;	Version 1, William Thompson, GSFC, 12 April 1993.
;		Incorporated into CDS library.
;	Version 2, William Thompson, GSFC, 27 May 1994
;		Added ERRMSG keyword.
;	Version 3, William Thompson, GSFC, 21 June 1994
;		Extended ERRMSG to call to FXBPARSE
;       Version 4, William Thompson, GSFC, 23 June 1994
;               Modified so that ERRMSG is not touched if not defined.
;       Version 4, 23 June 1994
;       	Converted to IDL V5.0   W. Landsman   September 1997
;
; Added ACCESS, REOPEN keywords, and FXFILTER package, CM 1999 Feb 03
; Added FILENAME[EXT] and FILENAME+EXT extension parsing, CM 1999 Jun 28
; Some general tidying, CM 1999 Nov 18
;

; NAME: 
;	FXBPARSE
; Purpose     : 
;	Parse the binary table extension header.
; Explanation : 
;	Parses the binary table extension header, and store the information
;	about the format of the binary table in the FXBINTABLE common
;	block--called from FXBCREATE and FXBOPEN.
; Use         : 
;	FXBPARSE, ILUN, UNIT, HEADER
; Inputs      : 
;	ILUN	= Index into the arrays in the FXBINTABLE common block.
;	HEADER	= FITS binary table extension header.
; Opt. Inputs : 
;	None.
; Outputs     : 
;	None.
; Opt. Outputs: 
;	None.
; Keywords    : 
;	NO_TDIM	  = If set, then any TDIMn keywords found in the header are
;		    ignored.
;	ERRMSG	  = If defined and passed, then any error messages will be
;		    returned to the user in this parameter rather than
;		    depending on the MESSAGE routine in IDL.  If no errors are
;		    encountered, then a null string is returned.  In order to
;		    use this feature, ERRMSG must be defined first, e.g.
;
;			ERRMSG = ''
;			FXBPARSE, ERRMSG=ERRMSG, ...
;			IF ERRMSG NE '' THEN ...
;
; Calls       : 
;	FXBFIND, FXBTDIM, FXBTFORM, FXPAR
; Common      : 
;	Uses common block FXBINTABLE--see "fxbintable.pro" for more
;	information.
; Restrictions: 
;	None.
; Side effects: 
;	Any TDIMn keywords found for bit arrays (format 'X') are ignored, since
;	the dimensions would refer to bits, not bytes.
; Category    : 
;	Data Handling, I/O, FITS, Generic.
; Prev. Hist. : 
;	William Thompson, Feb. 1992.
;	William Thompson, Jan. 1993, modified for renamed FXBTFORM and FXBTDIM.
; Written     : 
;	William Thompson, GSFC, February 1992.
; Modified    : 
;	Version 1, William Thompson, GSFC, 12 April 1993.
;		Incorporated into CDS library.
;	Version 2, William Thompson, GSFC, 21 June 1994
;		Added ERRMSG keyword.
;       Version 3, William Thompson, GSFC, 23 June 1994
;               Modified so that ERRMSG is not touched if not defined.
;	Version 4, Michael Schubnell, University of Michigan, 22 May 1996
;		Change N_DIMS from short to long integer.
;	Version 5, W. Landsman, GSFC, 12 Aug 1997
;		Use double complex datatype, if needed
;	Version 6, W. Landsman GSFC 30 Aug 1997
; Version     : 
;	Version 6, 31 Aug 1997
;	Converted to IDL V5.0   W. Landsman   September 1997
;       Optimized FXPAR; call FXBFIND for speed, CM 1999 Nov 18
;       Modify DHEAP(ILUN) when opening table now, CM 2000 Feb 22

; NAME: 
;	FXBREAD
; Purpose     : 
;	Read a data array from a disk FITS binary table file.
; Explanation : 
;	Each call to FXBREAD will read the data from one column and one row
;	from the FITS data file, which should already have been opened by
;	FXBOPEN.  One needs to call this routine for every column and every row
;	in the binary table.  FXBCLOSE will then close the FITS data file.
; Use         : 
;	FXBREAD, UNIT, DATA, COL  [, ROW ]
; Inputs      : 
;	UNIT	= Logical unit number corresponding to the file containing the
;		  binary table.
;	COL	= Column in the binary table to read data from, either as a
;		  character string containing a column label (TTYPE), or as a
;		  numerical column index starting from column one.
; Opt. Inputs : 
;	ROW	= Either row number in the binary table to read data from,
;		  starting from row one, or a two element array containing a
;		  range of row numbers to read.  If not passed, then the entire
;		  column is read in.
;
;		  Row must be passed for variable length arrays.
;
; Outputs     : 
;	DATA	= IDL data array to be read from the file.
; Opt. Outputs: 
;	None.
; Keywords    : 
;	NOSCALE	= If set, then the output data will not be scaled using the
;		  optional TSCAL and TZERO keywords in the FITS header.
;		  Default is to scale.
;       NOIEEE  = If set, then the output data is not byte-swapped to 
;                 machine order.  NOIEEE implies NOSCALE.
;                 Default is to perform the byte-swap.
;	VIRTUAL	= If set, and COL is passed as a name rather than a number,
;		  then if the program can't find a column with that name, it
;		  will then look for a keyword with that name in the header.
;		  Such a keyword would then act as a "virtual column", with the
;		  same value for every row.
;	DIMENSIONS = Vector array containing the dimensions to be used to read
;		  in the data.  Bypasses any dimensioning information stored in
;		  the header.  Ignored for bit arrays.  If the data type is
;		  double-precision complex, then an extra dimension of 2 is
;		  prepended to the dimensions passed by the user.
;	NANVALUE= Value signalling data dropout.  All points corresponding to
;		  IEEE NaN (not-a-number) are converted to this number.
;		  Ignored unless DATA is of type float, double-precision or
;		  complex.
;	ERRMSG	= If defined and passed, then any error messages will be
;		  returned to the user in this parameter rather than
;		  depending on the MESSAGE routine in IDL.  If no errors are
;		  encountered, then a null string is returned.  In order to
;		  use this feature, ERRMSG must be defined first, e.g.
;
;			ERRMSG = ''
;			FXBREAD, ERRMSG=ERRMSG, ...
;			IF ERRMSG NE '' THEN ...
;
; Calls       : 
;	IEEE_TO_HOST, FXPAR, WHERE_NEGZERO, WHERENAN
; Common      : 
;	Uses common block FXBINTABLE--see "fxbintable.pro" for more
;	information.
; Restrictions: 
;	The binary table file must have been opened with FXBOPEN.
;
;	The data must be consistent with the column definition in the binary
;	table header.
;
;	The row number must be consistent with the number of rows stored in the
;	binary table header.
;
;	The number of elements implied by the dimensions keyword must not
;	exceed the number of elements stored in the file.
;
; Side effects: 
;	If the DIMENSIONS keyword is used, then the number of data points read
;	in may be less than the number of points stored in the table.
;
;	If there are no elements to read in (the number of elements is zero),
;	then the program sets !ERR to -1, and DATA is unmodified.
;
; Category    : 
;	Data Handling, I/O, FITS, Generic.
; Prev. Hist. : 
;	W. Thompson, Jan 1992.
;	W. Thompson, Feb 1992, modified to support variable length arrays.
;	W. Thompson, Jun 1992, modified way that row ranges are read in.  No
;			       longer works reiteratively.
;	W. Thompson, Jun 1992, fixed bug where NANVALUE would be modified by
;			       TSCAL and TZERO keywords.
;	W. Thompson, Jun 1992, fixed bug when reading character strings.
;			       Treats dimensions better when reading multiple
;			       rows.
; Written     : 
;	William Thompson, GSFC, January 1992.
; Modified    : 
;	Version 1, William Thompson, GSFC, 12 April 1993.
;		Incorporated into CDS library.
;	Version 2, William Thompson, GSFC, 30 June 1993.
;		Added overwrite keyword to REFORM call to speed up.
;	Version 3, William Thompson, GSFC, 21 July 1993.
;		Fixed bug with variable length arrays.
;	Version 4, William Thompson, GSFC, 29 October 1993.
;		Added error message for not finding column by name.
;	Version 5, William Thompson, GSFC, 31 May 1994
;		Added ERRMSG keyword.
;       Version 6, William Thompson, GSFC, 23 June 1994
;               Modified so that ERRMSG is not touched if not defined.
;	Version 7, William Thompson, GSFC, 29 December 1994
;		Fixed bug where single element dimensions were lost.
;	Version 8, William Thompson, GSFC, 20 March 1995
;		Fixed bug introduced in version 7.
;	Version 9, Wayne Landsman, GSFC, 3 July 1996
;		Fixed bug involving use of virtual keyword.
;	Version 10, William Thompson, GSFC, 31-Jan-1997
;		Added call to WHERE_NEGZERO.
;	Version 11, Wayne Landsman, GSFC, 12 Aug, 1997
;		Use IDL dcomplex datatype if needed
;	Version 12, Wayne Landmsan, GSFC, 20 Feb, 1998
;		Remove call to WHERE_NEGZERO (now part of IEEE_TO_HOST)
;	Version 13, 18 Nov 1999, CM, Add NOIEEE keyword
;	Version 14, 21 Aug 2000, William Thompson, GSFC
;		Catch I/O errors
; Version     :
;       Version 14, 21 Aug 2000

; NAME:
;       FXBREADM
; PURPOSE: 
;       Read multiple columns/rows from a disk FITS binary table file.
; EXPLANATION : 
;       A call to FXBREADM will read data from multiple rows and
;       multiple columns in a single procedure call.  Up to forty-nine
;       columns may be read in a single pass; the number of rows is
;       limited essentially by available memory.  The file should have
;       already been opened with FXBOPEN.  FXBREADM optimizes reading
;       multiple columns by first reading a large chunk of data from
;       the FITS file directly, and then slicing the data into columns
;       within memory.  FXBREADM can read variable-length arrays (see
;       below).
;
;       The number of columns is limited to 49 if data are passed by
;       positional argument.  However, this limitation can be overcome
;       by having FXBREADM return the data in an array of pointers or
;       handles.  The user should set the PASS_METHOD keyword to
;       'POINTER' or 'HANDLE' as appropriate, and an array of pointers
;       to the data will be returned in the POINTERS keyword.  The
;       user is responsible for freeing the pointers; however,
;       FXBREADM will reuse any pointers or handles passed into the
;       procedure, and hence any pointed-to data will be destroyed.
;
;       FXBREADM can also read variable-length columns from FITS
;       binary tables.  Since such data is not of a fixed size, it is
;       returned as a structure.  The structure has the following
;       elements:
;
;              VARICOL:    ;; Flag: variable length column (= 1)
;              N_ELEMENTS: ;; Total number of elements returned
;              TYPE:       ;; IDL data type code (integer)
;              N_ROWS:     ;; Number of rows read from table (integer)
;              INDICES:    ;; Indices of each row's data (integer array)
;              DATA:       ;; Raw data elements (variable type array)
;
;       In order to gain access to the Ith row's data, one should
;       examine DATA(INDICES(I):INDICES(I+1)-1), which is similar in
;       construct to the REVERSE_INDICES keyword of the HISTOGRAM
;       function.
;
; CALLING SEQUENCE: 
;       FXBREADM, UNIT, COL, DATA1, [ DATA2, ... DATA48, ROW=, BUFFERSIZE = ]
;           /NOIEEE, /NOSCALE, /VIRTUAL, NANVALUE=, PASS_METHOD = POINTERS=, 
;           ERRMSG = , WARNMSG = , STATUS = ]
;
; INPUT PARAMETERS : 
;       UNIT    = Logical unit number corresponding to the file containing the
;                 binary table.
;       COL     = An array of columns in the binary table to read data
;                 from, either as character strings containing column
;                 labels (TTYPE), or as numerical column indices
;                 starting from column one.
; Outputs     : 
;       DATA1, DATA2...DATA48 = A named variable to accept the data values, one
;                 for each column.  The columns are stored in order of the
;                 list in COL.  If the read operation fails for a
;                 particular column, then the corresponding output Dn
;                 variable is not altered.  See the STATUS keyword.
;                 Ignored if PASS_METHOD is 'POINTER' or 'HANDLE'
;
; OPTIONAL INPUT KEYWORDS: 
;       ROW     = Either row number in the binary table to read data from,
;                 starting from row one, or a two element array containing a
;                 range of row numbers to read.  If not passed, then the entire
;                 column is read in.
;       /NOIEEE = If set, then then IEEE floating point data will not
;                be converted to the host floating point format (and
;                this by definition implies NOSCALE).  The user is
;                responsible for their own floating point conversion.
;       /NOSCALE = If set, then the output data will not be scaled using the
;                 optional TSCAL and TZERO keywords in the FITS header.
;                 Default is to scale.
;       VIRTUAL = If set, and COL is passed as a name rather than a number,
;                 then if the program can't find a column with that name, it
;                 will then look for a keyword with that name in the header.
;                 Such a keyword would then act as a "virtual column", with the
;                 same value for every row.
;       DIMENSIONS = FXBREADM ignores this keyword.  It is here for
;	          compatibility only.
;       NANVALUE= Value signalling data dropout.  All points corresponding to
;                 IEEE NaN (not-a-number) are converted to this number.
;                 Ignored unless DATA is of type float, double-precision or
;                 complex.
;       PASS_METHOD = A scalar string indicating method of passing
;                 data from FXBREADM.  One of 'ARGUMENT' (indicating
;                 pass by positional argument), 'POINTER' (indicating
;                 passing an array of pointers by the POINTERS
;                 keyword), or 'HANDLE' (indicating passing an array
;                 of handles by the POINTERS keyword).
;                 Default: 'ARGUMENT'
;       POINTERS = If PASS_METHOD is 'POINTER' then an array of IDL
;                 pointers is returned in this keyword, one for each
;                 requested column.  If PASS_METHOD is 'HANDLE' then
;                 an array of IDL handles is returned instead.  Any
;                 handles or pointers passed into FXBREADM will have
;                 their pointed-to data destroyed.  Ultimately the
;                 user is responsible for deallocating pointers and
;                 handles.
;       BUFFERSIZE = Raw data are transferred from the file in chunks
;                 to conserve memory.  This is the size in bytes of
;                 each chunk.  If a value of zero is given, then all
;                 of the data are transferred in one pass.  Default is
;                 32768 (32 kB).
; OPTIONAL OUTPUT KEYWORDS:
;       ERRMSG  = If defined and passed, then any error messages will be
;                 returned to the user in this parameter rather than
;                 depending on the MESSAGE routine in IDL.  If no errors are
;                 encountered, then a null string is returned.  In order to
;                 use this feature, ERRMSG must be defined first, e.g.
;
;                       ERRMSG = ''
;                       FXBREAD, ERRMSG=ERRMSG, ...
;                       IF ERRMSG NE '' THEN ...
;       WARNMSG = Messages which are considered to be non-fatal
;                 "warnings" are returned in this output string.
;                 Note that if some but not all columns are
;                 unreadable, this is considered to be non-fatal.
;       STATUS  = An output array containing the status for each
;                 column read, 1 meaning success and 0 meaning failure.
;
; Calls       : 
;       IEEE_TO_HOST, FXPAR(), WHERENAN()
; Common      : 
;       Uses common block FXBINTABLE--see "fxbintable.pro" for more
;       information.
; Restrictions: 
;       The binary table file must have been opened with FXBOPEN.
;
;       The data must be consistent with the column definition in the binary
;       table header.
;
;       The row number must be consistent with the number of rows stored in the
;       binary table header.
;
;       Generaly speaking, FXBREADM will be faster than iterative
;       calls to FXBREAD when (a) a large number of columns is to be
;       read or (b) the size in bytes of each cell is small, so that
;       the overhead of the FOR loop in FXBREAD becomes significant.
;
; SIDE EFFECTS: 
;       If there are no elements to read in (the number of elements is zero),
;       then the program sets !ERR to -1, and DATA is unmodified.
;
; Category    : 
;       Data Handling, I/O, FITS, Generic.
; Prev. Hist. : 
;       C. Markwardt, based in concept on FXBREAD version 12 from
;                              IDLASTRO, but with significant and
;                              major changes to accomodate the
;                              multiple row/column technique.  Mostly
;                              the parameter checking and general data
;                              flow remain.
;       C. Markwardt, updated to read variable length arrays, and to
;                              pass columns by handle or pointer.
;                              20 Jun 2001
;       C. Markwardt, try to conserve memory when creating the arrays
;                              13 Oct 2001
;   Handle case of GE 50 columns, C. Markwardt, 18 Apr 2002
;   Handle case where TSCAL/TZERO changes type of column,
;       C. Markwardt, 23 Feb 2003
;   Fix bug in handling of FOUND and numeric columns, 
;       C. Markwardt 12 May 2003
;
;

; NAME: 
;      FXBSTATE()
;
; PURPOSE:
;       Returns the state of a FITS binary table.
;
; Explanation : This procedure returns the state of a FITS binary table that
;               was either opened for read with the command FXBOPEN, or for
;               write with the command FXBCREATE.
;
; Use         : Result = FXBSTATE(UNIT)
;
; Inputs      : UNIT    = Logical unit number returned by FXBOPEN routine.
;                         Must be a scalar integer.
;
; Opt. Inputs : None.
;
; Outputs     : The result of the function is the state of the FITS binary
;               table that UNIT points to.  This can be one of three values:
;
;                       0 = Closed
;                       1 = Open for read
;                       2 = Open for write
;
; Opt. Outputs: None.
;
; Keywords    : None.
;
; Calls       : FXBFINDLUN
;
; Common      : Uses common block FXBINTABLE--see "fxbintable.pro" for more
;               information.
;
; Restrictions: None.
;
; Side effects: If UNIT is an undefined variable, then 0 (closed) is returned.
;
; Category    : Data Handling, I/O, FITS, Generic.
;
; Prev. Hist. : None.
;
; Written     : William Thompson, GSFC, 1 July 1993.
;
; Modified    : Version 1, William Thompson, GSFC, 1 July 1993.
;
; Version     : Version 1, 1 July 1993.
;       Converted to IDL V5.0   W. Landsman   September 1997

; NAME: 
;	FXBTDIM()
; Purpose     : 
;	Parse TDIM-like kwywords.
; Explanation : 
;	Parses the value of a TDIM-like keyword (e.g. TDIMnnn, TDESC, etc.) to
;	return the separate elements contained within.
; Use         : 
;	Result = FXBTDIM( TDIM_KEYWORD )
; Inputs      : 
;	TDIM_KEYWORD	= The value of a TDIM-like keyword.  Must be a
;			  character string of the form "(value1,value2,...)".
;			  If the parentheses characters are missing, then the
;			  string is simply returned as is, without any further
;			  processing.
; Opt. Inputs : 
;	None.
; Outputs     : 
;	The result of the function is a character string array containing the
;	values contained within the keyword parameter.  If a numerical result
;	is desired, then simply call, e.g.
;
;		Result = FIX( FXBTDIM( TDIM_KEYWORD ))
;
; Opt. Outputs: 
;	None.
; Keywords    : 
;	None.
; Calls       : 
;	GETTOK
; Common      : 
;	None.
; Restrictions: 
;	The input parameter must have the proper format.  The separate values
;	must not contain the comma character.  TDIM_KEYWORD must not be an
;	array.
; Side effects: 
;	None.
; Category    : 
;	Data Handling, I/O, FITS, Generic.
; Prev. Hist. : 
;	William Thompson, Jan. 1992.
;	William Thompson, Jan. 1993, renamed to be compatible with DOS
;		limitations.
; Written     : 
;	William Thompson, GSFC, January 1992.
; Modified    : 
;	Version 1, William Thompson, GSFC, 12 April 1993.
;		Incorporated into CDS library.
; Version     : 
;	Version 1, 12 April 1993.
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME: 
;	FXBTFORM
; Purpose     : 
;	Returns information about FITS binary table columns.
; Explanation : 
;	Procedure to return information about the format of the various columns
;	in a FITS binary table.
; Use         : 
;	FXBTFORM,HEADER,TBCOL,IDLTYPE,FORMAT,NUMVAL,MAXVAL
; Inputs      : 
;	HEADER	= Fits binary table header.
; Opt. Inputs : 
;	None.
; Outputs     : 
;	TBCOL	= Array of starting column positions in bytes.
;	IDLTYPE	= IDL data types of columns.
;	FORMAT	= Character code defining the data types of the columns.
;	NUMVAL	= Number of elements of the data arrays in the columns.
;	MAXVAL	= Maximum number of elements for columns containing variable
;		  length arrays, or zero otherwise.
; Opt. Outputs: 
;	None.
; Keywords    : 
;	ERRMSG	  = If defined and passed, then any error messages will be
;		    returned to the user in this parameter rather than
;		    depending on the MESSAGE routine in IDL.  If no errors are
;		    encountered, then a null string is returned.  In order to
;		    use this feature, ERRMSG must be defined first, e.g.
;
;			ERRMSG = ''
;			FXBTFORM, ERRMSG=ERRMSG, ...
;			IF ERRMSG NE '' THEN ...
;
; Calls       : 
;	FXPAR
; Common      : 
;	None.
; Restrictions: 
;	None.
; Side effects: 
;	None.
; Category    : 
;	Data Handling, I/O, FITS, Generic.
; Prev. Hist. : 
;	W. Thompson, Feb. 1992, from TBINFO by D. Lindler.
;	W. Thompson, Jan. 1993, renamed to be compatible with DOS limitations.
; Written     : 
;	William Thompson, GSFC, February 1992.
; Modified    : 
;	Version 1, William Thompson, GSFC, 12 April 1993.
;		Incorporated into CDS library.
;	Version 2, William Thompson, GSFC, 21 June 1994
;		Added ERRMSG keyword.
;       Version 3, William Thompson, GSFC, 23 June 1994
;               Modified so that ERRMSG is not touched if not defined.
;	Version 4, William Thompson, GSFC, 9 April 1997
;		Modified so that variable length arrays can be read, even if
;		the maximum array size is not in the header.
;	Version 5  Wayne Landsman, GSFC, August 1997
;		Recognize double complex array type if since IDL version 4.0
; Version     :
;       Version 6
;       Optimized FXPAR call, CM 1999 Nov 18

; NAME: 
;	FXBWRITE
; Purpose     : 
;	Write a binary data array to a disk FITS binary table file.
; Explanation : 
;	Each call to FXBWRITE will write to the data file, which should already
;	have been created and opened by FXBCREATE.  One needs to call this
;	routine for every column and every row in the binary table.  FXBFINISH
;	will then close the file.
; Use         : 
;	FXBWRITE, UNIT, DATA, COL, ROW
; Inputs      : 
;	UNIT	= Logical unit number corresponding to the file containing the
;		  binary table.
;	DATA	= IDL data array to be written to the file.
;	COL	= Column in the binary table to place data in, starting from
;		  column one.
;	ROW	= Row in the binary table to place data in, starting from row
;		  one.
; Opt. Inputs : 
;	None.
; Outputs     : 
;	None.
; Opt. Outputs: 
;	None.
; Keywords    : 
;	BIT	= Number of bits in bit mask arrays (type "X").  Only used if
;		  the column is of variable size.
;	NANVALUE= Value signalling data dropout.  All points corresponding to
;		  this value are set to be IEEE NaN (not-a-number).  Ignored
;		  unless DATA is of type float, double-precision or complex.
;	ERRMSG	= If defined and passed, then any error messages will be
;		  returned to the user in this parameter rather than
;		  depending on the MESSAGE routine in IDL.  If no errors are
;		  encountered, then a null string is returned.  In order to
;		  use this feature, ERRMSG must be defined first, e.g.
;
;			ERRMSG = ''
;			FXBWRITE, ERRMSG=ERRMSG, ...
;			IF ERRMSG NE '' THEN ...
;
; Calls       : 
;	HOST_TO_IEEE
; Common      : 
;	Uses common block FXBINTABLE--see "fxbintable.pro" for more
;	information.
; Restrictions: 
;	The binary table file must have been opened with FXBCREATE.
;
;	The data must be consistent with the column definition in the binary
;	table header.
;
;	The row number must be consistent with the number of rows stored in the
;	binary table header.
;
; Side effects: 
;	None.
; Category    : 
;	Data Handling, I/O, FITS, Generic.
; Prev. Hist. : 
;	W. Thompson, Jan 1992, based on WRITEFITS by J. Woffard and W. Landsman.
;	W. Thompson, Feb 1992, modified to support variable length arrays.
;	W. Thompson, Feb 1992, removed all references to temporary files.
; Written     : 
;	William Thompson, GSFC, January 1992.
; Modified    : 
;	Version 1, William Thompson, GSFC, 12 April 1993.
;		Incorporated into CDS library.
;	Version 2, William Thompson, GSFC, 21 July 1993.
;		Fixed bug with variable length arrays.
;	Version 3, William Thompson, GSFC, 31 May 1994
;		Added ERRMSG keyword.
;       Version 4, William Thompson, GSFC, 23 June 1994
;               Modified so that ERRMSG is not touched if not defined.
;	Version 5, Wayne Landsman, GSFC, 12 Aug 1997
;		Recognize IDL double complex data type
; Version     :
;       Version 5, 12 August 1997
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME: 
;	FXBWRITM
; PURPOSE: 
;       Write multiple columns/rows to a disk FITS binary table file.
; EXPLANATION : 
;       A call to FXBWRITM will write multiple rows and multiple
;       columns to a binary table in a single procedure call.  Up to
;       fifty columns may be read in a single pass.  The file should
;       have already been opened with FXBOPEN (with write access) or
;       FXBCREATE.  FXBWRITM optimizes writing multiple columns by
;       first writing a large chunk of data to the FITS file all at
;       once.  FXBWRITM cannot write variable-length arrays; use
;       FXBWRITE instead.
;
;       The number of columns is limited to 50 if data are passed by
;       positional argument.  However, this limitation can be overcome
;       by passing either pointers or handles to FXBWRITM.  The user
;       should set the PASS_METHOD keyword to 'POINTER' or 'HANDLE' as
;       appropriate, and an array of pointers or handles to the data
;       in the POINTERS keyword.  The user is responsible for freeing
;       the pointers.
;
; CALLING SEQUENCE: 
;	FXBWRITM, UNIT, COL, D0, D1, D2, ..., [ ROW= ]
;    
; INPUT PARAMETERS: 
;	UNIT	= Logical unit number corresponding to the file containing the
;		  binary table.
;	D0,..D49= An IDL data array to be written to the file, one for
;                 each column.
;	COL	= Column in the binary table to place data in, starting from
;		  column one.
; OPTIONAL INPUT KEYWORDS: 
;	ROW	= Either row number in the binary table to write data to,
;		  starting from row one, or a two element array containing a
;		  range of row numbers to write.  If not passed, then
;		  the entire column is written.
;	NANVALUE= Value signalling data dropout.  All points corresponding to
;		  this value are set to be IEEE NaN (not-a-number).  Ignored
;		  unless DATA is of type float, double-precision or complex.
;       PASS_METHOD = A scalar string indicating method of passing
;                 data to FXBWRITM.  One of 'ARGUMENT' (indicating
;                 pass by positional argument), 'POINTER' (indicating
;                 passing an array of pointers by the POINTERS
;                 keyword), or 'HANDLE' (indicating passing an array
;                 of handles by the POINTERS keyword).
;                 Default:  'ARGUMENT'
;       POINTERS = If PASS_METHOD is 'POINTER' then the user must pass
;                 an array of IDL pointers to this keyword, one for
;                 each column.  If PASS_METHOD is 'HANDLE' then pass
;                 an array of IDL handles instead.  Ultimately the
;                 user is responsible for deallocating pointers and
;                 handles.
;       BUFFERSIZE = Data are transferred in chunks to conserve
;                 memory.  This is the size in bytes of each chunk.
;                 If a value of zero is given, then all of the data
;                 are transferred in one pass.  Default is 32768 (32
;                 kB).
; OPTIONAL OUTPUT KEYWORDS:
;	ERRMSG	= If defined and passed, then any error messages will be
;		  returned to the user in this parameter rather than
;		  depending on the MESSAGE routine in IDL.  If no errors are
;		  encountered, then a null string is returned.  In order to
;		  use this feature, ERRMSG must be defined first, e.g.
;
;			ERRMSG = ''
;			FXBWRITE, ERRMSG=ERRMSG, ...
;			IF ERRMSG NE '' THEN ...
;       WARNMSG = Messages which are considered to be non-fatal
;                 "warnings" are returned in this  output string.
;       STATUS  = An output array containing the status for each
;                 read, 1 meaning success and 0 meaning failure.
;
; PROCEDURE CALLS: 
;	HOST_TO_IEEE, PRODUCT()
; EXAMPLE:
;      Write a binary table 'sample.fits' giving 43 X,Y positions and a 
;      21 x 21 PSF at each position:
;
;      (1) First, create sample values
;      x = findgen(43) & y = findgen(43)+1 & psf = randomn(seed,21,21,32)
;      
;      (2) Create primary header, write it to disk, and make extension header
;      fxhmake,header,/initialize,/extend,/date
;      fxwrite,'sample.fits',header
;      fxbhmake,header,43,'TESTEXT','Test binary table extension'
;
;      (3) Fill extension header with desired column names
;      fxbaddcol,1,header,x[0],'X'             ;Use first element in each array
;      fxbaddcol,2,header,y[0],'Y'             ;to determine column properties
;      fxbaddcol,3,header,psf[*,*,0],'PSF'
;
;      (4) Write extension header to FITS file
;      fxbcreate,unit,'sample.fits',header
;
;      (5) Use FXBWRITM to write all data to the extension in a single call
;      fxbwritm,unit,['X','Y','PSF'], x, y, psf
;      fxbfinish,unit                 ;Close the file
;
; COMMON BLOCKS: 
;	Uses common block FXBINTABLE--see "fxbintable.pro" for more
;	information.
; RESTRICTIONS: 
;	The binary table file must have been opened with FXBCREATE or
;       FXBOPEN (with write access).
;
;	The data must be consistent with the column definition in the binary
;	table header.
;
;	The row number must be consistent with the number of rows stored in the
;	binary table header.
;
; CATEGORY: 
;	Data Handling, I/O, FITS, Generic.
; PREVIOUS HISTORY: 
;       C. Markwardt, based on FXBWRITE and FXBREADM (ver 1), Jan 1999
; WRITTEN: 
;	Craig Markwardt, GSFC, January 1999.
; MODIFIED:
;       Version 1, Craig Markwardt, GSFC 18 January 1999.
;               Documented this routine, 18 January 1999. 
;       C. Markwardt, added ability to pass by handle or pointer.
;               Some bug fixes, 20 July 2001  
;       W. Landsman/B.Schulz  Allow more than 50 arguments when using pointers     

; NAME: 
;	FXFINDEND
; Purpose     : 
;	Find the end of a FITS file.
; Explanation : 
;	This routine finds the end of the last logical record in a FITS file,
;	which may be different from that of the physical end of the file.  Each
;	FITS header is read in and parsed, and the file pointer is moved to
;	where the next FITS extension header would be if there is one, or to
;	the end of the file if not.
; Use         : 
;	FXFINDEND, UNIT [, EXTENSION]
; Inputs      : 
;	UNIT	= Logical unit number for the opened file.
; Opt. Inputs : 
;	None.
; Outputs     : 
;	None.
; Opt. Outputs: 
;       EXTENSION = The extension number that a new extension would
;                   have if placed at the end of the file.
; Keywords    : 
;	None.
; Calls       : 
;	FXHREAD, FXPAR
; Common      : 
;	None.
; Restrictions: 
;	The file must have been opened for block I/O.  There must not be any
;	FITS "special records" at the end of the file.
; Side effects: 
;	None.
; Category    : 
;	Data Handling, I/O, FITS, Generic.
; Prev. Hist. : 
;	William Thompson, Feb. 1992.
; Written     : 
;	William Thompson, GSFC, February 1992.
; Modified    : 
;	Version 1, William Thompson, GSFC, 12 April 1993.
;		Incorporated into CDS library.
; Version     : 
;	Version 1, 12 April 1993.
;	Converted to IDL V5.0   W. Landsman   September 1997
;       Added EXTENSION parameter, CM 1999 Nov 18

; NAME: 
;	FXHCLEAN
; Purpose     : 
;	Removes required keywords from FITS header.
; Explanation : 
;	Removes any keywords relevant to array structure from a FITS header,
;	preparatory to recreating it with the proper values.
; Use         : 
;	FXHCLEAN, HEADER
; Inputs      : 
;	HEADER	= FITS header to be cleaned.
; Opt. Inputs : 
;	None.
; Outputs     : 
;	HEADER	= The cleaned FITS header is returned in place of the input
;		  array.
; Opt. Outputs: 
;	None.
; Keywords    : 
;	ERRMSG	= If defined and passed, then any error messages will be
;		  returned to the user in this parameter rather than
;		  depending on the MESSAGE routine in IDL.  If no errors are
;		  encountered, then a null string is returned.  In order to
;		  use this feature, ERRMSG must be defined first, e.g.
;
;			ERRMSG = ''
;			FXHCLEAN, ERRMSG=ERRMSG, ...
;			IF ERRMSG NE '' THEN ...
;
; Calls       : 
;	SXDELPAR, FXPAR
; Common      : 
;	None.
; Restrictions: 
;	HEADER must be a string array containing a properly formatted FITS
;	header.
; Side effects: 
;	Warning:  when cleaning a binary table extension header, not all of the
;	keywords pertaining to columns in the table may be removed.
; Category    : 
;	Data Handling, I/O, FITS, Generic.
; Prev. Hist. : 
;	William Thompson, Jan 1992.
; Written     : 
;	William Thompson, GSFC, January 1992.
; Modified    : 
;	Version 1, William Thompson, GSFC, 12 April 1993.
;		Incorporated into CDS library.
;	Version 2, William Thompson, GSFC, 31 May 1994
;		Added ERRMSG keyword.
;       Version 3, William Thompson, GSFC, 23 June 1994
;               Modified so that ERRMSG is not touched if not defined.
;	Version 4, William Thompson, GSFC, 30 December 1994
;		Added TCUNIn to list of column keywords to be removed.
; Version     :
;       Version 4, 30 December 1994
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME: 
;	FXHMAKE
; Purpose     : 
;	Create a basic FITS header array.
; Explanation : 
;	Creates a basic header array with all the required keywords.  This
;	defines a basic structure which can then be added to or modified by
;	other routines.
; Use         : 
;	FXHMAKE, HEADER  [, DATA ]
; Inputs      : 
;	None required.
; Opt. Inputs : 
;	DATA	= IDL data array to be written to file in the primary data unit
;		  (not in an extension).  This is used to determine the values
;		  of the BITPIX and NAXIS, etc. keywords.
;
;		  If not passed, then BITPIX is set to eight, NAXIS is set to
;		  zero, and no NAXISnnn keywords are included in this
;		  preliminary header.
; Outputs     : 
;	HEADER = String array containing FITS header.
; Opt. Outputs: 
;	None.
; Keywords    : 
;	INITIALIZE = If set, then the header is completely initialized, and any
;		     previous entries are lost.
;	EXTEND	= If set, then the keyword EXTEND is inserted into the file,
;		  with the value of "T" (true).
;	DATE	= If set, then the DATE keyword is added to the header.
;	ERRMSG	= If defined and passed, then any error messages will be
;		  returned to the user in this parameter rather than
;		  depending on the MESSAGE routine in IDL.  If no errors are
;		  encountered, then a null string is returned.  In order to
;		  use this feature, ERRMSG must be defined first, e.g.
;
;			ERRMSG = ''
;			FXHMAKE, ERRMSG=ERRMSG, ...
;			IF ERRMSG NE '' THEN ...
;
; Calls       : 
;	GET_DATE, FXADDPAR, FXHCLEAN
; Common      : 
;	None.
; Restrictions: 
;	Groups are not currently supported.
; Side effects: 
;	BITPIX, NAXIS, etc. are defined such that complex arrays are stored as
;	floating point, with an extra first dimension of two elements (real and
;	imaginary parts).
; Category    : 
;	Data Handling, I/O, FITS, Generic.
; Prev. Hist. : 
;	William Thompson, Jan 1992, from FXHMAKE by D. Lindler and M. Greason.
;	Differences include:
;
;		* Use of FITS standard (negative BITPIX) to signal floating
;		  point numbers instead of (SDAS/Geis) DATATYPE keyword.
;		* Storage of complex numbers as pairs of real numbers.
;		* Support for EXTEND keyword, and for cases where there is no
;		  primary data array.
;		* Insertion of DATE record made optional.  Only required FITS
;		  keywords are inserted automatically.
; Written     : 
;	William Thompson, GSFC, January 1992.
; Modified    : 
;	Version 1, William Thompson, GSFC, 12 April 1993.
;		Incorporated into CDS library.
;	Version 2, William Thompson, GSFC, 21 June 1994
;		Added ERRMSG keyword.
;       Version 3, William Thompson, GSFC, 23 June 1994
;               Modified so that ERRMSG is not touched if not defined.
;	Version 4, Wayne Landsman, GSFC, 12 August 1997
;		Recognize double complex data type
; Version     :
;       Version 4, 12 Aug 1997
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME: 
;	FXHMODIFY
; Purpose     : 
;	Modify a FITS header in a file on disk.
; Explanation : 
;	Opens a FITS file, and adds or modifies a parameter in the FITS header.
;	Can be used for either the main header, or for an extension header. 
;	The modification is performed directly on the disk file.
; Use         : 
;	FXHMODIFY, FILENAME, NAME, VALUE, COMMENT
; Inputs      : 
;	FILENAME = String containing the name of the file to be read.
;
;	NAME	= Name of parameter.  If NAME is already in the header the
;		  value and possibly comment fields are modified. Otherwise a
;		  new record is added to the header.  If NAME is equal to
;		  either "COMMENT" or "HISTORY" then the value will be added to
;		  the record without replacement.  In this case the comment
;		  parameter is ignored.
;
;	VALUE	= Value for parameter.  The value expression must be of the
;		  correct type, e.g. integer, floating or string.  String
;		  values of 'T'	or 'F' are considered logical values.
;
; Opt. Inputs : 
;	COMMENT	= String field.  The '/' is added by this routine.  Added
;		  starting in position 31.  If not supplied, or set equal to ''
;		  (the null string), then any previous comment field in the
;		  header for that keyword is retained (when found).
; Outputs     : 
;	None.
; Opt. Outputs: 
;	None.
; Keywords    : 
;	EXTENSION = Either the number of the FITS extension, starting with the
;		    first extension after the primary data unit being one; or a
;		    character string containing the value of EXTNAME to search
;		    for.  If not passed, then the primary FITS header is
;		    modified.           
;
;	BEFORE	= Keyword string name.  The parameter will be placed before the
;		  location of this keyword.  For example, if BEFORE='HISTORY'
;		  then the parameter will be placed before the first history
;		  location.  This applies only when adding a new keyword;
;		  keywords already in the header are kept in the same position.
;
;	AFTER	= Same as BEFORE, but the parameter will be placed after the
;		  location of this keyword.  This keyword takes precedence over
;		  BEFORE.
;
;       FORMAT	= Specifies FORTRAN-like format for parameter, e.g. "F7.3".  A
;		  scalar string should be used.  For complex numbers the format
;		  should be defined so that it can be applied separately to the
;		  real and imaginary parts.
;	ERRMSG	= If defined and passed, then any error messages will be
;		  returned to the user in this parameter rather than
;		  depending on the MESSAGE routine in IDL.  If no errors are
;		  encountered, then a null string is returned.  In order to
;		  use this feature, ERRMSG must be defined first, e.g.
;
;			ERRMSG = ''
;			FXHMODIFY, ERRMSG=ERRMSG, ...
;			IF ERRMSG NE '' THEN ...
;
; Calls       : 
;	FXHREAD, FXPAR, FXADDPAR, BLKSHIFT
; Common      : 
;	None.
; Restrictions: 
;	This routine can not be used to modify any of the keywords that control
;	the structure of the FITS file, e.g. BITPIX, NAXIS, PCOUNT, etc.  Doing
;	so could corrupt the readability of the FITS file.
;
; Side effects: 
;       If adding a record to the FITS header would increase the
;       number of 2880 byte records stored on disk, then the file is
;       enlarged before modification, unless the NOGROW keyword is passed.
;  
; Category    : 
;	Data Handling, I/O, FITS, Generic.
; Prev. Hist. : 
;	None.
; Written     : 
;	William Thompson, GSFC, 3 March 1994.
; Modified    : 
;	Version 1, William Thompson, GSFC, 3 March 1994.
;	Version 2, William Thompson, GSFC, 31 May 1994
;		Added ERRMSG keyword.
;       Version 3, William Thompson, GSFC, 23 June 1994
;               Modified so that ERRMSG is not touched if not defined.
; Version     :
;       Version 3, 23 June 1994
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME: 
;	FXHREAD
; Purpose     : 
;       Reads a FITS header from an opened disk file.
; Explanation : 
;       Reads a FITS header from an opened disk file.
; Use         : 
;	FXHREAD, UNIT, HEADER  [, STATUS ]
; Inputs      : 
;	UNIT	= Logical unit number.
; Opt. Inputs : 
;
; Outputs     : 
;	HEADER	= String array containing the FITS header.
; Opt. Outputs: 
;	STATUS	= Condition code giving the status of the read.  Normally, this
;		  is zero, but is set to !ERR if an error occurs, or if the
;		  first byte of the header is zero (ASCII null).
; Keywords    : 
;	None.
; Calls       : 
;	None.
; Common      : 
;	None.
; Restrictions: 
;	The file must already be positioned at the start of the header.  It
;	must be a proper FITS file.
; Side effects: 
;	The file ends by being positioned at the end of the FITS header, unless
;	an error occurs.
; Category    : 
;	Data Handling, I/O, FITS, Generic.
; Prev. Hist. : 
;	W. Thompson, Feb 1992, from READFITS by J. Woffard and W. Landsman.
;	W. Thompson, Aug 1992, added test for SIMPLE keyword.
; Written     : 
;	William Thompson, GSFC, February 1992.
; Modified    : 
;	Version 1, William Thompson, GSFC, 12 April 1993.
;		Incorporated into CDS library.
; Version     : 
;	Version 1, 12 April 1993.
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;     FXMOVE
; PURPOSE:
;     Skip a specified number of extensions in a FITS file
;
; CALLING SEQUENCE:
;     STATUS=FXMOVE(UNIT, N_EXT, /Silent)
;
; INPUT PARAMETERS:
;     UNIT     = An open unit descriptor for a FITS data stream.
;     N_EXT   = Number of extensions to skip.
;
; OPTIONAL INPUT PARAMETER:
;     /SILENT - If set, then any messages about invalid characters in the 
;               FITS file are suppressed.
; RETURNS:
;     0 if successful.
;    -1 if an error is encountered.
;
; COMMON BLOCKS:
;      None.
; SIDE EFFECTS:
;      Repositions the file pointer.
; PROCEDURE:
;      Each FITS header is read in and parsed, and the file pointer is moved
;      to where the next FITS extension header until the desired
;      extension is reached.
; PROCEDURE CALLS:
;      FXPAR(), MRD_HREAD, MRD_SKIP
; MODIFICATION HISTORY:
;      Extracted from FXPOSIT 8-March-2000 by T. McGlynn
;      Added /SILENT keyword  14-Dec-2000 by W. Landsman
;      Save time by not reading the full header  W. Landsman   Feb. 2003

; NAME: 
;        FXPAR()
; PURPOSE: 
;       Obtain the value of a parameter in a FITS header.
; EXPLANATION: 
;       The first 8 chacters of each element of HDR are searched for a match to
;       NAME.  If the keyword is one of those allowed to take multiple values
;       ("HISTORY", "COMMENT", or "        " (blank)), then the value is taken
;       as the next 72 characters.  Otherwise, it is assumed that the next
;       character is "=", and the value (and optional comment) is then parsed
;       from the last 71 characters.  An error occurs if there is no parameter
;       with the given name.
;      
;       If the value is too long for one line, it may be continued on to the
;       the next input card, using the OGIP CONTINUE convention.  For more info,
;       http://heasarc.gsfc.nasa.gov/docs/heasarc/ofwg/docs/ofwg_recomm/r13.html
;
;       Complex numbers are recognized as two numbers separated by one or more
;       space characters.
;
;       If a numeric value has no decimal point (or E or D) it is returned as
;       type LONG.  If it contains more than 8 numerals, or contains the
;       character 'D', then it is returned as type DOUBLE.  Otherwise it is
;       returned as type FLOAT.    If an integer is too large to be stored as
;       type LONG, then it is returned as DOUBLE.
;
; CALLING SEQUENCE: 
;       Result = FXPAR( HDR, NAME  [, ABORT, COUNT=, COMMENT=, /NOCONTINUE ] )
;
;       Result = FXPAR(HEADER,'DATE')           ;Finds the value of DATE
;       Result = FXPAR(HEADER,'NAXIS*')         ;Returns array dimensions as
;                                               ;vector
; REQUIRED INPUTS: 
;       HDR     = FITS header string array (e.g. as returned by FXREAD).  Each
;                 element should have a length of 80 characters
;       NAME    = String name of the parameter to return.  If NAME is of the
;                 form 'keyword*' then an array is returned containing values
;                 of keywordN where N is an integer.  The value of keywordN
;                 will be placed in RESULT(N-1).  The data type of RESULT will
;                 be the type of the first valid match of keywordN found.
; OPTIONAL INPUT: 
;       ABORT   = String specifying that FXPAR should do a RETALL if a
;                 parameter is not found.  ABORT should contain a string to be
;                 printed if the keyword parameter is not found.  If not
;                 supplied, FXPAR will return with a negative !err if a keyword
;                 is not found.
;       START   = A best-guess starting position of the sought-after
;                 keyword in the header.  If specified, then FXPAR
;                 first searches for scalar keywords in the header in
;                 the index range bounded by START-PRECHECK and
;                 START+POSTCHECK.  This can speed up keyword searches
;                 in large headers.  If the keyword is not found, then
;                 FXPAR searches the entire header.  
;
;                 If not specified then the entire header is searched.
;                 Searches of the form 'keyword*' also search the
;                 entire header and ignore START.
;
;                 Upon return START is changed to be the position of
;                 the newly found keyword.  Thus the best way to
;                 search for a series of keywords is to search for
;                 them in the order they appear in the header like
;                 this:
;
;                       START = 0L
;                       P1 = FXPAR('P1', START=START)
;                       P2 = FXPAR('P2', START=START)
;       PRECHECK = If START is specified, then PRECHECK is the number
;                  of keywords preceding START to be searched.
;                  Default: 5
;       POSTCHECK = If START is specified, then POSTCHECK is the number
;                   of keywords after START to be searched.
;                   Default: 20
; OUTPUT: 
;       The returned value of the function is the value(s) associated with the
;       requested keyword in the header array.
;
;       If the parameter is complex, double precision, floating point, long or
;       string, then the result is of that type.  Apostrophes are stripped from
;       strings.  If the parameter is logical, 1 is returned for T, and 0 is
;       returned for F.
;
;       If NAME was of form 'keyword*' then a vector of values are returned.
;
; OPTIONAL INPUT KEYWORDS: 
;       /NOCONTINUE = If set, then continuation lines will not be read, even
;                 if present in the header
; OPTIONAL OUTPUT KEYWORD:
;       COUNT   = Optional keyword to return a value equal to the number of
;                 parameters found by FXPAR.
;       COMMENTS= Array of comments associated with the returned values.
;
; PROCEDURE CALLS: 
;       GETTOK(), VALID_NUM
; SIDE EFFECTS: 
;
;       The system variable !err is set to -1 if parameter not found, 0 for a
;       scalar value returned.  If a vector is returned it is set to the number
;       of keyword matches found.
;
;       If a keyword occurs more than once in a header, a warning is given,
;       and the first occurence is used.  However, if the keyword is "HISTORY",
;       "COMMENT", or "        " (blank), then multiple values are returned.
;
; NOTES:
;	The functions SXPAR() and FXPAR() are nearly identical, although
;	FXPAR() has slightly more sophisticated parsing.   There is no
;	particular reason for having two nearly identical procedures, but
;	both are too widely used to drop either one.
;
; REVISION HISTORY: 
;       Version 1, William Thompson, GSFC, 12 April 1993.
;               Adapted from SXPAR
;       Version 2, William Thompson, GSFC, 14 October 1994
;               Modified to use VALID_NUM instead of STRNUMBER.  Inserted
;               additional call to VALID_NUM to trap cases where character
;               strings did not contain quotation marks.
;       Version 3, William Thompson, GSFC, 22 December 1994
;               Fixed bug with blank keywords, following suggestion by Wayne
;               Landsman.
;       Version 4, Mons Morrison, LMSAL, 9-Jan-98
;               Made non-trailing ' for string tag just be a warning (not
;               a fatal error).  It was needed because "sxaddpar" had an
;               error which did not write tags properly for long strings
;               (over 68 characters)
;       Version 5, Wayne Landsman GSFC, 29 May 1998
;               Fixed potential problem with overflow of LONG values
;       Version 6, Craig Markwardt, GSFC, 28 Jan 1998, 
;               Added CONTINUE parsing         
;       Version 7, Craig Markwardt, GSFC, 18 Nov 1999,
;               Added START, PRE/POSTCHECK keywords for better performance

; NAME: 
;	FXPARPOS()
; Purpose     : 
;	Finds position to insert record into FITS header.
; Explanation : 
;	Finds the position to insert a record into a FITS header.  Called from
;	FXADDPAR.
; Use         : 
;	Result = FXPARPOS(KEYWRD, IEND  [, BEFORE=BEFORE ]  [, AFTER=AFTER ])
; Inputs      : 
;	KEYWRD	= Array of eight-character keywords in header.
;	IEND	= Position of END keyword.
; Opt. Inputs : 
;	None.
; Outputs     : 
;	Result of function is position to insert record.
; Opt. Outputs: 
;	None.
; Keywords    : 
;	BEFORE	= Keyword string name.  The parameter will be placed before the
;		  location of this keyword.  For example, if BEFORE='HISTORY'
;		  then the parameter will be placed before the first history
;		  location.  This applies only when adding a new keyword;
;		  keywords already in the header are kept in the same position.
;
;	AFTER	= Same as BEFORE, but the parameter will be placed after the
;		  location of this keyword.  This keyword takes precedence over
;		  BEFORE.
;
;	If neither BEFORE or AFTER keywords are passed, then IEND is returned.
;
; Calls       : 
;	None.
; Common      : 
;	None.
; Restrictions: 
;	KEYWRD and IEND must be consistent with the relevant FITS header.
; Side effects: 
;	None.
; Category    : 
;	Data Handling, I/O, FITS, Generic.
; Prev. Hist. : 
;	William Thompson, Jan 1992.
; Written     : 
;	William Thompson, GSFC, January 1992.
; Modified    : 
;	Version 1, William Thompson, GSFC, 12 April 1993.
;		Incorporated into CDS library.
; Version     : 
;	Version 1, 12 April 1993.
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;     FXPOSIT
; PURPOSE:
;     Return the unit number of a FITS file positioned at specified extension
; EXPLANATION:
;     The FITS file will be ready to be read at the beginning of the 
;     specified extension.
;
; CALLING SEQUENCE:
;     unit=FXPOSIT(FILE, EXT_NO, /READONLY, COMPRESS=program, /SILENT)
;
; INPUT PARAMETERS:
;     FILE    = FITS file name, scalar string
;     EXT_NO  = Extension to be moved to, scalar nonnegative integer
;
; RETURNS:
;     Unit number of file or -1 if an error is detected.
;
; OPTIONAL KEYWORD PARAMETER:
;     /READONLY - If this keyword is set and non-zero, then OPENR rather 
;                than OPENU will be used to open the FITS file.
;     COMPRESS - If this keyword is set and non-zero, then then treat
;                the file as compressed.  If 1 assume a gzipped file.
;                Where possible use IDLs internal decompression
;                facilities (i.e., v5.3 or greater) or on Unix systems
;                spawn off a process to decompress and use its output
;                as the FITS stream.  If the keyword is not 1, then
;                use its value as a string giving the command needed for
;                decompression.
;     /SILENT    If set, then suppress any messages about invalid characters
;                in the FITS file.
;
; COMMON BLOCKS:
;      None.
; SIDE EFFECTS:
;      Opens and returns the descriptor of a file.
; PROCEDURE:
;      Open the appropriate file, or spawn a command and intercept
;      the output.
;      Call FXMOVE to get to the appropriate extension.
; PROCEDURE CALLS:
;      EXPAND_TILDE() (Unix only), FXPAR(), FXMOVE()
; MODIFICATION HISTORY:
;      Derived from William Thompson's FXFINDEND routine.
;      Modified by T.McGlynn, 5-October-1994.
;       Modified by T.McGlynn, 25-Feb-1995 to handle compressed
;          files.  Pipes cannot be accessed using FXHREAD so
;          MRD_HREAD was written.
;       W. Landsman 23-Apr-1997    Force the /bin/sh shell when uncompressing 
;       W. Landsman 26-May-1997    Non-unix is not just VMS
;       T. McGlynn  22-Apr-1999    Add /binary modifier needed for Windows
;       T. McGlynn  03-June-1999   Use /noshell option to get rid of processes left by spawn.
;                                  Use findfile to retain ability to use wildcards
;       W. Landsman 03-Aug-1999    Use EXPAND_TILDE under Unix to find file
;       T. McGlynn  04-Apr-2000    Put reading code into FXMOVE,
;                                  additional support for compression from D.Palmer.
;       W. Landsman/D.Zarro 04-Jul-2000    Added test for !VERSION.OS EQ 'Win32' (WinNT)
;       W. Landsman    12-Dec-2000 Added /SILENT keyword
;       W. Landsman April 2002     Use FILE_SEARCH for V5.5 or later

; NAME: 
;	FXREAD
; Purpose     : 
;	Read basic FITS files.
; Explanation : 
;	Read the primary array from a disk FITS file.  Optionally allows the
;	user to read in only a subarray and/or every Nth pixel.
; Use         : 
;	FXREAD, FILENAME, DATA  [, HEADER  [, I1, I2  [, J1, J2 ]]  [, STEP]]
; Inputs      : 
;	FILENAME = String containing the name of the file to be read.
; Opt. Inputs : 
;	I1,I2	 = Data range to read in the first dimension.  If passed, then
;		   HEADER must also be passed.  If not passed, or set to -1,-1,
;		   then the entire range is read.
;	J1,J2	 = Data range to read in the second dimension.  If passed, then
;		   HEADER and I1,J2 must also be passed.  If not passed, or set
;		   to -1,-1, then the entire range is read.
;	STEP	 = Step size to use in reading the data.  If passed, then
;		   HEADER must also be passed.  Default value is 1.  Ignored if
;		   less than 1.
; Outputs     : 
;	DATA	 = Data array to be read from the file.
; Opt. Outputs: 
;	HEADER	 = String array containing the header for the FITS file.
; Keywords    : 
;	NANVALUE = Value signalling data dropout.  All points corresponding to
;		   IEEE NaN (not-a-number) are set to this value.  Ignored
;		   unless DATA is of type float or double-precision.
;	PROMPT	 = If set, then the optional parameters are prompted for at the
;		   keyboard.
;	AVERAGE	 = If set, then the array size is reduced by averaging pixels
;		   together rather than by subselecting pixels.  Ignored unless
;		   STEP is nontrivial.  Note:  this is much slower.
;	YSTEP	 = If passed, then STEP is the step size in the 1st dimension,
;		   and YSTEP is the step size in the 2nd dimension.  Otherwise,
;		   STEP applies to both directions.
;	NOSCALE	 = If set, then the output data will not be scaled using the
;		   optional BSCALE and BZERO keywords in the FITS header.
;		   Default is to scale, if and only if BSCALE and BZERO are
;		   present and nontrivial.
;	NOUPDATE = If set, then the optional BSCALE and BZERO keywords in the
;		   optional HEADER array will not be changed.  The default is
;		   to reset these keywords to BSCALE=1, BZERO=0.  Ignored if
;		   NOSCALE is set.
;	ERRMSG   = If defined and passed, then any error messages will be
;		   returned to the user in this parameter rather than
;		   depending on the MESSAGE routine in IDL.  If no errors are
;		   encountered, then a null string is returned.  In order to
;		   use this feature, ERRMSG must be defined first, e.g.
;
;			ERRMSG = ''
;			FXREAD, ERRMSG=ERRMSG, ...
;			IF ERRMSG NE '' THEN ...
;
; Calls       : 
;	GET_DATE, IEEE_TO_HOST, FXADDPAR, FXHREAD, FXPAR, WHERENAN
; Common      : 
;	None.
; Restrictions: 
;	Groups are not supported.
;
;	The optional parameters I1, I2, and STEP only work with one or
;	two-dimensional arrays.  J1 and J2 only work with two-dimensional
;	arrays.
;
;	Use of the AVERAGE keyword is not compatible with arrays with missing
;	pixels.
;
; Side effects: 
;	If the keywords BSCALE and BZERO are present in the FITS header, and
;	have non-trivial values, then the returned array DATA is formed by the
;	equation
;
;			DATA = BSCALE*original + BZERO
;
;	However, this behavior can overridden by using the /NOSCALE keyword.
;
;	If the data is scaled, then the optional HEADER array is changed so
;	that BSCALE=1 and BZERO=0.  This is so that these scaling parameters
;	are not applied to the data a second time by another routine.  Also,
;	history records are added storing the original values of these
;	constants.  Note that only the returned array is modified--the header
;	in the FITS file itself is untouched.
;
;	If the /NOUPDATE keyword is set, however, then the BSCALE and BZERO
;	keywords are not changed.  It is then the user's responsibility to
;	ensure that these parameters are not reapplied to the data.  In
;	particular, these keywords should not be present in any header when
;	writing another FITS file, unless the user wants their values to be
;	applied when the file is read back in.  Otherwise, FITS readers will
;	read in the wrong values for the data array.
;	
; Category    : 
;	Data Handling, I/O, FITS, Generic.
; Prev. Hist. : 
;	W. Thompson, May 1992, based in part on READFITS by W. Landsman, and
;			       STSUB by M. Greason and K. Venkatakrishna.
;	W. Thompson, Jun 1992, added code to interpret BSCALE and BZERO
;			       records, and added NOSCALE and NOUPDATE
;			       keywords.
;	W. Thompson, Aug 1992, changed to call FXHREAD, and to add history
;			       records for BZERO, BSCALE.
; Written     : 
;	William Thompson, GSFC, May 1992.
; Modified    : 
;	Version 1, William Thompson, GSFC, 12 April 1993.
;		Incorporated into CDS library.
;	Version 2, William Thompson, GSFC, 17 November 1993.
;		Corrected bug with AVERAGE keyword on non-IEEE compatible
;		machines.
;		Corrected bug with subsampling on VAX machines.
;	Version 3, William Thompson, GSFC, 31 May 1994
;		Added ERRMSG keyword.
;       Version 4, William Thompson, GSFC, 23 June 1994
;               Modified so that ERRMSG is not touched if not defined.
;       Version 5, Zarro (SAC/GSFC), 14 Feb 1997 
;               Added I/O error checking
;       Version 6, 20-May-1998, David Schlegel/W. Thompson
;               Allow a single pixel to be read in.
;               Change the signal to read in the entire array to be -1
; Version     :
;       Version 6,   20-May-1998

; NAME: 
;	FXWRITE
; Purpose     : 
;	Write a disk FITS file.
; Explanation : 
;	Creates a disk FITS file and writes a FITS primary header, and
;	optionally a primary data array.
; Use         : 
;	FXWRITE, FILENAME, HEADER [, DATA ]
; Inputs      : 
;	FILENAME = String containing the name of the file to be written.
;	HEADER	 = String array containing the header for the FITS file.
; Opt. Inputs : 
;	DATA	 = IDL data array to be written to the file.  If not passed,
;		   then it is assumed that extensions will be added to the
;		   file.
; Outputs     : 
;	None.
; Opt. Outputs: 
;	None.
; Keywords    : 
;	NANVALUE = Value signalling data dropout.  All points corresponding to
;		   this value are set to be IEEE NaN (not-a-number).  Ignored
;		   unless DATA is of type float, double-precision or complex.
;	NOUPDATE = If set, then the optional BSCALE and BZERO keywords in the
;		   HEADER array will not be changed.  The default is to reset
;		   these keywords to BSCALE=1, BZERO=0.
;	ERRMSG	 = If defined and passed, then any error messages will be
;		   returned to the user in this parameter rather than
;		   depending on the MESSAGE routine in IDL.  If no errors are
;		   encountered, then a null string is returned.  In order to
;		   use this feature, ERRMSG must be defined first, e.g.
;
;			ERRMSG = ''
;			FXWRITE, ERRMSG=ERRMSG, ...
;			IF ERRMSG NE '' THEN ...
;
; Calls       : 
;	CHECK_FITS, GET_DATE, HOST_TO_IEEE, FXADDPAR, FXPAR
; Common      : 
;	None.
; Restrictions: 
;	If DATA is passed, then HEADER must be consistent with it.  If no data
;	array is being written to the file, then HEADER must also be consistent
;	with that.  The routine FXHMAKE can be used to create a FITS header.
;
;	If found, then the optional keywords BSCALE and BZERO in the HEADER
;	array is changed so that BSCALE=1 and BZERO=0.  This is so that these
;	scaling parameters are not applied to the data a second time by another
;	routine.  Also, history records are added storing the original values
;	of these constants.
;
;	If the /NOUPDATE keyword is set, however, then the BSCALE and BZERO
;	keywords are not changed.  The user should then be aware that FITS
;	readers will apply these numbers to the data, even if the data is
;	already converted to floating point form.
;
;	Groups are not supported.
;
; Side effects: 
;	None.
; Category    : 
;	Data Handling, I/O, FITS, Generic.
; Prev. Hist. : 
;	W. Thompson, Jan 1992, from WRITEFITS by J. Woffard and W. Landsman.
;	Differences include:
;
;		* Made DATA array optional, and HEADER array mandatory.
;		* Changed order of HEADER and DATA parameters.
;		* No attempt made to fix HEADER array.
;
;	W. Thompson, May 1992, changed open statement to force 2880 byte fixed
;			       length records (VMS).  The software here does not
;			       depend on this file configuration, but other
;			       FITS readers might.
;	W. Thompson, Aug 1992, added code to reset BSCALE and BZERO records,
;			       and added the NOUPDATE keyword.
; Written     : 
;	William Thompson, GSFC, January 1992.
; Modified    : 
;	Version 1, William Thompson, GSFC, 12 April 1993.
;		Incorporated into CDS library.
;	Version 2, William Thompson, GSFC, 31 May 1994
;		Added ERRMSG keyword.
;	Version 3, William Thompson, GSFC, 23 June 1994
;		Modified so that ERRMSG is not touched if not defined.
;	Version 4, William Thompson, GSFC, 12 August 1999
;		Catch error if unable to open file.
;       Version 4.1 Wayne Landsman, GSFC, 02 May 2000
;               Remove !ERR in call to CHECK_FITS, Use ARG_PRESENT()
; Version     : 
;	Version 4.1, 2 May 2000

; NAME:
;	F_FORMAT
; PURPOSE:
;	Choose a nice floating format for displaying an array of REAL data.
; EXPLANATION:
;	Called by TVLIST, IMLIST.
;
; CALLING SEQUENCE:
;	fmt = F_FORMAT( minval, maxval, factor, [ length ] )
;
; INPUTS:
;	MINVAL - REAL scalar giving the minimum value of an array of numbers
;		for which one desires a nice format.
;	MAXVAL - REAL scalar giving maximum value in array of numbers
;
; OPTIONAL INPUT:
;	LENGTH - length of the output F format (default = 5)
;		must be an integer scalar > 2
;
; OUTPUT:
;	FMT - an F or I format string, e.g. 'F5.1'
;	FACTOR - factor of 10 by which to multiply array of numbers to achieve
;		a pretty display using format FMT.
;
; EXAMPLE:
;	Find a nice format to print an array of numbers with a minimum of 5.2e-3
;	and a maximum  of 4.2e-2.
;
;		IDL> fmt = F_FORMAT( 5.2e-3, 4.2e-2, factor )
;         
;	yields fmt = '(F5.2)' and factor = .01, i.e. the array can be displayed
;	with a F5.2 format after multiplication by 100.
;
; REVISION HISTORY:
;	Written W. Landsman              December 1988
;	Deal with factors < 1.           August 1991
;	Deal with factors < 1. *and* a large range    October 1992
;	Now returns In format rather than Fn.0    February, 1994
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME: 
;   GALAGE
;
; PURPOSE:
;   Determine the age of a galaxy given its redshift and a formation redshift.
;
; CALLING SEQUENCE:
;   age = galage(z, [zform,  H0 =, k=, lambda0 =, Omega_m= , q0 =, /SILENT])' 
;
; INPUTS:
;    z - positive numeric vector or scalar of measured redshifts 
;    zform - redshift of galaxy formation (> z), numeric positive scalar 
;        To determine the age of the universe at a given redshift, set zform
;        to a large number (e.g. ~1000).
;
; OPTIONAL KEYWORD INPUTS: 
;    H0 - Hubble constant in km/s/Mpc, positive scalar, default is 70
;    /SILENT - If set, then the adopted cosmological parameters are not 
;         displayed at the terminal.
;
;        No more than two of the following four parameters should be
;        specified.   None of them need be specified -- the adopted defaults
;        are given. 
;    k - curvature constant, normalized to the closure density.   Default is
;        0, (indicating a flat universe)
;    Omega_m -  Matter density, normalized to the closure density, default
;        is 0.3.   Must be non-negative
;    Lambda0 - Cosmological constant, normalized to the closure density,
;        default is 0.7
;    q0 - Deceleration parameter, numeric scalar = -R*(R'')/(R')^2, default
;        is -0.5
;       
; OUTPUTS:
;    age -  age of galaxy in years, will have the same number of elements
;           as the input Z vector
;
; EXAMPLE:
;    (1) Determine the age of a galaxy observed at z = 1.5 in a cosmology with
;    Omega_matter = 0.3 and Lambda = 0.0.    Assume the formation redshift was
;    at z = 25, and use the default Hubble constant (=70 km/s/Mpc)
;
;    IDL> print,galage(1.5,25,Omega_m=0.3, Lambda = 0)
;             ===> 3.35 Gyr
;     
;    (2) Plot the age of a galaxy in Gyr out to a redshift of z = 5, assuming 
;        the default cosmology (omega_m=0.3, lambda=0.7), and zform = 100
;
;    IDL> z = findgen(50)/10.
;    IDL> plot,z,galage(z,100)/1e9,xtit='z',ytit = 'Age (Gyr)'
;
; PROCEDURE:
;    For a given formation time zform and a measured z, integrate dt/dz from 
;    zform to z. Analytic formula of dt/dz in Gardner, PASP 110:291-305, 1998 
;    March  (eq. 7)
; 
; COMMENTS:
;    (1) Integrates using the IDL Astronomy Library procedure QSIMP.    (The 
;    intrinsic IDL QSIMP() function is not called because of its ridiculous
;    restriction that only scalar arguments can be passed to the integrating
;    function.)    The function 'dtdz' is defined at the beginning of the 
;    routine (so it can compile first).
;    
;    (2) Should probably be fixed to use a different integrator from QSIMP when
;    computing age from an "infinite" redshift of formation.    But using a 
;    large value of zform seems to work adequately.
; PROCEDURES CALLED:
;    COSMO_PARAM, QSIMP
; HISTORY: 
;     STIS version by P. Plait (ACC)                  June 1999
;     IDL Astro Version   W. Landsman (Raytheon ITSS)      April 2000
;     Avoid integer overflow for more than 32767 redshifts  July 2001

; NAME:
;	GAL_FLAT
;
; PURPOSE:
;	Transforms the image of a galaxy so that the galaxy appears face-on
; EXPLANATION:
;	Either a nearest-neighbor approximations or a bilinear interpolation 
;	may  be used.
;
; CALLING SEQUENCE:
;	RESULT = GAL_FLAT( image, ang, inc, [, cen, /INTERP ] )  
;
; INPUTS:   
;	IMAGE  - Image to be transformed
;	ANG  - Angle of major axis, counterclockwise from Y-axis, degrees
;		For an image in standard orientation (North up, East left)
;		this is the Position Angle
;	INC - Angle of inclination of galaxy, degrees
;
; OPTIONAL INPUTS:
;	CEN - Two element vector giving the X and Y position of galaxy center
;		If not supplied, then the galaxy center is assumed to coincide
;		 with the image center
;
; INPUT KEYWORDS:
;	INTERP - If present, and non-zero, then bilinear interpolation will be
;		performed.  Otherwise a nearest neighbor approximation  is used.
;
; OUTPUTS:
;	RESULT - the transformed image, same dimensions and type as IMAGE
;
; METHOD:
;	A set of 4 equal spaced control points are corrected for inclination
;	using the procedure POLYWARP.   These control points are used by 
;	POLY_2D to correct the whole image.
;
; REVISION HISTORY:
;	Written by R. S. Hill, SASC Technologies Inc., 4 December 1985
;	Code cleaned up a bit    W. Landsman      December 1992
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;     GAL_UVW
; PURPOSE:
;     Calculate the Galactic space velocity (U,V,W) of star  
; EXPLANATION:
;     Calculates the Galactic space velocity U, V, W of star given its 
;     (1) coordinates, (2) proper motion, (3) distance (or parallax), and 
;     (4) radial velocity.
; CALLING SEQUENCE:
;     GAL_UVW, U, V, W, [/LSR, RA=, DEC=, PMRA= ,PMDEC=, VRAD= , DISTANCE= 
;              PLX= ]
; OUTPUT PARAMETERS:
;      U - Velocity (km/s) positive toward the Galactic *anti*center
;      V - Velocity (km/s) positive in the direction of Galactic rotation
;      W - Velocity (km/s) positive toward the North Galactic Pole 
; REQUIRED INPUT KEYWORDS:
;      User must supply a position, proper motion,radial velocity and distance
;      (or parallax).    Either scalars or vectors can be supplied.
;     (1) Position:
;      RA - Right Ascension in *Degrees*
;      Dec - Declination in *Degrees*
;     (2) Proper Motion
;      PMRA = Proper motion in RA in arc units (typically milli-arcseconds/yr)
;      PMDEC = Proper motion in Declination (typically mas/yr)
;     (3) Radial Velocity
;      VRAD = radial velocity in km/s
;     (4) Distance or Parallax
;      DISTANCE - distance in parsecs 
;                 or
;      PLX - parallax with same distance units as proper motion measurements
;            typically milliarcseconds (mas)
;
; OPTIONAL INPUT KEYWORD:
;      /LSR - If this keyword is set, then the output velocities will be 
;             corrected for the solar motion (U,V,W)_Sun = (-9,+12,+7)  
;             (Mihalas & Binney, 1981) to the local standard of rest
;  EXAMPLE:
;      (1) Compute the U,V,W coordinates for the halo star HD 6755.  
;          Use values from Hipparcos catalog, and correct to the LSR
;      ra = ten(1,9,42.3)*15.    & dec = ten(61,32,49.5)
;      pmra = 627.89  &  pmdec = 77.84         ;mas/yr
;      dis = 144    &  vrad = -321.4
;      gal_uvw,u,v,w,ra=ra,dec=dec,pmra=pmra,pmdec=pmdec,vrad=vrad,dis=dis,/lsr
;          ===>  u=154  v = -493  w = 97        ;km/s
;
;      (2) Use the Hipparcos Input and Output Catalog IDL databases (see 
;      http://idlastro.gsfc.nasa.gov/ftp/zdbase/) to obtain space velocities
;      for all stars within 10 pc with radial velocities > 10 km/s
;
;      dbopen,'hipparcos,hic'      ;Need Hipparcos output and input catalogs
;      list = dbfind('plx>100,vrad>10')      ;Plx > 100 mas, Vrad > 10 km/s
;      dbext,list,'pmra,pmdec,vrad,ra,dec,plx',pmra,pmdec,vrad,ra,dec,plx
;      ra = ra*15.                 ;Need right ascension in degrees
;      GAL_UVW,u,v,w,ra=ra,dec=dec,pmra=pmra,pmdec=pmdec,vrad=vrad,plx = plx 
;      forprint,u,v,w              ;Display results
; METHOD:
;      Follows the general outline of Johnson & Soderblom (1987, AJ, 93,864)
;      except that U is positive outward toward the Galactic *anti*center, and 
;      the J2000 transformation matrix to Galactic coordinates is taken from  
;      the introduction to the Hipparcos catalog.   
; REVISION HISTORY:
;      Written, W. Landsman                       December   2000

; NAME:
;       GAUSSIAN
; PURPOSE:
;       Compute the 1-d Gaussian function and optionally the derivative
; EXPLANATION:
;       Compute the 1-D Gaussian function and optionally the derivative 
;       at an array of points.
;
; CALLING SEQUENCE:
;       y = gaussian( xi, parms,[ pderiv ])
;
; INPUTS:
;       xi = array, 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,
;               parms[2] = 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[3] = 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:
;       None
; HISTORY:
;       Written, Frank Varosi NASA/GSFC 1992.
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Use machar() for machine precision, added /DOUBLE keyword,
;       add optional constant 4th parameter    W. Landsman   November 2001

; NAME:
;     GCIRC
; PURPOSE:
;     Computes rigorous great circle arc distances.  
; EXPLANATION:
;     Input/Output can either be either sexigesimal RA, Dec, or in radians. 
;     All computations are double precision. 
;
; CALLING SEQUENCE:
;      GCIRC, U, RA1, DC1, RA2, DC2, DIS
;
; INPUTS:
;      U    -- Describes units of inputs and output:
;              0:  everything radians
;              1:  RAx in decimal hours, DCx in decimal
;                       degrees, DIS in arc seconds 
;      RA1  -- Right ascension of point 1
;      DC1  -- Declination of point 1
;      RA2  -- Right ascension of point 2
;      DC2  -- Declination of point 2
;
; OUTPUTS:
;      DIS  -- Angular distance on the sky between points 1 and 2
;              See U above for units;  double precision  
;
; PROCEDURE:
;      "Cosine formula" (p. 7 of Smart's Spherical Astronomy or
;      p. 12 of Green's Spherical Astronomy)
;
; NOTES:
;       (1) If RA1,DC1 are scalars, and RA2,DC2 are vectors, then DIS is a
;       vector giving the distance of each element of RA2,DC2 to RA1,DC1.
;       Similarly, if RA1,DC1 are vectors, and RA2, DC2 are scalars, then DIS
;       is a vector giving the distance of each element of RA1, DC1 to 
;       RA2, DC2.    If both RA1,DC1 and RA2,DC2 are vectors then DIS is a
;       vector giving the distance of each element of RA1,DC1 to the 
;       corresponding element of RA2,DC2.    If the input vectors are not the 
;       same length, then excess elements of the longer ones will be ignored.
;
;       (2) Coordinates closer together than a few milliarcsec cannot
;       be distinguished.  If you are in this realm, you should be
;       using special-purpose algorithms.
;
;       (3) The function SPHDIST provides an alternate method of computing
;        a spherical distance.
;
; PROCEDURE CALLS:
;      None
;
;   MODIFICATION HISTORY:
;      Written in Fortran by R. Hill -- SASC Technologies -- January 3, 1986
;      Translated from FORTRAN to IDL, RSH, STX, 2/6/87
;      Vector arguments allowed    W. Landsman    April 1989
;      Prints result if last argument not given.  RSH, RSTX, 3 Apr. 1998
;      Converted to IDL V5.0                      April 1998
;      Remove ISARRAY(), V5.1 version        W. Landsman   August 2000

; NAME:
;     GEO2ECI
;
; PURPOSE:
;     Convert geographic spherical coordinates to Earth-centered inertial coords
;
; EXPLANATION:
;     Converts from geographic spherical coordinates [latitude, longitude, 
;     altitude] to ECI (Earth-Centered Inertial) [X,Y,Z] rectangular 
;     coordinates.    JD time is also needed.
;
;     Geographic coordinates are in degrees/degrees/km
;     Geographic coordinates assume the Earth is a perfect sphere, with radius 
;       equal to its equatorial radius.
;     ECI coordinates are in km from Earth center.
;
; CALLING SEQUENCE:
;       ECIcoord=geo2eci(gcoord,JDtime)
;
; INPUT:
;       gcoord: geographic [latitude,longitude,altitude], or a an array [3,n] 
;                of n such coordinates
;       JDtime: Julian Day time, double precision. Can be a 1-D array of n 
;               such times.
;
; KEYWORD INPUTS:
;       None
;
; OUTPUT:
;       a 3-element array of ECI [X,Y,Z] coordinates, or an array [3,n] of 
;                n such coordinates, double precision   
;       
; COMMON BLOCKS:
;       None
;
; PROCEDURES USED:
;       CT2LST - Convert Local Civil Time to Local Mean Sidereal Time
;
; EXAMPLES:
;
;       IDL> ECIcoord=geo2eci([0,0,0], 2452343.38982663D)
;       IDL> print,ECIcoord
;      -3902.9606       5044.5548       0.0000000
;
;       (The above is the ECI coordinates of the intersection of the equator and Greenwitch's 
;       meridien on 2002/03/09 21:21:21.021)
;
; MODIFICATION HISTORY:
;       Written by Pascal Saint-Hilaire (shilaire@astro.phys.ethz.ch) on 2002/05/14
;               

; NAME:
;       GEO2GEODETIC
;
; PURPOSE:
;       Convert from geographic/planetographic to geodetic coordinates
; EXPLANATION:
;       Converts from geographic (latitude, longitude, altitude) to geodetic
;       (latitude, longitude, altitude).  In geographic coordinates, the 
;           Earth is assumed a perfect sphere with a radius equal to its equatorial 
;               radius. The geodetic (or ellipsoidal) coordinate system takes into 
;               account the Earth's oblateness.
;
;       Geographic and geodetic longitudes are identical.
;               Geodetic latitude is the angle between local zenith and the equatorial plane.
;               Geographic and geodetic altitudes are both the closest distance between 
;               the satellite and the ground.
;
;       The PLANET keyword allows a similar transformation for the other 
;       planets  (planetographic to planetodetic coordinates). 
;
;       The EQUATORIAL_RADIUS and POLAR_RADIUS keywords allow the 
;       transformation for any ellipsoid.
;
;       Latitudes and longitudes are expressed in degrees, altitudes in km.
;
;       REF: Stephen P.  Keeler and Yves Nievergelt, "Computing geodetic
;       coordinates", SIAM Rev. Vol. 40, No. 2, pp. 300-309, June 1998
;
;       Planterary constants from "Allen's Astrophysical Quantities", 
;       Fourth Ed., (2000)
;
; CALLING SEQUENCE:
;       ecoord=geo2geodetic(gcoord,[ PLANET=,EQUATORIAL_RADIUS=, POLAR_RADIUS=])
;
; INPUT:
;       gcoord = a 3-element array of geographic [latitude,longitude,altitude],
;                or an array [3,n] of n such coordinates.
;
;
; OPTIONAL KEYWORD INPUT:
;       PLANET = keyword specifying planet (default is Earth).   The planet
;                may be specified either as an integer (1-9) or as one of the
;                (case-independent) strings 'mercury','venus','earth','mars',
;                'jupiter','saturn','uranus','neptune', or 'pluto'
;               
;       EQUATORIAL_RADIUS : Self-explanatory. In km. If not set, PLANET's 
;                value is used.
;       POLAR_RADIUS : Self-explanatory. In km. If not set, PLANET's value is 
;                used.
;
; OUTPUT:
;      a 3-element array of geodetic/planetodetic [latitude,longitude,altitude],
;        or an array [3,n] of n such coordinates, double precision.
;
; COMMON BLOCKS:
;       None
;
; RESTRICTIONS:
;
;       Whereas the conversion from geodetic to geographic coordinates is given
;       by an exact, analytical formula, the conversion from geographic to
;       geodetic isn't. Approximative iterations (as used here) exist, but tend 
;       to become less good with increasing eccentricity and altitude.
;       The formula used in this routine should give correct results within
;       six digits for all spatial locations, for an ellipsoid (planet) with
;       an eccentricity similar to or less than Earth's.
;       More accurate results can be obtained via calculus, needing a 
;       non-determined amount of iterations.
;       In any case, 
;          IDL> PRINT,geodetic2geo(geo2geodetic(gcoord)) - gcoord
;       is a pretty good way to evaluate the accuracy of geo2geodetic.pro.
;
; EXAMPLES:
;
;       Locate the geographic North pole, altitude 0., in geodetic coordinates
;       IDL> geo=[90.d0,0.d0,0.d0]  
;       IDL> geod=geo2geodetic(geo); convert to equivalent geodetic coordinates
;       IDL> PRINT,geod
;       90.000000       0.0000000       21.385000
;
;       As above, but for the case of Mars
;       IDL> geod=geo2geodetic(geo,PLANET='Mars')
;       IDL> PRINT,geod
;       90.000000       0.0000000       18.235500
;
; MODIFICATION HISTORY:
;       Written by Pascal Saint-Hilaire (shilaire@astro.phys.ethz.ch), May 2002
;       Generalized for all solar system planets by Robert L. Marcialis
;               (umpire@lpl.arizona.edu), May 2002
;       Modified 2002/05/18, PSH: added keywords EQUATORIAL_RADIUS and 
;               POLAR_RADIUS

; NAME:
;       GEO2MAG()
;
; PURPOSE:
;       Convert from geographic to geomagnetic coordinates
; EXPLANATION:
;       Converts from GEOGRAPHIC (latitude,longitude) to GEOMAGNETIC (latitude, 
;       longitude).   (Altitude remains the same)
;
;       Latitudes and longitudes are expressed in degrees.
;
; CALLING SEQUENCE:
;       mcoord=geo2mag(gcoord)
;
; INPUT:
;       gcoord = a 2-element array of geographic [latitude,longitude], or an 
;                array [2,n] of n such coordinates.
;
; KEYWORD INPUTS:
;       None
;
; OUTPUT:
;       a 2-element array of magnetic [latitude,longitude], or an array [2,n] 
;         of n such coordinates                     
;
; COMMON BLOCKS:
;       None
;
; EXAMPLES:
;       geographic coordinates of magnetic south pole
;
;       IDL> mcoord=geo2mag([79.3,288.59])      
;       IDL> print,mcoord
;       89.999992      -173.02325
;
; MODIFICATION HISTORY:
;       Written by Pascal Saint-Hilaire (Saint-Hilaire@astro.phys.ethz.ch), 
;            May 2002
;               

; NAME:
;       GEODETIC2GEO
;
; PURPOSE:
;       Convert from geodetic (or planetodetic) to geographic coordinates
; EXPLANATION:
;       Converts from geodetic (latitude, longitude, altitude) to geographic
;       (latitude, longitude, altitude).  In geographic coordinates, the 
;       Earth is assumed a perfect sphere with a radius equal to its equatorial 
;       radius. The geodetic (or ellipsoidal) coordinate system takes into 
;       account the Earth's oblateness.
;
;       Geographic and geodetic longitudes are identical.
;       Geodetic latitude is the angle between local zenith and the equatorial 
;       plane.   Geographic and geodetic altitudes are both the closest distance
;       between the satellite and the ground.
;
;       The PLANET keyword allows a similar transformation for the other 
;       planets  (planetodetic to planetographic coordinates). 
;
;       The EQUATORIAL_RADIUS and POLAR_RADIUS keywords allow the 
;       transformation for any ellipsoid.
;
;       Latitudes and longitudes are expressed in degrees, altitudes in km.
;
;       REF: Stephen P.  Keeler and Yves Nievergelt, "Computing geodetic
;       coordinates", SIAM Rev. Vol. 40, No. 2, pp. 300-309, June 1998
;       Planetary constants from "Allen's Astrophysical Quantities", 
;       Fourth Ed., (2000)
;
; CALLING SEQUENCE:
;       gcoord = geodetic2geo(ecoord, [ PLANET= ] )
;
; INPUT:
;       ecoord = a 3-element array of geodetic [latitude,longitude,altitude],
;                or an array [3,n] of n such coordinates.
;
; OPTIONAL KEYWORD INPUT:
;       PLANET = keyword specifying planet (default is Earth).   The planet
;                may be specified either as an integer (1-9) or as one of the
;                (case-independent) strings 'mercury','venus','earth','mars',
;                'jupiter','saturn','uranus','neptune', or 'pluto'
;
;       EQUATORIAL_RADIUS : Self-explanatory. In km. If not set, PLANET's value
;                is used.   Numeric scalar
;       POLAR_RADIUS : Self-explanatory. In km. If not set, PLANET's value is 
;                 used.   Numeric scalar
;
; OUTPUT:
;       a 3-element array of geographic [latitude,longitude,altitude], or an
;         array [3,n] of n such coordinates, double precision
;
;       The geographic and geodetic longitudes will be identical.
; COMMON BLOCKS:
;       None
;
; EXAMPLES:
;
;       IDL> geod=[90,0,0]  ; North pole, altitude 0., in geodetic coordinates
;       IDL> geo=geodetic2geo(geod)
;       IDL> PRINT,geo
;       90.000000       0.0000000      -21.385000
;
;       As above, but the equivalent planetographic coordinates for Mars
;       IDL> geod=geodetic2geo(geod,PLANET='Mars'); 
;       IDL> PRINT,geod
;       90.000000       0.0000000      -18.235500
;
; MODIFICATION HISTORY:
;       Written by Pascal Saint-Hilaire (shilaire@astro.phys.ethz.ch),
;                  May 2002
;
;       Generalized for all solar system planets by Robert L. Marcialis
;               (umpire@lpl.arizona.edu), May 2002
;
;       Modified 2002/05/18, PSH: added keywords EQUATORIAL_RADIUS and 
;                POLAR_RADIUS
;

; NAME:
;	GETFILES
; PURPOSE:
;	Prompt the user to interactively specify a list of files
; EXPLANATION:
;	User can specify a single file per line or a range of files 
;	separated by a dash or comma.    Used, for example, by FITSRD to
;	return a list of file numbers on tape to read
;
; CALLING SEQUENCE:
;	getfiles, list
;
; OUTPUT:
;	LIST - integer array containing file numbers
;
; SIDE EFFFECTS:
;	User will be prompted to enter a list of file numbers
;
; REVISION HISTORY
;	Written D. Lindler November, 1985
;	Converted to Version 2 IDL,  August 1990
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;     GETLOG
; PURPOSE:
;     Formats a logical directory for the given operating system.
;
; CALLING SEQUENCE:
;     result = GETLOG(lname)
;
; INPUTS:
;     lname   - the base name of the logical (without special characters).
;
; OUTPUTS:
;     Returns appropriate string.
;     Under VMS the logical is not translated since it may correspond to
;     multiple directories.    
;
; RESTRICTIONS:
;     Assumes that the directory logical will have meaning to the host
;     operating system.
; PROCEDURE:
;       The operating system in !version.os_family is checked. If it equals:
;
;               'vms'           then a ':' is appended.
;               'windows'       directory name is translated with GETENV()
;                               and a '\' is appended
;               'unix'          directory name is translated with GETENV()
;                               and a '/' is appended
;               'MacOS'         directory name is translated with GETENV()
;
; EXAMPLE:
;       Open the file 'stars.dbh' in the logical directory ZDBASE in an 
;       operating system independent way:
;               IDL> openr,1,getlog('ZDBASE') + 'stars.dbh'
;
; MODIFICATION HISTORY:
;       Written, JDNeill, May, 1990.
;       Modified, JDNeill,Sep, 1990 -- for unix return full path instead of
;               just environment variable name.
;       Modified, I. Freedman, HSTX April 1994 -- for MacOS return full path
;       Bug in CASE statement fixed.    JDO, HSTX, May 2 1994.
;       Added Windows compatibility  W. Landsman      September 1995
;       Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	GETOPT
; PURPOSE:
;	Convert a string supplied by the user into a valid scalar or vector
; EXPLANATION:
;	Distinct elements in the string may be
;	separated by either a comma or a space.  The output scalar
;	or vector can be specified to be  either  integer or floating
;	point.   A null string is converted to a zero.   
; CALLING SEQUENCE:
;     option = GETOPT( input, [ type, numopt, COUNT = ])
;
; INPUTS:
;	input   - string that was input by user in response to a prompt
;		Arithmetic operations can be included in the string (see
;		examples)
;
; OPTIONAL INPUTS:
;	type    - Either an "I" (integer) or an "F" (floating point) specifying 
;		the datatype of the output vector.  Default is floating point
;
;	numopt  - number of values expected by calling procedure
;		If less than NUMOPT values are supplied the output
;		vector will be padded with zeros.  
; OUTPUTS:
;	option  - scalar or vector containing the numeric conversion of
;		the fields in the string INPUT.  If NUMOPT is not
;		supplied, the number of elements in OPTION will 
;		equal the number of distinct fields in INPUT.
; OPTIONAL INPUT KEYWORD:
;       Count - integer giving the number of values actually returned by
;               GETOPT.   If the input is invalid then COUNT is set to -1
; NOTES:
;	(1) If an input is invalid, Count is set to -1 and the result is set 
;		to 999.
;	(2) GETOPT uses the execute function to interpret the user string.   
;	 	Therefore GETOPT itself cannot be called with the EXECUTE 
;		function.
;	(3) GETOPT has a hard limit of 10 tokens in the input string. 
;
; EXAMPLES:
;	(1)   a = getopt( '3.4,5*4 ', 'I' )    yields   a = [ 3, 20]
;	(2)   a = getopt( '5/2.', 'F', 5)      yields   a = [2.5,0.,0.,0.,0.]
;	(3)   a = getopt( '2*3,5,6')           yields   a = [6.,5.,6.]
;
; REVISON HISTORY:
;	written by B. Pfarr, STX, 5/6/87
;	change value of !ERR W. Landsman   STX,  6/30/88
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;     GETPRO
; PURPOSE:
;     Search !PATH for a procedure, and copy into user's working directory
; EXPLANATION:
;     Extract a procedure from an IDL Library or directory given in the 
;     !PATH  system variable and place it in the current default directory
;     (presumably to be edited by the user).  GETPRO can also be used to 
;     obtain a copy of the default startup file.
;
; CALLING SEQUENCE:
;     GETPRO, [ proc_name ]          ;Find PROC_NAME in !PATH and copy
;
; OPTIONAL INPUT:
;     proc_name - Character string giving the name of the IDL procedure or 
;               function.  Do not give an extension.   If omitted, 
;               the program will prompt for PROC_NAME.   
;
; OUTPUTS:
;     None.
;
; SIDE EFFECTS:
;      A file with the extension .pro and a name given by PROC_NAME will
;      be created on the user's directory.
;
; PROCEDURE:
;      The system variable !PATH is parsed into individual libraries or 
;      directories.   Each library or directory is then searched for the
;      procedure name.   When found, a SPAWN is used to extract or copy
;      the procedure into the user's directory.    If not found in !PATH,
;      then the ROUTINE_INFO() function is used to determine if it is an
;      intrinsic IDL procedure.  
;
; EXAMPLE:
;       Put a copy of the USER library procedure CURVEFIT on the current
;       directory
;
;       IDL> getpro, 'CURVEFIT'
;
; RESTRICTIONS:
;       User will be unable to obain source code for a native IDL function
;       or procedure, or for a FORTRAN or C routine added with CALL_EXTERNAL.
;       User must have write privilege to the current directory
;
;       This procedure is not used with Macintosh IDL. 
; PROCEDURE CALLS:
;       FDECOMP, ZPARCHECK
; REVISION HISTORY:
;      Written W. Landsman, STX Corp.   June 1990
;      Now use intrinsic EXPAND_PATH() command  W. Landsman November 1994
;      Use ROUTINE_NAMES() to check for intrinsic procs  W. Landsman July 95
;      Update for Windows/IDL     W. Landsman      September 95
;      Check if procedure is in current directory  W. Landsman  June 1997
;      Converted to IDL V5.0   W. Landsman   September 1997
;      Use ROUTINE_INFO instead of undocumented ROUTINE_NAMES W.L. October 1998

; NAME:
;	GETPSF
; PURPOSE:
;	To generate a point-spread function (PSF) from observed stars. 
; EXPLANATION:
;	The PSF is represented as a 2-dimensional Gaussian
;	(integrated over each pixel) and a lookup table of residuals.
;	The lookup table and Gaussian parameters are output in a FITS
;	image file.   The PSF FITS file created by GETPSF can be
;	read with the procedure RDPSF.      Adapted from the 1986 STSDAS 
;	version of DAOPHOT
;
; CALLING SEQUENCE:
;	GETPSF, image, xc, yc, apmag, sky, [ronois, phpadu, gauss, psf, 
;			idpsf, psfrad, fitrad, psfname, /DEBUG ]
;
; INPUTS:
;	IMAGE  - input image array
;	XC     - input vector of x coordinates (from FIND), these should be
;		IDL (first pixel is (0,0)) convention.
;	YC     - input vector of y coordinates (from FIND)
;	APMAG  - vector of magnitudes (from APER), used for initial estimate
;		of gaussian intensity.  If APMAG is multidimensional, (more
;		than 1 aperture was used in APER) then the first aperture
;		is used.
;	SKY    - vector of sky values (from APER)                
;
; OPTIONAL INPUTS:
;	The user will be prompted for the following parameters if not supplied.
;
;	RONOIS - readout noise per pixel, (in electrons, or equivalent photons)
;	PHPADU - photons per analog digital unit, used to scale the data
;		numbers in IMAGE into photon units
;	IDPSF  - subscripts of the list of stars created by 
;		APER which will be used to define the PSF.   Stars whose
;		centroid does not fall within PSFRAD of the edge of the frame,
;		or for which a Gaussian fit requires more than 25 iterations,
;		will be ignored when creating the final PSF.
;	PSFRAD - the scalar radius, in pixels, of the circular area within
;		which the PSF will be defined.   This should be slightly larger
;		than the radius of the brightest star that one will be
;		interested in.
;	FITRAD - the scalar radius, in pixels of the circular area used in the
;		least-square star fits.  Stetson suggest that FITRAD should
;		approximately equal to the FWHM, slightly less for crowded
;		fields.  (FITRAD must be smaller than PSFRAD.)
;	PSFNAME- Name of the FITS file that will contain the table of residuals,
;		and the best-fit Gaussian parameters.    This file is 
;		subsequently required for use by NSTAR.  
;
; OPTIONAL OUTPUTS:
;	GAUSS  - 5 element vector giving parameters of gaussian fit to the 
;		first PSF star
;		GAUSS(0) - height of the gaussian (above sky)
;		GAUSS(1) - the offset (in pixels) of the best fitting gaussian
;			and the original X centroid
;		GAUSS(2) - similiar offset from the Y centroid 
;		GAUSS(3) - Gaussian sigma in X
;		GAUSS(4) - Gaussian sigma in Y
;	PSF    - 2-d array of PSF residuals after a Gaussian fit.
;
; PROCEDURE:
;	GETPSF fits a Gaussian profile to the core of the first PSF star 
;	and generates a look-up table of the residuals of the
;	actual image data from the Gaussian fit.  If desired, it will then
;	fit this PSF to another star (using PKFIT) to determine its precise 
;	centroid, scale the same Gaussian to the new star's core, and add the
;	differences between the actual data and the scaled Gaussian to the
;	table of residuals.   (In other words, the Gaussian fit is performed
;	only on the first star.)
;
; OPTIONAL KEYWORD INPUT:
;	DEBUG - if this keyword is set and non-zero, then the result of each
;		fitting iteration will be displayed.
;
; PROCEDURES CALLED
;	DAOERF, MAKE_2D, MKHDR, RINTER(), PKFIT, STRNUMBER(), STRN(), WRITEFITS
;
; REVISON HISTORY:
;	Adapted from the 1986 version of DAOPHOT in STSDAS
;	IDL Version 2  W Landsman           November 1988
;	Use DEBUG keyword instead of !DEBUG  W. Landsman       May 1996
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;    GETROT
; PURPOSE:
;     Return the rotation and plate scale of an image from its FITS header
; EXPLANATION:
;     Derive the counterclockwise rotation angle, and the X and Y scale
;     factors of an image, from a FITS image header.   Input parameter 
;     may be either a FITS image header or an astrometry structure (as 
;     obtained by EXTAST.PRO)
;
; CALLING SEQUENCE:
;     GETROT, Hdr, [ Rot, CDelt, /SILENT, DEBUG =  ]   
;             or 
;     GETROT, Astr, Rot, CDelt, /SILENT, DEBUG = ]       
;
; INPUT PARAMETERS:
;     HDR - FITS Image header (string array).  Program will extract the 
;             astrometry structure
;              or
;     ASTR -  ASTROMETRY structure, of the type returned by EXTAST.
;             See the documentation for EXTAST.PRO for details.
;
; OPTIONAL OUTPUT PARAMETERS:
;       ROT - Scalar giving the counterclockwise rotation of NORTH in DEGREES 
;               from the +Y axis of the image.
;       CDELT- 2 element vector giving the scale factors in DEGREES/PIXEL in 
;               the X and Y directions.   CDELT[1] is always positive, whereas
;               CDELT[0] is negative for a normal left-handed coordinate system,
;               and positive for a right-handed system. 
;
;       If no output variables are supplied (or /DEBUG is set), then GETROT 
;       will display the rotation and plate scale at the terminal.
;
; OPTIONAL INPUT KEYWORD
; 
;       DEBUG - if DEBUG is set, GETROT will print the rotation for both the 
;           X and Y axis when these values are unequal.  If DEBUG is set to 2, 
;           then the output parameter ROT will contain both X and Y rotations.
;
;       /SILENT - if set, then do not provide a warning about a right-handed
;           coordinate system
; PROCEDURE:
;       If the FITS header already contains CDELT (and CD or CROTA) keyword,
;       (as suggested by the Calabretta & Greisen (2002, A&A, 395, 1077) FITS 
;       standard) then this is used for the scale factor.
;       
;       If the header contains CD keywords but no CDELT keywords (as in IRAF
;       headers) then the scale factor is derived from the CD matrix. 
;
; PROCEDURES USED:
;       EXTAST, GSSS_EXTAST
; REVISION HISTORY:
;       Written W. Landsman STX January 1987 
;       Convert to IDL V2. M. Greason, STX, May 1990
;       Option to return both rotations added.  J. D. Offenberg, STX, Aug 1991
;       Use new astrometry structure   W. Landsman  Mar 1994
;       Recognize a GSSS header        W. Landsman  June 1994
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Correct rotation determination with unequal CDELT values WL October 1998
;       Consistent conversion between CROTA and CD matrix  WL  October 2000
;       Correct CDELT computations for rotations near 90 deg WL November 2002
;       Preserve sign in the CDELT output  WL June 2003

; NAME:
;	GETTOK                                    
; PURPOSE:
;	Retrieve the first part of the string up to a specified character
; EXPLANATION:
;	GET TOKen - Retrieve first part of string until the character char 
;	is encountered.
;
; CALLING SEQUENCE:
;	token = gettok( st, char )
;
; INPUT:
;	char - character separating tokens, scalar string
;
; INPUT-OUTPUT:
;	st - (scalar) string to get token from (on output token is removed)
;
; OUTPUT:
;	token - scalar string value is returned 
;
; EXAMPLE:
;	If ST is 'abc=999' then gettok(ST,'=') would return
;	'abc' and ST would be left as '999' 
;
; NOTES:
;       A version of GETTOK that accepts vector strings is available for users 
;       of IDL V5.3 or later from  http://idlastro.gsfc.nasa.gov/ftp/v53/
; HISTORY
;	version 1  by D. Lindler APR,86
;	Remove leading blanks    W. Landsman (from JKF)    Aug. 1991
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;       GETWRD
; PURPOSE:
;       Return the n'th word from a text string.
; CATEGORY:
; CALLING SEQUENCE:
;       wrd = getwrd(txt, n, [m])
; INPUTS:
;       txt = text string to extract from.         in
;         The first element is used if txt is an array.
;       n = word number to get (first = 0 = def).  in
;       m = optional last word number to get.      in
; KEYWORD PARAMETERS:
;       Keywords:
;         LOCATION = l.  Return word n string location.
;         DELIMITER = d. Set word delimiter (def = space & tab).
;         /LAST means n is offset from last word.  So n=0 gives
;           last word, n=-1 gives next to last, ...
;           If n=-2 and m=0 then last 3 words are returned.
;         /NOTRIM suppresses whitespace trimming on ends.
;         NWORDS=n.  Returns number of words in string.
; OUTPUTS:
;       wrd = returned word or words.              out
; COMMON BLOCKS:
;       getwrd_com
; NOTES:
;       Note: If a NULL string is given (txt="") then the last string
;             given is used.  This saves finding the words again.
;             If m > n wrd will be a string of words from word n to
;             word m.  If no m is given wrd will be a single word.
;             n<0 returns text starting at word abs(n) to string end
;             If n is out of range then a null string is returned.
;             See also nwrds.
; MODIFICATION HISTORY:
;       Ray Sterner,  6 Jan, 1985.
;       R. Sterner, Fall 1989 --- converted to SUN.
;       R. Sterner, Jan 1990 --- added delimiter.
;       R. Sterner, 18 Mar, 1990 --- added /LAST.
;       R. Sterner, 31 Jan, 1991 --- added /NOTRIM.
;       R. Sterner, 20 May, 1991 --- Added common and NULL string.
;       R. Sterner, 13 Dec, 1992 --- Made tabs equivalent to spaces.
;       R. Sterner,  4 Jan, 1993 --- Added NWORDS keyword.
;       R. Sterner, 2001 Jan 15 --- Fixed to use first element if not a scalar.
;       Johns Hopkins University Applied Physics Laboratory.
;
; Copyright (C) 1985, 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.

; NAME:
;       GET_COORDS
;
; PURPOSE:
;       Converts a string with angular coordinates  to floating point values.  
; EXPLANATION:
;       Although called by ASTRO.PRO, this is a general purpose routine.
;       The user may input as floating point or sexigesimal.  If user inputs 
;       calling procedure's job to convert hours to degrees if needed.
;       Since the input string is parsed character-by-character, ANY character
;       that is not a digit, minus sign or decimal point may be used as a 
;       delimiter, i.e. acceptable examples of user input are:
;
;       1:03:55 -10:15:31
;       1 3 55.0 -10 15 31
;       1*3 55              -10abcd15efghij31
;       1.065278  hello   -10.25861
;
; CALLING SEQUENCE:
;       GET_COORDS, Coords, [ PromptString, NumVals, INSTRING =, /QUIET ]
;
; OPTIONAL INPUT:
;       PromptString - A string to inform the user what data are to be entered
;
; OPTIONAL KEYWORD INPUT:
;       InString - a keyword that, if set, is assumed to already contain the
;               input data string to be parsed.  If this keyword is set, then
;               the user is not prompted for any input.
;       /Quiet - if set the program won't printout any error messages, but bad
;               input is still flagged by Coords=[-999,-999].
;
; OUTPUT:
;       Coords - a 2 element floating array containing the coordinates.  The
;               vector [-999,-999] is returned if there has been an error.
;
; OPTIONAL OUTPUT:
;       NumVals - the number of separate values entered by the user:  2 if the
;               user entered the coordinates as floating point numbers, 6 if 
;               the user entered the coordinates as sexigesimal numbers.  Some
;               calling procedures might find this information useful (e.g., to
;               to print some output in the same format as the user's input).
;
; REVISION HISTORY:
;       Written by Joel Parker, 5 MAR 90
;       Included InString and Quiet keywords.  Cleaned up some of the code and
;       comments.  JWmP,  16 Jun 94
;
;*******************************************************************************
;       Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;       GET_DATE
; PURPOSE:
;       Return the (current) UTC date in CCYY-MM-DD format for FITS headers
; EXPLANATION:
;       This is the format required by the DATE and DATE-OBS keywords in a 
;       FITS header.
;
; CALLING SEQUENCE:
;       GET_DATE, FITS_date, [ in_date, /OLD, /TIMETAG, LOCAL_DIFF=]
; OPTIONAL INPUTS:
;       in_date - string (scalar or vector) containing dates in IDL
;            systime() format (e.g. 'Tue Sep 25 14:56:14 2001')
; OUTPUTS:
;       FITS_date = A scalar character string giving the current date.    Actual
;               appearance of dte depends on which keywords are supplied.
;       
;       No Keywords supplied - dte is a 10 character string with the format
;               CCYY-MM-DD where  represents a calendar year,  the
;               ordinal number of a calendar month within the calendar year, 
;               and 
the ordinal number of a day within the calendar month. ; /TIMETAG set - dte is a 19 character string with the format ; CCYY-MM-DDThh:mm:ss where represents the hour in the day, ; the minutes, the seconds, and the literal 'T' the ; ISO 8601 time designator ; /OLD set - dte is an 8 character string in DD/MM/YY format ; ; INPUT KEYWORDS: ; /TIMETAG - Specify the time to the nearest second in the DATE format ; /OLD - Return the DATE format formerly (pre-1997) recommended for FITS ; Note that this format is now deprecated because it uses only ; a 2 digit representation of the year. ; LOCAL_DIFF - numeric scalar giving the difference between local time ; and Greenwich Mean Time (GMT) in hours. This keyword is only ; needed for non-Unix users prior to V5.4. Unix users should not ; use this keyword because under Unix (or since V5.4 with any OS), ; SYSTIME(1) returns the UTC (=GMT) time directly. ; Users on other machines must either supply a LOCAL_DIFF keyword, ; or use the TIME_CONV environment variable discussed below. ; For example, a user on U.S. Eastern Standard Time should set ; LOCAL_DIFF = -5 ; EXAMPLE: ; Add the current date to the DATE keyword in a FITS header,h ; ; IDL> GET_DATE,dte ; IDL> sxaddpar, h, 'DATE', dte, 'Date header was created' ; ENVIRONMENT VARIABLE: ; An alternate method of inputing the difference between local and GMT ; time for non-Unix machines is to specify this information in a file ; named local_diff.dat in a directory specified with the environment ; variable TIME_CONV. For example, a user in EST should write -5 ; on this first (and only) line of this file. ; ; NOTES: ; (1) A discussion of the DATExxx syntax in FITS headers can be found in ; http://www.cv.nrao.edu/fits/documents/standards/year2000.txt ; ; (2) Those who wish to use need further flexibility in their date ; formats (e.g. to use TAI time) should look at Bill Thompson's time ; routines in http://sohowww.nascom.nasa.gov/solarsoft/gen/idl/time ; ; PROCEDURES USED: ; DAYCNV - Convert Julian date to Gregorian calendar date ; REVISION HISTORY: ; Written W. Landsman March 1991 ; Major rewrite to write new DATExxx syntax W. Landsman August 1997 ; Converted to IDL V5.0 W. Landsman September 1997 ; Work after year 2000 even with /OLD keyword W. Landsman January 2000 ; Don't need to worry about TIME_DIFF since V5.4 W. Landsman July 2001

; NAME:
;       GET_EQUINOX
; PURPOSE:
;       Return the equinox value from a FITS header.  
; EXPLANATION:
;       Checks for 3 possibilities:
;
;       (1)  If the EQUINOX keyword is found and has a numeric value, then this
;               value is returned
;       (2)  If the EQUINOX keyword has the values 'J2000' or 'B1950', then
;               either 2000. or 1950. is returned.
;       (3)  If the EQUINOX keyword is not found, then GET_EQUINOX will return
;               the EPOCH keyword value.   This usage of EPOCH is disparaged.
;
;       According Calabretta & Greisen (2002, A&A, 395, 1077) the EQUINOX should
;       be written as a numeric value, as in format (1).   However, in older 
;       FITS headers, the EQUINOX might have been written using formats (2) or 
;       (3) 
; CALLING SEQUENCE:
;       Year = GET_EQUINOX( Hdr, [ Code ] )   
;
; INPUTS:
;       Hdr - FITS Header, string array, will be searched for the EQUINOX
;               (or EPOCH) keyword.
;
; OUTPUT:
;       Year - Year of equinox in FITS header, numeric scalar
; OPTIONAL OUTPUT:
;       Code - Result of header search, scalar
;               -1 - EQUINOX or EPOCH keyword not found in header
;               0 - EQUINOX found as a numeric value
;               1 - EPOCH keyword used for equinox (not recommended)
;               2 - EQUINOX found as  'B1950'
;               3 - EQUINOX found as  'J2000'
;
; PROCEDURES USED:
;       ZPARCHECK, SXPAR()
; REVISION HISTORY:                                               
;       Written  W. Landsman        STX              March, 1991
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Don't use !ERR          W. Landsman   February 2000
;       N = 1 for check of EPOCH keyword, not 0 S. Ott July 2000

; NAME:
;    GET_JULDATE
; PURPOSE:
;     Return the current Julian Date
;
; EXPLANATION:
;     This procedure became partially obsolete with the introduction of the
;     /JULIAN keyword to the intrinsic SYSTIME function in IDL V5.2.   Note
;     however, that SYSTIME(/JULIAN) always returns the *local* time, whereas
;     for most machines, GET_JULDATE returns  Universal Time (i.e. Greenwich
;     mean time.)
;
;     In V5.4, GET_JULDATE became completely obsolete with the introduction
;     of the /UTC keyword to SYSTIME().   So GET_JULDATE,jd is equivalent to
;     jd = SYSTIME(/JULIAN,/UTC).
;
; CALLING SEQUENCE:
;       GET_JULDATE,jd
;
; INPUTS:
;       None
;
; OUTPUTS:
;       jd = Current Julian Date, double precision scalar
;
; EXAMPLE:
;       Return the current hour, day, month and year as integers
;
;       IDL> GET_JULDATE, JD                  ;Get current Julian date
;       IDL> DAYCNV, JD, YR, MON, DAY, HOURS  ;Convert to hour,day month & year
;
; METHOD:
;       The systime(1) function is used to obtain the number of days after 
;       1-JAN-1970.     The offset to Julian days is then computed.
;
;       WARNING!   This procedure assumes that systime(1) returns the value
;       of Universal Time (UT).    This appears to be true for most Unix
;       workstations and DOS machines, but not for VMS or Macintoshes, 
;       for which systime(1) returns the local time.     Users
;       may need to add the difference between UT and local time to the value
;       of JD, depending on the particular installation.
;
; REVISION HISTORY:
;       Written Wayne Landsman                March, 1991
;       Converted to IDL V5.0   W. Landsman   September 1997

; NAME:  
;       GLACTC
; PURPOSE:
;        Convert between celestial and Galactic (or Supergalactic) coordinates.
; EXPLANATION:
;       Program to convert right ascension (ra) and declination (dec) to
;       Galactic longitude (gl) and latitude (gb) (j=1) or vice versa (j=2).
;
; CALLING SEQUENCE: 
;       GLACTC, ra, dec, year, gl, gb, j, [ /DEGREE, /FK4, /SuperGalactic ]
;
; INPUT PARAMETERS: 
;       year     equinox of ra and dec, scalar       (input)
;       j        direction of conversion     (input)
;               1:  ra,dec --> gl,gb
;               2:  gl,gb  --> ra,dec
;
; INPUTS OR OUTPUT PARAMETERS: ( depending on argument J )
;       ra       Right ascension, hours (or degrees if /DEGREES is set), 
;                         scalar or vector
;       dec      Declination, degrees,scalar or vector
;       gl       Galactic longitude, degrees, scalar or vector
;       gb       Galactic latitude, degrees, scalar or vector
;
;       All results forced double precision floating.
;
; OPTIONAL INPUT KEYWORD PARAMETERS:
;       /DEGREE - If set, then the RA parameter (both input and output) is 
;                given in degrees rather than hours. 
;       /FK4 - If set, then the celestial (RA, Dec) coordinates are assumed
;              to be input/output in the FK4 system.    By default,  coordinates
;              are assumed to be in the FK5 system.    For B1950 coordinates,
;              set the /FK4 keyword *and* set the year to 1950.
;       /SuperGalactic - If set, the GLACTC returns SuperGalactic coordinates
;              as defined by deVaucouleurs et al. (1976) to account for the 
;              local supercluster. The North pole in SuperGalactic coordinates 
;              has Galactic coordinates l = 47.47, b = 6.32, and the origin is 
;              at Galactic coordinates l = 137.37, b= 0 
;              
; EXAMPLES:
;       Find the Galactic coordinates of Altair (RA (J2000): 19 50 47 
;       Dec (J2000): 08 52 06)
;
;       IDL> glactc, ten(19,50,47),ten(8,52,6),2000,gl,gb,1
;       ==> gl = 47.74, gb = -8.91
;
; PROCEDURE CALLS:
;       BPRECESS, JPRECESS, PRECESS
; HISTORY: 
;       FORTRAN subroutine by T. A. Nagy, 21-MAR-78.
;       Conversion to IDL, R. S. Hill, STX, 19-OCT-87.
;       Modified to handle vector input, E. P. Smith, GSFC, 14-OCT-94
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Added DEGREE keyword, C. Markwardt, Nov 1999
;       Major rewrite, default now FK5 coordinates, added /FK4 keyword
;       use external precession routines    W. Landsman   April 2002
;       Add /Supergalactic keyword W. Landsman  September 2002
;       Fix major bug when year not 2000 and /FK4 not set W. Landsman July 2003

; NAME:
;      GROUP
; PURPOSE:
;      Assign stars with non-overlapping PSF profiles into distinct groups
; EXPLANATION:
;      Part of the IDL-DAOPHOT sequence
;
; CALLING SEQUENCE:
;      GROUP, X, Y, RCRIT, NGROUP
;
; INPUTS:
;      X - vector, giving X coordinates of a set of stars.
;      Y - vector, giving Y coordinates of a set of stars.
;           If X and Y are input as integers, then they will be converted to 
;           floating point
;      RCRIT - scalar, giving minimum distance between stars of two
;               distinct groups.  Stars less than this distance from
;               each other are always in the same group.    Stetson suggests
;               setting the critical distance equal to the PSF radius +
;               the Fitting radius.
;
; OUTPUTS:
;      NGROUP - integer vector, same number of elements as X and Y,
;               giving a group number for each star position.  Group
;               numbering begins with 0.
;
; METHOD:
;      Each position is initially given a unique group number.  The distance
;      of each star is computed against every other star.   Those distances
;      less than RCRIT are assigned the minimum group number of the set.   A
;      check is then made to see if any groups have merged together.
;
; PROCEDURES USED:
;      REM_DUP()
;
; REVISION HISTORY:
;      Written W. Landsman  STX                  April, 1988
;      Major revision to properly merge groups together  W. Landsman   Sep 1991
;      Work for more than 32767 points    W. Landsman  March 1997
;      Converted to IDL V5.0   W. Landsman   September 1997
;      Avoid overflow if X and Y are integers      W. Landsman  Feb. 1999   

; NAME:
;      GSSSADXY
; PURPOSE:
;       Converts RA and DEC (J2000) to (X,Y) for an STScI GuideStar image.   
; EXPLANATION:
;       The sky coordinates may be printed and/or returned in variables.
;
; CALLING SEQEUNCE:
;       GSSSADXY, GSA, Ra,Dec, [ X, Y, /Print ] 

; INPUT:
;       GSA - the GSSS Astrometry structure created by GSSSEXTAST
;       RA  - the RA coordinate(s) in *degrees*, scalar or vector
;       DEC - the DEC coordinate(s) in *degrees*, scalar or vector
;
; OPTIONAL KEYWORD INPUT:
;       /PRINT - If this keyword is set and non-zero, then coordinates will be
;               displayed at the terminal
; OUTPUT:
;       X - the corresponding X pixel coordinate(s), double precision
;       Y - the corresponding Y pixel coordinate(s), double precision
;
;       X and Y will be in IDL convention (first pixel 0,0)
; EXAMPLE:
;       Given a FITS header, hdr, from the STScI Guidestar Survey, determine
;       the X,Y coordinates of 3C 273 (RA = 12 29 6.7  +02 03 08)
;
;       IDL> GSSSEXTAST, hdr, gsa          ;Extract astrometry structure
;       IDL> GSSSADXY, gsa, ten(12,29,6.7)*15,ten(2,3,8),/print
;
; NOTES:
;       For most purpose users can simply use ADXY, which will call GSSSADXY
;       if it is passed a GSSS header.
;
; PROCEDURES CALLED:
;       ASTDISP - Print RA, Dec in standard format
; HISTORY:
;       10-JUL-90 Version 1 written by Eric W. Deutsch
;               Derived from procedures written by Brian McLean
;       Vectorized code   W. Landsman        March, 1991
;       14-AUG-91 Fixed error which caused returned X and Y to be .5 pixels too
;               large.  Now X,Y follows same protocol as ADXY.
;       June 1994 - Dropped PRFLAG parameter, added /PRINT  W. Landsman (HSTX)
;       Converted to IDL V5.0   W. Landsman   September 1997
;       29-JUN-99 Added support for AMD[X,Y]1[2-3] for DSS images by E. Deutsch

; NAME: 
;      GSSSEXTAST
;
; PURPOSE:
;      Extract IDL astrometry structure from a ST Guide Star Survey FITS header
;
; EXPLANATION:
;      This procedure extracts the astrometry information from a ST Guide
;      Star Survey FITS header and places it in an IDL structure for 
;      subsequent use with GSSSxyad and GSSSadxy.
;
; CALLING SEQUENCE:
;      GSSSExtast, hdr, astr, noparams
; INPUT:
;      h - the GSSS FITS header
; OUTPUT:
;      astr  - Structure containing the GSSS Astrometry information
;               .CTYPE  =  ['RA---GSS','DEC--GSS'] 
;               .CRVAL = plate center Ra, Dec (from PLTRAH, PLTRAM etc.)
;               .XLL,.YLL = offsets lower lefthand corner
;               .AMDX, .AMDY = 12 transformation coefficients
;               .XSZ,.YSZ = X and Y pixel size in microns
;               .PLTSCL = plate scale in arc sec/mm
;               .PPO3, .PPO6 - orientation coefficients
; NOTES:
;      Most users should use EXTAST rather than this procedure.   EXTAST will
;      call GSSSEXTAST if supplied with GSSS FITS header.
;
; PROCEDURES CALLED:
;      SXPAR() - Extract parameter values from a FITS header
; HISTORY:
;       01-JUL-90 Version 1 written by Eric W. Deutsch
;       Code derived from Software by Brian McLean
;       20-AUG-91 Modified to Double Precision Variables.  E. Deutsch
;       June 94 Change astrometry tags to better agree with EXTAST  W. Landsman
;       Converted to IDL V5.0   W. Landsman   September 1997
;       29-JUN-99 Added support for AMD[X,Y]1[2-3] for DSS images by E. Deutsch
;       Eliminate use of obsolete !ERR  W. Landsman    February 2000

; NAME:
;       GSSSXYAD
; PURPOSE:
;       Convert (X,Y) coordinates in a STScI Guide Star image to RA and Dec
; EXPLANATION:
;       The sky coordinates may be printed and/or returned in variables.
;
; CALLING SEQUENCE:
;       GSSSxyad, gsa, x, y, ra, dec, [ /PRINT ]
; INPUT:
;       GSA  - The GSSS Astrometry structure extracted from a FITS header 
;              by GSSSEXTAST
;       X - The X pixel coordinate(s) of the image, scalar or vector
;       Y - The Y pixel coordinate(s) of the image, scalar or vector
;
; OUTPUT:
;       RA - The RA coordinate of the given pixel(s) in *degrees*
;       DEC - The DEC coordinate of the given pixel(s) in *degrees*
;
;       Both RA and Dec will be returned as double precision
;
; OPTIONAL KEYWORD INPUT:
;       /PRINT - If this keyword is set and non-zero, then coordinates will be
;               displayed at the terminal
; EXAMPLE:
;       Given a FITS header,hdr, from a GSSS image, print the astronomical
;       coordinates of (X,Y) = (200.23, 100.16) at the terminal
;
;       IDL> GSSSExtast, hdr, gsa        ;Extract astrometry structure
;       IDL> GSSSxyad, gsa, 200.23, 100.16, /print
;
; NOTES:
;       For most purpose users can simply use XYAD, which will call GSSSXYAD
;       if it is passed a GSSS header.
;
; PROCEDURES CALLED:
;       ASTDISP - print RA, Dec in a standard format
; HISTORY:
;       01-JUL-90 Version 1 written by Eric W. Deutsch
;       Vectorized Code   W. Landsman        March, 1991
;       14-AUG-91 Fixed error which caused returned RA and DEC to be off by
;       -.5 pixels in both X,Y.  Now X,Y follows same protocol as ADXY.
;       20-AUG-91 Modified to use AstDisp procedure.
;       June 94 Added /PRINT keyword instead of PRFLAG W. Landsman June 94
;       Converted to IDL V5.0   W. Landsman   September 1997
;       29-JUN-99 Added support for AMD[X,Y]1[2-3] for DSS images by E. Deutsch

; NAME:
;      GSSS_STDAST
;
; PURPOSE:
;      Insert the closest tangent projection astrometry into an GSSS Image
;   
; DESCRIPTION:
;       This procedure takes a header with GSSS (ST Guide Star Survey) 
;       astrometry and writes a roughly equivalent tangent projection 
;       astrometry into the header. 
;
; CALLING SEQUENCE:
;       GSSS_STDAST, H, [Xpts, Ypts]
;
; INPUT - OUTPUT:
;       H -  FITS header (string array) containing GSSS astrometry.  
;       GSSS_STDAST will write the roughly equivalent tangent projection 
;               astrometry solution into H.
; OPTIONAL INPUTS:
;       xpts, ypts -- Vectors giving the X and Y positions of the three 
;               reference points used to find approximate tangent projection.
;               Default is Xpts = [0.2,0.8,0.5], Ypts = [0.2, 0.4, 0.8]
; METHOD:
;       The procedures GSSSXYAD is used to exactly determine the RA and Dec
;       at 3 reference points.    STARAST is then used to find the tangent
;       projection astrometry that best matches these reference points.
;
; NOTES:
;       Some early GSSS images (before the 1994 CD-Rom) used keywords CRPIXx
;       rather than CNPIXx.    The GSSS astrometry in these images could be
;       corrupted by this procedure as the CRPIXx values will be altered.
;
;       The tangent is only a approximation of the nonlinear GSSS astrometry,
;       but is generally accurate to about 0.1 pixels on a 1024 x 1024 image.
;
; PROCEDURES USED:
;       GSSSEXTAST, GSSSXYAD, STARAST, PUTAST, SXADDHIST, SXDELPAR
;
; HISTORY:
;       13-AUG-91 Version 2 written from MAKEASTGSSS  Eric Deutsch (STScI)
;       Delete CDELT* keywords from header   W. Landsman      May 1994
;       Remove call to BUILDAST  W. Landsman                  Jan, 1995
;       Added optional Xpts, Ypts parameters   E. Deutsch     Oct, 1995
;       Converted to IDL V5.0   W. Landsman   September 1997

;  NAME:
;     HADEC2ALTAZ
;  PURPOSE:
;      Converts Hour Angle and Declination to Horizon (alt-az) coordinates.
;  EXPLANATION:
;      Can deal with NCP/SCP singularity.    Intended mainly to be used by
;      program EQ2HOR
;
; CALLING SEQUENCE:
;      HADEC2ALTAZ, ha, dec, lat ,alt ,az [ /WS ]
;
; INPUTS
;     ha -  the local apparent hour angle, in DEGREES, scalar or vector
;     dec -  the local apparent declination, in DEGREES, scalar or vector
;     lat -  the local latitude, in DEGREES, scalar or vector
;
; OUTPUTS
;     alt - the local apparent altitude, in DEGREES.
;     az  - the local apparent azimuth, in DEGREES, all results in double
;           precision
; OPTIONAL KEYWORD INPUT:
;      /WS - Set this keyword for the output azimuth to be measured West from 
;            South.    The default is to measure azimuth East from North.
;
; EXAMPLE:
;     What were the apparent altitude and azimuth of the sun when it transited 
;     the local meridian at Pine Bluff Observatory (Lat=+43.07833 degrees) on 
;     April 21, 2002?   An object transits the local meridian at 0 hour angle.
;     Assume this will happen at roughly 1 PM local time (18:00 UTC).
;
;     IDL> jdcnv, 2002, 4, 21, 18., jd  ; get rough Julian date to determine 
;                                       ;Sun ra, dec.
;     IDL> sunpos, jd, ra, dec
;     IDL> hadec2altaz, 0., dec, 43.078333, alt, az
;
;       ===> Altitude alt = 58.90
;            Azimuth  az = 180.0

; REVISION HISTORY:
;      Written  Chris O'Dell Univ. of Wisconsin-Madison May 2002

; NAME:
;       HASTROM
; PURPOSE:
;       Linear transformation of an image to align it with a reference image
; EXPLANATION:
;       A linear transformation is applied (using POLY_2D) to an image so that   
;       its astrometry is identical with that in a reference header.  This
;       procedure can be used to align two images.
;
; CALLING SEQUENCE:
;       HASTROM, oldim, oldhd, newim, newhd, refhd, [MISSING =, INTERP = ]
;                            or
;       HASTROM, oldim, oldhd, refhd, [MISSING =, INTERP ={0,1,2}, NGRID =, 
;                                      CUBIC =, DEGREE = ]
;
; INPUTS:
;       OLDIM - Image array to be manipulated.  If only 3 parameters are
;               supplied then OLDIM and OLDHD will be modified to contain 
;               the output image array and header
;       OLDHD - FITS header array for OLDIM, containing astrometry parameters
;       REFHD - Reference header, containing astrometry parameters.  OLDIM
;               will be rotated, shifted, and compressed or expanded until
;               its astrometry matches that in REFHD.
; OUTPUTS:
;       NEWIM - Image array after linear tranformation has been performed.
;               The dimensions of NEWIM will be identical to the NAXIS1 and 
;               NAXIS2 keywords specified in REFHD.  Regions on the reference 
;               image that do not exist in OLDIM can be assigned a value with
;               the MISSING keyword.
;       NEWHD - Updated FITS image header associated with NEWIM
;
; OPTIONAL INPUT KEYWORDS:
;       MISSING - Set this keyword to a scalar value which will be assigned
;               to pixels in the output image which are out of range of the
;               supplied imput image.  If not supplied, then linear 
;               extrapolation is used.   See the IDL manual on POLY_2D.
;               ***NOTE: A bug was introduced into the POLY_2D function in IDL 
;               V5.5 (still present in V5.6) such that the MISSING keyword
;               may not work properly.***
;       INTERP - Scalar, one of 0, 1, or 2 determining type of interpolation
;               0 nearest neighbor, 1 (default) bilinear interpolation, 
;               2 cubic interpolation.
;       CUBIC - a scalar value between -1 and 0 specifying cubic interpolation
;               with the specified value as the cubic interpolation parameter.
;              (see poly_2d for info).    Setting CUBIC to a value greater 
;               than zero is equivalent to setting CUBIC = -1. 
;       NGRID -  Integer scalar specifying the number of equally spaced grid 
;               points on each axis to use to specify the transformation.   
;               Default is NGRID = 3 (9 total grid points).     The value of
;               NGRID must always be greater than DEGREE + 1
;       DEGREE - Integer scalar specifying the degree of the transformation.
;               See the routine POLYWARP for more info.   Default = 1
;              (linear transformation).
; OPTIONAL OUTPUT KEYWORD:
;       ERRMSG - If this keyword is supplied, then any error mesasges will be
;               returned to the user in this parameter rather than depending on
;               on the MESSAGE routine in IDL.   If no errors are encountered
;               then a null string is returned.               
; NOTES:
;       (1) The 3 parameter calling sequence is less demanding on virtual 
;               memory.
;       (2) The astrometry in OLDHD will be precessed to match the equinox
;                given in REFHD.
;       (3) If an ST Guidestar image is used for the reference header, then the
;                output header will be converted to standard astrometry.  
; EXAMPLE:
;       Suppose one has an image array, IM, and an associated FITS header H.
;       One desires to warp the image array so that it is aligned with another
;       image with a FITS header, HREF.    Both headers contain astrometry info.
;       Set pixel values to 0 where there is no overlap between the input and
;       reference image, and use linear interpolation (default)
;
;       IDL> hastrom, IM, H, HREF, MISSING = 0
;
; PROCEDURES USED:
;       ad2xy, check_FITS, extast, get_EQUINOX(), gsssextast, hprecess,
;       putast, sxaddpar, sxaddhist, sxpar(), xy2ad, zparcheck
;
; REVISION HISTORY:
;       Written  W. Landsman, STX Co.              Feb, 1989
;       Updated to CHECK_FITS                      Dec, 1991
;       New astrometry keywords                    Mar, 1994
;       Recognize GSSS header   W. Landsman        June, 1994
;       Added CUBIC keyword     W. Landsman        March, 1997
;       Converted to IDL V5.0   W. Landsman        September 1997
;       Accept INTERP=0, Convert output GSS header to standard astrometry
;                               W. Landsman        June 1998
;       Remove calls to obsolete !ERR system variable   March 2000
;       Added ERRMSG output keyword  W. Landsman    April 2000
;       Need to re-extract astrometry after precession  W. Landsman Nov. 2000
;       

; NAME:
;       HBOXAVE
; PURPOSE:
;       Box average an image array and update the FITS header array
; EXPLANATION:
;       The function BOXAVE() is used.  This procedure is recommended for 
;       integer images when photometric precision is desired, because it 
;       performs intermediate steps using REAL*4 arithmetic.   Otherwise, the 
;       procedure HREBIN is much faster.
;
; CALLING SEQUENCE:
;       HBOXAVE, Oldim, Oldhd, Newim, Hewhd, box
;               or
;       HBOXAVE, Oldim, Oldhd, box
;
; INPUTS:
;       Oldim - the original image array
;       Oldhd - the original image FITS header, string array
;
; OPTIONAL INPUTS:
;       box - the box size to be used, integer scalar.  If omitted, then
;               HBOXAVE will prompt for this parameter.
;
; OPTIONAL OUTPUTS:
;       Newim - the image after boxaveraging
;       Newhd - header for newim containing updated astrometry info
;               If output parameters are not supplied, the program
;               will modify the input parameters OLDIM and OLDHD
;               to contain the new array and updated header.
; OPTIONAL KEYWORD OUTPUT:
;       ERRMSG - If this keyword is supplied, then any error mesasges will be
;               returned to the user in this parameter rather than depending on
;               on the MESSAGE routine in IDL.   If no errors are encountered
;               then a null string is returned.               
;
; PROCEDURE:
;       The parameters BSCALE, NAXIS1, NAXIS2, CRPIX1, and CRPIX2 and
;       the CD (or CDELT) parameters are updated for the new FITS header.
;
; EXAMPLE:
;       Compress the image in a FITS file 'image.fits' by a factor of 4 and 
;       update the astrometry in the FITS header
;
;       IDL> im = readfits('image.fits',hdr)    ;Read FITS file into IDL arrays
;       IDL> hboxave, im, hdr, 4                ;Boxaverage by 4
;       IDL> writefits,'image.fits',im,hdr      ;Write a new FITS file
;
; CALLED PROCEDURES:
;       CHECK_FITS - Check that the FITS header is appropriate to the image
;       BOXAVE() - Performs box averaging of an image
;       SXPAR(), SXADDPAR - Read and write FITS keyword values
;
; MODIFICATION HISTORY:
;       Written, Aug. 1986 W. Landsman, STI Corp.
;       IDLV2 changes, sxaddpar format keyword added, J. Isensee, July,1990
;       Fix 0.5 pixel offset in new CRPIX computation W. Landsman, Dec, 1991
;       Update BSCALE even if no astrometry present   W. Landsman, May 1997
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Added ERRMSG keyword, Use double formatting   W. Landsman   April 2000
;       Recognize PC matrix astrometry format    W. Landsman   December 2001

; NAME:
;       HCONGRID
; PURPOSE:
;       CONGRID an image and update astrometry in a FITS header
; EXPLANATION:
;       Expand or contract an image using CONGRID and update the 
;       associated FITS header array.
;
; CALLING SEQUENCE:
;       HCONGRID, oldhd                       ;Update FITS header only
;       HCONGRID, oldim, oldhd, [ newim, newhd, newx, newy, /HALF_HALF
;                                 CUBIC = , INTERP=, OUTSIZE =, ERRMSG = ]
;
; INPUTS:
;       OLDIM - the original image array
;       OLDHD - the original image FITS header, string array
;
; OPTIONAL INPUTS:
;       NEWX - size of the new image in the X direction
;       NEWY - size of the new image in the Y direction
;               The OUTSIZE keyword can be used instead of the 
;               NEWX, NEWY parameters
;
; OPTIONAL OUTPUTS:
;       NEWIM - the image after expansion or contraction with CONGRID
;       NEWHD - header for newim containing updated astrometry info
;               If output parameters are not supplied, the program
;               will modify the input parameters OLDIM and OLDHD
;               to contain the new array and updated header.
;
; OPTIONAL KEYWORD INPUTS:
;       CUBIC - If set and non-zero, then cubic interpolation is used.   Valid
;               ranges are  -1 <= Cubic < 0.   Setting /CUBIC is equivalent to
;               CUBIC = -1 and also equivalent to INTERP = 2.   See INTERPOLATE
;               for more info.    Setting CUBIC = -0.5 is recommended.
;       ERRMSG - If this keyword is supplied, then any error mesasges will be
;               returned to the user in this parameter rather than depending on
;               on the MESSAGE routine in IDL.   If no errors are encountered
;               then a null string is returned.               
;       /HALF_HALF - Due to edge effects, the default behaviour of CONGRID is 
;           to introduce a slight shift in the image center.  Craig Markwardt
;           (http://cow.physics.wisc.edu/~craigm/idl/misc.html) has written
;           a modified version of CONGRID called CMCONGRID that when used with
;           the /HALF_HALF keyword eliminates any shift.   The use of the 
;           /HALF keyword emulates CMCONGRID and eliminates any shift in the
;           image centroid. 
;       INTERP   - 0 for nearest neighbor, 1 for bilinear interpolation
;               (default), 2 for cubic (=-1) interpolation.   
;       OUTSIZE - Two element integer vector which can be used instead of the
;               NEWX and NEWY parameters to specify the output image dimensions
; OPTIONAL KEYWORD OUTPUT:
;       ERRMSG - If this keyword is supplied, then any error mesasges will be
;               returned to the user in this parameter rather than depending on
;               on the MESSAGE routine in IDL.   If no errors are encountered
;               then a null string is returned.               
; PROCEDURE:
;       Expansion or contraction is done using the CONGRID function, unless
;       HALF_HALF is set. 
;
;       The parameters BSCALE, NAXIS1, NAXIS2, CRPIX1, and CRPIX2 and
;       the CD (or CDELT) parameters are updated for the new header.
;
; NOTES:
;       A FITS header can be supplied as the first parameter without having
;       to supply an image array.   The astrometry in the FITS header will be
;       updated to be appropriate to the specified image size.
;
;       If the FITS header contains astrometry from a ST Guide Star image,
;       then the astrometry will be converted to an approximately equivalent
;       tangent projection before applying CONGRID.
; EXAMPLE:
;       Congrid an 512 x 512 image array IM and FITS header H to size 300 x 300
;       using cubic interpolation.   Use the HALF_HALF keyword to avoid 
;       a shift of the image centroid
;
;       IDL> hcongrid, IM ,H, OUT = [300, 300], CUBIC = -0.5, /HALF
;
;       The variables IM and H will be modified to the new image size.
;
; PROCEDURES CALLED:
;       CHECK_FITS, CONGRID(), EXTAST, GSSS_STDAST, SXADDHIST, 
;       SXADDPAR, SXPAR(), ZPARCHECK
; MODIFICATION HISTORY:
;       Written, Aug. 1986 W. Landsman, STI Corp.
;       Added interp keywords, J. Isensee, July, 1990
;       Add cubic interpolation W. Landsman HSTX   January 1994
;       Recognize a GSSS FITS header   W. Landsman   June 1994
;       Fix case where header but not image supplied  W. Landsman  May 1995
;       Remove call to SINCE_VERSION()   W. Landsman   March 1996
;       Assume since IDL V3.5, add CUBIC keyword      W. Landsman   March 1997
;       Update BSCALE even if no astrometry present   W. Landsman   May 1997
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Added HALF_HALF keyword  W. Landsman  February 2000
;       Added ERRMSG keyword, use double precision formatting W.L.  April 2000
;       Recognize PC00n00m astrometry format  W. Landsman   December 2001
;       Now works when both /INTERP and /HALF are set W. Landsman January 2002

; NAME:
;       HEADFITS
; PURPOSE:
;       Read a FITS (primary or extension) header into a string array.
; EXPLANATION:
;       Under Unix, HEADFITS() can also read gzip (.gz) or Unix compressed
;       (.Z) FITS files.   In IDL V5.3 or later, HEADFITS() can read gzip files
;       under any machine OS. 
;
; CALLING SEQUENCE:
;       Result = HEADFITS(Filename/Fileunit ,[ ERRMSG =, EXTEN= , COMPRESS=, 
;                                            /SILENT ])
;
; INPUTS:
;       Filename = String containing the name of the FITS file to be read.
;                File names ending in '.gz' are assumed to be gzip'ed compressed
;                and under Unix file names ending in '.Z' are assumed to be
;                Unix compressed.    If this default behaviour is not sufficient
;                then use the COMPRESS keyword.
;                            or
;       Fileunit - A scalar integer specifying the unit of an already opened
;                  FITS file.  The unit will remain open after exiting 
;                  HEADFITS().  There are two possible reasons for choosing 
;                  to specify a unit number rather than a file name:
;          (1) For a FITS file with many extensions, one can move to the 
;              desired extensions with FXPOSIT() and then use HEADFITS().  This
;              is more efficient that repeatedly starting at the beginning of 
;              the file.
;          (2) For reading a FITS file across a Web http: address after opening
;              the unit with the SOCKET procedure (IDL V5.4 or later,
;              Unix and Windows only) 
; OPTIONAL INPUT KEYWORDS:
;      EXTEN  = integer scalar, specifying which FITS extension to read.
;               For example, to read the header of the first extension set
;               EXTEN = 1.   Default is to read the primary FITS header 
;               (EXTEN = 0).    The EXTEN keyword cannot be used when a unit
;               number is supplied instead of a file name.
;     COMPRESS - If this keyword is set and non-zero, then treat the file
;              as compressed.  If 1 assume a gzipped file.   Where possible use
;              IDLs internal decompression facilities (i.e., v5.3 or greater) 
;              or on Unix systems spawn off a process to decompress and use its
;              output as the FITS stream.  If the keyword is not 1, then use 
;              its value as a string giving the command needed for 
;              decompression.   See FXPOSIT for more info.
;     /SILENT - If set, then suppress any warning messages about invalid 
;              characters in the FITS file.
; OPTIONAL KEYWORD OUTPUT:
;       ERRMSG	= If this keyword is present, then any error messages will be
;                 returned to the user in this parameter rather than
;                 depending on the MESSAGE routine in IDL.  If no errors are
;                 encountered, then a null string is returned.  
;
; OUTPUTS:
;       Result of function = FITS header, string array
;
; EXAMPLE:
;       Print the main FITS header of a file 'test.fits' into a string 
;       variable, h
;
;       IDL>  print, headfits( 'test.fits')
;
;       Print the second extension header of a gzip compressed FITS file
;       'test.fits.gz'.  Use HPRINT for pretty format
;
;       IDL> hprint, headfits( 'test.fits.gz', ext=2)
;
; PROCEDURES CALLED
;       FXPOSIT(), MRD_HREAD
; MODIFICATION HISTORY:
;       adapted by Frank Varosi from READFITS by Jim Wofford, January, 24 1989
;       Keyword EXTEN added, K.Venkatakrishna, May 1992
;       Make sure first 8 characters are 'SIMPLE'  W. Landsman October 1993
;       Check PCOUNT and GCOUNT   W. Landsman    December 1994
;       Major rewrite, work for Unix gzip files,   W. Landsman  April 1996
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Added COMPRESS keyword  W. Landsman   April 2000
;       Added ERRMSG keyword    W. Landsman   July 2000
;       Added /SILENT keyword   W. Landsman    December 2000
;       Option to read a unit number rather than file name W.L    October 2001

; NAME: 
;      HELIO
; PURPOSE: 
;      Compute (low-precision) heliocentric coordinates for the planets.
; EXPLANATION:
;      The mean orbital elements for epoch J2000 are used.   These are derived
;      from a 250 yr least squares fit of the DE 200 planetary ephemeris to a 
;      Keplerian orbit where each element is allowed to vary linearly with 
;      time.  For dates between 1800 and 2050, this solution fits the 
;      terrestrial planet orbits to ~25" or better, but achieves only ~600" 
;      for Saturn.   
;
;      Use PLANET_COORDS (which calls HELIO) to get celestial (RA, Dec)
;      coordinates of the planets
; CALLING SEQUENCE: 
;       HELIO, JD, LIST, HRAD, HLONG, HLAT, [/RADIAN]
; INPUTS:
;       JD = Julian date, double precision scalar or vector
;       LIST = List of planets array.  May be a single number.
;               1 = merc, 2 = venus, ... 9 = pluto.
;
; OUTPUTS:
;       HRAD = array of Heliocentric radii (A.U).
;       HLONG = array of Heliocentric (ecliptic) longitudes (degrees).
;       HLAT = array of Heliocentric latitudes (degrees).
;             These output parameters will be dimensioned Nplanet by Ndate,
;             where Nplanet is the number of elements of list, and Ndate is 
;             the number of elements of JD.
;
; OPTIONAL INPUT KEYWORD:
;       /RADIAN - If set, then the output longitude and latitude are given in 
;                 radians.         
; EXAMPLE:
;       (1) Find the current heliocentric positions of all the planets
;
;        IDL> GET_JULDATE, jd      ;Get current Julian date
;        IDL> HELIO,jd,indgen(9)+1,hrad,hlong,hlat  ;Get radius, long, and lat
;
;       (2) Find heliocentric position of Mars on August 23, 2000 
;         IDL> JDCNV, 2000,08,23,0,jd
;         IDL> HELIO,JD,2,HRAD,HLONG,HLAT
;                  ===> hrad = 1.6407 AU hlong = 124.3197 hlat = 1.7853
;         For comparison, the JPL ephemeris gives
;                       hrad = 1.6407 AU hlong = 124.2985 hlat = 1.7845
;       (3) Find the heliocentric positions of Mars and Venus for every day in
;           November 2000
;        IDL> JDCNV, 2000, 11, 1, 0, jd    ;Julian date of November 1, 2000
;        IDL> helio, jd+indgen(30), [4,2], hrad,hlong,hlat   ;Mars=4, Venus=2 
;                   hrad, hlong, and hlat will be dimensioned [2,30]
;                   first column contains Mars data, second column Venus
; COMMON BLOCKS: 
;       None 
; ROUTINES USED: 
;       CIRRANGE - force angle between 0 and 2*!PI
; NOTES:
;       (1) The calling sequence for this procedure was changed in August 2000
;       (2) This program is based on the two-body model and thus neglects 
;           interactions between the planets.   This is why the worst results
;           are for Saturn.  Use the procedure JPLEPHINTERp for more accurate
;           positions using the JPL ephemeris.   Also see 
;           http://ssd.jpl.nasa.gov/cgi-bin/eph for a more accurate ephemeris 
;           generator online.     
;       (3) The coordinates are given for equinox 2000 and *not* the equinox
;           of the supplied date(s)
; MODIFICATION HISTORY: 
;       R. Sterner.  20 Aug, 1986.
;       Code cleaned up a bit      W. Landsman             December 1992
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Major rewrite, use modern orbital elements, vectorize, more accurate
;         solution to Kepler's equation          W. Landsman August 2000
;       Wasn't working for planet vectors        W. Landsman August 2000

; NAME:
;      HELIO_JD
; PURPOSE:
;      Convert geocentric (reduced) Julian date to heliocentric Julian date
; EXPLANATION:
;      This procedure correct for the extra light travel time between the Earth 
;      and the Sun.
;
; CALLING SEQUENCE:
;       jdhelio = HELIO_JD( date, ra, dec, /B1950, /TIME_DIFF)
;
; INPUTS
;       date - reduced Julian date (= JD - 2400000), scalar or vector, MUST
;               be double precision
;       ra,dec - scalars giving right ascension and declination in DEGREES
;               Equinox is J2000 unless the /B1950 keyword is set
;
; OUTPUTS:
;       jdhelio - heliocentric reduced Julian date.  If /TIME_DIFF is set, then
;                 HELIO_JD() instead returns the time difference in seconds
;                 between the geocentric and heliocentric Julian date.
;                 
; OPTIONAL INPUT KEYWORDS 
;       /B1950 - if set, then input coordinates are assumed to be in equinox 
;                B1950 coordinates.
;       /TIME_DIFF - if set, then HELIO_JD() returns the time difference
;                (heliocentric JD - geocentric JD ) in seconds 
;
; EXAMPLE:
;       What is the heliocentric Julian date of an observation of V402 Cygni
;       (J2000: RA = 20 9 7.8, Dec = 37 09 07) taken June 15, 1973 at 11:40 UT?
;
;       IDL> juldate, [1973,6,15,11,40], jd      ;Get geocentric Julian date
;       IDL> hjd = helio_jd( jd, ten(20,9,7.8)*15., ten(37,9,7) )  
;                                                            
;       ==> hjd = 41848.9881
;
; Wayne Warren (Raytheon ITSS) has compared the results of HELIO_JD with the
; FORTRAN subroutines in the STARLINK SLALIB library (see 
; http://star-www.rl.ac.uk/).    
;                                                  Time Diff (sec)
;      Date               RA(2000)   Dec(2000)  STARLINK      IDL
;
; 1999-10-29T00:00:00.0  21 08 25.  -67 22 00.  -59.0        -59.0
; 1999-10-29T00:00:00.0  02 56 33.4 +00 26 55.  474.1        474.1
; 1940-12-11T06:55:00.0  07 34 41.9 -00 30 42.  366.3        370.2
; 1992-02-29T03:15:56.2  12 56 27.4 +42 10 17.  350.8        350.9
; 2000-03-01T10:26:31.8  14 28 36.7 -20 42 11.  243.7        243.7
; 2100-02-26T09:18:24.2  08 26 51.7 +85 47 28.  104.0        108.8
; PROCEDURES CALLED:
;       bprecess, xyz, zparcheck
;
; REVISION HISTORY:
;       Algorithm from the book Astronomical Photometry by Henden, p. 114
;       Written,   W. Landsman       STX     June, 1989 
;       Make J2000 default equinox, add B1950, /TIME_DIFF keywords, compute
;       variation of the obliquity      W. Landsman   November 1999

; NAME:
;       HELIO_RV
;
; PURPOSE:
;       Return the heliocentric radial velocity of a spectroscopic binary
;
; EXPLANATION:
;       This function will return the heliocentric radial velocity of a 
;       spectroscopic binary star at a given heliocentric Julian date (HJD) 
;       given its orbit.
;
; CALLING SEQUENCE:
;
;  Result = HELIO_RV ( Reduced_HJD ,T ,Period ,Gamma [,e ,Omega ] )
;
; INPUT:
;
; Reduced_HJD   - Reduced_HJD of observation
; T             - Reduced_HJD of periastron passage (max. +ve velocity
;                 for circular orbits)
; Period        - the period in days
; Gamma         - systemic velocity
; K             - velocity semi-amplitude in the same units as Gamma.
; e             - eccentricity of the orbit, default is 0.
; Omega         - longitude of periastron in degrees. Must be specified for
;                 eccentric orbits.
;
; OUTPUT:
;
;  The predicted heliocentric radial velocity in the same units as Gamma
;  for the date(s) specified by Reduced_HJD.
;
; RESTRICTIONS:
;
;  To ensure consistency with the routines JULDATE and HELIO_JD, the
;  reduced HJD must be used throughtout.
;
; EXAMPLES:
;
; Example 1
;
;  What was the heliocentric radial velocity of the primary component of HU Tau
; at 1730 UT 25 Oct 1994?
; 
; IDL> juldate ,[94,10,25,17,30],JD                 ;Get Geocentric julian date
; IDL> hjd = helio_jd(jd,ten(04,38,16)*15.,ten(20,41,05)) ; Convert to HJD
; IDL> print, helio_rv(hjd,46487.5303D,2.0563056D,-6.0,59.3)
;      -63.661180
;
; NB. 1. The routines JULDATE and HELIO_JD return a reduced HJD (HJD - 2400000)
;        and so T and P must be specified in the same fashion.
;     2. The user should be careful to use double precision format to specify
;        T and P to sufficient precision where necessary. 
; 
; Example 2
;
;  Plot two cycles of an eccentric orbit, e=0.6, omega=45 for both
;  components of a binary star
;
; IDL> phi=findgen(100)/50.0             ; Generates 100 phase points
; IDL> plot, phi,helio_rv(phi,0,1,0,100,0.6,45),yrange=[-100,150]
; IDL> oplot, phi,helio_rv(phi,0,1,0,50,0.6,45+180)
; 
; This illustrates both the use of arrays to perform multiple calculations
; and generating radial velocities for a given phase by setting T=0 and P=1.
; Note also that omega has been changed by 180 degrees for the orbit of the
; second component  (the same 'trick' can be used for circular orbits).
;
; 
; MODIFICATION HISTORY:
;
;  Written by:  Pierre Maxted CUOBS, October, 1994
;
;  Circular orbits handled by setting e=0 and omega=0 to allow
;  binary orbits to be handled using omega and omega+180.
;                                                      Pierre Maxted,Feb 95
;  BUG - omega was altered by the routine - corrected Feb 95,Pierre Maxted
;  Iteration for E changed to that  given by Reidel , Feb 95,Pierre Maxted
;  /SINGLE keyword removed.                           May 96,Pierre Maxted
;
;       Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;       HERMITE
; PURPOSE:
;       To compute Hermite spline interpolation of a tabulated function.
; EXPLANATION:
;       Hermite interpolation computes the cubic polynomial that agrees with 
;       the tabulated function and its derivative at the two nearest 
;       tabulated points.   It may be preferable to Lagrangian interpolation 
;       (QUADTERP) when either (1) the first derivatives are known, or (2)
;       one desires continuity of the first derivative of the interpolated
;       values.    HERMITE() will numerically compute the necessary
;       derivatives, if they are not supplied.
;       
; CALLING SEQUENCE:
;       F = HERMITE( XX, FF, X, [ FDERIV = ])
;
; INPUT PARAMETERS:
;       XX - Vector giving tabulated X values of function to be interpolated
;               Must be either monotonic increasing or decreasing   
;       FF - Tabuluated values of function, same number of elements as X
;       X -  Scalar or vector giving the X values at which to interpolate
;
; OPTIONAL INPUT KEYWORD:
;       FDERIV - function derivative values computed at XX.    If not supplied,
;               then HERMITE() will compute the derivatives numerically.
;               The FDERIV keyword is useful either when (1) the derivative
;               values are (somehow) known to better accuracy than can be 
;               computed numerically, or (2) when HERMITE() is called repeatedly
;               with the same tabulated function, so that the derivatives
;               need be computed only once.
;
; OUTPUT PARAMETER:
;       F - Interpolated values of function, same number of points as X
;
; EXAMPLE:
;       Interpolate the function 1/x at x = 0.45 using tabulated values
;       with a spacing of 0.1
;
;       IDL> x = findgen(20)*0.1 + 0.1
;       IDL> y = 1/x
;       IDL> print,hermite(x,y,0.45)         
;               This gives 2.2188 compared to the true value 1/0.45 = 2.2222
;
;       IDL> yprime = -1/x^2      ;But in this case we know the first derivatives
;       IDL> print,hermite(x,y,0.45,fderiv = yprime)
;             == 2.2219            ;and so can get a more accurate interpolation
; NOTES:
;       The algorithm here is based on the FORTRAN code discussed by 
;       Hill, G. 1982, Publ Dom. Astrophys. Obs., 16, 67.   The original 
;       FORTRAN source is U.S. Airforce. Surveys in Geophysics No 272. 
;
;       HERMITE() will return an error if one tries to interpolate any values 
;       outside of the range of the input table XX
; PROCEDURES CALLED:
;       None
; REVISION HISTORY:
;       Written,    B. Dorman (GSFC) Oct 1993, revised April 1996
;       Added FDERIV keyword,  W. Landsman (HSTX)  April 1996
;       Test for out of range values  W. Landsman (HSTX) May 1996
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Use VALUE_LOCATE instead of TABINV   W. Landsman   February 2001

; NAME:
;      HEULER 
;
; PURPOSE:
;       Change the coordinate system of a FITS header or astrometry structure
; EXPLANATION:
;       Converts a FITS header or a astrometry structure containing WCS (world 
;       coordinate system) information between celestial, ecliptic, and 
;       Galactic coordinates
;
; CALLING SEQUENCE:
;       HEULER, hdr, [/GALACTIC, /CELESTIAL, /ECLIPTIC, ALT_IN = , ALT_OUT=]  
;                      or
;       HEULER, astr, /GALACTIC, /CELESTIAL, /ECLIPTIC
;
; INPUT/OUTPUT PARAMETERS:
;       hdr - FITS header (string array) containing WCS information
;                            or
;       Astr - Astrometry structure as extracted from a FITS header
;             by extast.pro (See EXTAST for more info).
;
;       Header or astrometry structure will be modified by the program to 
;       contain astrometry in the new coordinates system.
; REQUIRED INPUT KEYWORDS:
;       One of the following exclusive keywords is *required*
;       /GALACTIC - Convert the header to Galactic coordinates
;       /CELESTIAL - Convert the header to celestial (RA & Dec) coordinates
;       /ECLIPTIC - Convert the header to ecliptic coordinates
;
; OPTIONAL INPUT KEYWORDS:
;      The following two keywords apply if the FITS header contains multiple
;      WCS keywords. See Section 3.3 of Greisen & Calabretta (2002, A&A, 395, 
;      1061) for information about alternate astrometry keywords.
;
;      ALT_IN -  single character 'A' through 'Z' or ' ' specifying an 
;          alternate astrometry system present in the input FITS header.  The 
;          default isto use the primary astrometry or ALT = ' '.   If /ALT_IN 
;          is set, then this is equivalent to ALT_IN = 'A'.
;      ALT_OUT - single character specifying the alternate WCS keywords 
;          to write the *output* astrometry.    If not specified, then ALT_OUT
;          is set equal to ALT_IN.
; RESTRICTIONS:
;       Currently assumes that celestial and ecliptic coordinates are in
;       J2000.   Use HPRECESS if this is not the case.
;
;       ST Guide Star (DSS) image headers are first converted to a standard
;       tangent projection, prior to the coordinate conversion
; METHOD:
;       The algorithm used is described in Section 2.7 of Calabretta & Greisen
;       (2002, A&A, 395, 1077).    The CRVAL coordinates are transformed
;       directly using EULER.    The new LONPOLE and LATPOLE values are then
;       determined by transforming the pole of the new system to the old, and
;       converted to native coordinates using WCS_ROTATE. 
; PROCEDURES USED:
;       EULER, EXTAST, GSSS_STDAST, WCS_ROTATE
; REVISION HISTORY:
;       Written    W. Landsman                  June 2003

; NAME:
;	HEXTRACT
; PURPOSE:
;	Extract a subimage from an array and update astrometry in FITS header
; EXPLANATION:
;	Extract a subimage from an array and create a new FITS header with
;	updated astrometry for the subarray
; CALLING SEQUENCE:
;	HEXTRACT, Oldim, Oldhd, [ Newim, Newhd, x0, x1, y0, y1, /SILENT ]
;		or
;	HEXTRACT, Oldim, Oldhd, [x0, x1, y0, y1, /SILENT, ERRMSG =  ]	 
;
; INPUTS:
;	Oldim - the original image array
;	Oldhd - the original image header
;
; OPTIONAL INPUTS:
;	x0, x1, y0, y1 - respectively, first and last X pixel, and first and
;	last Y pixel to be extracted from the original image, integer scalars.
;	If omitted,  HEXTRACT will prompt for these parameters
;
; OPTIONAL OUTPUTS:
;	Newim - the new subarray extracted from the original image 
;	Newhd - header for newim containing updated astrometry info
;		If output parameters are not supplied or set equal to
;		-1, then the HEXTRACT will modify the input parameters 
;		OLDIM and OLDHD to contain the subarray and updated header.
;
; OPTIONAL INPUT KEYWORD:
;	/SILENT - If set and non-zero, then a message describing the extraction
;		is not printed at the terminal.   This message can also be 
;		suppressed by setting !QUIET.
; OPTIONAL KEYWORD OUTPUT:
;       ERRMSG - If this keyword is supplied, then any error mesasges will be
;               returned to the user in this parameter rather than depending on
;               on the MESSAGE routine in IDL.   If no errors are encountered
;               then a null string is returned.               
;
; PROCEDURE:
;	The FITS header parameters NAXIS1, NAXIS2, CRPIX1, and CRPIX2 are
;	updated for the extracted image.
;
; EXAMPLE:  
;	Read an image from a FITS file 'IMAGE', extract a 512 x 512 subimage 
;	with the same origin, and write to a new FITS file 'IMAGENEW'
;
;	IDL> im = READFITS( 'IMAGE', hdr )	;Read FITS files into IDL arrays
;	IDL> hextract, im, h, 0, 511, 0, 511	;Extract 512 x 512 subimage
;	IDL> writefits, 'IMAGENEW', im ,h	;Write subimage to a FITS file
;
; PROCEDURES CALLED
;	CHECK_FITS, STRN(), SXPAR(), SXADDPAR, SXADDHIST
; MODIFICATION HISTORY:
;	Written, Aug. 1986 W. Landsman, STX Corp.
;	Use astrometry structure,   W. Landsman      Jan, 1994
;	Minor fix if bad Y range supplied   W. Landsman    Feb, 1996
;	Added /SILENT keyword              W. Landsman     March, 1997
;	Converted to IDL V5.0   W. Landsman   September 1997
;       Added ERRMSG keyword    W. Landsman   May 2000

; NAME:
;     HGREP
;
; PURPOSE:
;       Find a substring in a FITS header (or any other string array)
;
; CALLING SEQUENCE:
;       HGREP, header, substring, [/KEEPCASE, /LINENUM ]
;
; INPUTS: 
;       header -  FITS header or other string array
;       substring - scalar string to find in header; if a numeric value is 
;                 supplied, it will be converted to type string
;
; OPTIONAL INPUT KEYWORDS:
;       /KEEPCASE: if set, then look for an exact match of the input substring 
;                 Default is to ignore case .
;       /LINENUM: if set, prints line number of header in which
;                substring appears 
;
; OUTPUTS:
;       None, results are printed to screen
;
; EXAMPLE: 
;       Find every place in a FITS header that the word 'aperture'
;       appears in lower case letters and print the element number 
;       of the header array:
;       
;       IDL> hgrep, header, 'aperture', /keepcase, /linenum
;
; HISTORY: 
;       Written, Wayne Landsman (Raytheon ITSS)      August 1998
;       Adapted from STIS version by Phil Plait/ ACC November 14, 1997
;       Remove trailing spaces if a non-string is supplied W. Landsman Jun 2002

;NAME:
;       HISTOGAUSS
;
; PURPOSE:
;       Histograms data and overlays it with a Gaussian. Draws the mean, sigma,
;       and number of points on the plot.
;
; CALLING SEQUENCE:
;       HISTOGAUSS, Sample, A, [XX, YY, GX, GY, /NOPLOT, /NOFIT, CHARSIZE = ]
;
; INPUT:
;       SAMPLE = Vector to be histogrammed
;
; OUTPUT ARGUMENTS:
;       A = coefficients of the Gaussian fit: Height, mean, sigma
;               A[0]= the height of the Gaussian
;               A[1]= the mean
;               A[2]= the standard deviation
;               A[3]= the half-width of the 95% conf. interval of the standard
;                     mean
;               A[4]= 1/(N-1)*total( (y-mean)/sigma)^2 ) = a measure of 
;                       normality
;
;       Below: superceded. The formula is not entirely reliable.
;       A[4]= measure of the normality of the distribution. =1.0, perfectly
;       normal. If no more than a few hundred points are input, there are
;       formulae for the 90 and 95% confidence intervals of this quantity:
;       M=ALOG10(N-1) ; N = number of points
;       T90=ABS(.6376-1.1535*M+.1266*M^2)  ; = 90% confidence interval
;       IF N LT 50 THEN T95=ABS(-1.9065-2.5465*M+.5652*M^2) $
;                  ELSE T95=ABS( 0.7824-1.1021*M+.1021*M^2)   ;95% conf.
;       (From Martinez, J. and Iglewicz, I., 1981, Biometrika, 68, 331-333.)
;
;       XX = the X coordinates of the histogram bins (CENTER)
;       YY = the Y coordinates of the histogram bins
;       GX = the X coordinates of the Gaussian fit
;       GY = the Y coordinates of the Gaussian fit
;
; OPTIONAL INPUT KEYWORDS:
;       /NOPLOT - If set, nothing is drawn
;       /FITIT   If set, a Gaussian is actually fitted to the distribution.
;               By default, a Gaussian with the same mean and sigma is drawn; 
;               the height is the only free parameter.
;       CHARSIZE Size of the characters in the annotation. Default = 0.82.
;
;       _EXTRA - Any value keywords to the PLOT command (e.g. XTITLE) may also
;               be passed to HISTOGAUSS
; SUBROUTINE CALLS:
;       BIWEIGHT_MEAN, which determines the mean and std. dev.
;       AUTOHIST, which draws the histogram
;       GAUSSFIT() (IDL Library) which does just that
;
; REVISION HISTORY:
;       Written, H. Freudenreich, STX, 12/89
;       Modified for IDL Version 2, 1/91, HF
;       More quantities returned in A, 2/94, HF
;       Added NOPLOT keyword and print if Gaussian, 3/94
;       Stopped printing confidence limits on normality 3/31/94 HF
;       Added CHARSIZE keyword, changed annotation format, 8/94 HF
;       Simplified calculation of Gaussian height, 5/95 HF
;       Convert to V5.0, use T_CVF instead of STUDENT_T, GAUSSFIT instead of
;           FITAGAUSS  W. Landsman April 2002 
;       Correct call to T_CVF for calculation of A[3], 95% confidence interval
;                P. Broos/W. Landsman   July 2003

; NAME:
;   HOR2EQ
;
; PURPOSE:
;    Converts local horizon coords (alt-az) of something to equatorial (ra-dec).
;
; EXPLANATION:
;     This is a nice code to calculate equatorial (ra,dec) coordinates from
;     horizon (alt,az) coords.    It is typically accurate to about 1 arcsecond
;     or better (I have checked the output against the publicly available XEPHEM
;     software). It preforms precession, nutation, abberation, and refraction
;     corrections.  The perhaps best thing about it is that it can take arrays
;     as inputs, in all variables and keywords EXCEPT Lat, lon, and Altitude
;    (the code assumes these aren't changing), and uses vector arithmetic in
;     every calculation except when calculating the precession matrices.
;
; CALLING SEQUENCE:
;
;    HOR2EQ, alt, az, jd, ra, dec, [ha, LAT= , LON= , /WS, OBSNAME= , $
;                       /B1950 , PRECESS_= 0, NUTATE_= 0, REFRACT_= 0, $
;                       ABERRATION_= 0, ALTITUDE= , /VERBOSE, _EXTRA= ]
;
;
; INPUT VARIABLES
;       alt  : altitude (in degrees) [scalar or vector]
;       az   : azimuth angle (in degrees, measured EAST from NORTH, but see
;              keyword WS below.) [scalar or vector]
;       JD   : Julian Date [scalar or vector]

;       Note: if RA and DEC are arrays, then alt and az will also be arrays.
;             If RA and DEC are arrays, JD may be a scalar OR an array of
;              the same dimensionality.
;
; OPTIONAL INPUT KEYWORDS:
;       lat   : north geodetic latitude of location in degrees
;       lon   : EAST longitude of location in degrees
;               (Specify west longitude with a negative sign.)
;       /WS   : Set this to get the azimuth measured westward from south
;               (not East of North).
;       obsname   : Set this to a valid observatory name to be used by the
;               astrolib OBSERVATORY procedure, which will return the latitude
;               and longitude to be used by this program.
;       /B1950  : Set this if your ra and dec are specified in B1950,
;               FK4 coordinates (instead of J2000, FK5)
;       precess_ : Set this to 1 to force precession [default], 0 for no
;                 precession.
;       nutate_  : Set this to 1 to force nutation [default], 0 for no nutation.
;       aberration_ : Set this to 1 to force aberration correction [default],
;                 0 for no correction.
;       refract_  : Set to 1 to force refraction correction [default], 0 for
;                   no correction.
;       altitude: The altitude of the observing location, in meters. [default=0].
;       /verbose: Set this for verbose output.  The default is verbose=0.
;   _extra: This is for setting TEMPERATURE or PRESSURE explicity, which are
;           used by CO_REFRACT to calculate the refraction effect of the
;           atmosphere. If you don't set these, the program will make an
;           intelligent guess as to what they are (taking into account your
;            altitude).  See CO_REFRACT for more details.
;
; OUTPUT VARIABLES
;       ra   : Right Ascension of object  (J2000) in degrees (FK5); scalar or
;              vector.
;       dec  : Declination of object (J2000) in degrees (FK5), scalar or vector.
;       ha   : hour angle (in degrees) (optional)
;
; DEPENDENCIES:
;       NUTATE, PRECESS, ADSTRING(), SUNPOS, OBSERVATORY (from the astrolib)
;       CO_NUTATE, CO_ABERRATION, CO_REFRACT, HADEC2ALTAZ
;
; BASIC STEPS
;   Precess Ra-Dec to current equinox.
;   Nutation Correction to Ra-Dec
;   Aberration correction to Ra-Dec
;   Calculate Local Mean Sidereal Time
;   Calculate Local Apparent Sidereal Time
;   Calculate Hour Angle
;   Do Spherical Trig to find Apparent Alt-Az
;   Apply refraction correction to find observed Alt.
;
;CORRECTIONS I DO NOT MAKE:
;   *  Deflection of Light by the sun due to GR. (typically milliarcseconds,
;        can be arseconds within one degree of the sun)
;   *  The Effect of Annual Parallax (typically < 1 arcsecond)
;   *  and more (see below)
;
; TO DO
;    * Better Refraction Correction.  Need to put in wavelength dependence,
;       and integrate through the atmosphere.
;    * Topocentric Parallax Correction (will take into account elevation of
;          the observatory)
;    * Proper Motion (but this will require crazy lookup tables or something).
;    * Difference between UTC and UT1 in determining LAST -- is this important?
;    * Effect of Annual Parallax (is this the same as topocentric Parallax?)
;    * Polar Motion
;    * Better connection to Julian Date Calculator.
;
; EXAMPLE:
;
;   You are at Kitt Peak National Observatory, looking at a star at azimuth
;   angle 264d 55m 06s and elevation 37d 54m 41s (in the visible).  Today is
;   Dec 25, 2041 and the local time is 10 PM precisely.  What is the ra and dec
;   (J2000) of the star you're looking at?   The temperature here is about 0
;   Celsius, and the pressure is 781 millibars.    The Julian date for this
;   time is 2466879.7083333
;
;  IDL> hor2eq, ten(37,54,41), ten(264,55,06), 2466879.7083333d, ra, dec, $
;           /verb, obs='kpno', pres=781.0, temp=273.0
;
; The program produces this output (because the VERBOSE keyword was set):
;
; Latitude = +31 57 48.0   Longitude = *** 36  0.0   ; longitude prints weirdly b/c of negative input to ADSTRING!!
; Julian Date =  2466879.708333
; Az, El =  17 39 40.4  +37 54 41.0   (Observer Coords)
; Az, El =  17 39 40.4  +37 53 39.6   (Apparent Coords)
; LMST = +03 53 54.1
; LAST = +03 53 53.6
; Hour Angle = +03 38 30.1  (hh:mm:ss)
; Ra, Dec:  00 15 23.5  +15 25  1.9   (Apparent Coords)
; Ra, Dec:  00 15 24.2  +15 25  0.1   (J2041.9841)
; Ra, Dec:  00 13 14.1  +15 11  0.3   (J2000)
;
; The star is therefore Algenib!  Compare the derived Ra, Dec with what XEPHEM
; got:
; Ra, Dec:      00 13 14.2  +15 11  1.0   (J2000)
;
; AUTHOR:
;   Chris O'Dell
;       Univ. of Wisconsin-Madison
;   Observational Cosmology Laboratory
;   Email: odell@cmb.physics.wisc.edu

; NAME:
;     HOST_TO_IEEE
; PURPOSE:
;     Translate an IDL variable from host to IEEE representation 
; EXPLANATION:
;     The variable is converted from the format used by the host architecture
;     into IEEE-754 representation (as used, for example, in FITS data ).
;
;     Duplicates most of the functionality of the SWAP_ENDIAN_INPLACE procedure
;     introduced in V5.6, with the addition of the IDLTYPE keyword.
; CALLING SEQUENCE:
;     HOST_TO_IEEE, data, [ IDLTYPE = ]
;
; INPUT-OUTPUT PARAMETERS:
;     data - any IDL variable, scalar or vector.   It will be modified by
;             HOST_TO_IEEE to convert from host to IEEE representation.  Byte 
;             and string variables are returned by HOST_TO_IEEE unchanged
;
; OPTIONAL KEYWORD INPUTS:
;     IDLTYPE - scalar integer (1-15) specifying the IDL datatype according
;               to the code given by the SIZE function.      This keyword
;               will usually be used when supplying a byte array that needs
;               to be interpreted as another data type (e.g. FLOAT).
;
; EXAMPLE:
;     Suppose FITARR is a 2880 element byte array to be converted to a FITS
;     record and interpreted a FLOAT data.
;
;       IDL> host_to_ieee, FITARR, IDLTYPE = 4
;
; METHOD:
;     The BYTEORDER procedure is called with the appropriate keywords
;
; MODIFICATION HISTORY:
;      Adapted from CONV_UNIX_VAX, W. Landsman   Hughes/STX    January, 1992
;      Version for IDL V5.0  August 1997
;      Converted to IDL V5.0   W. Landsman   September 1997
;      Added new integer datatypes  C. Markwardt/W. Landsman  July 2000
;      Use /SWAP_IF_LITTLE_ENDIAN keyword for 64bit types W. Landsman Feb 2003

; NAME:
;       HPRECESS
; PURPOSE:
;       Precess the astrometry in a FITS header to a new equinox
;
; CALLING SEQUENCE:
;       HPRECESS, HDR, [ yearf ]      
;
; INPUT-OUTPUT:
;       HDR - FITS Header, must contain the CRVAL astrometry keywords,
;               and either an EPOCH or EQUINOX keyword.
;               HDR will be modified to contain the precessed astrometry
;
; OPTIONAL INPUT:
;       YEARF - Scalar, giving the year of the new (Final) equinox.
;               If not supplied, user will be prompted for this value.
;
; METHOD:
;       The CRVAL and CD (or CROTA) keywords are extracted from the header 
;       and precessed to the new equinox.  The EPOCH or EQUINOX keyword in 
;       the header is  updated.  A HISTORY record is added
;
; RESTRICTIONS:
;       The FK5 reference frame is assumed for both equinoxes.
;
; PROCEDURES USED:
;       EXTAST, GET_EQUINOX(), SXADDPAR, SXADDHIST, PRECESS, PRECESS_CD
;       PUTAST, ZPARCHECK
; REVISION HISTORY:                                               
;       Written  W. Landsman        STX              July, 1988
;       CD matrix precessed -                        February, 1989
;       Update EQUINOX keyword when CROTA2 present   November, 1992
;       Recognize a GSSS header                      June, 1994
;       Additional Noparams value recognize for storing CDs.  RSH, 6 Apr 95
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Understand reversed X,Y (X-Dec, Y-RA) axes,   W. Landsman  October 1998

; NAME:
;       HPRINT
; PURPOSE:
;       Print a FITS header (or other string array) one line at a time
; EXPLANATION:
;       The string array is  printed 1 line at a time.
;       Needed because IDL will add an extra space to the 80 character
;       FITS lines on TTY terminals, causing a space to appear between lines.
;
; CALLING SEQUENCE:
;       HPRINT, h, [ firstline ]
;
; INPUTS:
;       H - FITS header (or any other string array).
;
; OPTIONAL INPUT:
;       FIRSTLINE - scalar integer specifying the first line to begin 
;               displaying.   The default is FIRSTLINE = 1, i.e. display 
;               all the lines.     If Firstline is negative, then the first
;               line to be printed is counted backward from the last line.
;
; NOTES:
;       HPRINT has the following differences from the intrinsic PRINT procedure
;
;       (1) Arrays are printed one line at a time to avoid a space between 80
;               character lines
;       (2) Lines are trimmed with STRTRIM before being printed to speed up 
;               display
;       (3) The /more option is used for output. 
;
; EXAMPLE:
;       Read the header from a FITS file named 'test.fits' and display it at the
;       terminal beginning with line 50
;
;       IDL> h = headfits( 'test.fits')         ;Read FITS header
;       IDL> hprint, h, 50                      ;Display starting at line 50
;
;       To print the last 25 lines of the header
;
;       IDL> hprint, h, -25
;
; REVISION HISTORY:
;       Written W. Landsman                     July, 1990
;       Added test for user quit                July, 1991
;       Added optional FIRSTLINE parameter      November, 1992
;       Modified for when STDOUT is not a TTY W. Landsman  September 1995
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Fixed printing in IDLDE, C. Gehman      August, 1998

; NAME:
;    HREBIN
; PURPOSE:
;    Expand or contract a FITS image using (F)REBIN and update the header 
; EXPLANATION:
;    If the output size is an exact multiple of the input size then REBIN is 
;    used, else FREBIN is used.     User can either overwrite the input array,
;    or write to new variables.
;
; CALLING SEQUENCE:
;    HREBIN, oldhd        ;Special calling sequence to just update header
;    HREBIN, oldim, oldhd, [ newim, newhd, newx, newy, OUTSIZE = ,/SAMPLE, 
;                            ERRMSG =  ]
;
; INPUTS:
;    OLDIM - the original image array
;    OLDHD - the original image FITS header, string array
;
; OPTIONAL INPUTS:
;    NEWX - size of the new image in the X direction, integer scalar
;    NEWY - size of the new image in the Y direction, integer scalar
;            HREBIN will prompt for NEWX and NEWY if not supplied
;
; OPTIONAL OUTPUTS:
;    NEWIM - the image after expansion or contraction with REBIN
;    NEWHD - header for newim containing updated astrometry info
;            If output parameters are not supplied, the program will modify
;            the input parameters OLDIM and OLDHD to contain the new array and 
;            updated header.
;
; OPTIONAL INPUT KEYWORDS:
;    /SAMPLE - Expansion or contraction is done using REBIN which uses 
;              bilinear interpolation when magnifying and boxaveraging when 
;              minifying.   If the SAMPLE keyword is supplied and non-zero, 
;              then nearest neighbor sampling is used in both cases.   Keyword
;              has no effect when output size is not a multiple of input size.
;
;    OUTSIZE - Two element integer vector which can be used instead of the
;             NEWX and NEWY parameters to specify the output image dimensions
;
; OPTIONAL KEYWORD OUTPUT:
;       ERRMSG - If this keyword is supplied, then any error mesasges will be
;               returned to the user in this parameter rather than depending on
;               on the MESSAGE routine in IDL.   If no errors are encountered
;               then a null string is returned.               
; PROCEDURE:
;     The parameters BSCALE, NAXIS1, NAXIS2, CRPIX1, and CRPIX2 and the CD 
;     (or CDELT) parameters are updated for the new FITS header.
;
; EXAMPLE:
;     Compress a 2048 x 2048 image array IM, with FITS header HDR, to a 
;     724 x 724 array.   Overwrite the input variables with the compressed 
;     image and header.
;
;     IDL> hrebin, im, hdr, OUT = [724, 724]
;
; PROCEDURES USED:
;     CHECK_FITS, EXTAST, FREBIN, GSSS_STDAST, STRN(), SXPAR(), SXADDHIST, 
;     SXADDPAR, ZPARCHECK
;
; MODIFICATION HISTORY:
;     Written, December 1990  W. Landsman, ST System Corp.
;     Update CD1_1 keywords   W. Landsman   November 1992
;     Check for a GSSS header   W. Landsman  June 1994
;     Update BSCALE even if no astrometry present   W. Landsman  May 1997
;     Converted to IDL V5.0   W. Landsman   September 1997
;     Use FREBIN to accept sizes that are not a integer multiple of the original
;         size    W. Landsman     August 1998
;     Correct for "edge" effects when expanding with REBIN W. Landsman Apr. 1999
;     Fixed initialization of header only call broken in Apr 98 change May. 1999
;     Remove reference to obsolete !ERR  W. Landsman   February 2000
;     Use double precision formatting for CD matrix W. Landsman April 2000
;     Recognize PC00n00m astrometry format   W. Landsman   December 2001
;     Correct astrometry for integral contraction W. Landsman  April 2002

; NAME:
;       HREVERSE
; PURPOSE:
;       Reverse an image about either dimension and update FITS astrometry
; EXPLANATION:
;       Reverse an image about either the X or Y axis, and create a new 
;       header with updated astrometry for the reversed image.
;
; CALLING SEQUENCE:
;       HREVERSE,oldim,oldhd, [ subs, /SILENT ]   ;Update input image and header
;               or
;       HREVERSE, oldim, oldhd, newim, newhd, [ subs, /SILENT ]   
;
; INPUTS:
;       OLDIM - the original image array
;       OLDHD - the original image header
;
; OPTIONAL INPUTS:
;       SUBS - Subs equals 1 to reverse the order of the X dimension,
;               2 to reverse Y order.  If omitted, then HREVERSE will
;               prompt for this scalar parameter.
;
; OPTIONAL OUTPUTS:
;       NEWIM - the rotated image, with the same dimensions as Oldim 
;       NEWHD - header for newim containing updated astrometry info
;               If output parameters are not supplied, the program
;               will modify the input parameters OLDIM and OLDHD
;               to contain the rotated image and updated header.
;
; OPTIONAL KEYWORD INPUT:
;       SILENT - if set and non-zero, then informative messages are suppressed.
;
; OPTIONAL KEYWORD OUTPUT:
;       ERRMSG - If this keyword is supplied, then any error mesasges will be
;               returned to the user in this parameter rather than depending on
;               on the MESSAGE routine in IDL.   If no errors are encountered
;               then a null string is returned.               
;
; SIDE EFFECTS:
;       A right-handed coordinate system is converted into a left-
;       handed one, and vice-versa.
;
; PROCEDURE:
;       The User's Library procedure REVERSE is used to reverse the image.
;       The CD and CRPIX header parameters are updated for the new header.
;       For AIPS type astrometry, the CDELT parameters are also updated.
;       A history record is also added to the header
;
; PROCEDURES USED:
;       CHECK_FITS, EXTAST, REVERSE(), STRN(), SXADDPAR 
; MODIFICATION HISTORY:
;       Written, Aug. 1986 W. Landsman, STI Corp.
;       Error modifying CROTA angles corrected     9-23-88
;       Added format keyword, J. Isensee, July, 1990
;       Work for ST Guide Star images, W. Landsman   HSTX, May 1995
;       Compute CRPIX1 correctly for X reversal   W. Landsman HSTX August 1995
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Added ERRMSG, Use double precision formatting, W. Landsman April 2000
;       Recognize PC00n00m astrometry matrix   W. Landsman   December 2001

; NAME:
;       HROT
; PURPOSE:
;       Rotate an image and create new FITS header with updated astrometry.
; EXPLANATION: 
;       Cubic, bilinear or nearest neighbor interpolation can be used.
;
; CALLING SEQUENCE:
;       HROT, oldim, oldhd, [ newim, newhd, angle, xc, yc, int, 
;                       MISSING =, INTERP =, CUBIC = , /PIVOT]
; INPUTS:
;       OLDIM - the original image array                             
;       OLDHD - the original FITS image header, string array
;
; OPTIONAL INPUTS:
;       NEWIM - If NEWIM is set to -1, then the old image and header will
;               be updated
;       ANGLE - Rotation angle, degrees clockwise
;       XC    - X Center of rotation (-1 for center of image)
;       YC    - Y Center of rotation (-1 for center of image)
;       INT   - 0 for nearest neighbor, 1 for bilinear interpolation
;               2 for cubic interpolation.  
;
; OPTIONAL OUTPUTS:
;       NEWIM - the rotated image, with the same dimensions as Oldim 
;       NEWHD - header for newim containing updated astrometry info
;               If output parameters are not supplied, the program
;               will modify the input parameters OLDIM and OLDHD
;               to contain the rotated image and updated header.
;
; OPTIONAL INPUT KEYWORD:
;       MISSING - Set this keyword to a scalar value which will be assigned
;               to pixels in the output image which do not correspond to 
;               existing imput images (e.g if one rotates off-center). 
;               If not supplied then linear extrapolation is used.
;
;       INTERP - scalar set to either 0 (nearest neighbor interpolation),
;               1 (bilinear interpolation), or 2 (cubic interpolation).    
;               The interpolation type can be specified by either the INTERP 
;               keyword or the int parameter
;             
;       CUBIC - If set and non-zero then cubic interpolation is used (see ROT),
;               which is equivalent to setting INT = 2.   In IDL V5.0 and later,
;                this keyword can also be set to a value between -1 and 0.
;
;       /PIVOT - Setting this keyword causes the image to pivot around the point
;		XC, YC, so that this point maps into the same point in the
;		output image.  If this keyword is set to 0 or omitted, then the
;		point XC, YC in the input image is mapped into the center of
;		the output image.
;
; OPTIONAL OUTPUT KEYWORD:
;       ERRMSG - If this keyword is supplied, then any error mesasges will be
;               returned to the user in this parameter rather than depending on
;               on the MESSAGE routine in IDL.   If no errors are encountered
;               then a null string is returned.               
; EXAMPLE:
;       Rotate an image non-interactively 30 degrees clockwise.  Use
;       bilinear interpolation, and set missing values to 0.
;
;       IDL>  HROT, im_old, h_old, im_new, h_new, 30, -1, -1, 1, MIS = 0
;
;       As above but update the input image and header and pivot about (100,120)
;
;       IDL>  HROT, im_old, h_old, -1, -1, 30, 100, 120, 1, MIS = 0, /PIVOT
; RESTRICTIONS:
;       Unlike the ROT procedure, HROT cannot be used to magnify or
;       or demagnify an image. Use HCONGRID or HREBIN instead.
;
; PROCEDURE:
;       The image array is rotated using the ROT procedure.
;       The CD (or CROTA) and CRPIX parameters, if present in the FITS header,
;       are updated for the new rotation.
;       History records are also added to the header
;
; PROCEDURES USED:
;       CHECK_FITS, EXTAST, GETOPT(), GETROT, ROT(), STRN(), SXADDPAR
;
; MODIFICATION HISTORY:
;       Written, Aug. 1986 W. Landsman, ST Systems Corp.
;       Added MISSING keyword, W. Landsman March, 1991
;       Added cubic interpolation, use astrometry structure   Feb 1994
;       Removed call to SINCE_VERSION()  W. Landsman  March 1996
;       Assume at least V3.5, add CUBIC parameter       W. Landsman  March 1997
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Fix for CROTA2 defined and CDELT1 NE CDELT2, W. Landsman  November 1998
;       Fix documentation  to specify clockwise rotation W. Landsman Dec. 1999
;       Added /PIVOT keyword    W. Landsman  January 2000
;       Added ERRMSG, Use double precision formatting, W. Landsman April 2000
;       Consistent conversion between CROTA and CD matrix W. Landsman Oct 2000
;       Work for both CD001001 and CDELT defined  W. Landsman   March 2001
;       Recognize PC matrix astrometry  W. Landsman December 2001
;       Update astrometry correctly when /PIVOT applied W. Landsman March 2002
;       Update CROTA2 astrometry correctly, approximate GSSS W.L. June 2003
;       Work with CD1_1, PC1_1 and CROTA keywords W. L. July 2003 

; NAME:
;     HROTATE
; PURPOSE:
;     Apply the IDL ROTATE function and update astrometry in a FITS header
; EXPLANATION:
;     Apply the intrinsic IDL ROTATE function to an image and update 
;     astrometry in the associated FITS header.
;
; CALLING SEQUENCE:
;     HROTATE, oldim, oldhd, newim, newhd, direction
;               or
;     HROTATE, oldim, oldhd, direction 
;                       
; INPUTS:
;     OLDIM - the original image array                             
;     OLDHD - the original FITS image header, string array
;     DIRECTION - Scalar integer (0-7) specifying rotation direction, 
;               exactly as specified by the IDL ROTATE function.
;
;        Direction  Transpose?  Rot. CCW  X1  Y1 
;       ---------------------------------------- 
;       0          No          None     X0  Y0    (no change)
;       1          No          90      -Y0  X0 
;       2          No          180     -X0 -Y0 
;       3          No          270      Y0 -X0 
;       4          Yes         None     Y0  X0 
;       5          Yes         90      -X0  Y0                   
;       6          Yes         180     -Y0 -X0 
;       7          Yes         270      X0 -Y0 
;
; OPTIONAL OUTPUTS:
;     NEWIM - the rotated image, with the same dimensions as Oldim 
;     NEWHD - header for newim containing updated astrometry info
;               If output parameters are not supplied, the program
;               will modify the input parameters OLDIM and OLDHD
;               to contain the rotated image and updated header.
;
; OPTIONAL KEYWORD OUTPUT:
;     ERRMSG - If this keyword is supplied, then any error mesasges will be
;               returned to the user in this parameter rather than depending on
;               on the MESSAGE routine in IDL.   If no errors are encountered
;               then a null string is returned.               
; EXAMPLE:
;     Rotate an image exactly 90 degrees counterclockwise and update the
;     FITS image array and header. 
;
;       IDL>  HROT, im, h, im_new, h_new, 1
;
; PROCEDURE:
;      The image array is rotated using the ROTATE function.
;      The CD (or CROTA) and CRPIX parameters, if present in the FITS header,
;      are updated for the new rotation.
;      History records are also added to the header
;
; PROCEDURES USED:
;     CHECK_FITS(), SXADDPAR, EXTAST
;
; MODIFICATION HISTORY:
;     Written,  Mar 1997    W. Landsman,  Hughes STX
;     Work for non-square images   W. Landsman   June 1998 Raytheon STX
;     Converted to IDL V5.0  W. Landsman     June 1998
;     Fix for different plate scales, and CROTA2 defined, November 1998  
;     Added ERRMSG, Use double precision formatting, W. Landsman April 2000
;     Consistent conversion between CROTA and CD matrix W. Landsman Oct 2000
;     Correct update when CROTA keyword present W. Landsman  June 2003
;     Update CDELT for AIPS-style astrometry headers M. Perrin/Landsman Jul 2003

; NAME: 
;  IDL_VALIDNAME()
;
; PURPOSE: 
;   Modify a string if necessary, so that it can used as a IDL variable name.
;   
; EXPLANATION:
;   Duplicates the intrinsic V6.0 function IDL_VALIDNAME() with the 
;       CONVERT_ALL keyword, for  pre-V6.0 compatibility
;   IDL_VALIDNAME performs the following:
;   (1) All non-alphanumeric characters (except '_' and '$') are converted
;       to underscores
;   (2) If the first character is not alphabetic or a '_' or a '!' then an 
;       underscore is preprended to the string
;   (3) If the string is an IDL reserved word (e.g. 'endif') then an 
;       underscore is preprended to the string.
;
; CALLING SEQUENCE: 
;    result = IDL_VALIDNAME( str, /Convert_all ) 
;
; INPUT: 
;      str - Scalar string to be converted to a valid variable name. 
;
; OUTPUT:
;      result - the input string modified, if necessary, according to the
;           3 rules above, so that it can be used as a valid IDL variable.
; OPTIONAL INPUT KEYWORDS:
;    /CONVERT_ALL -- Does nothing, but ensures compatibility with V6.0
;          intrinsic call IDL_VALIDNAME(/CONVERT_ALL)
; PROCEDURES USED:
;     None.
;
; EXAMPLES:
;      (1) print,idl_validname('switch',/convert_all)
;          _switch           ;IDL reserved keyword
;
;      (2) print,idl_validname('2mass',/convert_all)
;          _2mass            ;1st character must be alphabetic
;
;      (3) print,idl_validname('date$',/convert_all)
;          date$             ;no change, input string already valid
; MODIFICATION HISTORY: 
;         Written by W. Landsman  SSAI  October 2003
;

; NAME:
;     IEEE_TO_HOST
; PURPOSE:
;     Translate an IDL variable from IEEE-754 to host representation 
; EXPLANATION:
;     The variable is translated from IEEE-754 (as used, for
;     example, in FITS data ), into the host machine architecture.
;
;     Duplicates most of the functionality of the SWAP_ENDIAN_INPLACE procedure
;     introduced in V5.6, with the addition of the IDLTYPE keyword.
; CALLING SEQUENCE:
;     IEEE_TO_HOST, data, [ IDLTYPE = , ]
;
; INPUT-OUTPUT PARAMETERS:
;     data - any IDL variable, scalar or vector.   It will be modified by
;             IEEE_TO_HOST to convert from IEEE to host representation.  Byte 
;             and string variables are returned by IEEE_TO_HOST unchanged
;
; OPTIONAL KEYWORD INPUTS:
;     IDLTYPE - scalar integer (1-15) specifying the IDL datatype according
;               to the code given by the SIZE function.     This keyword
;               is usually when DATA is a byte array to be interpreted as
;               another datatype (e.g. FLOAT).
;
; EXAMPLE:
;       A 2880 byte array (named FITARR) from a FITS record is to be 
;       interpreted as floating and converted to the host representaton:
;
;       IDL> IEEE_TO_HOST, fitarr, IDLTYPE = 4     
;
; METHOD:
;       The BYTEORDER procedure is called with the appropriate keyword
;
; MODIFICATION HISTORY:
;      Written, W. Landsman   Hughes/STX   May, 1992
;      Converted to IDL V5.0   W. Landsman   September 1997
;      Under VMS check for IEEE -0.0 values   January 1998
;      VMS now handle -0.0 values under IDL V5.1    July 1998
;      Added new integer datatypes  C. Markwardt/W. Landsman  July 2000
;      Post-V5.1 version, no VMS negative zero check  W. Landsman July 2001
;      Use size(/type)  W. Landsman December 2002
;      Use /SWAP_IF_LITTLE_ENDIAN keyword for 64bit types W. Landsman Feb 2003

; 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.
;
;       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.
;
; 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
;       Converted to IDL V5.0   W. Landsman   September 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
;       

; NAME:
;     IMDBASE
; PURPOSE:
;     Find the sources in an IDL database that are located on a given image.
;
; CALLING SEQUENCE:
;    imdbase, hdr, catalogue, [list, XPOS= ,YPOS=, XRANGE= ,YRANGE= , 
;                       SUBLIST = ]  
;
; INPUTS:
;    hdr - FITS image header containing astrometry, and the NAXIS1,
;               NAXIS2 keywords giving the image size
;    catalogue - string giving name of catalogue in database
;              Database must contain the (preferably indexed)
;              fields RA (in hours) and DEC.   Type DBHELP for a 
;              list of the names of available catalogues.
;
; OPTIONAL OUTPUT PARAMETER:
;    LIST - A long vector containing the entry numbers of sources found
;           within the image.   This vector can then be used with other
;           database procedures, e.g. to print specified fields (DBPRINT)
;           or subselect with further criteria (DBFIND)
;
; OPTIONAL OUTPUT KEYWORD PARAMETER:
;     XPOS - REAL*4 vector giving X positions of catalogue sources found 
;            within the image
;     YPOS - REAL*4 vector giving Y positions of catalogue sources found 
;            within the image
;
; OPTIONAL INPUT KEYWORD PARAMETERS
;     XRANGE - 2 element vector giving the X range of the image to consider.
;              The default is to search for catalogue sources within the entire
;             image
;     YRANGE - 2 element vector giving the Y range of the image to consider.
;     SUBLIST - vector giving entries in the database to consider in the
;               search.  If not supplied, or set equal to -1, then all entries
;               are considered.
;
; NOTES:
;     If an output list vector is not supplied, then the found objects are
;     diplayed at the terminal.
;
; EXAMPLE:
;      Find all existing IUE SWP observations within the field of the STSDAS
;      disk file FUV0435FC.  Subselect those taken with the SWP camera
;
;      SXHREAD,'fuv0435fc',H             ;Read header from disk
;      IMDBASE,H,'IUE',list              ;Find IUE obs. within image 
;      LIST2 = DBFIND('CAM_NO=3',LIST)   ;Subselect on SWP images
;
; SIDE EFFECTS:
;      The IDL database is left open upon exiting IMDBASE.
; NOTES:
;      IMDBASE checks the description of the RA item in the database for the
;      string '2000'.    If found, the database RA and Dec are assumed to be 
;      in equinox J2000.   Otherwise they are assumed to be in equinox B1950 
;
; SYSTEM VARIABLES:                                                
;      The non-standard system variable !TEXTOUT is required for use with the
;      database procedures.   
;
; PROCEDURES USED:
;      AD2XY, DBEXT, DB_ITEM, DB_ITEM_INFO(), DBOPEN, DBFIND(), EXTAST, 
;      GET_EQUINOX(), GSSSADXY, GSSSXYAD, HPRECESS, SXPAR(), XY2AD 
; REVISION HISTORY:
;      Written W. Landsman            September, 1988
;      Added SUBLIST keyword          September, 1991
;      Updated to use ASTROMETRY structures    J.D. Offenberg, HSTX, Jan 1993
;      Conversion for precession fixed.   R.Hill, HSTX, 22-Apr-93
;      Check RA description for equinox   W. Landsman  Aug 96
;      Converted to IDL V5.0   W. Landsman   September 1997
;      Call HPRECESS if header equinox does not match DB  W. Landsman Oct. 1998

; NAME:
;       IMF
; PURPOSE:
;       Compute an N-component power-law logarithmic initial mass function 
; EXPLANTION:
;       The function is normalized so that the total mass distribution 
;       equals one solar mass.
;
; CALLING SEQUENCE:
;       psi = IMF( mass, expon,  mass_range )
;
; INPUTS:
;       mass - mass in units of solar masses (scalar or vector)
;               Converted to floating point if necessary
;       expon - power law exponent, usually negative, scalar or vector
;               The number of values in expon equals the number of different
;               power-law components in the IMF
;               A Saltpeter IMF has a scalar value of expon = -1.35
;       mass_range - vector containing the mass upper and lower limits of the 
;               IMF and masses where the IMF exponent changes.   The number 
;               of values in mass_range should be one more than in expon.   
;               The values in mass_range should be monotonically increasing.
;
; OUTPUTS
;       psi - mass function, number of stars per unit logarithimic mass interval
;               evaluated for supplied masses
;
; NOTES:
;       The mass spectrum f(m) giving the number of stars per unit mass 
;       interval is related to psi(m) by  m*f(m) = psi(m).    The normalization
;       condition is that the integral of psi(m) between the upper and lower
;       mass limit is unity.
;
; EXAMPLE:
;       (1) Print the number of stars per unit mass interval at 3 Msun 
;               for a Salpeter (expon = -1.35) IMF, with a mass range from 
;               0.1 MSun to 110 Msun.
;
;               IDL> print, imf(3, -1.35, [0.1, 110] ) / 3
;
;       (2) Lequex et al. (1981, A & A 103, 305) describes an IMF with an
;               exponent of -0.6 between 0.007 Msun and 1.8 Msun, and an
;               exponent of -1.7 between 1.8 Msun and 110 Msun.    Plot
;               the mass spectrum f(m)
;
;               IDL> m = [0.01,0.1,indgen(110) + 1 ]  ;Make a mass vector
;               IDL> expon = [-0.6, -1.7]       ;Exponent Vector
;               IDL> mass_range = [ 0.007, 1.8, 110]    ;Mass range
;               IDL> plot_oo, m, imf(m, expon, mass_range ) / m
;
; METHOD
;       IMF first calculates the constants to multiply the power-law 
;       components such that the IMF is continuous at the intermediate masses, 
;       and that the total mass integral is one solar mass.  The IMF is then 
;       calculated for the supplied masses.   Also see Scalo (1986, Fund. of
;       Cosmic Physics, 11, 1)
;
; PROCEDURES CALLED:
;       None
; REVISION HISTORY:
;       Written    W. Landsman              August, 1989  
;       Set masses LE mass_u rather than LT mass_u  August, 1992
;       Major rewrite to accept arbitary power-law components   April 1993
;       Convert EXPON to float if necessary  W. Landsman     March 1996
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Remove call to DATATYPE, V5.3 version  W. Landsman  August 2000

; NAME:
;	IMGREAD
; PURPOSE:
;	Read a WFPC or FOC file into IDL image and data arrays
; EXPLANATION:
;	Open an SDAS/GEIS file and read the image into a data array of 
;	appropriate type and read the header into a string array.  This 
;	procedure was designed to be more versatile than the STRD procedure 
;	and to be specifically useful to WF/PC and FOC data, as well as all 
;	other GEIS images.  IMGread supports multiple GROUPS (i.e. in STSDAS 
;	format).
;
; CALLING SEQEUNCE:
;	IMGread,image,hdr,[filename],[groupno],[/NoAssoc,/silent,Astrmfix=]
;
; OPTIONAL INPUT:
;	FILENAME  The filename of the HEADER file (must have extention .xxh 
;		where xx may be any two alphanumerics but it usually hh.)  If 
;		there is no extention supplied, .hhh and .hhd are assumed.  If
;		this parameter is not supplied, a filename is prompted for, 
;		with the option of pressing [ENTER] to call the GETFILE() 
;		function provides a menu listing of available *.*h files.  If 
;		widgets are available, the function PICKFILE() is called 
;		instead.
;	GROUP - This parameter specifies the GROUP number image to read from a
;               file which contains multiple groups.  For example, for WF/PC
;               images where all four chips are contained in one file, one
;               specify a GROUP of 0 to read PC5, 1 for PC6, 3 for PC8,
;               0 to read WF1 for a WF image, etc.  therefore, the range of
;               GROUP is 0 to GCOUNT-1 (where GCOUNT is a header keyword.)
; OUTPUT:
;	IMAGE - The returned array which contains the pixel information.  
;		IMAGE will be of whatever datatype the header indicates (or 
;		seems to... i.e. if BITPIX=32 but there is no DATATYPE keyword,
;               IMGread assumes REAL*4 if BZERO is 0 or non-existant and
;               INTEGER*4 if BZERO is not 0.  This is usually right, but not
;               always.)
;	H - The returned string array containing the image header 
;		information as if SXHREAD were used.
;
; OPTIONAL KEYWORDS:
;	NoAssoc -  This keyword controls how IDL reads the file.    If NoAssoc
;		is set and non-zero then the READU function is used instead
;		of the ASSOC function.    The user can select the type of
;		read that gives the best performance on his particular setup.
;		In general, the ASSOC function seems to be faster, but is more
;		demanding on virtual memory.
;	SILENT - If this keyword is set and non-zero, then the "Loading..." 
;		message will not be ;               printed.
;	ASTRMFIX  Controls whether the procedure AstrmFix is run.  AstrmFix
;               calculates an astrometric solution from the HST Spacecraft
;               angle in the header.  CRPIXn and CRVALn are left alone.  Only
;               CDn_n are changed.  The Default is currently set to 1 since
;               correct astrometry still does not come with the headers.  Once
;               the astrometric fix is implemented in PODPS, the default should
;               be switched to 0.
;
; SIDE EFFECTS:
;	For an image with group parameters, all parameters are extracted from
;	the .HHD file and values are inserted into the returned header variable.
;	To get the original header, use SXHREAD for these type of image files.
;	The EXTGRP procedure takes care of this process.
;
; EXAMPLE:
;	Read the WF/PC file named 'w0hd0203t.c1h' into IDL variables, IM and H.
;
;	IDL> IMGREAD, im,h,'w0hd0203t.c1h'
;
; OTHER PROCEDURES CALLED:
;	SXPAR, SXADDPAR, SXOPEN, SXHREAD, FDECOMP, WFPCREAD, PICKFILE, EXTGRP
;
; HISTORY:
;	09-JUL-92 Header finally added to this procedure which has been in use
;	 for two or more years.  All versions and header by Eric W. Deutsch
;	01-APR-93 Made a few minor adjustments.  EWD.  (No, really)
;	July 93 Added /NoAssoc, MAKE_ARRAY, removed GET_FILE W. Landsman (HSTX)
;	Converted to IDL V5.0   W. Landsman   September 1997
;       Remove use of !ERR  W. Landsman   January 2001

; NAME:
;      IMLIST        
; PURPOSE:
;      Display pixel values on an image surrounding a specified X,Y center.
; EXPLANATION:
;      IMLIST is similar to TVLIST but the center pixel is supplied directly by
;      the user, rather than being read off of the image display
;
; CALLING SEQUENCE:
;      IMLIST, Image, Xc, Yc, [ TEXTOUT = , DX = , DY = ,WIDTH = ,DESCRIP = ]
;
; INPUTS:
;      Image - Two-dimensional array containing the image 
;      Xc  -   X pixel value at which to center the display, integer scalar 
;      Yc -    Y pixel value at which to center the display, integer scalar 
;
; OPTIONAL INPUTS KEYWORDS:
;      TEXTOUT - Scalar number (1-7) or string which determines output device.
;               (see TEXTOPEN) The following dev/file is opened for output.
;
;               textout=1       TERMINAL using /more option
;               textout=2       TERMINAL without /more option
;               textout=3       .prt
;               textout=4       laser.tmp
;               textout=5       user must open file
;               textout=7       same as 3 but text is appended to .prt
;                               if file already exists
;               textout = filename (default extension of .prt)
;
;       DX     -Integer scalar giving the number of pixels inthe  X direction 
;               to be displayed.  If omitted then DX = 18 for byte images, and 
;               DX = 14 for integer images.  IMLIST will display REAL data 
;               with more significant figures if more room is available to 
;               print.  
;
;       DY    - Same as DX, but in Y direction.  If omitted, then DY = DX 
;       WIDTH - Integer scalar giving the character width of the output device.
;               Default is 80 characters.
;       DESCRIP =  Scalar string which will be written as a description over
;               the output pixel values.   If DESCRIP is not supplied, and the
;               output device specified by TEXTOUT is not a terminal, then the
;               user will be prompted for a description.
;       OFFSET - 2 element numeric vector giving an offset to apply to the 
;               display of the X,Y coordinates of the image (e.g. if the 
;               supplied image array is a subarray of a larger image).
; OUTPUTS:
;       None.
;
; PROCEDURE:
;       Corresponding region of image is then displayed at
;       the terminal.   If necessary, IMLIST will divide all pixel values
;       in a REAL*4 image by a (displayed) factor of 10 to make a pretty format.
;
; SYSTEM VARIABLES:
;       If the keyword TEXTOUT is not supplied, then the non-standard system
;       variable !TEXTOUT will be read.    (The procedure ASTROLIB can be
;       used to add the non-standard system variables.)
;
; RESTRICTIONS:
;       IMLIST may not be able to correctly format all pixel values if the
;       dynamic range of the values near the center pixel is very large
;
; EXAMPLE:
;       Display the pixel values of an image array IM in the vicinity of 254,111
;
;       IDL> imlist, IM, 254, 111
;
; PROCEDURES USED
;       TEXTOPEN, F_FORMAT(), TEXTCLOSE
; REVISION HISTORY:
;       Written,    W. Landsman             June, 1991
;       Added DESCRIP keyword    W. Landsman      December, 1991
;       Treat LONG image as integer when possible, call TEXTOPEN with /STDOUT
;       keyword, W. Landsman   April, 1996
;       Use SYSTIME() instead of !STIME  August 1997
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Recognize new integer types, added OFFSET keyword  W. Landsman Jan. 2000
;       Replace DATATYPE() with size(/TNAME)  W. Landsman Nov. 2001

; NAME:
;	IRAFDIR
; PURPOSE:
;	Provide a brief description of the IRAF images on a directory
; CALLING SEQUENCE:
;	IRAFDIR, [ directory, TEXTOUT = ]
;
; OPTIONAL INPUT PARAMETERS:
;	DIRECTORY - Scalar string giving file name, disk or directory to 
;		be searched 
;
; OPTIONAL INPUT KEYWORD:
;	TEXTOUT - specifies output device (see TEXTOPEN)
;		textout=1	TERMINAL using /more option
;		textout=2	TERMINAL without /more option
;		textout=3	.prt
;		textout=4	laser.tmp
;		textout=5      user must open file
;		textout=7       Append to existing .prt file
;		textout = 'filename' (default extension of .prt)
;
; OUTPUT PARAMETERS:
;	None
;
; PROCEDURE:
;	FINDFILE is used to find all '.imh' files in the directory. 
;	The object name and image size (NAXIS1, NAXIS2) are extracted
;	from the header. Each header is also searched for the parameters
;	DATE-OBS (or TDATEOBS), TELESCOP (or OBSERVAT), EXPTIME.
;  
; RESTRICTIONS:
;	(1) Some fields may be truncated since IRAFDIR uses a fixed format 
;		output
;	(2) No more than 2 dimension sizes are displayed 
; SYSTEM VARIABLES:
;	If 'textout' keyword is not specified to select an output device,
;	!TEXTOUT will be the default.    This non-standard system variable
;	can be added using the procedure ASTROLIB.
;
; PROCEDURE CALLS:
;	EXPAND_TILDE(), FDECOMP, REMCHAR, TEXTOPEN, TEXTCLOSE
; MODIFICATION HISTORY:
;	Written, K. Venkatakrishna, ST Systems Corp, August 1991
;	Work for IRAF V2.11 format   W. Landsman   November 1997
;	Converted to IDL V5.0   W. Landsman  2-Nov-1997

; NAME:
;     IRAFRD
; PURPOSE:
;       Read an IRAF (.imh) file into IDL image and header arrays.
; EXPLANATION:
;       The internal IRAF format changed somewhat in IRAF V2.11 to a machine
;       independent format, with longer filename allocations.  This version 
;       of IRAFRD should be able to read either format. 
;
; CALLING SEQUENCE:
;       IRAFRD, im, hdr, filename, [/SILENT ]  
;
; OPTIONAL INPUT:
;       FILENAME -  Character string giving the name of the IRAF image 
;               header.  If omitted, then program will prompt for the 
;               file name.  IRAFRD always assumes the header file has an 
;               extension '.imh'.    IRAFRD will automatically locate the
;               ".pix" file containing the data by parsing the contents of 
;               the .imh file.   (If the parse is unsuccesful, then IRAFRD looks
;               in the same directory as the .imh file.)
; OUTPUTS:
;       IM - array containing image data
;       HDR - string array containing header.  Basic information in the
;               IRAF header is converted to a FITS style header
;
; OPTIONAL INPUT KEYWORDS:
;       /SILENT  - If this keyword is set and non-zero, then messages displayed
;               while reading the image will be suppressed.  
;
; RESTRICTIONS:
;       (1)  Image size and history sections of the IRAF header are copied 
;               into the FITS header HDR.  Other information (e.g. astrometry)
;               might not be included unless it is also in the history section
;       (2)  IRAFRD ignores the node name when deciphering the name of the
;               IRAF ".pix" file.
;       (3)  Certain FITS keywords ( DATATYPE, IRAFNAME) may appear more than
;               once in the output name
;       (4)  Does not read the DATE keyword for the new (V2.11) IRAF files
; NOTES:
;       IRAFRD obtains dimensions and type of image from the IRAF header.
;
; PROCEDURES CALLED:
;       FDECOMP, SPEC_DIR(), SXADDPAR, SXPAR()
;
; MODIFICATION HISTORY:
;       Written W. Landsman, STX January 1989
;       Converted to IDL Version 2.  M. Greason, STX, June 1990
;       Updated for DecStation compatibility   W. Landsman   March 1992
;       Don't leave an open LUN  W. Landsman   July 1993
;       Don't overwrite existing OBS-DATE  W. Landsman  October 1994
;       Don't bomb on very long FITS headers W. Landsman  April 1995
;       Work on Alpha/OSF and Linux      W. Landsman     Dec 1995
;       Remove /VMSIMG keyword, improve efficiency when physical and
;               image dimensions differ   W. Landsman     April 1996
;       Don't use FINDFILE (too slow)     W. Landsman     Oct 1996
;       Read V2.11 files, remove some parameter checks W. Landsman Nov. 1997
;       Fixed problem reading V2.11 files with long headers Jan. 1998
;       Accept names with multiple extensions    W. Landsman   April 98 
;       Test for big endian machine under V2.11 format W. Landsman Feb. 1999
;       Don't read past the end of file for V5.4 compatilibity  W.L.  Jan. 2001
;       Convert to square brackets W.L   May 2001

; NAME:
;     IRAFWRT
; PURPOSE:
;     Write IDL data in IRAF (OIF) format (.imh and .pix files).
; EXPLANATION:
;     Does the reverse of IRAFRD.    IRAFWRT writes the "old" IRAF format
;     used prior to v2.11.   However, this "old" format is still readable by
;     the current version of IRAF.
;
; CALLING SEQUENCE: 
;    IRAFWRT, image, hdr, filename, [ PIXDIR = ]
;
; INPUTS:
;     image - array containing data
;     hdr   - The  corresponding FITS header.   Use MKHDR to create a minimal
;             FITS header if one does not already exist.
;     filename - Scalar string giving the name of the file to be written 
;             Should not include the extension name, which will be supplied 
;             by IRAFWRT.
; OUTPUTS:
;     None
;
; OPTIONAL KEYWORD INPUT:
;      PIXDIR - scalar string specifying the directory into which to write
;              the IRAF pixel (.pix) file.   The default is to write the pixel
;              file to the same directory as the header (.imh) file
;
; SIDE EFFECTS:
;      Image array and  FITS header are written to IRAF pixel file 
;               'filename'.pix and header file 'filename'.imh
;
; EXAMPLE:
;       Write an empty 50 x 50 array of all zeros to an IRAF file named 'EMPTY'
;
;       IDL> im = intarr( 50, 50)         ;Create empty array
;       IDL> mkhdr, hdr, im               ;Create a minimal FITS header
;       IDL> irafwrt, im, hdr, 'empty'    ;Write to a IRAF file named 'empty'
;
; PROCEDURE:
;       IRAFWRT gets information about the data - image dimensions, size, 
;       datatype, maximum and minimum pixel values - and writes it into
;       the binary part of the header. The ASCII part of the header
;       is directly copied after deleting records with certain keywords 
;       A pixel file is created, with a header in the first 1024 bytes
;
; RESTRICTIONS:
;       (1) The files are not created by IRAFWRT are not identical to those 
;               created by the IRAF routine rfits.    However, the files 
;               created by IRAFWRT appear to be compatible with all the IRAF 
;               routines tested so far.
;       (2)  IRAFWRT has been tested on a limited number of data types
;       (3)  IRAFWRT has only been tested on Unix and VMS systems.
;
; PROCEDURES CALLED:
;       FDECOMP, IS_IEEE_BIG(), ISARRAY(), REPCHR(), STRN(), SXDELPAR, SXPAR()
; MODIFICATION HISTORY:
;       Written K. Venkatakrishna, STX February 1992
;       VMS compatibility    W. Landsman      April 1992
;       Work with headers without DATE-OBS or ORIGIN           August 1992
;       Preserve HISTORY records with other FITS records       March 1995    
;       Fix case where a minimal FITS header supplied          August 1995
;       Work under Alpha/OSF and Linux                         Dec.   1995
;       Make sureheader has 80 char lines, use IS_IEEE_BIG()   May    1997
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Don't apply strlowcase to .pix name   W. Landsman      April 1999
;       Work with double precision            W. Landsman      May 1999
;       Minimize use of obsolete !ERR         W. Landsman      Feb. 2000

; NAME:
;       ISARRAY
; PURPOSE:
;       Tests if the argument is an array.
; CATEGORY:
; CALLING SEQUENCE:
;       flag = isarray(a)
; INPUTS:
;       a = variable to test.                                in
; KEYWORD PARAMETERS:
; OUTPUTS:
;       flag = test result: 0 if not array, else non-zero.   out
; COMMON BLOCKS:
; NOTES:
; MODIFICATION HISTORY:
;       R. Sterner  20 Mar, 1986.
;       Checked for undefined variables.  RES 25 Aug, 1989.
;       Johns Hopkins Applied Physics Lab.
;
; Copyright (C) 1986, 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.
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;       ISMEUV
; PURPOSE:
;       Compute the interstellar EUV optical depth 
;
; EXPLANATION:
;       The EUV optical depth is computed from the photoionization of
;       hydrogen and helium.
;
; CALLING SEQUENCE:
;       tau = ISMEUV( wave, Hcol, [ HeIcol, HeIIcol, /Fano ]
;
; INPUTS:
;       wave - Vector of wavelength values (in Angstroms).   Useful range is
;               40 - 912 A; at shorter wavelengths metal opacity should be
;               considered, at longer wavelengths there is no photoionization.
;       Hcol - Scalar specifying interstellar hydrogen column density in cm-2.
;                 Typical values are 1E17 to 1E20.
;
; OUTPUT:
;       tau - Vector giving resulting optical depth, same number of elements 
;               as wave, non-negative values.   To obtain the attenuation of 
;               an input spectrum, multiply by exp(-tau).
;
; OPTIONAL INPUTS:
;       HeIcol - Scalar specifying neutral helium column density in cm-2.    
;               Default is 0.1*Hcol (10% of hydrogen column)
;       HeIIcol - Scalar specifying ionized helium column density in cm-2
;               Default is 0 (no HeII)
;
; OPTIONAL INPUT KEYWORDS:
;       /FANO - If this keyword is set and non-zero, then the 4 strongest 
;               auto-ionizing resonances of He I are included.   The shape 
;               of these resonances is given by a Fano profile - see Rumph, 
;               Bowyer, & Vennes 1994, AJ, 107, 2108.  If these resonances are
;               included then the input wavelength vector should have
;               a fine (>~0.01 A) grid between 190 A and 210 A, since the
;               resonances are very narrow.
; EXAMPLE:
;       (1) One has a model EUV spectrum with wavelength, w (in Angstroms) and 
;       flux,f .  Plot the model flux after attenuation by 1e18 cm-2 of HI, 
;       with N(HeI)/N(HI) = N(HeII)/N(HI) = 0.05
;
;       IDL> Hcol = 1e18
;       IDL> plot, w, f*exp(-ismeuv(w, Hcol, .05*Hcol, .05*Hcol))
;
;       (2)  Plot the cross-section of HeI from 180 A to 220 A for 1e18 cm-2
;               of HeI, showing the auto-ionizing resonances.   This is 
;               Figure 1 in Rumph et al. (1994)
;
;       IDL> w = 180 + findgen(40000)*0.001        ;Need a fine wavelength grid
;       IDL> plot, w, ismeuv(w, 0, 1e18, /Fano)          
;
; HISTORY
;       Written,    W. Landsman                  October, 1994
;       Adapted from ism.c at anonymous ftp site cea-ftp.cea.berkeley.edu
;       by Pat Jelinsky, Todd Rumph & others.
;       Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	IS_IEEE_BIG
; PURPOSE:
;	Determine if the current machine uses IEEE, big-endian numbers.
; EXPLANATION:
;       (Big endian implies that byteorder XDR conversions are no-ops).
; CALLING SEQUENCE:
;	flag = is_ieee_big()
; INPUT PARAMETERS:
;       None
; RETURNS:
;       1 if the machine appears to be IEEE-compliant, 0 if not.
; COMMON BLOCKS:
;	None.
; SIDE EFFECTS:
;	None
; RESTRICTIONS:
; PROCEDURE:
;       The first byte of the two-byte representation of 1 is examined.
;       If it is zero, then the data is stored in big-endian order.
; MODIFICATION HISTORY:
;       Written 15-April-1996 by T. McGlynn for use in MRDFITS.
;	13-jul-1997	jkf/acc	- added calls to check_math to avoid
;				  underflow messages in V5.0 on Win32 (NT).
;	Converted to IDL V5.0   W. Landsman   September 1997
;       Follow RSI and just do a single test  W. Landsman   April 2003

; NAME:
;	JDCNV
; PURPOSE:
;	Converts Gregorian dates to Julian days   
;
; EXPLANATION:
;       For IDL versions V5.1 or greater, this procedure is superceded by
;       JULDAY() function in the standard IDL distribution.   Note, however,
;       that prior to V5.1 there wasa bug in JULDAY() that gave answers off
;       by 0.5 days. 
;        
; CALLING SEQUENCE:
;	JDCNV, YR, MN, DAY, HR, JULIAN
;
; INPUTS:
; 	YR = Year, integer scalar or vector
;	MN = Month  integer (1-12) scalar or vector
;	DAY = Day   integer 1-31) scalar or vector 
;	HR  = Hours and fractions of hours of universal time (U.T.), scalar
;              or vector
;		
; OUTPUTS:
;	JULIAN = Julian date (double precision) 
;
; EXAMPLE:
;	To find the Julian Date at 1978 January 1, 0h (U.T.)
;
;	IDL> JDCNV, 1978, 1, 1, 0., JULIAN
;
;	will give JULIAN = 2443509.5
; NOTES:
;	(1) JDCNV will accept vector arguments 
;	(2) JULDATE is an alternate procedure to perform the same function
;
; REVISON HISTORY:
;	Converted to IDL from Don Yeomans Comet Ephemeris Generator,
;	B. Pfarr, STX, 6/15/88
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;   JPLEPHINTERP
;
; AUTHOR:
;   Craig B. Markwardt, NASA/GSFC Code 662, Greenbelt, MD 20770
;   craigm@lheamail.gsfc.nasa.gov
;   UPDATED VERSIONs can be found on my WEB PAGE: 
;      http://cow.physics.wisc.edu/~craigm/idl/idl.html
;
; PURPOSE:
;   Interpolate position and motion of planetary bodies (JPL Ephemeris)
;
; MAJOR TOPICS:
;   Planetary Orbits, Interpolation
;
; CALLING SEQUENCE:
;   JPLEPHINTERP, INFO, RAWDATA, T, X, Y, Z, [VX, VY, VZ, /EARTH, /SUN,
;         OBJECTNAME=, CENTER=, TBASE=, POSUNITS=, VELUNITS= ]
;
; DESCRIPTION:
;
;   JPLEPHINTERP interpolates the JPL DE200 or DE405 planetary
;   ephemeris to find the positions and motions of planetary bodies.
;
;   This routine is the second stage of a two-stage process to
;   interpolate the JPL ephemeris.  In this first stage, the file is
;   opened using JPLEPHREAD, and the relevant portions of the table
;   are read and stored into the two variables INFO and RAWDATA.  In
;   the second stage, the user actually interpolates the ephemeris for
;   the desired bodies and to the desired ephemeris time using
;   JPLEPHINTERP.
;
;   The only independent variable which must be specified is T, the
;   ephemeris time.  For low to moderate accuracy applications, T is
;   simply the conventional calendar date, expressed in Julian days.
;   See below for high precision applications.
;
;   Upon output, the position components of the desired body are
;   returned in parameters X, Y and Z, and if requested velocity
;   components are returned in parameters VX, VY and VZ.  Coordinates
;   are referred to the ephemeris's coordinate system: FK5 for
;   JPL-DE200 and ICRS for JPL-DE405.  By default, the origin of
;   coordinates is the solar system barycenter (SSB), unless another
;   origin is selected using the CENTER keyword.
;
;   Users must set the VELOCITY keyword to generate body velocities.
;   By default they are not generated.
;
;   Users can select the desired body by using either the EARTH or SUN
;   keywords, or the OBJECTNAME keyword.
;
;   By default, positions are returned in units of KM and velocities
;   in units of KM/DAY.  However, the output units are selectable by
;   setting the POSUNITS and VELUNITS keywords.
;
; High Precision Applications
;
;   If the required precision is finer than a few hundred meters, the
;   user must be aware that the formal definition of the ephemeris
;   time is the coordinate time of a clock placed at the solar system
;   barycenter (SSB).  If the user's time is measured by a clock
;   positioned elsewhere, then various corrections must be applied.
;   Usually, the most significant correction is that from the
;   geocenter to the SSB (see Fairhead & Bretagnon 1990; Fukushima
;   1995).  Not applying this correction creates an error with
;   amplitude ~170 nano-light-seconds ( = 50 m) on the earth's
;   position.  (see TDB2TDT)
;
;   For high precision, the user should also specify the TBASE
;   keyword.  TBASE should be considered a fixed epoch with respect to
;   which T is measured; T should be small compared to TBASE.
;   Internally, subtraction of large numbers occurs with TBASE first,
;   so truncation error is minimized by specifying TBASE.
;
; Nutations and Librations
;
;   This routine also provides information about earth nutations and
;   lunar librations, which are stored in the JPL ephemeris tables.
;   The POSUNITS and VELUNITS keywords do not affect these
;   computations.
;
;   Lunar librations in the form of three Euler angles are returned in
;   X, Y, Z, in units of radians, and their time derivatives are
;   returned in VX, VY, and VZ in units of radians per day.
;
;   The earth nutation angles psi (nutation in longitude) and epsilon
;   (nutation in obliquity) are returned in X and Y, in units of
;   radians.  Their time derivatives are returned in VX and VY
;   respectively.  The quantities returned in Z and VZ are undefined.
;
; Verification
;
;   The precision routine has been verified using JPLEPHTEST, which is
;   similar to the original JPL program EPHTEST.  For years 1950 to
;   2050, JPLEPHINTERP reproduces the original JPL ephemeris to within
;   1.5 centimeters.
;
;
; PARAMETERS: 
;
;   INFO - structure returned by JPLEPHREAD.  Users should not modify
;          this structure.
;
;   RAWDATA - raw data array returned by JPLEPHREAD.  Users should not
;             modify this data array.
;
;   T - ephemeris time(s) of interest.  May be a scalar or vector.
;       The actual time is (T+TBASE).
;
;   X, Y, Z - upon return, the x-, y- and z-components of the body
;             position are returned in these parameters.  For
;             nutations and librations see above.
;
;   VX, VY, VZ - upon return, the x-, y- and z-components of the body
;                velocity are returned in these parameters, if the
;                VELOCITY keyword is set.  For nutations and
;                librations see above.
;
;
; KEYWORD PARAMETERS:
;
;   EARTH, SUN - set one of these keywords if the desired body is the
;                earth or the sun.  One of EARTH, SUN or OBJECTNAME
;                must be specified.
;
;   OBJECTNAME - a scalar string or integer, specifies the planetary
;                body of interest.  May take any one of the following
;                integer or string values.
;
;                   1 - 'MERCURY'     9 - 'PLUTO'
;                   2 - 'VENUS'      10 - 'MOON'  (earth's moon)
;                   3 - 'EARTH'      11 - 'SUN'
;                   4 - 'MARS'       12 - 'SOLARBARY' (solar system barycenter)
;                   5 - 'JUPITER'    13 - 'EARTHBARY' (earth-moon barycenter)
;                   6 - 'SATURN'     14 - 'NUTATIONS' (see above)
;                   7 - 'URANUS'     15 - 'LIBRATIONS' (see above)
;                   8 - 'NEPTUNE' 
;
;   CENTER - a scalar string or integer, specifies the origin of
;            coordinates.  See OBJECTNAME for allowed values.
;            Default: 12 (Solar system barycenter)
;
;   VELOCITY - if set, body velocities are generated and returned in
;              VX, VY and VZ.
;              Default: unset (no velocities)
;
;   POSUNITS - a scalar string specifying the desired units for X, Y,
;              and Z.  Allowed values:
;                 'KM' - kilometers  (default)
;                 'CM' - centimeters
;                 'AU' - astronomical units
;                 'LT-S' - light seconds
;
;   VELUNITS - a scalar string specifying the desired units for VX, VY
;              and VZ.  Allowed values:
;                 'KM/DAY' - kilometers per day  (default)
;                 'KM/S' - kilometers per second
;                 'CM/S' - centimeters per second
;                 'LT-S/S' - light seconds per second
;                 'AU/DAY' - astronomical units per day
;
;   TBASE - a scalar number, specifies a fixed epoch against wich T is
;           measured.  The ephemeris time will be (T+TBASE).  Use this
;           keyword for maximum precision.
;
;
; EXAMPLE:
;
;   Find position of earth at ephemeris time 2451544.5 JD.  Units are
;   in Astronomical Units.
;
;   JPLEPHREAD, 'JPLEPH.200', pinfo, pdata, [2451544D, 2451545D]
;
;   JPLEPHINTERP, pinfo, pdata, 2451544.5D, xearth, yearth, zearth, $
;                 /EARTH, posunits='AU'
;     
;
; REFERENCES:
;
;   AXBARY, Arnold Rots.
;      ftp://heasarc.gsfc.nasa.gov/xte/calib_data/clock/bary/
;
;   HORIZONS, JPL Web-based ephermis calculator (Ephemeris DE406)
;      http://ssd.jpl.nasa.gov/horizons.html
;   
;   Fairhead, L. & Bretagnon, P. 1990, A&A, 229, 240
;
;   Fukushima, T. 1995, A&A, 294, 895
;
;   Standish, E.M. 1982, "Orientation of the JPL Ephemerides,
;      DE200/LE200, to the Dynamical Equinox of J2000", Astronomy &
;      Astrophysics, vol. 114, pp. 297-302.
;
;   Standish, E.M.: 1990, "The Observational Basis for JPL's DE200,
;      the planetary ephemeris of the Astronomical Almanac", Astronomy
;      & Astrophysics, vol. 233, pp. 252-271.    
;
; SEE ALSO
;   JPLEPHREAD, JPLEPHINTERP, JPLEPHTEST, TDB2TDT
;   
; MODIFICATION HISTORY:
;   Written and Documented, CM, Jun 2001
;   Corrected bug in name conversion of NUTATIONS and LIBRATIONS, 18
;     Oct 2001, CM
;
;  $Id: jplephinterp.pro,v 1.9 2001/10/18 19:17:57 craigm Exp $
;

; NAME:
;   JPLEPHREAD
;
; AUTHOR:
;   Craig B. Markwardt, NASA/GSFC Code 662, Greenbelt, MD 20770
;   craigm@lheamail.gsfc.nasa.gov
;   UPDATED VERSIONs can be found on my WEB PAGE: 
;      http://cow.physics.wisc.edu/~craigm/idl/idl.html
;
; PURPOSE:
;   Open and read JPL DE200 or DE405 Ephemeride FITS File
;
; MAJOR TOPICS:
;   Planetary Orbits, Interpolation
;
; CALLING SEQUENCE:
;   JPLEPHREAD, FILENAME, INFO, RAWDATA, JDLIMITS, STATUS=, ERRMSG=
;
; DESCRIPTION:
;
;   JPLEPHREAD opens and reads the JPL DE200 or DE405 planetary
;   ephemerides, as available in FITS format.  The user must have the
;   IDL Astronomy Library installed to use this routine.
;
;   This routine is the initialization stage of a two-stage process to
;   interpolate the JPL ephemeris.  In this first stage, the file is
;   opened, and the relevant portions of the table are read and stored
;   into the two variables INFO and RAWDATA.  In the second stage, the
;   user actually interpolates the ephemeris for the desired bodies
;   and to the desired ephemeris time using JPLEPHINTERP.
;
;   Users must decide ahead of time the approximate dates of interest,
;   and pass this range in the JDLIMITS parameter.  Any date covered
;   by the ephemeris is valid.
;
;   JPLEPHREAD is able to read files of the following format:
;     DE200 - Chebyshev - FITS format - Note 1
;     DE405 - Chebyshev - FITS format - Note 1
;     DE200 - Taylor    - FITS format - Note 2
;
;   Note 1 - Chebyshev formatted FITS files are available in the
;            AXBARY package by Arnold Rots, found here:
;              ftp://heasarc.gsfc.nasa.gov/xte/calib_data/clock/bary/
;            or at the Markwardt FTP site:
;              ftp://cow.physics.wisc.edu/pub/craigm/bary/
;
;   Note 2 - Taylor-series based ephemerides have been available for
;            years in the FTOOLS / LHEASOFT package produced by NASA's
;            Goddard Space Flight Center.  The original file is
;            de200_new.fits, which covers the years 1959-2000,
;            inclusive.  A newer file is named
;            de200_1950-2050_v2.fits, and covers the years 1959-2050.
;            See Markwardt FTP site for these files.
;
; PARAMETERS: 
;
;   FILENAME - name of ephemeris file (scalar string).
;
;   INFO - upon completion, information about the ephemeris data is
;          returned in this parameter in the form of a structure.
;          Users must not modify INFO, although several fields are
;          useful and may be accessed read-only:
;              TSTART/TSTOP (start and stop time of data in Julian
;                            days);
;              C (speed of light in km/s);
;              DENUM (development ephemeris number [200 or 405])
;              AU (1 astronomical unit, in units of light-seconds)
;
;   RAWDATA - upon completion, raw ephemeris data is returned in this
;             parameter.  Users are not meant to access this data
;             directly, but rather to pass it to JPLEPHINTERP.
;
;   JDLIMITS - a two-element vector (optional), describing the desired
;              time range of interest.  The vector should have the
;              form [TSTART, TSTOP], where TSTART and TSTOP are the
;              beginning and ending times of the range, expressed in
;              Julian days.
;              Default: entire table is read (note, this can be
;              several megabytes)
;
;
; KEYWORD PARAMETERS:
;
;   STATUS - upon completion, a value of 1 indicates success, and 0
;            indicates failure.
;
;   ERRMSG - upon completion, an error message is returned in this
;            keyword.  If there were no errors, then the returned
;            value is the empty string, ''.
;
;
; EXAMPLE:
;
;   Find position of earth at ephemeris time 2451544.5 JD.  Units are
;   in Astronomical Units.
;
;   JPLEPHREAD, 'JPLEPH.200', pinfo, pdata, [2451544D, 2451545D]
;
;   JPLEPHINTERP, pinfo, pdata, 2451544.5D, xearth, yearth, zearth, $
;                 /EARTH, posunits='AU'
;     
;
; REFERENCES:
;
;   AXBARY, Arnold Rots.
;      ftp://heasarc.gsfc.nasa.gov/xte/calib_data/clock/bary/
;
;   HORIZONS, JPL Web-based ephermis calculator (Ephemeris DE406)
;      http://ssd.jpl.nasa.gov/horizons.html
;   
;   JPL Export Ephmeris FTP Site
;      ftp://navigator.jpl.nasa.gov/pub/ephem/export/
;      (ephemeris files are available here, however, they must be
;      converted to FITS format using the "bin2eph" utility found in
;      AXBARY)
;
;   JPL Export Ephemeris CD-ROM - Ordering Information
;      http://www.willbell.com/software/jpl.htm
;
;   Standish, E.M. 1982, "Orientation of the JPL Ephemerides,
;      DE200/LE200, to the Dynamical Equinox of J2000", Astronomy &
;      Astrophysics, vol. 114, pp. 297-302.
;
;   Standish, E.M.: 1990, "The Observational Basis for JPL's DE200,
;      the planetary ephemeris of the Astronomical Almanac", Astronomy
;      & Astrophysics, vol. 233, pp. 252-271.    
;
; SEE ALSO
;   JPLEPHREAD, JPLEPHINTERP, JPLEPHTEST
; PROCEDURES USED:
;     FXBCLOSE, FXBOPEN, FXPAR(), 
;   
; MODIFICATION HISTORY:
;   Written and Documented, CM, Jun 2001
;   Use GETTOK() instead of STR_SEP()  W. Landsman  July 2002
;
;  $Id: jplephread.pro,v 1.6 2001/07/01 03:32:02 craigm Exp $
;

; NAME:
;   JPLEPHTEST
;
; AUTHOR:
;   Craig B. Markwardt, NASA/GSFC Code 662, Greenbelt, MD 20770
;   craigm@lheamail.gsfc.nasa.gov
;   UPDATED VERSIONs can be found on my WEB PAGE: 
;      http://cow.physics.wisc.edu/~craigm/idl/idl.html
;
; PURPOSE:
;   Test JPLEPHTEST with JPL test data set
;
; MAJOR TOPICS:
;   Planetary Orbits, Interpolation
;
; CALLING SEQUENCE:
;   JPLEPHTEST, EPHFILE, TESTFILE
;
; DESCRIPTION:
;
;   JPLEPHTEST tests the JPLEPHINTERP procedure for precision.  In
;   order to function, you must have a JPL ephemeris test data set.
;   The test data set testpo.405 is available in 
;   ftp://idlastro.gsfc.nasa.gov/pub/data
;
;   The procedure opens and reads the test set, which contains
;   precomputed data.  Every tenth value is printed on the screen.
;   Any deviations that exceed 1.5d-13 AU = 1.5 cm are reported.
;
;   The columns are labelled according to the input file, except for
;   the final column, which is the deviation between the input file
;   and the computed value.
;
;
; PARAMETERS: 
;
;   EPHFILE - a scalar string, specifies the name of the ephemeris
;             file, in FITS format.    JPLEPHTEST will look in the directory
;             $ASTRO_DATA for the file if it is not in the current directory.
;
;   TESTFILE - a scalar string, specifies JPL test data set to compare
;              against.   JPLEPHTEST will look in the directory
;             $ASTRO_DATA for the file if it is not in the current directory.
;
;
; EXAMPLE:
;
;   Test JPL DE200 and DE405 ephemerides.  Assumes files are in the
;   current directory.
;
;   JPLEPHTEST, 'JPLEPH.200', 'testpo.200'
;   JPLEPHTEST, 'JPLEPH.405', 'testpo.405'
;     
;
; REFERENCES:
;
;   JPL Export Ephmeris FTP Site
;      ftp://navigator.jpl.nasa.gov/pub/ephem/export/
;      (see test-data/ for test data sets)
;   
;   HORIZONS, JPL Web-based ephermis calculator (Ephemeris DE406)
;      http://ssd.jpl.nasa.gov/horizons.html
;
;
; SEE ALSO
;   JPLEPHREAD, JPLEPHINTERP, JPLEPHTEST
;   
; MODIFICATION HISTORY:
;   Written and Documented, CM, Jun 2001
;   Removed TRANSREAD, improved output, improved docs, CM, 9 Jul 2001
;
;  $Id: jplephtest.pro,v 1.4 2001/07/20 13:29:53 craigm Exp $
;

; NAME:
;      JPRECESS
; PURPOSE:
;      Precess astronomical coordinates from B1950 to J2000
; EXPLANATION:
;      Calculate the mean place of a star at J2000.0 on the FK5 system from the
;      mean place at B1950.0 on the FK4 system.
;
;      Use BPRECESS for the reverse direction J2000 ==> B1950
; CALLING SEQUENCE:
;      jprecess, ra, dec, ra_2000, dec_2000, [ MU_RADEC = , PARALLAX = 
;               RAD_VEL =, EPOCH =   ]
;
; INPUTS:
;      RA,DEC - input B1950 right ascension and declination in *degrees*.
;               Scalar or vector
;
; OUTPUTS:
;      RA_2000, DEC_2000 - the corresponding J2000 right ascension and 
;               declination in *degrees*.   Same number of elements as RA,DEC
;               but always double precision. 
;
; OPTIONAL INPUT-OUTPUT KEYWORDS
;      MU_RADEC - 2xN element double precision vector containing the proper 
;                  motion in seconds of arc per tropical *century* in right 
;                  ascension and declination.
;      PARALLAX - N_element vector giving stellar parallax (seconds of arc)
;      RAD_VEL  - N_element vector giving radial velocity in km/s
;
;       The values of MU_RADEC, PARALLAX, and RADVEL will all be modified
;       upon output to contain the values of these quantities in the
;       J2000 system.    Values will also be converted to double precision.  
;       The parallax and radial velocity will have a very minor influence on 
;       the J2000 position.
;
;       EPOCH - scalar giving epoch of original observations, default 1950.0d
;           This keyword value is only used if the MU_RADEC keyword is not set.
;  NOTES:
;       The algorithm is taken from the Explanatory Supplement to the 
;       Astronomical Almanac 1992, page 184.
;       Also see Aoki et al (1983), A&A, 128,263
;
;       JPRECESS distinguishes between the following two cases:
;       (1) The proper motion is known and non-zero
;       (2) the proper motion is unknown or known to be exactly zero (i.e.
;               extragalactic radio sources).   In this case, the algorithm
;               in Appendix 2 of Aoki et al. (1983) is used to ensure that
;               the output proper motion is  exactly zero.    Better precision
;               can be achieved in this case by inputting the EPOCH of the
;               original observations.
;
;       The error in using the IDL procedure PRECESS for converting between
;       B1950 and J2000 can be up to 1.5", mainly in right ascension.   If
;       better accuracy than this is needed then JPRECESS should be used.
;
; EXAMPLE:
;       The SAO catalogue gives the B1950 position and proper motion for the 
;       star HD 119288.   Find the J2000 position. 
;
;          RA(1950) = 13h 39m 44.526s      Dec(1950) = 8d 38' 28.63''  
;          Mu(RA) = -.0259 s/yr      Mu(Dec) = -.093 ''/yr
;
;       IDL> mu_radec = 100D* [ -15D*.0259, -0.093 ]
;       IDL> ra = ten(13,39,44.526)*15.D 
;       IDL> dec = ten(8,38,28.63)
;       IDL> jprecess, ra, dec, ra2000, dec2000, mu_radec = mu_radec
;       IDL> print, adstring(ra2000, dec2000,2)
;               ===> 13h 42m 12.740s    +08d 23' 17.69"
;
; RESTRICTIONS:
;      "When transferring individual observations, as opposed to catalog mean
;       place, the safest method is to tranform the observations back to the
;       epoch of the observation, on the FK4 system (or in the system that was
;       used to to produce the observed mean place), convert to the FK5 system,
;       and transform to the the epoch and equinox of J2000.0" -- from the
;       Explanatory Supplement (1992), p. 180
;
; REVISION HISTORY:
;       Written,    W. Landsman                September, 1992
;       Corrected a couple of typos in M matrix   October, 1992
;       Vectorized, W. Landsman                   February, 1994
;       Implement Appendix 2 of Aoki et al. (1983) for case where proper
;       motion unknown or exactly zero     W. Landsman    November, 1994
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Fixed typo in updating proper motion   W. Landsman   April 1999
;       Make sure proper motion is floating point  W. Landsman December 2000

; NAME:
;     JULDATE
; PURPOSE:                                   
;     Convert from calendar to Reduced Julian Date
;
; EXPLANATION:
;     Julian Day Number is a count of days elapsed since Greenwich mean noon 
;     on 1 January 4713 B.C.  The Julian Date is the Julian day number
;     followed by the fraction of the day elapsed since the preceding noon. 
;
;     This procedure duplicates the functionality of the JULDAY() function in
;     in the standard IDL distribution, but also allows interactive input and
;     gives output as Reduced Julian date (=JD - 2400000.)  
;     (Also note that prior to V5.1 there was a bug in JULDAY() that gave 
;     answers offset by 0.5 days.)
;
; CALLING SEQUENCE:
;     JULDATE, /PROMPT           ;Prompt for calendar Date, print Julian Date
;               or
;     JULDATE, date, jd      
;
; INPUT:
;     DATE -  3 to 6-element vector containing year,month (1-12),day, and 
;              optionally hour, minute, and second all specified as numbers
;              (Universal Time).   Year should be supplied with all digits.
;              Years B.C should be entered as negative numbers (and note that
;              Year 0 did not exist).  If Hour, minute or seconds are not 
;              supplied, they will default to 0. 
;
;  OUTPUT:
;       JD - Reduced Julian date, double precision scalar.  To convert to
;               Julian Date, add 2400000.   JULDATE will print the value of
;               JD at the terminal if less than 2 parameters are supplied, or 
;               if the /PROMPT keyword is set
;      
;  OPTIONAL INPUT KEYWORD:
;       /PROMPT - If this keyword is set and non-zero, then JULDATE will prompt
;               for the calendar date at the terminal.
;
;  RESTRICTIONS:
;       The procedure HELIO_JD can be used after JULDATE, if a heliocentric
;       Julian date is required.
;
;  EXAMPLE:
;       A date of 25-DEC-1981 06:25 UT may be expressed as either
;
;       IDL> juldate, [1981, 12, 25, 6, 25], jd       
;       IDL> juldate, [1981, 12, 25.2673611d], jd 
;
;       In either case, one should obtain a Reduced Julian date of 
;       JD = 44963.7673611
;
;  PROCEDURE USED:
;       GETOPT()
;  REVISION HISTORY
;       Adapted from IUE RDAF (S. Parsons)                      8-31-87
;       Algorithm from Sky and Telescope April 1981   
;       Added /PROMPT keyword, W. Landsman    September 1992
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Make negative years correspond to B.C. (no year 0), work for year 1582
;       Disallow 2 digit years.    W. Landsman    March 2000

; NAME:
;       KSONE
; PURPOSE:
;       Compute the one-sided Kolmogorov-Smirnov statistic
; EXPLANATION:
;       Returns the Kolmogorov-Smirnov statistic and associated probability for 
;       for an array of data values and a user-supplied cumulative distribution
;       function (CDF) of a single variable.   Algorithm from the procedure of
;       the same name in "Numerical Recipes" by Press et al. 2nd edition (1992)
;
; CALLING SEQUENCE:
;       ksone, data, func_name, D, prob, [ /PLOT ]
;
; INPUT PARAMETERS:
;       data -  vector of data values, must contain at least 4 elements for the
;               K-S statistic to be meaningful 
;       func_name - scalar string giving the name of the cumulative distribution
;               function.    The function must be defined to accept the data
;               vector as its only input (see example).
;
; OUTPUT PARAMETERS:
;       D - floating scalar giving the Kolmogorov-Smirnov statistic.   It 
;               specified the maximum deviation between the cumulative 
;               distribution of the data and the supplied function 
;       prob - floating scalar between 0 and 1 giving the significance level of
;               the K-S statistic.   Small values of PROB show that the 
;               cumulative distribution function of DATA is significantly 
;               different from FUNC_NAME.
;
; OPTIONAL INPUT KEYWORD:
;       PLOT - If this keyword is set and non-zero, then KSONE will display a
;               plot of the CDF of the data with the supplied function 
;               superposed.   The data value where the K-S statistic is 
;               computed (i.e. at the maximum difference between the data CDF 
;               and the function) is indicated by a vertical line.
;               KSONE accepts the _EXTRA keyword, so that most plot keywords
;               (e.g. TITLE, XTITLE, XSTYLE) can also be passed to KSONE.
;
; EXAMPLE:
;       Determine if a vector created by the RANDOMN function is really 
;       consistent with a Gaussian distribution with unit variance.
;       The CDF of a Gaussian is the error function except that a factor
;       of 2 is included in the error function.   So we must create a special
;       function:
;
;       function gauss_cdf, x
;       return, errorf( x/sqrt(2) )
;       end
;
;       IDL> data = randomn(seed, 50)          ;create data array to be tested
;       IDL> ksone, abs(data), 'gauss_cdf', D, prob, /PLOT     ;Use K-S test
;      
;       PROB gives the probability that the null hypothesis (DATA came from a 
;       Gaussian distribution with unit variance) is correct.
;
; NOTES:
;       The code for PROB_KS is from the 2nd (1992) edition of Numerical 
;       Recipes which includes a more accurate computation of the K-S 
;       significance for small values of N than the first edition.
;
; PROCEDURE CALLS
;       procedure PROB_KS - computes significance of K-S distribution
;
; REVISION HISTORY:
;       Written     W. Landsman                   August, 1992
;       Accept _EXTRA keywords   W. Landsman      September, 1995          
;       Fixed possible bug in plot display showing position maximum difference
;       in histogram   M. Fardal/ W. Landsman      March, 1997
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Documentation updates   W. Landsman   June 2003

; NAME:
;       KSTWO
; PURPOSE:
;       Return the two-sided Kolmogorov-Smirnov statistic
; EXPLANATION:
;       Returns the Kolmogorov-Smirnov statistic and associated probability 
;       that two arrays of data values are drawn from the same distribution
;       Algorithm taken from procedure of the same name in "Numerical
;       Recipes" by Press et al., 2nd edition (1992), Chapter 14
;
; CALLING SEQUENCE:
;       kstwo, data1, data2, D, prob
;
; INPUT PARAMATERS:
;       data1 -  vector of data values, at least 4 data values must be included
;               for the K-S statistic to be meaningful
;       data2 -  second set of data values, does not need to have the same 
;               number of elements as data1
;
; OUTPUT PARAMETERS:
;       D - floating scalar giving the Kolmogorov-Smirnov statistic.   It
;               specifies the maximum deviation between the cumulative 
;               distribution of the data and the supplied function 
;       prob - floating scalar between 0 and 1 giving the significance level of
;               the K-S statistic.   Small values of PROB show that the 
;               cumulative distribution function of DATA1 is significantly 
;               different from DATA2
;
; EXAMPLE:
;       Test whether two vectors created by the RANDOMN function likely came
;       from the same distribution
;
;       IDL> data1 = randomn(seed,40)        ;Create data vectors to be 
;       IDL> data2 = randomn(seed,70)        ;compared
;       IDL> kstwo, data1, data2, D, prob   & print,D,prob
;
; PROCEDURE CALLS
;       procedure PROB_KS - computes significance of K-S distribution
;
; REVISION HISTORY:
;       Written     W. Landsman                August, 1992
;       FP computation of N_eff      H. Ebeling/W. Landsman  March 1996
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Fix for arrays containing equal values J. Ballet/W. Landsman Oct. 2001

; NAME:
;       LEGEND
; PURPOSE:
;       Create an annotation legend for a plot.
; EXPLANATION:
;       This procedure makes a legend for a plot.  The legend can contain
;       a mixture of symbols, linestyles, Hershey characters (vectorfont),
;       and filled polygons (usersym).  A test procedure, legendtest.pro,
;       shows legend's capabilities.  Placement of the legend is controlled
;       with keywords like /right, /top, and /center or by using a position
;       keyword for exact placement (position=[x,y]) or via mouse (/position).
; CALLING SEQUENCE:
;       LEGEND [,items][,keyword options]
; EXAMPLES:
;       The call:
;               legend,['Plus sign','Asterisk','Period'],psym=[1,2,3]
;         produces:
;               -----------------
;               |               |
;               |  + Plus sign  |
;               |  * Asterisk   |
;               |  . Period     |
;               |               |
;               -----------------
;         Each symbol is drawn with a plots command, so they look OK.
;         Other examples are given in optional output keywords.
;
;       lines = indgen(6)                       ; for line styles
;       items = 'linestyle '+strtrim(lines,2)   ; annotations
;       legend,items,linestyle=lines            ; vertical legend---upper left
;       items = ['Plus sign','Asterisk','Period']
;       sym = [1,2,3]
;       legend,items,psym=sym                   ; ditto except using symbols
;       legend,items,psym=sym,/horizontal       ; horizontal format
;       legend,items,psym=sym,box=0             ; sans border
;       legend,items,psym=sym,delimiter='='     ; embed '=' betw psym & text
;       legend,items,psym=sym,margin=2          ; 2-character margin
;       legend,items,psym=sym,position=[x,y]    ; upper left in data coords
;       legend,items,psym=sym,pos=[x,y],/norm   ; upper left in normal coords
;       legend,items,psym=sym,pos=[x,y],/device ; upper left in device coords
;       legend,items,psym=sym,/position         ; interactive position
;       legend,items,psym=sym,/right            ; at upper right
;       legend,items,psym=sym,/bottom           ; at lower left
;       legend,items,psym=sym,/center           ; approximately near center
;       legend,items,psym=sym,number=2          ; plot two symbols, not one
;       legend,items,/fill,psym=[8,8,8],colors=[10,20,30]; 3 filled squares
; INPUTS:
;       items = text for the items in the legend, a string array.
;               For example, items = ['diamond','asterisk','square'].
;               You can omit items if you don't want any text labels.
; OPTIONAL INPUT KEYWORDS:
;
;       linestyle = array of linestyle numbers  If linestyle[i] < 0, then omit
;               ith symbol or line to allow a multi-line entry.     If 
;               linestyle = -99 then text will be left-justified.  
;       psym = array of plot symbol numbers.  If psym[i] is negative, then a
;               line connects pts for ith item.  If psym[i] = 8, then the
;               procedure usersym is called with vertices define in the
;               keyword usersym.   If psym[i] = 88, then use the previously
;               defined user symbol
;       vectorfont = vector-drawn characters for the sym/line column, e.g.,
;               ['!9B!3','!9C!3','!9D!3'] produces an open square, a checkmark,
;               and a partial derivative, which might have accompanying items
;               ['BOX','CHECK','PARTIAL DERIVATIVE'].
;               There is no check that !p.font is set properly, e.g., -1 for
;               X and 0 for PostScript.  This can produce an error, e.g., use
;               !20 with PostScript and !p.font=0, but allows use of Hershey
;               *AND* PostScript fonts together.
;       N. B.: Choose any of linestyle, psym, and/or vectorfont.  If none is
;               present, only the text is output.  If more than one
;               is present, all need the same number of elements, and normal
;               plot behaviour occurs.
;               By default, if psym is positive, you get one point so there is
;               no connecting line.  If vectorfont[i] = '',
;               then plots is called to make a symbol or a line, but if
;               vectorfont[i] is a non-null string, then xyouts is called.
;       /help = flag to print header
;       /horizontal = flag to make the legend horizontal
;       /vertical = flag to make the legend vertical (D=vertical)
;       box = flag to include/omit box around the legend (D=include)
;       clear = flag to clear the box area before drawing the legend
;       delimiter = embedded character(s) between symbol and text (D=none)
;       colors = array of colors for plot symbols/lines (D=!P.color)
;       textcolors = array of colors for text (D=!P.color)
;       margin = margin around text measured in characters and lines
;       spacing = line spacing (D=bit more than character height)
;       pspacing = psym spacing (D=3 characters) (when number of symbols is
;             greater than 1)
;       charsize = just like !p.charsize for plot labels
;       charthick = just like !p.charthick for plot labels
;       thick = array of line thickness numbers (D = !P.thick), if used, then 
;               linestyle must also be specified
;       position = data coordinates of the /top (D) /left (D) of the legend
;       normal = use normal coordinates for position, not data
;       device = use device coordinates for position, not data
;       number = number of plot symbols to plot or length of line (D=1)
;       usersym = 2-D array of vertices, cf. usersym in IDL manual. 
;             (/USERSYM =square, default is to use existing USERSYM definition)
;       /fill = flag to fill the usersym
;       /left_legend = flag to place legend snug against left side of plot
;                 window (D)
;       /right_legend = flag to place legend snug against right side of plot
;               window.    If /right,pos=[x,y], then x is position of RHS and
;               text runs right-to-left.
;       /top_legend = flag to place legend snug against top of plot window (D)
;       /bottom = flag to place legend snug against bottom of plot window
;               /top,pos=[x,y] and /bottom,pos=[x,y] produce same positions.
;
;       If LINESTYLE, PSYM, VECTORFONT, THICK, COLORS, or TEXTCOLORS are
;       supplied as scalars, then the scalar value is set for every line or
;       symbol in the legend.
; Outputs:
;       legend to current plot device
; OPTIONAL OUTPUT KEYWORDS:
;       corners = 4-element array, like !p.position, of the normalized
;         coords for the box (even if box=0): [llx,lly,urx,ury].
;         Useful for multi-column or multi-line legends, for example,
;         to make a 2-column legend, you might do the following:
;           c1_items = ['diamond','asterisk','square']
;           c1_psym = [4,2,6]
;           c2_items = ['solid','dashed','dotted']
;           c2_line = [0,2,1]
;           legend,c1_items,psym=c1_psym,corners=c1,box=0
;           legend,c2_items,line=c2_line,corners=c2,box=0,pos=[c1[2],c1[3]]
;           c = [c1[0]c2[2],c1[3]>c2[3]]
;           plots,[c[0],c[0],c[2],c[2],c[0]],[c[1],c[3],c[3],c[1],c[1]],/norm
;         Useful also to place the legend.  Here's an automatic way to place
;         the legend in the lower right corner.  The difficulty is that the
;         legend's width is unknown until it is plotted.  In this example,
;         the legend is plotted twice: the first time in the upper left, the
;         second time in the lower right.
;           legend,['1','22','333','4444'],linestyle=indgen(4),corners=corners
;                       ; BOGUS LEGEND---FIRST TIME TO REPORT CORNERS
;           xydims = [corners[2]-corners[0],corners[3]-corners[1]]
;                       ; SAVE WIDTH AND HEIGHT
;           chdim=[!d.x_ch_size/float(!d.x_size),!d.y_ch_size/float(!d.y_size)]
;                       ; DIMENSIONS OF ONE CHARACTER IN NORMALIZED COORDS
;           pos = [!x.window[1]-chdim[0]-xydims[0] $
;                       ,!y.window[0]+chdim[1]+xydims[1]]
;                       ; CALCULATE POSITION FOR LOWER RIGHT
;           plot,findgen(10)    ; SIMPLE PLOT; YOU DO WHATEVER YOU WANT HERE.
;           legend,['1','22','333','4444'],linestyle=indgen(4),pos=pos
;                       ; REDO THE LEGEND IN LOWER RIGHT CORNER
;         You can modify the pos calculation to place the legend where you
;         want.  For example to place it in the upper right:
;           pos = [!x.window[1]-chdim[0]-xydims[0],!y.window[1]-xydims[1]]
; Common blocks:
;       none
; Procedure:
;       If keyword help is set, call doc_library to print header.
;       See notes in the code.  Much of the code deals with placement of the
;       legend.  The main problem with placement is not being
;       able to sense the length of a string before it is output.  Some crude
;       approximations are used for centering.
; Restrictions:
;       Here are some things that aren't implemented.
;       - An orientation keyword would allow lines at angles in the legend.
;       - An array of usersyms would be nice---simple change.
;       - An order option to interchange symbols and text might be nice.
;       - Somebody might like double boxes, e.g., with box = 2.
;       - Another feature might be a continuous bar with ticks and text.
;       - There are no guards to avoid writing outside the plot area.
;       - There is no provision for multi-line text, e.g., '1st line!c2nd line'
;         Sensing !c would be easy, but !c isn't implemented for PostScript.
;         A better way might be to simply output the 2nd line as another item
;         but without any accompanying symbol or linestyle.  A flag to omit
;         the symbol and linestyle is linestyle[i] = -1.
;       - There is no ability to make a title line containing any of titles
;         for the legend, for the symbols, or for the text.
; Side Effects:
; Modification history:
;       write, 24-25 Aug 92, F K Knight (knight@ll.mit.edu)
;       allow omission of items or omission of both psym and linestyle, add
;         corners keyword to facilitate multi-column legends, improve place-
;         ment of symbols and text, add guards for unequal size, 26 Aug 92, FKK
;       add linestyle(i)=-1 to suppress a single symbol/line, 27 Aug 92, FKK
;       add keyword vectorfont to allow characters in the sym/line column,
;         28 Aug 92, FKK
;       add /top, /bottom, /left, /right keywords for automatic placement at
;         the four corners of the plot window.  The /right keyword forces
;         right-to-left printing of menu. 18 Jun 93, FKK
;       change default position to data coords and add normal, data, and
;         device keywords, 17 Jan 94, FKK
;       add /center keyword for positioning, but it is not precise because
;         text string lengths cannot be known in advance, 17 Jan 94, FKK
;       add interactive positioning with /position keyword, 17 Jan 94, FKK
;       allow a legend with just text, no plotting symbols.  This helps in
;         simply describing a plot or writing assumptions done, 4 Feb 94, FKK
;       added thick, symsize, and clear keyword Feb 96, W. Landsman HSTX
;               David Seed, HR Wallingford, d.seed@hrwallingford.co.uk
;       allow scalar specification of keywords, Mar 96, W. Landsman HSTX
;       added charthick keyword, June 96, W. Landsman HSTX
;       Made keyword names  left,right,top,bottom,center longer,
;                                 Aug 16, 2000, Kim Tolbert
;       Added ability to have regular text lines in addition to plot legend 
;       lines in legend.  If linestyle is -99 that item is left-justified.
;       Previously, only option for no sym/line was linestyle=-1, but then text
;       was lined up after sym/line column.    10 Oct 2000, Kim Tolbert
;       Make default value of thick = !P.thick  W. Landsman  Jan. 2001
;       Don't overwrite existing USERSYM definition  W. Landsman Mar. 2002

; NAME:
;	LEGENDTEST
; PURPOSE:
;	Demo program to show capabilities of  the legend procedure.
; CALLING SEQUENCE:
;	legendtest
; INPUTS:
;	none
; OPTIONAL INPUTS:
;	none
; KEYWORDS:
;	none
; OUTPUTS:
;	legends of note
; COMMON BLOCKS:
;	none
; SIDE EFFECTS:
;	Sets !20 font to symbol if PostScript and !p.font=0.
; RESTRICTIONS:
;	With the vectorfont test, you'll get different results for PostScript
;	depending on the value of !p.font.
; MODIFICATION HISTORY:
;	write, 27 Aug 92, F.K.Knight (knight@ll.mit.edu)
;	add test of /left,/right,/top,/bottom keywords, 21 June 93, FKK
;	update based on recent changes to legend, 7 Feb 94, FKK
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	LINEID_PLOT
; PURPOSE:
;	 Plot spectrum with specified line identifications annotated at the
;	 top of the plot.
;
; CALLING SEQUENCE:
;	lineid_plot, wave, flux, wline, text1, [ text2, 
;			LCHARSIZE=, LCHARTHICK=, EXTEND =, ...plotting keywords]
;
; INPUTS:
;	wave - wavelength vector for the plot
;	flux - flux vector
;	wline - wavelength vector of line identifications.  (only the lines 
;		between	the plot limits will be used)
;	text1 - string array of text to be used to annotate each line
;	text2 - (OPTIONAL) second string array of text to be used for
;		line annotation.  Since the text is written with
;		proportional spaced characters, TEXT2 can be used if
;		you want two sets of annotation to be alinged:
;
;		eg:	Cr IV  1390.009
;			Fe V   1390.049
;			Ni IV  1390.184
;			    instead of
;			Cr IV 1390.009
;			Fe V 1390.049
;			Ni IV 1390.184
;
; OPTIONAL KEYWORD INPUTS:
;	EXTEND - specifies that the annotated lines should have a dotted line 
;		extended to the spectrum to indicate the line position.  
;		EXTEND can be a scalar (applies to all lines) or a vector with
;		a different value for each line.  The value of EXTEND gives 
;		the line IDL plot line thickness for the dotted lines.
;		If EXTEND is a vector each dotted line can have a different 
;		thickness.  A value of 0 indicates that no dotted line is to 
;		be drawn. (default = scalar 0)
;	LCHARSIZE - the character size of the annotation for each line.
;		If can be a vector so that different lines are annotated with 
;		different size characters.  LCHARSIZE can be used to make 
;		stronger lines have a larger annotation. (default = scalar 1.0).
;	LCHARTHICK = the character thickness of the annotation for each line. 
;		It can be a vector so that different lines are annotated with 
;		characters of varying thickness.   LCHARTHICK can be used to 
;		make stronger lines have a bolder annotation. 
;		(default = !p.charthick)
;
;	LINEID_PLOT uses the _EXTRA facility to allow the use of any plotting
;	keywords (e.g. LINESTYLE, CHARSIZE) to be passed to the plot
;
; SIDE EFFECTS:
;	Program uses SET_VIEWPORT to set the !P.POSITION parameter to allow
;	room for the annotation.   This system variable can be reset to the 
;	default value by setting !P.POSTION=0 or typing SET_VIEWPORT with no 
;	parameters
;
; OPERATIONAL NOTES:
;	Once the program has completed, You can use OPLOT to draw additional
;	plots on the display. 
;
;	If your annotated characters are not being rotated properly,
;	try setting !P.FONT to a non zero value.
; EXAMPLE:
;	Annotate some interstellar lines between 1240 and 1270 A.
;
;	IDL> w = 1240+ indgen(300)*0.1    ;Make a wavelength vector
;	IDL> f = randomn(seed,300)        ;Random flux vector
;	IDL> id = ['N V','Si II','Si II','Si II']   ;Line IDs
;	IDL> wl = [1242.80,1260.42,1264.74,1265.00] ;Line positions
;	IDL> lineid_plot,w,f,wl,id,wl,/ext
;
;	Note that LINEID_PLOT is smart enough not to overlap the annotation
;	for the two closely spaced lines at 1264.74 and 1265.00	
; HISTORY:
;	version 1  D. Lindler Jan, 1992
;	Sept 27, 1993  DJL  fixed bug in /extend option
;	Apr 19, 1994 DJL corrected bug in sorting of charthick (cthick)
;	Sep 1996, W. Landsman,  added _EXTRA keyword, changed keyword names
;		CHARTHICK==>LCHARTHICK, CHARSIZE==>LCHARSIZE
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:   
;       LINTERP  
; PURPOSE: 
;       Linearly interpolate tabulated 1-d data from one grid to a new one.
; EXPLANATION:
;       The results of LINTERP are numerically equivalent to the RSI
;       INTERPOL() function, but note the following:
;         (1) LINTERP is a procedure rather than a function
;         (2) INTERPOL() extrapolates beyond the end points whereas LINTERP
;             truncates to the endpoints (or uses the MISSING keyword)
;         (3) LINTERP (unlike INTERPOL) uses the intrinsic INTERPOLATE function
;                 and thus may have a speed advantage
;         (4) LINTERP always converts the new grid vector to floating point 
;                (because INTERPOLATE does this) whereas INTERPOL() will 
;                 keep double precision if supplied.
;
;       Use QUADTERP for quadratic interpolation.
;
; CALLING SEQUENCE:
;       LINTERP, Xtab, Ytab, Xint, Yint, [MISSING =, /NoInterp ]   
;
; INPUT PARAMETERS: 
;       Xtab -  Vector containing the current independent variable grid.
;               Must be monotonic increasing or decreasing
;       Ytab -  Vector containing the current dependent variable values at 
;               the XTAB grid points.
;       Xint -  Scalar or vector containing the new independent variable grid 
;               points for which interpolated value(s) of the dependent 
;               variable are sought.    Note that -- due to a limitation of the
;               intrinsic INTERPOLATE() function -- Xint is always converted to
;               floating point internally.
;
; OUTPUT PARAMETERS:
;       Yint  -  Scalar or vector with the interpolated value(s) of the 
;               dependent variable at the XINT grid points.
;               YINT is double precision if XTAB or YTAB are double,
;               otherwise YINT is REAL*4
;
; OPTIONAL INPUT KEYWORD:
;       MISSING - Scalar specifying YINT value(s) to be assigned, when Xint
;               value(s) are outside of the range of Xtab.     Default is to
;               truncate the out of range YINT value(s) to the nearest value 
;               of YTAB.   See the help for the INTERPOLATE function.
;       /NoINTERP - If supplied then LINTERP returns the YTAB value(s) 
;               associated with the closest XTAB value(s)rather than 
;               interpolating.
;
; EXAMPLE:
;       To linearly interpolate from a spectrum wavelength-flux pair
;       WAVE, FLUX to another wavelength grid defined as:
;       WGRID = [1540., 1541., 1542., 1543., 1544, 1545.]
;   
;       IDL>  LINTERP, WAVE, FLUX, WGRID, FGRID  
;
;       FGRID will be a 6 element vector containing the values of FLUX 
;       linearly interpolated onto the WGRID wavelength scale
;
; PROCEDURE: 
;       Uses TABINV to calculate the effective index of the values
;       in Xint in the table Xtab.  The resulting index is used
;       with the intrinsic INTERPOLATE function to find the corresponding 
;       Yint value in Ytab.  Unless the MISSING keyword is supplied, out
;       of range Yint values are truncated to the nearest value of Ytab.
;
; PROCEDURES CALLED:
;       TABINV, ZPARCHECK
; MODIFICATION HISTORY:
;       Adapted from the IUE RDAF,  W. Landsman      October, 1988
;       Modified to use the new INTERPOLATE function        June, 1992
;       Modified to always return REAL*4             October, 1992
;       Added MISSING keyword                        August, 1993
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Added NoInterp keyword  W. Landsman      July 1999
;       Work for unsigned, 64 bit integers  W. Landsman  October 2001

; NAME: 
;	LIST_WITH_PATH
; PURPOSE: 
;	Search for files in a specified directory path.
; EXPLANATION:
;	Lists files in a set of default paths, similar to using FINDFILE,
;	except that a list of paths to be searched can be given.
;
; CALLING SEQUENCE: 
;	Result = LIST_WITH_PATH( FILENAME, PATHS )
;
; INPUTS: 
;	FILENAME   = Name of file to be searched for.  It may contain wildcard
;		     characters, e.g. "*.dat".
;
;	PATHS	   = One or more default paths to use in the search in case
;		     FILENAME does not contain a path itself.  The individual
;		     paths are separated by commas, although in UNIX, colons
;		     can also be used.  In other words, PATHS has the same
;		     format as !PATH, except that commas can be used as a
;		     separator regardless of operating system.  The current
;		     directory is always searched first, unless the keyword
;		     NOCURRENT is set.
;
;		     A leading $ can be used in any path to signal that what
;		     follows is an environmental variable, but the $ is not
;		     necessary.  (In VMS the $ can either be part of the path,
;		     or can signal logical names for compatibility with Unix.)
;		     Environmental variables can themselves contain multiple
;		     paths.
;
; OUTPUTS: 
;	The result of the function is a list of filenames.
; EXAMPLE:
;	FILENAME = ''
;	READ, 'File to open: ', FILENAME
;	FILE = LIST_WITH_PATH( FILENAME, 'SERTS_DATA', '.fix' )
;	IF FILE NE '' THEN ...
; PROCEDURE CALLS: 
;	BREAK_PATH, CONCAT_DIR
; Category    : 
;	Utilities, Operating_system
; REVISION HISTORY:
;	Version 1, William Thompson, GSFC, 3 November 1994
;	Documentation modified Wayne Landsman HSTX  November 1994
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;     LSF_ROTATE:
; PURPOSE:
;     Create a 1-d convolution kernel to broaden a spectrum from a rotating star
; EXPLANATION:
;     Can be used to derive the broadening effect (line spread function; LSF) 
;     due to  rotation on a synthetic stellar spectrum.     Assumes constant 
;     limb darkening across the disk.
; CALLING SEQUENCE
;     lsf = LSF_ROTATE(deltav, vsini, EPSILON=, VELGRID=)
; INPUT PARAMETERS:
;    deltaV - numeric scalar giving the step increment (in km/s) in the output 
;             rotation kernel.  
;    Vsini - the rotational velocity projected  along the line of sight (km/s)
; OUTPUT PARAMETERS:
;    LSF - The convolution kernel vector for the specified rotational velocity.
;          The  number of points in LSF will be always be odd (the kernel is
;          symmetric) and equal to  either ceil(2*Vsini/deltav) or 
;          ceil(2*Vsini/deltav) +1 (whichever number is odd).    LSF will 
;          always be of type FLOAT.
;
;          To actually compute the broadening. the spectrum should be convolved
;          with the rotational LSF. 
; OPTIONAL INPUT PARAMETERS:
;    Epsilon - numeric scalar giving the limb-darkening coefficient, 
;          default = 0.6 which is typical for  photospheric lines.    The
;          specific intensity I at any angle theta from the specific intensity
;          Icen at the center of the disk is given by:
;  
;          I = Icen*(1-epsilon*(1-cos(theta))
;                    
; OPTIONAL OUTPUT PARAMETER:
;     Velgrid - Vector with the same number of elements as LSF 
; EXAMPLE:
;    (1) Plot the LSF for a star rotating at 90 km/s in both velocity space and
;        for a central wavelength of 4300 A.    Compute the LSF every 3 km/s
;
;       IDL> lsf = lsf_rotate(3,90,velgrid=vel)      ;LSF will contain 61 pts
;       IDL> plot,vel,lsf                    ;Plot the LSF in velocity space
;       IDL> wgrid = 4300*(1+vel/3e5)       ;Speed of light = 3e5 km/s
;       IDL> oplot,wgrid,lsf                ;Plot in wavelength space
;
; NOTES:
;    Adapted from rotin3.f in the SYNSPEC software of Hubeny & Lanz 
;        http://tlusty.gsfc.nasa.gov/index.html.    Also see Eq. 17.12 in 
;    "The Observation and Analysis of Stellar Photospheres" by D. Gray (1992)
; REVISION HISTORY:
;    Written,   W. Landsman                November 2001

; NAME: 
;    LUMDIST
;       
; PURPOSE: 
;    Calculate luminosity distance (in Mpc) of an object given its redshift 
; EXPLANATION:
;    The luminosity distance in the Friedmann-Robertson-Walker model is 
;    taken from  Caroll, Press, and Turner (1992, ARAA, 30, 499), p. 511
;    Uses a closed form (Mattig equation) to compute the distance when the 
;    cosmological constant is zero.   Otherwise integrates the function using
;    QSIMP.	
; CALLING SEQUENCE: 
;    result = lumdist(z, [H0 = , k = , Omega_M =, Lambda0 = , q0 = ,/SILENT])
;      
; INPUTS:
;    z = redshift, positive scalar or vector
;
; OPTIONAL KEYWORD INPUTS: 
;    /SILENT - If set, the program will not display adopted cosmological
;        parameters at the terminal.
;    H0: Hubble parameter  in km/s/Mpc, default is 70
;
;        No more than two of the following four parameters should be
;        specified.   None of them need be specified -- the adopted defaults
;        are given.
;    k - curvature constant, normalized to the closure density.   Default is
;        0, indicating a flat universe
;    Omega_m -  Matter density, normalized to the closure density, default
;        is 0.3.   Must be non-negative
;    Lambda0 - Cosmological constant, normalized to the closure density,
;        default is 0.7
;    q0 - Deceleration parameter, numeric scalar = -R*(R'')/(R')^2, default
;        is -0.5
;       
; OUTPUTS:
;    The result of the function is the luminosity distance (in Mpc) for each 
;    input value of z.
;
; EXAMPLE:
;    (1) Plot the distance of a galaxy in Mpc as a function of redshift out 
;        to z = 5.0, assuming the default cosmology (Omega_m=0.3, Lambda = 0.7,
;        H0 = 70 km/s/Mpc)
;
;        IDL> z = findgen(50)/10.
;        IDL> plot,z,lumdist(z),xtit='z',ytit='Distance (Mpc)'
;
;        Now overplot the relation for zero cosmological constant and 
;        Omega_m=0.3
;        IDL> oplot,z,lumdist(z,lambda=0,omega=0.3),linestyle=1
; COMMENTS:
;    (1) Integrates using the IDL Astronomy Version procedure QSIMP.    (The 
;    intrinsic IDL QSIMP function is not called because of its ridiculous
;    restriction that only scalar arguments can be passed to the integrating
;    function.)
;    (2) Can fail to converge at high redshift for closed universes with
;    non-zero lambda.   This can presumably be fixed by replacing QSIMP with
;    an integrator that can handle a singularity 
; PROCEDURES CALLED:
;    COSMO_PARAM, QSIMP   
; REVISION HISTORY:
;    Written   W. Landsman        Raytheon ITSS       April 2000
;    Avoid integer overflow for more than 32767 redshifts  July 2001

; NAME:
;	MAG2FLUX
; PURPOSE:
;	Convert from magnitudes to flux (ergs/s/cm^2/A). 
; EXPLANATION:
;	Use FLUX2MAG() for the opposite direction.
;
; CALLING SEQUENCE:
;	flux = mag2flux( mag, [ zero_pt, ABwave = ] )
;
; INPUTS:
;	mag - scalar or vector of magnitudes
;
; OPTIONAL INPUT:
;	zero_pt - scalar giving the zero point level of the magnitude.
;		If not supplied then zero_pt = 21.1 (Code et al. 1976)
;               Ignored if the ABwave keyword is set.
;
; OPTIONAL KEYWORD INPUT:
;     ABwave - wavelength scalar or vector in Angstroms.   If supplied, then 
;              the input vector, mag, is assumed to contain Oke AB magnitudes
;              (Oke & Gunn 1983, ApJ, 266, 713)
;
; OUTPUT:
;	flux - scalar or vector flux vector, in erg cm-2 s-1 A-1
;              If the ABwave keyword is set, then the flux is given by
;
;              f = 10^(-0.4*(mag +2.406 + 4*alog10(ABwave)))     
;
;              Otherwise the flux is given by
;              f =  10^(-0.4*(mag + zero_pt))
;
; EXAMPLE:
;       Suppose one is given vectors of wavelengths and AB magnitudes, w (in
;       Angstroms) and mag.   Plot the spectrum in erg cm-2 s-1 A-1
;
;       IDL> plot, w, mag2flux(mag,ABwave = w)
; REVISION HISTORY:
;	Written    J. Hill        STX Co.       1988
;	Converted to IDL V5.0   W. Landsman   September 1997
;       Added ABwave keyword,   W. Landsman   September 1998

; NAME:
;      MAG2GEO()
;
; PURPOSE:
;     Convert from geomagnetic to geographic coordinates
;
; EXPLANATION:
; 
;     Converts from GEOMAGNETIC (latitude,longitude) to GEOGRAPHIC (latitude,
;    longitude).    (altitude remains the same)
;
; CALLING SEQUENCE:
;       gcoord=mag2geo(mcoord)
;
; INPUT:
;       mcoord = a 2-element array of magnetic [latitude,longitude], or an 
;                array [2,n] of n such coordinates.
;
; KEYWORD INPUTS:
;               None
;
; OUTPUT:
;       a 2-element array of geographic [latitude,longitude], or an array [2,n]
;            of n such coordinates                   
;
; COMMON BLOCKS:
;               None
;
; EXAMPLES:
;       IDL> gcoord=mag2geo([90,0])       ; coordinates of magnetic south pole
;       IDL> print,gcoord
;       79.300000      -71.409990
;
; MODIFICATION HISTORY:
;       Written by Pascal Saint-Hilaire (Saint-Hilaire@astro.phys.ethz.ch), 
;        May 2002

; NAME:
;       MAKE_2D
; PURPOSE:
;       Change from 1-d indexing to 2-d indexing
; EXPLANATION:
;       Convert an N element X vector, and an M element Y vector, into
;       N x M arrays giving all possible combination of X and Y pairs.
;       Useful for obtaining the X and Y positions of each element of
;       a regular grid.
;
; CALLING SEQUENCE:
;       MAKE_2D, X, Y, [ XX, YY ]
;
; INPUTS:
;       X - N element vector of X positions
;       Y - M element vector of Y positions
;
; OUTPUTS:
;       XX - N x M element array giving the X position at each pixel
;       YY - N x M element array giving the Y position of each pixel
;               If only 2 parameters are supplied then X and Y will be
;               updated to contain the output arrays
;
; EXAMPLE:
;       To obtain the X and Y position of each element of a 30 x 15 array
;
;       IDL> x = indgen(30)  &  y = indgen(15)     
;       IDL> make_2d, x, y 
; REVISION HISTORY:
;       Written,    Wayne Landsman    ST Systems Co.    May, 1988
;       Added /NOZERO keyword       W. Landsman         Mar, 1991
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Improved speed          P. Broos      July 2000

; NAME:
;       MAKE_ASTR
; PURPOSE:
;       Build an astrometry structure from input parameter values
; EXPLANATION:
;       This structure can be subsequently placed in a FITS header with 
;       PUTAST
;
; CALLING SEQUENCE:
;       MAKE_ASTR, astr, CD = , DELT =, CRPIX =, CRVAL =, CTYPE =,
;               LATPOLE = , LONGPOLE =, PROJP1 =, PROJP2 =    
;
; OUTPUT PARAMETER:
;       ASTR - Anonymous structure containing astrometry info.  See the 
;              documentation for EXTAST for descriptions of the individual
;              tags
;
; REQUIRED INPUT KEYWORDS
;       CRPIX - 2 element vector giving X and Y coordinates of reference pixel
;               (def = NAXIS/2).  VALUES MUST BE IN FITS CONVENTION (first pixel
;               is [1,1]) AND NOT IDL CONVENTION (first pixel is [0,0]).
;       CRVAL - 2 element double precision vector giving R.A. and DEC of 
;               reference pixel in DEGREES
; OPTIONAL INPUT KEYWORDS
;       CD -  2 x 2 array containing the astrometry parameters CD1_1 CD1_2
;              in DEGREES/PIXEL                                CD2_1 CD2_2
;       DELT - 2 element vector giving physical increment at reference pixel
;              CDELT default = [1.0D, 1.0D].
;       CTYPE - 2 element string vector giving projection types, default
;              ['RA---TAN','DEC--TAN']
;       LATPOLE - Scalar latitude of the north pole, default = 0
;       LONGPOLE - scalar longitude of north pole, default = 180
;                Note that the default value of 180 is valid only for zenithal
;               projections; it should be set to PV2_1 for conic projections,
;               and zero for other projections.
;       PROJP1 - Scalar parameter needed in some projections, usually 
;                corresponding to FITS keyword PV2_1, default = 0.0
;       PROJP2 - Scalar parameter needed in some projections, usually 
;                corresponding to FITS keyword PV2_2, default = 0.0
;
; NOTES:
;       (1) 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).
;       (2) The name of the keyword for the CDELT parameter is DELT because
;               the IDL keyword CDELT would conflict with the CD keyword
;       (3) The astrometry structure definition was slightly modified in 
;               July 2003; all angles are now double precision, and the 
;               LATPOLE tag was added.
; REVISION HISTORY:
;       Written by   W. Landsman              Mar. 1994
;       Converted to IDL V5.0                 Jun  1998
;       Added LATPOLE, all angles double precision  W. Landsman July 2003

; NAME:
;       MATCH
; PURPOSE:
;       Routine to match values in two vectors.
;
; CALLING SEQUENCE:
;       match, a, b, suba, subb, [ COUNT =, /SORT ]
;
; INPUTS:
;       a,b - two vectors to match elements, numeric or string data types
;
; OUTPUTS:
;       suba - subscripts of elements in vector a with a match
;               in vector b
;       subb - subscripts of the positions of the elements in
;               vector b with matchs in vector a.
;
;       suba and subb are ordered such that a[suba] equals b[subb]
;
; OPTIONAL INPUT KEYWORD:
;       /SORT - By default, MATCH uses two different algorithm: (1) the 
;               /REVERSE_INDICES keyword to HISTOGRAM is used for integer data,
;               while a sorting algorithm is used for non-integer data.   The
;               histogram algorithm is usually faster, except when the input
;               vectors are sparse and contain very large numbers, possibly
;               causing memory problems.   Use the /SORT keyword to always use
;               the sort algorithm.
;               
; OPTIONAL KEYWORD OUTPUT:
;       COUNT - set to the number of matches, integer scalar
;
; SIDE EFFECTS:
;       The obsolete system variable !ERR is set to the number of matches;
;       however, the use !ERR is deprecated in favor of the COUNT keyword 
;
; RESTRICTIONS:
;       The vectors a and b should not have duplicate values within them.
;       You can use rem_dup function to remove duplicate values
;       in a vector
;
; EXAMPLE:
;       If a = [3,5,7,9,11]   & b = [5,6,7,8,9,10]
;       then 
;               IDL> match, a, b, suba, subb, COUNT = count
;
;       will give suba = [1,2,3], subb = [0,2,4],  COUNT = 3
;       and       suba[a] = subb[b] = [5,7,9]
;
; 
; METHOD:
;       For non-integer data types, the two input vectors are combined and
;       sorted and the consecutive equal elements are identified.   For integer
;       data types, the /REVERSE_INDICES keyword to HISTOGRAM of each array
;       is used to identify where the two arrays have elements in common.   
; HISTORY:
;       D. Lindler  Mar. 1986.
;       Fixed "indgen" call for very large arrays   W. Landsman  Sep 1991
;       Added COUNT keyword    W. Landsman   Sep. 1992
;       Fixed case where single element array supplied   W. Landsman Aug 95
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Use a HISTOGRAM algorithm for integer vector inputs for improved 
;             performance                W. Landsman         March 2000
;       Work again for strings           W. Landsman         April 2000
;       Use size(/type)                  W. Landsman         December 2002
;       Work for scalar integer input    W. Landsman         June 2003

; NAME:
;	MAX_ENTROPY
;
; PURPOSE:
;	Deconvolution of data by Maximum Entropy analysis, given the PSF
; EXPLANATION:
;	Deconvolution of data by Maximum Entropy analysis, given the 
;	instrument point spread response function (spatially invariant psf).
;	Data can be an observed image or spectrum, result is always positive.
;	Default is convolutions using FFT (faster when image size = power of 2).
;
; CALLING SEQUENCE:
;	for i=1,Niter do begin
;	Max_Entropy, image_data, psf, image_deconv, multipliers, FT_PSF=psf_ft
;
; INPUTS:
;	data = observed image or spectrum, should be mostly positive,
;					with mean sky (background) near zero.
;	psf = Point Spread Function of instrument (response to point source,
;							must sum to unity).
;	deconv = result of previous call to Max_Entropy,
;	multipliers = the Lagrange multipliers of max.entropy theory
;		(on first call, set = 0, giving flat first result).
;
; OUTPUTS:
;	deconv = deconvolution result of one more iteration by Max_Entropy.
;	multipliers = the Lagrange multipliers saved for next iteration.
;
; OPTIONAL INPUT KEYWORDS:
;	FT_PSF = passes (out/in) the Fourier transform of the PSF,
;		so that it can be reused for the next time procedure is called,
;      /NO_FT overrides the use of FFT, using the IDL function convol() instead.
;      /LINEAR switches to Linear convergence mode, much slower than the
;		default Logarithmic convergence mode.
;	LOGMIN = minimum value constraint for taking Logarithms (default=1.e-9).
; EXTERNAL CALLS:
;	function convolve( image, psf ) for convolutions using FFT or otherwise.
; METHOD:
;	Iteration with PSF to maximize entropy of solution image with
;	constraint that the solution convolved with PSF fits data image.
;	Based on paper by Hollis, Dorband, Yusef-Zadeh, Ap.J. Feb.1992,
;	which refers to Agmon, Alhassid, Levine, J.Comp.Phys. 1979.
;
;       A more elaborate image deconvolution program using maximum entropy is 
;       available at 
;       http://sohowww.nascom.nasa.gov/solarsoft/gen/idl/image/image_deconvolve.pro
; HISTORY:  
;	written by Frank Varosi at NASA/GSFC, 1992.
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	MAX_LIKELIHOOD
;
; PURPOSE:
;	Maximum likelihood deconvolution of an image or a spectrum.
; EXPLANATION:
; 	Deconvolution of an observed image (or spectrum) given the 
;	instrument point spread response function (spatially invariant psf).
;	Performs iteration based on the Maximum Likelihood solution for
;	the restoration of a blurred image (or spectrum) with additive noise.
;	Maximum Likelihood formulation can assume Poisson noise statistics
;	or Gaussian additive noise, yielding two types of iteration.
;
; CALLING SEQUENCE:
;	for i=1,Niter do Max_Likelihood, data, psf, deconv, FT_PSF=psf_ft
;
; INPUTS PARAMETERS:
;	data = observed image or spectrum, should be mostly positive,
;				with mean sky (background) near zero.
;	psf = Point Spread Function of the observing instrument,
;				(response to a point source, must sum to unity).
; INPUT/OUTPUT PARAMETERS:
;	deconv = as input: the result of previous call to Max_Likelihood,
;		(initial guess on first call, default = average of data),
;		as output: result of one more iteration by Max_Likelihood.
;	Re_conv = (optional) the current deconv image reconvolved with PSF
;		for use in next iteration and to check convergence.
;
; OPTIONAL INPUT KEYWORDS:
;      /GAUSSIAN causes max-likelihood iteration for Gaussian additive noise
;		to be used,  otherwise the default is Poisson statistics.
;	FT_PSF = passes (out/in) the Fourier transform of the PSF,
;		so that it can be reused for the next time procedure is called,
;      /NO_FT overrides the use of FFT, using the IDL function convol() instead.
;	POSITIVITY_EPS = value of epsilon passed to function positivity,
;			default = -1 which means no action (identity).
;	UNDERFLOW_ZERO = cutoff to consider as zero, if numbers less than this.
;
; EXTERNAL CALLS:
;	function convolve( image, psf ) for convolutions using FFT or otherwise.
;	function positivity( image, EPS= ) to make image positive.
;
; METHOD:
;	Maximum Likelihood solution is a fixed point of an iterative eq.
;	(derived by setting partial derivatives of Log(Likelihood) to zero).
;	Poisson noise case was derived by Richardson(1972) & Lucy(1974).
;	Gaussian noise case is similar with subtraction instead of division.
; HISTORY:
;	written: Frank Varosi at NASA/GSFC, 1992.
;	F.V. 1993, added optional arg. Re_conv (to avoid doing it twice).
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	MEANCLIP
;
; PURPOSE:
;	Computes an iteratively sigma-clipped mean on a data set
; EXPLANATION:
;       Clipping is done about median, but mean is returned.
;       Called by SKYADJ_CUBE
;
; CATEGORY:
;	Statistics
;
; CALLING SEQUENCE:
;	MEANCLIP, Data, Mean, Sigma
;
; INPUT POSITIONAL PARAMETERS:
;	Data: 	  Input data, any numeric array
;	
; OUTPUT POSITIONAL PARAMETERS:
;       Mean:     N-sigma clipped mean.
;       Sigma:    Standard deviation of remaining pixels.
;
; INPUT KEYWORD PARAMETERS:
;       CLIPSIG:  Number of sigma at which to clip.  Default=3
;	MAXITER:  Ceiling on number of clipping iterations.  Default=5
;       CONVERGE_NUM:  If the proportion of rejected pixels is less
;           than this fraction, the iterations stop.  Default=0.02, i.e.,
;           iteration stops if fewer than 2% of pixels excluded.
;       /VERBOSE:  Set this flag to get messages.
;
; OUTPUT KEYWORD PARAMETER:
;       SUBS:     Subscript array for pixels finally used.
;
;
; MODIFICATION HISTORY:
; 	Written by:	RSH, RITSS, 21 Oct 98
;       20 Jan 99 - Added SUBS, fixed misplaced paren on float call, 
;                   improved doc.  RSH

; NAME:
;       MEDARR
; PURPOSE:
;       Compute the median at each pixel across a set of 2-d images
; EXPLANATION:
;       Each pixel in the output array contains  the median of the 
;       corresponding pixels in the input arrays.   Useful, for example to 
;       combine a stack of CCD images, while removing cosmic ray hits.
;
;       This routine became partially obsolete in V5.6 with the introduction
;       of the DIMENSION keyword to the intrinsic MEDIAN() function.   However,
;       it is  still useful if a input mask is needed (though it is much 
;       faster to set invalid pixels to NaN values.)
; CALLING SEQUENCE:
;       MEDARR, inarr, outarr, [ mask, output_mask ]
; INPUTS:
;       inarr  -- A three dimensional array containing the input arrays to 
;                 combine together.  Each of the input arrays must be two 
;                 dimensional and must have the same dimensions.  These arrays
;                 should then be stacked together into a single 3-D array,
;                 creating INARR.
;
; OPTIONAL INPUT:
;       mask   -- Same structure as inarr, byte array with 1b where
;                 pixels are to be included, 0b where they are to be
;                 excluded.    For floating point images, it is much faster to 
;                 set masked pixels in inarr equal to !VALUES.F_NAN (see below),
;                 rather than use the mask parameter.
;                
; OUTPUTS:
;       outarr -- The output array.  It will have dimensions equal to the
;                 first two dimensions of the input array.
;
; OPTIONAL OUPUT:
;       output_mask -- Same structure as outarr, byte array with 1b
;                      pixels are valid, 0b where all the input pixels
;                      have been masked out.
; RESTRICTIONS:
;        Prior to V5.6, this procedure was *SLOW* because it had to loop over 
;        each pixel of the image.   See notes below about an alternative with 
;        CALL_EXTERNAL.
;
; EXAMPLE:
;       Suppose one wants to combine three floating point 1024 x 1024 bias 
;       frames which have been read into the IDL variables im1,im2,im3
;
;       IDL> bigim = fltarr(1024,1024,3)        ;Create big array to hold images
;       IDL> bigim(0,0,0) = im1 & bigim(0,0,1) = im2 & bigim(0,0,2) = im2  
;       IDL> medarr, bigim, avgbias
;
;       The variable avgbias will be the desired 1024x 1024 float image.
; PROCEDURE:
;       A scalar median function over the third dimension is looped over 
;       each pixel of the first two dimensions.   The /EVEN keyword is used
;       with MEDIAN (which averages the two middle values), since this avoids 
;       biasing the output for an even number of images.
;
;       Any values set to NAN (not a number) are ignored when computing the
;       median.    If all values for a pixel location are NAN, then the median
;       is also returned as NAN.
;
;       MEDARR is also available as a C procedure linked to IDL via
;       CALL_EXTERNAL (but without the mask parameter).   The callable C 
;       version is 2-3 times faster for large  (~ 500 x 500 x 7) images.   
;       Contact W. Landsman (landsman@mpb.gsfc.nasa.gov) for the C program
; MODIFICATION HISTORY:
;       Written by Michael R. Greason, STX, 12 June 1990.
;       Don't use MEDIAN function for even number of images.
;          W. Landsman Sep 1996
;       Mask added.  RS Hill, HSTX, 13 Mar. 1997
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Use /EVEN keyword to MEDIAN    W. Landsman  September 1997
;       Rearranged code for faster execution   W. Landsman January 1998
;       Faster execution for odd number of images   W. Landsman July 2000
;       V5.4 fix for change in SIZE() definition of undefined variable 
;                W. Landsman/E. Young   May 2001
;       Use MEDIAN(/DIMEN) for V5.6 or later   W. Landsman   November 2002
;       Use keyword_set() instead of ARG_present() to test for presence of mask
;           parameter  D. Hanish/W. Landsman   June 2003

; NAME:
;       MEDSMOOTH
;
; PURPOSE:
;       Median smoothing of a vector, including points near its ends.
;
; CALLING SEQUENCE:
;       SMOOTHED = MEDSMOOTH( VECTOR, WINDOW_WIDTH )
;
; INPUTS:
;       VECTOR  = The (1-d numeric) vector to be smoothed
;       WINDOW = Odd integer giving the full width of the window over which 
;               the median is determined for each point.     (If WINDOW is
;               specified as an even number, then the effect is the same as
;               using WINDOW+1)   
;
; OUTPUT:
;       Function returns the smoothed vector
;
; PROCEDURE:
;       Each point is replaced by the median of the nearest WINDOW of points.
;       The width of the window shrinks towards the ends of the vector, so that
;       only the first and last points are not filtered. These points are 
;       replaced by forecasting from smoothed interior points.
;
; EXAMPLE:
;       Create a vector with isolated high points near its ends
;       IDL> a = randomn(seed,40) & a[1] = 10  & a[38] = 10
;       Now do median smoothing with a 7 point window 
;       IDL> b = medsmooth(a,7)
;       Note that, unlike MEDIAN(), that MEDSMOOTH will remove the isolated
;       high points near the ends.
; REVISION HISTORY:
;       Written, H. Freudenreich, STX, 12/89
;       H.Freudenreich, 8/90: took care of end-points by shrinking window.
;       Speed up using vector median when possible  W. Landsman February 2002

; NAME:
;	MID_RD_DISDSC
; PURPOSE:
;	Get a MIDAS directory descriptor from a MIDAS BDF. 
; EXPLANATION:
;	Note: PORTABLE MIDAS.
;
; CALLING SEQUENCE:
;	MID_RD_DIRDSC,IMAGE,DSCNAME,DSCVALUE
;
; INPUTS:
;	IMAGE = Filename or Logical Unit Number.
;		* If a filename is given, the file will be opened and closed 
;		using a local LUN.  The filename is that of the MIDAS image, 
;		without extension (.BDF will is assumed) or version number 
;		(latest version is assumed).
;		* If a LUN is given, the file associated with that LUN will be
;		 used.
;	DSCNAME = Name of the Descriptor wanted.
;
; OUTPUTS:
;	DSCVALUE = Value of the directory descriptor wanted.
;
; ALGORITHM:
;	0) Check inputs and set error handling.
;	1) Open file for access using the access method indicated by the type of
;		the input parameter IMAGE.
;	2) Find the descriptor by name (string type).
;	3) Decode the 30 byte descriptor block.
;	4) Use #3 to find descriptor data area.
;	5) Convert descriptor data as indicated by descriptor block information.
;	6) Terminate file access as is proper for the type of parameter IMAGE.
;
; RESTRICTIONS:
;	   1) There must be only one FCB and it must be in VBN 1.
;	2) The LDBs must begin in VBN 2.
;	3) All descriptors must be in the first LDB.
;	4) Note: .bdf and .tbl extensions assumed lower case.
;
; AUTHORS:
;   SAV  - Stephen A. Voels, USM/DAN
;
; MODIFICATION HISTORY:
;	FEB 1989 SAV  Initial programming.
;	MAY 1989 FM   Change of name of routine; some minor alterations.
;	AUG 1990 FM   Updates for Portable MIDAS (noted as comments below).
;	FEB 1991 FM   Conversion to V. 2 of IDL, Unix.
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	MID_RD_IMAGE
;
; PURPOSE:
;	Get a pixel matrix and some support information from a MIDAS file.
;
; CALLING SEQUENCE:
;	MID_RD_IMAGE,IMAGE,DATA,NAXIS,NPIX
;
;INPUTS:
;	IMAGE = Filename or Logical Unit Number.
;	* If a filename is given, the file will be opened and closed using a
;		local LUN.  The filename is that of the MIDAS image, without
;		extension (.BDF will is assumed) or version number (latest 
;		version is assumed).
;	* If a LUN is given, the file associated with that LUN will be used.
;
; OUTPUTS:
;	NAXIS = Number of dimensions in MIDAS image. I*4 values.
;	NPIX  = Array containing the dimensions. I*4 values.
;	DATA  = Array containing the MIDAS image. Dimensions are defined by
;		NAXIS and NPIX. R*4 values.
;
; ALGORITHM:
;	0) Check inputs and set error handling.
;	1) Open file for access using the access method indicated by the type of
;	the input parameter IMAGE.
;	2) Get the descriptors of the IMAGE.
;		a) NAXIS set the output parameter NAXIS to this value.
;		b) NPIX  set the output parameter NPIX to this value.
;	3) Locate the pixel data start block
;	4) Load pixel data into output parameter DATA
;	5) Terminate file access as is proper for the type of parameter IMAGE.
;
; RESTRICTIONS:
;	1) There must be only one FCB and it must be in VBN 1.
;	2) The LDBs must begin in VBN 2.
;	3) All descriptors must be in the first LDB.
;	4) Currently only works for real data, does not check to see if this is
;		true or not.
;	5) Midas file extensions (.bdf, .tbl) assumed lower case.
;
;AUTHORS:
;	FM   - F. Murtagh, ST-ECF
;	SAV  - Stephen A. Voels, USM/DAN
;
;MODIFICATION HISTORY:
;	OCT 1988 FM   Initial programing and decoding of MIDAS files.
;	FEB 1989 SAV  Name and calling sequence change.
;		General reprograming for effeciency and modularity.
;		Additional parameter checking.
;	MAY 1989 FM   Minor change for case of 1-d images. 
;	FEB 1991 FM   Conversion to V. 2 IDL, Unix.
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	MID_RD_TABLE
;
; PURPOSE:
;	Open and read data from a MIDAS table.
;
; CALLING SEQUENCE:
;	MID_RD_TABLE,table,ncol,nrow,data
;
; INPUTS:
;	Table =  file name of MIDAS table or Logical Unit Number.  
;	* If a filename is given, the file will be opened and closed
;		using a local LUN. An extension -- not to be
;		supplied -- of .TBL is assumed.  No version number is
;		allowed: the most recent version is used.  
;	* If an LUN is given, the file associated with that LUN will
;		be used.
;
; OUTPUTS:
;	Ncol =   number of columns in the input MIDAS table.  Long
;		integer (I*4).
;	Nrow =   number of rows in the MIDAS table. Long integer (I*4).
;	Data =   table data.  Floating (R*4).  Data is of dimensions
;		nrow*ncol.  The select column in the MIDAS table is 
;		disregarded.
;
; ALGORITHM:
;	We first consider the File Control Block of the MIDAS table file
;	to determine the start of descriptor information and the start of
;	the data. 
;	Next we consider the Descriptor Directory Entry for `tblcontr' (the 
;	number of columns and rows allocated; followed by the number of 
;	columns and rows in the actual table).
;	Finally we read the data values.
;
; RESTRICTIONS: 
;	Real data handled only.  Midas table SELECTION mechanism is ignored.
;	Also ignored are missing values.  
;	Midas file extensions (.tbl) assumed lower case.
;
; AUTHORS:
;	FM  -  Fionn Murtagh, ST-ECF, Munich.
;	
; MODIFICATION HISTORY:
;	OCT 1988  FM  Initial programming.
;	MAY 1989  FM  Name change, debugging, etc.
;	FEB 1991  FM  Conversion to V.2 IDL, Unix.
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	MID_UP_IMAGE
;
; PURPOSE:
;	Get a pixel matrix and some support information from a MIDAS file.
; EXPLANATION:
;	Allows updating of data, using DATA parameter.
;
; CALLING SEQUENCE:
;	MID_UP_IMAGE,IMAGE,DATA,NAXIS,NPIX
;
; INPUTS:
;	IMAGE = Filename or Logical Unit Number.
;	* If a filename is given, the file will be opened and closed using a
;		local LUN.  The filename is that of the MIDAS image, without
;		extension (.BDF will is assumed) or version number (latest 
;		version is assumed).
;	* If a LUN is given, the file associated with that LUN will be used.
;
; OUTPUTS:
;	NAXIS = Number of dimensions in MIDAS image. I*4 values.
;	NPIX  = Array containing the dimensions of the data to be written into
;		the MIDAS image. Must be compatible with (i.e. smaller than or
;		equal to the corresponding dimensions of) the latter. 
;		I*4 values.
;	DATA  = Array to be written into the MIDAS image. Dimensions are 
;		defined by NAXIS and NPIX. R*4 values.
;
; ALGORITHM:
;	0) Check inputs and set error handling.
;	1) Open file for access using the access method indicated by the type of
;		the input parameter IMAGE.
;	2) Get the descriptors of the IMAGE.
;		a) NAXIS set the output parameter NAXIS to this value.
;		b) NPIX  set the output parameter NPIX to this value.
;	3) Locate the pixel data start block
;	4) Load pixel data into output parameter DATA
;	5) Check consistency of dimensions of data array to be written, and
;		image dimensions; then write data array into image.
;	6) Terminate file access as is proper for the type of parameter IMAGE.
;
; RESTRICTIONS:
;	1) There must be only one FCB and it must be in VBN 1.
;	2) The LDBs must begin in VBN 2.
;	3) All descriptors must be in the first LDB.
;	4) Currently only works for real data, does not check to see if this is
;		true or not.
;	5) Midas extensions (.bdf, .tbl) assumed lower case.
;
; AUTHORS:
;	FM   - F. Murtagh, ST-ECF
;	SAV  - Stephen A. Voels, USM/DAN
;
; MODIFICATION HISTORY:
;	MAY 1989  FM   Initial programming.
;	FEB 1991  FM   Conversion to v.2 IDL, Unix.
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	MID_UP_TABLE
;
; PURPOSE:
;	Open and update data from a MIDAS table.
;
; CALLING SEQUENCE:
;	MID_UP_TABLE,table,ncol,nrow,data
;
; INPUTS:
;	Table =  file name of MIDAS table or Logical Unit Number.  
;		* If a filename is given, the file will be opened and closed 
;		using a local LUN.  An extension -- not to be
;		supplied -- of .TBL is assumed.  No version number is
;		allowed: the most recent version is used.  
;		* If an LUN is given, the file associated with that LUN will be 
;		used.
;	Ncol =   number of columns in the array to be written into the 
;		MIDAS table.  Long integer (I*4).  Must be less than or
;		equal to the number of columns in the MIDAS table.
;		"Ncol" and "nrow" are checked for consistency only.
;	Nrow =   number of rows in the array to be written into the MIDAS 
;		table. Long integer (I*4).  Must be less than or equal to
;		the number of rows in the MIDAS table.
;		"Ncol" and "nrow" are checked for consistency only.
;	Data =   array of data to be written into the MIDAS table.  Floating 
;		(R*4).  Data is of dimensions nrow*ncol.  The select column 
;		in the MIDAS table is disregarded.
;
; RESTRICTIONS:
;	Dimensions of the array to be written into the MIDAS table must be
;	less than or equal to the corresponding dimensions of the latter.
;	Note that in the case of smaller dimensions, only part of the given
;	MIDAS table in altered (i.e. the 'upper left hand corner').
;	No changes in the MIDAS table descriptors are carried out.  No 
;	changes in the MIDAS table 'select' are carried out.
;	Real data handled only.
;
;	Midas extensions (.tbl) in lower case.
;
; OUTPUTS:
;	None.
;
; ALGORITHM:
;	We first consider the File Control Block of the MIDAS table file
;	to determine the start of descriptor information and the start of
;	the data. 
;	Next we consider the Descriptor Directory Entry for `tblcontr' (the 
;	number of columns and rows allocated; followed by the number of 
;	columns and rows in the actual table).
;	We check consistency between input array dimensions and the dimensions
;	of the MIDAS table into which the array is to be written.
;	Finally we carry out the writing of the data values.
;
; EXAMPLE:
;	Given two MIDAS tables, PSF.TBL and PSF2.TBL, of the same dimensions;
;	we wish to overwrite PSF2 with the contents of PSF.
;
;	MID_RD_TABLE,'PSF',NC,NR,DAT
;	DATTR = TRANSPOSE(DAT)
;	MID_UP_TABLE,'PSF2',NC,NR,DATTR
;
; AUTHORS:
;	FM - Fionn Murtagh, ST-ECF, Munich.
;
;MODIFICATION HISTORY:
;	OCT 1988  FM  Initial programming and decoding of MIDAS files.
;	MAY 1989  FM  Name of routine changed; allowance made for LUN instead
;		of table name; bug fixes.
;	FEB 1991  FM  Conversion to V. 2, IDL, Unix.
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;       MINF_BRACKET
; PURPOSE:
;       Bracket a local minimum of a 1-D function with 3 points,
; EXPLANATION:
;       Brackets a local minimum of a 1-d function with 3 points,
;       thus ensuring that a minimum exists somewhere in the interval.
;       This routine assumes that the function has a minimum somewhere....
;       Routine can also be applied to a scalar function of many variables,
;       for such case the local minimum in a specified direction is bracketed,
;       This routine is called by minF_conj_grad, to bracket minimum in the 
;       direction of the conjugate gradient of function of many variables
; CALLING EXAMPLE:
;       xa=0  & xb=1                                    
;       minF_bracket, xa,xb,xc, fa,fb,fc, FUNC_NAME="name"      ;for 1-D func.
;  or:
;       minF_bracket, xa,xb,xc, fa,fb,fc, FUNC="name",     $
;                                         POINT=[0,1,1],   $
;                                         DIRECTION=[2,1,1]     ;for 3-D func.
; INPUTS:
;       xa = scalar, guess for point bracketing location of minimum.
;       xb = scalar, second guess for point bracketing location of minimum.
; KEYWORDS:
;       FUNC_NAME = function name (string)
;               Calling mechanism should be:  F = func_name( px )
;               where:
;                       px = scalar or vector of independent variables, input.
;                       F = scalar value of function at px.
;       POINT_NDIM = when working with function of N variables,
;               use this keyword to specify the starting point in N-dim space.
;               Default = 0, which assumes function is 1-D.
;       DIRECTION = when working with function of N variables,
;               use this keyword to specify the direction in N-dim space
;               along which to bracket the local minimum, (default=1 for 1-D).
;               (xa,xb,xc) are then relative distances from POINT_NDIM.
; OUTPUTS:
;       xa,xb,xc = scalars, 3 points which bracket location of minimum,
;               that is, f(xb) < f(xa) and f(xb) < f(xc), so minimum exists.
;               When working with function of N variables
;               (xa,xb,xc) are then relative distances from POINT_NDIM,
;               in the direction specified by keyword DIRECTION,
;               with scale factor given by magnitude of DIRECTION.
; OPTIONAL OUTPUT:
;       fa,fb,fc = value of function at 3 points which bracket the minimum,
;                       again note that fb < fa and fb < fc if minimum exists.
; PROCEDURE:
;       algorithm from Numerical Recipes (by Press, et al.), sec.10.1 (p.281).
; MODIFICATION HISTORY:
;       Written, Frank Varosi NASA/GSFC 1992.
;       Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;        MINF_CONJ_GRAD
; PURPOSE:
;       Find the local minimum of a scalar function using conjugate gradient
; EXPLANATION:
;       Find the local minimum of a scalar function of several variables using 
;       the Conjugate Gradient method (Fletcher-Reeves-Polak-Ribiere algorithm).
;       Function may be anything with computable partial derivatives.
;       Each call to minF_conj_grad performs one iteration of algorithm,
;       and returns an N-dim point closer to the local minimum of function.
; CALLING EXAMPLE:
;       p_min = replicate( 1, N_dim )
;       minF_conj_grad, p_min, f_min, conv_factor, FUNC_NAME="name",/INITIALIZE
;
;       while (conv_factor GT 0) do begin
;               minF_conj_grad, p_min, f_min, conv_factor, FUNC_NAME="name"
;       endwhile
; INPUTS:
;       p_min = vector of independent variables, location of minimum point
;               obtained from previous call to minF_conj_grad, (or first guess).
; KEYWORDS:
;       FUNC_NAME = function name (string)
;               Calling mechanism should be:  F = func_name( px, gradient )
;         where:
;               F = scalar value of function at px.
;               px = vector of independent variables, input.
;               gradient = vector of partial derivatives of the function
;                       with respect to independent variables, evaluated at px.
;                       This is an optional output parameter:
;                       gradient should not be calculated if parameter is not
;                       supplied in call (Unless you want to waste some time).
;      /INIT must be specified on first call (whenever p_min is a guess),
;                       to initialize the iteration scheme of algorithm.
;      /USE_DERIV causes the directional derivative of function to be used
;                       in the 1-D minimization part of algorithm
;                       (default is not to use directional derivative).
;       TOLERANCE = desired accuracy of minimum location, default=sqrt(1.e-7).
;      /QUADRATIC runs simpler version which works only for quadratic function.
; OUTPUTS:
;       p_min = vector giving improved solution for location of minimum point.
;       f_min = value of function at p_min.
;       conv_factor = gives the current rate of convergence (change in value),
;                       iteration should be stopped when rate gets near zero.
; EXTERNAL CALLS:
;       pro minF_bracket,  to find 3 points which bracket the minimum in 1-D.
;       pro minF_parabolic,  to find minimum point in 1-D.
;       pro minF_parabol_D,  to find minimum point in 1-D, using derivatives.
; COMMON BLOCKS:
;       common minf_conj_grad, grad_conj, grad_save, gs_norm
;       (to keep conjugate gradient, gradient and norm from previous iteration)
; PROCEDURE:
;       Algorithm adapted from Numerical Recipes, sec.10.6 (p.305).
;       Conjugate gradient is computed from gradient, which then gives
;       the best direction (in N-dim space) in which to proceed to find
;       the minimum point. The function is then minimized along
;       this direction of conjugate gradient (a 1-D minimization).
;       The algorithm is repeated starting at the new point by calling again.
; MODIFICATION HISTORY:
;       Written, Frank Varosi NASA/GSFC 1992.
;       Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;       MINF_PARABOLIC
; PURPOSE:
;       Minimize a function using Brent's method with parabolic interpolation
; EXPLANATION:
;       Find a local minimum of a 1-D function up to specified tolerance.
;       This routine assumes that the function has a minimum nearby.
;       (recommend first calling minF_bracket, xa,xb,xc, to bracket minimum).
;       Routine can also be applied to a scalar function of many variables,
;       for such case the local minimum in a specified direction is found,
;       This routine is called by minF_conj_grad, to locate minimum in the 
;       direction of the conjugate gradient of function of many variables.
;
; CALLING EXAMPLES:
;       minF_parabolic, xa,xb,xc, xmin, fmin, FUNC_NAME="name"  ;for 1-D func.
;  or:
;       minF_parabolic, xa,xb,xc, xmin, fmin, FUNC="name", $
;                                         POINT=[0,1,1],   $
;                                         DIRECTION=[2,1,1]     ;for 3-D func.
; INPUTS:
;       xa,xb,xc = scalars, 3 points which bracket location of minimum,
;               that is, f(xb) < f(xa) and f(xb) < f(xc), so minimum exists.
;               When working with function of N variables
;               (xa,xb,xc) are then relative distances from POINT_NDIM,
;               in the direction specified by keyword DIRECTION,
;               with scale factor given by magnitude of DIRECTION.
; INPUT KEYWORDS:
;      FUNC_NAME = function name (string)
;               Calling mechanism should be:  F = func_name( px )
;               where:
;                       px = scalar or vector of independent variables, input.
;                       F = scalar value of function at px.
;
;      POINT_NDIM = when working with function of N variables,
;               use this keyword to specify the starting point in N-dim space.
;               Default = 0, which assumes function is 1-D.
;      DIRECTION = when working with function of N variables,
;               use this keyword to specify the direction in N-dim space
;               along which to bracket the local minimum, (default=1 for 1-D).
;               (xa, xb, xc, x_min are then relative distances from POINT_NDIM)
;      MAX_ITER = maximum allowed number iterations, default=100.
;      TOLERANCE = desired accuracy of minimum location, default=sqrt(1.e-7).
; OUTPUTS:
;       xmin = estimated location of minimum.
;               When working with function of N variables,
;               xmin is the relative distance from POINT_NDIM,
;               in the direction specified by keyword DIRECTION,
;               with scale factor given by magnitude of DIRECTION,
;               so that min. Loc. Pmin = Point_Ndim + xmin * Direction.
;       fmin = value of function at xmin (or Pmin).
; PROCEDURE:
;       Brent's method to minimize a function by using parabolic interpolation.
;       Based on function BRENT in Numerical Recipes in FORTRAN (Press et al. 
;       1992),  sec.10.2 (p. 397).
; MODIFICATION HISTORY:
;       Written, Frank Varosi NASA/GSFC 1992.
;       Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;       MINF_PARABOL_D
; PURPOSE:
;       Minimize a function using a modified  Brent's method with derivatives
; EXPLANATION:
;       Based on the procedure DBRENT in Numerical Recipes by Press et al.
;       Finds a local minimum of a 1-D function up to specified tolerance,
;       using the first derivative of function in the algorithm.
;       This routine assumes that the function has a minimum nearby.
;       (recommend first calling minF_bracket, xa,xb,xc, to bracket minimum).
;       Routine can also be applied to a scalar function of many variables,
;       for such case the local minimum in a specified direction is found,
;       This routine is called by minF_conj_grad, to locate minimum in the 
;       direction of the conjugate gradient of function of many variables.
;
; CALLING EXAMPLES:
;       minF_parabol_D, xa,xb,xc, xmin, fmin, FUNC_NAME="name"  ;for 1-D func.
;  or:
;       minF_parabol_D, xa,xb,xc, xmin, fmin, FUNC="name", $
;                                         POINT=[0,1,1],   $
;                                         DIRECTION=[2,1,1]     ;for 3-D func.
; INPUTS:
;       xa,xb,xc = scalars, 3 points which bracket location of minimum,
;               that is, f(xb) < f(xa) and f(xb) < f(xc), so minimum exists.
;               When working with function of N variables
;               (xa,xb,xc) are then relative distances from POINT_NDIM,
;               in the direction specified by keyword DIRECTION,
;               with scale factor given by magnitude of DIRECTION.
; KEYWORDS:
;       FUNC_NAME = function name (string)
;               Calling mechanism should be:  F = func_name( px, gradient )
;               where:
;                       px = scalar or vector of independent variables, input.
;                       F = scalar value of function at px.
;                       gradient = derivative of function, a scalar if 1-D,
;                               a gradient vector if N-D,
;                               (should only be computed if arg. is present).
;
;       POINT_NDIM = when working with function of N variables,
;               use this keyword to specify the starting point in N-dim space.
;               Default = 0, which assumes function is 1-D.
;       DIRECTION = when working with function of N variables,
;               use this keyword to specify the direction in N-dim space
;               along which to bracket the local minimum, (default=1 for 1-D).
;               (xa, xb, xc, x_min are then relative distances from POINT_NDIM)
;       MAX_ITER = maximum allowed number iterations, default=100.
;       TOLERANCE = desired accuracy of minimum location, default=sqrt(1.e-7).
;
; OUTPUTS:
;       xmin = estimated location of minimum.
;               When working with function of N variables,
;               xmin is the relative distance from POINT_NDIM,
;               in the direction specified by keyword DIRECTION,
;               with scale factor given by magnitude of DIRECTION,
;               so that min. Loc. Pmin = Point_Ndim + xmin * Direction.
;       fmin = value of function at xmin (or Pmin).
; PROCEDURE:
;       Brent's method to minimize a function by using parabolic interpolation
;       and using first derivative of function,
;       from Numerical Recipes (by Press, et al.), sec.10.3 (p.287),
; MODIFICATION HISTORY:
;       Written, Frank Varosi NASA/GSFC 1992.

; NAME:
;      MINMAX
; PURPOSE:
;      Return a 2 element array giving the minimum and maximum of an array
; EXPLANATION:
;      Using MINMAX() is faster than doing a separate MAX and MIN.
;
; CALLING SEQUENCE:
;      value = minmax( array )
; INPUTS:
;      array - an IDL numeric scalar, vector or array.
;
; OUTPUTS:
;      value = a two element vector (if DIMEN is not supplied)
;            value[0] = minimum value of array
;            value[1] = maximum value of array
;
;            If the DIMEN keyword is supplied then value will be a 2 x N element
;            array where N is the number of elements in the specified
;            dimension
;              
; OPTIONAL INPUT KEYWORD:
;      /NAN   - Set this keyword to cause the routine to check for occurrences
;            of the IEEE floating-point value NaN in the input data.  Elements 
;            with the value NaN are treated as missing data.
;
;      DIMEN - (V5.5 or later) integer (either 1 or 2) specifying which 
;            dimension of a 2-d array to  take the minimum and maximum.   Note
;            that DIMEN is only valid for a 2-d array, larger dimensions are 
;            not supported.
; EXAMPLE:
;     (1)  Print the minimum and maximum of an image array, im
; 
;            IDL> print, minmax( im )
;
;     (2) Given a 2-dimension array of (echelle) wavelengths w, print the
;         minimum and maximum of each order (requires V5.5 or later)
;
;         print,minmax(w,dimen=1)
;
; PROCEDURE:
;      The MIN function is used with the MAX keyword
;
; REVISION HISTORY:
;      Written W. Landsman                January, 1990
;      Converted to IDL V5.0   W. Landsman   September 1997
;      Added NaN keyword.      M. Buie       June 1998
;      Added DIMENSION keyword    W. Landsman  January 2002

; NAME:
;       MKHDR
; PURPOSE:
;       Make a minimal primary (or IMAGE extension) FITS header
; EXPLANATION:
;       If an array is supplied,  then the created FITS header will be 
;       appropriate to the supplied array.  Otherwise, the user can specify 
;       the dimensions and datatype.
;
; CALLING SEQUENCE:
;       MKHDR, header                   ;Prompt for image size and type
;               or
;       MKHDR, header, im, [ /IMAGE, /EXTEND ]
;               or
;       MKHDR, header, type, naxisx, [/IMAGE, /EXTEND ]         
;
; OPTIONAL INPUTS:
;       IM - If IM is a vector or array then the header will be made
;               appropriate to the size and type of IM.  IM does not have
;               to be the actual data; it can be a dummy array of the same
;               type and size as the data.    Set IM = '' to create a dummy
;               header with NAXIS = 0. 
;       TYPE - If more than 2 parameters are supplied, then the second parameter
;               is interpreted as an integer giving the IDL datatype e.g. 
;               1 - LOGICAL*1, 2 - INTEGER*2, 4 - REAL*4, 3 - INTEGER*4
;       NAXISX - Vector giving the size of each dimension (NAXIS1, NAXIS2, 
;               etc.).  
;
; OUTPUT:
;       HEADER - image header, (string array) with required keywords
;               BITPIX, NAXIS, NAXIS1, ... Further keywords can be added
;               to the header with SXADDPAR. 
;
; OPTIONAL INPUT KEYWORDS:
;       /IMAGE   = If set, then a minimal header for a FITS IMAGE extension
;               is created.    An IMAGE extension header is identical to
;               a primary FITS header except the first keyword is 
;               'XTENSION' = 'IMAGE' instead of 'SIMPLE  ' = 'T'
;       /EXTEND  = If set, then the keyword EXTEND is inserted into the file,
;               with the value of "T" (true).    The EXTEND keyword must be
;               included in a primary header, if the FITS file contains 
;               extensions.
;
; RESTRICTIONS:
;       (1)  MKHDR should not be used to make an STSDAS header or a FITS
;               ASCII or Binary Table extension header.   Instead use
;
;               SXHMAKE - to create a minimal STSDAS header
;               FXBHMAKE - to create a minimal FITS binary table header
;               FTCREATE - to create a minimal FITS ASCII table header
;
;       (2)  Any data already in the header before calling MKHDR
;               will be destroyed.
; EXAMPLE:
;       Create a minimal FITS header, Hdr, for a 30 x 40 x 50 INTEGER*2 array
;
;             IDL> mkhdr, Hdr, 2, [30,40,50]
;
;       Alternatively, if the array already exists as an IDL variable, Array,
;
;              IDL> mkhdr, Hdr, Array
;
; PROCEDURES CALLED:
;       SXADDPAR, GET_DATE
;
; REVISION HISTORY:
;       Written November, 1988               W. Landsman
;       May, 1990, Adapted for IDL Version 2.0, J. Isensee
;       Aug, 1997, Use SYSTIME(), new DATE format  W. Landsman
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Allow unsigned data types    W. Landsman   December 1999
;       Set BZERO = 0 for unsigned integer data  W. Landsman January 2000
;       EXTEND keyword must immediately follow last NAXISi W. Landsman Sep 2000
;       Add FITS definition COMMENT to primary headers W. Landsman Oct. 2001
;       Allow (nonstandard) 64 bit integers   W. Landsman  Feb. 2003

; NAME:
;       MMM
; PURPOSE: 
;       Estimate the sky background in a stellar contaminated field.
; EXPLANATION:  
;       MMM assumes that contaminated sky pixel values overwhelmingly display 
;       POSITIVE departures from the true value.  Adapted from DAOPHOT 
;       routine of the same name.
;
; CALLING SEQUENCE:
;       MMM, sky, [ skymde, sigma, skew, HIGHBAD = , /DEBUG  ]
;
; INPUTS:
;       SKY - Array or Vector containing sky values.  This version of
;               MMM does not require SKY to be sorted beforehand.  SKY
;               is unaltered by this program.
;
; OPTIONAL OUTPUTS:
;       SKYMDE - Scalar giving estimated mode of the sky values
;       SIGMA -  Scalar giving standard deviation of the peak in the sky
;               histogram.  If for some reason it is impossible to derive
;               SKYMDE, then SIGMA = -1.0
;       SKEW -   Scalar giving skewness of the peak in the sky histogram
;               If no output variables are supplied or if /DEBUG is set
;               then the values of SKYMDE, SIGMA and SKEW will be printed.
;
; OPTIONAL KEYWORD INPUTS:
;       HIGHBAD - scalar value of the high "bad" pixel level (e.g. cosmic rays)
;               If not supplied, then there is assumed to be no high bad
;               pixels.
;       /DEBUG - If this keyword is set and non-zero, then additional information
;               is displayed at the terminal.
;
; RESTRICTIONS:
;       Program assumes that low "bad" pixels (e.g. bad CCD columns) have
;       already been deleted from the SKY vector.
;
; METHOD:
;       The algorithm used by MMM consists of roughly two parts:
;       (1) The average and sigma of the sky pixels is computed.   These values
;       are used to eliminate outliers, i.e. values with a low probability
;       given a Gaussian with specified average and sigma.   The average
;       and sigma are then recomputed and the process repeated up to 20
;       iterations:
;       (2) The amount of contamination by stars is estimated by comparing the 
;       mean and median of the remaining sky pixels.   If the mean is larger
;       than the median then the true sky value is estimated by
;       3*median - 2*mean
;         
; REVISION HISTORY:
;       Adapted to IDL from 1986 version of DAOPHOT in STSDAS, 
;       W. Landsman, STX Feb 1987
;       Adapted for IDL Version 2, J. Isensee, STX, Sept 1990
;       Added HIGHBAD keyword, W. Landsman January, 1991
;       Fixed occasional problem with integer inputs    W. Landsman  Feb, 1994
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Avoid possible 16 bit integer overflow   W. Landsman  November 2001

; NAME:
;      MODFITS
; PURPOSE:
;      Modify a FITS file by updating the header and/or data array.  
; EXPLANATION:
;      Since August 2003, the size of the supplied FITS header or data array
;      does not need to match the size of the existing header or data array.
;
; CALLING SEQUENCE:
;      MODFITS, Filename_or_fcb, Data, [ Header, EXTEN_NO =, ERRMSG=]
;
; INPUTS:
;      FILENAME/FCB = Scalar string containing either the name of the FITS file  
;                  to be modified, or the IO file control block returned after 
;                  opening the file with FITS_OPEN,/UPDATE.   The explicit
;                  use of FITS_OPEN can save time if many extensions in a 
;                  single file will be updated.
;
;      DATA - data array to be inserted into the FITS file.   Set DATA = 0
;               to leave the data portion of the FITS file unmodified
;
;      HEADER - FITS header (string array) to be updated in the FITS file.
;
; OPTIONAL INPUT KEYWORDS:
;      EXTEN_NO - scalar integer specifying the FITS extension to modified.  For
;               example, specify EXTEN = 1 or /EXTEN to modify the first 
;               FITS extension. 
; OPTIONAL OUTPUT KEYWORD:
;       ERRMSG - If this keyword is supplied, then any error mesasges will be
;               returned to the user in this parameter rather than depending on
;               on the MESSAGE routine in IDL.   If no errors are encountered
;               then a null string is returned.               
;
; EXAMPLES:
;     (1) Modify the value of the DATE keyword in the primary header of a 
;             file TEST.FITS.
;
;              IDL> h = headfits('test.fits')      ;Read primary header
;              IDL> sxaddpar,h,'DATE','2001-03-23' ;Modify value of DATE 
;              IDL> modfits,'test.fits',0,h        ;Update header only
;
;       (2) Replace the values of the primary image array in 'test.fits' with 
;               their absolute values
;
;               IDL> im = readfits('test.fits')    ;Read image array
;               IDL> im = abs(im)                  ;Take absolute values
;               IDL> modfits,'test.fits',im        ;Update image array
;
;       (3) Add some HISTORY records to the FITS header in the first extension
;               of a file 'test.fits'
;       
;               IDL> h = headfits('test.fits',/ext)  ;Read first extension hdr
;               IDL> sxaddhist,['Comment 1','Comment 2'],h
;               IDL> modfits,'test.fits',0,h,/ext    ;Update extension hdr
;
;       (4) Change 'OBSDATE' keyword to 'OBS-DATE' in every extension in a 
;           FITS file.    Explicitly open with FITS_OPEN to save compute time.
;
;               fits_open,'test.fits',io,/update    ;Faster to explicity open
;               for i = 1,nextend do begin          ;Loop over extensions
;                   fits_read,io,0,h,/header_only,exten_no=i,/No_PDU ;Get header     
;                   date= sxpar(h,'OBSDATE')         ;Save keyword value
;                   sxaddpar,h,'OBS-DATE',date,after='OBSDATE' 
;                   sxdelpar,h,'OBSDATE'             ;Delete bad keyword
;                   modfits,io,0,h,exten_no=i        ;Update header
;               endfor
;
;           Note the use of the /No_PDU keyword in the FITS_READ call -- one 
;           does *not* want to append the primary header, if the STScI 
;           inheritance convention is adopted.
;
; NOTES:
;       Use the BLKSHIFT procedure to shift the contents of the FITS file if 
;       the new data or header differs in size by more than 2880 bytes from the
;       old data or header.
;
;       Also see the procedures FXHMODIFY to add a single FITS keyword to a 
;       header in a FITS files, and FXBGROW to enlarge the size of a binary 
;       table.
; RESTRICTIONS:
;       (1) Cannot be used to modifiy the data in FITS files with random 
;           groups or variable length binary tables.   (The headers in such
;           files *can* be modified.)
;
;       (2) If a data array but no FITS header is supplied, then MODFITS does 
;           not check to make sure that the existing header is consistent with
;           the new data.
; PROCEDURES USED:
;       Functions:   IS_IEEE_BIG(), N_BYTES(), SXPAR()
;       Procedures:  BLKSHIFT, CHECK_FITS, FITS_OPEN, FITS_READ, HOST_TO_IEEE
;
; MODIFICATION HISTORY:
;       Written,    Wayne Landsman          December, 1994
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Fixed possible problem when using WRITEU after READU   October 1997
;       New and old sizes need only be the same within multiple of 2880 bytes
;       Added call to IS_IEEE_BIG()     W. Landsman   May 1999
;       Added ERRMSG output keyword     W. Landsman   May 2000
;       Update tests for incompatible sizes   W. Landsman   December 2000
;       Major rewrite to use FITS_OPEN procedures W. Landsman November 2001
;       Add /No_PDU call to FITS_READ call  W. Landsman  June 2002
;       Update CHECKSUM keywords if already present in header, add padding 
;       if new data  size is smaller than old  W.Landsman December 2002
;       Only check XTENSION value if EXTEN_NO > 1   W. Landsman Feb. 2003
;       Correct for unsigned data on little endian machines W. Landsman Apr 2003
;       Major rewrite to allow changing size of data or header W.L. Aug 2003

; NAME:
;       MONTH_CNV
; PURPOSE:
;       Convert between a month name and  the equivalent number 
; EXPLANATION: (e.g.,
;       For example, converts from 'January' to 1  or vice-versa.
; CALLING SEQUENCE:
;       Result = MONTH_CNV( MonthInput, [/UP, /LOW, /SHORT ] )
; INPUTS:
;       MonthInput - either a string ('January', 'Jan', 'Decem', etc.) or
;               an number from 1 to 12.  Scalar or array. 
; OPTIONAL KEYWORDS:
;       UP - if set and if a string is being returned, it will be in all
;               uppercase letters.
;       LOW - if set and if a string is being returned, it will be in all 
;               lowercase letters.
;       SHORT - if set and if a string is being returned, only the first
;               three letters are returned.
;       
; OUTPUTS:
;       If the input is a string, the output is the matching month number.If
;               an input string isn't a valid month name, -1 is returned.
;       If the input is a number, the output is the matching month name.  The
;               default format is only the first letter is capitalized.
; EXAMPLE:
;       To get a vector of all the month names:
;               Names = month_cnv(indgen(12)+1)
;
; MODIFICATION HISTORY:
;       Written by:     Joel Wm. Parker, SwRI, 1998 Dec 9

; NAME:                                     
;       MOONPOS
; PURPOSE:
;       To compute the RA and Dec of the Moon at specified Julian date(s).
;
; CALLING SEQUENCE:
;       MOONPOS, jd, ra, dec, dis, geolong, geolat, [/RADIAN ]
;
; INPUTS:
;       JD - Julian date, scalar or vector, double precision suggested
;
; OUTPUTS:
;       Ra  - Apparent right ascension of the moon in DEGREES, referred to the
;               true equator of the specified date(s) 
;       Dec - The declination of the moon in DEGREES 
;       Dis - The Earth-moon distance in kilometers (between the center of the
;             Earth and the center of the Moon).
;       Geolong - Apparent longitude of the moon in DEGREES, referred to the
;               ecliptic of the specified date(s)
;       Geolat - Apparent longitude of the moon in DEGREES, referred to the
;               ecliptic of the specified date(s)
;
;       The output variables will all have the same number of elements as the
;       input Julian date vector, JD.   If JD is a scalar then the output 
;       variables will be also.
;
; OPTIONAL INPUT KEYWORD:
;       /RADIAN - If this keyword is set and non-zero, then all output variables 
;               are given in Radians rather than Degrees
;
; EXAMPLES:
;       (1) Find the position of the moon on April 12, 1992
;
;       IDL> jdcnv,1992,4,12,0,jd    ;Get Julian date
;       IDL> moonpos, jd, ra ,dec     ;Get RA and Dec of moon
;       IDL> print,adstring(ra,dec,1)
;               ==> 08 58 45.23  +13 46  6.1
;
;       This is within 1" from the position given in the Astronomical Almanac
;       
;       (2) Plot the Earth-moon distance for every day at 0 TD in July, 1996
;
;       IDL> jdcnv,1996,7,1,0,jd                   ;Get Julian date of July 1
;       IDL> moonpos,jd+dindgen(31), ra, dec, dis  ;Position at all 31 days
;       IDL> plot,indgen(31),dis, /YNOZ
;
; METHOD:
;       Derived from the Chapront ELP2000/82 Lunar Theory (Chapront-Touze' and
;       Chapront, 1983, 124, 50), as described by Jean Meeus in Chapter 47 of
;       ``Astronomical Algorithms'' (Willmann-Bell, Richmond), 2nd edition, 
;       1998.    Meeus quotes an approximate accuracy of 10" in longitude and
;       4" in latitude, but he does not give the time range for this accuracy.
;
;       Comparison of this IDL procedure with the example in ``Astronomical
;       Algorithms'' reveals a very small discrepancy (~1 km) in the distance 
;       computation, but no difference in the position calculation.
;
;       This procedure underwent a major rewrite in June 1996, and the new
;       calling sequence is *incompatible with the old* (e.g. angles now 
;       returned in degrees instead of radians).
;
; PROCEDURES CALLED:
;       CIRRANGE, ISARRAY(), NUTATE, TEN()  - from IDL Astronomy Library
;       POLY() - from IDL User's Library
; MODIFICATION HISTORY:
;       Written by Michael R. Greason, STX, 31 October 1988.
;       Major rewrite, new (incompatible) calling sequence, much improved 
;               accuracy,       W. Landsman   Hughes STX      June 1996
;       Added /RADIAN keyword  W. Landsman August 1997
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Use improved expressions for L',D,M,M', and F given in 2nd edition of
;            Meeus (very slight change),  W. Landsman    November 2000

; NAME:
;       MPHASE
; PURPOSE:
;       Return the illuminated fraction of the Moon at given Julian date(s) 
;
; CALLING SEQUENCE:
;       MPHASE, jd, k
; INPUT:
;       JD - Julian date, scalar or vector, double precision recommended
; OUTPUT:
;       k - illuminated fraction of Moon's disk (0.0 < k < 1.0), same number
;           of elements as jd.   k = 0 indicates a new moon, while k = 1 for
;           a full moon.
; EXAMPLE:
;       Plot the illuminated fraction of the moon for every day in July 
;       1996 at 0 TD (~Greenwich noon).
;
;       IDL> jdcnv, 1996, 7, 1, 0, jd         ;Get Julian date of July 1
;       IDL> mphase, jd+dindgen(31), k        ;Moon phase for all 31 days
;       IDL> plot, indgen(31),k               ;Plot phase vs. July day number
;
; METHOD:
;       Algorithm from Chapter 46 of "Astronomical Algorithms" by Jean Meuus
;       (Willmann-Bell, Richmond) 1991.   SUNPOS and MOONPOS are used to get
;       positions of the Sun and the Moon (and the Moon distance).   The
;       selenocentric elongation of the Earth from the Sun (phase angle)
;       is then computed, and used to determine the illuminated fraction.
; PROCEDURES CALLED:
;       MOONPOS, SUNPOS
; REVISION HISTORY:
;       Written W. Landsman     Hughes STX           June 1996
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Use /RADIAN keywords to MOONPOS, SUNPOS internally  W. Landsman Aug 2000

; NAME: 
;     MRD_HREAD
;
; PURPOSE: 
;     Reads a FITS header from an opened disk file or Unix pipe
; EXPLANATION:
;     Like FXHREAD but also works with compressed Unix files
;
; CALLING SEQUENCE: 
;     MRD_HREAD, UNIT, HEADER  [, STATUS, /SILENT ]
; INPUTS: 
;     UNIT    = Logical unit number of an open FITS file
; OUTPUTS: 
;     HEADER  = String array containing the FITS header.
; OPT. OUTPUTS: 
;     STATUS  = Condition code giving the status of the read.  Normally, this
;                 is zero, but is set to -1 if an error occurs, or if the
;                 first byte of the header is zero (ASCII null).
; OPTIONAL KEYWORD INPUT:
;      /SILENT - If set, then warning messages about any invalid characters in
;                the header are suppressed.
;      /FIRSTBLOCK - If set, then only the first block (36 lines or less) of 
;                the FITS header are read into the output variable.   If only
;                size information (e.g. BITPIX, NAXIS) is needed from the
;                header, then the use of this keyword can save time.  The 
;                file pointer is still positioned at the end of the header,
;                even if the /FIRSTBLOCK keyword is supplied.
; RESTRICTIONS: 
;      The file must already be positioned at the start of the header.  It
;      must be a proper FITS file.
; SIDE EFFECTS: 
;       The file ends by being positioned at the end of the FITS header, unless
;       an error occurs.
; REVISION HISTORY:
;      Written,  Thomas McGlynn                     August 1995
;      Modified, Thomas McGlynn		     January 1996
;         Changed MRD_HREAD to handle Headers which have null characters
;          A warning message is printed out but the program continues.
;          Previously MRD_HREAD would fail if the null characters were
;          not in the last 2880 byte block of the header.  Note that
;          such characters are illegal in the header but frequently
;          are produced by poor FITS writers.
;      Converted to IDL V5.0   W. Landsman   September 1997
;      Added /SILENT keyword   W. Landsman   December 2000
;      Added /FIRSTBLOCK keyword  W. Landsman   February 2003

; NAME:
;       MRD_SKIP
; PURPOSE:
;       Skip a number of bytes from the current location in a file or a pipe
; EXPLANATION:
;       First tries using POINT_LUN and if this doesn't work, perhaps because
;       the unit is a pipe, MRD_SKIP will just read in the requisite number 
;       of bytes.    GZIP files opened with /COMPRESS (in V5.3 or later) are
;       also read as a series of bytes, since this is faster than using 
;       POINT_LUN when not at the beginning of a file. 
; CALLING SEQUENCE:
;       MRD_SKIP, Unit, Nskip
;
; INPUTS:
;       Unit - File unit for the file or pipe in question, integer scalar
;       Nskip - Number of bytes to be skipped, positive integer
; NOTES:
;       This routine should be used in place of POINT_LUN wherever a pipe
;       may be the input unit (see the procedure FXPOSIT for an example).  
;       Note that it assumes that it can only work with nskip >= 0 so it 
;       doesn't even try for negative values.      
;
;       For reading a pipe, MRD_SKIP currently uses a maximum buffer size
;       of 8 MB.   This chunk value can be increased for improved efficiency
;       (or decreased if you really have little memory.)
; REVISION HISTORY:
;       Written, Thomas A. McGlynn    July 1995
;	Don't even try to skip bytes on a pipe with POINT_LUN, since this
;	might reset the current pointer     W. Landsman        April 1996
;       Increase buffer size, check fstat.compress W. Landsman  Jan 2001
;       Only a warning if trying read past EOF   W. Landsman   Sep 2001
;       Use 64bit longword for skipping in very large files W. Landsman Sep 2003

; NAME:
;       MRD_STRUCT
; PURPOSE:
;       Return a structure as defined in the names and values data.
; CALLING SEQUENCE:
;       struct = MRD_STRUCT(NAMES, VALUES, NROW,                $
;                   STRUCTYP=structyp,                          $
;                   TEMPDIR=tempdir, /OLD_STRUCT)
; INPUT PARAMETERS:
;       NAMES   = A string array of names of structure fields.
;       VALUES  = A string array giving the values of the structure
;                 fields.  See examples below.
;       NROW    = The number of elements in the structure array.
;       
; RETURNS:
;       A structure as described in the parameters or 0 if an error
;       is detected.
;
; OPTIONAL KEYWORD PARAMETERS:
;       STRUCTYP = The structure type.  Since IDL does not allow the
;                  redefinition of a named structure it is an error
;                  to call MRD_STRUCT with different parameters but
;                  the same STRUCTYP in the same session.  If this
;                  keyword is not set an anonymous structure is created.
;       TEMPDIR  = If the structure is more than modestly complex a
;                  temporary file is created.  This file will be
;                  created in the current directory unless the TEMPDIR
;                  keyword is specified.  Note that the temporary directory
;                  should also be in the IDL search path.
;       OLD_STRUCT=Use old format structures.
; COMMON BLOCKS:
;       MRD_COMMON
; SIDE EFFECTS:                                                            
;       May create a temporary file if the structure definition is too long 
;       for the EXECUTE function and using old style structures
;
; RESTRICTIONS:
;       By default this program uses a series of execute
;       commands and create_struct's to create the structure.
;       If the old_struct keyword is set, then a program may
;       be dynamically compiled.  The nominal maximum length
;       of the execute string is 131 characters, but many systems
;       seem to allow longer values.  This code may execute more
;       efficiently with a longer execute buffer.
; PROCEDURE:
;       A structure definition is created using the parameter values.
;       MRD_NSTRUCT is called if the OLD_STRUCT keyword is not specified
;       and generates the structure in pieces using the
;       execute and create_struct keywords.
;
;       If the old_struct flag is set, then the program tries to compile
;       the structure with a single execute command.  If the structure
;       definition is too long  MRD_FSTRUCT is called to write, compile and
;       execute a function which will define the structure.
; EXAMPLES:
;       str = mrd_struct(['fld1', 'fld2'], ['0','dblarr(10,10)'],3)
;       print, str(0).fld2(3,3)
;
;       str = mrd_struct(['a','b','c','d'],['1', '1.', '1.d0', "'1'"],1)
;               ; returns a structure with integer, float, double and string
;               ; fields.
; PROCEDURE CALLS:
;       CONCAT_DIR - Used to concatenate temporary directory with filename
; MODIFICATION HISTORY:
;       Created by T. McGlynn October, 1994.
;       Modified by T. McGlynn September, 1995.
;          Added capability to create substructures so that structure
;          may contain up to 4096 distinct elements.  [This can be
;          increased by futher iteration of the process used if needed.]
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Removed V4.0 reference to common block  October 1997
;       Allowed unlimited number of structure elements if the version
;       is greater than 5.0.  Put back in code to handle prior versions.
;       The [] will need to be translated back to () for this to
;       work.  T. McGlynn December 15 1998.
;       Add MRD_NSTRUCT since IDL has mysterious problems compiling
;       very large structures.

; 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.
;
;	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
; 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

; NAME:
;       MWRFITS
; PURPOSE:
;       Write all standard FITS data types from input arrays or structures.
;
; CALLING SEQUENCE:
;       MWRFITS, Input, Filename, [Header],
;                       /LSCALE , /ISCALE, /BSCALE, 
;                       /USE_COLNUM, /Silent, /Create, /No_comment, /Version, $
;                       Alias=, /ASCII, Separator=, Terminator=, Null=,
;                       /Logical_cols, /Bit_cols, /Nbit_cols, 
;                       Group=, Pscale=, Pzero=
;
; INPUTS:
;       Input = Array or structure to be written to FITS file.
;
;               -When writing FITS primary data or image extensions
;                input should be an array.
;               --If data is to be grouped
;                 the Group keyword should be specified to point to
;                 a two dimensional array.  The first dimension of the
;                 Group array will be PCOUNT while the second dimension
;                 should be the same as the last dimension of Input.
;               --If Input is undefined, then a dummy primary dataset
;                 or Image extension is created [This might be done, e.g.,
;                 to put appropriate keywords in a dummy primary
;                 HDU].
;
;               -When writing an ASCII table extension, Input should
;                be a structure array where no element of the structure
;                is a structure or array (except see below).
;               --A byte array will be written as A field.  No checking
;                 is done to ensure that the values in the byte field
;                 are valid ASCII.
;               --Complex numbers are written to two columns with '_R' and
;                 '_I' appended to the TTYPE fields (if present).  The
;                 complex number is enclosed in square brackets in the output.
;               --Strings are written to fields with the length adjusted
;                 to accommodate the largest string.  Shorter strings are
;                 blank padded to the right.
;
;               -When writing a binary table extension, the input should
;                be a structure array with no element of the structure
;                being a substructure.
;
;               If a structure is specified on input and the output
;               file does not exist or the /CREATE keyword is specified
;               a dummy primary HDU is created.
;
;       Filename = String containing the name of the file to be written.
;                By default MWRFITS appends a new extension to existing
;                files which are assumed to be valid FITS.  The /CREATE
;                keyword can be used to ensure that a new FITS file
;                is created even if the file already exists.
;
; OUTPUTS:
;
; OPTIONAL INPUTS:
;       Header = Header should be a string array.  Each element of the
;                array is added as a row in the FITS  header.  No
;                parsing is done of this data.  MWRFITS will prepend
;                required structural (and, if specified, scaling)
;                keywords before the rows specified in Header.
;                Rows describing columns in the table will be appended
;                to the contents of Header.
;                Header lines will be extended or truncated to
;                80 characters as necessary.
;                If Header is specified then on return Header will have
;                the header generated for the specified extension.
;
; OPTIONAL INPUT KEYWORDS:
;       ALias=   Set up aliases to convert from the IDL structure
;                to the FITS column name.  The value should be
;                a STRARR(2,*) value where the first element of
;                each pair of values corresponds to a column
;                in the structure and the second is the name
;                to be used in the FITS file.
;                The order of the alias keyword is compatible with
;                use in MRDFITS.
;       ASCII  - Creates an ASCII table rather than a binary table.
;                This keyword may be specified as:
;                /ASCII - Use default formats for columns.
;                ASCII='format_string' allows the user to specify
;                  the format of various data types such using the following
;                  syntax 'column_type:format, column_type:format'.  E.g.,
;                ASCII='A:A1,I:I6,L:I10,B:I4,F:G15.9,D:G23.17,C:G15.9,M:G23.17'
;                gives the default formats used for each type.  The TFORM
;                fields for the real and complex types indicate will use corresponding
;                E and D formats when a G format is specified.
;                Note that the length of the field for ASCII strings and
;                byte arrays is automatically determined for each column.
;       BIT_COLS=   An array of indices of the bit columns.   The data should
;                comprise a byte array with the appropriate dimensions.
;                If the number of bits per row (see NBIT_COLS)
;                is greater than 8, then the first dimension of the array 
;                should match the number of input bytes per row.
;       BSCALE   Scale floats, longs, or shorts to unsigned bytes (see LSCALE)
;       CREATE   If this keyword is non-zero, then a new FITS file will
;                be created regardless of whether the file currently
;                exists.  Otherwise when the file already exists,
;                a FITS extension will be appended to the existing file
;                which is assumed to be a valid FITS file.
;       GROUP=   This keyword indicates that GROUPed FITS data is to
;                be generated.
;                Group should be a 2-D array of the appropriate output type.
;                The first dimension will set the number of group parameters.
;                The second dimension must agree with the last dimension
;                of the Input array.
;       ISCALE   Scale floats or longs to short integer (see LSCALE)
;       LOGICAL_COLS=  An array of indices of the logical column numbers.
;                These should start with the first column having index 0.
;                The structure element should be an array of characters
;                with the values 'T' or 'F'.  This is not checked.
;       LSCALE   Scale floating point numbers to long integers.
;                This keyword may be specified in three ways.
;                /LSCALE (or LSCALE=1) asks for scaling to be automatically
;                determined. LSCALE=value divides the input by value.
;                I.e., BSCALE=value, BZERO=0.  Numbers out of range are 
;                given the value of NULL if specified, otherwise they are given
;                the appropriate extremum value.  LSCALE=(value,value)
;                uses the first value as BSCALE and the second as BZERO
;                (or TSCALE and TZERO for tables).
;       NBIT_COLS=  The number of bits actually used in the bit array.
;                This argument must point to an array of the same dimension
;                as BIT_COLS.
;       NO_TYPES  If the NO_TYPES keyword is specified, then no TTYPE
;                keywords will be created for ASCII and BINARY tables.
;       No_comment Do not write comment keywords in the header
;       NULL=    Value to be written for integers/strings which are
;                undefined or unwritable.
;       PSCALE=  An array giving scaling parameters for the group keywords.
;                It should have the same dimension as the first dimension
;                of Group.
;       PZERO=   An array giving offset parameters for the group keywords.
;                It should have the same dimension as the first dimension
;                of Group.
;       Separator= This keyword can be specified as a string which will
;                be used to separate fields in ASCII tables.  By default
;                fields are separated by a blank.
;       SILENT   Suppress informative messages.  Errors will still
;                be reported.
;       Terminator= This keyword can be specified to provide a string which
;                will be placed at the end of each row of an ASCII table.
;                No terminator is used when not specified.
;                If a non-string terminator is specified (including
;                when the /terminator form is used), a new line terminator
;                is appended.
;       USE_COLNUM  When creating column names for binary and ASCII tables
;                MWRFITS attempts to use structure field name
;                values.  If USE_COLNUM is specified and non-zero then
;                column names will be generated as 'C1, C2, ... 'Cn'
;                for the number of columns in the table.
;       Version   Print the version number of MWRFITS.
;
; EXAMPLE:
;       Write a simple array:
;            a=fltarr(20,20)
;            mwrfits,a,'test.fits'
;
;       Append a 3 column, 2 row, binary table extension to file just created.
;            a={name:'M31', coords:(30., 20.), distance:2}
;            a=replicate(a, 2);
;            mwrfits,a,'test.fits'
;
;       Now add on an image extension:
;            a=lonarr(10,10,10)
;            hdr=("COMMENT  This is a comment line to put in the header", $
;                 "MYKEY    = "Some desired keyword value")
;            mwrfits,a,'test.fits',hdr
;
; RESTRICTIONS:
;       (1)     Variable length columns are not supported for anything
;               other than simple types (byte, int, long, float, double).
; NOTES:
;       This multiple format FITS writer is designed to provide a
;       single, simple interface to writing all common types of FITS data.
;       Given the number of options within the program and the
;       variety of IDL systems available it is likely that a number
;       of bugs are yet to be uncovered.  If you find an anomaly
;       please send a report to:
;           Tom McGlynn
;           NASA/GSFC Code 660.2
;           tam@silk.gsfc.nasa.gov (or 301-286-7743)
;
; PROCEDURES USED:
;       FXPAR(), FXADDPAR, IS_IEEE_BIG(), HOST_TO_IEEE
; MODIfICATION HISTORY:
;       Version 0.9: By T. McGlynn   1997-07-23
;              Initial beta release.
;       Dec 1, 1997, Lindler, Modified to work under VMS.
;       Version 0.91: T. McGlynn  1998-03-09
;               Fixed problem in handling null primary arrays.
;       Reconverted to IDL 5.0 format using IDLv4_to_v5
;       Version 0.92: T. McGlynn 1998-09-09
;               Add no_comment flag and keep user comments on fields.
;               Fix handling of bit fields.
;       Version 0.93: T. McGlynn 1999-03-10
;               Fix table appends on VMS.
;       Version 0.93a  W. Landsman/D. Schlegel
;               Update keyword values in chk_and_upd if data type has changed 
;       Version 0.94: T. McGlynn 2000-02-02
;               Efficient processing of ASCII tables.
;               Use G rather than E formats as defaults for ASCII tables
;                and make the default precision long enough that transformations
;                binary to/from ASCII are invertible.
;               Some loop indices made long.
;               Fixed some ends to match block beginnings.
;       Version 0.95: T. McGlynn 2000-11-06
;               Several fixes to scaling.  Thanks to David Sahnow for
;               documenting the problems.
;               Added PCOUNT,GCOUNT keywords to Image extensions.
;               Version numbers shown in SIMPLE/XTENSION comments
;       Version 0.96: T. McGlynn 2001-04-06
;               Changed how files are opened to handle ~ consistently
;       Version 1.0: T. McGlynn 2001-12-04
;               Unsigned integers,
;               64 bit integers.
;               Aliases
;               Variable length arrays
;               Some code cleanup
;       Version 1.1: T. McGlynn 2002-2-18
;               Fixed major bug in processing of unsigned integers.
;               (Thanks to Stephane Beland)
;       Version 1.2: Stephane Beland 2003-03-17
;               Fixed problem in creating dummy dataset when passing undefined
;               data, caused by an update to FXADDPAR routine.
;       Version 1.2.1 Stephane Beland 2003-09-10
;               Exit gracefully if write priveleges unavailable
;
;              

; NAME:
;       NGP
;
; PURPOSE:
;       Interpolate an irregularly sampled field using Nearest Grid Point
;
; EXPLANATION:
;       This function interpolates irregularly gridded points to a
;       regular grid using Nearest Grid Point.
;
; CATEGORY:
;       Mathematical functions, Interpolation
;
; CALLING SEQUENCE:
;       Result = NGP, VALUE, POSX, NX[, POSY, NY, POSZ, NZ, 
;                     /AVERAGE, /WRAPAROUND, /NO_MESSAGE]
;
; INPUTS:
;       VALUE: Array of sample weights (field values). For e.g. a
;              temperature field this would be the temperature and the
;              keyword AVERAGE should be set. For e.g. a density field
;              this could be either the particle mass (AVERAGE should
;              not be set) or the density (AVERAGE should be set).
;       POSX:  Array of X coordinates of field samples, unit indices: [0,NX>.
;       NX:    Desired number of grid points in X-direction.
;       
; OPTIONAL INPUTS:
;      POSY: Array of Y coordinates of field samples, unit indices: [0,NY>.
;      NY:   Desired number of grid points in Y-direction.
;      POSZ: Array of Z coordinates of field samples, unit indices: [0,NZ>.
;      NZ:   Desired number of grid points in Z-direction.
;
; KEYWORD PARAMETERS:
;       AVERAGE:    Set this keyword if the nodes contain field samples
;                   (e.g. a temperature field). The value at each grid
;                   point will then be the average of all the samples
;                   allocated to it. If this keyword is not set, the
;                   value at each grid point will be the sum of all the
;                   nodes allocated to it (e.g. for a density field from
;                   a distribution of particles). (D=0). 
;       WRAPAROUND: Set this keyword if the data is periodic and if you
;                   want the first grid point to contain samples of both
;                   sides of the volume (see below). (D=0).
;       NO_MESSAGE: Suppress informational messages.
;
; Example of default NGP allocation: n0=4, *=gridpoint.
;
;     0   1   2   3     Index of gridpoints
;     *   *   *   *     Grid points
;   |---|---|---|---|   Range allocated to gridpoints ([0.0,1.0> --> 0, etc.)
;   0   1   2   3   4   posx
;
; Example of NGP allocation for WRAPAROUND: n0=4, *=gridpoint.
;
;   0   1   2   3         Index of gridpoints
;   *   *   *   *         Grid points
; |---|---|---|---|--     Range allocated to gridpoints ([0.5,1.5> --> 1, etc.)
;   0   1   2   3   4=0   posx
;
;
; OUTPUTS:
;       Prints that a NGP interpolation is being performed of x
;       samples to y grid points, unless NO_MESSAGE is set. 
;
; RESTRICTIONS:
;       All input arrays must have the same dimensions.
;       Postition coordinates should be in `index units' of the
;       desired grid: POSX=[0,NX>, etc.
;
; PROCEDURE:
;       Nearest grid point is determined for each sample.
;       Samples are allocated to nearest grid points.
;       Grid point values are computed (sum or average of samples).
;
; EXAMPLE:
;       nx = 20
;       ny = 10
;       posx = randomu(s,1000)
;       posy = randomu(s,1000)
;       value = posx^2+posy^2
;       field = ngp(value,posx*nx,nx,posy*ny,ny,/average)
;       surface,field,/lego
;
; NOTES:
;       Use tsc.pro or cic.pro for a higher order interpolation schemes.    A 
;       standard reference for these interpolation methods is:   R.W. Hockney 
;       and J.W. Eastwood, Computer Simulations Using Particles (New York: 
;       McGraw-Hill, 1981).
; MODIFICATION HISTORY:
;       Written by Joop Schaye, Feb 1999.
;       Check for LONG overflow  P. Riley/W. Landsman   December 1999

; NAME:
;	NINT
; PURPOSE:
;	Nearest integer function.
; EXPLANATION:   
;	NINT() is similar to the intrinsic ROUND function, with the following
;	two differences:
;	(1) if no absolute value exceeds 32767, then the array is returned as
;		as a type INTEGER instead of LONG
;	(2) NINT will work on strings, e.g. print,nint(['3.4','-0.9']) will
;		give [3,-1]  
;
; CALLING SEQUENCE:
;	result = nint( x, [ /LONG] )
;
; INPUT:
;	X - An IDL variable, scalar or vector, usually floating or double
;		Unless the LONG keyword is set, X must be between -32767.5 and 
;		32767.5 to avoid integer overflow
;
; OUTPUT
;	RESULT - Nearest integer to X
;
; OPTIONAL KEYWORD INPUT:
;	LONG - If this keyword is set and non-zero, then the result of NINT
;		is of type LONG.   Otherwise, the result is of type LONG if
;		any absolute values exceed 32767, and type INTEGER if all
;		all absolute values are less than 32767.
; EXAMPLE:
;	If X = [-0.9,-0.1,0.1,0.9] then NINT(X) = [-1,0,0,1]
;
; PROCEDURE CALL:
;	None:
; REVISION HISTORY:
;	Written W. Landsman        January 1989
;	Added LONG keyword         November 1991
;	Use ROUND if since V3.1.0  June 1993
;	Always start with ROUND function    April 1995
;	Return LONG values, if some input value exceed 32767
;		and accept string values   February 1998 
;       Use size(/TNAME) intead of DATATYPE()      October 2001

; NAME:
;       NSTAR
; PURPOSE:
;       Simultaneous point spread function fitting (adapted from DAOPHOT)
; CALLING SEQUENCE:
;       NSTAR, image, id, xc, yc, mags, sky, group, [ phpadu, readns, psfname,
;               magerr, iter, chisq, peak, /PRINT , /SILENT, /VARSKY, /DEBUG ]
;
; INPUTS:
;       image - image array
;       id    - vector of stellar ID numbers given by FIND
;       xc    - vector containing X position centroids of stars (e.g. as found
;               by FIND)
;       yc    - vector of Y position centroids
;       mags  - vector of aperture magnitudes (e.g. as found by APER)
;               If 9 or more parameters are supplied then, upon output
;               ID,XC,YC, and MAGS will be modified to contain the new
;               values of these parameters as determined by NSTAR.
;               Note that the number of output stars may be less than 
;               the number of input stars since stars may converge, or 
;               "disappear" because they are too faint.
;       sky   - vector of sky background values (e.g. as found by APER)
;       group - vector containing group id's of stars as found by GROUP
;
; OPTIONAL INPUT:
;       phpadu - numeric scalar giving number of photons per digital unit.  
;               Needed for computing Poisson error statistics.   
;       readns - readout noise per pixel, numeric scalar.   If not supplied, 
;               NSTAR will try to read the values of READNS and PHPADU from
;               the PSF header.  If still not found, user will be prompted.
;       psfname - name of FITS image file containing the point spread
;               function residuals as determined by GETPSF, scalar string.  
;               If omitted, then NSTAR will prompt for this parameter.
;
; OPTIONAL OUTPUTS:
;       MAGERR - vector of errors in the magnitudes found by NSTAR
;       ITER - vector containing the number of iterations required for
;               each output star.  
;       CHISQ- vector containing the chi square of the PSF fit for each
;               output star.
;       PEAK - vector containing the difference of the mean residual of
;               the pixels in the outer half of the fitting circle and
;               the mean residual of pixels in the inner half of the
;               fitting circle
;
; OPTIONAL KEYWORD INPUTS:
;       /SILENT - if set and non-zero, then NSTAR will not display its results
;               at the terminal
;       /PRINT - if set and non-zero then NSTAR will also write its results to
;               a file nstar.prt.   One also can specify the output file name
;               by setting PRINT = 'filename'.
;       /VARSKY - if this keyword is set and non-zero, then the sky level of
;               each group is set as a free parameter.
;       /DEBUG - if this keyword is set and non-zero, then the result of each
;               fitting iteration will be displayed.
;
; PROCEDURES USED:
;       DAO_VALUE(), READFITS(), REMOVE, SPEC_DIR(), STRN(), SXPAR()
;
; COMMON BLOCK:
;       RINTER - contains pre-tabulated values for cubic interpolation
; REVISION HISTORY
;       W. Landsman                 ST Systems Co.       May, 1988
;       Adapted for IDL Version 2, J. Isensee, September, 1990
;       Minor fixes so that PRINT='filename' really prints to 'filename', and
;       it really silent if SILENT is set.  J.Wm.Parker HSTX 1995-Oct-31
;       Added /VARSKY option   W. Landsman   HSTX      May 1996
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Replace DATATYPE() with size(/TNAME)  W. Landsman November 2001

; NAME:
;	NULLTRIM
; PURPOSE:
;	Trim a string of all characters after and including the first null
; EXPLANATION:
;	The null character is an ascii 0b
;
; CALLING SEQUENCE:
;	result = nulltrim( st )
;
; INPUTS:
;	st = input string
; OUTPUTS:
;	trimmed string returned as the function value.
; HISTORY:
;	D. Lindler  July, 1987
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;     NUMLINES() 
; PURPOSE:
;     Return the number of lines in a file
;
;     This procedures became mostly obsolete in V5.6 with the introduction of
;     the FILE_LINES() procedure
; CALLING SEQUENCE:
;     nl = NUMLINES( filename )
; INPUT:
;     filename = name of file, scalar string
; OUTPUT:
;     nl = number of lines in the file, scalar longword
;          Set to -1 if the number of lines could not be determined
; METHOD:
;     If Unix then spawn to wc; otherwise read 1 line at a time and count
;
; PROCEDURE CALLS:
;     EXPAND_TILDE(), SPEC_DIR()
; MODIFICATION HISTORY:
;     W. Landsman                              February 1996
;     Use /bin/sh shell with wc under Unix     March 1997
;     Use EXPAND_TILDE() under Unix         September 1997
;     Converted to IDL V5.0   W. Landsman   September 1997
;     Call intrinsic FILE_LINES() if V5.6 or later   December 2002

; NAME:
;       NUTATE
; PURPOSE:
;       Return the nutation in longitude and obliquity for a given Julian date
;
; CALLING SEQUENCE:
;       NUTATE, jd, Nut_long, Nut_obliq
;
; INPUT:
;       jd - Julian ephemeris date, scalar or vector, double precision  
; OUTPUT:
;       Nut_long - the nutation in longitude, same # of elements as jd
;       Nut_obliq - nutation in latitude, same # of elements as jd
;
; EXAMPLE:
;       (1) Find the nutation in longitude and obliquity 1987 on Apr 10 at Oh.
;              This is example 22.a from Meeus
;        IDL> jdcnv,1987,4,10,0,jul
;        IDL> nutate, jul, nut_long, nut_obliq
;             ==> nut_long = -3.788    nut_obliq = 9.443
;            
;       (2) Plot the large-scale variation of the nutation in longitude 
;               during the 20th century
;
;       IDL> yr = 1900 + indgen(100)     ;Compute once a year        
;       IDL> jdcnv,yr,1,1,0,jul          ;Find Julian date of first day of year
;       IDL> nutate,jul, nut_long        ;Nutation in longitude
;       IDL> plot, yr, nut_long
;
;       This plot will reveal the dominant (18.6 year) period, but a finer
;       grid is needed to display the shorter periods in the nutation.
; METHOD:
;       Uses the formula in Chapter 22 of ``Astronomical Algorithms'' by Jean 
;       Meeus (1998, 2nd ed.) which is based on the 1980 IAU Theory of Nutation
;       and includes all terms larger than 0.0003".
;
; PROCEDURES CALLED:
;       POLY()                       (from IDL User's Library)
;       CIRRANGE, ISARRAY()          (from IDL Astronomy Library)
;
; REVISION HISTORY:
;       Written, W.Landsman (Goddard/HSTX)      June 1996       
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Corrected minor typos in values of d_lng W. Landsman  December 2000
;       Updated typo in cdelt term              December 2000

; NAME:
;       N_bytes()
;
; PURPOSE:
;       To return the total number of bytes in data element
;
; CALLING SEQUENCE:
;       result = N_bytes(a)
;
; INPUTS:
;       a - any idl data element, scalar or array
;
; OUTPUTS:
;       total number of bytes in a is returned as the function value
;       (longword scalar)
; NOTES:
;       (1) Not valid for object or pointer data types
;       (2) For a string array, the number of bytes is computed after conversion
;           with the BYTE() function, i.e. each element has the same length,
;           equal to the maximum individual string length.
;
; MODIFICATION HISTORY:
;       Version 1  By D. Lindler  Oct. 1986
;       Include new IDL data types    W. Landsman          June 2001

; NAME:
;	N_STRUCT 
;
; PURPOSE:
;	To determine if variable is a structure and return number of elements.
;
; CALLING SEQUENCE:
;	n = N_struct( var, ntags )
;
; INPUT:
;	var = any variable.
;
; OUTPUT:
;	ntags = number of structure tags.
;
; RESULT:
;	Returns zero if variable is not a structure, otherwise returns # elems.
;
; PROCEDURE:
;	Determine if argument is a structure by checking for # of tags.
;	If structure, use size function to get # of elements
;	(instead of N_elements) so that it works on I/O associated structures.
;
; MODIFICATION HISTORY:
;	Written, Frank Varosi NASA/GSFC 1989.
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;       OBSERVATORY
; PURPOSE:
;       Return longitude, latitude, altitude & time zones of an observatory
; EXPLANATION:
;       Given an observatory name, returns a structure giving the longitude,
;       latitude, altitude, and time zone 
;
; CALLING SEQUENCE:
;       Observatory, obsname, obs_struct, [ /PRINT ]
;
; INPUTS:
;       obsname - scalar or vector string giving abbreviated name(s) of 
;             observatories for which location or time information is requested.
;             If obsname is an empty string, then information is returned for 
;             all observatories in the database.     See the NOTES: section
;             for the list of recognized observatories.   The case of the 
;             string does not matter  
; OUTPUTS:
;       obs_struct - an IDL structure containing information on  the specified
;                 observatories.   The structure tags are as follows: 
;       .observatory - abbreviated observatory name
;       .name - full observatory name  
;       .longitude - observatory longitude in degrees *west* 
;       .latitude - observatory latitude in degrees
;       .altitude - observatory altitude in meters above sea level
;       .tz - time zone, number of hours *west* of Greenwich
;
; OPTIONAL INPUT KEYWORD:
;     /PRINT - If this keyword is set, (or if only 1 parameter is supplied)
;             then OBSERVATORY will display information about the specified
;             observatories at the terminal
; EXAMPLE:
;     Get the latitude, longitude and altitude of Kitt Peak National Observatory
;
;     IDL> observatory,'kpno',obs
;     IDL> print,obs.longitude  ==> 111.6 degrees west 
;     IDL> print,obs.latitude  ==> +31.9633 degrees
;     IDL> print,obs.altitude  ==> 2120 meters above sea level
;
; NOTES:
;   Observatory information is taken from noao$lib/obsdb.dat file in IRAF 2.11
;   Currently recognized observatory names are as follows:
;
;  'kpno': Kitt Peak National Observatory
;  'ctio': Cerro Tololo Interamerican Observatory
;  'eso': European Southern Observatory
;  'lick': Lick Observatory
;  'mmto': MMT Observatory
;  'cfht': Canada-France-Hawaii Telescope
;  'lapalma': Roque de los Muchachos, La Palma
;  'mso': Mt. Stromlo Observatory
;  'sso': Siding Spring Observatory
;  'aao': Anglo-Australian Observatory
;  'mcdonald': McDonald Observatory
;  'lco': Las Campanas Observatory
;  'mtbigelow': Catalina Observatory: 61 inch telescope
;  'dao': Dominion Astrophysical Observatory
;  'spm': Observatorio Astronomico Nacional, San Pedro Martir
;  'tona': Observatorio Astronomico Nacional, Tonantzintla
;  'Palomar': The Hale Telescope
;  'mdm': Michigan-Dartmouth-MIT Observatory
;  'NOV': National Observatory of Venezuela
;  'bmo': Black Moshannon Observatory
;  'BAO': Beijing XingLong Observatory
;  'keck': W. M. Keck Observatory
;  'ekar': Mt. Ekar 182 cm. Telescope
;  'apo': Apache Point Observatory
;  'lowell': Lowell Observatory
;  'vbo': Vainu Bappu Observatory
;  'flwo': Whipple Observatory
;  'oro': Oak Ridge Observatory
;  'lna': Laboratorio Nacional de Astrofisica - Brazil
;  'saao': South African Astronomical Observatory
;  'casleo': Complejo Astronomico El Leoncito, San Juan
;  'bosque': Estacion Astrofisica Bosque Alegre, Cordoba
;  'rozhen': National Astronomical Observatory Rozhen - Bulgaria
;  'irtf': NASA Infrared Telescope Facility
;  'bgsuo': Bowling Green State Univ Observatory
;  'ca': Calar Alto Observatory
;  'holi': Observatorium Hoher List (Universitaet Bonn) - Germany
;  'lmo': Leander McCormick Observatory
;  'fmo': Fan Mountain Observatory
;  'whitin': Whitin Observatory, Wellesley College
;
; PROCEDURE CALLS:
;    TEN()             
; REVISION HISTORY:
;    Written   W. Landsman                 July 2000

; NAME:
;	ONE_ARROW
; PURPOSE:
;	Draws an arrow labeled with a single character on the current device
; EXPLANATION:
;	ONE_ARROW is called, for example, by ARROWS to create a
;	"weathervane" showing the N-E orientation of an image.
;
; CALLING SEQUENCE:
;	one_arrow, xcen, ycen, angle, label, CHARSIZE = , THICK = , COLOR = 
;			ARROWSIZE=, FONT =  ]
; INPUT PARAMETERS:
;    xcen, ycen = starting point of arrow in device coordinates, floating
;			point scalars,
;    angle      = angle of arrow in degrees counterclockwise from +X direction
;    label      = single-character label (may be blank)
;
; OUTPUT PARAMETERS:  none
;
; OPTIONAL INPUT PARAMETERS:
;      	CHARSIZE   = usual IDL meaning, default = 2.0
;	THICK      = usual IDL meaning, default = 2.0
;	COLOR      = usual IDL meaning, default = !P.COLOR
;	ARROWSIZE  = 3-element vector defining appearance of arrow.
;		Default = [30.0, 9.0, 35.0], meaning arrow is 30 pixels
;		long; arrowhead lines 9 pixels long and inclined 35
;		degrees from arrow shaft.
;		If you try to use a non-TV device, you will probably
;		want to change this.
;	FONT - IDL vector font number to use (1-20).   For example, to write
;		the 'N' and 'E' characters in complex script, set font=13
; EXAMPLE:
;	Draw an triple size arrow emanating from the point (212,224)
;	and labeled with the character 'S'
;
;	IDL> one_arrow,212,224,270,'S',charsize=3
; PROCEDURE:  
;	Calls one_ray to vector-draw arrow.
; MODIFICATION HISTORY:
;	Written by R. S. Hill, Hughes STX Corp., 20-May-1992.
;	Added font keyword, W.B. Landsman Hughes STX Corp. April 1995
;	Modified to work correctly for COLOR=0  J.Wm.Parker, HITC   1995 May 25
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	ONE_RAY
; PURPOSE:
;	Draw a line with a specified starting point, length, and  angle
;
; CALLING SEQUENCE:
;	one_ray, xcen, ycen, len, angle, terminus, [  THICK=, COLOR =, /NODRAW ]
;
; INPUT PARAMETERS:
;	xcen, ycen = starting point in device coordinates, floating point 
;			scalars
;	len        = length in pixels, device coordinates
;	angle      = angle in degrees counterclockwise from +X direction
;
; OUTPUT PARAMETERS:
;	terminus = two-element vector giving ending point of ray in device
;		coordinates
;
; OPTIONAL KEYWORD INPUT PARAMETERS:
;	thick    usual IDL meaning, default = 1.0
;	color    usual IDL meaning, default = !P.COLOR
;	nodraw   if non-zero, the ray is not actually drawn, but the terminus
;		is still calculated
;
; EXAMPLE:
;	Draw a double thickness line of length 32 pixels from (256,256) 
;	45 degrees counterclockwise from the X axis
;
;	IDL> one_ray, 256, 256, 32, 45 ,term, THICK = 2
;
; PROCEDURE:  straightforward matrix arithmetic
;
; MODIFICATION HISTORY:
;    Written by R. S. Hill, Hughes STX Corp., 20-May-1992.
;    Modified to work correctly for COLOR=0  J.Wm.Parker  HITC   1995 May 25
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;      OPLOTERROR
; PURPOSE:
;      Over-plot data points with accompanying X or Y error bars.
; EXPLANATION:
;      For use instead of PLOTERROR when the plotting system has already been
;      defined. 
;
; CALLING SEQUENCE:
;      oploterror, [ x,]  y, [xerr], yerr,   
;            [ /NOHAT, HATLENGTH= , ERRTHICK =, ERRSTYLE=, ERRCOLOR =, 
;              /LOBAR, /HIBAR, NSKIP = , NSUM = , ... OPLOT keywords ]
; INPUTS:
;      X = array of abcissae, any datatype except string
;      Y = array of Y values, any datatype except string
;      XERR = array of error bar values (along X)
;      YERR = array of error bar values (along Y)
;
; OPTIONAL INPUT KEYWORD PARAMETERS:
;      /NOHAT     = if specified and non-zero, the error bars are drawn
;                  without hats.
;      HATLENGTH = the length of the hat lines used to cap the error bars.
;                  Defaults to !D.X_VSIZE / 100).
;      ERRTHICK  = the thickness of the error bar lines.  Defaults to the
;                  THICK plotting keyword.
;      ERRSTYLE  = the line style to use when drawing the error bars.  Uses
;                  the same codes as LINESTYLE.
;      ERRCOLOR =  scalar integer (0 - !D.N_TABLE) specifying the color to
;                  use for the error bars
;      NSKIP = Positive Integer specifying the error bars to be plotted.   
;            For example, if NSKIP = 2 then every other error bar is 
;            plotted; if NSKIP=3 then every third error bar is plotted.   
;            Default is to plot every error bar (NSKIP = 1)
;      NSUM =  Number of points to average over before plotting, default = 
;             !P.NSUM  The errors are also averaged, and then divided by 
;             sqrt(NSUM).   This approximation is meaningful only when the 
;             neighboring error bars have similar sizes.
; 
;      /LOBAR = if specified and non-zero, will draw only the -ERR error bars.
;      /HIBAR = if specified and non-zero, will draw only the +ERR error bars.
;                  If neither LOBAR or HIBAR are set _or_ if both are set,
;                  you will get both error bars.  Just specify one if you
;                  only want one set.
;     Any valid keywords to the OPLOT command (e.g. PSYM, YRANGE) are also 
;     accepted by OPLOTERROR via the _EXTRA facility.
;
; NOTES:
;     If only two parameters are input, they are taken as Y and YERR.  If only
;     three parameters are input, they will be taken as X, Y and YERR, 
;     respectively.
;
; EXAMPLE:
;      Suppose one has X and Y vectors with associated errors XERR and YERR
;      and that a plotting system has already been defined:
;
;       (1) Overplot Y vs. X with both X and Y errors and no lines connecting
;           the points
;                  IDL> oploterror, x, y, xerr, yerr, psym=3
;
;       (2) Like (1) but overplot only the Y errors bars and omits "hats"
;                  IDL> oploterror, x, y, yerr, psym=3, /NOHAT
;
;       (3) Like (2) but suppose one has a positive error vector YERR1, and 
;               a negative error vector YERR2 (asymmetric error bars)
;                  IDL> oploterror, x, y, yerr1, psym=3, /NOHAT,/HIBAR
;                  IDL> oploterror, x, y, yerr2, psym=3, /NOHAT,/LOBAR
;
; PROCEDURE:
;      A plot of X versus Y with error bars drawn from Y - YERR to Y + YERR
;      and optionally from X - XERR to X + XERR is written to the output device
;
; WARNING:
;      This an enhanced version of the procedure OPLOTERR in the standard RSI
;      library.    It was renamed to OPLOTERROR in June 1998 in the IDL 
;      Astronomy library.
;
; MODIFICATION HISTORY:
;      Adapted from the most recent version of PLOTERR.  M. R. Greason,
;            Hughes STX, 11 August 1992.
;      Added COLOR keyword option to error bars W. Landsman   November 1993
;      Add ERRCOLOR, use _EXTRA keyword,           W. Landsman, July 1995
;      Remove spurious call to PLOT_KEYWORDS     W. Landsman, August 1995
;      OPLOT more than 32767 error bars          W. Landsman, Feb 1996
;      Added NSKIP keyword                       W. Landsman, Dec 1996
;      Added HIBAR and LOBAR keywords, M. Buie, Lowell Obs., Feb 1998
;      Rename to OPLOTERROR    W. Landsman    June 1998
;      Converted to IDL V5.0   W. Landsman    June 1998
;      Ignore !P.PSYM when drawing error bars   W. Landsman   Jan 1999
;      Handle NSUM keyword correctly           W. Landsman    Aug 1999
;      Check limits for logarithmic axes       W. Landsman    Nov. 1999
;      Work in the presence of  NAN values     W. Landsman    Dec 2000
;      Improve logic when NSUM or !P.NSUM is set  W. Landsman      Jan 2001
;      Remove NSUM keyword from PLOTS call    W. Landsman      March 2001
;      Only draw error bars with in XRANGE (for speed)  W. Landsman Jan 2002
;      Fix Jan 2002 update to work with log plots  W. Landsman Jun 2002

; NAME:
;	ORDINAL
; PURPOSE:
;	Convert an integer to a correct English ordinal string:
; EXPLANATION:
;	The first four ordinal strings are "1st", "2nd", "3rd", "4th" ....
;
; CALLING SEQUENCE:
;	result = ordinal( num )
;
; INPUT PARAMETERS:
;	num = number to be made an ordinal.  If float, will be FIXed.
;
; OUTPUT PARAMETERS:
;	result = string such as '1st' '3rd' '164th' '87th', etc.
;
; MODIFICATION HISTORY:  
;	Written by R. S. Hill, STX, 8 Aug. 1991
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	OSFCNVRT
;
; PURPOSE:
;	Return the correctly formatted logical directory syntax for the host OS
;
; CALLING SEQUENCE:
;	OSFCNVRT,lname
;
; INPUTS:
;	lname	- the file specification as a logical name + file name string
;
; OUTPUTS:
;	Returns appropriate string.
;
; SIDE EFFECTS:
;	None.
;
; RESTRICTIONS:
;	Assumes that the input is composed of only a logical and a filename combination
;	without lower directory garbage.
;
; PROCEDURE:
;	The operating system in !version.os is checked. If it equals:
;
;		'vms'		then a ':' is appended.
;
;		else		unix os is assumed and the logical portion is
;				uppercased, a '$' is prepended and a '/' is
;				appended.
;
; MODIFICATION HISTORY:
;	Written, JDNeill, May, 1990.
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;      PARTVELVEC
;
; PURPOSE:
;	Plot the velocity vectors of particles at their positions
; EXPLANATION:
;       This procedure plots the velocity vectors of particles (at the
;       positions of the particles).
;
; CATEGORY:
;       Plotting, Two-dimensional.
;
; CALLING SEQUENCE:
;       PARTVELVEC, VELX, VELY, POSX, POSY [, X, Y]
;
; INPUTS:
;       VELX:  An array of any dimension, containing the x-components
;              of the particle velocities.
;       VELY:  An array of the same dimension as velx, containing the 
;              y-components of the particle velocities.
;       POSX:  An array of the same dimension as velx, containing the
;              x-components of the particle positions.
;       POSY:  An array of the same dimension as velx, containing the 
;              y-components of the particle positions.
;
; OPTIONAL INPUTS:
;       X:   Optional abcissae values. X must be a vector.
;       Y:   Optional ordinate values. Y must be a vector. If only X 
;            is specified, then Y is taken equal to be equal to X.
;	
; OPTIONAL INPUT KEYWORD PARAMETERS:
;       FRACTION:   The fraction of the vectors to plot. They are
;                   taken at random from the complete sample.    Default is
;	            FRACTION = 1.0, use all vectors
;
;       LENGTH:     The maximum vectorlength relative to the plot data
;                   window.   Default = 0.08
;
;       COLOR:      The color for the vectors, axes and titles. 
;	            Default=!P.COLOR
;
;       OVER:       Plot over the previous plot
;
;       Plot        All other keywords available to PLOT are also used
;       Keywords:   by this procedure.
;
; OUTPUTS:
;       This procedure plots the velocity vectors (VELX,VELY) at the
;       positions of the particles, (POSX,POSY). If X and Y are not
;       specified, then the size of the plot is such that all vectors
;       just fit within in the plot data window.
;            
; SIDE EFFECTS:
;       Plotting on the current device is performed.
;
; EXAMPLE:
;       Generate some particle positions and velocities.
;
;         POSX=RANDOMU(seed,200)
;         POSY=RANDOMU(seed,200)
;         VELX=RANDOMU(seed,200)-0.5
;         VELY=RANDOMU(seed,200)-0.5
;
;       Plot the particle velocities.
;
;         PARTVELVEC, VELX, VELY, POSX, POSY
;
; MODIFICATION HISTORY:
;       Written by:  Joop Schaye (jschaye@astro.rug.nl), Sep 1996.
;	Converted to IDL V5.0   W. Landsman   September 1997
;       Added /OVER keyword   Theo Brauers (th.brauers@fz-juelich.de) Jul 2002

; NAME:
;    PCA
;
; PURPOSE:
;    Carry out a Principal Components Analysis (Karhunen-Loeve Transform)
; EXPLANATION:
;    Results can be directed to the screen, a file, or output variables
;    See notes below for comparison with the intrinsic IDL function PCOMP.
;
; CALLING SEQUENCE:
;    PCA, data, eigenval, eigenvect, percentages, proj_obj, proj_atr, 
;             [MATRIX =, TEXTOUT = ,/COVARIANCE, /SSQ, /SILENT ]
;
; INPUT PARAMETERS:
;     data -  2-d data matrix, data(i,j) contains the jth attribute value
;               for the ith object in the sample.    If N_OBJ is the total
;               number of objects (rows) in the sample, and N_ATTRIB is the 
;               total number of attributes (columns) then data should be
;               dimensioned N_OBJ x N_ATTRIB.
;
; OPTIONAL INPUT KEYWORD PARAMETERS:
;     /COVARIANCE - if this keyword is set, then the PCA will be carried out
;              on the covariance matrix (rare), the default is to use the
;              correlation matrix
;     /SILENT - If this keyword is set, then no output is printed
;     /SSQ - if this keyword is set, then the PCA will be carried out on
;               on the sums-of-squares & cross-products matrix (rare)
;     TEXTOUT - Controls print output device, defaults to !TEXTOUT
;
;              textout=1       TERMINAL using /more option
;              textout=2       TERMINAL without /more option
;              textout=3       .prt
;              textout=4       laser.tmp
;              textout=5      user must open file
;              textout = filename (default extension of .prt)
;
; OPTIONAL OUTPUT PARAMETERS:
;     eigenval -  N_ATTRIB element vector containing the sorted eigenvalues
;     eigenvect - N_ATRRIB x N_ATTRIB matrix containing the corresponding 
;               eigenvectors
;     percentages - N_ATTRIB element containing the cumulative percentage 
;             variances associated with the principal components
;     proj_obj - N_OBJ by N_ATTRIB matrix containing the projections of the 
;             objects on the principal components
;     proj_atr - N_ATTRIB by N_ATTRIB matrix containing the projections of 
;               the attributes on the principal components
;
; OPTIONAL OUTPUT PARAMETER
;      MATRIX   = analysed matrix, either the covariance matrix if /COVARIANCE
;              is set, the "sum of squares and cross-products" matrix if
;              /SSQ is set, or the (by default) correlation matrix.    Matrix
;              will have dimensions N_ATTRIB x N_ATTRIB
;
; NOTES:
;      This procedure performs Principal Components Analysis (Karhunen-Loeve
;      Transform) according to the method described in "Multivariate Data 
;      Analysis" by Murtagh & Heck [Reidel : Dordrecht 1987], pp. 33-48. 
;
;      Keywords /COVARIANCE and /SSQ are mutually exclusive.
;
;      The printout contains only (at most) the first seven principle 
;      eigenvectors.    However, the output variables EIGENVECT contain 
;      all the eigenvectors
;       
;      Different authors scale the covariance matrix in different ways.
;      The eigenvalues output by PCA may have to be scaled by 1/N_OBJ or
;      1/(N_OBJ-1) to agree with other calculations when /COVAR is set.
;
;      PCA uses the non-standard system variables !TEXTOUT and !TEXTUNIT.
;      These can be added to one's session using the procedure ASTROLIB.
;
;      The intrinsic IDL function PCOMP (introduced in V5.0) duplicates most
;      most of the functionality of PCA, but uses different conventions and
;      normalizations.   Note the following:
;
;   (1) PCOMP requires a N_ATTRIB x N_OBJ input array; this is the transpose
;         of what PCA expects
;   (2) PCA uses standardized variables; use /STANDARIZE keyword to PCOMP
;         for a direct comparison.
;   (3) PCA (unlike PCOMP) normalizes the eigenvectors by the square root
;         of the eigenvalues.
;   (4) PCA returns cumulative percentages; the VARIANCES keyword of PCOMP
;         returns the variance in each variable
;
; EXAMPLE:
;      Perform a PCA analysis on the covariance matrix of a data matrix, DATA,
;      and write the results to a file
;
;      IDL> PCA, data, /COVAR, t = 'pca.dat'
;
;      Perform a PCA analysis on the correlation matrix.   Suppress all 
;      printing, and save the eigenvectors and eigenvalues in output variables
;
;      IDL> PCA, data, eigenval, eigenvect, /SILENT
;
; PROCEDURES CALLED:
;      TEXTOPEN, TEXTCLOSE
;
; REVISION HISTORY:
;      Immanuel Freedman (after Murtagh F. and Heck A.).     December 1993
;      Wayne Landsman, modified I/O              December 1993
;      Converted to IDL V5.0   W. Landsman   September 1997
;      Fix MATRIX output, remove GOTO statements   W. Landsman August 1998      
;      Changed some index variable to type LONG    W. Landsman March 2000

; NAME:
;       PENT
; PURPOSE:
;       Return the information entropy of a time series
; EXPLANATION:
;       This function will return S, the information entropy of a time series
;       for a set of trial periods 
;
; CATEGORY:
;       Time series analysis, period finding, astronomical utilities.
;
; CALLING SEQUENCE:
;       Result = PENT(P, T, X, [N, M ] )
;
; INPUTS:
;       P - array of trial period values.
;       T - array of observation times (same units as P).
;       X - array of observations.
;
; OPTIONAL INPUTS:
;       N   - If  four parameters are given then the 4th parameter is assumed
;               to be N. Then NxN boxes are used to calculate S.
;       M,N - If five parameters are given then parameter 4 is M and parameter
;               5 is N. S is then calculated using MxN boxes - M partitions for the
;               phase and N partitions for the data.
;       
; OUTPUTS:
;       This function returns S, the information entropy of the time series for
;       the periods given in P as defined by Cincotta, Me'ndez & Nu'n~ez
;       (Astrophysical Journal 449, 231-235, 1995). The minima of S occur at
;       values of P where X shows periodicity.
;   
; PROCEDURE:
;       The procedure involves dividing the phase space into N^2 partitions 
;       (NxN boxes) and then calculating:
;       
;               __ N^2
;         S = - \        mu_i . ln(mu_i)  for all mu_i <> 0
;               /_  
;                 i = 1 
;
;       where  mu_i is the number of data points in partition i normalised by 
;       the number of partitions.
;
;       The option of using MxN boxes is an additional feature of this routine.
;
; EXAMPLE:
;
;       To generate a similar sythetic data set to Cincotta et al. we
;        do the following:
;
;       IDL> P0 = 173.015                        ; Fundamental period
;       IDL> T = randomu(seed,400)*15000         ; 400 random observation times
;       IDL> A0 = 14.0                           ; Mean magnitude
;       IDL> M0 = -0.5  * sin(2*!pi*T/P0)        ; Fundamental mode
;       IDL> M1 = -0.15 * sin(4*!pi*T/P0)        ; 1st harmonic
;       IDL> M2 = -0.05 * sin(6*!pi*T/P0)        ; 2nd harmonic
;       IDL> sig = randomu(seed,400)*0.03        ; noise
;       IDL> U = A0 + M0 + M1 + M2 + sig         ; Synthetic data
;       IDL> Ptest = 100. + findgen(2000)/2.     ; Trial periods 
;       IDL> S = pent(Ptest,T,U)                 ; Calculate S
;               ... this takes a few seconds ...
;       IDL> plot,Ptest,S,xtitle="P",ytitle="S"  ; plot S v. P
;       IDL> print,Ptest(where(S eq min(S)))     ; Print best period (+/- 0.5)
;
;       The plot produced should be similar to Fig. 2 of Cincotta et al.
;
; RESTRICTIONS:
;
;       My own (limited) experience with this routine suggests that it is not
;       as good as other techniques for finding  weak,  multi-periodic signals in 
;       poorly sampled  data, but is good for establishing periods of eclipsing
;       binary stars when M is quite large (try MxN = 64x16, 128x16 or even 
;       256x16).  This suggests it may be good for other periodic light curves 
;       (Cepheids, RR Lyrae etc.).
;       I would be glad to receive reports of other peoples experience with
;       this technique (e-mail pflm@bro730.astro.ku.dk).
;
; MODIFICATION HISTORY:
;       Written by:   Pierre Maxted, 14Sep95
;       Modifications:
;       Normalisation of S corrected, T-min(T) taken out of loop.
;               -  Pierre Maxted, 15Sep95
;       Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	PIXCOLOR
; PURPOSE:
;	Assign colors to specified pixel values in a color lookup table
;
; CALLING SEQUENCE:
;      	PIXCOLOR, pixvalue, color         ;Set color at specified pixel values
;
; OPTIONAL INPUT PARMETERS:
;	pixvalue - value or range of pixel value whose color will be modified.
;		A single pixel value may be specified by an integer
;		If a range of values is specified, then it must be written
;		as a string, with a colon denoting the range (e.g.'102:123')
;		If omitted, program will prompt for this parameter.
;
;	color -    single character string giving specified color values.
;		Available options are 'R' (red), 'B' (blue), 'G' (green)
;		'Y' (yellow), 'T' (turquoise), 'V' (violet), 'W' (white)
;		or 'D' (dark).  If omitted, program will prompt for this 
;		parameter.
;
; OUTPUTS:
;	None
; PROCEDURE:
;	TVLCT is used in RGB mode to load the specified pixel values.
;
; EXAMPLE:
;	Set pixel values of 245 to a color of red
;
;	IDL> pixcolor,245,'R'
;
; REVISION HISTORY:
;	Written, W. Landsman ST Systems Corp.		February, 1987
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	PIXWT
; PURPOSE: 
;	Circle-rectangle overlap area computation.
; DESCRIPTION:
;	Compute the fraction of a unit pixel that is interior to a circle.
;	The circle has a radius r and is centered at (xc, yc).  The center of
;	the unit pixel (length of sides = 1) is at (x, y).
;
; CATEGORY:
;	CCD data processing
; CALLING SEQUENCE:
;	area = Pixwt( xc, yc, r, x, y )
; INPUTS:
;	xc, yc : Center of the circle, numeric scalars
;	r      : Radius of the circle, numeric scalars
;	x, y   : Center of the unit pixel, numeric scalar or vector
; OPTIONAL INPUT PARAMETERS:
;	None.
; KEYWORD PARAMETERS:
;	None.
; OUTPUTS:
;	Function value: Computed overlap area.
; EXAMPLE:
;       What is the area of overlap of a circle with radius 3.44 units centered
;       on the point 3.23, 4.22 with the pixel centered at [5,7]
;
;       IDL> print,pixwt(3.23,4.22,3.44,5,7)  ==>  0.6502
; COMMON BLOCKS:
;    None.
; PROCEDURE:
;	Divides the circle and rectangle into a series of sectors and
;	triangles.  Determines which of nine possible cases for the
;	overlap applies and sums the areas of the corresponding sectors
;	and triangles.    Called by aper.pro
;
; NOTES:
;      If improved speed is needed then a C version of this routines, with
;      notes on how to linkimage it to IDL is available at   
;       ftp://ftp.lowell.edu/pub/buie/idl/custom/
;
; MODIFICATION HISTORY:
;     Ported by Doug Loucks, Lowell Observatory, 1992 Sep, from the
;    routine pixwt.c, by Marc Buie.

; NAME:
;	PKFIT
; PURPOSE:
;	Subroutine of  GETPSF to perform a one-star least-squares fit 
; EXPLANATION:
;	Part of the DAOPHOT PSF photometry sequence
;
; CALLING SEQUENCE:
;	PKFIT, f, scale, x, y, sky, radius, ronois, phpadu, gauss, psf, 
;				errmag, chi, sharp, Niter, /DEBUG 
; INPUTS:
;	F      - NX by NY array containing actual picture data.           
;	X, Y   - the initial estimates of the centroid of the star relative
;		to the corner (0,0) of the subarray.  Upon return, the
;		final computed values of X and Y will be passed back to the
;		calling routine.
;	SKY  -   the local sky brightness value, as obtained from APER
;	RADIUS-  the fitting radius-- only pixels within RADIUS of the
;		instantaneous estimate of the star's centroid will be
;		included in the fit, scalar
;	RONOIS - readout noise per pixel, scalar
;	PHPADU - photons per analog digital unit, scalar
;	GAUSS -  vector containing the values of the five parameters defining
;		the analytic Gaussian which approximates the core of the PSF.
;	PSF   -  an NPSF by NPSF look-up table containing corrections from
;		the Gaussian approximation of the PSF to the true PSF.
;
; INPUT-OUTPUT:
;	SCALE  - the initial estimate of the brightness of the star,
;		expressed as a fraction of the brightness of the PSF.
;		Upon return, the final computed value of SCALE will be
;		passed back to the calling routine.
; OUTPUTS:
;	ERRMAG - the estimated standard error of the value of SCALE
;		returned by this routine.
;	CHI    - the estimated goodness-of-fit statistic:  the ratio
;		of the observed pixel-to-pixel mean absolute deviation from
;		the profile fit, to the value expected on the basis of the
;		noise as determined from Poisson statistics and the 
;		readout noise.
;	SHARP  - a goodness-of-fit statistic describing how much broader  
;		the actual profile of the object appears than the
;		profile of the PSF.
;	NITER -  the number of iterations the solution required to achieve
;		convergence.  If NITER = 25, the solution did not converge.
;		If for some reason a singular matrix occurs during the least-
;		squares solution, this will be flagged by setting NITER = -1.
;
; RESTRICTIONS:
;	No parameter checking is performed
; REVISON HISTORY:
;	Adapted from the official DAO version of 1985 January 25
;	Version 2.0 W. Landsman STX             November 1988
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;       PLANCK()   
; PURPOSE: 
;       To calculate the Planck function in units of ergs/cm2/s/A  
;
; CALLING SEQUENCE: 
;       bbflux = PLANCK( wave, temp) 
;
; INPUT PARAMETERS: 
;       WAVE   Scalar or vector giving the wavelength(s) in **Angstroms**
;               at which the Planck function is to be evaluated.
;       TEMP   Scalar giving the temperature of the planck function in degree K
;
; OUTPUT PARAMETERS:
;       BBFLUX - Scalar or vector giving the blackbody flux (i.e. !pi*Intensity)
;               in erg/cm^2/s/A in at the specified wavelength points.
;
; EXAMPLES:
;       To calculate the blackbody flux at 30,000 K every 100 Angstroms between
;       2000A and 2900 A
;   
;       IDL> wave = 2000 + findgen(10)*100
;       IDL> bbflux = planck(wave,30000)
;
;       If a star with a blackbody spectrum has a radius R, and distance,d, then
;       the flux at Earth in erg/cm^2/s/A will be bbflux*R^2/d^2
; PROCEDURE:
;       The wavelength data are converted to cm, and the Planck function
;       is calculated for each wavelength point. See Allen (1973), Astrophysical
;       Quantities, section 44 for more information.
;
; NOTES:
;       See the procedure planck_radiance.pro in 
;       ftp://origin.ssec.wisc.edu/pub/paulv/idl/Radiance/planck_radiance.pro
;       for computation of Planck radiance given wavenumber in cm-1 or  
;       wavelength in microns 
; MODIFICATION HISTORY:
;       Adapted from the IUE RDAF               August, 1989
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Improve precision of constants    W. Landsman  January 2002

; NAME:
;    PLANET_COORDS
; PURPOSE:  
;    Find low or high precision RA and DEC for the planets given a date
;
; EXPLANATION:
;    For low precision this routine uses HELIO to get the heliocentric ecliptic
;    coordinates of the planets at the given date, then converts these to 
;    geocentric ecliptic coordinates ala "Astronomical Algorithms" by Jean 
;    Meeus (1991, p 209). These are then converted to RA and Dec using EULER.
;    The accuracy between the years 1800 and 2050 is better than 1 arcminute 
;    for  the terrestial planets, but reaches 10 arcminutes for Saturn.    
;    Before 1850 or after 2050 the accuracy can get much worse.   
;
;    For high precision use the /JPL option ito use the full JPL ephemeris.
; CALLING SEQUENCE:
;    PLANET_COORDS, DATE, RA, DEC, [ PLANET = , /JD, /JPL]
;
; INPUTS:
;       DATE - If /JD is not set, then date is a 3-6 element vector containing
;              year,month (1-12), day, and optionally hour, minute, & second.
;              If /JD is set then DATE is a Julian date.   An advantage of the
;              /JD option is that it allows the use of vector dates.
; OUTPUTS:
;       RA - right ascension of planet(s), J2000 degrees, double precision
;       DEC - declination of   planet(s), J2000 degrees, double precision
;
; OPTIONAL INPUT KEYWORD:
;       PLANET - scalar string giving name of a planet, e.g. 'venus'. Default 
;               is to compute coords for all of them (except Earth).
;       /JD - If set, then the date parameter should be supplied as Julian date
;       JPL - if /JPL set, then PLANET_COORDS will call the procedure 
;             JPLEPHINTERP to compute positions using the full JPL ephemeris.   
;             The JPL ephemeris FITS file JPLEPH.405 must exist in either the 
;             current directory, or in the directory specified by the 
;             environment variable ASTRO_DATA.   Alternatively, the JPL keyword
;             can be set to the full path and name of the ephemeris file.
;             A copy of the JPL ephemeris FITS file JPLEPH.405 is available in
;                 http://idlastro.gsfc.nasa.gov/ftp/data/         
; EXAMPLES:
;    (1)  Find the RA, Dec of Venus on 1992 Dec 20
;          IDL> planet_coords, [1992,12,20], ra,dec    ;Compute for all planets
;          IDL> print,adstring(ra[1],dec[1],1)         ;Venus is second planet
;     ====> RA = 21 05  2.66  Dec = -18 51 45.7
;    This position is 37" from the full DE406 ephemeris position of
;          RA = 21 05  5.24        -18 51 43.1
;
;    (2) Return the current RA and Dec of all 8 planets using JPL ephemeris
;          IDL> get_juldate, jd                 ;Get current Julian Date
;          IDL> planet_coords,jd,ra,dec,/jd,/jpl  ;Find positions of all planets
;          IDL> forprint,adstring(ra,dec,0)     ;Display positions   
;
;    (3) Plot the declination of Mars for every day in the year 2001
;          IDL> jdcnv,2001,1,1,0,jd      ;Get Julian date of midnight on Jan 1 
;               Now get Mars RA,Dec for 365 consecutive days
;          IDL> planet_coords,jd+indgen(365),ra,dec,/jd, planet = 'mars'     
;          IDL> plot,indgen(365)+1,dec
; NOTES:
;          HELIO is based on the two-body problem and neglects interactions 
;           between the planets.   This is why the worst results are for
;           Saturn.   Use the /JPL option or the online ephemeris generator 
;           http://ssd.jpl.nasa.gov/cgi-bin/eph for more accuracy. 
;
;           The procedure returns astrometric coordinates, i.e. no correction
;           for aberration.   A correction for light travel time is applied
;           when /JPL is set, but not for the default low-precision calculation.
; PROCEDURES USED:
;        JULDATE 
;        EULER, HELIO  - if /JPL is not set
;        JPLEPHREAD, JPLEPHINTERP - if /JPL is set
; REVISION HISTORY:
;        Written P.Plait & W. Landsman     August 2000
;        Fixed Julian date conversion   W. Landsman August 2000
;        Added /JPL keyword  W. Landsman   July 2001
;        Allow vector Julian dates with JPL ephemeris W. Landsman December 2002

; NAME:
;     PLOTERROR
; PURPOSE:
;     Plot data points with accompanying X or Y error bars.
; EXPLANATION:
;     This is a greatly enhanced version of the standard IDL Library routine
;     PLOTERR
;
; CALLING SEQUENCE:
;     ploterror, [ x,]  y, [xerr], yerr [, TYPE=, /NOHAT, HATLENGTH= , NSUM =
;                  ERRTHICK=, ERRSTYLE=, ERRCOLOR=, NSKIP=, .. PLOT keywords]
;
; INPUTS:
;     X = array of abcissae.
;     Y = array of Y values.
;     XERR = array of error bar values (along X)
;     YERR = array of error bar values (along Y)
;
; OPTIONAL INPUT KEYWORD PARAMETERS:
;     TYPE = type of plot produced.  The possible types are:
;              TYPE = 0 :       X Linear - Y Linear  (default)
;              TYPE = 1 :       X Linear - Y Log
;              TYPE = 2 :       X Log    - Y Linear
;              TYPE = 3 :       X Log    - Y Log
;              Actually, if 0 is specified, the XLOG and YLOG keywords
;              are used.  If these aren't specified, then a linear-linear
;              plot is produced.  This keyword is available to maintain
;              compatibility with the previous version of PLOTERROR.
;     /NOHAT     = if specified and non-zero, the error bars are drawn
;              without hats.
;     HATLENGTH = the length of the hat lines in device units used to cap the 
;              error bars.   Defaults to !D.X_VSIZE / 100).
;     ERRTHICK  = the thickness of the error bar lines.  Defaults to the
;              THICK plotting keyword.
;     ERRSTYLE  = the line style to use when drawing the error bars.  Uses
;              the same codes as LINESTYLE.
;     ERRCOLOR =  scalar integer (0 - !D.N_TABLE) specifying the color to
;              use for the error bars
;     NSKIP = Integer specifying the error bars to be plotted.   For example,
;              if NSKIP = 2 then every other error bar is plotted; if NSKIP=3
;              then every third error bar is plotted.   Default is to plot
;              every error bar (NSKIP = 1)
;     NSUM =  Number of points to average over before plotting, default=!P.NSUM
;             The errors are also averaged, and then divided by sqrt(NSUM).   
;             This  approximation is meaningful only when the neighboring error
;             bars have similar sizes.    PLOTERROR does not pass the NSUM 
;             keyword to the PLOT command, but rather computes the binning 
;             itself using the  FREBIN function.
;
;     Any valid keywords to the PLOT command (e.g. PSYM, YRANGE) are also 
;     accepted by PLOTERROR via the _EXTRA facility.
;
; RESTRICTIONS:
;       Arrays must not be of type string.  There must be enough points to plot.
;       If only three parameters are input, they will be taken as X, Y and
;       YERR respectively.
;
;       PLOTERROR cannot be used for asymmetric error bars.   Instead use
;       OPLOTERROR with the /LOBAR and /HIBAR keywords.
;
;       Any data points with NAN values in the X, Y, or error vectors are 
;       ignored.
; EXAMPLE:
;       Suppose one has X and Y vectors with associated errors XERR and YERR
;
;       (1) Plot Y vs. X with both X and Y errors and no lines connecting
;           the points
;                  IDL> ploterror, x, y, xerr, yerr, psym=3
;
;       (2) Like (1) but plot only the Y errors bars and omits "hats"
;                  IDL> ploterror, x, y, yerr, psym=3, /NOHAT
;
; WARNING:
;       This an enhanced version of the procedure PLOTERR in the standard IDL
;       distribution.    It was renamed from PLOTERR to PLOTERROR in June 1998
;       in the IDL Astronomy Library to avoid conflict with the RSI procedure.
;
; PROCEDURE:
;       A plot of X versus Y with error bars drawn from Y - YERR to Y + YERR
;       and optionally from X - XERR to X + XERR is written to the output device
;
; PROCEDURE CALLS:
;     FREBIN - used to compute binning if NSUM keyword is present
; MODIFICATION HISTORY:
;     William Thompson        Applied Research Corporation  July, 1986
;     DMS, April, 1989        Modified for Unix
;     Michael R. Greason      ST Systems
;     May, 1991               Added most of the plotting keywords, put hats
;                               on the error bars.
;     K. Venkatakrishna       Added option to plot xerr, May, 1992
;     Michael R. Greason      Corrected handling of reversed axes.  Aug. 1992
;     W. Landsman             Use _EXTRA keyword                    July 1995
;     W. Landsman             Plot more than 32767 points           Feb 1996
;     W. Landsman     Fix Y scaling when only XRANGE supplied       Nov 1996
;     W. Landsman     Added NSKIP keyword                           Dec 1996
;     W. Landsman     Use XLOG, YLOG instead of XTYPE, YTYPE        Jan 1998
;     W. Landsman     Rename to PLOTERROR, OPLOTERROR               Jun 1998
;     W. Landsman     Convert to IDL V5.0                           Jun 1998
;     W. Landsman  Better default scaling when NSKIP supplied       Oct 1998 
;     W. Landsman  Ignore !P.PSYM when drawing error bars           Jan 1999
;     W. Landsman  Handle NSUM keyword correctly                    Aug 1999
;     W. Landsman  Fix case of /XLOG but no X error bars            Oct 1999
;     W. Landsman  Work in the presence of NAN values               Nov 2000
;     W. Landsman  Improve logic when NSUM or !P.NSUM is set        Jan 2001
;     W. Landsman  Only draw error bars with in XRANGE (for speed)  Jan 2002
;     W. Landsman  Fix Jan 2002 update to work with log plots       Jun 2002

; NAME:
;      PLOTHIST
; PURPOSE:
;      Plot the histogram of an array with the corresponding abcissa.
;
; CALLING SEQUENCE:
;      plothist, arr, xhist, yhist, [, BIN=, /FILL, /NOPLOT, /OVERPLOT, PEAK=,
;                                      ...plotting keywords]
; INPUTS:
;      arr - The array to plot the histogram of.   It can include negative
;            values, but non-integral values will be truncated.              
;
; OPTIONAL OUTPUTS:
;      xhist - X vector used in making the plot  
;              ( = lindgen( N_elements(h)) * bin + min(arr) )
;      yhist - Y vector used in making the plot  (= histogram(arr/bin))
;
; OPTIONAL INPUT KEYWORDS:
;      BIN -  The size of each bin of the histogram,  scalar (not necessarily
;             integral).  If not present (or zero), the bin size is set to 1.
;      HALFBIN - Set this keyword to a nonzero value to shift the binning by
;              half a bin size.     This is useful for integer data, where e.g.
;              the bin for values of 6 will go from 5.5 to 6.5.   The default
;              is to set the HALFBIN keyword for integer data, and not for
;              non-integer data.    Note: prior to May 2002, the default was 
;              to always shift the binning by half a bin.                
;      /NAN - If set, then check for the occurence of IEEE not-a-number values
;      /NOPLOT - If set, will not plot the result.  Useful if intention is to
;             only get the xhist and yhist outputs.
;      /OVERPLOT - If set, will overplot the data on the current plot.  User
;            must take care that only keywords valid for OPLOT are used.
;      PEAK - if non-zero, then the entire histogram is normalized to have
;             a maximum value equal to the value in PEAK.  If PEAK is
;             negative, the histogram is inverted.
;      /FILL - if set, will plot a filled (rather than line) histogram.
;
; The following keywords take effect only if the FILL keyword is set:
;      FCOLOR - color to use for filling the histogram
;      /FLINE - if set, will use lines rather than solid color for fill (see
;              the LINE_FILL keyword in the POLYFILL routine)
;      FORIENTATION - angle of lines for fill (see the ORIENTATION keyword
;              in the POLYFILL routine)
;      FPATTERN - the pattern to use for the fill (see the PATTERN keyword
;              in the POLYFILL routine)
;      FSPACING - the spacing of the lines to use in the fill (see the SPACING
;              keyword in the POLYFILL routine)
;
; Any input keyword that can be supplied to the PLOT procedure (e.g. XRANGE,
;    LINESTYLE) can also be supplied to PLOTHIST.
;
; EXAMPLE:
;       Create a vector of random 1000 values derived from a Gaussian of mean 0,
;       and sigma of 1.    Plot the histogram of these values with a bin
;       size of 0.1
;
;       IDL> a = randomn(seed,1000)
;       IDL> plothist,a, bin = 0.1
;
; MODIFICATION HISTORY:
;        Written     W. Landsman            January, 1991
;        Add inherited keywords W. Landsman        March, 1994
;        Use ROUND instead of NINT  W. Landsman   August, 1995
;        Add NoPlot and Overplot keywords.   J.Wm.Parker  July, 1997
;        Add Peak keyword.   J.Wm.Parker  Jan, 1998
;        Add FILL,FCOLOR,FLINE,FPATTERN,FSPACING keywords. J.Wm.Parker Jan, 1998
;	 Converted to IDL V5.0   W. Landsman 21-Jan-1998
;        Add /NAN keyword        W. Landsman October 2001
;        Don't plot out of range with /FILL, added HALFBIN keyword, make
;        half bin shift default for integer only W. Landsman/J. Kurk May 2002

; NAME:
;     POIDEV
; PURPOSE:
;     Generate a Poisson random deviate
; EXPLANATION:
;     Return an integer random deviate drawn from a Poisson distribution with
;     a specified mean.    Adapted from procedure of the same name in 
;     "Numerical Recipes" by Press et al. (1992), Section 7.3
;
;     NOTE: This routine became partially obsolete in V5.0 with the 
;     introduction of the POISSON keyword to the intrinsic functions 
;     RANDOMU and RANDOMN.     However, POIDEV is still useful for adding 
;     Poisson noise to an existing image array, for which the coding is much 
;     simpler than it would be using RANDOMU (see example 1) 
; CALLING SEQUENCE:
;     result = POIDEV( xm, [ SEED = ] )
;
; INPUTS:
;     xm - numeric scalar, vector or array, specifying the mean(s) of the 
;          Poisson distribution
;
; OUTPUT:
;     result - Long integer scalar or vector, same size as xm
;
; OPTIONAL KEYWORD INPUT-OUTPUT:
;     SEED -  Scalar to be used as the seed for the random distribution.  
;             For best results, SEED should be a large (>100) integer.
;             If SEED is undefined, then its value is taken from the system 
;             clock (see RANDOMU).    The value of SEED is always updated 
;             upon output.   This keyword can be used to have POIDEV give 
;             identical results on consecutive runs.     
;
; EXAMPLE:
;     (1) Add Poisson noise to an integral image array, im
;              IDL> imnoise = POIDEV( im)
;
;     (2) Verify the expected mean  and sigma for an input value of 81
;              IDL> p = POIDEV( intarr(10000) + 81)   ;Test for 10,000 points
;              IDL> print,avg(p),sigma(p)
;     Average and sigma of the 10000 points should be close to 81 and 9
;
; METHOD: 
;     For small values (< 20) independent exponential deviates are generated 
;     until their sum exceeds the specified mean, the number of events 
;     required is returned as the Poisson deviate.   For large (> 20) values,
;     uniform random variates are compared with a Lorentzian distribution 
;     function.
;
; NOTES:
;     Negative values in the input array will be returned as zeros.  
;
;     Versions 5.1.1 and 5.2 of IDL have a bug in the RANDOMU function, such
;     that it is initialized to the same value at the start of each IDL session
;     rather than being initialized to the system clock.    This bug will affect
;     POIDEV in a similar manner.
;       
; REVISION HISTORY:
;      Version 1               Wayne Landsman        July  1992
;      Added SEED keyword                            September 1992
;      Call intrinsic LNGAMMA function               November 1994
;      Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;     POLINT
; PURPOSE:
;     Interpolate a set of N points by fitting a polynomial of degree N-1
; EXPLANATION:
;     Adapted from algorithm in Numerical Recipes, Press et al. (1992), 
;     Section 3.1.
;
; CALLING SEQUENCE
;     POLINT, xa, ya, x, y, [ dy ]
; INPUTS:
;     XA - X Numeric vector, all values must be distinct.   The number of
;          values in XA should rarely exceed 10 (i.e. a 9th order polynomial)
;     YA - Y Numeric vector, same number of elements
;     X - Numeric scalar specifying value to be interpolated 
;
; OUTPUT:
;     Y - Scalar, interpolated value in (XA,YA) corresponding to X
;
; OPTIONAL OUTPUT
;     DY - Error estimate on Y, scalar
;
; EXAMPLE:
;     Find sin(2.5) by polynomial interpolation on sin(indgen(10))
;
;               IDL> xa = indgen(10)
;               IDL> ya = sin( xa )
;               IDL> polint, xa, ya, 2.5, y ,dy
;             
;     The above method gives  y = .5988 & dy = 3.1e-4  a close
;     approximation to the actual sin(2.5) = .5985
;
; METHOD:
;     Uses Neville's algorithm to iteratively build up the correct
;     polynomial, with each iteration containing one higher order.
;
; REVISION HISTORY:
;     Written W. Landsman                 January, 1992
;     Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;       POLREC
; PURPOSE:
;       Convert 2-d polar coordinates to rectangular coordinates.
; CATEGORY:
; CALLING SEQUENCE:
;       polrec, r, a, x, y
; INPUTS:
;       r, a = vector in polar form: radius, angle (radians).  in
; KEYWORD PARAMETERS:
;       Keywords:
;         /DEGREES means angle is in degrees, else radians.
; OUTPUTS:
;       x, y = vector in rectangular form, double precision     out
; COMMON BLOCKS:
; NOTES:
; MODIFICATION HISTORY:
;       R. Sterner. 18 Aug, 1986.
;       Johns Hopkins University Applied Physics Laboratory.
;       RES 13 Feb, 1991 --- added /degrees.
;	Converted to IDL V5.0   W. Landsman   September 1997
;       1999 May 03 --- Made double precision.  R. Sterner.
;
; Copyright (C) 1986, 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.

; NAME:
;       POLYLEG
;
; PURPOSE:
;       Evaluate a Legendre polynomial with specified coefficients.
; EXPLANATION:
;       Meant to be used analogously to the POLY function in the IDL User's
;       Library distribution.
;
; CALLING SEQUENCE:
;       Result = POLYLEG( X, C )        
;
; INPUTS:
;       X - input variable, scalar or vector    
;       C - vector of Legendre polynomial coefficients. 
; OUTPUTS:
;       POLYLEG returns a result equal to:
;               C[0] + C[1]*P_1(x) + C[2]*P_2(x) + ...
;
;       where P_j(x) is the jth Legendre polynomial.   The output will have
;       the same dimensions as the input X variable.
;
; EXAMPLE:
;       If x = [0.5, 1.0] and C = [2.4, 1.3, 2.5] then
;       print, polyleg(x, c)    ====> [2.7375, 6.20]
;
;       The result can be checked using the first 3 Legendre polynomial terms
;       C[0] + C[1]*x + C[2]*(0.5*(3*x^2-1))
; METHOD:
;       Uses the recurrence relation of Legendre polynomials
;               (n+1)*P_n+1(x) = (2n+1)*x*P_n(x) - n*P_n-1(x)
;       evaluated with the Clenshaw recurrence formula, see Numerical Recipes
;       by Press et al. (1992), Section 5.5
;
; REVISION HISTORY:
;       Written W. Landsman   Hughes STX Co.        April, 1995    
;       Fixed for double precision  W. Landsman     May, 1997
;       Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;       POLY_SMOOTH  
;
; PURPOSE:
;       Apply a least-squares (Savitzky-Golay) polynomial smoothing filter
; EXPLANATION:
;       Reduce noise in 1-D data (e.g. time-series, spectrum) but retain 
;       dynamic range of variations in the data by applying a least squares 
;       smoothing polynomial filter,
;
;       Also called the Savitzky-Golay smoothing filter, cf. Numerical
;       Recipes (Press et al. 1992, Sec.14.8)
;
;       The low-pass filter coefficients are computed by effectively
;       least-squares fitting a polynomial in moving window,
;       centered on each data point, so the new value will be the
;       zero-th coefficient of the polynomial. Approximate first derivates
;       of the data can be computed by using first degree coefficient of
;       each polynomial, and so on. The filter coefficients for a specified
;       polynomial degree and window width are computed independent of any
;       data, and stored in a common block. The filter is then convolved
;       with the data array to result in smoothed data with reduced noise,
;       but retaining higher order variations (better than SMOOTH).
;
;       This procedure became partially obsolete in IDL V5.4 with the 
;       introduction of the SAVGOL function, which computes the smoothing
;       coefficients.
; CALLING SEQUENCE:
;
;       spectrum = poly_smooth( data, [ width, DEGREE = , NLEFT = , NRIGHT = 
;                                       DERIV_ORDER = ,COEFF = ]
;
; INPUTS:
;       data = 1-D array, such as a spectrum or time-series.
;
;       width = total number of data points to use in filter convolution,
;               (default = 5, using 2 past and 2 future data points),
;               must be larger than DEGREE of polynomials, and a guideline is to
;               make WIDTH between 1 and 2 times the FWHM of desired features.
;
; OPTIONAL INPUT KEYWORDS:
;
;       DEGREE = degree of polynomials to use in designing the filter
;               via least squares fits, (default DEGREE = 2)
;               The higher degrees will preserve sharper features.
;
;       NLEFT = # of past data points to use in filter convolution,
;               excluding current point, overrides width parameter,
;               so that width = NLEFT + NRIGHT + 1.  (default = NRIGHT)
;
;       NRIGHT = # of future data points to use (default = NLEFT).
;
;       DERIV_ORDER = order of derivative desired (default = 0, no derivative).
;
; OPTIONAL OUTPUT KEYWORD:
;
;       COEFFICIENTS = optional output of the filter coefficients applied,
;               but they are all stored in common block for reuse, anyway.
; RESULTS:
;       Function returns the data convolved with polynomial filter coefs.
;
; EXAMPLE:
;
;       Given a wavelength - flux spectrum (w,f), apply a 31 point quadratic
;       smoothing filter and plot
;
;       IDL> plot, w, poly_smooth(f,31) 
; COMMON BLOCKS:
;       common poly_smooth, degc, nlc, nrc, coefs, ordermax
;
; PROCEDURE:
;       As described in Numerical Recipies, 2nd edition sec.14.8, 
;       Savitsky-Golay filter.
;       Matrix of normal eqs. is formed by starting with small terms
;       and then adding progressively larger terms (powers).
;       The filter coefficients of up to derivative ordermax are stored
;       in common, until the specifications change, then recompute coefficients.
;       Coefficients are stored in convolution order, zero lag in the middle.
;
; MODIFICATION HISTORY:
;       Written, Frank Varosi NASA/GSFC 1993.
;       Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;       POSANG
; PURPOSE:
;       Computes rigorous position angle of source 2 relative to source 1
;       
; EXPLANATION:
;       Computes the rigorous position angle of source 2 (with given RA, Dec) 
;       using source 1 (with given RA, Dec) as the center.
; 
; CALLING SEQUENCE:
;       POSANG, U, RA1, DC1, RA2, DC2, ANGLE
;
; INPUTS:
;       U    -- Describes units of inputs and output:
;               0:  everything radians
;               1:  RAx in decimal hours, DCx in decimal
;                       degrees, ANGLE in degrees
;       RA1  -- Right ascension of point 1
;       DC1  -- Declination of point 1
;       RA2  -- Right ascension of point 2
;       DC2  -- Declination of point 2
;
;   OUTPUTS:
;       ANGLE-- Angle of the great circle containing [ra2, dc2] from
;               the meridian containing [ra1, dc1], in the sense north
;               through east rotating about [ra1, dc1].  See U above 
;               for units.
;
;   PROCEDURE:
;       The "four-parts formula" from spherical trig (p. 12 of Smart's
;       Spherical Astronomy or p. 12 of Green' Spherical Astronomy).
;
;   EXAMPLE:
;       For the star 56 Per, the Hipparcos catalog gives a position of 
;       RA = 66.15593384, Dec = 33.94988843 for component A, and 
;       RA = 66.15646079, Dec =  33.96100069 for component B.   What is the
;       position angle of B relative to A?
;
;       IDL> RA1 = 66.15593384/15.d   & DC1 = 33.95988843
;       IDL> RA2 = 66.15646079/15.d   & DC2 = 33.96100069
;       IDL> posang,1,ra1,dc1,ra2,dc2, ang
;            will give the answer of ang = 21.4 degrees
;   NOTES:
;       (1) If RA1,DC1 are scalars, and RA2,DC2 are vectors, then ANGLE is a
;       vector giving the position angle between each element of RA2,DC2 and 
;       RA1,DC1.   Similarly, if RA1,DC1 are vectors, and RA2, DC2 are scalars,
;       then DIS is a vector giving the position angle of each element of RA1, 
;       DC1 and RA2, DC2.    If both RA1,DC1 and RA2,DC2 are vectors then ANGLE 
;       is a vector giving the position angle between each element of RA1,DC1 
;       and the corresponding element of RA2,DC2.    If then vectors are not the
;       same length, then excess elements of the longer one will be ignored.
;
;       (2) Note that POSANG is not commutative -- the position angle between
;        A and B is theta, then the position angle between B and A is 180+theta 
;   PROCEDURE CALLS:
;        ISARRAY()
;   HISTORY:
;       Modified from GCIRC, R. S. Hill, RSTX, 1 Apr. 1998
;

; NAME:
;	POSITIVITY
; PURPOSE:
;	Map an image uniquely and smoothly into all positive values.
; EXPLANATION:
;	Take unconstrained x (usually an image), and map it uniquely and 
;	smoothly into positive values.   Negative values of x get mapped to 
;	interval ( 0, sqrt( epsilon )/2 ], positive values go to 
;	( sqrt( epsilon )/2, oo ) with deriv approaching 1.  Derivative is 
;	always 1/2 at x=0.   Derivative is used by the MRL deconvolution 
;	algorithm.
;
; CALLING SEQUENCE:
;	result = POSITIVITY( x, [ /DERIVATIVE, EPSILON = )
;
; INPUTS:
;	x - input array, unconstrained
;
; OUTPUT:
;	result =  output array = ((x + sqrt(x^2 + epsilon))/2
;		if the /DERIV keyword is set then instead the derivative of
;		the above expression with respect to X is returned
;
; OPTIONAL INPUT KEYWORDS:
;	DERIV -  if this keyword set, then the derivative of the positivity
;		mapping is returned, rather than the mapping itself
;	EPSILON - real scalar specifying the interval into which to map
;		negative values.    If EPSILON EQ 0 then the mapping reduces to 
;		positive truncation.   If EPSILON LT then the mapping reduces to
;		an identity (no change).  Default is EPSILON = 1e-9 
;
; REVISION HISTORY:
;	 F.Varosi NASA/GSFC 1992, as suggested by R.Pina UCSD.
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;      PRECESS
; PURPOSE:
;      Precess coordinates from EQUINOX1 to EQUINOX2.  
; EXPLANATION:
;      For interactive display, one can use the procedure ASTRO which calls 
;      PRECESS or use the /PRINT keyword.   The default (RA,DEC) system is 
;      FK5 based on epoch J2000.0 but FK4 based on B1950.0 is available via 
;      the /FK4 keyword.
;
;      Use BPRECESS and JPRECESS to convert between FK4 and FK5 systems
; CALLING SEQUENCE:
;      PRECESS, ra, dec, [ equinox1, equinox2, /PRINT, /FK4, /RADIAN ]
;
; INPUT - OUTPUT:
;      RA - Input right ascension (scalar or vector) in DEGREES, unless the 
;              /RADIAN keyword is set
;      DEC - Input declination in DEGREES (scalar or vector), unless the 
;              /RADIAN keyword is set
;              
;      The input RA and DEC are modified by PRECESS to give the 
;      values after precession.
;
; OPTIONAL INPUTS:
;      EQUINOX1 - Original equinox of coordinates, numeric scalar.  If 
;               omitted, then PRECESS will query for EQUINOX1 and EQUINOX2.
;      EQUINOX2 - Equinox of precessed coordinates.
;
; OPTIONAL INPUT KEYWORDS:
;      /PRINT - If this keyword is set and non-zero, then the precessed
;               coordinates are displayed at the terminal.    Cannot be used
;               with the /RADIAN keyword
;      /FK4   - If this keyword is set and non-zero, the FK4 (B1950.0) system
;               will be used otherwise FK5 (J2000.0) will be used instead.
;      /RADIAN - If this keyword is set and non-zero, then the input and 
;               output RA and DEC vectors are in radians rather than degrees
;
; RESTRICTIONS:
;       Accuracy of precession decreases for declination values near 90 
;       degrees.  PRECESS should not be used more than 2.5 centuries from
;       2000 on the FK5 system (1950.0 on the FK4 system).
;
; EXAMPLES:
;       (1) The Pole Star has J2000.0 coordinates (2h, 31m, 46.3s, 
;               89d 15' 50.6"); compute its coordinates at J1985.0
;
;       IDL> precess, ten(2,31,46.3)*15, ten(89,15,50.6), 2000, 1985, /PRINT
;
;               ====> 2h 16m 22.73s, 89d 11' 47.3"
;
;       (2) Precess the B1950 coordinates of Eps Ind (RA = 21h 59m,33.053s,
;       DEC = (-56d, 59', 33.053") to equinox B1975.
;
;       IDL> ra = ten(21, 59, 33.053)*15
;       IDL> dec = ten(-56, 59, 33.053)
;       IDL> precess, ra, dec ,1950, 1975, /fk4
;
; PROCEDURE:
;       Algorithm from Computational Spherical Astronomy by Taff (1983), 
;       p. 24. (FK4). FK5 constants from "Astronomical Almanac Explanatory
;       Supplement 1992, page 104 Table 3.211.1.
;
; PROCEDURE CALLED:
;       Function PREMAT - computes precession matrix 
;
; REVISION HISTORY
;       Written, Wayne Landsman, STI Corporation  August 1986
;       Correct negative output RA values   February 1989
;       Added /PRINT keyword      W. Landsman   November, 1991
;       Provided FK5 (J2000.0)  I. Freedman   January 1994
;       Precession Matrix computation now in PREMAT   W. Landsman June 1994
;       Added /RADIAN keyword                         W. Landsman June 1997
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Correct negative output RA values when /RADIAN used    March 1999 
;       Work for arrays, not just vectors  W. Landsman    September 2003 

; NAME:
;       PRECESS_CD
;
; PURPOSE:
;       Precess the CD (coordinate description) matrix from a FITS header 
; EXPLANATION:
;       The CD matrix is precessed from EPOCH1 to EPOCH2.  Called by HPRECESS
;
; CALLING SEQUENCE:
;       PRECESS_CD, cd, epoch1, epoch2, crval_old, crval_new, [/FK4]  
;
; INPUTS/OUTPUT:
;       CD - 2 x 2 CD (coordinate description) matrix in any units
;               (degrees or radians).  CD will altered on output to contain 
;               precessed values in the same units.    On output CD will always
;               be double precision no matter how input.
;
; INPUTS:
;       EPOCH1 - Original equinox of coordinates, scalar (e.g. 1950.0).  
;       EPOCH2 - Equinox of precessed coordinates, scalar (e.g. 2000.0)
;       CRVAL_OLD - 2 element vector containing RA and DEC in DEGREES
;               of the reference pixel in the original equinox
;       CRVAL_NEW - 2 elements vector giving CRVAL in the new equinox 
;
; INPUT KEYWORD:
;       /FK4 - If this keyword is set, then the precession constants are taken
;             in the FK4 reference frame.   The default is the FK5 frame.
;
; RESTRICTIONS:
;       PRECESS_CD should not be used more than 2.5 centuries from the
;       year 1900.      
;
; PROCEDURE:
;       Adapted from the STSDAS program FMATPREC.  Precession changes the
;       location of the north pole, and thus changes the rotation of
;       an image from north up.  This is reflected in the precession of the
;       CD matrix.   This is usually a very small change. 
;
; PROCEDURE CALLS:
;       PRECESS
;
; REVISION HISTORY:
;       Written, Wayne Landsman, ST Systems  February 1988
;       Fixed sign error in computation of SINRA     March 1992
;       Added /FK4 keyword                           Feb 1994
;       Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	PRECESS_XYZ
;
; PURPOSE:
;	Precess equatorial geocentric rectangular coordinates. 
;
; CALLING SEQUENCE:
;	precess_xyz, x, y, z, equinox1, equinox2
;
; INPUT/OUTPUT:
;	x,y,z: scalars or vectors giving heliocentric rectangular coordinates
;              THESE ARE CHANGED UPON RETURNING.
; INPUT:
;	EQUINOX1: equinox of input coordinates, numeric scalar
;       EQUINOX2: equinox of output coordinates, numeric scalar
;
; OUTPUT:
;	x,y,z are changed upon return
;
; NOTES:
;   The equatorial geocentric rectangular coords are converted
;      to RA and Dec, precessed in the normal way, then changed
;      back to x, y and z using unit vectors.
;
;EXAMPLE:
;	Precess 1950 equinox coords x, y and z to 2000.
;	IDL> precess_xyz,x,y,z, 1950, 2000
;
;HISTORY:
;	Written by P. Plait/ACC March 24 1999 
;	   (unit vectors provided by D. Lindler)
;       Use /Radian call to PRECESS     W. Landsman     November 2000
;       Use two parameter call to ATAN   W. Landsman    June 2001

; NAME:
;       PREMAT
; PURPOSE:
;       Return the precession matrix needed to go from EQUINOX1 to EQUINOX2.  
; EXPLANTION:
;       This matrix is used by the procedures PRECESS and BARYVEL to precess 
;       astronomical coordinates
;
; CALLING SEQUENCE:
;       matrix = PREMAT( equinox1, equinox2, [ /FK4 ] )
;
; INPUTS:
;       EQUINOX1 - Original equinox of coordinates, numeric scalar.  
;       EQUINOX2 - Equinox of precessed coordinates.
;
; OUTPUT:
;      matrix - double precision 3 x 3 precession matrix, used to precess
;               equatorial rectangular coordinates
;
; OPTIONAL INPUT KEYWORDS:
;       /FK4   - If this keyword is set, the FK4 (B1950.0) system precession
;               angles are used to compute the precession matrix.   The 
;               default is to use FK5 (J2000.0) precession angles
;
; EXAMPLES:
;       Return the precession matrix from 1950.0 to 1975.0 in the FK4 system
;
;       IDL> matrix = PREMAT( 1950.0, 1975.0, /FK4)
;
; PROCEDURE:
;       FK4 constants from "Computational Spherical Astronomy" by Taff (1983), 
;       p. 24. (FK4). FK5 constants from "Astronomical Almanac Explanatory
;       Supplement 1992, page 104 Table 3.211.1.
;
; REVISION HISTORY
;       Written, Wayne Landsman, HSTX Corporation, June 1994
;       Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;     PRIME
; PURPOSE:
;     Return an array with the specified number of prime numbers.
; EXPLANATATION:
;     This procedure is similar to PRIMES in the standard IDL distribution,
;     but stores results in a common block, and so is much faster 
;
; CALLING SEQUENCE:
;       p = prime(n)
; INPUTS:
;       n = desired number of primes, scalar positive integer
; OUTPUTS:
;       p = resulting array of primes, vector of positive integers
; COMMON BLOCKS:
;       prime_com
; NOTES:
;       Note: Primes that have been found in previous calls are
;         remembered and are not regenerated.
; MODIFICATION HISTORY:
;       R. Sterner  17 Oct, 1985.
;       R. Sterner,  5 Feb, 1993 --- fixed a bug that missed a few primes.
;       Converted to IDL V5          March 1999
;
; Copyright (C) 1985, 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.

; NAME:
;	PRINT_STRUCT
;
; PURPOSE:
;	Print the tag values of an array of structures in nice column format.
; EXPLANATION:
;	The tag names are displayed in a header line.
;
; CALLING SEQUENCE:
;	print_struct, structure, Tags_to_print [ , title, string_matrix ]
;
; INPUTS:
;	structure = array of structured variables
;
;	Tags_to_print = string array specifying the names of tags to print.
;			Default is to print all tags which are not arrays.
; OPTIONAL INPUT KEYWORDS:
;	FILE = string, optional file name to which output will then be written.
;	LUN_OUT = Logical unit number for output to an open file,
;		default is to print to standard output.
;	TNUMS = tag numbers to print (alternative to specifying tag names).
;	TRANGE = [beg,end] tag number range to print.
;	FRANGE = same as TRANGE.
;	WHICH = optional array of subscripts to select
;		which structure elements to print.
;	FORM_FLOAT = string array of three elements specifying
;		floating point format, ex: FORM=['f','9','2'] means "(F9.2)",
;		(default float format is G12.4).
;	MAX_ELEMENTS = positive integer, print only tags that have less than
;			this number of elements (default is no screening).
;	/STRINGS : instead of printing, return the array of strings in
;		fourth argument of procedure: string_matrix.
; OUTPUTS:
;	title = optional string, list of tags printed/processed.
;	string_matrix = optional output of string matrix of tag values,
;			instead of printing to terminal or file, if /STRINGS.
; EXTERNAL CALLS:
;	function N_struct
; PROCEDURE:
;	Check the types and lengths of fields to decide formats,
;	then loop and form text string from requested fields, then print.
; HISTORY:
;	Written: Frank Varosi NASA/GSFC 1991.
;	F.V.1993, fixed up the print formats.
;	F.V.1994, added more keyword options.
;	F.V.1997, added WHICH and MAX_ELEM keyword options.
;	WBL 1997, Use UNIQ() rather than UNIQUE function
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;       PROB_KS
; PURPOSE:
;       Return the significance of the Kolmogoroff-Smirnov statistic
; EXPLANATION:
;       Returns the significance level of an observed value of the 
;       Kolmogorov-Smirnov statistic D for an effective number of data points
;       N_eff.   Called by KSONE and KSTWO
;
; CALLING SEQUENCE:
;       prob_ks, D, N_eff, probks
;
; INPUT PARAMATERS:
;       D -  Kolmogorov statistic, floating scalar, always non-negative
;       N_eff - Effective number of data points, scalar.   For a 2 sided test 
;               this is given by (N1*N2)/(N1+N2) where N1 and N2 are the number 
;               of points in each data set.
;
; OUTPUT PARAMETERS:
;       probks - floating scalar between 0 and 1 giving the significance level of
;               the K-S statistic.   Small values of PROB suggest that the 
;               distribution being tested are not the same
;
; REVISION HISTORY:
;       Written     W. Landsman                August, 1992
;       Corrected typo (termbv for termbf)    H. Ebeling/W.Landsman  March 1996
;       Probably did not affect numeric result, but iteration went longer
;       than necessary
;       Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;       PRODUCT()
; PURPOSE:
;       Calculate the product of all the elements of an array
; EXPLANATION:
;       This routine serves as an equivalent to the intrinsic PRODUCT() function
;       introduced in V5.6, except that the CUMULATIVE keyword is not available.
;
;       PRODUCT() is the multiplicative equivalent of TOTAL().   
; CALLING SEQUENCE:
;       Result = PRODUCT(ARRAY, [/NaN] )
; INPUT PARAMETERS:
;       ARRAY   = Array of elements to multiply together.  For instance, ARRAY
;                 could contain the dimensions of another array--then
;                 PRODUCT(ARRAY) would be the total number of elements of that
;                 other array.
; OUTPUT:
;       The result of the function is the total product of all the elements of
;       ARRAY.   If the input is double precision or 64bit integer, then the 
;       result will be the same; otherwise the result will be floating point.
; OPTIONAL OUTPUT KEYWORD:
;       /NAN - If set, then PRODUCT() will check for the presence of IEEE
;               floating point NaN values in the input array.
; RESTRICTIONS:
;       ARRAY must be a numerical type.

; PROCEDURE:
;      Vector multiplication in groups of powers of two make this operation
;      faster than a simple FOR loop.  The number of actual multiplications is 
;      still N_ELEMENTS(ARRAY).  Double precision should be used for the highest
;      accuracy when multiplying many numbers.
; MODIFICATION HISTORY:
;       William Thompson, Feb. 1992.
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Use vector algorithm from C. Markwardt's CMPRODUCT W. Landsman Nov. 2001   
;       Added /NAN keyword, documentation about V5.6 emulation W.L Nov. 2002       

; NAME:
;       PSF_GAUSSIAN
;
; PURPOSE:
;       Create a 1-d, 2-d, or 3-d Gaussian with specified FWHM, center 
; EXPLANATION:
;       Return a point spread function having Gaussian profiles,
;       as either a 1D vector, a 2D image, or 3D volumetric-data.
;
; CALLING SEQUENCE:
;       psf = psf_Gaussian( NPIXEL=, FWHM= , CENTROID = 
;                     [ /DOUBLE, /NORMALIZE, ST_DEV=,  NDIMEN= ] ) 
; or:
;       psf = psf_Gaussian( parameters, NPIXEL = ,NDIMEN = )
;
; REQUIRED INPUT KEYWORD:
;       NPIXEL = number pixels for each dimension, specify as an array,
;               or just one number to make all sizes equal.
;
; OPTIONAL KEYWORDS:
;       CENTROID = floating scalar or vector giving position of  PSF center.    
;               default is exact center of requested vector/image/volume.
;               The number of elements in CENTROID should equal the number of
;               dimensions.    **The definition of Centroid was changed in
;               March 2002, and now an integer defines the center of a pixel.**
;
;       /DOUBLE  = If set, then the output array is computed in double precision
;               the default is to return a floating point array.
;
;       FWHM = the desired Full-Width Half-Max (pixels) in each dimension,
;               specify as an array, or single number to make all the same.
;
;       NDIMEN = integer dimension of result: either 1 (vector), 2 (image), or 
;                3 (volume), default = 2 (an image result).
;
;       /NORMALIZE causes resulting PSF to be normalized so Total( psf ) = 1.
;
;       ST_DEV = optional way to specify width by standard deviation param.
;                Ignored if FWHM is specified.
;
;       XY_CORREL = scalar between 0 and 1 specifying correlation coefficient
;               Use this keyword, for example, to specify an elliptical 
;               Gaussian oriented at an angle to the X,Y axis.   Only valid
;               for 2-dimensional case.
;
;
; INPUTS (optional):
;
;       parameters = an NDIMEN by 3 array giving for each dimension:
;                       [ maxval, center, st_dev ],  overrides other keywords.
;
; EXAMPLE:
;       (1) Create a 31 x 31 array containing a normalized centered Gaussian 
;       with an X FWHM = 4.3 and a Y FWHM = 3.6
;
;       IDL> array = PSF_GAUSSIAN( Npixel=31, FWHM=[4.3,3.6], /NORMAL )
;
;       (2) Create a 50 pixel 1-d Gaussian vector with a maximum of 12, 
;          centered at  pixel 23 with a sigma of 19.2
;
;       IDL> psf = psf_gaussian([12,23,19.2],npixel=50)
; EXTERNAL CALLS:
;       function Gaussian()
; NOTES:
;       To improve speed, floating underflow exceptions are suppressed (using 
;       the MASK=32  keyword of CHECK_MATH() rather than being flagged.
;
; HISTORY:
;       Written, Frank Varosi NASA/GSFC 1991.
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Suppress underflow messages, add DOUBLE keyword. **Modified centroid
;       definition so integer position is pixel center** W. Landsman March 2002
;       Allow use of the ST_DEV (not STDEV) keyword W. Landsman Nov. 2002

; NAME:
;    PUTAST
; PURPOSE:
;    Put WCS astrometry parameters into a given FITS header.
;
; CALLING SEQUENCE:
;     putast, hdr              ;Prompt for all values
;               or
;     putast, hdr, astr, [EQUINOX =, CD_TYPE = ]
;               or
;     putast, hdr, cd,[ crpix, crval, ctype], [ EQUINOX =, CD_TYPE = ]    
;
; 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, PROJP1, and PROJP2
;            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:
;      EQUINOX - numeric scalar giving the year of equinox  of the reference 
;                coordinates.   Default (if EQUINOX keyword is not already
;                present in header) is 2000.
;
;       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.
;            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
; NOTES:
;       The recommended use of this procedure is to supply an astrometry
;       structure.    
;
; 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:
;       Written by W. Landsman 9-3-87
;       Major rewrite, use new astrometry structure   March, 1994
;       Use both CD and CDELT to get plate scale for CD_TYPE=1   September 1995
;       Use lower case for FITS keyword Comments  W.L.    March 1997
;       Fixed for CD_TYPE=1 and CDELT = [1.0,1.0]   W.L   September 1997
;       Default value of CD_TYPE is now 2, Use GET_COORDS to read coordinates
;       to correct -0 problem           W.L.  September 1997
;       Update CROTA1 if it already exists  W.L. October 1997
;       Convert rotation to degrees for CD_TYPE = 1  W. L.   June 1998
;       Convert to IDL V5.0    W.L. June 1998
;       Accept CD_TYPE = 0 keyword input   W.L   October 1998
;       Remove reference to obsolete !ERR  W.L.  February 2000
;       No longer support CD001001 format, write default tangent CTYPE value
;       consistent conversion between CROTA and CD matrix W.L. October 2000
;       Use GET_EQUINOX to get equinox value  W.L.  January 2001
;       Update CTYPE keyword if previous value is 'LINEAR'  W.L. July 2001
;       Use SIZE(/TNAME) instead of DATATYPE()  W.L.   November 2001
;       Allow direct specification of CTYPE W.L.        June 2002
;       Don't assume celestial coordinates W. Landsman  April 2003
;       Make default CD_TYPE = 2  W. Landsman   September 2003

; NAME:
;	QDCB_GRID
;
; PURPOSE:
;	Produce an overlay of latitude and longitude lines over a plot or image
; EXPLANATION:
;	Grid is plotted on the current graphics device assuming that the 
;	current plot is a map  in the so called quad cube projection. The 
;	output plot range is assumed to go from 7.0 to -1.0 on the X axis and 
;	-3.0 to 3.0 on the Y axis. Within this plotting space, the quad cube 
;	faces are laid out as follows (X=Empty, Astronomical Layout shown - 
;	X axis can be swapped for geographic maps):
;
;	    3.0_
;		XXX0
;		4321
;	   -3.0_XXX5
;		|  |
;	      7.0  -1.0
;
; CATEGORY:
;	Mapping Support Routine
;
; CALLING SEQUENCE:
;
;	QDCB_GRID,[,DLONG,DLAT,[LINESTYLE=N,/LABELS]
;
; INPUT PARAMETERS:
;
;	DLONG	= Optional input longitude line spacing in degrees. If left
;		  out, defaults to 30.
;
;	DLAT    = Optional input lattitude line spacing in degrees. If left
;		  out, defaults to 30.
;
;
; OPTIONAL KEYWORD PARAMETERS:
;
;	LINESTYLE	= Optional input integer specifying the linestyle to
;			  use for drawing the grid lines.
;
;	LABELS		= Optional keyword specifying that the lattitude and
;			  longitude lines on the prime meridian and the
;			  equator should be labeled in degrees. If LABELS is
;			  given a value of 2, i.e. LABELS=2, then the longitude
;			  labels will be in hours and minutes instead of
;			  degrees.
;
; OUTPUT PARAMETERS:
;
;	NONE
;
; PROCEDURE:
;
;	Uses WCSSPH2XY.PRO with projection 23 ("QSC" - COBE Quadrilatieralized
;	Spherical Cube) to compute positions of grid lines and labels.
;
; COPYRIGHT NOTICE:
;
;	Copyright 1991, The Regents of the University of California. This
;	software was produced under U.S. Government contract (W-7405-ENG-36)
;	by Los Alamos National Laboratory, which is operated by the
;	University of California for the U.S. Department of Energy.
;	The U.S. Government is licensed to use, reproduce, and distribute
;	this software. Neither the Government nor the University makes
;	any warranty, express or implied, or assumes any liability or
;	responsibility for the use of this software.
;
; AUTHOR:
;
;	Jeff Bloch
;
; MODIFICATIONS/REVISION LEVEL:
;
;	%I%	%G%
;	Use WCSSPH2XY instead of QDCB   Wayne Landsman   December 1994
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;     QGET_STRING
; PURPOSE:
;     To get a string from the keyboard without echoing it to the screen.
;
; CALLING SEQUENCE:
;     string = QGET_STRING() 
;
; INPUTS:
;     None.
;
; OUTPUTS:
;     string   The string read from the keyboard.
;
; SIDE EFFECTS:
;     A string variable is created and filled.
;
; PROCEDURE:
;     The IDL GET_KBRD functions is used to get each character in
;     the string.  Each character is added to the string until a
;     carriage return is struck.  The carriage return is not appended
;     to the string.  Striking the delete key or the backspace key
;     removes the previous character from the string (only the backspace
;     key will work in VMS IDL).
;
; NOTES:
;     For a widget password procedure see 
;     http://www.dfanning.com/tip_examples/password.pro
; MODIFICATION HISTORY:
;     Written by Michael R. Greason, STX, 8 January 1991.
;     Work for Mac and Windows IDL  W. Landsman    September 1995
;     Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;       QSIMP
; PURPOSE:
;       Integrate using Simpson's rule to specified accuracy.
; EXPLANATION:
;       Integrate a function to specified accuracy using the extended 
;       trapezoidal rule.   Adapted from algorithm in Numerical Recipes, 
;       by Press et al. (1992, 2nd edition), Section 4.2.     This procedure
;       has been partly obsolete since IDL V3.5 with the introduction of the 
;       intrinsic function QSIMP(), but see notes below.
;
; CALLING SEQUENCE:
;       QSIMP, func, A, B, S, [ EPS = , MAX_ITER =, _EXTRA =  ]
;
; INPUTS:
;       func - scalar string giving name of function of one variable to 
;               be integrated
;       A,B  - numeric scalars giving the lower and upper bound of the 
;               integration
;
; OUTPUTS:
;       S - Scalar giving the approximation to the integral of the specified
;               function between A and B.
;
; OPTIONAL KEYWORD PARAMETERS:
;       EPS - scalar specifying the fractional accuracy before ending the 
;               iteration.  Default = 1E-6
;       MAX_ITER - Integer specifying the total number iterations at which 
;               QSIMP will terminate even if the specified accuracy has not yet
;               been met.   The maximum number of function evaluations will be
;               2^(MAX_ITER).    Default value is MAX_ITER = 20
;
;       Any other keywords are passed directly to the user-supplied function
;       via the _EXTRA facility.
; NOTES:
;       (1) The function QTRAP is robust way of doing integrals that are not 
;       very smooth.  However, if the function has a continuous 3rd derivative
;       then QSIMP will likely be more efficient at performing the integral.
;
;       (2) QSIMP can be *much* faster than the intrinsic QSIMP() function (as
;       of IDL V5.3).   This is because the intrinsic QSIMP() function only 
;       requires that the user supplied function accept a *scalar* variable.
;       Thus on the the 16th iteration, the intrinsic QSIMP() makes 32,767
;       calls to the user function, whereas this procedure makes one call 
;       with a  32,767 element vector.  Also, unlike the intrinsic QSIMP(), this
;       procedure allows keywords in the user-supplied function.
;
;       (3) Since the intrinsic QSIMP() is a function, and this file contains a 
;       procedure, there should be no name conflict.
; EXAMPLE:
;       Compute the integral of sin(x) from 0 to !PI/3.
;    
;       IDL> QSIMP, 'sin', 0, !PI/3, S   & print, S
;   
;       The value obtained should be cos(!PI/3) = 0.5
;
; PROCEDURES CALLED:
;       TRAPZD, ZPARCHECK
;
; REVISION HISTORY:
;       W. Landsman         ST Systems Co.         August, 1991
;       Continue after max iter warning message   W. Landsman   March, 1996
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Pass keyword to function via _EXTRA facility  W. Landsman July 1999

; NAME:
;       QTRAP
; PURPOSE:
;       Integrate using trapezoidal rule to specified accuracy.
; EXPLANATION:
;       Integrate a function to specified accuracy using the extended 
;       trapezoidal rule.   Adapted from Numerical Recipes (1992, 2nd edition),
;       Section 4.2. 
;
; CALLING SEQUENCE:
;       QTRAP, func, A, B, S, [EPS = , MAX_ITER =, _EXTRA = ]
;
; INPUTS:
;       func - scalar string giving name of function of one variable to 
;               be integrated
;       A,B  - numeric scalars giving the lower and upper bound of the 
;               integration
;
; OUTPUTS:
;       S - Scalar giving the approximation to the integral of the specified
;               function between A and B.
;
; OPTIONAL KEYWORD PARAMETERS:
;       EPS - scalar specify the fractional accuracy before ending the 
;             iteration.    Default = 1E-6
;       MAX_ITER - Integer specifying the total number iterations at which 
;               QTRAP will terminate even if the specified accuracy has not yet
;               been met.    The maximum number of function evaluations will 
;               be 2^(MAX_ITER).   Default value is MAX_ITER = 20
;
;       Any other keywords are passed directly to the user-supplied function
;       via the _EXTRA facility.
; NOTES:
;       QTRAP is robust way of doing integrals that are not very smooth.  If the
;       function has a continuous 3rd derivative then the function QSIMP will 
;          likely be more efficient at performing the integral.
; EXAMPLE:
;       Compute the integral of sin(x) from 0 to !PI/3.
;    
;       IDL> QTRAP, 'sin', 0, !PI/3, S   & print,S
;   
;       The value obtained should be cos(!PI/3) = 0.5
;
; PROCEDURES CALLED:
;       TRAPZD, ZPARCHECK
; REVISION HISTORY:
;       W. Landsman         ST Systems Co.         August, 1991
;       Continue after Max Iter warning message, W. Landsman  March 1996
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Pass keyword to function via _EXTRA facility  W. Landsman July 1999

; NAME:
;       QUADTERP     
; PURPOSE:
;       Quadratic interpolation of X,Y vectors onto a new X grid
; EXPLANATION:
;       Quadratically interpolate (3 point Lagrangian) a function Y = f(X)
;       at specified grid points.  Use LINTERP for linear interpolation
;
; CALLING SEQUENCE:
;       QUADTERP, Xtab, Ytab, Xint, Yint, [ MISSING = ]
;
; INPUT: 
;       Xtab - Vector (X TABle) containing the current independent variable 
;               Must be either monotonic increasing or decreasing
;       Ytab - Vector (Y TABle) containing the dependent variable defined
;               at each of the points of XTAB.
;       Xint - Scalar or vector giving the values of X for which interpolated 
;               Y values are sought
;
; OUTPUT: 
;       Yint - Interpolated value(s) of Y, same number of points as Xint
;
; OPTIONAL INPUT KEYWORD:
;       MISSING - Scalar specifying Yint value(s) to be assigned, when Xint
;               value(s) are outside of the range of Xtab.     Default is to
;               truncate the out of range Yint value(s) to the nearest value 
;               of Ytab.   See the help for the INTERPOLATE function.
; METHOD:
;       3-point Lagrangian interpolation.  The average of the two quadratics 
;       derived from the four nearest  points is returned in YTAB.   A single
;       quadratic is used near the end points.   VALUE_LOCATE is used 
;       to locate center point of the interpolation.
;
; NOTES:
;       QUADTERP provides one method of high-order interpolation.   In IDL V5.3
;           the following alternatives became available:
;
;       interpol(/LSQUADRATIC) - least squares quadratic fit to a 4 pt 
;               neighborhood
;       interpol(/QUADRATIC) - quadratic fit to a 3 pt neighborhood
;       interpol(/SPLINE) - cubic spline fit to a 4 pt neighborhood
;
;       Also, the IDL Astro function HERMITE fits a cubic polynomial and its
;             derivative to the two nearest points. 
; RESTRICTIONS:
;       Unless MISSING keyword is set, points outside the range of Xtab in 
;       which valid quadratics can be computed are returned at the value 
;       of the nearest end point of Ytab (i.e. Ytab[0] and Ytab[NPTS-1] ).
;
; EXAMPLE:
;       A spectrum has been defined using a wavelength vector WAVE and a
;       flux vector FLUX.  Interpolate onto a new wavelength grid, e.g. 
;
;       IDL> wgrid = [1540.,1541.,1542.,1543.,1544.,1545.]
;       IDL> quadterp, wave, flux, wgrid, fgrid 
;     
;       FGRID will be a 5 element vector containing the quadratically
;       interpolated values of FLUX at the wavelengths given in WGRID.
;
;  EXTERNAL ROUTINES:
;       VALUE_LOCATE -- this is an intrinsic function in IDL V5.3 and later.
;           For earlier IDL versions one can substitute the emulation procedure 
;           http://idlastro.gsfc.nasa.gov/ftp/pro/math/value_locate.pro
;       ZPARCHECK
;  REVISION HISTORY:
;       31 October 1986 by B. Boothman, adapted from the IUE RDAF
;       12 December 1988 J. Murthy, corrected error in Xint
;       September 1992, W. Landsman, fixed problem with double precision
;       August 1993, W. Landsman, added MISSING keyword
;       June, 1995, W. Landsman, use single quadratic near end points
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Fix occasional problem with integer X table,  
;       YINT is a scalar if XINT is a scalar   W. Landsman Dec 1999
;       Use VALUE_LOCATE instead of TABINV W. Landsman  Feb. 2000

; NAME: 
;   QueryDSS
;
; PURPOSE: 
;    Query the digital sky survey (DSS) on-line at  the ESO or STSCI servers
;
; EXPLANATION: 
;     The script can query the DSS survey and retrieve an image and FITS 
;     header either from the European Southern Observatory (ESO) or the 
;     Space Telescope Science Institute (STScI) servers.
;     See http://archive.eso.org/dss/dss and/or 
;     http://archive.stsci.edu/dss/index.html for details.
;
; CALLING SEQUENCE: 
;      QueryDSS, targetname_or_coords, Im, Hdr, [IMSIZE= , /ESO, /STSCI ]
;
; INPUTS:
;      TARGETNAME_OR_COORDS - Either a scalar string giving a target name, 
;          (with J2000 coordinates determined by SIMBAD (default) or NED), or 
;          a 2-element numeric vector giving the J2000 right ascension in 
;          *degrees* and the target declination in degrees.
;
; OPTIONAL INPUTS: 
;          None
;
; OPTIONAL KEYWORD PARAMETERS: 
;     ImSize - Numeric scalar giving size of the image to be retrieved in 
;                 arcminutes.    Default is 10 arcminute.
;
;     /ESO - Use the ESO server for image retrieval.    Default is to use
;            the STScI server if user is in the Western hemisphere, and 
;            otherwise to use the ESO server.
;
;     /NED - Query the Nasa Extragalactic Database (NED) for the
;            target's coordinates.  The default is to use Simbad for
;            the target search.
;
;     /STSCI - Use the STSCI server for image retrieval.  Default is to use
;            the STScI server if user is in the Western hemisphere, and 
;            otherwise to use the ESO server.    
;
;     SURVEY - Scalar string specifying which survey to retrieve.  
;          Possible values are 
;          '1' - First generation (red), this is the default
;          '2b' - Second generation blue
;          '2r' - Second generation red
;          '2i' - Second generation near-infrared
; 
;      Note that 2nd generation images may not be available for all regions
;      of the sky.   Also note that the first two letters of the 'REGION'
;      keyword in the FITS header gives the bandpass 'XP' - Red IIIaF, 
;      'XJ' - Blue IIIaJ, 'XF' - Near-IR IVN
;
; OUTPUTS: 
;       Im - The image returned by the server. If there is an error, this 
;             contains a single 0.
;
;       Hdr - The FITS header of the image. Empty string in case of errors.
;
;       If the OutFile keyword is set then no outputs are returned (only the
;       file is written).
; SIDE EFFECTS: 
;     If Im and Hdr exist in advance,  they are overwritten.
;
; RESTRICTIONS: 
;      Relies on a working network connection. 
;
; PROCEDURE: 
;      Construct a query-url,  call WEBGET() and sort out the server's 
;      answer.
;
; EXAMPLE:           
;      Retrieve an 10'  image surrounding the ultracompact HII region
;       G45.45+0.06.   Obtain the 2nd generation blue image.
;
;       IDL> QueryDSS, 'GAL045.45+00.06', image, header, survey = '2b'
;       IDL> tvscl, image
;       IDL> hprint, header
;       IDL> writefits,'dss_image.fits', image, header
; Note that the coordinates could have been specified directly, rather than
; giving the target name.
;       IDL> QueryDSS, [288.587, 11.1510], image, header,survey='2b'
;
; To write a file directly to disk, use the OutFile keyword
;
;       IDL> QueryDSS, [288.587, 11.1510], survey='2b', out='gal045_2b.fits'
;   
; PROCEDURES CALLED:
;       QUERYSIMBAD, WEBGET()
; MODIFICATION HISTORY: 
;       Written by M. Feldt, Heidelberg, Oct 2001 
;       Option to supply target name instead of coords  W. Landsman Aug. 2002
;       Added OUTFILE, /NED keywords W. Landsman   April 2003
;       Don't abort on Simbad failure W. landsman/J. Brauher  June 2003
;

; NAME: 
;   QUERYGSC
;
; PURPOSE: 
;   Query the Guide Star Catalog (GSC V2.2) at STScI by position
; 
; EXPLANATION:
;   Uses the IDL SOCKET command to query the GSC 2.2 database over the Web.    
;   Requires IDL V5.4 or later.
; 
;   The GSC  all-sky catalog will contain an estimated 2 billion objects
;   and will be complete to a magnitude of at least J=18 and as faint as J=21 at
;   high galactic latitudes. Using the observations in different bandpasses at 
;   different epochs allows the computation of both colors and proper motions. 
;   These data are in an object-oriented database at 
;   http://www-gsss.stsci.edu/support/data_access.htm.  The final version 
;   (GSC 2.3),  expected to be released in 2003, will also contain proper 
;   motions.   
;
; CALLING SEQUENCE: 
;     info = QueryGSC(targetname_or_coords, [ dis, Magrange =, /HOURS] )
;
; INPUTS: 
;      TARGETNAME_OR_COORDS - Either a scalar string giving a target name, 
;          (with J2000 coordinates determined by SIMBAD), or a 2-element
;          numeric vector giving the J2000 right ascension in *degrees* (or 
;          hours if /HOURS is set) and the target declination in degrees.
;
; OPTIONAL INPUT:
;    dis - Search radius in arcminutes to search around specified target
;          Default is 5 arcminutes
;
; OPTIONAL INPUT KEYWORDS:
;
;    /HOURS - If set, then the right ascension is both input and output (in
;             the info .ra tag) in hours instead of degrees
;
;    MAGRANGE - two element vector giving the magnitude range (on either the
;           F plate or the J plate) to search for  GSC stars.   
;           Default is [0,30]
;
; OUTPUTS: 
;   info - IDL structure containing information on the GSC stars within the 
;          specified distance of the specified center.   There are (currently)
;          23 tags in this structure  -- for further information see
;           http://www-gsss.stsci.edu/gsc/gsc2/gsc22_release_notes.htm  
;
;          .GSCID2 - GSC 2.2 identification number
;          .RA,.DEC - Position in degrees (double precision).   RA is given in
;                   hours if the /HOURS keyword is set.
;          .RAERR, .DECERR - uncertainty (in arcseconds) in the RA and Dec
;          .EPOCH - mean epoch of the observation
;          .RAPM,DECPM - RA and Dec proper motion (mas/year) 
;          .RAPMERR,DECPMERR - Uncertainty RA and Dec proper motion (mas/year) 
;          .FMAG, .FMAGERR - magnitude and error in photographic F
;          .JMAG, .JMAGERR - magnitude and error in photographic J
;          .VMAG, .VMAGERR - V magnitude and error 
;          .NMAG, .NMAGERR - magnitude and error
;          .A - semi-major axis in pixels
;          .E - eccentricity of extended objects
;          .PA - Position angle of extended objects in degrees
;          .C - classification (0-5): 0-star, 1-galaxy, 2-blend, 3-nonstar,
;                                     4-unclassified, 5-defect
;          .STATUS -10 digit field  used to encode more detailed information 
;              about the properties of the catalog object.   For more info, see 
;http://www-gsss.stsci.edu/gsc/gsc2/gsc22_release_notes.htm#SourceStatusFlagCodes
;
; EXAMPLE: 
;          Plot a histogram of the photographic J magnitudes of all GSC 2.2 
;          stars within 10 arcminutes of the center of the globular cluster M13 
;
;          IDL> info = querygsc('M13',10)
;          IDL> plothist,info.jmag,xran=[10,20]
;
; PROCEDURES USED:
;          QUERYSIMBAD, RADEC, WEBGET()
;
; MODIFICATION HISTORY: 
;         Written by W. Landsman  SSAI  August 2002
;         Fixed parsing of RA and Dec  W. Landsman September 2002
;

; NAME: 
;   QUERYSIMBAD
;
; PURPOSE: 
;   Query the SIMBAD or NED astronomical name resolver to obtain coordinates
;
; EXPLANATION: 
;   Uses the IDL SOCKET command to query either the SIMBAD or NED nameserver 
;   over the Web to return J2000 coordinates.     Requires IDL V5.4 or later.
;
;   For details on the SIMBAD service, see http://simbad.u-strasbg.fr/Simbad 
;   and for the NED service, see http://ned.ipac.caltech.edu/
;
; CALLING SEQUENCE: 
;    QuerySimbad, name, ra, dec, [ id, Found=, /NED, ERRMSG=]
;
; INPUTS: 
;    name - a scalar string containing the target name in SIMBAD (or NED)
;           nomenclature. For SIMBAD details see
;           http://vizier.u-strasbg.fr/cgi-bin/Dic-Simbad .
;
; OUTPUTS: 
;     ra - the right ascension of the target in J2000.0 in *degrees* 
;     dec - declination of the target in degrees
;
; OPTIONAL INPUT KEYWORD:
;     /NED - if set, then nameserver of the NASA Extragalactic database is
;           used to resolve the name and return coordinates.   Note that
;           /NED cannot be used with Galactic objects
; OPTIONAL OUTPUT: 
;     id - the primary SIMBAD (or NED) ID of the target, scalar string
;
; OPTIONAL KEYWORD OUTPUT:
;     found - set to 1 if the translation was successful, or to 0 if the
;           the object name could not be translated by SIMBAD or NED
;     Errmsg - if supplied, then any error messages are returned in this
;            keyword, rather than being printed at the terminal.   May be either
;            a scalar or array.
;            
; EXAMPLES:
;     (1) Find the J2000 coordinates for the ultracompact HII region
;         G45.45+0.06 
;
;      IDL> QuerySimbad,'GAL045.45+00.06', ra, dec
;      IDL> print, adstring(ra,dec,1)
;           ===>19 14 20.77  +11 09  3.6
; PROCEDURES USED:
;       REPSTR(), WEBGET()
;
; MODIFICATION HISTORY: 
;     Written by M. Feldt, Heidelberg, Oct 2001   
;     Minor updates, W. Landsman   August 2002
;     Added option to use NED server, better parsing of SIMBAD names such as 
;          IRAS F10190+5349    W. Landsman  March 2003
;     Turn off extended name search for NED server, fix negative declination
;     with /NED    W. Landsman  April 2003
;

; NAME: 
;   QUERYUSNO
;
; PURPOSE: 
;   Query the USNO-A2.0 Catalog at the ESO/ST-ECF Archive by position
; 
; EXPLANATION:
;   Uses the IDL SOCKET command to query the USNO-A2.0 database over the Web.    
;   Requires IDL V5.4 or later.
; 
;   With the introduction of QUERYVIZIER this routine became mostly obsolete
;   as the newer USNO-B1 catalog can be accessed from QUERYVIZIER.
;
;   USNO-A2.0 contains entries for over a half billion stars (526,230,881, to 
;   be exact!) which were detected in the digitized images of three photographic
;   sky surveys. For the entire northern sky and the southern sky down to 
;   declinations of -30°, all the photographic plates were part of the original
;   Palomar Optical Sky Survey (POSS-I).  Photographs were taken on blue- and 
;   red-sensitive emulsions. Only those stars which were detected in both colors
;   were included in the USNO-A2.0 catalog. The rest of the southern sky was 
;   covered by the Science Research Council (SRC)-J survey and the European 
;   Southern Observatory (ESO)-R survey.  Only stars appearing in both 
;   colors were accepted for the final catalogue.   Coordinates are J2000 
;   at the epoch of the mean of the blue and red exposure. 
;
; CALLING SEQUENCE: 
;     info = QueryUSNO(targetname_or_coords, [ dis, Magrange =, /HOURS] )
;
; INPUTS: 
;      TARGETNAME_OR_COORDS - Either a scalar string giving a target name, 
;          (with J2000 coordinates determined by SIMBAD), or a 2-element
;          numeric vector giving the J2000 right ascension in *degrees* and
;          the target declination in degrees.
;
; OPTIONAL INPUT:
;    dis - Search radius in arcminutes to search around specified target
;          Default is 5 arcminutes
;
; OPTIONAL INPUT KEYWORDS:
;
;    /HOURS - If set, then the right ascension is both input and output (in
;             the info .ra tag) in hours instead of degrees
;
;    MAGRANGE - two element vector giving the magnitude range (on the
;           r plate) to search for  stars.   Default is to return all stars
;
; OUTPUTS: 
;   info - IDL structure containing information on the USNO-A2 stars within the 
;          specified distance of the specified center.   There are (currently)
;          5 tags in this structure  -- for further information see
;           http://ftp.nofs.navy.mil/projects/pmm/readme.html
;
;          .ID - USNO-A2.0 identification number
;          .RA,.DEC - Position in degrees (double precision).   RA is given in
;                   hours if the /HOURS keyword is set.
;          .r_mag, .b_mag - magnitudes on the red and blue plates
;
; EXAMPLE: 
;          Plot a histogram of the photographic r magnitudes of all USNO-A2 
;          stars within 10 arcminutes of the center of the globular cluster M13 
;
;          IDL> info = queryusno('M13',10)
;          IDL> plothist,info.r_mag,xran=[10,20]
;
; PROCEDURES USED:
;          QuerySIMBAD, RADEC, WEBGET()
;
; MODIFICATION HISTORY: 
;         Written by W. Landsman  SSAI  September 2002
;

; NAME: 
;   QUERYVIZIER
;
; PURPOSE: 
;   Query any catalog in the Vizier database by position
; 
; EXPLANATION:
;   Uses the IDL SOCKET command to provide a positional query of any catalog 
;   in the the Vizier (http://vizier.u-strasbg.fr/) database over the Web.    
;   Requires IDL V5.4 or later.
; 
;    
; CALLING SEQUENCE: 
;     info = QueryVizier(catalog, targetname_or_coords, [ dis )
;
; INPUTS: 
;      CATALOG - Scalar string giving the name of the VIZIER catalog to be
;            searched.    The complete list of catalog names is available at
;            http://vizier.u-strasbg.fr/vizier/cats/U.htx . 
;
;            Popular VIZIER catalogs include  
;            '2MASS-PSC' - 2MASS point source catalog (2003)
;            'GSC2.2' - Version 2.2 of the HST Guide Star Catalog (2003)
;            'USNO-B1' - Verson B1 of the US Naval Observatory catalog (2003)
;            'NVSS'  - NRAO VLA Sky Survey (1998)
;            'B/DENIS/DENIS' - 2nd Deep Near Infrared Survey of southern Sky
;            'I/259/TYC2' - Tycho-2 main catalog (2000)
;
;          Note that some names will prompt a search of multiple catalogs
;          and QUERYVIZIER will only return the result of the first search.
;          Thus, (as in the case of the Tycho catalog above), it may be 
;          important to use the specific VIZIER name.
;                             
;      TARGETNAME_OR_COORDS - Either a scalar string giving a target name, 
;          (with J2000 coordinates determined by SIMBAD), or a 2-element
;          numeric vector giving the J2000 right ascension in *degrees* and 
;          the target declination in degrees.
;
; OPTIONAL INPUT:
;    dis - scalar or 2-element vector.   If one value is supplied then this
;          is the search radius in arcminutes.     If two values are supplied
;          then this is the width (i.e., in longitude direction) and height of the
;          of the search box.   Default is a radius search with radius of
;          5 arcminutes
;
; OUTPUTS: 
;   info - IDL structure containing information on the catalog stars within the 
;          specified distance of the specified center.   The structure tags
;          are identical with the VIZIER catalog column names, with the 
;          exception of an occasional underscore addition, if necessary to 
;          convert the column name to a valid structure tag.    The VIZIER Web 
;          page should consulted for the column names and their meaning for 
;          each particular catalog..
;           
;          If the tagname is numeric and the catalog field is blank then either
;          NaN  (if floating) or -1 (if integer) is placed in the tag.
;
;          If no sources are found within the specified radius, or an
;          error occurs in the query then -1 is returned. 
; OPTIONAL KEYWORDS:
;          /CANADA - By default, the query is sent to the main VIZIER site in
;            Strasbourg, France.   If /CANADA is set then the VIZIER site
;            at the Canadian Astronomical Data Center (CADC) is used instead.
;            Note that not all Vizier sites have the option to return
;            tab-separated values (TSV) which is required by this program.
; EXAMPLES: 
;          (1) Plot a histogram of the J magnitudes of all 2MASS point sources 
;          stars within 10 arcminutes of the center of the globular cluster M13 
;
;          IDL>  info = queryvizier('2MASS-PSC','m13',10)
;          IDL> plothist,info.jmag,xran=[10,20]
;
;          (2)  Find the brightest R magnitude GSC2.2 source within 3' of the 
;               J2000 position ra = 10:12:34, dec = -23:34:35
;          
;          IDL> str = queryvizier('GSC2.2',[ten(10,12,34)*15,ten(-23,34,35)],3)
;          IDL> print,min(str.rmag,/NAN)
; PROCEDURES USED:
;          GETTOK(),IDL_VALIDNAME()(if prior to V6.0), RADEC, REMCHAR, REPSTR(),
;          WEBGET()
; TO DO:
;       (1) Allow specification of output sorting
;       (2) Allow non-positional queries.
; MODIFICATION HISTORY: 
;         Written by W. Landsman  SSAI  October 2003

; NAME:
;	RADEC
; PURPOSE:
;	To convert RA and Dec  from decimal to sexigesimal units.
; EXPLANATION: 
;	The conversion is to sexigesimal hours for RA,  and sexigesimal 
;	degrees for declination.
;
; CALLING SEQUENCE:
;	radec, ra, dec, ihr, imin, xsec, ideg, imn, xsc, [/HOURS}
;
; INPUTS:
;	ra   - right ascension, scalar or vector, in DEGREES unless the
;              /HOURS keyword is set
;	dec  - declination in decimal DEGREES, scalar or vector, same number
;		of elements as RA
;
; OUTPUTS:
;	ihr  - right ascension hours   (INTEGER*2)
;	imin - right ascension minutes (INTEGER*2)
;	xsec - right ascension seconds  (REAL*4 or REAL*8)
;	ideg - declination degrees (INTEGER*2)
;	imn  - declination minutes (INTEGER*2)
;	xsc  - declination seconds (REAL*4 or REAL*8)
;
; OPTIONAL KEYWORD INPUT:
;       /HOURS - if set, then the input righ ascension should be specified in
;              hours instead of degrees.
; RESTRICTIONS:
;	RADEC does minimal parameter checking.
;
; REVISON HISTORY:
;	Written by B. Pfarr, STX, 4/24/87
;	Converted to IDL V5.0   W. Landsman   September 1997
;       Added /HOURS keyword W. Landsman  August 2002

; NAME:
;       RANDOMP
; PURPOSE:
;       Generates an array of random numbers distributed as a power law.
; CALLING SEQUENCE:
;       RANDOMP, X, Pow, N, [ RANGE_X = [low,high], SEED= ]'
; INPUTS:
;       Pow:  Exponent of power law.
;               The pdf of X is f_X(x) = A*x^pow, low <= x <= high
;               ASTRONOMERS PLEASE NOTE:  
;               pow is little gamma  = big gamma - 1 for stellar IMFs.
;       N:    Number of elements in generated vector.
;
; OPTIONAL INPUT KEYWORD PARAMETER:
;       RANGE_X:  2-element vector [low,high] specifying the range of 
;               output X values; the default is [5, 100].
;
; OPTIONAL INPUT-OUTPUT KEYWORD PARAMETER:
;       SEED:    Seed value for RANDOMU function.    As described in the 
;               documentation for RANDOMU, the value of SEED is updated on 
;               each call to RANDOMP, and taken from the system clock if not
;               supplied.   This keyword can be used to have RANDOMP give 
;               identical results on different runs.
; OUTPUTS:
;       X:    Vector of random numbers, distributed as a power law between
;               specified range
; PROCEDURE:  
;       "Transformation Method" for random variables is described in Bevington 
;       & Robinson, "Data Reduction & Error Analysis for Physical Sciences", 2nd
;       Edition (McGraw-Hill, 1992). p. 83.
;       Output of RANDOMU function is transformed to power-law
;       random variable.
;
; EXAMPLE:
;       Create a stellar initial mass function (IMF) with 10000 stars
;       ranging from 0.5 to 100 solar masses and a Salpeter slope.  Enter:
;
;       RANDOMP,MASS,-2.35,10000,RANGE_X=[0.5,100]
;
; NOTES:
;       Versions 5.1.1 and V5.2 of IDL have a bug in RANDOMU such that the SEED
;       value is initialized to the same value at the start of each session,
;       rather than being initialized by the system clock.    RANDOMP will be
;       affected in a similar manner.
; MODIFICATION HISTORY:
;       Written by R. S. Hill, Hughes STX, July 13, 1995
;       July 14, 1995   SEED keyword added at Landsman's suggestion.
;                    Documentation converted to standard format.  RSH
;       Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;      RDFITS_STRUCT
; PURPOSE:
;      Read an entire FITS file (all extensions) into a single IDL structure. 
; EXPLANATION:
;      Each header, image or table array is placed in a separate structure 
;      tag.
;
; CALLING SEQUENCE:
;      RDFITS_STRUCT, filename, struct, /SILENT ]
;
; INPUT:
;      FILENAME = Scalar string giving the name of the FITS file.   Since V5.3
;                 one can also specify a gzip (.gz) compressed file 
;
; OPTIONAL KEYWORD: 
;      /SILENT - Set this keyword to suppress informational displays at the
;               terminal.
; OUTPUT:
;      struct = structure into which FITS data is read.   The primary header
;             and image are placed into tag names HDR0 and IM0.   The ith
;             extension is placed into the tag names HDRi, and either TABi
;             (if it is a binary or ASCII table) or IMi (if it is an image
;             extension)
;
; PROCEDURES USED:
;       FITS_OPEN, FITS_READ, FITS_CLOSE
;
; METHOD:
;       The file is opened with FITS_OPEN which return information on the 
;       number and type of each extension.    The CREATE_STRUCT() function
;       is used iteratively, with FITS_READ calls to build the final structure.
;
; EXAMPLE:
;       Read the FITS file 'm33.fits' into an IDL structure, st
;
;       IDL> rdfits_struct, 'm33.fits', st
;       IDL> help, /str, st                   ;Display info about the structure
;
; RESTRICTIONS:
;       Does not handle random groups or variable length binary tables
; MODIFICATION HISTORY:
;       Written K. Venkatakrishna, STX April 1992
;       Code cleaned up a bit  W. Landsman  STX  October 92
;       Modified for MacOS     I.  Freedman  HSTX April 1994
;       Work under Windows 95  W. Landsman   HSTX  January 1996
;       Use anonymous structures, skip extensions without data WBL April 1998
;       Converted to IDL V5.0, W. Landsman, April 1998
;       OS-independent deletion of temporary file  W. Landsman  Jan 1999
;       Major rewrite to use FITS_OPEN and CREATE_STRUCT() W. Landsman Sep 2002

; NAME:
;      RDFLOAT
; PURPOSE:
;      Quickly read a numeric ASCII data file into IDL floating/double vectors.  
; EXPLANATION:
;      Columns of data may be separated by tabs or spaces.      This 
;      program is fast but is restricted to data files where all columns can 
;      be read as floating point (or all double precision).   
;
;      Use READCOL if  greater flexibility is desired.   Use READFMT to read a 
;      fixed-format ASCII file.   Use FORPRINT to print columns of data.
;
; CALLING SEQUENCE:
;      RDFLOAT, name, v1, [ v2, v3, v4, v5, ...  v19] 
;                         COLUMNS, /DOUBLE, SKIPLINE = , NUMLINE = ]
;
; INPUTS:
;      NAME - Name of ASCII data file, scalar string.  In VMS, an extension of 
;              .DAT is assumed, if not supplied.
;
; OPTIONAL INPUT KEYWORDS:
;      COLUMNS - Numeric scalar or vector specifying which columns in the file
;               to read.    For example, if COLUMNS = [3,7,11] then the first
;               output variable (v1) would contain column 3, the second would
;               contain column 7 and the third would contain column 11.   If
;               the number of elements in the COLUMNS vector is less than the
;               number of output parameters, then consecutive columns are 
;               implied.    For example, if 3 output parameters are supplied
;               (v1,v2,v3) and COLUMNS = 3, then columns 3,4, and 5 will be
;               read.   
;      SKIPLINE - Integer scalar specifying number of lines to skip at the top
;              of file before reading.   Default is to start at the first line.
;      NUMLINE - Integer scalar specifying number of lines in the file to read.  
;             Default is to read the entire file
;      /DOUBLE - If this keyword is set, then all variables are read in as
;              double precision.
;      /SILENT - Set this keyword to suppress any informative messages
;
; OUTPUTS:
;      V1,V2,V3,...V19 - IDL vectors to contain columns of data.
;               Up to 19 columns may be read.  All output vectors are of type
;               float, unless the /DOUBLE keyword is set, 
;
; EXAMPLES:
;      Each row in a file 'position.dat' contains a star number and 6 columns
;      of data giving an RA and Dec in sexigesimal format.   Read into IDL 
;      variables.     
;
;       IDL> rdfloat,'position.dat',ID,hr,min,sec,deg,dmin,dsec  
;
;       All output vectors will be floating point.    To only read the 
;       declination vectors (Deg,dmin,dsec)
;
;       IDL> rdfloat,'position.dat',deg,dmin,dsec,col=4
;
; RESTRICTIONS:
;      (1) All rows in the file must be formatted identically (except for 
;          those skipped by SKIPLINE).    RDFLOAT reads the first line of 
;          the data (after SKIPLINE) to determine the number of columns of 
;          data.
;      (2) Cannot be used to read strings
; PROCEDURES USED:
;      NUMLINES()
; REVISION HISTORY:
;      Written         W. Landsman                 September 1995
;      Call NUMLINES() function                    February 1996
;      Read up to 19 columns                       August 1997
;      Converted to IDL V5.0   W. Landsman         September 1997
;      Allow to skip more than 32767 lines  W. Landsman  June 2001
;      Added /SILENT keyword   W. Landsman         March 2002
;      Added COLUMNS keyword, use STRSPLIT    W. Landsman May 2002
;      Use SKIP_LUN if V5.6 or later          W. Landsamn Nov 2002

; NAME:
;   RDPLOT
;
; PURPOSE:
;   Like CURSOR but with a full-screen cursor and continuous readout option
; EXPLANATION:
;   This program is designed to essentially mimic the IDL CURSOR command,
;   but with the additional options of continuously printing out the data
;   values of the cursor's position, and using a full-screen cursor rather 
;   than a small cross cursor.  The Full screen cursor uses OPLOT and 
;   X-windows graphics masking to emulate the cursor.
;      One difference is that IF the PRINT keyword is set but the DOWN, WAIT,
;   or CHANGE keywords are not set, then the leftmost mouse button will 
;   print a "newline" line-feed, but not exit.
;
; CALLING SEQUENCE:
;   RDPLOT, [X, Y, WaitFlag], [/DATA, /DEVICE, /NORMAL,
;      /NOWAIT, /WAIT, /DOWN, /CHANGE, ERR=,
;      PRINT=, XTITLE=, YTITLE=, XVALUES=, YVALUES=,
;      /FULLCURSOR, /NOCLIP, LINESTYLE=, THICK=, COLOR=, /CROSS]
;
; REQUIRED INPUTS:
;   None.
;
; OPTIONAL INPUTS: 
;   WAITFLAG = Uses the same table as the intrinsic CURSOR command, But note
;	that unlike the CURSOR command, there is no UP keyword.
;		WaitFlag=0 sets the NOWAIT keyword
;		WaitFlag=1 sets the WAIT keyword {default}
;		WaitFlag=2 sets the CHANGE keyword
;		WaitFlag=3 sets the DOWN keyword
;
; OPTIONAL OUTPUTS:
;    X - a named variable to receive the final cursor X position, scalar
;    Y - a named variable to receive the final cursor Y position, scalar
; OPTIONAL KEYWORD INPUT PARAMETERS:
;   /DATA = Data coordinates are displayed and returned.
;   /DEVICE = device coordinates are displayed and returned.
;   /NORMAL = normal coordinates are displayed and returned.
;          Default is to use DATA coordinates if available (see notes).
;   /NOWAIT = if non-zero the routine will immediately return the cursor's
;      present position.
;   WAIT = if non-zero will wait for a mouse key click before returning.  If
;      cursor key is already down, then procedure immediately exits.
;   DOWN = equivalent to WAIT *except* that if the mouse key is already down
;      when the procedure is called, the procedure will wait until the mouse
;      key is clicked down again.
;   CHANGE = returns when the mouse is moved OR a key is clicked up or down.
;   PRINT = if non-zero will continuously print out (at the terminal) the data 
;      values of the cursor's position.  If PRINT>1, program will printout a 
;      brief header describing the mouse button functions.  However, note that 
;      the button functions are overridden if any of the DOWN, WAIT, mouse
;      or CHANGE values are non-zero.
;   XTITLE = label used to describe the values of the abscissa if PRINT>0.
;   YTITLE = label used to describe the values of the ordinate if PRINT>0.
;   XVALUES = a vector corresponding to the values to be printed when the
;	PRINT keyword is set.  This allows the user the option of printing
;	out other values rather than the default X coordinate position of
;	the cursor.  E.g., if XVALUES is a string vector of dates such as
;	['May 1', 'May 2', ...], then those dates will be printed rather than
;	the X value of the cursor's position: if X=1 then 'May 2' would be
;	printed, etc.  This requires that the values of the X coordinate read
;	by the cursor must be positive (can't access negative elements).
;       If XVALUES=-1, then NO values for X will be printed.
;   YVALUES = analagous to the XVALUES keyword.
;   FULLCURSOR = if non-zero default cursor is blanked out and full-screen 
;      (or full plot window, depending on the value of NOCLIP) lines are
;      drawn; their intersecton is centered on the cursor position.
;   NOCLIP = if non-zero will make a full-screen cursor, otherwise it will
;      default to the value in !P.NOCLIP.
;   LINESTYLE = style of line that makes the full-screen cursor.
;   THICK = thickness of the line that makes the full-screen cursor.
;   COLOR = color of the full-screen cursor.
;   CROSS = if non-zero will show the regular cross AND full screen cursors.
;
; OPTIONAL KEYWORD OUTPUT PARAMETER:
;   ERR = returns the most recent value of the !mouse.button value.
;
; NOTES:
;   Note that this procedure does not allow the "UP" keyword/flag...which 
;   doesn't seem to work too well in the origianl CURSOR version anyway.
;
;   If a data coordinate system has not been established, then RDPLOT will
;   create one identical to the device coordinate system.   Note that this
;   kluge is required even if the user specified /NORMAL coordinates, since
;   RDPLOT makes use of the OPLOT procedure.  This new data coordinate system
;   is effectively "erased" (!X.CRange and !Y.CRange are both set to zero)
;   upon exit of the routine so as to not change the plot status from the
;   user's point of view.
;
;   Only tested on X-windows systems.  If this program is interrupted, the
;   graphics function might be left in a non-standard state; in that case,
;   run the program RESET_RDPLOT to return the standard graphics functions,
;   or type the command:   DEVICE, /CURSOR_CROSS, SET_GRAPHICS=3, BYPASS=0
;
; BUGS:
;   It is assumed that the current background of the plot is correctly
;   defined by the value in !P.Background.  Otherwise, the color of the
;   long cursor probably will not be correct.  Sometimes the color doesn't
;   work anyway, and I'm not sure why.
;
;   There may be some cases (e.g., when THICK>1 and NOCLIP=0) when the
;   full-screen cursor is not correctly erased, leaving "ghost images" on the
;   plot.  It just seems that the screen updates get slow or the positions
;   ambiguous with a thick line and the cursor off the plot.
;
; PROCEDURE:
;   Basically is a bells-n-whistles version of the CURSOR procedure.  All
;   the details are covered in the above discussion of the keywords.
;
; EXAMPLE (a silly, but informative one):
;   Months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', $
;             'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
;   plot, indgen(12), xrange=[-5, 15]
;   rdplot, /FULL, /PRINT, XTITLE='Month: ', YTITLE='Y-value per month = ', $
;      xvalues=Months
;
; MODIFICATION HISTORY:
;   Written (originally named CURFULL) by J.Wm.Parker  1993 Nov 22 
;   Created data coordinates if not already present, W. Landsman Nov. 93
;   Added continuous printout of data values, COLOR and FULLCURSOR keywords
;      (so that default is that it acts just like the cursor command).
;      Changed name from CURFULL to RDPLOT.   J.Wm.Parker  1994 Apr 20
;   Modified (with some translation table assistance from the IDL support 
;      group) to correctly plot the crosshair with the desired IDL 
;      color using the device's translation table to determine the XOR 
;      function and using the BYPASS function.  Added the RESET_RDPLOT
;      procedure to cleanup crashes that might occur while running
;      RDPLOT.  Other minor changes/bug fixes.  J.Wm.Parker  1994 May 21
;   Modified DOWN, WAIT, CHANGE functions to behave more similar to the
;      generic CURSOR procedure.   J.Wm.Parker  1995 April 24
;   Added XVALUES, YVALUES keywords and cleanup.   J.Wm.Parker  1995 April 24
;   Convert to IDL V5.0,  W. Landsman    July 1998
;   Change !D.NCOLORS to !D.TABLE_SIZE for 24 bit displays W. Landsman May 2000
;   Skip translation table for TrueColor visuals   W. Landsman  March 2001

; NAME:
;       RDPSF
; PURPOSE:
;       Read the FITS file created by GETPSF in the DAOPHOT sequence 
; EXPLANATION:
;       Combines the Gaussian with the residuals to create an output PSF array.
;
; CALLING SEQUENCE:
;       RDPSF, PSF, HPSF, [ PSFname]
;
; OPTIONAL INPUTS
;       PSFname - string giving the name of the FITS file containing the PSF
;               residuals
;
; OUTPUTS
;       psf - array containing the actual PSF
;       hpsf - header associated with psf
;
; PROCEDURES CALLED:
;       DAO_VALUE(), MAKE_2D, SXADDPAR, READFITS(), SXPAR()
; REVISION HISTORY:
;       Written W. Landsman              December, 1988
;       Checked for IDL Version 2, J. Isensee & J. Hill, December, 1990
;       Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;       READCOL
; PURPOSE:
;       Read a free-format ASCII file with columns of data into IDL vectors 
; EXPLANATION:
;       Lines of data not meeting the specified format (e.g. comments) are 
;       ignored.  Columns may be separated by commas, tabs or spaces.
;
;       Use READFMT to read a fixed-format ASCII file.   Use RDFLOAT for
;       much faster I/O (but less flexibility).    Use FORPRINT to write 
;       columns of data (inverse of READCOL).
;
; CALLING SEQUENCE:
;       READCOL, name, v1, [ v2, v3, v4, v5, ...  v25 , COMMENT=
;           DELIMITER= ,FORMAT = , /DEBUG ,  /SILENT , SKIPLINE = , NUMLINE = ]
;
; INPUTS:
;       NAME - Name of ASCII data file, scalar string.  In VMS, an extension of 
;               .DAT is assumed, if not supplied.
;
; OPTIONAL INPUT KEYWORDS:
;       FORMAT - scalar string containing a letter specifying an IDL type
;               for each column of data to be read.  Allowed letters are 
;               A - string data, B - byte, D - double precision, F- floating 
;               point, I - integer, L - longword, Z - longword hexadecimal, 
;               and X - skip a column.
;
;               Columns without a specified format are assumed to be floating 
;               point.  Examples of valid values of FMT are
;
;       'A,B,I'        ;First column to read as a character string, then 
;                       1 column of byte data, 1 column integer data
;       'L,L,L,L'       ;Four columns will be read as longword arrays.
;       ' '             ;All columns are floating point
;
;       If a FORMAT keyword string is not supplied, then all columns are 
;       assumed to be floating point.
;
;       /SILENT - Normally, READCOL will display each line that it skips over.
;               If SILENT is set and non-zero then these messages will be 
;               suppressed.
;       /DEBUG - If this keyword is non-zero, then additional information is
;                printed as READCOL attempts to read and interpret the file.
;       COMMENT - single character specifying comment signal.   Any line 
;                beginning with this character will be skipped.   Default is
;                no comment lines.
;       DELIMITER - single character specifying delimiter used to separate 
;                columns.   Default is either a comma, tab, or a blank.
;       SKIPLINE - Scalar specifying number of lines to skip at the top of file
;               before reading.   Default is to start at the first line.
;       NUMLINE - Scalar specifying number of lines in the file to read.  
;               Default is to read the entire file
;
; OUTPUTS:
;       V1,V2,V3,...V25 - IDL vectors to contain columns of data.
;               Up to 25 columns may be read.  The type of the output vectors
;               are as specified by FORMAT.
;
; EXAMPLES:
;       Each row in a file position.dat contains a star name and 6 columns
;       of data giving an RA and Dec in sexigesimal format.   Read into IDL 
;       variables.   (NOTE: The star names must not include the delimiter 
;       as a part of the name, no spaces or commas as default.)
;
;       IDL> FMT = 'A,I,I,F,I,I,F'
;       IDL> READCOL,'position.dat',F=FMT,name,hr,min,sec,deg,dmin,dsec  
;
;       The HR,MIN,DEG, and DMIN variables will be integer vectors.
;
;       Alternatively, all except the first column could be specified as
;       floating point.
;
;       IDL> READCOL,'position.dat',F='A',name,hr,min,sec,deg,dmin,dsec 
;
;       To read just the variables HR,MIN,SEC
;       IDL> READCOL,'position.dat',F='X,I,I,F',HR,MIN,SEC
;
; RESTRICTIONS:
;       This procedure is designed for generality and not for speed.
;       If a large ASCII file is to be read repeatedly, it may be worth
;       writing a specialized reader.
;
;       Columns to be read as strings must not contain the delimiter character
;       (i.e. commas or spaces by default).   Either change the default 
;       delimiter with the DELIMITER keyword, or use READFMT to read such files.
;
;       Numeric values are converted to specified format.  For example,
;       the value 0.13 read with an 'I' format will be converted to 0.
;
; PROCEDURES CALLED
;       GETTOK(), NUMLINES(), REPCHR(), STRNUMBER()
;
; REVISION HISTORY:
;       Written         W. Landsman                 November, 1988
;       Modified             J. Bloch                   June, 1991
;       (Fixed problem with over allocation of logical units.)
;       Added SKIPLINE and NUMLINE keywords  W. Landsman    March 92
;       Read a maximum of 25 cols.  Joan Isensee, Hughes STX Corp., 15-SEP-93.
;       Call NUMLINES() function W. Landsman          Feb. 1996
;       Added DELIMITER keyword  W. Landsman          Nov. 1999
;       Fix indexing typos (i for k) that mysteriously appeared W. L. Mar. 2000
;       Hexadecimal support added.  MRG, RITSS, 15 March 2000.
;       Default is comma or space delimiters as advertised   W.L. July 2001
;       Faster algorithm, use STRSPLIT if V5.3 or later  W.L.  May 2002
;       Restore default recognition of tab delimiter  W.L. June 2002
;       Use SKIP_LUN if V5.6 or later W.L. Nov. 2002

; NAME:
;       READFITS
; PURPOSE:
;       Read a FITS file into IDL data and header variables. 
; EXPLANATION:
;       See http://idlastro.gsfc.nasa.gov/fitsio.html for other ways of
;       reading FITS files with IDL.
;
; CALLING SEQUENCE:
;       Result = READFITS( Filename/Fileunit,[ Header, heap, /NOSCALE, EXTEN_NO=,
;                       NSLICE=, /SILENT, STARTROW =, NUMROW = , HBUFFER=,
;                       /COMPRESS, /No_Unsigned ] )
;
; INPUTS:
;       Filename = Scalar string containing the name of the FITS file  
;                 (including extension) to be read.   If the filename has
;                  a *.gz extension, it will be treated as a gzip compressed
;                  file.   If it has a .Z extension, it will be treated as a
;                  Unix compressed file.
;                                   OR
;       Fileunit - A scalar integer specifying the unit of an already opened
;                  FITS file.  The unit will remain open after exiting 
;                  READFITS().  There are two possible reasons for choosing 
;                  to specify a unit number rather than a file name:
;          (1) For a FITS file with many extensions, one can move to the 
;              desired extensions with FXPOSIT() and then use READFITS().  This
;              is more efficient that repeatedly starting at the beginning of 
;              the file.
;          (2) For reading a FITS file across a Web http: address after opening
;              the unit with the SOCKET procedure (IDL V5.4 or later,
;              Unix and Windows only) 
; OUTPUTS:
;       Result = FITS data array constructed from designated record.
;                If the specified file was not found, then Result = -1
;
; OPTIONAL OUTPUT:
;       Header = String array containing the header from the FITS file.
;              If you don't need the header, then the speed may be improved by
;              not supplying this parameter.
;       heap = For extensions, the optional heap area following the main
;              data array (e.g. for variable length binary extensions).
;
; OPTIONAL INPUT KEYWORDS:
;       /CHECKSUM - If set, then READFITS() will call FITS_TEST_CHECKSUM to 
;                verify the data integrity if CHECKSUM keywords are present
;                in the FITS header.   Cannot be used with the NSLICE, NUMROW
;                or STARTROW keywords, since verifying the checksum requires 
;               that all the data be read.  See FITS_TEST_CHECKSUM() for more
;               information.
;
;       /COMPRESS - Signal that the file is gzip compressed.  By default, 
;               READFITS will assume that if the file name extension ends in 
;               '.gz' then the file is gzip compressed.   The /COMPRESS keyword
;               is required only if the the gzip compressed file name does not 
;               end in '.gz'.   Keyword only valid for IDL V5.3 or later.
;
;       EXTEN_NO - positive scalar integer specifying the FITS extension to
;               read.  For example, specify EXTEN = 1 or /EXTEN to read the 
;               first FITS extension.   
;
;       /NOSCALE - If present and non-zero, then the ouput data will not be
;                scaled using the optional BSCALE and BZERO keywords in the 
;                FITS header.   Default is to scale.
;
;       /NO_UNSIGNED -By default, if the header indicates an unsigned integer 
;              (BITPIX = 16, BZERO=2^15, BSCALE=1) then FITS_READ will output 
;               an IDL unsigned integer data type (UINT).   But if /NO_UNSIGNED
;               is set, then the data is converted to type LONG.  
;
;       NSLICE - Non-negative integer scalar specifying which N-1 dimensional 
;                slice of a N-dimensional array to read.   For example, if the 
;                primary image of a file 'wfpc.fits' contains a 800 x 800 x 4 
;                array, then 
;
;                 IDL> im = readfits('wfpc.fits',h, nslice=2)
;                           is equivalent to 
;                 IDL> im = readfits('wfpc.fits',h)
;                 IDL> im = im[*,*,2]
;                 but the use of the NSLICE keyword is much more efficient.
;
;       NUMROW -  Scalar non-negative integer specifying the number of rows 
;                 of the image or table extension to read.   Useful when one 
;                 does not want to read the entire image or table.    
;
;       POINT_LUN  -  Position (in bytes) in the FITS file at which to start
;                 reading.   Useful if READFITS is called by another procedure
;                 which needs to directly read a FITS extension.    Should 
;                 always be a multiple of 2880, and not be used with EXTEN_NO
;                 keyword.
;
;       /SILENT - Normally, READFITS will display the size the array at the
;                 terminal.  The SILENT keyword will suppress this
;
;        STARTROW - Non-negative integer scalar specifying the row
;               of the image or extension table at which to begin reading. 
;               Useful when one does not want to read the entire table.
;
;        HBUFFER - Number of lines in the header, set this to slightly larger
;                than the expected number of lines in the FITS header, to 
;               improve performance when reading very large FITS headers. 
;               Should be a multiple of 36 -- otherwise it will be modified
;               to the next higher multiple of 36.   Default is 180
;
; EXAMPLE:
;       Read a FITS file test.fits into an IDL image array, IM and FITS 
;       header array, H.   Do not scale the data with BSCALE and BZERO.
;
;              IDL> im = READFITS( 'test.fits', h, /NOSCALE)
;
;       If the file contains a FITS extension, it could be read with
;
;              IDL> tab = READFITS( 'test.fits', htab, /EXTEN )
;
;       The function TBGET() can be used for further processing of a binary 
;       table, and FTGET() for an ASCII table.
;       To read only rows 100-149 of the FITS extension,
;
;              IDL> tab = READFITS( 'test.fits', htab, /EXTEN, 
;                                   STARTR=100, NUMR = 50 )
;
;       To read in a file that has been compressed:
;
;              IDL> tab = READFITS('test.fits.gz',h)
;
; ERROR HANDLING:
;       If an error is encountered reading the FITS file, then 
;               (1) the system variable !ERROR is set (via the MESSAGE facility)
;               (2) the error message is displayed (unless /SILENT is set),
;                   and the message is also stored in !ERR_STRING
;               (3) READFITS returns with a value of -1
; RESTRICTIONS:
;       (1) Cannot handle random group FITS
;
; NOTES:
;       (1) If data is stored as integer (BITPIX = 16 or 32), and BSCALE
;       and/or BZERO keywords are present, then the output array is scaled to 
;       floating point (unless /NOSCALE is present) using the values of BSCALE
;       and BZERO.   In the header, the values of BSCALE and BZERO are then 
;       reset to 1. and 0., while the original values are written into the 
;       new keywords O_BSCALE and O_BZERO.     If the BLANK keyword was
;       present, then any input integer values equal to BLANK in the input
;       integer image are unchanged by BSCALE or BZERO
;       
;       (2) The use of the NSLICE keyword is incompatible with the NUMROW
;       or STARTROW keywords.
;
;       (3) READFITS() underwent a substantial rewrite in October 1998 to 
;       eliminate recursive calls, and improve efficiency when reading
;       extensions.
;            1. The NUMROW and STARTROW keywords can now be used when reading
;              a primary image (extension = 0).
;            2. There is no error check for moving past the end of file when
;               reading the data array.
;
;       (4) On some Unix shells, one may get a "Broken pipe" message if reading
;        a UNIX compressed file, and not reading to the end of the file (i.e. 
;        the decompression has not gone to completion).     This is an 
;        informative message only, and should not affect the output of 
;        READFITS().  
;
; PROCEDURES USED:
;       Functions:   SXPAR() 
;       Procedures:  SXADDPAR, SXDELPAR
;
; MODIFICATION HISTORY:
;       Original Version written in 1988, W.B. Landsman   Raytheon STX
;       Revision History prior to October 1998 removed          
;       Major rewrite to eliminate recursive calls when reading extensions
;                  W.B. Landsman  Raytheon STX                    October 1998
;       Add /binary modifier needed for Windows  W. Landsman    April 1999
;       Read unsigned datatypes, added /no_unsigned   W. Landsman December 1999
;       Output BZERO = 0 for unsigned data types   W. Landsman   January 2000
;       Open with /swap_if_little_endian if since V5.1 W. Landsman February 2000
;       Fixed logic error when using NSLICE keyword W. Landsman March 2000
;       Fixed byte swapping problem for compressed files on little endian 
;             machines introduced in Feb 2000     W. Landsman       April 2000
;       Fix error handling so FREE_LUN is called in case of READU error
;						W. Landsman N. Rich, Aug. 2000
;       Assume since V5.1, remove NANvalue keyword  W. Landsman   July 2001 
;       Support the unofficial 64bit integer format W. Landsman   September 2001
;       Option to read a unit number rather than file name W.L    October 2001
;       Fix byte swapping problem for compressed files again (sigh...) 
;                W. Landsman   March 2002
;       Make sure gzip defined when using a unit number W. Landsman Oct. 2002 
;       Assume V5.2 or later            W. Landsman        Jan. 2003
;       Don't read entire header unless needed   W. Landsman  Jan. 2003
;       Added HBUFFER keyword    W. Landsman   Feb. 2003
;       Added CHECKSUM keyword   W. Landsman   May 2003

; NAME:
;     READFMT
; PURPOSE:
;       Quickly read a fixed format ASCII data file into IDL variables. 
; EXPLANATION:
;       Lines of data not meeting the specified format (e.g. comments) are
;       ignored.  
;      
;       To read a free format ASCII data file use the procedures 
;       READCOL or RDFLOAT.     To print (formatted or free) columns of data
;       use the procedure FORPRINT.   
;
; CALLING SEQUENCE:
;       READFMT, name, fmt, v1,[ v2, v3, v4, ..., v25 , 
;                          /SILENT, /DEBUG, SKIPLINE= , NUMLINE =]
;
; INPUTS:
;       NAME - Name of ASCII data file.  An extension of .DAT is assumed,
;               if not supplied.
;       FMT - scalar string containing a valid FORTRAN read format.
;               Must include a field length specification.   Cannot include
;               internal parenthesis.  A format field must be included for 
;               each output vector.   Multiple format fields are allowed, but
;               the repetition factor must be less than 100, (.i.e. 19X is 
;               allowed but 117X is illegal) 
;
;       Examples of valid FMT values are
;               FMT = 'A7,3X,2I4'  or FMT = '1H ,5I7,2A7'
;       Examples of INVALID FMT values are
;               FMT = 'A7,B3'           ;'B' is not a valid FORTRAN format
;               FMT = 'A7,2(I3,F5.1)'   ;Internal parenthesis not allowed
;               FMT = 'A7,F,I'          ;Field length not included
;
; OUTPUTS:
;       V1,V2,V3,V4... - IDL vectors to contain columns of data.
;               Up to 25 output vectors may be read.  The type of the output 
;               vectors are specified by FMT.
;
; OPTIONAL KEYWORD INPUTS:
;       /SILENT - If this keyword is set and non-zero, then certain terminal
;               output is suppressed while reading the file
;       /DEBUG - Set this keyword to display additional information while
;               reading the file.
;       SKIPLINE - Scalar specifying number of lines to skip at the top of
;               file before reading. Default is to start at first line
;       NUMLINE - Scalar specifying number of lines in the file to read.
;               Default is to read the entire file 
;
; EXAMPLES:
;       Each row in a fixed-format file POSITION.DAT contains a 5 character 
;       star name  and 6 columns of data giving an RA and Dec in sexigesimal 
;       format.   A possible format for such data might be
;
;       IDL> FMT = 'A5,2I3,F5.1,2x,3I3'    
;       and the file could be quickly read with
;
;       IDL> READFMT,'POSITION', fmt, name, hr, min, sec, deg, dmin, dsec 
;    
;       NAME will be a string vector,SEC will be a floating point vector, and
;       the other vectors will be of integer type.
;
; RESTRICTIONS:
;       This procedure is designed for generality and not for speed.
;       If a large ASCII file is to be read repeatedly, it may be worth
;       writing a specialized reader.
;
; NOTES:
;       When reading a field with an integer format I, the output vector is
;               byte  - if n = 1
;               integer*2 - if 1 < n < 5
;               integer*4  - in all other cases
;       Octal ('O') and hexadecimal ('Z') formats are read into longwords
;
; PROCEDURE CALLS:
;       GETTOK(), NUMLINES(), REMCHAR, ZPARCHECK
;
; REVISION HISTORY:
;       Written         W. Landsman                 November, 1988
;       Added SKIPLINE and NUMLINE keywords         March 92
;       Allow up to 25 columns to be read           June 92
;       Call NUMLINES() function                    Feb 1996
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Recognize 'O' and 'Z' formats  W. Landsman   September 1997

; NAME:
;	READ_KEY
; PURPOSE:
;	To read a keystroke and return its ASCII equivalent
; EXPLANATION:
;	If an ESCAPE sequence was produced and  the sequence is
;	recognized (e.g. up arrow), then a code is returned.
;
; CALLING SEQUENCE:
;	key = READ_KEY(Wait)
;
; INPUTS:
;	Wait  -  The wait flag.  If non-zero, execution is halted until a
;	         key is struck.  If zero, execution returns immediately and
;	         a zero is returned if there was no keystroke waiting in the
;	         keyboard buffer.  If not specified, zero is assumed.
;
; OUTPUT:
;	Returned - The key struck.  The ASCII code for non-escape sequences.
;	           Escape sequence equivalents:
;			Up Arrow     --  128
;			Down Arrow   --  130
;			Left Arrow   --  129
;			Right Arrow  --  131
;			Else         --    0
;
;	The return value is a byte value.
;
; MODIFICATION HISTORY:
;	Written by Michael R. Greason, STX, 22 June 1990.
;	Rewritten for a SUN workstation.  MRG, STX, 23 August 1990.
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;       RECPOL
; PURPOSE:
;       Convert 2-d rectangular coordinates to polar coordinates.
; CATEGORY:
; CALLING SEQUENCE:
;       recpol, x, y, r, a
; INPUTS:
;       x, y = vector in rectangular form.           in
; KEYWORD PARAMETERS:
;       Keywords:
;         /DEGREES means angle is in degrees, else radians.
; OUTPUTS:
;       r, a = vector in polar form: radius, angle.  out
; COMMON BLOCKS:
; NOTES:
; MODIFICATION HISTORY:
;       R. Sterner. 18 Aug, 1986.
;       Johns Hopkins University Applied Physics Laboratory.
;       RES 13 Feb, 1991 --- added /degrees.
;       R. Sterner, 30 Dec, 1991 --- simplified.
;       R. Sterner, 25 May, 1993 --- Fixed atan (0,0) problem.
;
; Copyright (C) 1986, 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.
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;       REDSHIFT
; PURPOSE:
;       Interactively converts between redshift, Recession velocity, & Distance
; EXPLANATION:
;       This simple program assumes a linear Hubble law and no cosmological
;       constant.    For more general and precise conversions use the program
;       lumdist.pro 
; CALLING SEQUENCE:
;       redshift, [h, /HELP]
; INPUTS:
;       h = optional Hubble constant (def = 50 km/s/Mpc).      in
; OUTPUTS:
;       Results are displayed at the terminal screen
; NOTES:
;       Note: H may be changed at any time by typing h=new_value.
;       Also displays angular size equivalence and photometric information.
;
; MODIFICATION HISTORY:
;       R. Sterner. 17 July, 1987.
;       Johns Hopkins University Applied Physics Laboratory.
;       RES 7 Jan, 1988 --- added H0.
;
; Copyright (C) 1987, 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.
;       Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	REMCHAR
; PURPOSE:
;	Remove all appearances of character (char) from string (st)
;
; CALLING SEQUENCE:
;	REMCHAR, ST, CHAR
;
; INPUT-OUTPUT:
;	ST  - String from which character will be removed, scalar or vector  
; INPUT:
;	CHAR- Single character to be removed from string or all elements of a
;		string array 
;
; EXAMPLE:
;	If a = 'a,b,c,d,e,f,g' then 
;
;	IDL> remchar,a, ','
;
;      will give a = 'abcdefg'
;
; REVISIONS HISTORY
;	Written D. Lindler October 1986
;	Test if empty string needs to be returned   W. Landsman  Feb 1991
;	Work on string arrays    W. Landsman   August 1997
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;       REMOVE
; PURPOSE:
;       Contract a vector or up to 7 vectors by removing specified elements   
; CALLING SEQUENCE:
;       REMOVE, index, v1,[ v2, v3, v4, v5, v6, v7]     
; INPUTS:
;       INDEX - scalar or vector giving the index number of elements to
;               be removed from vectors.  Duplicate entries in index are
;               ignored.    An error will occur if one attempts to remove
;               all the elements of a vector.
;
; INPUT-OUTPUT:
;       v1 - Vector or array.  Elements specifed by INDEX will be 
;               removed from v1.  Upon return v1 will contain
;               N fewer elements, where N is the number of values in
;               INDEX.
;
; OPTIONAL INPUT-OUTPUTS:
;       v2,v3,...v7 - additional vectors containing
;               the same number of elements as v1.  These will be
;               contracted in the same manner as v1.
;
; EXAMPLES:
;       (1) If INDEX = [2,4,6,4] and V = [1,3,4,3,2,5,7,3] then after the call
;
;               IDL> remove,index,v      
;
;       V will contain the values [1,3,3,5,3]
;
;       (2) Suppose one has a wavelength vector W, and three associated flux
;       vectors F1, F2, and F3.    Remove all points where a quality vector,
;       EPS is negative
;
;               IDL> bad = where( EPS LT 0, Nbad)
;               IDL> if Nbad GT 0 then remove, bad, w, f1, f2, f3
;
; METHOD:
;       If more than one element is to be removed, then HISTOGRAM is used
;       to generate a 'keep' subscripting vector.    To minimize the length of 
;       the subscripting vector, it is only computed between the minimum and 
;       maximum values of the index.   Therefore, the slowest case of REMOVE
;       is when both the first and last element are removed.
;
; REVISION HISTORY:
;       Written W. Landsman        ST Systems Co.       April 28, 1988
;       Cleaned up code          W. Landsman            September, 1992
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Major rewrite for improved speed   W. Landsman    April 2000

; NAME:	
;	REM_DUP
; PURPOSE:  
;	Function to remove duplicate values from a vector.
;
; CALLING SEQUENCE:
;	result = rem_dup( a, [ flag ] )
;
; INPUTS:
;	a - vector of values from which duplicates are to be found
;	flag - (optional) if supplied then when duplicates occur,
;		the one with the largest value of flag is selected.
;		If not supplied the the first occurence of the value
;		in a is selected.     Should be a vector with the same
;               number of elements as a.
;
; OUTPUT:
;	A vector of subscripts in a is returned.  Each subscript
;	points to a selected value such that a(rem_dup(a,flag))
;	has no duplicates.
;
; SIDE EFFECTS:
;	The returned subscripts will sort the values in a in ascending
;	order with duplicates removed.
;
; EXAMPLES:
;
;	Remove duplicate values in vector a.
;	 	a = a( rem_dup(a) )
;
;	Remove duplicates in vector WAVE.  When duplicate values
;	are found, select the one with the largest intensity, INTE.
;
;		sub = rem_dup( wave, inte)
;		wave = wave( sub )
;		inte = inte( sub )
;
; NOTES:
;	The UNIQ function in the User's Library uses a faster algorithm,
;	but has no equivalent of the "flag" parameter
;
; MODIFICATION HISTORY:
;	D. Lindler  Mar. 87
;	11/16/90 JKF ACC - converted to IDL Version 2.
;	August 1997  -- Changed loop index to type LONG
;	October 1997 -- Also changed NGOOD index to LONG
;	Converted to IDL V5.0   W. Landsman   October 1997

; NAME:
;       REPCHR
; PURPOSE:
;       Replace all occurrences of one character with another in a text string.
; CATEGORY:
; CALLING SEQUENCE:
;       new = repchr(old, c1, [c2])
; INPUTS:
;       old = original text string.          in
;       c1 = character to replace.           in
;       c2 = character to replace it with.   in
;            default is space.
; KEYWORD PARAMETERS:
; OUTPUTS:
;       new = edited string.                 out
; COMMON BLOCKS:
; NOTES:
; MODIFICATION HISTORY:
;       R. Sterner.  28 Oct, 1986.
;       Johns Hopkins Applied Physics Lab.
;       RES 1 Sep, 1989 --- converted to SUN.
;       R. Sterner, 27 Jan, 1993 --- dropped reference to array.
;
; Copyright (C) 1986, 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.
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	REPSTR
; PURPOSE:
;	Replace all occurences of one substring by another.
; EXPLANATION:
;	Meant to emulate the string substitution capabilities of text editors
; CALLING SEQUENCE:
;	result = repstr( obj, in, out )
;
; INPUT PARAMETERS:
;	obj    = object string for editing, scalar or array
;	in     = substring of 'obj' to be replaced, scalar 
;
; OPTIONAL INPUT PARMETER:
;	out    = what 'in' is replaced with, scalar.   If not supplied
;		then out = '', i.e. 'in' is not replaced by anything. 
;
; OUTPUT PARAMETERS:
;	Result returned as function value.  Input object string
;	not changed unless assignment done in calling program.
;
; PROCEDURE:
;	Searches for 'in', splits 'obj' into 3 pieces, reassembles
;	with 'out' in place of 'in'.  Repeats until all cases done.
;
; EXAMPLE:
;	If a = 'I am what I am' then print,repstr(a,'am','was')
;	will give 'I was what I was'.
;
; MODIFICATION HISTORY:
;	Written by Robert S. Hill, ST Systems Corp., 12 April 1989.
;	Accept vector object strings, W. Landsman   HSTX,   April, 1996
;	Converted to IDL V5.0   W. Landsman   September 1997
;       Convert loop to LONG, vectorize STRLEN call W. Landsman June 2002
;       Correct bug in optimization, case where STRLEN(OBJ) EQ
;         STRLEN(IN), C. Markwardt, Jan 2003
;       Fixed problem when multiple replacements extend the string length
;                 D. Finkbeiner, W. Landsman  April 2003
;       Allow third parameter to be optional again W. Landsman  August 2003

; NAME:
;    RESISTANT_Mean  
;
; PURPOSE:
;    Outlier-resistant determination of the mean and standard deviation. 
; 
; EXPLANATION:
;    RESISTANT_Mean trims away outliers using the median and the median 
;    absolute deviation.    An approximation formula is used to correct for
;    the trunction caused by trimming away outliers
;
; CALLING SEQUENCE:
;    RESISTANT_Mean, VECTOR, Sigma_CUT, Mean, Sigma_Mean, Num_RejECTED
;
; INPUT ARGUMENT:
;       VECTOR    = Vector to average
;       Sigma_CUT = Data more than this number of standard deviations from the
;               median is ignored. Suggested values: 2.0 and up.
;
; OUTPUT ARGUMENT:
;       Mean  = the mean of the input vector, numeric scalar
; OPTIONAL OUTPUTS:
;	Sigma_Mean = the approximate standard deviation of the mean, numeric 
;            scalar.  This is the Sigma of the distribution divided by sqrt(N-1)
;            where N is the number of unrejected points. The larger
;            SIGMA_CUT, the more accurate. It will tend to underestimate the 
;            true uncertainty of the mean, and this may become significant for 
;            cuts of 2.0 or less. 
;       Num_RejECTED = the number of points trimmed, integer scalar
;
; EXAMPLE:
;       IDL> a = randomn(seed, 10000)    ;Normal distribution with 10000 pts
;       IDL> RESISTANT_Mean,a, 3, mean, meansig, num    ;3 Sigma clipping    
;       IDL> print, mean, meansig,num
; 
;       The mean should be near 0, and meansig should be near 0.01 ( =
;        1/sqrt(10000) ).     
; PROCEDURES USED:
;       AVG() - compute simple mean
; REVISION HISTORY:
;       Written, H. Freudenreich, STX, 1989; Second iteration added 5/91.
;       Use MEDIAN(/EVEN)    W. Landsman   April 2002
;       Correct conditional test, higher order truncation correction formula
;                R. Arendt/W. Landsman   June 2002
;       New truncation formula for sigma H. Freudenriech  July 2002

; NAME:
;      RINTER
; PURPOSE:
;      Cubic interpolation of an image at a set of reference points.
; EXPLANATION:
;      This interpolation program is equivalent to using the intrinsic 
;      INTERPOLATE() function in IDL V5.0 or later with CUBIC = -0.5.   However,
;      RINTER() has two advantages: (1) one can optionally obtain the 
;      X and Y derivatives at the reference points, and (2) if repeated
;      interpolation is to be applied to an array, then some values can
;      be pre-computed and stored in Common.   RINTER() was originally  
;      for use with the DAOPHOT procedures, but can also be used for 
;      general cubic interpolation.
;
; CALLING SEQUENCE:
;      Z = RINTER( P, X, Y, [ DFDX, DFDY ] )
;               or
;      Z = RINTER(P, /INIT)
;
; INPUTS:                 
;      P  - Two dimensional data array, 
;      X  - Either an N element vector or an N x M element array,
;               containing X subscripts where cubic interpolation is desired.
;      Y -  Either an N element vector or an N x M element array, 
;               containing Y subscripts where cubic interpolation is desired.
;
; OUTPUT:
;      Z -  Result = interpolated vector or array.  If X and Y are vectors,
;              then so is Z, but if X and Y are arrays then Z will be also.
;              If P is DOUBLE precision, then so is Z, otherwise Z is REAL.
;
; OPTIONAL OUTPUT:
;      DFDX - Vector or Array, (same size and type as Z), containing the 
;               derivatives with respect to X
;      DFDY - Array containing derivatives with respect to Y
;
; OPTIONAL KEYWORD INPUT:
;     /INIT - Perform computations associated only with the input array (i.e. 
;             not with X and Y) and store in common.    This can save time if
;             repeated calls to RINTER are made using the same array.  
;        
; EXAMPLE:
;      suppose P is a 256 x 256 element array and X = FINDGEN(50)/2. + 100.
;      and Y = X.  Then Z will be a 50 element array, containing the
;      cubic interpolated points.
;
; SIDE EFFECTS:
;      can be time consuming.
;
; RESTRICTION:
;      Interpolation is not possible at positions outside the range of 
;       the array (including all negative subscripts), or within 2 pixel
;       units of the edge.  No error message is given but values of the 
;       output array are meaningless at these positions.
;
; PROCEDURE:
;       invokes CUBIC interpolation algorithm to evaluate each element
;       in Z at virtual coordinates contained in X and Y with the data
;       in P.                                                          
;
; COMMON BLOCKS:
;       If repeated interpolation of the same array is to occur, then
;       one can save time by initializing the common block RINTER.    
;
; REVISION HISTORY:
;       March 1988 written W. Landsman STX Co.
;       Checked for IDL Version 2, J. Isensee, September, 1990
;       Corrected call to HISTOGRAM, W. Landsman November 1990
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Fix output derivatives for 2-d inputs, added /INIT W. Landsman May 2000
;       

; NAME:
;       ROBUST_LINEFIT
;
; PURPOSE:
;       An outlier-resistant two-variable linear regression. 
; EXPLANATION:
;       Either Y on X or, for the case in which there is no true independent 
;       variable, the bisecting line of Y vs X and X vs Y is calculated. No 
;       knowledge of the errors of the input points is assumed.
;
; CALLING SEQUENCE:
;       COEFF = ROBUST_LINEFIT( X, Y, YFIT, SIG, COEF_SIG, [ /BISECT,
;                       BiSquare_Limit = , Close_factor = , NumIT = ] )
;
; INPUTS:
;       X = Independent variable vector, floating-point or double-precision
;       Y = Dependent variable vector
;
; OUTPUTS:
;       Function result = coefficient vector. 
;       If = 0.0 (scalar), no fit was possible.
;       If vector has more than 2 elements (the last=0) then the fit is dubious.
;
; OPTIONAL OUTPUT PARAMETERS:
;       YFIT = Vector of calculated y's
;       SIG  = The "standard deviation" of the fit's residuals. If BISECTOR 
;               is set, this will be smaller by ~ sqrt(2).
;       COEF_SIG  = The estimated standard deviations of the coefficients. If 
;               BISECTOR is set, however, this becomes the vector of fit 
;               residuals measured orthogonal to the line.
;
; OPTIONAL INPUT KEYWORDS:
;       NUMIT = the number of iterations allowed. Default = 25
;       BISECT  if set, the bisector of the "Y vs X" and "X vs Y" fits is 
;               determined.  The distance PERPENDICULAR to this line is used 
;               in calculating weights. This is better when the uncertainties 
;               in X and Y are comparable, so there is no true independent 
;               variable.  Bisquare_Limit  Limit used for calculation of 
;               bisquare weights. In units of outlier-resistant standard 
;               deviations. Default: 6.
;               Smaller limit ==>more resistant, less efficient
; Close_Factor  - Factor used to determine when the calculation has converged.
;               Convergence if the computed standard deviation changes by less 
;               than Close_Factor * ( uncertainty of the std dev of a normal
;               distribution ). Default: 0.03.
; SUBROUTINE CALLS:
;       ROB_CHECKFIT
;       ROBUST_SIGMA, to calculate a robust analog to the std. deviation
;
; PROCEDURE:
;       For the initial estimate, the data is sorted by X and broken into 2
;       groups. A line is fitted to the x and y medians of each group.
;       Bisquare ("Tukey's Biweight") weights are then calculated, using the 
;       a limit of 6 outlier-resistant standard deviations.
;       This is done iteratively until the standard deviation changes by less 
;       than CLOSE_ENOUGH = CLOSE_FACTOR * {uncertainty of the standard 
;               deviation of a normal distribution}
;
; REVISION HISTORY:
;       Written, H. Freudenreich, STX, 4/91.
;       4/13/93 to return more realistic SS's HF
;       2/94 --more error-checking, changed convergence criterion HF
;       5/94 --added BISECT option. HF.
;       8/94 --added Close_Factor and Bisquare_Limit options  Jack Saba.
;       4/02 --V5.0 version, use MEDIAN(/EVEN)  W. Landsman

; NAME:
;	ROBUST_POLY_FIT
;
; PURPOSE:
;	An outlier-resistant polynomial fit.
;
; CALLING SEQUENCE:
;	COEFF = ROBUST_POLY_FIT(X,Y,NDEGREE  ,[ YFIT,SIG, NUMIT =] )
;
; INPUTS:
;	X = Independent variable vector, floating-point or double-precision
;	Y = Dependent variable vector
;
; OUTPUTS:
;	Function result = coefficient vector, length NDEGREE+1. 
;	IF COEFF=0.0, NO FIT! If N_ELEMENTS(COEFF) > degree+1, the fit is poor
;	(in this case the last element of COEFF=0.)
;	Either floating point or double precision.
;
; OPTIONAL OUTPUT PARAMETERS:
;	YFIT = Vector of calculated y's
;	SIG  = the "standard deviation" of the residuals
;
; RESTRICTIONS:
;	Large values of NDEGREE should be avoided. This routine works best
;	when the number of points >> NDEGREE.
;
; PROCEDURE:
;	For the initial estimate, the data is sorted by X and broken into 
;	NDEGREE+2 sets. The X,Y medians of each set are fitted to a polynomial
;	 via POLY_FIT.   Bisquare ("Tukey's Biweight") weights are then 
;	calculated, using a limit  of 6 outlier-resistant standard deviations.
;	The fit is repeated iteratively until the robust standard deviation of 
;	the residuals changes by less than .03xSQRT(.5/(N-1)).
;
; REVISION HISTORY
;	Written, H. Freudenreich, STX, 8/90. Revised 4/91.
;	2/94 -- changed convergence criterion

; NAME:
;	ROBUST_SIGMA  
;
; PURPOSE:
;	Calculate a resistant estimate of the dispersion of a distribution.
; EXPLANATION:
;	For an uncontaminated distribution, this is identical to the standard
;	deviation.
;
; CALLING SEQUENCE:
;	result = ROBUST_SIGMA( Y, [ /ZERO ] )
;
; INPUT: 
;	Y = Vector of quantity for which the dispersion is to be calculated
;
; OPTIONAL INPUT KEYWORD:
;	/ZERO - if set, the dispersion is calculated w.r.t. 0.0 rather than the
;		central value of the vector. If Y is a vector of residuals, this
;		should be set.
;
; OUTPUT:
;	ROBUST_SIGMA returns the dispersion. In case of failure, returns 
;	value of -1.0
;
; PROCEDURE:
;	Use the median absolute deviation as the initial estimate, then weight 
;	points using Tukey's Biweight. See, for example, "Understanding Robust
;	and Exploratory Data Analysis," by Hoaglin, Mosteller and Tukey, John
;	Wiley & Sons, 1983.
;
; REVSION HISTORY: 
;	H. Freudenreich, STX, 8/90
;       Replace MED() call with MEDIAN(/EVEN)  W. Landsman   December 2001
;

; NAME:
;	ROB_CHECKFIT
; PURPOSE:
;	Used by ROBUST_... routines to determine the quality of a fit and to
;	return biweights.
; CALLING SEQUENCE:
;	status = ROB_CHECKFIT( Y, YFIT, EPS, DEL, SIG, FRACDEV, NGOOD, W, B
;				BISQUARE_LIMIT = )
; INPUT:
;	Y     = the data
;	YFIT  = the fit to the data
;	EPS   = the "too small" limit
;	DEL   = the "close enough" for the fractional median abs. deviations
; RETURNS:
;	Integer status. if =1, the fit is considered to have converged
;
; OUTPUTS:
;	SIG   = robust standard deviation analog
;	FRACDEV = the fractional median absolute deviation of the residuals
;	NGOOD   = the number of input point given non-zero weight in the 
;		calculation
;	W     = the bisquare weights of Y
;	B     = residuals scaled by sigma
;
; OPTIONAL INPUT KEYWORD:
;	BISQUARE_LIMIT = allows changing the bisquare weight limit from 
;			default 6.0
; PROCEDURES USED:
;       ROBUST_SIGMA()
; REVISION HISTORY:
;	Written, H.T. Freudenreich, HSTX, 1/94

; NAME:
;	SCREEN_SELECT
; PURPOSE:
;	Allow a user to make an interactive screen selection from a list
; EXPLANATION:
;	This procedure determines whether to use the dumb terminal version,  
;	or the widget version by examining the !D.NAME system variable.
;
; CALLING SEQUENCE:
;	screen_select, selections, iselected, comments, command_line, only_one
;
; INPUTS:
;	selections - string array giving list of items that can be
;		selected.
;
; OPTIONAL INPUTS:
;	comments - comments which can be requested for each item in
;		array selections.  It can be:
;			string array - same length as array selections.
;			null string - no comments available
;			scalar string - name of a procedure which will
;				return comments.  It will take selections
;				as its first argument and return comments
;				as its second argument.
;	command_line - optional command line to be placed at the bottom
;		of the screen.  It is usually used to specify what the
;		user is selecting.
;	only_one - integer flag. If set to 1 then the user can only select
;		one item.  The routine returns immediately after the first
;		selection is made.
;
; OUTPUTS:
;	iselected - list of indices in selections giving the selected
;		items.
;
; OPTIONAL OUTPUT KEYWORD:
;       COUNT - Integer scalar giving the number of selections made
;
; SIDE EFFECTS:
;	The obsolete system variable !err is set to the number of selections
;
; PROCEDURE:
;	The actual processing is farmed out to different procedures depending
;	on the terminal type.    
;
;	Widget Terminal   ==>  SELECT_W.PRO
;	VT100 Terminal  ==>    SELECT_O.PRO
; HISTORY:
;	Written by M. Greason, STX, May 1990.
;       Added widget support    W. Landsman           January, 1992
;	Remove X window but no widget option         November, 1994
;	Converted to IDL V5.0   W. Landsman   September 1997
;       Added COUNT keyword, deprecate !ERR   W. Landsman   March 2000

; NAME:
;	SCR_ATTRIB
; PURPOSE:
;	To set the screen attribute to those given, in the given order.
; CALLING SEQUENCE:
;	scr_attrib [, a1, a2, a3, a4, a5]
; INPUTS:
;	a1 - a5  --  The attribute codes.  The attributes are set in the
;	             command string in the given order.  Thus, if a1 turns
;	             the attributes off and a2 sets reverse video, the final
;	             attribute will reset and then set to reverse video.  If
;	             the order were reversed, then the current attribute 
;	             would have reverse video added to it, and then would be
;	             reset, leaving the terminal with all attributes off.  Up
;	             to five attribute codes may be specified.  The codes are:
;	                  0 : all attributes off  (default)
;	                  1 : bold on
;	                  2 : underscore on
;	                  3 : blink on
;	                  4 : reverse video on
; OUTPUTS:
;	None.
; SIDE EFFECTS:
;	None.
; RESTRICTIONS:
;	This procedure will only work with DEC compatible equipment (or
;	terminal emulators).
; PROCEDURE:
;	A string containing the appropriate DEC terminal command is put 
;	together and printed.  NOTE:  In general, the DEC commands correspond
;	to the ANSI escape sequences.
; MODIFICATION HISTORY:
;	Written by Michael R. Greason, STX, May 1990.
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	SCR_CHARSET
; PURPOSE:
;	To change the character sets.
; CALLING SEQUENCE:
;	scr_charset [, g, cset]
; INPUTS:
;	g     --  The terminal character set to change (either 0, for the
;	          G0 designator, or 1, for the G1 designator).  0 = default.
;	cset  --  The character set to use:
;	               0 : United Kingdom.
;	               1 : United States (USASCII)  --  default.
;	               2 : Special graphics characters and line drawing set.
;	               3 : Alternate character ROM.
;	               4 : Alternate character ROM special graphics chars.
; OUTPUTS:
;	None.
; SIDE EFFECTS:
;	None.
; RESTRICTIONS:
;	This procedure will only work with DEC compatible equipment (or
;	terminal emulators).
; PROCEDURE:
;	A string containing the appropriate DEC terminal command is put 
;	together and printed.  NOTE:  In general, the DEC commands correspond
;	to the ANSI escape sequences.
; MODIFICATION HISTORY:
;	Written by Michael R. Greason, STX, May 1990.
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	SCR_CURMOV
; PURPOSE:
;	To mov the cursor around the screen relative to its original position.
; CALLING SEQUENCE:
;	scr_curmov [, cmd, n]
; INPUTS:
;	cmd  --  An integer indicating the direction in which to move the curs.
;	              0 : Up
;	              1 : Down  (Default)
;	              2 : Left
;	              3 : Right
;	n    --  The number of spaces to move the cursor.  If not specified
;	         (or if less than or equal to zero), this is set to one.
; OUTPUTS:
;	None.
; SIDE EFFECTS:
;	None.
; RESTRICTIONS:
;	This procedure will only work with DEC compatible equipment (or
;	terminal emulators).
; PROCEDURE:
;	A string containing the appropriate DEC terminal command is put 
;	together and printed.  NOTE:  In general, the DEC commands correspond
;	to the ANSI escape sequences.
; MODIFICATION HISTORY:
;	Written by Michael R. Greason, STX, May 1990.
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	SCR_CURPOS
; PURPOSE:
;	To position the cursor at the specified screen location.  
; EXPLANATION:
;	Unspecified coordinates are set to one.  Please note that the ESCAPE 
;	sequence expects the coordinates to be counted from (1,1).
; CALLING SEQUENCE:
;	scr_curpos [, lin, col]
; INPUTS:
;	lin  --  The screen line coordinate.
;	col  --  The screen column coordinate.
; OUTPUTS:
;	None.
; SIDE EFFECTS:
;	None.
; RESTRICTIONS:
;	This procedure will only work with DEC compatible equipment (or
;	terminal emulators).
; PROCEDURE:
;	A string containing the appropriate DEC terminal command is put 
;	together and printed.  NOTE:  In general, the DEC commands correspond
;	to the ANSI escape sequences.
; MODIFICATION HISTORY:
;	Written by Michael R. Greason, STX, May 1990.
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	SCR_ERASE
; PURPOSE:
;	To erase portions of the terminal screen.
; CALLING SEQUENCE:
;	scr_erase [, cmd]
; INPUTS:
;	cmd  --  An integer telling the procedure what part of the screen to
;	         erase.  If not specified, it is set to 5.  Key:
;	                 0 : From cursor to end-of-line.
;	                 1 : From beginning-of-line to cursor.
;	                 2 : Entire line containing cursor.
;	                 3 : From cursor to end-of-screen.
;	                 4 : from beginning-of-screen to cursor.
;	              ELSE : Entire screen.
; OUTPUTS:
;	None.
; SIDE EFFECTS:
;	None.
; RESTRICTIONS:
;	This procedure will only work with DEC compatible equipment (or
;	terminal emulators).
; PROCEDURE:
;	A string containing the appropriate DEC terminal command is put 
;	together and printed.  NOTE:  In general, the DEC commands correspond
;	to the ANSI escape sequences.
; MODIFICATION HISTORY:
;	Written by Michael R. Greason, STX, May 1990.
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	SCR_OTHER
; PURPOSE:
;	To allow the user to issue any ESCAPE sequence.
; CALLING SEQUENCE:
;	scr_other, str
; INPUTS:
;	str  --  A string containing the escape sequence.  The initial ESCAPE
;	         should not be included; this will be added by this procedure.
;	         This parameter is NOT optional; if not available, the 
;	         procedure will return without doing anything.
; OUTPUTS:
;	None.
; SIDE EFFECTS:
;	None.
; RESTRICTIONS:
;	This procedure will only work with DEC compatible equipment (or
;	terminal emulators).
; PROCEDURE:
;	A string containing the appropriate DEC terminal command is put 
;	together and printed.  NOTE:  In general, the DEC commands correspond
;	to the ANSI escape sequences.
; MODIFICATION HISTORY:
;	Written by Michael R. Greason, STX, May 1990.
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	SCR_RESET
; PURPOSE:
;	To reset the terminal.
; CALLING SEQUENCE:
;	scr_reset
; INPUTS:
;	None.
; OUTPUTS:
;	None.
; SIDE EFFECTS:
;	None.
; RESTRICTIONS:
;	This procedure will only work with DEC compatible equipment (or
;	terminal emulators).
; PROCEDURE:
;	A string containing the appropriate DEC terminal command is put 
;	together and printed.  NOTE:  In general, the DEC commands correspond
;	to the ANSI escape sequences.
; MODIFICATION HISTORY:
;	Written by Michael R. Greason, STX, May 1990.
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	SCR_SCROLL
; PURPOSE:
;	Define the scrolling area on the screen.
; EXPLANATION:  
;	Please note that the line coordinates should be counted from 1.
; CALLING SEQUENCE:
;	scr_scroll [, top, bot]
; INPUTS:
;	top  --  The line to be the top of the scrolling area.
;	         The default value is 1 and the maximum value is 23.
;	bot  --  The line to be the bottom of the scrolling area.
;	         The default value is 24 and the minimum value is 2.
; OUTPUTS:
;	None.
; SIDE EFFECTS:
;	NOTE:  The screen coordinate system is NOT effected.  (1,1) is not
;	       the top of the scrolling area but the top of the screen.
; RESTRICTIONS:
;	This procedure will only work with DEC compatible equipment (or
;	terminal emulators).
; PROCEDURE:
;	A string containing the appropriate DEC terminal command is put 
;	together and printed.  NOTE:  In general, the DEC commands correspond
;	to the ANSI escape sequences.
; MODIFICATION HISTORY:
;	Written by Michael R. Greason, STX, May 1990.
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	SELECT_O
; PURPOSE:
;	Dumb-terminal routine to let a user interactively select from a list
; EXPLANATION: 
;	This is the non-widget version of SCREEN_SELECT
;
; CALLING SEQUENCE:
;	select_o, selections, iselected, comments, command_line, only_one, $
;                            [ COUNT = ]
;
; INPUTS:
;	selections - string array giving list of items that can be
;		selected.
;
; OPTIONAL INPUTS:
;	comments - comments which can be requested for each item in
;		array selections.  It can be:
;			string array - same length as array selections.
;			null string - no comments available
;			scalar string - name of a procedure which will
;				return comments.  It will take selections
;				as its first argument and return comments
;				as its second argument.
;	command_line - optional command line to be placed at the bottom
;		of the screen.  It is usually used to specify what the
;		user is selecting.
;	only_one - integer flag. If set to 1 then the user can only select
;		one item.  The routine returns immediately after the first
;		selection is made.
; OUTPUTS:
;	iselected - list of indices in selections giving the selected
;		items.
; OPTIONAL OUTPUT KEYWORD:
;       COUNT - Integer scalar giving the number of selections
; SIDE EFFECTS:
;	The obsolete system variable !err is set to the number of selections
; HISTORY:
;	version 1, D. Lindler  April 88.
;	modified to IDL V2 (from screen_select).  M. Greason, May 1990.
;	changed name from screen_select_o         W. Landsman January 1993
;	Converted to IDL V5.0   W. Landsman   September 1997
;       Added COUNT keyword, deprecate !ERR   W. Landsman   March 2000

; NAME:
;	SELECT_W    
; PURPOSE:
;	Create a non-exclusive widget menu of items
; EXPLANATION:
;	More than one item may be selected or 'de-selected'.   
;	Normally called by SCREEN_SELECT
;
; CALLING SEQUENCE:
;	SELECT_W, items ,iselected, [ comments, command_line, only_one ]
;
; INPUTS:
;	items - string array giving list of items that can be
;		selected.
;
; OPTIONAL INPUTS:
;	comments - comments which can be requested for each item in
;		array selections.    NOT YET IMPLEMENTED
;	command_line - optional command line to be placed at the bottom
;		of the screen.  It is usually used to specify what the
;		user is selecting.
;	only_one - integer flag. If set to 1 then the user can only select
;		one item.  The routine returns immediately after the first
;		selection is made.
; OPTIONAL KEYWORD INPUT
;       SELECTIN - vector of items to be pre-selected upon input (not used for
;               only_one option)
;
; OUTPUT:
;	iselected - list of indices in selections giving the selected
;		items.
;
; OPTIONAL OUTPUT KEYWORD:
;       COUNT  - Integer scalar giving the number of items selected
; COMMON BLOCKS:
;	SELECT_W - Used to communicate with the SELECT_W_EVENT procedure 
;
; MODIFICATION HISTORY:
;	Written, K. Venkatakrishna & W. Landsman, Hughes/STX    January, 1992
;	Widgets made MODAL.  M. Greason, Hughes STX, 15 July 1992.
;       Changed handling of MODAL keyword for V5.0   W.Thompson  September 1997
;	Converted to IDL V5.0   W. Landsman   September 1997
;       Added selectin keyword  D. Lindler 01/12/99 

; NAME:
;	SIGMA_FILTER
; PURPOSE:
;	Replace pixels more than a specified pixels deviant from its neighbors
; EXPLANATION:
;	Computes the mean and standard deviation of pixels in a box centered at 
;	each pixel of the image, but excluding the center pixel. If the center 
;	pixel value exceeds some # of standard deviations from the mean, it is 
;	replaced by the mean in box. Note option to process pixels on the edges.
; CALLING SEQUENCE:
;	Result = sigma_filter( image, box_width, N_sigma=(#), /ALL,/MON )
; INPUTS:
;	image = 2-D image (matrix)
;	box_width = width of square filter box, in # pixels (default = 3)
; KEYWORDS:
;	N_sigma = # standard deviations to define outliers, floating point,
;			recommend > 2, default = 3. For gaussian statistics:
;			N_sigma = 1 smooths 35% of pixels, 2 = 5%, 3 = 1%.
;	RADIUS = alternative to specify box radius, so box_width = 2*radius+1.
;      /ALL_PIXELS causes computation to include edges of image,
;      /KEEP causes opposite effect: pixels with values outside of specified
;		deviation are not changed, pixels within deviation are smoothed.
;      /ITERATE causes sigma_filter to be applied recursively (max = 20 times)
;		until no more pixels change (only allowed when N_sigma >= 2).
;      /MONITOR prints information about % pixels replaced.
; Optional Outputs:
;	N_CHANGE = # of pixels changed (replaced with neighborhood mean).
;	VARIANCE = image of pixel neighborhood variances * (N_sigma)^2,
;	DEVIATION = image of pixel deviations from neighborhood means, squared.
; CALLS:
;	function filter_image( )
; PROCEDURE:
;	Compute mean over moving box-cars using smooth, subtract center values,
;	compute variance using smooth on deviations from mean,
;	check where pixel deviation from mean is within variance of box,
;	replace those pixels in smoothed image (mean) with orignal values,
;	return the resulting partial mean image.
; MODIFICATION HISTORY:
;	Written, 1991, Frank Varosi and Dan Gezari NASA/GSFC
;	F.V.1992, added optional keywords /ITER,/MON,VAR=,DEV=,N_CHANGE=.
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME: 
;	SIGRANGE()
; PURPOSE: 
;	Selects the most significant data range in an image.
; EXPLANATION: 
;	Selects out the most significant range in the data to be used in 
;	displaying images.  The histogram of ARRAY is used to select the most
;	significant range.      Useful for scaling an image display.
; CALLING SEQUENCE: 
;	OUTPUT = SIGRANGE( ARRAY )
; INPUTS: 
;	ARRAY	 = Array to take most significant range of.
; OPTIONAL INPUTS: 
;	None.
; OUTPUTS: 
;	The function returns an array where values above and below the
;	selected range are set equal to the maximum and minimum of the
;	range respectively.
; OPTIONAL INPUT KEYWORDS: 
;	FRACTION = Fraction of data to consider most significant.
;		   Defaults to 0.99
;	MISSING	 = Value used to flag missing points.  Data points with this
;		   value are not considered or changed.
; OPTIONAL OUTPUT KEYWORD
;	RANGE    = 2 element vector, giving the range (minimum and maxmimum) 
;		used
;
; NOTES:
;       If the image array contains more than 10,000 points then SIGRANGE() 
;       uses random indexing of a subset of the points to determine the range
;       (for speed).    Thus identical calls to SIGRANGE() might not yield
;       identical results (although they should be very close).     
; RESTRICTIONS: 
;	ARRAY must have more than two points.  Fraction must be greater than 0 
;	and less than 1.
;
;	SIGRANGE was originally part of the SERTS image display package.   
;	Other routines from this package are available at 
;
;	http://sohowww.nascom.nasa.gov/solarsoft/gen/idl/image/
;
;	Note that this version of SIGRANGE does not include the non-standard 
;	system variables used in the SERTS package.
; REVISION HISTORY: 
;	Version 1, William Thompson, GSFC, 12 May 1993.
;		Incorporated into CDS library.
;	Version 2, William Thompson, GSFC, 25 May 1993.
;		Changed call to HISTOGRAM to be compatible with OpenVMS/ALPHA
;       Version 3, CDP, RAL, Add RANGE keyword.  16-Apr-96
;	Version 4, William Thompson, GSFC, 17 April 1996
;		Corrected some problems when range is too high.
;	Version 5, 13-Jan-1998, William Thompson, GSFC
;		Use random numbers to improve statistics when only using a
;		fraction of the array.
;	Version 6, 06-Mar-1998, William Thompson, GSFC
;		Change default to 0.99

; NAME:
;       SIXLIN
; PURPOSE:
;       Compute linear regression coefficients by six different methods.
; EXPLANATION:
;       Adapted from the FORTRAN program (Rev. 1.1)  supplied by Isobe, 
;       Feigelson, Akritas, and Babu Ap. J. Vol. 364, p. 104 (1990).   
;       Suggested when there is no understanding about the nature of the 
;       scatter about a linear relation, and NOT when the errors in the 
;       variable are calculable.
;
; CALLING SEQUENCE:
;       SIXLIN, xx, yy, a, siga, b, sigb   
;
; INPUTS:
;       XX - vector of X values
;       YY - vector of Y values, same number of elements as XX
;
; OUTPUTS:
;       A - Vector of 6 Y intercept coefficients
;       SIGA - Vector of standard deviations of 6 Y intercepts
;       B - Vector of 6 slope coefficients
;       SIGB - Vector of standard deviations of slope coefficients
;
;       The output variables are computed using linear regression for each of 
;       the following 6 cases:
;               (0) Ordinary Least Squares (OLS) Y vs. X
;               (1) Ordinary Least Squares  X vs. Y
;               (2) Ordinary Least Squares Bisector
;               (3) Orthogonal Reduced Major Axis
;               (4) Reduced Major-Axis 
;               (5) Mean ordinary Least Squares
;
; NOTES:
;       Isobe et al. make the following recommendations
;
;       (1) If the different linear regression methods yield similar results
;               then quoting OLS(Y|X) is probably the most familiar.
;
;       (2) If the linear relation is to be used to predict Y vs. X then
;               OLS(Y|X) should be used.   
;
;       (3) If the goal is to determine the functional relationship between
;               X and Y then the OLS bisector is recommended.
;
; REVISION HISTORY:
;       Written   Wayne Landsman          February, 1991         
;       Corrected sigma calculations      February, 1992
;       Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	SIXTY()
; PURPOSE:
;	Converts a decimal number to sexigesimal.
; EXPLANATION:
;	Reverse of the TEN() function.
;
; CALLING SEQUENCE:
;	X = SIXTY( SCALAR ) 
;
; INPUTS:
;	SCALAR -- Decimal quantity.  
; OUTPUTS:
;	Function value returned = floating real vector of three elements, 
;	sexigesimal equivalent of input decimal quantity.
;	A negative number is signified by making the first non-zero
;	element of the output vection negative.
;
; PROCEDURE:
;	Mostly involves checking arguments and setting the sign.
;
; EXAMPLE:
;	If x = -0.345d then sixty(x) = [0.0, -20.0, 24.0]
;
; MODIFICATION HISTORY:
;	Written by R. S. Hill, STX, 19-OCT-87         
;	Output changed to single precision.  RSH, STX, 1/26/88
;	Accept single element vector   W. Landsman   Sep. 1996
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	SIZE_STRUCT
; PURPOSE:
;	Obtain the size in bytes of an IDL structure definition.    
; EXPLANATION:
;	For most applications this function is superceded by use 
;	of the /LENGTH keyword to the intrinsic N_TAGS function 
;	introduced in IDL V2.3.0
;
; CALLING SEQUENCE:
;			bytes = size_struct( structure )
;	examples:
;			print, size_struct( "fdq_sdf" )
; INPUTS:
;		structure = a structure variable or
;				a string giving the structure name
;				as known by IDL (help,/struct,variable).
;		/PRINT = to print all sub structure sizes.
;
; inputs/outputs used recursively:
;		struct = the structure VARIABLE currently analyzed.
;		Max_Field_Size = size of the largest field found in structure.
; RESULT:
;		Function returns the total size in bytes of a structure element.
; PROCEDURE:
;		Strategy is to call size_struct recursively if
;		structure contains sub-structures.
;		Otherwise just add up the field sizes.
;
; MODIFICATION HISTORY:
;	written 1990 Frank Varosi STX @ NASA/GSFC (using align_struct).
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;       SKY
; PURPOSE:
;       Determine the sky level in an image using the the procedure MMM
; EXPLANATION:
;       Approximately 4000 uniformly spaced pixels are selected for the
;       computation.  Adapted from the DAOPHOT routine of the same name.
;
; CALLING SEQUENCE:
;       SKY, image, [ skymode, skysig, CIRCLE = ,/SILENT ]
;
; INPUTS:
;       IMAGE - One or two dimensional array
;
; OPTIONAL OUTPUT ARRAYS:
;       SKYMODE - Scalar, giving the mode of the sky pixel values of the 
;               array IMAGE, as determined by the procedure MMM.
;       SKYSIG -  Scalar, giving standard deviation of sky brightness
;
; INPUT KEYWORD PARAMETERS:
;       CIRCLERAD - Use the keyword to have SKY only select pixels within
;               the specified pixel radius of the center of the image.  If 
;               CIRCLERAD = 1, then the radius is set equal to half the image
;               width.   Useful when the data is restricted to a circular area
;               of the image.
;
;       /SILENT - If this keyword is supplied and non-zero, then SKY will not
;               display the sky value and sigma at the terminal
;
; PROCEDURE:
;       A regular grid of points, not exceeding 4000 in number, is extracted
;       from the image array.  The mode of these pixel values is determined
;       by the procedure MMM.
;
; PROCEDURE CALLS:
;       MMM
; REVISION HISTORY:
;       Written, W. Landsman   STX Co.            September, 1987     
;       Changed INDGEN to LINDGEN                 January, 1994
;       Fixed display of # of points used         March, 1994
;       Converted to IDL V5.0   W. Landsman   September 1997

; NAME:                    
;        SKYADJ_CUBE
;
; PURPOSE:
;       Sky adjust the planes of a datacube.
;
; EXPLANATION:
;       When removing cosmic rays from a set of images, it is desirable that
;       all images have the same sky level.    This procedure (called by
;       CR_REJECT) removes the sky from each image in a data cube.    
;
; CALLING SEQUENCE:
;       SKYADJ_CUBE,Datacube,Skyvals,Totsky
;
; MODIFIED ARGUMENT:
;       Datacube:  3-D array with one image of same field in each plane.
;                  Returned with sky in each plane adjusted to zero.
;
; OUTPUT ARGUMENTS:
;       Skyvals:   Array of sky values used on each plane of datacube.
;                  For a scalar sky, this parameter is a vector
;                  containing the sky value for each image plane.  For a
;                  vector sky, this parameter is a 2-D array where each
;                  line corresponds to one image plane.
;
; INPUT KEYWORD PARAMETERS:
;
;       REGION   - [X0,X1,Y0,Y1] to restrict area used for computation
;                  of sky.  Default is 0.1*Xdim, 0.9*Xdim, 0.1*Ydim,
;                  0.9*Ydim.  If INPUT_MASK is specified, the two 
;                  specs are combined, i.e., the intersection of the
;                  areas is used.
;       VERBOSE  - Flag.  If set, print information on skyvals.
;       NOEDIT   - Flag.  If set, return sky values without changing
;                  datacube.
;       XMEDSKY  - Flag.  If set, return vector sky as a function of X.
;       SELECT   - Array of subscripts of planes of the cube to process.
;                  (Default=all)
;       EXTRAPR  - Applies only in XMEDSKY mode.
;                  Subregion to use for polynomial extrapolation of sky
;                  vector into portions excluded by REGION parameter.
;                  (Default=first and last 10% of pixels; set to zero
;                  to defeat extrapolation)
;       EDEGREE  - Applies only in XMEDSKY mode.  
;                  Degree of polynomial for extrapolation (Default=1)
;       INPUT_MASK - Cube of flags corresponding to data cube.  If used,
;                  the sky computation is restricted to the smallest 
;                  contiguous rectangle containing all the pixels flagged
;                  valid (with 1 rather than 0).
;
; PROCEDURE:
;       Uses astronomy library "sky" routine for scalar sky and
;       column-by-column median for vector sky.
;
; MODIFICATION HISTORY:
;   10 Jul. 1997   - Written.  R. S. Hill, Hughes STX
;   20 Oct. 1997   - 1-D sky option.  RSH
;    7 Aug. 1998   - SELECT keyword.  RSH
;    6 Oct. 1998   - Extrapolation.  RSH
;    7 Oct. 1998   - INPUT_MASK added.  RSH
;   21 Oct. 1998   - Fallback to 3-sigma clipped mean if mode fails.  RSH
;   22 Mar. 2000   - Combine mask with region rather having mask
;                    override region.  Improve comments.  RSH
;   16 June 2000   - On_error and message used.  Square brackets for array 
;                    subscripts.  EXTRAP included in this file.  
;                    WBL & RSH, 16 June 2000

; NAME:
;     SPEC_DIR
; PURPOSE:
;     Complete a file specification by appending the default disk or directory
;
; CALLING SEQUENCE:                      
;     File_spec = SPEC_DIR( filename, [ extension ] )
; INPUT:
;     filename - character string giving partial specification of a file
;               name.  Examples for different operating systems include the
;                       following:
;               VMS: '$1$DUA5:TEST.DAT','[.SUB]TEST'
;               Unix: 'pro/test.dat', '$IDL_HOME/test','~/subpro'
;               MacOS: ':Programs:test'
;               Windows: '\pro\test.dat','d:\pro\test'
;
; OPTIONAL INPUT:
;     exten - string giving a default file name extension to be used if
;             filename does not contain one.  Do not include the period.
;
; OUTPUT:
;     File_spec - Complete file specification using default disk or 
;               directory when necessary.  
;
; EXAMPLE:
;      IDL> a = spec_dir('test','dat')
;
;      is equivalent to the commands
;      IDL> cd, current=cdir
;      IDL> a = cdir + delim + 'test.dat'
;
;      where delim is the OS-dependent separator 
; METHOD:
;      SPEC_DIR() decomposes the file name using FDECOMP, and appends the 
;      default directory (obtained from the CD command) if necessary.   
;      Under VMS, SPEC_DIR() will also try to translate disk and directory 
;      logical names.
;
;      SPEC_DIR() does not check whether the constructed file name actually
;      exists.
; PROCEDURES CALLED:
;      EXPAND_TILDE(), FDECOMP
; REVISION HISTORY:
;      Written W. Landsman         STX         July, 1987
;      Added Unix compatibility, W.  Landsman, STX   August 1991
;      Added Windows and Macintosh compatibility   W. Landsman  September, 1995
;      Work for relative Unix directory            W. Landsman  May, 1997
;      Expand Unix tilde if necessary              W. Landsman  September 1997
;      Converted to IDL V5.0   W. Landsman   September 1997
;      Fix VMS call to TRNLOG()  W. Landsman       September 2000

; NAME:
;       SPHDIST
; PURPOSE:
;       Angular distance between points on a sphere.
; CALLING SEQUENCE:
;       d = sphdist(long1, lat1, long2, lat2)
; INPUTS:
;       long1 = longitude of point 1, scalar or vector
;       lat1 = latitude of point 1, scalar or vector
;       long2 = longitude of point 2, scalar or vector
;       lat2 = latitude of point 2, scalar or vector
;
; OPTIONAL KEYWORD INPUT PARAMETERS:
;       /DEGREES - means angles are in degrees, else radians.
; OUTPUTS:
;       d = angular distance between points (in radians unless /DEGREES
;           is set.)
; PROCEDURES CALLED:
;       RECPOL, POLREC
; NOTES:
;       (1) The procedure GCIRC is similar to SPHDIST(), but may be more 
;           suitable for astronomical applications.
;
;       (2) If long1,lat1 are scalars, and long2,lat2 are vectors, then
;           SPHDIST returns a vector giving the distance of each element of 
;           long2,lat2 to long1,lat1.   Similarly, if long1,lat1 are vectors,
;           and long2, lat2 are scalars, then SPHDIST returns a vector giving
;           giving the distance of each element of long1,lat1 to to long2,lat2. 
;           If both long1,lat1 and long2,lat2 are vectors then SPHDIST returns
;           vector giving the distance of each element of long1,lat1 to the 
;           corresponding element of long2, lat2.   If the input vectors are 
;           not of equal length, then excess elements of the longer ones will 
;           be ignored.
; MODIFICATION HISTORY:
;       R. Sterner, 5 Feb, 1991
;       R. Sterner, 26 Feb, 1991 --- Renamed from sphere_dist.pro
;
; Copyright (C) 1991, 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.
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;       SPLINE_SMOOTH
;
; PURPOSE:
;       Compute a cubic smoothing spline to (weighted) data
; EXPLANATION:
;       Construct cubic smoothing spline (or give regression solution) to given
;       data with minimum "roughness" (measured by the energy in the second 
;       derivatives) while restricting the weighted mean square distance
;       of the approximation from the data.  The results may be written to
;       the screen or a file or both and are optionally returned in the 
;       parameters.  The results may be optionally displayed graphically.
;
; CALLING SEQUENCE:
;       SPLINE_SMOOTH,X,Y,Yerr,distance, [coefficients,smoothness,xplot,yplot 
;               [ XTITLE= ,YTITLE=, INTERP=, TEXTOUT=,/SILENT,/PLOT,/ERRBAR]
;
; INPUT PARAMETERS:
;       X - N_POINT element vector containing the data abcissae
;       Y - N_POINT element vector containing the data ordinates
;       Yerr -     estimated uncertainty in ordinates ( positive scalar)
;       distance - upper bound on the weighted mean square distance
;                  of the approximation from the data (non-negative scalar)
;
; OPTIONAL INPUT PARAMETERS
;      xplot -    vector of spline evaluation abcissae
;
; OPTIONAL INPUT KEYWORD PARAMETERS:
;       TEXTOUT - Controls print output device, defaults to !TEXTOUT
;       
;               textout=1       TERMINAL using /more option
;               textout=2       TERMINAL without /more option
;               textout=3       .prt
;               textout=4       laser.tmp
;               textout=5       user must open file
;               textout = filename (default extension of .prt)
;
; OPTIONAL OUTPUT PARAMETERS:
;       coefficients - N_POINT x 4 element array containing the sequence of
;                      spline coefficients including the smoothed ordinates.
;       smoothness  - N_POINT element vector containing the energy in second 
;                     derivatives of approximated function.
;       yplot       - vector of evaluated spline ordinates.
;
; OPTIONAL OUTPUT KEYWORD PARAMETERS
;       /SILENT     - suppress all printing.
;       /PLOT       - display smooth curve, data ordinates and error bars
;       /ERRBAR     - display error bars
;       XTITLE      - optional title for X-axis
;       YTITLE      - optional title for Y-axis
;       INTERP      - optionally returned interpolated smooth spline
; NOTES:
;       This procedure constructs a smoothing spline according to the method
;       described in "Fundamentals of Image Processing" by A. Jain  [Prentice-
;       Hall : New Jersey 1989].
;       If the distance parameter is sufficiently large a linear regression
;       is performed, otherwise a cubic smoothing spline is constructed.
;
;       This procedure assumes regular sampling and independent identically 
;       distributed normal errors without missing data.  The data are sorted.
;       
;       SPLINE_SMOOTH uses the non-standard system variables !TEXTOUT and
;       !TEXTUNIT.
;       These can be added to one's session using the procedure ASTROLIB.
;
; COMMON BLOCKS:
;       None.
; EXAMPLE:
;       Obtain coefficients of a univariate smoothing spline fitted to data
;       X,Y assuming normally distributed errors Yerr and write the results to
;       a file.
;
;       IDL> SPLINE_SMOOTH, X, Y, Yerr, distance, coefficients, smoothness,
;            t='spline.dat'
;
;       Fit a smoothing spline to observational data.  Suppress all printing 
;       and save the smoothed ordinates in output variables. Display results.
;
;       IDL> SPLINE_SMOOTH, X, Y, Yerr, distance, coefficients, /SILENT, /PLOT
;       
; PROCEDURES CALLED:
;       Procedures TEXTOPEN, TEXTCLOSE, PLOT, PLOTERROR
;
; RESTRCTIONS:
;       This procedure is damn slow and should probably be rewritten using
;       the Cholesky decomposition.
; AUTHOR:
;       Immanuel Freedman (after A. Jain).      December, 1993
; REVISIONS
;       January 12, 1994    I. Freedman (HSTX)  Adjusted formats
;       March   14, 1994    I. Freedman (HSTX)  Improved convergence
;       March   15, 1994    I. Freedman (HSTX)  User-specified interpolates
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Call PLOTERROR instead of PLOTERR  W. Landsman      February 1999

; NAME:
;       SRCOR
; PURPOSE:
;       Correlate the source positions found on two lists.
; CALLING SEQUENCE:
;       srcor,x1in,ylin,x2in,y2in,dcr,ind1,ind2
; INPUTS:
;       x1in,y1in - First set of x and y coordinates.  The program
;                   marches through this list element by element,
;                   looking in list 2 for the closest match.  So, the program
;                   will run faster if this is the shorter of the two lists.
;                   Unless you use the option or magnitude keyword, there is
;                   nothing to guarantee unique matches.  
;       x2in,y2in - Second set of x and y coordinates.  This list is
;                   searched in its entirety every time one element of list 1
;                   is processed.
;       dcr - Critical radius outside which correlations are rejected;
;             but see 'option' below.
; OPTIONAL KEYWORD INPUT:
;       option - Changes behavior of program and description of output
;                lists slightly, as follows: 
;       OPTION=0 or left out
;             Same as older versions of SRCOR.  The closest match from list2
;             is found for each element of list 1, but if the distance is
;             greater than DCR, the match is thrown out.  Thus the index
;             of that element within list 1 will not appear in the IND1 output
;             array.
;       OPTION=1
;             Forces the output mapping to be one-to-one.  OPTION=0 results,
;             in general, in a many-to-one mapping from list 1 to list 2.
;             Under OPTION=1, a further processing step is performed to
;             keep only the minimum-distance match, whenever an entry from
;             list 1 appears more than once in the initial mapping.
;       OPTION=2
;             Same as OPTION=1, except the critical distance parameter DCR
;             is ignored.  I.e., the closest object is retrieved from list 2
;             for each object in list 1 WITHOUT a critical-radius criterion,
;             then the clean-up of duplicates is done as under OPTION=1.
;       magnitude
;             An array of stellar magnitudes corresponding to x1in and y1in.  
;             If this is supplied, then the brightest star from list 1
;             within the selected distance of the star in list 2 is taken.
;             The option keyword is ignored in this case.
;       spherical
;             If SPHERICAL=1, it is assumed that the input arrays are in
;             celestial coordinates (RA and Dec), with x1in and x2in in
;             decimal hours and y1in and y2in in decimal degrees.  If
;             SPHERICAL=2 then it is assumed that the input arrays are in
;             longitude and latitude with x1in,x2in,y1in,y2in in decimal
;             degrees.  In both cases, the critial radius dcr is in
;             *arcseconds*.  Calculations of spherical distances are made
;             with the gcirc program.
; OUTPUTS:
;       ind1 - index of matched stars in first list
;       ind2 - index of matched stars in second list
; COMMON BLOCKS:
;       none
; SIDE EFFECTS:
;       none
; METHOD:
;       See under keyword LEVEL above.
; REVISON HISTORY:
;       Adapted from UIT procedure  J.Wm.Parker, SwRI 29 July 1997
;       Converted to IDL V5.0   W. Landsman   September 1997
;       

; NAME:
;       STARAST 
; PURPOSE:
;       Compute astrometric solution using positions of 2 or 3 reference stars
; EXPLANATION:
;       Computes an exact astrometric solution using the positions and 
;       coordinates from 2 or 3 reference stars and assuming a tangent 
;       (gnomonic) projection.   If 2 stars are used, then
;       the X and Y plate scales are assumed to be identical, and the
;       axis are assumed to be orthogonal.   Use of three stars will
;       allow a unique determination of each element of the CD matrix.
;
; CALLING SEQUENCE:
;       starast, ra, dec, x, y, cd, [/Righthanded, HDR = h, PROJECTION=]
;
; INPUTS:
;       RA - 2 or 3 element vector containing the Right Ascension in DEGREES
;       DEC- 2 or 3 element vector containing the Declination in DEGREES
;       X -  2 or 3 element vector giving the X position of reference stars
;       Y -  2 or 3 element vector giving the Y position of reference stars
; OUTPUTS:
;       CD - CD (Coordinate Description) matrix (DEGREES/PIXEL) determined 
;               from stellar positions and coordinates.
; OPTIONAL INPUT KEYWORD:
;       /RightHanded - If only 2 stars are supplied, then there is an ambiguity
;               in the orientation of the coordinate system.   By default,
;               STARAST assumes the astronomical standard left-handed system
;               (R.A. increase to the left).   If /Right is set then a 
;               righthanded coordinate is assumed.  This keyword has no effect
;               if 3 star positions are supplied.
;        PROJECTION - Either a 3 letter scalar string giving the projection
;               type (e.g. 'TAN' or 'SIN') or an integer 1 - 25 specifying the
;               projection as given in the WCSSPH2XY procedure.   If not 
;               specified then a tangent projection is computed.
; OPTIONAL INPUT-OUTPUT KEYWORD:
;        HDR - If a FITS header string array is supplied, then an astrometry 
;              solution is added to the header using the CD matrix and star 0
;              as the reference pixel (see example).   Equinox 2000 is assumed.
; EXAMPLE:
;        To use STARAST to add astrometry to a FITS header H;
;
;        IDL> starast,ra,dec,x,y,cd       ;Determine CD matrix
;        IDL> crval = [ra[0],dec[0]]      ;Use Star 0 as reference star
;        IDL> crpix = [x[0],y[0]] +1      ;FITS is offset 1 pixel from IDL
;        IDL> putast,H,cd,crpix,crval     ;Add parameters to header
;
;        This is equivalent to the following command:
;        IDL> STARAST,ra,dec,x,y,hdr=h      
;  
; METHOD:
;       The CD parameters are determined by solving the linear set of equations
;       relating position to local coordinates (l,m)
;
;       For highest accuracy the first star position should be the one closest
;       to the reference pixel.
; REVISION HISTORY:
;       Written, W. Landsman             January 1988
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Added /RightHanded and HDR keywords   W. Landsman   September 2000
;       Write CTYPE values into header   W. Landsman/A. Surkov  December 2002
;       CD matrix was mistakenly transpose in 3 star solution
;       Added projection keyword    W. Landsman   September 2003 

; NAME:
;	STORE_ARRAY
; PURPOSE:
;	Insert array INSERT into the array DESTINATION
; EXPLANATION:
;	The dimensions of the DESTINATION array are adjusted to accomodate
;	the inserted array.
; CATEGOBY:
;	Utility
; CALLING SEQUENCE:
;	STORE_ARRAY, DESTINATION, INSERT, INDEX
; INPUT:
;	DESTINATION	= Array to be expanded.
;	INSERT		= Array to insert into DESTINATION.
;	INDEX		= Index of the final dimension of DESTINATION to insert
;			  INSERT into.
; OUTPUTS:
;	DESTINATION	= Expanded output array.  If both input arrays have the
;			  same number of dimensions, then the DESTINATION will
;			  be replaced with INSERT.
; RESTRICTIONS:
;	DESTINATION and INSERT have to be either both of type string or both of
;	numerical types.
;
;	INSERT must not have more dimensions than DESTINATION.
;
; MODIFICATION HISTOBY:
;	William Thompson, Feb. 1992, from BOOST_ARRAY by D. Zarro and P. Hick.
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	STRD
; PURPOSE:
;	Open an STSDAS file and read into an image array and header. 
; EXPLANATION:
;	Combines the functions of SXREAD and SXOPEN. 
;
; CALLING SEQUENCE:
;	STRD, im, hdr, [ filename, GROUP = , PAR = ]
;
; OPTIONAL INPUT:
;	FILENAME -  Character string giving the name of the SDAS file
;		to be read.  If omitted, then program will prompt 
;		for the file name.  If an extension is given, then
;		it must terminate in a 'h'.
;		A default extension of '.hhh' is assumed, if one is
;		not supplied.  Under VMS, the version numbers are ignored, 
;		and the most recent version is always used.
;
; OUTPUTS:
;	IM - array containing image data
;	HDR - string array containing header
;
; OPTIONAL INPUT KEYWORD PARAMETER:
;	GROUP - scalar integer specifying group number to read.  Default is 0.
;
; OPTIONAL OUTPUT KEYWORD PARAMETER:
;	PAR - Parameter block (byte array) read from group formatted data
; COMMON BLOCKS:
;	STCOMMN - Created by SXOPEN.  STRD uses STCOMMN to check
;		for an open unit, and to get image dimensions.          
;
; SIDE EFFECTS:
;	STSDAS image array and header are read into IM and HDR
;	IF FILENAME is not supplied, then the program will check that
;	the image and header variable do not already contain data.
;
; SYSTEM VARIABLES:
;	Set !QUIET = 1 to suppress informational messages.
;
; METHOD:
;	Program checks that specified STSDAS file exists before calling 
;	SXOPEN and SXREAD to read in data.
;
; PROCEDURES CALLED:
;	FDECOMP, PICKFILE(), SPEC_DIR(), SXOPEN, SXREAD()
; MODIFICATION HISTORY:
;	Written W. Landsman, STI Corporation August 1986
;	Optional parameter "FILENAME" added November 1986
;	Correctly print header size when more than 2 dimensions February 1996
;	Add GROUP, PAR keywords, call PICKFILE   W. Landsman   March 1996
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	STRN
; PURPOSE:
;	Convert a number to a string and remove padded blanks.
; EXPLANATION:
;	The main and original purpose of this procedure is to convert a number
;	to an unpadded string (i.e. with no blanks around it.)  However, it 
;	has been expanded to be a multi-purpose formatting tool.  You may 
;	specify a length for the output string; the returned string is either 
;	set to that length or padded to be that length.  You may specify 
;	characters to be used in padding and which side to be padded.  Finally,
;	you may also specify a format for the number.  NOTE that the input 
;	"number" need not be a number; it may be a string, or anything.  It is
;	converted to string.
;
; CALLING SEQEUNCE:
;	tmp = STRN( number, [ LENGTH=, PADTYPE=, PADCHAR=, FORMAT = ] )
;
; INPUT:
;	NUMBER    This is the input variable to be operated on.  Traditionally,
;		 it was a number, but it may be any scalar type.
;
; OPTIONAL INPUT:
;	LENGTH    This KEYWORD specifies the length of the returned string.  
;		If the output would have been longer, it is truncated.  If 
;		the output would have been shorter, it is padded to the right 
;		length.
;	PADTYPE   This KEYWORD specifies the type of padding to be used, if any.
;		0=Padded at End, 1=Padded at front, 2=Centered (pad front/end)
;		IF not specified, PADTYPE=1
;	PADCHAR   This KEYWORD specifies the character to be used when padding.
;		The default is a space (' ').
;	FORMAT    This keyword allows the FORTRAN type formatting of the input
;		number (e.g. '(f6.2)')
;
; OUTPUT:
;	tmp       The formatted string
;
; USEFUL EXAMPLES:
;	print,'Used ',strn(stars),' stars.'  ==> 'Used 22 stars.'
;	print,'Attempted ',strn(ret,leng=6,padt=1,padch='0'),' retries.'
;		==> 'Attempted 000043 retries.'
;	print,strn('M81 Star List',length=80,padtype=2)
;		==> an 80 character line with 'M81 Star List' centered.
;	print,'Error: ',strn(err,format='(f15.2)')
;		==> 'Error: 3.24'     or ==> 'Error: 323535.22'
;
; HISTORY:
;	03-JUL-90 Version 1 written by Eric W. Deutsch
;	10-JUL-90 Trimming and padding options added         (E. Deutsch)
;	29-JUL-91 Changed to keywords and header spiffed up     (E. Deutsch)
;	Ma7 92 Work correctly for byte values (W. Landsman)
;	19-NOV-92 Added Patch to work around IDL 2.4.0 bug which caused an
;	error when STRN('(123)') was encountered.            (E. Deutsch)
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;      STRNUMBER
; PURPOSE:
;      Function to determine if a string is a valid numeric value.
;
; CALLING SEQUENCE:
;      result = strnumber( st, [val, /HEX] )
;
; INPUTS:
;      st - any IDL scalar string
;
; OUTPUTS:
;      1 is returned as the function value if the string st has a
;      valid numeric value, otherwise, 0 is returned.
;
; OPTIONAL OUTPUT:
;      val - (optional) value of the string.  real*8
;
; OPTIONAL INPUT KEYWORD:
;       /HEX - If present and nonzero, the string is treated as a hexadecimal
;             longword integer.
;
; EXAMPLES:
;      IDL> res = strnumber(' ',val)
;           returns res=0 (not a number) and val is undefined
;
;      IDL> res = strnumber('0.2d', val)
;           returns res=1 (a valid number), and val = 0.2000d
;              
; NOTES:
;      (1) STRNUMBER was modified in February 1993 to include a special test for 
;      empty or null strings, which now returns a 0 (not a number).    Without
;      this special test, it was found that a empty string (' ') could corrupt
;      the stack.
;
;       (2) STRNUMBER will return a string such as '23.45uyrg' as a valid 
;      number (=23.45) since this is how IDL performs the type conversion.  If
;      you want a stricter definition of valid number then use the VALID_NUM
;      function.
; HISTORY:
;      version 1  By D. Lindler Aug. 1987
;      test for empty string, W. Landsman          February, 1993
;      Converted to IDL V5.0   W. Landsman   September 1997
;      Hex keyword added.  MRG, RITSS, 15 March 2000.

; NAME:
;       STR_INDEX()
;
; PURPOSE:
;       Get indices of a substring (SUBSTR) in string.
;
; EXPLANATION:
;       The IDL intrinsic function STRPOS returns only the index of the first
;       occurrence of a substring. This routine calls itself recursively to get
;       indices of the remaining occurrences.
;
; CALLING SEQUENCE:
;       result= STR_INDEX(str, substr [, offset])
;
; INPUTS:
;       STR    -- The string in which the substring is searched for
;       SUBSTR -- The substring to be searched for within STR
;
; OPTIONAL INPUTS:
;       OFFSET -- The character position at which the search is begun. If
;                 omitted or being negative, the search begins at the first
;                 character (character position 0).
;
; OUTPUTS:
;       RESULT -- Integer scalar or vector containing the indices of SUBSTR
;                 within STR. If no substring is found, it is -1.
;
; CALLS:
;       DELVARX
;
; COMMON BLOCKS:
;       STR_INDEX -- internal common block. The variable save in the block is
;                    deleted upon final exit of this routine.
;
; CATEGORY:
;       Utility, string
;
; MODIFICATION HISTORY:
;       Written January 3, 1995, Liyun Wang, GSFC/ARC
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Use size(/TNAME) instead of DATATYPE()   W. Landsman   October 2001
;       

; NAME:
;	STSUB
; PURPOSE:
;	Subroutine of STSUBIM to read a subset of a SDAS image file.   
; EXPLANATION:
;	User can specify a subimage range or a step size    Called by STSUBIM
;
; CALLING SEQUENCE:
;	Result =  stsub( unit, x1, x2, y1, y2, step)
;
; INPUTS:
;	UNIT      =  Unit number of file, must be from 1 to 9.
;		     Unit must have been opened with SXOPEN.
;       x1        =  lower x value
;       x2        =  upper x value
;       y1        =  lower y value
;       y2        =  upper y value
;	step      =  used to extract every nth pixel.  If step = 1, a full res.
; 	             subimage is extracted; step = 2, every other pixel is
;	             extracted, etc.  Defaults to 1.  The minimum value is 1.
; OUTPUTS:
;	Result of function = array constructed from designated record.
;
; COMMON BLOCKS:
;	Uses idl common stcommn to access parameters (see SXOPEN)
;
; MODIFICATION HISTORY:
;	Written, M. Greason, STX, July 1990.
;	Remove initialization of array for increased efficiency  January, 1991
;	Removed call to STSUBC.EXE, do it all in IDL
;                                      - K. Venkatakrishna, STX, April 1992
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	STSUBIM
; PURPOSE:
;	Open an STSDAS file and read a portion of the file into an array.  
; EXPLANATION:
;	An enhanced version of STRD.  Program will prompt for the file name
;	and subimage bounds.
;
; CALLING SEQUENCE:
;	STSUBIM, im, hdr, [ filename, x1, x2, y1, y2, step, /SILENT ]
;
; OPTIONAL INPUTS:
;	FILENAME -  Character string giving the name of the SDAS file
;		to be read.  If omitted, then program will prompt 
;		for the file name.  If an extension is given, then
;		it must terminate in a 'h'.  A default extension of '.hhh' 
;		is assumed, if one is not supplied.  In VMS, version numbers 
;		are ignored, and the most recent version is always used.
;	X1      -  Starting x value (def=0), integer scalar
;	X2      -  Ending x value (def=total record size), integer scalar
;	Y1      -  Starting y value (def = 0), integer scalar
;	Y2      -  Ending y value (def = total no. of records), integer scalar
;     STEP    -  The number of pixels between extracted pixels.  This allows
;                the user to read every Nth pixel from the image.  STEP=1
;                indicates full resolution, STEP=2 indicates every other pixel,
;                etc.
; OUTPUTS:
;	IM - array containing image data
;	HDR - string array containing STSDAS header
;
; OPTIONAL KEYWORD INPUT:
;	SILENT  -  If this keyword is present, the size of the image 
;		will not be printed.
;
; COMMON BLOCKS:
;	STCOMMN - Created by SXOPEN.  STSUBIM uses STCOMMN to check
;	for an open unit, and to get image dimensions.          
;
; SIDE EFFECTS:
;	STSDAS image array and header are read into IM and HD
;	IF FILENAME is not supplied, then the program will check that
;	the image and header variable do not already contain data.
;
; RESTRICTIONS:
;	For use only on data without Groups!!  
;	For use only on 2 dimensional data files.
;
; PROCEDURE:
;	Program checks that STSDAS file exists and that IDL variables do
;	not already contain data, before calling SXOPEN and STSUB to
;	read in data.  The header keywords NAXIS* and CRPIX*
;	are updated to account for the actual image size.
;
; PROCEDURES CALLED:
;       FDECOMP, ORDINAL(), SPEC_DIR(), STSUB, SXOPEN, SXADDPAR, SXADDHIST
;
; MODIFICATION HISTORY:
;	Written B. Pfarr, STX, September 1987 from STRD
;	Modifed to IDL Version 2, M. Greason, STX, May 1990.
;	Prints 1st, 2nd, etc., instead of 1th, 2th... R. S.Hill, STX, Aug 1991
;	CRPIX transformation corrected.  RSH, HSTX, 27-May-1992.
;	Use new astrometry structure   W. Landsman   Feb 1994
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	STWRT
; PURPOSE:
;	Write a STSDAS header and/or 2-D array to disk (without groups!) 
;
; CALLING SEQUENCE:
;	STWRT, hdr                     ;Write image header (.hhh file) only
;	STWRT, im                      ;Create header to match image array
;	STWRT, im, hdr,[ name, /SDAS, /NOUPDATE ]  
;
; INPUT PARAMETERS:
;	im - image array to be written to disk.  If no header array is
;		supplied, then a simple header appropiate to the image will be
;		constructed.
;
; OPTIONAL INPUT PARAMETER:
;	hdr - STSDAS header, string array.  
;	name - character string containing the name of output file
;		to which the image is written.  If omitted, then 
;		the program will prompt for the file name.  A file
;		name will have the default extension of '.HHH'
;
; OPTIONAL KEYWORD INPUTS:
;	NOUPDATE-- By default, STWRT will modify the input FITS header to create
;		a proper SDAS .hhh file.   This includes  ensuring that (1) a 
;               DATATYPE keyword exists, and (2) that BITPIX is a positive
;		value.   
;	SDAS-- The SDAS keyword can be specified to modify the input header to 
;		ensure SDAS compatibility.
;
; RESTRICTIONS:
;	(1) STWRT is only for 2 dimensional images.  For other arrays use
;
;	SXOPEN,1,NAME,HD,HISTORY,'W'   ;HISTORY need not be defined
;	SXWRITE,1,IM
;	CLOSE,1
;
;	(2) The type of data written is determined by the DATATYPE 
;		keyword in the header.  A DATATYPE keyword appropiate to
;		the image array type will be added if does not already exist
;
; SIDE EFFECTS:
;	A STSDAS header and/or image array is written to disk.    Unit 2 is
;	opened and closed.
;
; REVISION HISTORY:
;	Written W. Landsman, STI Corp. August, 1986
;	Returned old version to not modify header.  W. Landsman July 1991.
;	Included call to CHKDType--option to change DATATYPE and BITPIX if they; 
;	do not match.				J.D.Offenberg Dec 1991.
;	Added call to CHECK_FITS, NOUPDATE keyword, remove autochange keyword
;                                        W. Landsman May 1992
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME: 
;       ST_DISKREAD
;
; PURPOSE:  
;       Read HST FITS formatted disk files and reconstruct GEIS (STSDAS) files.
;
; CALLING SEQUENCE:  
;       ST_DISKREAD, infiles
;
; INPUT PARAMETER:
;       infiles - (scalar string) input disk files to be converted into GEIS
;                       files. Wildcards are allowed.
; FILES CREATED:
;
;   GEIS files:
;         The GEIS file is reconstructed from each input Fits file. The 
;       output filename is composed from the rootname of the observation
;       and the appropriate GEIS file extension (i.e. d0h/d, c0h/d, etc.).
;   Tables:
;         If input file is a fits table, the output is an SDAS table.
;
; EXAMPLES:
;       a) Reconstruct the GEIS file for disk FITS file z29i020ct*.fits.
;               st_diskread,'z29i020ct*.fits'
;
; PROCEDURES CALLED:
;       ST_DISK_DATA, ST_DISK_TABLE, ST_DISK_GEIS
;       FTSIZE,SXPAR(),TAB_CREATE, TAB_WRITE
; HISTORY: 
;       10/17/94        JKF/ACC - taken from ST_TAPEREAD.
;       11/02/94        JKF/ACC - added /block on open statement to
;                                 handle files with 512 bytes/record.
;       12/6/95         JKF/ACC - include new jitter files...replaces
;                                               st_read_jitter.pro.
;       03/5/96         W. Landsman, change FORRD to READU, remove Version 1
;                               type codes, add message facility
;       05/20/00        W. Landsman, remove obsolete !ERR calls, new calling
;                               sequence to FTINFO
;
;****************************************************************************
;       Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	SUBSTAR
; PURPOSE:
;	Subtract a scaled point spread function at specified star position(s).
; EXPLANATION:
;	Part of the IDL-DAOPHOT photometry sequence
;
; CALLING SEQUENCE:
;	SUBSTAR, image, x, y, mag, [ id, psfname, /VERBOSE] 
;
; INPUT-OUTPUT:
;	IMAGE -  On input, IMAGE is the original image array.  A scaled
;		PSF will be subtracted from IMAGE at specified star positions.
;		Make a copy of IMAGE before calling SUBSTAR, if you want to
;		keep a copy of the unsubtracted image array
;
; INPUTS:
;	X -   REAL Vector of X positions found by NSTAR (or FIND)
;	Y -   REAL Vector of Y positions found by NSTAR (or FIND)        
;	MAG - REAL Vector of stellar magnitudes found by NSTAR (or APER)
;		Used to scale the PSF to match intensity at star position.
;		Stars with magnitude values of 0.0 are assumed missing and 
;		ignored in the subtraction.
;
; OPTIONAL INPUTS:
;	ID -  Index vector indicating which stars are to be subtracted.  If
;		omitted, (or set equal to -1), then stars will be subtracted 
;		at all positions specified by the X and Y vectors.
;
;	PSFNAME - Name of the FITS file containing the PSF residuals, as
;		generated by GETPSF.  SUBSTAR will prompt for this parameter
;		if not supplied.      
;
; OPTIONAL INPUT KEYWORD:
;	VERBOSE - If this keyword is set and nonzero, then SUBSTAR will 
;		display the star that it is currently processing      
;
; COMMON BLOCKS:
;	The RINTER common block is used (see RINTER.PRO) to save time in the
;	PSF calculations
;
; PROCEDURES CALLED:
;	DAO_VALUE(), READFITS(), REMOVE, SXOPEN, SXPAR(), SXREAD()
; REVISION HISTORY:
;	Written, W. Landsman                      August, 1988
;	Added VERBOSE keyword                     January, 1992
;	Fix star subtraction near edges, W. Landsman    May, 1996
;	Assume the PSF file is in FITS format  W. Landsman   July, 1997
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;       SUNPOS
; PURPOSE:
;       To compute the RA and Dec of the Sun at a given date.
;
; CALLING SEQUENCE:
;       SUNPOS, jd, ra, dec, [elong, obliquity, /RADIAN ]
; INPUTS:
;       jd    - The Julian date of the day (and time), scalar or vector
;               usually double precision
; OUTPUTS:
;       ra    - The right ascension of the sun at that date in DEGREES
;               double precision, same number of elements as jd
;       dec   - The declination of the sun at that date in DEGREES
;
; OPTIONAL OUTPUTS:
;       elong - Ecliptic longitude of the sun at that date in DEGREES.
;       obliquity - the obliquity of the ecliptic, in DEGREES
;
; OPTIONAL INPUT KEYWORD:
;       /RADIAN - If this keyword is set and non-zero, then all output variables 
;               are given in Radians rather than Degrees
;
; NOTES:
;       The accuracy in the 20th century  should be within 1"; however this 
;       has not been extensively tested.
;
;       The returned RA and Dec are in the given date's equinox.
;
;       Procedure was extensively revised in May 1996, and the new calling
;       sequence is incompatible with the old one.
; METHOD:
;       Uses a truncated version of Newcomb's Sun.    Adapted from the IDL
;       routine SUN_POS by CD Pike, which was adapted from a FORTRAN routine
;       by B. Emerson (RGO).
; EXAMPLE:
;       (1) Find the apparent RA and Dec of the Sun on May 1, 1982
;       
;       IDL> jdcnv, 1982, 5, 1,0 ,jd      ;Find Julian date jd = 2445090.5   
;       IDL> sunpos, jd, ra, dec
;       IDL> print,adstring(ra,dec,2)
;                02 31 32.61  +14 54 34.9
;
;       The Astronomical Almanac gives 02 31 32.58 +14 54 34.9 so the error
;               in SUNPOS for this case is < 0.5".      
;
;       (2) Find the apparent RA and Dec of the Sun for every day in 1997
;
;       IDL> jdcnv, 1997,1,1,0, jd                ;Julian date on Jan 1, 1997
;       IDL> sunpos, jd+ dindgen(365), ra, dec    ;RA and Dec for each day 
;
; MODIFICATION HISTORY:
;       Written by Michael R. Greason, STX, 28 October 1988.
;       Accept vector arguments, W. Landsman     April,1989
;       Eliminated negative right ascensions.  MRG, Hughes STX, 6 May 1992.
;       Rewritten using the 1993 Almanac.  Keywords added.  MRG, HSTX, 
;               10 February 1994.
;       Major rewrite, improved accuracy, always return values in degrees
;       W. Landsman  May, 1996 
;       Added /RADIAN keyword,    W. Landsman       August, 1997
;       Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	SUNSYMBOL
; PURPOSE:
;	Return the Sun symbol as a subscripted postscript character string
; EXPLANATION:
;	Returns the Sun symbol (circle with a dot in the middle) as a 
;	(subscripted) postscript character string.    Needed because although 
;	the Sun symbol	is available using the vector fonts as the string 
;	'!9n', it is not in the standard postscript set.   
;
; CALLING SEQUENCE:
;	result = SUNSYMBOL()
;
; INPUTS:
;	None
;
; OUTPUTS:
;	result - a scalar string representing the Sun symbol.   A different
;		string is output depending (1) the device is postscript and
;		hardware fonts are used (!P.FONT=0), (2) vector fonts are used,
;		or (3) hardware fonts are used on a non-postscript device.
;		For case (3), SUNSYMBOL simply outputs the 3 character string
;		'Sun'
;
; EXAMPLE:
;	To make the X-axis of a plot read  M/M_Sun
;	IDL>  plot,indgen(10),xtit = 'M / M' + sunsymbol()
;
; RESTRICTIONS:
;	(1) The postscript output does not have the dot perfectly centered in 
;		the circle
;	(2) SUNSYMBOL() includes subscript output positioning commands in the 
;		output string.
;       (3) True type fonts (!p.font = 1) are not supported
; REVISION HISTORY:
;	Written,  W. Landsman,    HSTX          April, 1997
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	SXADDHIST                           
; PURPOSE:
;	Procedure to add HISTORY (or COMMENT) line(s) to a FITS header
;
; EXPLANATION:
;       The advantage of using SXADDHIST instead of SXADDPAR is that with 
;       SXADDHIST many HISTORY or COMMENT records can be added in a single call.
;
; CALLING SEQUENCE
;	sxaddhist, history, header, [ /PDU, /COMMENT ]
;
; INPUTS:
;	history - string or string array containing history or comment line(s)
;		to add to the FITS header
; INPUT/OUTPUT
;	header - FITS header (string array).   Upon output, it will contain the
;               specified HISTORY records added to the end
;
; OPTIONAL KEYWORD INPUTS:
;       /BLANK - If specified then blank ('       ') keywords will be written
;              rather than 'HISTORY ' keywords.
;       /COMMENT - If specified, then 'COMMENT ' keyword will be written rather
;              than 'HISTORY ' keywords.    
;              Note that according to the FITS definition, any number of 
;              'COMMENT' and 'HISTORY' or blank keywords may appear in a header,
;              whereas all other keywords may appear only once.   
;	/PDU - if specified, the history will be added to the primary
;		data unit header, (before the line beginning BEGIN EXTENSION...)               
;		Otherwise, it will be added to the end of the header.
;               This has meaning only for extension headers using the STScI
;               inheritance convention. 
; OUTPUTS:
;	header - updated FITS header
;
; EXAMPLES:
;	sxaddhist, 'I DID THIS', header      ;Add one history record
;
;	hist = strarr(3)
;	hist[0] = 'history line number 1'
;	hist[1[ = 'the next history line'
;	hist[2] = 'the last history line'
;	sxaddhist, hist, header              ;Add three history records
;
; SIDE EFFECTS:
;       Header array is truncated to the final END statement
; HISTORY:
;	D. Lindler  Feb. 87
;	April 90  Converted to new idl  D. Lindler
;	Put only a single space after HISTORY   W. Landsman  November 1992
;	Aug. 95	  Added PDU keyword parameters
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;       SXADDPAR
; PURPOSE:
;       Add or modify a parameter in a FITS header array.
;
; CALLING SEQUENCE:
;       SXADDPAR, Header, Name, Value, [ Comment,  Location, /SaveComment, 
;                               BEFORE =, AFTER = , FORMAT= , /PDU]
;
; INPUTS:
;       Header = String array containing FITS or STSDAS header.    The
;               length of each element must be 80 characters.    If not 
;               defined, then SXADDPAR will create an empty FITS header array.
;
;       Name = Name of parameter. If Name is already in the header the value 
;               and possibly comment fields are modified.  Otherwise a new 
;               record is added to the header.  If name is equal to 'COMMENT'
;               or 'HISTORY' or a blank string then the value will be added to 
;               the record without replacement.  For these cases, the comment 
;               parameter is ignored.
;
;       Value = Value for parameter.  The value expression must be of the 
;               correct type, e.g. integer, floating or string.  String values
;                of 'T' or 'F' are considered logical values.
;
; OPTIONAL INPUT PARAMETERS:
;       Comment = String field.  The '/' is added by this routine.  Added 
;               starting in position 31.    If not supplied, or set equal to 
;               '', or /SAVECOMMENT is set, then the previous comment field is 
;               retained (when found) 
;
;       Location = Keyword string name.  The parameter will be placed before the
;               location of this keyword.    This parameter is identical to
;               the BEFORE keyword and is kept only for consistency with
;               earlier versions of SXADDPAR.
;
; OPTIONAL INPUT KEYWORD PARAMETERS:
;       BEFORE  = Keyword string name.  The parameter will be placed before the
;               location of this keyword.  For example, if BEFORE='HISTORY'
;               then the parameter will be placed before the first history
;               location.  This applies only when adding a new keyword;
;               keywords already in the header are kept in the same position.
;
;       AFTER   = Same as BEFORE, but the parameter will be placed after the
;               location of this keyword.  This keyword takes precedence over
;               BEFORE.
;
;       FORMAT  = Specifies FORTRAN-like format for parameter, e.g. "F7.3".  A
;               scalar string should be used.  For complex numbers the format
;               should be defined so that it can be applied separately to the
;               real and imaginary parts.  If not supplied then the default is
;               'G19.12' for double precision, and 'G14.7' for floating point.
;
;       /PDU    = specifies keyword is to be added to the primary data unit
;               header. If it already exists, it's current value is updated in
;               the current position and it is not moved.
;       /SAVECOMMENT = if set, then any existing comment is retained, i.e. the
;               COMMENT parameter only has effect if the keyword did not 
;               previously exist in the header.
; OUTPUTS:
;       Header = updated FITS header array.
;
; EXAMPLE:
;       Add a keyword 'TELESCOP' with the value 'KPNO-4m' and comment 'Name
;       of Telescope' to an existing FITS header h.
;
;       IDL> sxaddpar, h, 'TELESCOPE','KPNO-4m','Name of Telescope'
; NOTES:
;       The functions SXADDPAR() and FXADDPAR() are nearly identical, with the
;       major difference being that FXADDPAR forces required FITS keywords
;       BITPIX, NAXISi, EXTEND, PCOUNT, GCOUNT to appear in the required order
;       in the header, and FXADDPAR supports the OGIP LongString convention.   
;       There is no particular reason for having two nearly identical 
;       procedures, but both are too widely used to drop either one.
;
;       All HISTORY records are inserted in order at the end of the header.
;
;       All COMMENT records are also inserted in order at the end of the header
;       header, but before the HISTORY records.  The BEFORE and AFTER keywords
;       can override this.
;
;       All records with no keyword (blank) are inserted in order at the end of
;       the header, but before the COMMENT and HISTORY records.  The BEFORE and
;       AFTER keywords can override this.

; RESTRICTIONS:
;       Warning -- Parameters and names are not checked
;               against valid FITS parameter names, values and types.
;
; MODIFICATION HISTORY:
;       DMS, RSI, July, 1983.
;       D. Lindler Oct. 86  Added longer string value capability
;       Converted to NEWIDL  D. Lindler April 90
;       Added Format keyword, J. Isensee, July, 1990
;       Added keywords BEFORE and AFTER. K. Venkatakrishna, May '92
;       Pad string values to at least 8 characters   W. Landsman  April 94
;       Aug 95: added /PDU option and changed routine to update last occurence
;               of an existing keyword (the one SXPAR reads) instead of the
;               first occurence.
;       Comment for string data can start after column 32 W. Landsman June 97
;       Make sure closing quote supplied with string value  W. Landsman  June 98
;       Converted to IDL V5.0    W. Landsman   June 98
;       Increase precision of default formatting of double precision floating
;               point values.   C. Gehman, JPL  September 1998
;       Mar 2000, D. Lindler, Modified to use capital E instead of lower case
;               e for exponential formats.
;       Apr 2000, Make user-supplied format upper-case  W. Landsman 
;       Oct 2001, Treat COMMENT or blank string like HISTORY keyword W. Landsman
;       Jan 2002, Allow BEFORE, AFTER to apply to COMMENT keywords W. Landsman
;       June 2003, Added SAVECOMMENT keyword    W. Landsman
;       

; NAME:
;	SXDELPAR
; PURPOSE:
;	Procedure to delete a keyword parameter(s) from a FITS header
;
; CALLING SEQUENCE:
;	sxdelpar, h, parname
;
; INPUTS:
;	h - FITS or STSDAS header, string array
;	parname - string or string array of keyword name(s) to delete
;
; OUTPUTS:
;	h - updated FITS header, If all lines are deleted from 
;		the header, then h is returned with a value of 0
;
; EXAMPLE:
;	Delete the astrometry keywords CDn_n from a FITS header, h
;
;	IDL> sxdelpar, h, ['CD1_1','CD1_2','CD2_1','CD2_2']
;
; NOTES:
;	(1)  No message is returned if the keyword to be deleted is not found
;	(2)  All appearances of a keyword in the header will be deleted
; HISTORY:
;	version 1  D. Lindler Feb. 1987
;	Converted to new IDL  April 1990 by D. Lindler
;	Test for case where all keywords are deleted    W. Landsman Aug 1995 
;	Converted to IDL V5.0   W. Landsman   September 1997
;       Allow for headers with more than 32767 lines W. Landsman Jan. 2003

; NAME:
;	SXGINFO
;
; PURPOSE:
;	Return information on all group parameters in an STSDAS header.
; EXPLANATION:
;	Return datatype, starting byte, and number bytes for all group
;	parameters in an STSDAS file.     Obtaining these values 
;	greatly speed up execution time in subsequent calls to SXGPAR.
;
; CALLING SEQUENCE:
;	sxginfo, h, par, type, sbyte, nbytes
;
; INPUTS:
;	h - header returned by SXOPEN
;	par - parameter block returned by SXREAD or multiple
;		parameter blocks stored in array of dimension
;		greater than one.
;
; OUTPUT:
;	type - data type (if not supplied or null string, the
;		header is searched for type,sbyte, and nbytes)
;	sbyte - starting byte in parameter block for data
;	nbytes - number of bytes in parameter block for data
;
;	The number of elements in type,sbyte and nbytes equals the total
;	number of group parameters.
;
; METHOD:
;	The parameter type for each parameter is obtained
;	from PDTYPEn keyword.  If not found then DATATYPE keyword
;	value is used.  If that is not found then BITPIX is
;	used.  BITPIX=8, byte; BITPIX=16 integer*2; BITPIX=32
;	integer*4.
;
; NOTES:
;	For an example of the use of SXGINFO, see CONV_STSDAS
;
; HISTORY:
;	version 1  W. Landsman   Apr. 93
;
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	SXGPAR                           
;
; PURPOSE:
;	Obtain group parameter value in SDAS/FITS file
;
; CALLING SEQUENCE:
;	result = sxgpar( h, par, name, [ type, sbyte, nbytes] )
;
; INPUTS:
;	h - header returned by SXOPEN
;	par - parameter block returned by SXREAD or multiple
;		parameter blocks stored in array of dimension
;		greater than one.
;	name - parameter name (keyword PTYPEn) or integer
;		parameter number.
;
; OPTIONAL INPUT/OUTPUT
;	type - data type (if not supplied or null string, the
;		header is searched for type,sbyte, and nbytes)
;	sbyte - starting byte in parameter block for data
;	nbytes - number of bytes in parameter block for data
;
; OUTPUT:
;	parameter value or value(s) returned as function value
;
; SIDE EFFECTS:
;	If an error occured then !err is set to -1
;
; OPERATIONAL NOTES:
;	Supplying type, sbyte and nbytes greatly decreases execution
;	time.  The best way to get the types is on the first call
;	pass undefined variables for the three parameters or set
;	type = ''.  The routine will then return their values for
;	use in subsequent calls.
;	
; METHOD:
;	The parameter type for parameter n is obtained
;	from PDTYPEn keyword.  If not found then DATATYPE keyword
;	value is used.  If that is not found then BITPIX is
;	used.  BITPIX=8, byte; BITPIX=16 integer*2; BITPIX=32
;	integer*4.
;
; HISTORY:
;	version 1  D. Lindler  Oct. 86
;	version 2  D. Lindler Jan. 90  added ability to process
;		multiple parameter blocks in single call
;	version 3  D. Lindler  (converted to New vaxidl)
;       Apr 14 1991      JKF/ACC - fixed make_array datatypes(float/double)
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	SXGREAD
; PURPOSE:
;	Read group parameters from a Space Telescope STSDAS image file     
;
; CALLING SEQUENCE:
;	grouppar = sxgread( unit, group )
;
; INPUTS:
;	UNIT   = Supply same unit as used in SXOPEN.
;	GROUP  =  group number to read.  if omitted, read first group.
;		The first group is number 0.
;
; OUTPUTS:
;	GROUPPAR  =  parameter values from fits group parameter block.
;		It is a byte array which may contain multiple data types.
;		The function SXGPAR can be used to retrieve values from it.
;
; COMMON BLOCKS:
;	Uses IDL Common STCOMMN to access parameters.
; SIDE EFFECTS:
;	IO is performed. 
; MODIFICATION HISTORY:
;	WRITTEN, Don Lindler, July, 1 1987
;	MODIFIED, Don Neill, Jan 11, 1991 - derived from sxread.pro
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	SXHCOPY                            
; PURPOSE:
;	Copies selected portions of one header to another
;
; CALLING SEQUENCE:
;	sxhcopy, h, keyword1, keyword2, hout
;
; INPUTS:
;	h - input header
;	keyword1 - first keyword to copy
;	keyword2 - last keyword to copy
;
; INPUT/OUTPUT:
;	hout - header to copy the information to.
;
; METHOD:
;	the headers lines from keyword1 to keyword2 are copied to
;	the end of the output header.  No check is made to verify
;	that a keyword value already exists in the output header.
;
; HISTORY:
;	version 1  D. Lindler    Sept. 1989
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	SXHEDIT                             
; PURPOSE:
;	Routine to interactively edit an STSDAS header on disk.
; EXPLANATION:
;	VMS: uses EDT.
;	Unix: uses whatever your EDITOR environment variable is set to.
;
; CALLING SEQUENCE:
;	sxhedit, name, [ h ]
;
; INPUTS:
;	name - header file name (default extension is .hhh)
;
; OUTPUTS:
;	h - (optional) edited header
;
; SIDE EFFECTS:
;	A new version of the file will be created.
;
; HISTORY:
;	Version 1  D. Lindler July  1987
;	Version 2  JAH Dec '88:  Converted to Sun IDL.
;	Modified   D. Neill Sept, 1990: Now deletes all versions of sxhedit.tmp
;			made compatable with Unix
;	Modified   D. Neill Apr, 1991: Ensures 80 char headers and will not
;		create new version if no changes made.
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;       SXHMAKE
; PURPOSE:
;       Create a basic STSDAS header file from an IDL data array
;
; CALLING SEQUENCE:
;       sxhmake, Data, Groups, Header
;
; INPUTS:
;       Data = IDL data array of the same type, dimensions and
;               size as are to be written to file.
;       Groups = # of groups to be written.
;
; OUTPUTS:
;       Header = String array containing ST header file.
;
; PROCEDURE:
;       Call sxhmake to create a header file.  Then call sxopen to
;       open output image, followed by sxwrite to write the data.
;       If you do not plan to change the header created by sxhmake
;       before calling sxopen, you might consider using sxmake which
;       does both steps.
;
; MODIFICATION HISTORY:
;       Don Lindler  Feb 1990 modified from SXMAKE by DMS, July, 1983.
;       D. Lindler April 90  Converted to new VMS IDL
;       M. Greason May 1990  Header creation bugs eliminated.
;       W. Landsman Aug 1997 Use SYSTIME() instead of !STIME for V5.0 
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Recognize unsigned datatype    January 2000   W. Landsman 

; NAME:
;	SXHREAD                         
; PURPOSE:
;	Procedure to read a STSDAS header from disk.  
; EXPLANATION:
;	This version of SXHREAD can read three types of disk files
;	(1)  VMS Fixed record length 80 byte files, or GEIS files with
;		VMS buckets
;	(2)  Unix stream files with a CR after every 80 bytes
;	(3)  Variable length record files (Unix or VMS)
;
; CALLING SEQUENCE:
;	sxhread, name, header
;
; INPUT:
;	name - file name, scalar string.  An extension of .hhh is appended 
;		if not already supplied.   (Note STSDAS headers are required
;		to have a 3 letter extension ending in 'h'.)
; OUTPUT:
;	header - STSDAS header, string array
; NOTES:
;	SXHREAD  does not do any checking to see if the file is a valid
;	STSDAS header.    It simply reads the file into a string array with
;	80 byte elements
;
; HISTORY:
;	Version 1  D. Lindler  July, 1987
;	Version 2  M. Greason, August 1990
;	Use READU for certain ST VAX GEIS files   W. Landsman January, 1992
;	Read variable length Unix files  E. Deutsch/W. Landsman November, 1994
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	SXHWRITE
; PURPOSE:
;	Procedure to write an STSDAS or FITS header to disk as a *.hhh file.
;
; CALLING SEQUENCE:
;	SXHWRITE,name,h
;
; INPUTS:
;	name - file name. If an extension is supplied it must be 3 characters
;		ending in "h".
;	h - FITS header, string array
;
; SIDE EFFECTS:
;	File with specified name is written.  If qualifier not specified
;	then .hhh is used
;   
;	SXHWRITE will modify the header in the following ways, if necessary
;	(1)  If not already present, an END statement is added as the 
;		last line.   Lines after an existing END statment are
;		deleted.
;	(2)  Spaces are appended to force each line to be 80 characters.
;	(3)  On Unix machines, a carriage return is appended at the end
;		of each line.   This is consistent with STSDAS and allows
;		the file to be directly displayed on a stream device
;
; PROCEDURES USED:
;	zparcheck, fdecomp
; HISTORY:
;	version 1  D. Lindler  June 1987
;	conversion cleaned up.  M. Greason, June 1990
;	Add carriage return at the end of Unix files   W. Landsman Oct 1991
;	Use SYSTIME() instead of !STIME for V5.0 compatibility Aug 1997
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;       SXMAKE
; PURPOSE:
;       Create a basic ST header file from an IDL array prior to writing data.
;
; CALLING SEQUENCE:
;       sxmake, Unit, File, Data, Par, Groups, Header, [ PSIZE = ]
;
; INPUTS:
;       Unit = Logical unit number from 1 to 9.
;       File = file name of data and header files to create.   If no file name
;              extension is supplied then the default is to use .hhh for the
;              header file extension and .hhd for the data file extension    
;              If an extension is supplied, it should be of the form .xxh
;              where xx are any alphanumeric characters.
;       Data = IDL data array of the same type, dimensions and
;               size as are to be written to file.
;       Par = # of elements in each parameter block for each data record.  If 
;             set equal to 0, then parameter blocks will not be written.  The 
;             data type of the parameter blocks must be the same as the data 
;             array.   To get around this restriction, use the PSIZE keyword.
;       Groups = # of groups to write.  If 0 then write in basic
;               format without groups.  
;
; OPTIONAL INPUT PARAMETERS:
;       Header = String array containing ST header file.  If this
;               parameter is omitted, a basic header is constructed.
;               If included, the basic parameters are added to the
;               header using sxaddpar.  The END keyword must terminate
;               the parameters in Header.
;
; OPTIONAL KEYWORD INPUT PARAMETER:
;        PSIZE - Integer scalar giving the number of bits in the parameter 
;               block.    If the PSIZE keyword is given, then the Par input
;               parameter is ignored.
;                
; OPTIONAL OUTPUT PARAMETERS:
;       Header = ST header array, an 80 by N character array.
;
; COMMON BLOCKS:
;       Stcommn - as used in sxwrite, sxopen, etc.
;
; SIDE EFFECTS:
;       The header file is created and written and then the
;       data file is opened on the designated unit.
;
; RESTRICTIONS:
;       Header files must be named .xxh and data files must be
;       named .xxd, where xx are any alphanumeric characters.
;
; PROCEDURE:
;       Call sxmake to create a header file.  Then call sxwrite
;       to output each group.
; 
; PROCEDURES USED:
;       GET_DATE, SXADDPAR, SXOPEN
; MODIFICATION HISTORY:
;       DMS, July, 1983.
;       converted to new VMS IDL  April 90
;       Use SYSTIME() instead of !STIME   W. Landsman   Aug 1997
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Added optional PSIZE keyword   August 1999 W. Landsman 
;       Recognize unsigned datatype    January 2000   W. Landsman 

; NAME:
;       SXOPEN
; PURPOSE:
;       Open a Space Telescope formatted (STSDAS) header file.
; EXPLANATION:
;       Saves the parameters required subsequent SX routines in
;       the common block Stcommn.  Optionally save the header in 
;       the string array Header, and the history in the string array
;       History.  Open the data file associated with this
;       header on the same unit.
;
; CALLING SEQUENCE:
;       SXOPEN, Unit, Fname [, Header [,History] [,Access]]
;
; INPUTS:
;       Unit = IDL unit used for IO.  Must be from 1 to 9.
;       Fname = File name of header file.  Default extension
;               is .hhh for header files and .hhd for data
;               files.    If an extension is supplied it must have the 
;               form .xxh where xx are any alphanumeric characters. The
;               data file must have extension .xxd
;               No version number is allowed.  Most recent versions
;               of the files are used.
;
; OPTIONAL INPUT PARAMETER:
;       Access = 'R' to open for read, 'W' to open for write.
;
; OUTPUTS:
;       Stcommn = Common block containing ST parameter blocks.
;               (Long arrays.)
;
; OPTIONAL OUTPUT PARAMETERS:
;       Header = 80 char by N string array containing the
;               names, values and comments from the FITS header.
;               Use the function SXPAR to obtain individual
;               parameter values.
;       History = String array containing the value of the
;               history parameter.
;
; COMMON BLOCKS:
;       STCOMMN - Contains RESULT(20,10) where RESULT(i,LUN) =
;       0 - 121147 for consistency check, 1 - Unit for consistency,
;       2 - bitpix, 3 - naxis, 4 - groups (0 or 1), 5 - pcount,
;       6 - gcount, 7 - psize, 8 - data type as idl type code,
;       9 - bytes / record, 10 to 10+N-1 - dimension N,
;       17 = record length of file in bytes.
;       18 - # of groups written, 19 = gcount.
;
; SIDE EFFECTS:
;       The data and header files are accessed.
;
; RESTRICTIONS:
;       Works only for disc files.  The data file must have
;       must have the extension ".xxd" and the header file must
;       have the extension ".xxh" where x is any alphanumeric character
;
; PROCEDURE:
;       The header file is opened and each line is read.
;       Important parameters are stored in the output
;       parameter.  If the last two parameters are specified
;       the parameter names and values are stored.  The common
;       block STCOMMN is filled with the type of data, dimensions,
;       etc. for use by SXREAD.
;
;       If access is for write, each element of the header
;       array, which must be supplied, is written to the
;       header file.  The common block is filled with
;       relevant parameters for SXWRITE.  A keyword of "END"
;       ends the header.
;
; MODIFICATION HISTORY:
;       Written, DMS, May, 1983.
;       D. Lindler Feb. 1990
;               Modified to allow var. record length header files.
;       D. Lindler April 1990   Conversion to new VMS IDL
;       Added /BLOCK when opening new .hhd file
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Recognize unsigned datatype for V5.1 or greater   W. Landsman Jan 2000

; NAME:
;      SXPAR
; PURPOSE:
;      Obtain the value of a parameter in a FITS header
;
; CALLING SEQUENCE:
;      result = SXPAR( Hdr, Name, [ Abort, COUNT=, COMMENT =, /NoCONTINUE  ])   
;
; INPUTS:
;      Hdr =  FITS header array, (e.g. as returned by READFITS) 
;             string array, each element should have a length of 80 characters      
;
;      Name = String name of the parameter to return.   If Name is of the
;             form 'keyword*' then an array is returned containing values of
;             keywordN where N is an integer.  The value of keywordN will be
;             placed in RESULT(N-1).  The data type of RESULT will be the
;             type of the first valid match of keywordN found.
;
; OPTIONAL INPUTS:
;       ABORT - string specifying that SXPAR should do a RETALL
;               if a parameter is not found.  ABORT should contain
;               a string to be printed if the keyword parameter is not found.
;               If not supplied, SXPAR will return quietly with COUNT = 0
;               (and !ERR = -1) if a keyword is not found.
;
; OPTIONAL INPUT KEYWORDS: 
;       /NOCONTINUE = If set, then continuation lines will not be read, even
;                 if present in the header
;       /SILENT - Set this keyword to suppress warning messages about duplicate
;                 keywords in the FITS header.
;
; OPTIONAL OUTPUT KEYWORDS:
;       COUNT - Optional keyword to return a value equal to the number of 
;               parameters found by SXPAR, integer scalar
;
;       COMMENT - Array of comments associated with the returned values
;
; OUTPUTS:
;       Function value = value of parameter in header.
;               If parameter is double precision, floating, long or string,
;               the result is of that type.  Apostrophes are stripped
;               from strings.  If the parameter is logical, 1b is
;               returned for T, and 0b is returned for F.
;               If Name was of form 'keyword*' then a vector of values
;               are returned.
;
; SIDE EFFECTS:
;       !ERR is set to -1 if parameter not found, 0 for a scalar
;       value returned.  If a vector is returned it is set to the
;       number of keyword matches found.    The use of !ERR is deprecated, and
;       instead the COUNT keyword is preferred
;
;       If a keyword (except HISTORY or COMMENT) occurs more than once in a 
;       header, a warning is given, and the *last* occurence is used.
;
; EXAMPLES:
;       Given a FITS header, h, return the values of all the NAXISi values
;       into a vector.    Then place the history records into a string vector.
;
;       IDL> naxisi = sxpar( h ,'NAXIS*')         ; Extract NAXISi value
;       IDL> history = sxpar( h, 'HISTORY' )      ; Extract HISTORY records
;
; PROCEDURE:
;       The first 8 chacters of each element of Hdr are searched for a 
;       match to Name.  The value from the last 20 characters is returned.  
;       An error occurs if there is no parameter with the given name.
;
;       If a numeric value has no decimal point it is returned as type
;       LONG.   If it contains more than 8 numerals, or contains the 
;       characters 'D' or 'E', then it is returned as type DOUBLE.  Otherwise
;       it is returned as type FLOAT.    Very large integer values, outside
;       the range of valid LONG, are returned as DOUBLE.
;
;       If the value is too long for one line, it may be continued on to the
;       the next input card, using the OGIP CONTINUE convention.  For more info,
;       http://heasarc.gsfc.nasa.gov/docs/heasarc/ofwg/docs/ofwg_recomm/r13.html
;
;       Complex numbers are recognized as two numbers separated by one or more
;       space characters.
;
;       If a numeric value has no decimal point (or E or D) it is returned as
;       type LONG.  If it contains more than 8 numerals, or contains the
;       character 'D', then it is returned as type DOUBLE.  Otherwise it is
;       returned as type FLOAT.    If an integer is too large to be stored as
;       type LONG, then it is returned as DOUBLE.
;
; NOTES:
;       The functions SXPAR() and FXPAR() are nearly identical, although
;       FXPAR() has slightly more sophisticated parsing.   There is no
;       particular reason for having two nearly identical procedures, but
;       both are too widely used to drop either one.
;
; PROCEDURES CALLED:
;       GETTOK(), VALID_NUM()
; MODIFICATION HISTORY:
;       DMS, May, 1983, STPAR Written.
;       D. Lindler Jan 90 added ABORT input parameter
;       J. Isensee Jul,90 added COUNT keyword
;       W. Thompson, Feb. 1992, added support for FITS complex values.
;       W. Thompson, May 1992, corrected problem with HISTORY/COMMENT/blank
;               keywords, and complex value error correction.
;       W. Landsman, November 1994, fix case where NAME is an empty string 
;       W. Landsman, March 1995,  Added COMMENT keyword, ability to read
;               values longer than 20 character
;       W. Landsman, July 1995, Removed /NOZERO from MAKE_ARRAY call
;       T. Beck May 1998, Return logical as type BYTE
;       W. Landsman May 1998, Make sure integer values are within range of LONG
;       Converted to IDL V5.0, May 1998
;       W. Landsman Feb 1998, Recognize CONTINUE convention 
;       W. Landsman Oct 1999, Recognize numbers such as 1E-10 as floating point
;       W. Landsman Jan 2000, Only accept integer N values when name = keywordN
;       W. Landsman Dec 2001, Optional /SILENT keyword to suppress warnings
;       W. Landsman/D. Finkbeiner  Mar 2002  Make sure extracted vectors 
;             of mixed data type are returned with the highest type.

; NAME:
;	SXREAD
; PURPOSE:
;	Read a Space Telescope STSDAS image file     
;
; CALLING SEQUENCE:
;	result = sxread( Unit, group , [par] )
;
; INPUTS:
;	UNIT  =  Unit number of file, must be from 1 to 9.
;		Unit must have been opened with SXOPEN.
;	GROUP  =  group number to read.  if omitted, read first record.
;		The first record is number 0.
; OUTPUTS:
;	Result of function  =  array constructed from designated record.
;
; OPTIONAL OUTPUT:
;	PAR  =  Variable name into which parameter values from STSDAS
;		group parameter block are read.  It is a byte array
;		which may contain multiple data types.  The function
;		SXGPAR can be used to retrieve values from it.
;
; COMMON BLOCKS:
;	Uses IDL Common STCOMMN to access parameters.
;
; NOTES:
;	Use the function SXGREAD to read the group parameter blocks without
;	having to read the group array.
;
;	If the STSDAS file does not contain groups, then the optional output
;	parameter PAR is returned undefined, but no error message is given.
;
; SIDE EFFECTS:
;	IO is performed. 
; MODIFICATION HISTORY:
;	WRITTEN, Don Lindler, July, 1 1987
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	SXWRITE
; PURPOSE:
;	Write a group of data and parameters in ST format
;	to a STSDAS data file.
;
; CALLING SEQUENCE:
;	SXWRITE, Unit, Data,[ Par]
;
; INPUTS:
;	Unit = unit number of file.  The file must have been
;		previously opened by SXOPEN.
;	Data = Array of data to be written.  The dimensions
;		must agree with those supplied to SXOPEN and written
;		into the FITS header.  The type is converted if
;		necessary.
;
; OPTIONAL INPUT PARAMETERS:
;	Par = parameter block.  The size of this array must
;		agree with the Psize parameter in the FITS header.
;
; OUTPUTS:
;	None.
; COMMON BLOCKS:
;	STCOMMN - Contains RESULT(20,10) where RESULT(i,LUN) =
;	0 - 121147 for consistency check, 1 - Unit for consistency,
;	2 - bitpix, 3 - naxis, 4 - groups (0 or 1), 5 - pcount,
;	6 - gcount, 7 - psize, 8 - data type as idl type code,
;	9 - bytes / record, 10 to 10+N-1 - dimension N,
;	18 - # of groups written, 19 = gcount.
;
; SIDE EFFECTS:
;	The data are written into the next group.
;
; RESTRICTIONS:
;	SXOPEN must have been called to initialize the
;	header and the common block.
;
; MODIFICATION HISTORY:
;	DMS, July, 1983.
;	D.Lindler July, 1986 - changed block size of file to 512
;			moved group parameters after the groups data.
;	D.Lindler July, 1987 - modified to allow any size parameter block
;			(in bytes).
;	D. Lindler  April, 1990 - converted to new VMS IDL
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;       TABINV     
; PURPOSE:  
;       To find the effective index of a function value in an ordered vector.
;       
; EXPLANTION:
;       This version calls VALUE_LOCATE() internally, either as an intrinsic
;       IDL Function (V5.3 or later) or from the procedure
;       http://idlastro.gsfc.nasa.gov/ftp/pro/math/value_locate.pro
; CALLING SEQUENCE:
;       TABINV, XARR, X, IEFF, [/FAST]
; INPUTS:
;       XARR - the vector array to be searched, must be monotonic
;               increasing or decreasing
;       X    - the function value(s) whose effective
;               index is sought (scalar or vector)
;
; OUTPUT:
;       IEFF - the effective index or indices of X in XARR
;               real or double precision, same # of elements as X
;
; OPTIONAL KEYWORD INPUT:
;       /FAST - If this keyword is set, then the input vector is not checked
;               for monotonicity, in order to improve the program speed.
; RESTRICTIONS:
;       TABINV will abort if XARR is not monotonic.  (Equality of 
;       neighboring values in XARR is allowed but results may not be
;       unique.)  This requirement may mean that input vectors with padded
;       zeroes could cause routine to abort.
;
; PROCEDURE:
;       A binary search is used to find the values XARR[I]
;       and XARR[I+1] where XARR[I] < X < XARR[I+1].
;       IEFF is then computed using linear interpolation 
;       between I and I+1.
;               IEFF = I + (X-XARR[I]) / (XARR[I+1]-XARR[I])
;       Let N = number of elements in XARR
;               if x < XARR[0] then IEFF is set to 0
;               if x > XARR[N-1] then IEFF is set to N-1
;
; EXAMPLE:
;       Set all flux values of a spectrum (WAVE vs FLUX) to zero
;       for wavelengths less than 1150 Angstroms.
;         
;       IDL> tabinv, wave, 1150.0, I
;       IDL> flux[ 0:fix(I) ] = 0.                         
;
; FUNCTIONS CALLED:
;       None
; REVISION HISTORY:
;       Adapted from the IUE RDAF                     January, 1988         
;       More elegant code  W. Landsman                August, 1989
;       Mod to work on 2 element decreasing vector    August, 1992
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Updated for V5.3 to use VALUE_LOCATE()     W. Landsman January 2000
;       Work when both X and Xarr are integers     W. Landsman August 2001

; NAME:
;	TABLE_APPEND
; PURPOSE:
;	Routine to append STSDAS tables to create a single table. 
;	Input tables must all have identical columns.
;
; CALLING SEQUENCE:
;	table_append,list,name
;
; INPUTS:
;	list - string array listing the file names or a string
;		scalar giving a file name template.
;	name - output file name.
; SIDE EFFECTS:
;	a new STSDAS table is created with the specified name.
;
; OPERATIONAL NOTES:
;	all input tables must have the same number of columns
;	with the same names, datatypes, and column order.
;	Header parameters are taken only from the first table.
;
; HISTORY:
;	version 1  D. Lindler	April 1989
;       Removed call to non-standard system variable !DUMP WBL  September 1997
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	TABLE_CALC 
; PURPOSE:
;	Adds a new table column from a expression using existing columns
;
; CALLING SEQUENCE:
;	table_calc, table, expression, table_out
;
; INPUTS:
;	table - input SDAS table table
;	expression - expression for new or updated column values.
;		Any legal IDL expression is valid where existing
;		column names can be used as variables.  User functions
;		within the expression are allowed if the function
;		is in an IDL library or previously compiled.
;
; OPTIONAL INPUT:
;	table_out - output table name.  If not supplied, the
;		input name is used.
;
; OUTPUTS:
;	a new SDAS table file is created.
;
; EXAMPLES:
;
;	 create a column WAVELENGTH in table TAB which is the average
;	of the WLOW and WHIGH columns of table TAB.
;
;		table_calc,'tab','WAVELENGTH=(WLOW+WHIGH)/2.0'
;
;	add a column SINX which is the sin of column X to table JUNK.
;
;		table_calc,'junk','SINX=sin(X)'
;
;	add 10.0 to an existing column in table MYTAB.
;
;		table_calc,'mytab','flux=flux+10.0'
;
; HISTORY
;	version 1  D. Lindler November, 1989
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	TABLE_CONV
;
; PURPOSE:
;	Convert STSDAS table(s) to the host format
;
; EXPLANATION:
;	If on a BIG_ENDIAN machine (e.g. SparcStation), assumes table came
;		from a little endian machine unless /FROM_VMS keyword is set
;	If on a LITTLE_ENDIAN machine (e.g. OSF, Windows), assumes table came
;		from a big endian machine unless /FROM_VMS keyword is set
;	If on a VMS machine, assumes table came from a big endian machine
;		unless the /FROM_LITTLE keyword is set
;
; CALLING SEQUENCE:
;	TABLE_CONV, filespec, [ /FROM_VMS, /FROM_LITTLE ]
;
; INPUT PARAMETERS:
;	filespec - file specification for table(s), scalar string.
;		Can include wildcard values, e.g. '*.tab'
;
; EXAMPLE:
;	(1) An STSDAS table "calspec.tab" has been FTP'ed from a Sparcstation 
;	to a VMS machine.   Convert the table to the host VMS format.
;	(The FTP mode should be set to binary when copying STSDAS tables)
;
;	IDL> table_conv, 'calspec.tab'
;
;	(2) A set of files '*.tab' have been FTP'ed from VMS machine to a 
;	Sparcstation.   Convert all the files to the host format
;
;	IDL> table_conv, '*.tab', /FROM_VMS
;
; NOTES:
;	TABLE_CONV does not check whether byte-swapping is actually needed.
;	If this procedure is applied to a file that is already in the host
;	format, then that file will be corrupted.
;
; PROCEDURES CALLED:
;	CONV_VAX_UNIX(), CONV_UNIX_VAX, FDECOMP, IS_IEEE_BIG(), SWAP_ENDIAN(), 
;	TABLE_HCONV, TAB_PUT, TAB_READ, TAB_SIZE, TAB_WRITE
; MODIFICATION HISTORY:
;	W. Landsman,  Hughes STX/Goddad              July 1996 
;	Adapted from GHRS version by Don Lindler, Keith Feggans 
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	TABLE_DELETE 
; PURPOSE:
;	Delete specified rows from an STSDAS table
;
; CALLING SEQUENCE:
;	table_delete, name, rows, [ outname ]
;
; INPUT:
;	name - table name
;	rows - row (scalar) or rows(vector) to delete from the table
;
; OPTIONAL OUTPUT:
;	outname - output table name, if not supplied the input name
;		is used
;
; HISTORY:
;	version 1  D. Lindler  April 1989
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	TABLE_EXT
; PURPOSE:
;	Routine to extract columns from an STSDAS table
;
; CALLING SEQUENCE:
;	TABLE_EXT, name, columns, v1, [v2,v3,v4,v5,v6,v7,v8,v9]
; INPUTS:
;	name - table name, scalar string
;	columns - table columns to extract.  Can be either 
;		(1) String with names separated by commas
;		(2) Scalar or vector of column numbers
;
; OUTPUTS:
;	v1,...,v9 - values for the columns
;
; EXAMPLES:
;	Read wavelength and throughput vectors from STSDAS table, wfpc_f725.tab
;
;	IDL> table_ext,'wfpc_f725.tab','wavelength,throughput',w,t
;		or
;	IDL> table_ext,'wfpc_f725.tab',[1,2],w,t
;	
; PROCEDURES CALLED:
;	GETTOK(), TAB_READ, TAB_VAL()
; HISTORY:
;	version 1  D. Lindler  May 1989
;	Accept Column Numbers as well as names, W. Landsman  February 1996
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	TABLE_HELP
; PURPOSE:
;	Procedure to decribe an SDAS table file.
;
; CALLING SEQUENCE:
;	table_help, tcb, header
;	table_help, name
;
; INPUTS:
;	tcb - table control block returned by TAB_READ or TAB_CREATE
;	name -	the table name
;
; OPTIONAL INPUTS:
;	header - header array returned by TAB_READ.  If supplied
;		it will be printed, otherwise it won't.
;
; SIDE EFFECTS:
;	text output as specified by !textout
;
; HISTORY:
;	version 1  D. Lindler  JAN 1988
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	TABLE_LIST  
; PURPOSE:
;	List the contents of an STSDAS table.
; EXPLANATION:
;	Procedure to list contents of an STSDAS table.  This does not
;	print the table in tabular form but instead for each row
;	prints the column name followed by its value (one column per
;	output line.
;
; CALLING SEQUENCE:
;	table_list, name, row1, row2, [ TEXTOUT=, /HEADER ]
;
; INPUTS:
;	name - table name
;
; OPTIONAL KEYWORD INPUT:
;	TEXTOUT  - Scalar string giving output file name, or integer (1-5)
;		specifying output device.   See TEXTOPEN for more info.
;		Default is to display output at the terminal
;	HEADER - if set, the header is printed before the selected row printout
;
; OPTIONAL INPUTS:
;	row1 - first row to list (default = first row)
;	row2 - last row to list (default = last row)
;
; OUTPUT:
;	text output is written to the output device specified by the TEXTOUT
;	keyword, or the nonstandard system variable !TEXTOUT
;
; PROCEDURES USED:
;	TAB_COL, TAB_READ, TAB_SIZE, TAB_VAL(), TEXTOPEN, TEXTCLOSE
;
; HISTORY:
;	version 1  D. Lindler   May 1989
;	July 1996, DJL, added /header keyword to optionally print header
;	August 1996, WBL, added TEXTOUT keyword
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	TABLE_PRINT
; PURPOSE:
;	Routine to print an stsdas table.
;
; CALLING SEQUENCE:
;	table_print, name, columns, row1, row2
;
; INPUTS:
;	name - table name
; 
; OPTIONAL INPUTS:
;	columns - vector of column numbers to be printed or a string
;		with column names separated by commas. If not supplied
;		or set to the null string, all columns are printed.
;
;	row1 - first row to print.  (default=0)
;	row2 - last row to print.  (default=last row in table)
;
; SIDE EFFECTS:
;	text is printed as directed by !textout
;
; HISTORY:
;	version 1, D. Lindler  Apr 89
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	TABLE_SORT
; PURPOSE:
;	Procedure to sort an STSDAS table by the specified column
;
; CALLING SEQUENCE:
;	table_sort, name, column, [ name_out ]
;
; INPUTS:
;	name - table name
;	column - column to sort on
;
; OPTIONAL INPUTS:
;	name_out - output table name.  If not supplied, input name
;		is used.
;
; HISTORY:
;	version 1  D. Lindler  MAY 1989
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	TAB_ADDCOL   
; PURPOSE:
;	Procedure to add a new column to an existing STSDAS table.
;
; CALLING SEQUENCE:
;	tab_addcol, name, data, tcb, tab
;
; INPUTS:
;	name - column name
;	data - sample data of type to be written to the column.
;		This parameter is only used to determine data type.
;
; INPUT/OUTPUTS:
;	tcb - table control block
;	tab - table array
;
; HISTORY:
;	version 1  D. Lindler April 89
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	TAB_COL  
; PURPOSE:
;	Procedure to extract column information from table control block
;
; CALLING SEQUENCE:
;	tab_col, tcb, column, offset, width, datatype, name, units, format
;
; INPUTS:
;	tcb - table control block returned by tab_open.
;	column - column name (string) or column number
;
; OUTPUTS:
;	offset - column offset bytes
;	width - column width in bytes
;	datatype - column data type:
;		6 - real*4
;		7 - real*8
;		4 - integer*4
;		1 - boolean
;		2 - character string
;	name - column name
;	units - column units
;	format - format code
;
; SIDE EFFECTS:
;	If the column is not found then !err is set to -1.
;	Otherwise !err is set to the column number (starting at one).
;
; HISTORY:
;	version 1  D. Lindler  Jan 88
;	Converted to NEW IDL  April 90
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	TAB_CREATE  
; PURPOSE:
;	Procedure to create a new table file.
;
; CALLING SEQUENCE:
;	tab_create, tcb, tab, maxcol, maxrows, row_len, tb_type
;
; OUTPUTS:
;	tcb - table control block for reading from and writing
;		to the file (see tab_open for description)
;	tab - table array
;
; OPTIONAL INPUTS:
;	maxcol - maximum allocated number of columns [default=10]
;	maxrows - maximum allocated number of rows   [default=100]
;	row_len - row length in 2 byte units	     [default=2*maxcol]
;	tb_type - table type 'row' or 'column' ordered
;
; SIDE EFFECTS:
;	Table file is created and left opened to unit number tcb(0,0)
;	for writing.
;
; HISTORY:
;	version 1   D. Lindler   Dec. 88
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	TAB_DEL 
; PURPOSE:
;	Delete specified row(s) from an STSDAS table
;
; CALLING SEQUENCE:
;	tab_del, tcb, tab, rows
;
; INPUT/OUTPUTS
;	tcb - table control block
;	tab - table array
;
; OPTIONAL INPUTS:
;	rows - row (scalar) or rows(vector) to delete from the table
;		If not supplied all rows are deleted.
;
; HISTORY:
;	version 1  D. Lindler  April 1989
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	TAB_EXPAND
; PURPOSE:
;	routine to expand the size of an SDAS table file.
;
; CALLING SEQUENCE:
;	tab_expand, tcb, tab, maxcol, maxrow, rowlen
;
; INPUT/OUTPUT:
;	tcb - table control block returned by routine TAB_READ
;		or TAB_CREATE.
;	tab - table array
;
; OPTIONAL INPUTS:
;	maxcol - new maximum number of columns.
;	maxrow - new maximum number of rows.
;	rowlen - new maximum row length in 2 byte units.
;
;	If maxcol, maxrow, or rowlen are supplied with
;	values less than the previous maximums, the previous
;	maximums are used.  All values are defaulted to zero
;	if not supplied.
;
; HISTORY:
;	Version 1   D. Lindler   Dec. 88
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	TAB_FORTOSPP
; PURPOSE:
;	Procedure to convert a FORTRAN format to an SPP format specfication.
;
; CALLING SEQUENCE:
;	sppformat, format, sppformat
;
; INPUTS:
;	format - fortran format specification
;
; OUTPUTS:
;	sppformat - sppformat specification
;
; HISTORY:
;	version 1  D. Lindler   Jan, 1989
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	TAB_MODCOL
; PURPOSE:
;	Modify column description in a STSDAS table
;
; CALLING SEQUENCE:
;	tab_modcol, tcb, column, units, format, newname
;
; INPUTS:
;	tcb - table control block
;	column - column name or number to be modified
;
; OPTIONAL INPUTS:
;	units - string giving physical units for the column.
;		If not supplied or set to the null string
;		the units are not changed.
;	format - print format (either fortran or SPP format)
;		An spp format should be preceeded by a '%'.
;		If not supplied or set to a null string, the
;		print format for the column is not changed.
;	newname - new name for the column.  If not supplied
;		or set to a null string, the name is not
;		changed
; EXAMPLES:
;
;	change the wavelength column to WAVE with a new format
;	of 'F10.3' and columns units of ANGSTROMS.
;
;	   tab_modcol,tcb,'wavelength','ANGSTROMS','F10.3','WAVE'
;
;	Change to print format of column 3 to spp format
;	20.10e
;	   tab_modcol,tcb,3,'','%20.10e'
; HISTORY:
;	version 1  D. Lindler   Apr 1989
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	TAB_NULL  
; PURPOSE:
;	function to locate null values within a vector of values from
;	an STSDAS table.
;
; CALLING SEQUENCE
;	result = tab_null(values)
;
; INPUTS:
;	values - data value(s)
;
; OUTPUTS:
;	a boolean variable is returned with the same length as values.
;	1 indicates that the corresponding value was null
;
; OPERATIONAL NOTES:
;	Boolean columns in an STSDAS table does not presently
;	have the capability to flag null values.
;
; HISTORY:
;	version 1   D. Lindler   April 1989
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	TAB_NULLROW 
; PURPOSE:
;	Insert null row(s) into a STSDAS table
;
; CALLING SEQUENCE:
;	tab_nullrow, tcb, tab, [ row1, row2  ]
;
; INPUTS:
;	tcb - table control block
;
; INPUT/OUTPUTS:
;	tab - table array
;
; OPTIONAL INPUTS:
;	row1 - first row number to insert nulls (default=0)
;	row2 - last row number to insert nulls (default = last row)
;
; HISTORY:
;	version 1, D. Lindler  Apr 89
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	TAB_PRINT 
; PURPOSE:
;	Routine to print an stsdas table.
;
; CALLING SEQUENCE:
;	tab_print, tcb, tab, columns, row1, row2
;
; INPUTS:
;	tcb - table control block returned by TAB_READ
;	tab - table array read by TAB_READ
;
; OPTIONAL INPUTS:
;	columns - vector of column numbers to be printed or a string
;		with column names separated by commas. If not supplied
;		or set to the null string, all columns are printed.
;
;	row1 - first row to print.  (default=0)
;	row2 - last row to print.  (default=last row in table)
;
; SIDE EFFECTS:
;	text is printed as directed by !textout
;
; HISTORY:
;	version 1, D. Lindler  Apr 89
;	April 90  Converted to NEW IDL D. Lindler
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	TAB_PUT   
; PURPOSE:
;	Procedure to place new values into a STSDAS table.
;
; CALLING SEQUENCE:
;	tab_put, column, values, tcb, tab, row
;
; INPUTS:
;	column - column name or number (if it is a new column then
;		a column name must be specified)
;	values - data values to add to the table
;
; INPUT/OUTPUTS:
;	tcb - table control block
;	tab - table array
;
; OPTIONAL INPUT:
;	row - starting row to insert values
;
; HISTORY:
;	version 1  D. Lindler   April 1989
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;   TAB_READ   
; PURPOSE:
;   Procedure to read an SDAS table file
; CALLING SEQUENCE:
;	tab_read,name,tcb,table,header
; INPUTS:
;	name - name of the table file
; OUTPUTS:
;	tcb - table control block 
;		Longword array of size 16 x maxcols+2
;		where maxcols is the maximum number of columns
;		allocated for the table.
;		tcb(*,0) contains:
;		   word	0	SPARE
;			1	number of user parameters
;			2	max. number of user par. allowed
;			3	number of rows in the table
;			4	number of allocated rows (for col. ordered tab)
;			5	number of columns defined
;			6	max number of columns
;			7	length of row used (in units of 2-bytes)
;			8	max row length (in units of 2-bytes)
;					relevant only for row ordered tables.
;			9	table type (11 for row order, 12 for col. order)
;			15	update flag (0-readonly, 1-update)
;		tcb(*,i) contains description of column i
;		   word 0	column number
;			1	offset for start of row in units of 2-bytes
;			2	width or column in 2-byte units
;			3	data type
;					6 = real*4
;					7 = real*8
;					4 = integer*4
;					1 = boolean*4
;					2 = character string
;			4-8	ascii column name up to 19 characters
;			9-13	column units (up to 19 characters)
;			14-15	format string
;		tcb(*,max number of columns+1)= file name
;
;	table - table array, Byte array row length (bytes) x nrows
;
; 	header - header parameters in form usable by sxpar, sxaddhist,
;		sxaddpar, ect.
; HISTORY:
;	Version 1  D. Lindler  Jan 88
;	Converted to NEW IDL  April 90  D. Lindler
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	TAB_SIZE   
; PURPOSE:
;	Routine to extract the table size from a table control block
;
; CALLING SEQUENCE:
;	tab_size, tcb, nrows, ncols, maxrows, maxcols, rowlen, max_rowlen
;
; INPUTS:
;	tcb - table control block
;
; OUTPUTS:
;	nrows - number of rows in the table
;	ncols - number of columns in the table
;	maxrows - number of rows allocated
;	maxcols - number of columns allocated
;	rowlen - length of the rows in bytes
;	max_rowlen - allocated row length
;
; HISTORY:
;	version 1  D. Lindler  April 1989
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	TAB_SORT
; PURPOSE:
;	Procedure to sort table by the specified column
;
; CALLING SEQUENCE:
;	tab_sort, column, tcb, tab
;
; INPUTS:
;	column - column name or number to sort on
;	tcb - table control block
;
; INPUT/OUTPUTS:
;	tab - table array
;
; HISTORY:
;	version 1  D. Lindler  April 1989
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	TAB_SPPTOFOR  
; PURPOSE:
;	This procedure converts an spp format specification to a normal
;	Fortran format specification.
;
; CALLING SEQUENCE:
;	tab_spptofor, sppformat, format, width
;
; INPUTS:
;	sppformat - spp format specification (without preceeding %)
;
; OUTPUTS:
;	forformat - fortran format specification (string)
;	width - field width (integer)
;
; HISTORY:
;	version 1  D. Lindler  Jan 1989
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	TAB_VAL
; PURPOSE:
;	Routine to read a column from an SDAS table file
;
; CALLING SEQUENCE:
;	values = tab_val( tcb, table, column, [ rows ] )
; INPUTS:
;	tcb - table control block returned by tab_val
;	table - table array returned by tab_val
;	column - scalar column name or number
; OPTIONAL INPUT:
;	rows - scalar giving row number or vector giving rows.
;		If not supplied all rows are returned.
; OUTPUT:
;	the values for the specified column (and rows) is returned
;	as the function value.  If row is specified as a scalar
;	(single row) then the result will be a scalar.
; HISTORY:
;	version 1  D. Lindler  Jan. 1988
;       Allow for a null column Landsman/Feggans    April 1992
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	TAB_WRITE
; PURPOSE:
;	Routine to write an stsdas table to disk
;
; CALLING SEQUENCE:
;	tab_write, name, tcb, tab, header
;
; INPUTS:
;	name - file name (default extension = .tab)
;	tcb - table control block
;	tab - table array
;
; OPTIONAL INPUT:
;	header - FITS header array
;
; HISTORY:
;	version 1  D. Lindler   April 1989
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:        
;       TAG_EXIST()
; PURPOSE:              
;       To test whether a tag name exists in a structure.
; EXPLANATION:               
;       Routine obtains a list of tagnames and tests whether the requested one
;       exists or not. The search is recursive so if any tag names in the 
;       structure are themselves structures the search drops down to that level.
;       (However, see the keyword TOP_LEVEL).
;               
; CALLING SEQUENCE: 
;       status = TAG_EXIST(str, tag, [ INDEX =, /TOP_LEVEL ] )
;    
; INPUT PARAMETERS:     
;       str  -  structure variable to search
;       tag  -  tag name to search for, scalar string
;
; OUTPUTS:
;       Function returns 1b if tag name exists or 0b if it does not.
;                              
; OPTIONAL INPUT KEYWORD:
;       TOP_LEVEL = If set, then only the top level of the structure is
;                           searched.
;
; OPTIONAL OUTPUT KEYWORD:
;       INDEX = index of matching tag, scalar longward, -1 if tag name does
;               not exist
;
; EXAMPLE:
;       Determine if the tag 'THICK' is in the !P system variable
;       
;       IDL> print,tag_exist(!P,'THICK')
;
; PROCEDURE CALLS:
;       None.
;
; MODIFICATION HISTORY:     : 
;       Written,       C D Pike, RAL, 18-May-94               
;       Passed out index of matching tag,  D Zarro, ARC/GSFC, 27-Jan-95     
;       William Thompson, GSFC, 6 March 1996    Added keyword TOP_LEVEL
;       Zarro, GSFC, 1 August 1996    Added call to help 
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Use SIZE(/TNAME) rather than DATATYPE()  W. Landsman  October 2001

; NAME:
;       TBDELCOL
; PURPOSE:
;       Delete a column of data from a FITS binary table
;
; CALLING SEQUENCE:
;       TBDELCOL, h, tab, name
;
; INPUTS-OUPUTS
;       h,tab - FITS binary table header and data array.  H and TAB will
;               be updated with the specified column deleted
;
; INPUTS:
;       name - Either (1) a string giving the name of the column to delete
;                       or (2) a scalar giving the column number to delete
;
; EXAMPLE:
;       Delete the column "FLUX" from FITS binary table
;
;       IDL> TBDELCOL, H, TAB, 'FLUX'
;
; PROCEDURES USED:
;       SXADDPAR, TBINFO, TBSIZE
; REVISION HISTORY:                                           
;       Written   W. Landsman        STX Co.     August, 1988
;       Adapted for IDL Version 2, J. Isensee, July, 1990
;       Use new structure returned by TBINFO,  August, 1997
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Use SIZE(/TNAME) instead of DATATYPE()   October 2001

; NAME:
;	TBDELROW
; PURPOSE:
;	Delete specified row or rows of data from a FITS binary table
;
; CALLING SEQUENCE:
;	TBDELROW, h, tab, rows
;
; INPUTS-OUPUTS
;	h,tab - FITS binary table header and data array.  H and TAB will
;		be updated on output with the specified row(s) deleted.
;
;	rows  -  scalar or vector, specifying the row numbers to delete
;		First row has index 0.   If a vector it will be sorted and
;		duplicates removed by TBDELROW
;
; EXAMPLE:
;	Compress a table to include only non-negative flux values
;
;	flux = TBGET(h,tab,'FLUX')       ;Obtain original flux vector
;	bad = where(flux lt 0)           ;Find negative fluxes
;	TBDELROW,h,tab,bad               ;Delete rows with negative fluxes
;
; PROCEDURE:
;	Specified rows are deleted from the data array, TAB.  The NAXIS2
;	keyword in the header is updated.
;
; REVISION HISTORY:                                           
;	Written   W. Landsman        STX Co.     August, 1988
;	Checked for IDL Version 2, J. Isensee, July, 1990
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;       TBGET
; PURPOSE:
;       Return value(s) from specified column in a FITS binary table
;
; CALLING SEQUENCE
;       values = TBGET( h, tab, field, [ rows, nulls, /NOSCALE] )
;               or
;       values = TBGET( tb_str, tab, field, [ rows, nulls, /NOSCALE] )
;
; INPUTS:
;       h - FITS binary table header, e.g. as returned by FITS_READ
;                       or
;       tb_str - IDL structure extracted from FITS header by TBINFO.
;               Use of the IDL structure will improve processing speed
;       tab - FITS binary table array, e.g. as returned by FITS_READ
;       field - field name or number, scalar
;
; OPTIONAL INPUTS:
;       rows -  scalar or vector giving row number(s)
;               Row numbers start at 0.  If not supplied or set to
;               -1 then values for all rows are returned
;
; OPTIONAL KEYWORD INPUT:
;       /NOSCALE - If this keyword is set and nonzero, then the TSCALn and
;               TZEROn keywords will *not* be used to scale to physical values
;               Default is to perfrom scaling
;       CONTINUE - This keyword does nothing, it is kept for consistency with
;               with earlier versions of TBGET().
; OUTPUTS:
;       the values for the row are returned as the function value.
;       Null values are set to 0 or blanks for strings.
;
; OPTIONAL OUTPUT:
;       nulls - null value flag of same length as the returned data.
;               Only used for integer data types, B, I, and J
;               It is set to 1 at null value positions and 0 elsewhere.
;               If supplied then the optional input, rows, must also
;               be supplied.
;
; EXAMPLE:
;       Read the columns labeled 'WAVELENGTH' and 'FLUX' from the second
;       extension of a FITS file 'spectra.fits' into IDL vectors w and f
;
;       IDL> fits_read,'spectra.fits',tab,htab,exten=2   ;Read 2nd extension
;       IDL> w = tbget(htab,tab,'wavelength')
;       IDL> f = tbget(htab,tab,'flux')
;
; NOTES:
;       (1) If the column is variable length ('P') format, then TBGET() will 
;       return the longword array of pointers into the heap area.   TBGET() 
;       currently lacks the ability to actually extract the data from the 
;       heap area.
;       (2) Use the higher-level procedure FTAB_EXT (which calls TBGET()) to
;       extract vectors directly from the FITS file.   
;       (3) Use the procedure FITS_HELP to determine which extensions are 
;       binary tables, and FTAB_HELP or TBHELP to determine the columns of the
;       table
; PROCEDURE CALLS:
;       IS_IEEE_BIG(), TBINFO, TBSIZE 
; HISTORY:
;       Written  W. Landsman        February, 1991
;       Work for string and complex   W. Landsman         April, 1993
;       Default scaling by TSCALn, TZEROn, Added /NOSCALE keyword,
;       Fixed nulls output, return longword pointers for variable length
;               binary tables,     W. Landsman  December 1996
;       Added a check for zero width column  W. Landsman   April, 1997
;       Add TEMPORARY() and REFORM() for speed  W. Landsman  May, 1997
;       Use new structure returned by TBINFO    W. Landsman  August 1997
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Add IS_IEEE_BIG(), No subscripting when all rows requested
;                               W. Landsman    March 2000
;       Use SIZE(/TNAME) instead of DATATYPE()  W. Landsman October 2001
;       Bypass IEEE_TO_HOST call for improved speed W. Landsman November 2002
;       Cosmetic changes to SIZE() calls W. Landsman December 2002
;       Added unofficial support for 64bit integers W. Landsman February 2003
;       Support unsigned integers, new pointer types of TSCAL and TZERO
;       returned by TBINFO   W. Landsman        April 2003
;       Add an i = i[0] for V6.0 compatibility  W. Landsman  August 2003

; NAME:
;       TBHELP
; PURPOSE:
;       Routine to print a description of a FITS binary table header
;
; CALLING SEQUENCE:
;       TBHELP, h, [TEXTOUT = ]
;
; INPUTS:
;       h - FITS header for a binary table, string array
;
; OPTIONAL INPUT KEYWORD:
;       TEXTOUT - scalar number (0-7) or string (file name) controling 
;               output device (see TEXTOPEN).  Default is TEXTOUT=1, output 
;               to the user's terminal    
;
; METHOD:
;       FITS Binary Table keywords NAXIS*,EXTNAME,TFIELDS,TTYPE*,TFORM*,TUNIT*,
;       are read from the header and displayed at the terminal
;
;       A FITS header is recognized as bein for a binary table if the keyword 
;       XTENSION has the value 'BINTABLE' or 'A3DTABLE'
;
; NOTES:
;       Certain fields may be truncated in the display
; SYSTEM VARIABLES:
;       Uses the non-standard system variables !TEXTOUT and !TEXTUNIT.   These
;       are automatically defined by TBHELP if they have not been defined
;       previously. 
; PROCEDURES USED:
;       REMCHAR, SXPAR(), TEXTCLOSE, TEXTOPEN, ZPARCHECK 
; HISTORY:
;       W. Landsman       February, 1991
;       Parsing of a FITS binary header made more robust    May, 1992
;       Added TEXTOUT keyword      August 1997
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Define !TEXTOUT if not already present   W. Landsman  November 2002

; NAME:
;       TBPRINT
;  PURPOSE:
;       Procedure to print specified columns & rows of a FITS binary table
;
; CALLING SEQUENCE:
;       TBPRINT, h, tab, columns, [ rows, TEXTOUT =, FMT = ]
;               or
;       TBPRINT,tb_str, tab, columns, [ rows, TEXTOUT =, FMT =  ]
;
; INPUTS:
;       h - FITS header for table, string array
;                       or
;       tb_str - IDL structure extracted from FITS header by TBINFO, useful 
;           when TBPRINT is called many times with the same header
;       tab - table array 
;       columns - string giving column names, or vector giving
;               column numbers (beginning with 1).  If string 
;               supplied then column names should be separated by comma's.
;       rows - (optional) vector of row numbers to print.  If
;               not supplied or set to scalar, -1, then all rows
;               are printed.
;
; OUTPUTS:
;       None
; OPTIONAL INPUT KEYWORDS:
;       TEXTOUT - scalar number (0-7) or string (file name) determining
;               output device (see TEXTOPEN).  Default is TEXTOUT=1, output 
;               to the user's terminal    
;       FMT = Format string for print display.   If not supplied, then any 
;               formats in the TDISP keyword fields of the table will be
;               used, otherwise IDL default formats.   
;
; SYSTEM VARIABLES:
;       Uses nonstandard system variables !TEXTOUT and !TEXTOPEN
;       Set !TEXTOUT = 3 to direct output to a disk file.   The system
;       variable is overriden by the value of the keyword TEXTOUT
;
; EXAMPLES:
;       tab = readfits('test.fits',htab,/ext) ;Read first extension into vars
;       tbprint,h,tab,'STAR ID,RA,DEC'    ;print id,ra,dec for all stars
;       tbprint,h,tab,[2,3,4],indgen(100) ;print columns 2-4 for 
;                                          first 100 stars
;       tbprint,h,tab,text="stars.dat"    ;Convert entire FITS table to
;                                         ;an ASCII file named 'stars.dat'
;
; PROCEDURES USED:
;       GETTOK(), TEXTOPEN, TEXTCLOSE, TBINFO
;
; RESTRICTIONS: 
;       (1) Program does not check whether output length exceeds output
;               device capacity (e.g. 80 or 132).
;       (2) Column heading may be truncated to fit in space defined by
;               the FORMAT specified for the column
;       (3) Program does not check for null values
;       (4) Does not work with variable length columns
;
; HISTORY:
;       version 1  D. Lindler Feb. 1987
;       Accept undefined values of rows,columns W. Landsman  August 1997
;       Use new structure returned by TBINFO    W. Landsman  August 1997
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Made formatting more robust    W. Landsman   March 2000
;       Use STRSPLIT to parse string column listing W. Landsman July 2002
;       Wasn't always printing last row   W. Landsman  Feb. 2003

; NAME:
;       TBSIZE
;
; PURPOSE:
;       Procedure to return the size of a FITS binary table.
;
; CALLING SEQUENCE:
;       tbsize, h, tab, ncols, nrows, tfields, ncols_all, nrows_all
;
; INPUTS:
;       h - FITS table header
;       tab - FITS table array
;
; OUTPUTS:
;       ncols - number of characters per row in table
;       nrows - number of rows in table
;       tfields - number of fields per row
;       ncols_all - number of characters/row allocated (size of tab)
;       nrows_all - number of rows allocated
; PROCEDURES USED:
;       SXPAR()
; HISTORY
;       D. Lindler  July, 1987
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Remove obsolete !ERR call   W. Landsman   May 2000

; NAME:
;   TDB2TDT
;
; AUTHOR:
;   Craig B. Markwardt, NASA/GSFC Code 662, Greenbelt, MD 20770
;   craigm@lheamail.gsfc.nasa.gov
;   UPDATED VERSIONs can be found on my WEB PAGE: 
;      http://cow.physics.wisc.edu/~craigm/idl/idl.html
;
; PURPOSE:
;   Relativistic clock corrections due to Earth motion in solar system 
;
; MAJOR TOPICS:
;   Planetary Orbits
;
; CALLING SEQUENCE:
;   corr = TDB2TDT(JD, TBASE=, DERIV=deriv)
;
; DESCRIPTION:
;
;   The function TDB2TDT computes relativistic corrections that must
;   be applied when performing high precision absolute timing in the
;   solar system.
;
;   According to general relativity, moving clocks, and clocks at
;   different gravitational potentials, will run at different rates
;   with respect to each other.  A clock placed on the earth will run
;   at a time-variable rate because of the non-constant influence of
;   the sun and other planets.  Thus, for the most demanding
;   astrophysical timing applications -- high precision pulsar timing
;   -- times in the accelerating earth observer's frame must be
;   corrected to an inertial frame, such as the solar system
;   barycenter (SSB).  This correction is also convenient because the
;   coordinate time at the SSB is the ephemeris time of the JPL
;   Planetary Ephemeris.
;
;   In general, the difference in the rate of Ti, the time kept by an
;   arbitrary clock, and the rate of T, the ephemeris time, is given
;   by the expression (Standish 1998):
;
;      dTi/dT = 1 - (Ui + vi^2/2) / c^2
;
;   where Ui is the potential of clock i, and vi is the velocity of
;   clock i.  However, when integrated, this expression depends on the
;   position of an individual clock.  A more convenient approximate
;   expression is:
;
;     T = Ti + (robs(Ti) . vearth(T))/c^2 + dtgeo(Ti) + TDB2TDT(Ti)
;
;   where robs is the vector from the geocenter to the observer;
;   vearth is the vector velocity of the earth; and dtgeo is a
;   correction to convert from the observer's clock to geocentric TT
;   time.  TDB2TDT is the value computed by this function, the
;   correction to convert from the geocenter to the solar system
;   barycenter.
;
;   As the above equation shows, while this function provides an
;   important component of the correction, the user must also be
;   responsible for (a) correcting their times to the geocenter (ie,
;   by maintaining atomic clock corrections); (b) estimating the
;   observatory position vector; and and (c) estimating earth's
;   velocity vector (using JPLEPHINTERP).
;
;   Users may note a circularity to the above equation, since
;   vearth(T) is expressed in terms of the SSB coordinate time.  This
;   appears to be a chicken and egg problem since in order to get the
;   earth's velocity, the ephemeris time is needed to begin with.
;   However, to the precision of the above equation, < 25 ns, it is
;   acceptable to replace vearth(T) with vearth(TT).
;
;   The method of computation of TDB2TDT in this function is based on
;   the analytical formulation by Fairhead, Bretagnon & Lestrade, 1988
;   (so-called FBL model) and Fairhead & Bretagnon 1990, in terms of
;   sinusoids of various amplitudes.  TDB2TDT has a dominant periodic
;   component of period 1 year and amplitude 1.7 ms.  The set of 791
;   coefficients used here were drawn from the Princeton pulsar timing
;   program TEMPO version 11.005 (Taylor & Weisberg 1989).
;
;   Because the TDB2TDT quantity is rather expensive to compute but
;   slowly varying, users may wish to also retrieve the time
;   derivative using the DERIV keyword, if they have many times to
;   convert over a short baseline.
;
; Verification
;
;   This implementation has been compared against a set of FBL test
;   data found in the 1996 IERS Conventions, Chapter 11, provided by
;   T. Fukushima.  It has been verified that this routine reproduces
;   the Fukushima numbers to the accuracy of the table, within
;   10^{-14} seconds.
;
;   Fukushima (1995) has found that the 791-term Fairhead & Bretagnon
;   analytical approximation use here has a maximum error of 23
;   nanoseconds in the time range 1980-2000, compared to a numerical
;   integration.  In comparison the truncated 127-term approximation
;   has an error of ~130 nanoseconds.
;
;
; PARAMETERS: 
;
;   JD - Geocentric time TT, scalar or vector, expressed in Julian
;        days.  The actual time used is (JD + TBASE).  For maximum
;        precision, TBASE should be used to express a fixed epoch in
;        whole day numbers, and JD should express fractional offset
;        days from that epoch.
;
;
; KEYWORD PARAMETERS:
;
;   TBASE - scalar Julian day of a fixed epoch, which provides the
;           origin for times passed in JD.
;          Default: 0
;
;   DERIV - upon return, contains the derivative of TDB2TDT in units
;           of seconds per day.  As many derivatives are returned as
;           values passed in JD.
;
;
; RETURNS:
;   The correction offset(s) in units of seconds, to be applied as
;   noted above.
;
;
; EXAMPLE:
;
;   Find the correction at ephemeris time 2451544.5 (JD):
;     IDL> print, tdb2tdt(2451544.5d)
;       -0.00011376314
;   or 0.11 ms.
;
;
; REFERENCES:
;
;   Princeton TEMPO Program
;      http://pulsar.princeton.edu/tempo/
;
;   FBL Test Data Set
;      ftp://maia.usno.navy.mil/conventions/chapter11/fbl.results
;
;   Fairhead, L. & Bretagnon, P. 1990, A&A, 229, 240
;     (basis of this routine)
;
;   Fairhead, L. Bretagnon, P. & Lestrade, J.-F. 1988, in *The Earth's
;     Rotation and Reference Frames for Geodesy and Geodynamics*,
;     ed. A. K. Babcock and G. A. Wilkins, (Dordrecht: Kluwer), p. 419
;     (original "FBL" paper)
;
;   Fukushima, T. 1995, A&A, 294, 895  (error analysis)
;
;   Irwin, A. W. & Fukushima, T. 1999, A&A, 348, 642  (error analysis)
;
;   Standish, E. M. 1998, A&A, 336, 381 (description of time scales)
;
;   Taylor, J. H. & Weisberg, J. M. 1989, ApJ, 345, 434 (pulsar timing)
;
;
; SEE ALSO
;   JPLEPHREAD, JPLEPHINTERP, JPLEPHTEST
;   
; MODIFICATION HISTORY:
;   Original logic from Fairhead & Bretagnon, 1990
;   Drawn from TEMPO v. 11.005, copied 20 Jun 2001
;   Documented and vectorized, 30 Jun 2001
;   
;
;  $Id: tdb2tdt.pro,v 1.4 2001/07/01 07:37:40 craigm Exp $
;

; NAME:
;	TEN()
; PURPOSE:
;	Converts a sexigesimal number to decimal.
; EXPLANATION:
;	Inverse of the SIXTY() function.
;
; CALLING SEQUENCES:
;	X = TEN( [ HOUR_OR_DEG, MIN, SEC ] )
;	X = TEN( HOUR_OR_DEG, MIN, SEC )
;	X = TEN( [ HOUR_OR_DEG, MIN ] )
;	X = TEN( HOUR_OR_DEG, MIN )
;	X = TEN( [ HOUR_OR_DEG ] )      <--  Trivial cases
;	X = TEN( HOUR_OR_DEG )        <--
;
; INPUTS:
;	HOUR_OR_DEG,MIN,SEC -- Scalars giving sexigesimal quantity in 
;		in order from largest to smallest.    
;
; OUTPUTS:
;	Function value returned = double real scalar, decimal equivalent of
;	input sexigesimal quantity.  A minus sign on any nonzero element
;	of the input vector causes all the elements to be taken as
;	< 0.
;
; PROCEDURE:
;	Mostly involves checking arguments and setting the sign.
;
;	The procedure TENV can be used when dealing with a vector of 
;	sexigesimal quantities.
;
; MODIFICATION HISTORY:
;	Written by R. S. Hill, STX, 21 April 87       
;	Modified to allow non-vector arguments.  RSH, STX, 19-OCT-87
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	TENV()
; PURPOSE:
;	Converts sexigesimal number or vector to decimal.  
; EXPLANATION:
;	Like TEN() but allows vector input.
;
; CALLING SEQUENCES:
;	Result = TENV( dd, mm )           ; result = dd + mm/60.
;	Result = TENV( dd, mm, ss)        ; result = dd + mm/60. + ss/3600.
;
; INPUTS:
;	dd - Sexigesimal element(s) corresponding to hours or degrees
;	mm - Sexigesimal element(s) corresponding to minutes
;	ss - Sexigesimal element(s) corresponding to seconds (optional)
;		The input parameters can be scalars or vectors.   However, the
;		number of elements in each parameter must be the same.
;
; OUTPUTS:
;	Result -  double, decimal equivalent of input sexigesimal 
;		quantities.  Same number of elements as the input parameters.
;		If the nth element in any of the input parameters is negative 
;		then the nth element in Result wil also be negative.
;
; EXAMPLE:
;	If dd = [60,60,0], and mm = [30,-30,-30], then
;
;	IDL> Result = TENV(dd,mm)  ====>   Result =  [60.5,-60.5,-0.5]
;
; PROCEDURE:
;	Mostly involves checking arguments and setting the sign.
;
;   MODIFICATION HISTORY:
;	Written by W.B. Landsman           April, 1991
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	TEXTCLOSE                   
;
; PURPOSE:
;	Close a text outpu file previously opened with TEXTOPEN 
; EXPLANATION:
;	procedure to close file for text output as specifed
;	by the (non-standard) system variable !TEXTOUT. 
;
; CALLING SEQUENCE:
;	textclose, [ TEXTOUT = ]
;
; KEYWORDS:
;	textout - Indicates output device that was used by
;		TEXTOPEN
;
; SIDE EFFECTS:
;	if !textout is not equal to 5 and the textunit is
;	opened.   Then unit !textunit is closed and released
;
; HISTORY:
;	D. Lindler  Dec. 1986  (Replaces PRTOPEN)
;	Test if TEXTOUT is a scalar string   W. Landsman   August 1993
; Can't close unit -1 (Standard Output) I. Freedman  April  1994
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;       TEXTOPEN
; PURPOSE:
;       Open a device specified by TEXTOUT with unit !TEXTUNIT 
; EXPLANATION:
;       Procedure to open file for text output.   The type of output 
;       device (disk file or terminal screen) is specified by the 
;       TEXTOUT keyword or the (nonstandard) system variable !TEXTOUT.
;
; CALLING SEQUENCE:
;       textopen, program, [ TEXTOUT =, /STDOUT, /SILENT, MORE_SET= ]
;
; INPUTS:
;       program - scalar string giving name of program calling textopen
;
; OPTIONAL INPUT KEYWORDS:
;       TEXTOUT - Integer scalar (0-7) specifying output file/device to be 
;               opened (see below) or scalar string giving name of output file.
;               If TEXTOUT is not supplied, then the (non-standard) system 
;               variable !TEXTOUT is used.
;       /SILENT - By default, TEXTOPEN prints an informational message when
;                opening a file for hardcopy output.   Set /SILENT (or !QUIET)
;                to suppress this message.
;       /STDOUT - if this keyword is set and non-zero, then the standard output
;               (unit = -1) is used for TEXTOUT=1 or TEXTOUT=2.   The use
;               of STDOUT has  2 possible advantages:
;               (1) the output will appear in a journal file
;               (2) Many Unix machines print spurious control characters when
;               printing to /dev/tty.   These characters are eliminated by 
;               setting /STDOUT
;
;               The disadvantage of /STDOUT is that the /MORE option is not
;               available.
;
; OPTIONAL OUTPUT KEYWORD:
;       MORE_SET - Returns 1 if the output unit was opened with /MORE.   This
;               occurs if (1) TEXTOUT = 1 and (2) the device is a tty, and 
;               (3) /STDOUT is not set.      User can use the returned value
;                of MORE_SET to determine whether to end output when user
;                presses 'Q'.
; SIDE EFFECTS:
;       The following dev/file is opened for output.    Different effects
;       occur depending whether the standard output is a GUI (Macintosh,
;       Windows, Unix/IDLTool) or a TTY
;
;               textout=0       Nowhere
;               textout=1       if a TTY then TERMINAL using /more option
;                                   otherwise standard (Unit=-1) output
;               textout=2       if a TTY then TERMINAL without /more option
;                                   otherwise standard (Unit=-1) output
;               textout=3       .prt
;               textout=4       laser.tmp
;               textout=5      user must open file
;               textout=7      same as 3 but text is appended to .prt
;                               file if it already exists.
;               textout = filename (default extension of .prt)
;
;       The unit to be opened is obtained with the procedure GET_LUN
;       unless !TEXTOUT=5.  The unit number is placed in system variable 
;       !TEXTUNIT.  For !TEXTOUT=5 the user must set !TEXTUNIT to the 
;       appropriate unit number.
;
; NOTES:
;       When printing to a TTY terminal, the output will *not* appear in an 
;       IDL JOURNAL session, unlike text printed with the PRINT command.
;
; NON-STANDARD SYSTEM VARIABLES:
;       TEXTOPEN will automatically define the following system variables if
;       they are not previously defined:
;
;       DEFSYSV,'!TEXTOUT',1
;       DEFSYSV,'!TEXTUNIT',0
; HISTORY:
;       D. Lindler  Dec. 1986  
;       Keyword textout added, J. Isensee, July, 1990
;       Made transportable, D. Neill, April, 1991
;       Trim input PROGRAM string W. Landsman  Feb 1993
;       Don't modify TEXTOUT value   W. Landsman   Aug 1993
;       Modified for MacOS  I. Freedman April 1994
;       Modified for output terminals without a TTY  W. Landsman  August 1995
;       Added /STDOUT keyword   W. Landsman    April 1996
;       added textout=7 option, D. Lindler, July, 1996
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Exit with RETURN instead of RETALL  W. Landsman  June 1999
;       In IDL V5.4 filepath(/TERMINAL) not allowed in the IDLDE WL August 2001
;       Added MORE_SET output keyword   W.Landsman   January 2002
;       Added /SILENT keyword  W. Landsman  June 2002  
;	Define !TEXTOUT and !TEXTUNIT if needed.  R. Sterner, 2002 Aug 27
;       Return Calling Sequence if no parameters supplied W.Landsman Nov 2002

; NAME:
;	TICLABELS
; PURPOSE:
;	Create tic labels for labeling astronomical images.
; EXPLANATION: 
;	Used to display images with right ascension or declination
;	axes.  This routine creates labels for already determined tic
;	marks (every other tic mark by default)
;
; CALLING SEQUENCE:
;	TICLABELS, minval, numtics, incr, ticlabs, [ RA = ,DELTA = ]
;
; INPUTS:
;	minval  - minimum value for labels (degrees)
;	numtics - number of tic marks
;	incr    - increment in minutes for labels
;
; OUTPUTS:
;	ticlabs - array of charater string labels
;
; OPTIONAL INPUT KEYWORDS:
;	/RA - if this keyword is set then the grid axis is assumed to be
;		a Right Ascension.   Otherwise a declination axis is assumed
;	DELTA - Scalar specifying spacing of labels.   The default is 
;		DELTA = 2 which means that a label is made for every other tic
;		mark.  Set DELTA=1 to create a label for every tic mark.
;
; PROCEDURES USED:
;	RADEC
;
; RESTRICTIONS:
;	Invalid for wide field (> 2 degree) images since it assumes that a 
;	fixed interval in Y (or X) corresponds to a fixed interval in Dec 
;	(or RA)
;
; REVISON HISTORY:
;	written by B. Pfarr, 4/15/87
;	Added DELTA keywrd for compatibility with IMCONTOUR W. Landsman Nov 1991
;	Added nicer hms and dms symbols when using native PS fonts Deutsch 11/92
;	Added Patch for bug in IDL <2.4.0 as explained in NOTES E. Deutsch 11/92
;	Fix when crossing 0 dec or 24h RA
;	Fix DELTA keyword so that it behaves according to the documentation
;			W. Landsman  Hughes STX,  Nov 95  
;	Converted to IDL V5.0   W. Landsman   September 1997
;       Allow sub arcsecond formatting  W. Landsman   May 2000

; NAME:
;       TICPOS
; PURPOSE:
;       Specify distance between tic marks for astronomical coordinate overlays
; EXPLANATION:
;       User inputs number an approximate distance
;       between tic marks, and the axis length in degrees.  TICPOS will return 
;       a distance between tic marks such that the separation is a round
;       multiple in arc seconds, arc minutes, or degrees
;
; CALLING SEQUENCE:
;       TICPOS, deglen, pixlen, ticsize, incr, units
;
; INPUTS:
;       deglen - length of axis in DEGREES
;       pixlen - length of axis in plotting units (pixels)
;       ticsize - distance between tic marks (pixels).  This value will be
;               adjusted by TICPOS such that the distance corresponds to
;               a round multiple in the astronomical coordinate.
;
; OUTPUTS:
;       ticsize - distance between tic marks (pixels), positive scalar 
;       incr    - incremental value for tic marks in round units given 
;               by the UNITS parameter
;       units - string giving units of ticsize, either 'ARC SECONDS',
;               'ARC MINUTES', or 'DEGREES'
;
; EXAMPLE:
;       Suppose a 512 x 512 image array corresponds to 0.2 x 0.2 degrees on
;       the sky.   A tic mark is desired in round angular units, approximately 
;       every 75 pixels.
;
;       IDL> ticsize = 75
;       IDL> TICPOS,0.2,512,ticsize,incr,units   
;
;       ==> ticsize = 85.333, incr = 2. units = 'Arc Minutes'
;
;       i.e. a good tic mark spacing is every 2 arc minutes, corresponding
;       to 85.333 pixels.
;
; REVISON HISTORY:
;       written by W. Landsman            November, 1988
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Don't use all capital letters  W. Landsman May 2003

; NAME:
;       TICS
; PURPOSE:
;       Compute a nice increment between tic marks for astronomical images.
; EXPLANATION:       
;       For use in labelling a displayed image with right ascension
;       or declination axes.  An approximate distance between tic 
;       marks is input, and a new value is computed such that the 
;       distance between tic marks is in simple increments of the 
;       tic label values.
;
; CALLING SEQUENCE:
;       tics, radec_min, radec_max, numx, ticsize, incr, [ /RA ]
;
; INPUTS:
;       radec_min - minimum axis value (degrees)
;       radec_max - maximum axis value (degrees)
;       numx  - number of pixels in x direction
;
; INPUT/OUTPUT  
;       ticsize - distance between tic marks (pixels)
;
; OUTPUTS:
;       incr    - incremental value for tic labels (in minutes of 
;               time for R.A., minutes of arc for dec.)
;
; REVISON HISTORY:
;       written by B. Pfarr, 4/14/87
;       Added some more tick precision (i.e. 1 & 2 seconds in case:) EWD May92
;       Added sub arcsecond tick precision   W. Landsman   May 2000

; NAME:
;	TIC_ONE
; PURPOSE:
;	Determine the position of the first tic mark for astronomical images.
; EXPLANATION:
;	For use in labelling images with right ascension
;	and declination axes. This routine determines the 
;	position in pixels of the first tic.
;
; CALLING SEQUENCE:
;	tic_one, zmin, pixx, incr, min2, tic1, [RA = ]
;
; INPUTS:
;	zmin  - astronomical coordinate value at axis zero point (degrees 
;		or hours)
;	pixx - distance in pixels between tic marks (usually obtained from TICS)
;	incr - increment in minutes for labels (usually an even number obtained 
;		from the procedure TICS)
;
; OUTPUTS:
;	min2 - astronomical coordinate value at first tic mark 
;	tic1 - position in pixels of first tic mark
;
; EXAMPLE:
;	Suppose a declination axis has a value of 30.2345 degrees at its
;	zero point.  A tic mark is desired every 10 arc minutes, which 
;	corresponds to 12.74 pixels.  Then
;
;	IDL> TIC_ONE, 30.2345, 1, 12.74, min2, tic1
;
;	yields values of min2 = 30.333 and tic1 = 5.74, i.e. the first tic
;	mark should be labeled 30 deg 20 minutes and be placed at pixel value
;	5.74
;
; REVISION HISTORY:
;	by B. Pfarr, 4/15/87
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;       TO_HEX
; PURPOSE:
;       Translate a non-negative decimal integer to a hexadecimal string
;
; CALLING SEQUENCE:
;       HEX = TO_HEX( D, [ NCHAR ] )
; INPUTS:
;       D - non-negative decimal integer, scalar or vector.  If input as a
;           string, (e.g. '32') then all leading blanks are removed.
;
; OPTIONAL INPUT:
;       NCHAR - number of characters in the output hexadecimal string.
;               If not supplied, then the hex string will contain no 
;               leading zeros.
;
; OUTPUT:
;       HEX - hexadecimal translation of input integer, string
;
; EXAMPLES:
;       IDL> A = TO_HEX([11,16])    ==>   A = ['B','10']
;       IDL> A = TO_HEX(100,3) ==>   A = '064'
;
; METHOD:
;       The hexadecimal format code '(Z)' is used to convert.  No parameter
;       checking is done.
; PROCEDURES CALLED:
;       FSTRING() -- needed prior to V5.4 if formatting more than 1024 values
; REVISION HISTORY:
;       Written   W. Landsman         November, 1990
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Use FSTRING() for more than 1024 values      March 2000 
;       No FSTRING call needed if V5.4 or later      September 2002 

; NAME:
;       TRAPZD
; PURPOSE:
;       Compute the nth stage of refinement of an extended trapezoidal rule.
; EXPLANATION:
;       This procedure is called by QSIMP and QTRAP.   Algorithm from Numerical
;       Recipes, Section 4.2.   TRAPZD is meant to be called iteratively from
;       a higher level procedure.
;
; CALLING SEQUENCE:
;       TRAPZD, func, A, B, S, step, [ _EXTRA = ]
;
; INPUTS:
;       func - scalar string giving name of function to be integrated.   This
;               must be a function of one variable.
;       A,B -  scalars giving the limits of the integration
;
; INPUT-OUTPUT:
;       S -    scalar giving the total sum from the previous iterations on 
;               input and the refined sum after the current iteration on output.
;
;       step - LONG scalar giving the number of points at which to compute the
;               function for the current iteration.   If step is not defined on
;               input, then S is intialized using the average of the endpoints
;               of limits of integration.
;
; OPTIONAL INPUT KEYWORDS:
;       Any supplied keywords will be passed to the user function via the 
;       _EXTRA facility. 
;
; NOTES:
;       (1) TRAPZD will check for math errors when computing the function at the
;       endpoints, but not on subsequent iterations.
;
;       (2) TRAPZD always uses double precision to sum the function values
;       but the call to the user-supplied function is double precision only if 
;       one of the limits A or B is double precision.
; REVISION HISTORY:
;       Written         W. Landsman                 August, 1991
;       Always use double precision for TOTAL       March, 1996
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Pass keyword to function via _EXTRA facility  W. Landsman July 1999

; NAME:
;       TSC
;
; PURPOSE:
;       Interpolate an irregularly sampled field using a Triangular Shaped Cloud
;
; EXPLANATION:
;       This function interpolates an irregularly sampled field to a
;       regular grid using Triangular Shaped Cloud (nearest grid point
;       gets weight 0.75-dx^2, points before and after nearest grid
;       points get weight 0.5*(1.5-dx)^2, where dx is the distance
;       from the sample to the grid point in units of the cell size).
;
; CATEGORY:
;       Mathematical functions, Interpolation
;
; CALLING SEQUENCE:
;       Result = TSC, VALUE, POSX, NX[, POSY, NY, POSZ, NZ, 
;                     AVERAGE = average, WRAPAROUND =  wraparound,
;                     ISOLATED = isolated, NO_MESSAGE = no_message]
;
; INPUTS:
;       VALUE: Array of sample weights (field values). For e.g. a
;              temperature field this would be the temperature and the
;              keyword AVERAGE should be set. For e.g. a density field
;              this could be either the particle mass (AVERAGE should
;              not be set) or the density (AVERAGE should be set).
;       POSX:  Array of X coordinates of field samples, unit indices: [0,NX>.
;       NX:    Desired number of grid points in X-direction.
;       
; OPTIONAL INPUTS:
;      POSY: Array of Y coordinates of field samples, unit indices: [0,NY>.
;      NY:   Desired number of grid points in Y-direction.
;      POSZ: Array of Z coordinates of field samples, unit indices: [0,NZ>.
;      NZ:   Desired number of grid points in Z-direction.
;
; KEYWORD PARAMETERS:
;       AVERAGE:    Set this keyword if the nodes contain field samples
;                   (e.g. a temperature field). The value at each grid
;                   point will then be the weighted average of all the
;                   samples allocated to it. If this keyword is not
;                   set, the value at each grid point will be the
;                   weighted sum of all the nodes allocated to it
;                   (e.g. for a density field from a distribution of
;                   particles). (D=0). 
;       WRAPAROUND: Set this keyword if you want the first grid point
;                   to contain samples of both sides of the volume
;                   (see below).
;       ISOLATED:   Set this keyword if the data is isolated, i.e. not
;                   periodic. In that case total `mass' is not conserved.
;                   This keyword cannot be used in combination with the
;                   keyword WRAPAROUND.
;       NO_MESSAGE: Suppress informational messages.
;
; Example of default allocation of nearest grid points: n0=4, *=gridpoint.
;
;     0   1   2   3     Index of gridpoints
;     *   *   *   *     Grid points
;   |---|---|---|---|   Range allocated to gridpoints ([0.0,1.0> --> 0, etc.)
;   0   1   2   3   4   posx
;
; Example of ngp allocation for WRAPAROUND: n0=4, *=gridpoint.
;
;   0   1   2   3         Index of gridpoints
;   *   *   *   *         Grid points
; |---|---|---|---|--     Range allocated to gridpoints ([0.5,1.5> --> 1, etc.)
;   0   1   2   3   4=0   posx
;
;
; OUTPUTS:
;       Prints that a TSC interpolation is being performed of x
;       samples to y grid points, unless NO_MESSAGE is set.
;
; RESTRICTIONS:
;       Field data is assumed to be periodic with the sampled volume
;       the basic cell, unless ISOLATED is set.
;       All input arrays must have the same dimensions.
;       Postition coordinates should be in `index units' of the
;       desired grid: POSX=[0,NX>, etc.
;       Keywords ISOLATED and WRAPAROUND cannot both be set.
;
; PROCEDURE:
;       Nearest grid point is determined for each sample.
;       TSC weights are computed for each sample.
;       Samples are interpolated to the grid.
;       Grid point values are computed (sum or average of samples).
;
; EXAMPLE:
;       nx=20
;       ny=10
;       posx=randomu(s,1000)
;       posy=randomu(s,1000)
;       value=posx^2+posy^2
;       field=tsc(value,posx*nx,nx,posy*ny,ny,/average)
;       surface,field,/lego
;
; NOTES:
;       Use csc.pro or ngp.pro for lower order interpolation schemes.    A 
;       standard reference for these interpolation methods is:   R.W. Hockney 
;       and J.W. Eastwood, Computer Simulations Using Particles (New York: 
;       McGraw-Hill, 1981).
;
; MODIFICATION HISTORY:
;       Written by Joop Schaye, Feb 1999.
;       Check for overflow for large dimensions  P. Riley/W. Landsman Dec. 1999

; NAME:
;       TSUM
; PURPOSE:
;       Trapezoidal summation of the area under a curve. 
; EXPLANATION:
;       Adapted from the procedure INTEG in the IUE procedure library.  
;
; CALLING SEQUENCE:
;       Result = TSUM(y)
;              or
;       Result = TSUM( x, y, [ imin, imax ] )  
; INPUTS:
;       x = array containing monotonic independent variable.  If omitted, then
;               x is assumed to contain the index of the y variable.
;               x = lindgen( N_elements(y) ).
;       y = array containing dependent variable y = f(x)
;
; OPTIONAL INPUTS:
;       imin = scalar index of x array at which to begin the integration
;               If omitted, then summation starts at x[0].
;       imax = scalar index of x value at which to end the integration 
;               If omitted then the integration ends at x[npts-1].
;
; OUTPUTS:
;       result = area under the curve y=f(x) between x[imin] and x[imax].
;
; EXAMPLE:
;       IDL> x = [0.0,0.1,0.14,0.3] 
;       IDL> y = sin(x)
;       IDL> print,tsum(x,y)    ===>  0.0445843
;       
;       In this example, the exact curve can be computed analytically as 
;       1.0 - cos(0.3) = 0.0446635     
; PROCEDURE:
;       The area is determined of individual trapezoids defined by x[i],
;       x[i+1], y[i] and y[i+1].
;
;       If the data is known to be at all smooth, then a more accurate
;       integration can be found by interpolation prior to the trapezoidal
;       sums, for example, by the standard IDL User Library int_tabulated.pro.
; MODIFICATION HISTORY:
;       Written, W.B. Landsman, STI Corp. May 1986
;       Modified so X is not altered in a one parameter call Jan 1990
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Allow non-integer values of imin and imax  W. Landsman April 2001
;       Fix problem if only 1 parameter supplied W. Landsman June 2002

; NAME:
;      TVBOX
; PURPOSE:
;      Draw a box(es) or rectangle(s) of specified width
; EXPLANATION: 
;      Positions can be specified either by the cursor position or by 
;      supplying a vector of X,Y positions.   
;
; CALLING SEQUENCE:
;      TVBOX, width, [ x, y, color, /DATA, ANGLE= ,COLOR =, _EXTRA =  ]
;
; INPUTS:
;      WIDTH -  either a scalar giving the width of a box, or a 2 element
;               vector giving the length and width of a rectangle.
;
; OPTIONAL INPUTS:           
;      X  -  x position for box center, scalar or vector
;      Y  -  y position for box center, scalar or vector.   If vector, then Y
;            must have the same number of elements as X
;            Positions are specified in device coordinates unless /DATA is set
;            If X and Y are not specified, and device has a cursor, then 
;            TVBOX will draw a box at current cursor position
;      COLOR - intensity value(s) (0 - !D.N_COLORS) used to draw the box(es)
;            If COLORS is a scalar then all boxes are drawn with the same
;            color value.   Otherwise, the Nth box is drawn with the
;            Nth value of color.    Default = !P.COLOR.    
; OUTPUTS:
;      None
;
; OPTIONAL KEYWORD INPUTS:
;      ANGLE - numeric scalar specifying the clockwise rotation of
;              the boxes or rectangles.
;      COLOR - Scalar or vector, overrides the COLOR input parameter
;      /DATA - if this keyword is set and non-zero, then the box width and
;             X,Y position center are interpreted as being in DATA 
;             coordinates.   Note that data coordinates must be previously
;             defined (e.g. with a PLOT or CONTOUR call).
;
;      Any keyword recognized by PLOTS is also recognized by TVBOX.   
;      In particular, the color, linestyle, and thickness of the boxes is 
;      controlled by the COLOR, LINESTYLE, and THICK keywords.     
; SIDE EFFECTS:
;       A square or rectangle will be drawn on the device
;       For best results WIDTH should be odd when using the default DEVICE
;       coordinates.  (If WIDTH is even, the actual size of the box will be 
;       WIDTH + 1, so that box remains centered.)
;
; EXAMPLES:
;       (1) Draw a double thick box of width 13, centered at 221,256 in the
;       currently active window
;
;           IDL> tvbox, 13, 221, 256, thick=2
;
;       (2) Overlay a "slit" with dimension 52" x 2" on a previously displayed
;           image at a position angle (East of North) of 32 degrees.    The 
;           slit is to be centered at XC, YC and the plate scale 
;           arcsec_per_pixel is known.
;
;           IDL> w = [2.,52.]/arcsec_per_pixel ;Convert slit size to pixel units
;           IDL> tvbox,w,XC,YC,ang=-32          ;Draw slit
; RESTRICTIONS:
;       (1) TVBOX does not check whether box is off the edge of the screen
;       (2) Allows use of only device (default) or data (if /DATA is set) 
;           coordinates.   Normalized coordinates are not allowed
; PROCEDURES USED:
;       ZPARCHECK
; REVISON HISTORY:
;       Written, W. Landsman   STX Co.           10-6-87
;       Modified to take vector arguments. Greg Hennessy Mar 1991
;       Fixed centering of odd width    W. Landsman    Sep. 1991
;       Let the user specify COLOR=0, accept vector color, W. Landsman Nov. 1995
;       Fixed typo in _EXTRA keyword  W. Landsman   August 1997
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Added ANGLE keyword    W.Landsman     February 2000 
;       Make sure ANGLE is a scalar   W. Landsman  September 2001

; NAME:
;     TVCIRCLE
; PURPOSE:
;     Draw circle(s) of specified radius at specified position(s)
; EXPLANATION: 
;     If a position is not specified, and device has a cursor, then a circle
;     is drawn at the current cursor position.
;
; CALLING SEQUENCE:
;     TVCIRCLE, rad, x, y, color, [ /DATA, /FILL, _EXTRA  =  ]         
;
; INPUTS:
;     RAD - radius of circle(s) to be drawn, positive numeric scalar
;
; OPTIONAL INPUT:
;      X - x position for circle center, vector or scalar
;      Y - y position for circle center, vector or scalar
;               If X and Y are not specified, and the device has a cursor, 
;               then program will draw a circle at the current cursor position
;      COLOR - intensity value(s) (0 - !D.N_COLORS) used to draw the circle(s)
;               If COLOR is a scalar then all circles are drawn with the same
;               color value.   Otherwise, the Nth circle is drawn with the
;               Nth value of color.    Default = !P.COLOR.    
;
; OPTONAL KEYWORD INPUTS:
;       /DATA - if this keyword is set and non-zero, then the circle width and
;              X,Y position center are interpreted as being in DATA 
;              coordinates.   Note that data coordinates must be previously
;              defined (with a PLOT or CONTOUR call).    TVCIRCLE will
;              internally convert to device coordinates before drawing the
;              circle, in order to maintain optimal smoothness.
;       /FILL  - If set, fill the circle using POLYFILL
;
;               Any keyword recognized by PLOTS (or POLYFILL if /FILL is set)
;               is also recognized by TVCIRCLE.   In particular, the color,
;               linestyle, and thickness of the circles are controlled by the 
;               COLOR, LINESTYLE, and THICK keywords.    If POLYFILL is set
;               then available keywords are LINE_FILL and FILL_PATTERN. 
; OUTPUTS:
;       None
;
; RESTRICTIONS:
;       (1) TVCIRCLE does not check whether it writes off of the edge of the 
;           display
;       (2) Some round-off error may occur when non-integral values are 
;           supplied for both the radius and the center coordinates
;       (3) TVCIRCLE does not accept /NORMAL coordinates, only data coordinates
;           (if /DATA is set) or device coordinates (the default)
;       (4) TVCIRCLE always draws a circle --- even if /DATA is set, and the
;           X and Y data scales are unequal.    (The X data scale is used to 
;           define the circle radius.)     If this is not the behaviour
;           you want, then use TVELLIPSE instead.
; EXAMPLE:
;       (1) Draw circles of radius 9 pixels at the positions specified by 
;           X,Y vectors, using double thickness lines
;
;           IDL> tvcircle, 9, x, y, THICK = 2
;
;           Now fill in the circles using the LINE_FILL method
;
;           IDL> tvcircle, 9, x, y, /FILL, /LINE_FILL
; METHOD:
;           The method used is that of Michener's, modified to take into account
;           the fact that IDL plots arrays faster than single points.   See
;           "Fundamental of Interactive Computer Graphics" by Foley and Van Dam"
;           p. 445 for the algorithm.
;
; REVISON HISTORY:
;           Original version   written by B. Pfarr  STX   10-88 
;           Major rewrite adapted from CIRCLE by Allyn Saroyan   LNLL
;           Wayne Landsman   STX     Sep. 91
;           Added DATA keyword   Wayne Landsman  HSTX    June 1993
;           Added FILL keyword.  R. S. Hill, HSTX, 4-Nov-1993
;           Always convert to device coords, add _EXTRA keyword, allow vector
;           colors.   Wayne Landsman, HSTX,  May 1995
;           Allow one to set COLOR = 0,   W. Landsman, HSTX, November 1995
;           Check if data axes reversed.  P. Mangifico, W. Landsman  May 1996
;           Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;      TVELLIPSE
;
; PURPOSE:
;      Draw an ellipse on the current graphics device.
;
; CALLING SEQUENCE:
;      TVELLIPSE, rmax, rmin, xc, yc, [ pos_ang, color, COLOR= ,/DATA, NPOINTS=
;                                        LINESTYLE=, THICK = 
; INPUTS:
;       RMAX,RMIN - Scalars giving the major and minor axis of the ellipse
; OPTIONAL INPUTS:
;       XC,YC - Scalars giving the position on the TV of the ellipse center
;               If not supplied (or if XC, YC are negative and /DATA is not set), 
;               and an interactive graphics device (e.g. not postscript) is set,
;               then the user will be prompted for X,Y
;       POS_ANG - Position angle of the major axis, measured counter-clockwise
;                 from the X axis.  Default is 0.
;       COLOR - Scalar  giving intensity level to draw ellipse.   The color
;               can be specified either with either this parameter or with the 
;               COLOR keyword.   Default is !P.COLOR
;
; OPTIONAL KEYWORD INPUT:
;        COLOR - Intensity value used to draw the circle, overrides parameter
;               value.  Default = !P.COLOR
;        /DATA - if this keyword is set and non-zero, then the ellipse radii and
;               X,Y position center are interpreted as being in DATA 
;               coordinates.   Note that the data coordinates must have been 
;               previously defined (with a PLOT or CONTOUR call).
;        THICK - Thickness of the drawn ellipse, default = !P.THICK
;        LINESTLYLE - Linestyle used to draw ellipse, default = !P.LINESTYLE
;        NPOINTS - Number of points to connect to draw ellipse, default = 120
;                  Increase this value to improve smoothness
; RESTRICTIONS:
;        TVELLIPSE does not check whether the ellipse is within the boundaries
;        of the window.
;
;        The ellipse is evaluated at NPOINTS (default = 120) points and 
;        connected by straight lines, rather than using the more sophisticated 
;        algorithm used by TVCIRCLE
;
;        TVELLIPSE does not accept normalized coordinates.
;
;        TVELLIPSE is not vectorized; it only draws one ellipse at a time
; EXAMPLE:
;        Draw an ellipse of major axis 50 pixels, minor axis 30 pixels, centered
;        on (250,100), with the major axis inclined 25 degrees counter-clockwise
;        from the X axis.   Use a double thickness line and device coordinates 
;        (default)
;
;	IDL> tvellipse,50,30,250,100,25,thick=2
; NOTES:
;        Note that the position angle for TVELLIPSE (counter-clockwise from the
;        X axis) differs from the astronomical position angle (counter-clockwise
;        from the Y axis). 
;
; REVISION HISTORY:
;        Written  W. Landsman STX          July, 1989            
;        Converted to use with a workstation.  M. Greason, STX, June 1990
;        LINESTYLE keyword, evaluate at 120 points,  W. Landsman HSTX Nov 1995
;        Added NPOINTS keyword, fixed /DATA keyword W. Landsman HSTX Jan 1996
;        Check for reversed /DATA coordinates  P. Mangiafico, W.Landsman May 1996
;        Converted to IDL V5.0   W. Landsman   September 1997
;        Work correctly when X & Y data scales are unequal  December 1998
;        Removed cursor input when -ve coords are entered with /data 
;        keyword set  P. Maxted, Keele, 2002

; NAME:
;      TVLASER
; PURPOSE:
;      Prints screen or image array onto a Postscript file or printer.
;      Information from FITS header is optionally used for labeling.  
;
; CALLING SEQUENCE:     
;      TVLASER, [header, Image, BARPOS = ,CARROWS =, CLABELS = ,/COLORPS, 
;             COMMENTS = ,CSIZE = ,CTITLE = , DX = , DY =, /ENCAP, FILENAME =
;             HEADER = ,/HELP, IMAGEOUT = ,/INTERP, /MAGNIFY, /NoCLOSE, 
;             /NoDELETE, /NO_PERS_INFO, /NoEIGHT, /NoPRINT, /NoRETAIN, 
;             /PORTRAIT, PRINTER = , /REVERSE, /SCALE, TITLE = , /TrueColor, 
;             XDIM=, XSTART=, YDIM=, YSTART=, BOTTOMDW=, NCOLORSDW= ]	
;
;       Note that the calling sequence was changed in May 1997
; OPTIONAL INPUTS: 
;       HEADER - FITS header string array.   Object and astrometric info from
;               the FITS header will be used for labeling, if available
;       IMAGE - if an array is passed through this parameter, then this image
;               will be used rather than reading off the current window.  This
;		allows easy use of large images.     It is usually preferable
;               to optimally byte scale IMAGE before supplying it to TVLASER   
;
; OPTIONAL KEYWORD INPUT PARAMETERS: 
;       BARPOS - A four- or five-element vector giving the position and
;            orientation of the color bar.  The first four elements
;            [X0,Y0,XSize,YSize] indicate the position and size of the color
;            bar in INCHES, relative to origin of the displayed image.
;            (X0,Y0) are the position of the lower left corner and 
;            (XSize,YSize) are the width and height.  The fifth element is
;            optional, and if present, the color bar will be printed
;            horizontally rather than vertically.  If BARPOS is set to
;            anything but a four- or five-element vector, the bar is NOT
;            printed.  The default value is BARPOS = [-0.25, 0.0, 0.2, 2.0] 
;       BOTTOMDW - The lowest value to use in building the density
;            wedge.  Used with NCOLORSDW.  Compatible with BOTTOM and
;            NCOLORS keywords of XLOADCT.
;       CARROWS - The color to print the North-East arrows.  Default is dark.
;            Three types of values can be passed:
;                 SCALAR: that value's color in the current color table
;                 3-ELEMENT VECTOR: the color will be [R,G,B]
;                 STRING: A letter indicating the color.  Valid names are:  
;                 'W' (white), 'D' (dark/black), 'R' (red),    'G' (green), 
;                 'B' (blue),  'T' (turquoise),  'V' (violet), 'Y' (yellow), 
;             If the keyword is set to a value of -1, the arrows are
;             NOT printed.
;       COLORPS - If present and non-zero, the idl.ps file is written using
;             color postscript.
;       COMMENTS - A string that will be included in the comment line below the
;                image.  For multi-line comments you can either use "!C" in the
;                string as a carriage return {although the vertical spacing
;                might be a little off} or, preferably, make the COMMENTS a
;                string array with each line as a separate element. 
;       CLABELS - Color to print the labels, same format as for CARROWS.
;       CSIZE - Color to print the size-scale bar and label, same format as for
;                CARROWS.
;       CTITLE - Color to print the title, same format as for CARROWS.
;       DX,DY - offsets in INCHES added to the position of the figure on the
;               paper.  As is the case for the device keywords XOFFSET and
;               YOFFSET, when in landscape mode DX and DY are the same
;               *relative to the paper*, not relative to the plot (e.g., DX is
;               the horizontal offset in portrait mode, but the *vertical*
;               offset in landscape mode).
;       ENCAP - If present and non-zero, the IDL.PS file is written in
;               encapsulated postscript for import into LaTeX documents
;       FILENAME - scalar string giving name of output postscript file.
;               Default is idl.ps.   Automatically sets /NODELETE
;       HEADER = FITS header.   This is an alternative to supplying the FITS
;                header in the first parameter.
;       HELP - print out the sytax for this procedure.
;       INTERP - If present and non-zero, current color table will be
;                interpolated to fill the full range of the PostScript color
;                table (256 colors).  Otherwise, the current color table will be
;                directly copied.   You probably will want to use this if you
;                are using IMAGE keyword and a shared color table.
;       MAGNIFY - The net magnification of the entire figure.  At this point,
;                the figure is not automatically centered on the paper if the
;                value of MAGNIFY is not equal to 1, but the DX and DY keywords
;                can be used to shift location.  For example, to fit a full plot
;                on the printable area (8.5x8.5 inches) of the Tek PhaserIISD
;                color printer use:  MAGNIFY=0.8, DX=0.5, DY=0.5.;       
;       NCOLORSDW - The number of values to include in the density
;                wedge.  Used with BOTTOMDW.  Compatible with
;                BOTTOM/NCOLORS keywords of XLOADCT.
;       NoCLOSE - If present and non-zero, then the postscript file is not
;             closed (or printed), the device is set to 'PS', and the data 
;             coordinate system is set to match the image size.  This allows the
;             user to add additional plotting commands before printing.  For 
;             example, to include a 15 pixel circle around a source at 
;             coordinates (150,160), around an image, im, with FITS header 
;             array, h
;
;                IDL> tvlaser,h,im,/NoClose      ;Write image & annotation
;                IDL> tvcircle,15,150,160,/data  ;Draw circle
;                IDL> device,/close              ;Close postscript file & print
;
;       NoDELETE - If present and non-zero, the postscript file is kept AND is 
;                 also sent to the printer
;       NoEIGHT - if set then only four bits sent to printer (saves space)
;       NO_PERS_INFO - if present and non-zero, output notation will NOT
;                 include date/user block of information.
;       NoPRINT - If present and non-zero, the output is sent to a file (default
;                name 'idl.ps'), which is NOT deleted and is NOT sent to the 
;                printer.
;       NoRETAIN - In order to avoid possible problems when using TVRD with
;                 an obscured window, TVLASER will first copy the current window
;                 to a temporary RETAIN=2 window.    Set /NORETAIN to skip this
;                 step and improve performance
;       PORTRAIT - if present and non-zero, the printer results will be in
;                 portrait format; otherwise, they will be in landscape format.
;                 If labels are requested, image will be in portrait mode,
;                 regardless
;       PRINTER - scalar string giving the OS command to send a the postscript
;               file to the printer.   Under Unix, the default value of PRINTER
;               is 'lpr ' while for other OS it is 'print ' 
;       REVERSE - if present and non-zero, color table will be fliped, so black
;               and white are reversed.
;       SCALE - if present and non-zero, image will be bytscaled before being
;               sent to postscript file.      
;       TITLE - if present and non-zero, the string entered here will be the
;               title of the picture.  Default is the OBJECT field in the
;               header (if present).
;       TRUECOLOR - if present and non-zero, the postscript file is created
;               using the truecolor switch (i.e. true=3). The colorbar is
;               not displayed in this mode.  
;       XDIM,YDIM - Number of pixels.  Default is from !d.x_size and !d.y_size,
;               or size of image if passed with IMAGE keyword.
;       XSTART,YSTART - lower left corner (default of (0,0))
;
; OPTIONAL KEYWORD OUTPUT PARAMETER
;        IMAGEOUT = the image byte array actually sent to the postscript file.
;
; SIDE EFFECTS: 
;        A postscript file is created in the current directory.  User must have 
;        write privileges in the current directory.  The file is named idl.ps
;        unless the FILENAME keyword is given.   The file is directed to the
;        printer unless the /ENCAP, /NoCLOSE, or /NOPRINT keywords are given.
;        After printing, the file is deleted unless the /NODELETE or FILENAME 
;        keywords are given. 
; PROCEDURE:  
;       Read display or take IMAGE and then redisplay into a postscript file.
;       If a header exists, printout header information.  If header has
;       astrometry, then print out orientation and scale information.
; PROCEDURES USED:
;        ARROWS, EXTAST, FDECOMP, GETROT, PIXCOLOR, SXPAR(), XYAD, ZPARCHECK
;
;*EXAMPLE:
;       1) Send a true color image (xsize,ysize,3) to a printer (i.e. print23l),
;                tvlaser,huv,cpic,/colorps,/truecolor,printer="print23l"
;                % TVLASER: Now printing image: $print23l idl.ps
;
; MODIFICATION HISTORY:     
;       Major rewrite from UIT version   W. Landsman   Dec 94
;       Massive rewrite.  Added North-East arrows, pixel scale bar, color bar,
;       and keywords DX, DY, MAGNIFY, INTERP, HELP, and COMMENTS.
;       Created ablility to define colors for annotation and
;       text.  Repositioned text labels.     J.Wm.Parker, HITC, 5/95
;       Make Header and Image parameters instead of keywords.   Add PRINTER
;       keyword.   Include alternate FITS keywords.   W. Landsman May 97      
;       Copy to a RETAIN=2 window, work without FITS header W. Landsman June 97
;       Cleaner output when no astrometry in header  W. Landsman  June 97
;       Added /INFO to final MESSAGE  W. Landsman   July 1997
;       12/4/97	jkf/acc	- added TrueColor optional keyword.
;       Added /NoClose keyword, trim Equinox format  W. Landsman 9-Jul-1998
;       Don't display coordinate labels if no astrometry, more flexible
;       formatting of exposure time W. Landsman 30-Aug-1998
;       BottomDW and NColorsDW added.  R. S. Hill, 1-Mar-1999
;       Apply func tab to color bar if not colorps.  RSH, 21 Mar 2000
;       Fix problem with /NOCLOSE and unequal X,Y sizes  W. Landsman Feb 2001
;       Use TVRD(True=3) if /TRUECOLOR set    W. Landsman   November 2001

; NAME:
;	TVLIST
; PURPOSE:
;	Cursor controlled listing of image pixel values in a window. 
;
; CALLING SEQUENCE:
;	TVLIST, [image, dx, dy, TEXTOUT=, OFFSET= , ZOOM= ]
;
; OPTIONAL INPUTS:
;	IMAGE - Array containing the image currently displayed on the TV.
;		If omitted, the byte pixel intensities are read from the TV
;		If the array does not start at position (0,0) on the window then
;		the OFFSET keyword should be supplied.
;
;	DX     -Integer scalar giving the number of pixels in the X direction 
;		to be displayed.  If omitted then DX = 18 for byte images, and 
;		DX = 14 for integer images.  TVLIST will display REAL data 
;		with more significant figures if more room is availble to 
;		print.  
;
;	DY    - Same as DX, but in Y direction.  If omitted, then DY = DX 
;
; OPTIONAL INPUT KEYWORDS:
;      OFFSET - 2 element vector giving the location of the image pixel (0,0) 
;		on the window display.   OFFSET can be positive (e.g if the 
;		image is centered in a larger window) or negative (e.g. if the
;		only the central region of an image much larger than the window
;		is being displayed. 
;		Default value is [0,0], or no offset.
;	ZOOM - Scalar specifying the magnification of the window with respect
;		to the image variable.    Use, for example, if image has been
;		REBINed before display.
;	TEXTOUT - Optional keyword that determines output device.
;		The following dev/file is opened for output.
;
;		textout=1	TERMINAL using /more option (default)
;		textout=2	TERMINAL without /more option
;		textout=3	.prt  
;		textout=4	laser.tmp
;		textout=5       user must open file
;		textout=7	Append to an existing .prt file if it
;				exists
;		textout = filename (default extension of .prt)
;
;	If TEXTOUT > 3 or set to a filename, then TVLIST will prompt for a 
;	brief description to be included in the output file
; OUTPUTS:
;	None.
; PROCEDURE:
;	Program prompts user to place cursor on region of interest in 
;	image display.  Corresponding region of image is then displayed at
;	the terminal.   A compression factor between the image array and the
;	displayed image is determined using the ratio of image sizes.  If 
;	necessary, TVLIST will divide all pixel values in a REAL*4 image by a 
;	(displayed) factor of 10^n (n=1,2,3...) to make a pretty format.
;
; SYSTEM VARIABLE:
;	The nonstandard system variable !TEXTOUT is used as an alternative to
;	the keyword TEXTOUT.   The procedure ASTROLIB can be used to define
;	!TEXTOUT (and !TEXTUNIT) if necessary.
;
; RESTRICTIONS:
;	TVLIST may not be able to correctly format all pixel values if the
;	dynamic range near the cursor position is very large.
;
;       Probably does not work under Mac IDL which does not allow the cursor
;       to be positioned with TVCRS
; PROCEDURES CALLED:
;	IMLIST, UNZOOM_XY
; REVISION HISTORY:
;	Written by rhc, SASC Tech, 3/14/86.
;	Added textout keyword option, J. Isensee, July, 1990
;	Check for readable pixels     W. Landsman   May 1992
;	Use integer format statement from F_FORMAT    W. Landsman   Feb 1994
;	Added OFFSET, ZOOM keywords  W. Landsman   Mar 1996
;	More intelligent formatting of longword, call TEXTOPEN with /STDOUT
;		W. Landsman  April, 1996
;	Added check for valid dx value  W. Landsman   Mar 1997
;	Converted to IDL V5.0   W. Landsman   September 1997
;       Major rewrite to call IMLIST, recognize new integer data types
;                                           W. Landsman Jan 2000
;       Remove all calls to !TEXTUNIT   W. Landsman   Sep 2000

; NAME:
;       T_APER
; PURPOSE:
;       Driver procedure (for APER) to compute concentric aperture photometry.
; EXPLANATION:
;       Data is read from and written to disk FITS ASCII tables.   
;       Part of the IDL-DAOPHOT photometry sequence
;
; CALLING SEQUENCE:
;       T_APER, image, fitsfile, [ apr, skyrad, badpix, PRINT=, NEWTABLE=, 
;                       /EXACT, /SILENT, SETSKYVAL = ]
;
; INPUTS:
;       IMAGE   - input data array
;       FITSFILE  - disk FITS ASCII table name (from T_FIND).  Must contain
;               the keywords 'X' and 'Y' giving the centroid of the source
;               positions in FORTRAN (first pixel is 1) convention.   An
;               extension of .fit is assumed if not supplied.
;
; OPTIONAL INPUTS:
;       User will be prompted for the following parameters if not supplied.
;
;       APR    -  Vector of up to 12 REAL photometry aperture radii.
;       SKYRAD  - Two element vector giving the inner and outer radii
;               to be used for the sky annulus
;       BADPIX  - Two element vector giving the minimum and maximum
;               value of a good pixel (Default [-32765,32767])
;
; OPTIONAL KEYWORDS INPUTS:
;       /EXACT - If this keyword is set, then intersection of the circular
;               aperture is computed exactly (and slowly) rather than using
;               an approximation.   See APER for more info.
;       /PRINT - if set and non-zero then NSTAR will also write its results to
;               a file aper.prt.   One can specify a different output file 
;               name by setting PRINT = 'filename'.
;       /SILENT - If this keyword is set and non-zero, then APER will not
;               display photometry results at the screen, and the results 
;               will be automatically incorporated in the FITS table without
;               prompting the user
;       NEWTABLE  - Name of output disk FITS ASCII table, scalar string.   
;               If not supplied, then the input FITSFILE will be updated with 
;               the aperture photometry results.
;       SETSKYVAL - Use this keyword to force the sky to a specified value 
;               rather than have APER compute a sky value.    SETSKYVAL 
;               can either be a scalar specifying the sky value to use for 
;               all sources, or a 3 element vector specifying the sky value, 
;               the sigma of the sky value, and the number of elements used 
;               to compute a sky value.   The 3 element form of SETSKYVAL
;               is needed for accurate error budgeting.
;
; PROMPTS:
;       T_APER requires the number of photons per analog digital unit
;       (PHPADU), so that it can compute Poisson noise statistics to assign
;       photometry errors.    It first tries to find the PHPADU keyword in the
;       original image header, and if not found will look for the GAIN, 
;       CCDGAIN and finally ATODGAIN keywords.   If still not found, T_APER 
;       will prompt the user for this value.
;
; PROCEDURES:
;       APER, FTADDCOL, FTGET(), FTINFO, FTPUT, READFITS(), SXADDPAR, 
;       SXPAR(), WRITEFITS 
; REVISON HISTORY:
;       Written   W. Landsman   ST Systems Co.            May 1988
;       Store results as flux or magnitude                August 1988
;       Added SILENT keyword  W. Landsman                 Sep. 1991
;       Changed ERR SKY to ERR_SKY W. Landsman   March 1996
;       Replace TEXTOUT keyword with PRINT keyword  W. Landsman  May 1996
;       Check CCDGAIN or ATODGAIN keywords to find phpadu W. Landsman May 1997
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Updated for new FTINFO calling sequence   W. Landsman  May 2000
;       Added /EXACT keyword                      W. Landsman  June 2000
;       

; NAME:
;        T_FIND
; PURPOSE:
;       Driver procedure (for FIND) to locate stars in an image.
; EXPLANATION:
;       Finds positive brightness perturbations (i.e stars) in a 
;       2 dimensional image.  Output is to a FITS ASCII table.
;
; CALLING SEQUENCE:
;       T_FIND, image, im_hdr, [ fitsfile, hmin, fwhm, sharplim, roundlim, 
;                                       PRINT = , /SILENT ]
; INPUTS:
;       image - 2 dimensional image array (integer or real) for which one
;               wishes to identify the stars present
;       im_hdr - FITS header associated with image array
;
; OPTIONAL INPUTS: 
;       T_FIND will prompt for these parameters if not supplied
;
;       fitsfile - scalar string specifying the name of the output FITS ASCII
;               table file
;       fwhm - FWHM to be used in the convolving filter
;       hmin - Threshold intensity for a point source - should generally
;               be 3 or 4 sigma above background level
;       sharplim - 2 element vector giving low and high Limit for 
;               sharpness statistic (Default: [0.2,1.0] )
;       roundlim - 2 element vector giving low and high Limit for
;               roundness statistic (Default: [-1.0,1.0] )
;
; OPTIONAL INPUT KEYWORDS:
;       /PRINT - if set and non-zero then NSTAR will also write its results to
;               a file find.prt.   One can specify the output file name by
;               setting PRINT = 'filename'.
;       /SILENT -   If this keyword is set and non-zero, then FIND will work
;               silently, and not display each star found
;
; OUTPUTS:
;       None
;
; PROCEDURES CALLED:
;       CHECK_FITS, FDECOMP, FIND, FTADDCOL, FTCREATE, SXADDHIST, SXADDPAR, 
;       SXDELPAR, SXPAR(), WRITEFITS
;
; REVISION HISTORY:
;       Written W. Landsman, STX  May, 1988
;       Added phpadu, J. Hill, STX, October, 1990
;       New calling syntax output to disk FITS table, W. Landsman    May 1996
;       Work with more than 32767 stars  W. Landsman August 1997
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Remove obsolete !ERR system variable   W. Landsman   May 2000

; NAME:
;       T_GETPSF
; PURPOSE:
;       Driver procedure (for GETPSF) to generate a PSF from isolate stars.
; EXPLANATION:
;       Generates a point-spread function from one or more isolated stars.
;       List of stars is read from the FITS ASCII table output of T_APER.
;       PSF is represented as a sum of a Gaussian plus residuals.
;       Ouput residuals are written to a FITS image file.
;
; CALLING SEQUENCE:
;       T_GETPSF, image, fitsfile, [ idpsf, psfrad, fitrad, psfname, 
;                                       /DEBUG, NEWTABLE =]
;
; INPUTS:
;       IMAGE - image array
;       FITSFILE  - scalar string giving name of disk FITS ASCII table.  Must 
;               contain the keywords 'X','Y' (from T_FIND) and 'AP1_MAG','SKY'
;               (from T_APER).
;
; OPTIONAL INPUTS:
;       IDPSF - vector of stellar ID indices indicating which stars are to be 
;               used to create the PSF.    Not that the PSF star should be 
;               specified *not* by its STAR_ID value, but rather by the its 
;               row number (starting with 0) in the FITS table
;       PSFRAD - the radius for which the PSF will be defined
;       FITRAD - fitting radius, always smaller than PSFRAD
;       PSFNAME - name of FITS image file to contain PSF residuals,
;               scalar string
;       GETPSF will prompt for all the above values if not supplied.
;
; OPTIONAL KEYWORD INPUT
;       NEWTABLE - scalar string specifying the name of the output FITS ASCII
;               table.   If not supplied, then the input table is updated with
;               the keyword PSF_CODE, specifying which stars were used for the
;               PSF.
;       DEBUG - if this keyword is set and non-zero, then the result of each
;               fitting iteration will be displayed.
;
; PROMPTS:
;       T_GETPSF will prompt for the readout noise (in data numbers), and
;       the gain (in photons or electrons per data number) so that pixels can
;       be weighted during the PSF fit.   To avoid the prompt, add the 
;       keywords RONOIS and PHPADU to the FITS ASCII table header.     
;
; PROCEDURES USED:
;       FTADDCOL, FTGET(), FTPUT, GETPSF, READFITS(), SXADDHIST, SXADDPAR, 
;       SXPAR(), WRITEFITS, ZPARCHECK
; REVISION HISTORY:
;       Written  W. Landsman     STX           May, 1988
;       Update PSF_CODE to indicate PSF stars in order used, W. Landsman Mar 96
;       I/O to FITS ASCII disk files  W. Landsman    May 96
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Update for new FTINFO call   W. Landsman   May 2000

; NAME:
;	T_GROUP
; PURPOSE:
;	Driver procedure (for GROUP) to place stars in non-overlapping groups.
; EXPLANATION:
;	This procedure is part of the DAOPHOT sequence that places star
;	positions with non-overlapping PSFs into distinct groups   
;	Input and output are to FITS ASCII tables
;
; CALLING SEQUENCE:
;	T_GROUP, fitsfile, [ rmax, XPAR = , YPAR = , NEWTABLE = ]
;
; INPUTS:
;	FITSFILE -  Name of disk FITS ASCII table containing the X,Y positions
;		in FITS (FORTRAN) convention (first pixel is 1,1)
;
; OPTIONAL INPUTS:
;	rmax - maximum allowable distance between stars in a single group
;
; OPTIONAL INPUT KEYWORDS:
;	XPAR, YPAR - scalar strings giving the field name in the output table
;		containing the X and Y coordinates.   If not supplied,
;		then the fields 'X' and 'Y' are read.
;	NEWTABLE - scalar giving name of output disk FITS ASCII table.   If not
;		supplied, 
;
; PROCEDURES:
;	FTADDCOL, FTGET(), FTINFO, FTPUT, GROUP, READFITS(), SXADDHIST, 
;	SXADDHIST, WRITEFITS
; REVISION HISTORY:
;	Written, W. Landsman        STX Co.      May, 1996
;	Converted to IDL V5.0   W. Landsman   September 1997
;       Updated for new FTINFO call    W. Landsman    May 2000

; NAME:
;       T_NSTAR
; PURPOSE:
;       Driver procedure (for NSTAR) for simultaneous PSF fitting.  
; EXPLANATION:
;       Input and output are to disk FITS ASCII tables.
;
; CALLING SEQUENCE:
;       T_NSTAR, image, fitsfile, [psfname, groupsel, /SILENT, /PRINT
;                               NEWTABLE = , /VARSKY ]
; INPUTS:
;       IMAGE - 2-d image array
;       FITSFILE  - scalar string giving name of disk FITS ASCII table.  Must 
;               contain the keywords 'X','Y' (from T_FIND) 'AP1_MAG','SKY'
;               (from T_APER) and 'GROUP_ID' (from T_GROUP).   This table
;               will be updated with the results of T_NSTAR, unless the 
;               keyword NEWTABLE is supplied.   
;
; OPTIONAL INPUTS:
;       PSFNAME - Name of the FITS file created by T_GETPSF containing
;               PSF residuals, scalar string
;       GROUPSEL - Scalar or vector listing the groups to process.  For
;               example, to process stars in groups 2 and 5 set
;               GROUPSEL = [2,5].  If omitted, or set equal to -1,
;               then NSTAR will process all groups.
;
; OPTIONAL KEYWORD INPUTS:
;       VARSKY - If this keyword is set and non-zero, then the mean sky level
;               in each group of stars, will be fit along with the brightness
;               and positions.
;       /SILENT - if set and non-zero, then NSTAR will not display its results
;               at the terminal
;       /PRINT - if set and non-zero then NSTAR will also write its results to
;               a file NSTAR.PRT.   One can specify the output file name by
;               setting PRINT = 'filename'.
;       NEWTABLE  - Name of output disk FITS ASCII table to contain the results
;               of NSTAR.   If not supplied, then the input FITSFILE will be 
;               updated.  
;       DEBUG - if this keyword is set and non-zero, then the result of each
;               fitting iteration will be displayed.
;
; PROCEDURES CALLED:
;       FTADDCAL, FTINFO, FTGET(), FTPUT, NSTAR, SXADDHIST, 
;       SXADDPAR, SXPAR(), READFITS(), WRITEFITS
; REVISION HISTORY:
;       Written        W. Landsman         STX Co.    May, 1988
;       Check for CCDGAIN, ATODGAIN keywords to get PHPADU  W. Landsman May 1997
;       Fixed typo preventing compilation, groupsel parameter W.L. July 1997
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Update for new FTINFO call    W. Landsman   May 2000

; NAME:
;       T_SUBSTAR
; PURPOSE:
;       Driver procedure (for SUBSTAR) to subtract scaled PSF values 
; EXPLANATION:
;       Computes residuals of the PSF fitting program
;
; CALLING SEQUENCE:
;       T_SUBSTAR, image, fitsfile, id,[ psfname, /VERBOSE, /NOPSF ]
;
; INPUT-OUTPUT:
;       IMAGE -  On input, IMAGE is the original image array.  A scaled
;               PSF will be subtracted from IMAGE at specified star positions.
;               Make a copy of IMAGE before calling SUBSTAR, if you want to
;               keep a copy of the unsubtracted image array
; INPUTS:
;       FITSFILE  - scalar string giving the name of the disk FITS ASCII 
;               produced as an output from T_NSTAR.   
;
; OPTIONAL INPUTS:
;       ID -  Index vector indicating which stars are to be subtracted.  If
;               omitted, (or set equal to -1), then stars will be subtracted 
;               at all positions specified by the X and Y vectors.
;               (IDL convention - zero-based subscripts)
;       PSFNAME - Name of the FITS file containing the PSF residuals, as
;               generated by GETPSF.  SUBSTAR will prompt for this parameter
;               if not supplied.      
; OPTIONAL INPUT KEYWORD:
;       /VERBOSE - If this keyword is set and non-zero, then the value of each
;               star number will be displayed as it is processed.
;       /NOPSF - if this keyword is set and non-zero, then all stars will be 
;               be subtracted *except* those used to determine the PSF.
;               An improved PSF can then be derived from the subtracted image.
;               If NOPSF is supplied, then the ID parameter is ignored
; NOTES:
;       T_SUBSTAR does not modify the input FITS table.
;
; PROCEDURES USED:
;       FTGET(), FTINFO, READFITS(), REMOVE, SUBSTAR
; REVISION HISTORY:
;       Written, R. Hill, ST Sys. Corp., 22 August 1991
;       Added NOPSF keyword   W. Landsman        March, 1996
;       Use FITS format for PSF resduals         July, 1997
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Call FTINFO first to improve efficiency   W. Landsman  May 2000

; NAME:
;      UNZOOM_XY
; PURPOSE:
;      Converts X, Y position on the image display to the the X,Y position 
;      on the corresponding image array.  (These  positions are identical 
;      only for an unroamed, unzoomed image with with pixel (0,0) of the 
;      image placed at position (0,0) on the TV.)
;
; CALLING SEQUENCE:
;      UNZoom_XY, Xtv,Ytv,Xim,Yim, [ OFFSET =, ZOOM = ]   
;
; INPUTS:
;      XTV - Scalar or vector giving X position(s) as read on the image
;            display (e.g. with CURSOR,XTV,YTV,/DEVICE)
;      XTV - Scalar or vector giving Y position(s) on the image display.
;      If only 2 parameters are supplied then XTV and YTV will be modfied
;      on output to contain the image array coordinates.
;
; OPTIONAL KEYWORD INPUT:
;      OFFSET - 2 element vector giving the location of the image pixel (0,0) 
;               on the window display.   OFFSET can be positive (e.g if the 
;               image is centered in a larger window) or negative (e.g. if the
;               only the central region of an image much larger than the window
;               is being displayed. 
;               Default value is [0,0], or no offset.
; OUTPUTS:
;      XIM,YIM - X and Y coordinates of the image corresponding to the
;            cursor position on the TV display.
; NOTES:
;       The integer value of a pixel is assumed to refer to the *center*
;       of a pixel.
; REVISON HISTORY:
;       Adapted from MOUSSE procedure  W. Landsman       March 1996
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Proper handling of offset option          S. Ott/W. Landsman May 2000

; NAME:
;       UVBYBETA
; PURPOSE:
;       Derive dereddened colors, metallicity, and Teff from Stromgren colors.
; EXPLANATION:
;       Adapted from FORTRAN routine of same name published by T.T. Moon, 
;       Communications of University of London Observatory, No. 78. Parameters 
;       can either be input interactively (with /PROMPT keyword) or supplied 
;       directly.   
;
; CALLING SEQUENCE:
;       uvbybeta, /PROMPT               ;Prompt for all parameters
;       uvbybeta,by,m1,c1,Hbeta,n        ;Supply inputs, print outputs
;       uvbybeta, by, m1, c1, Hbeta, n, Te, Mv, Eby, delm0, radius, 
;                       [ TEXTOUT=, Eby_in =, Name =  ]
;
; INPUTS:
;       by - Stromgren b-y color, scalar or vector
;       m1 - Stromgren line-blanketing parameter, scalar or vector
;       c1 - Stromgren Balmer discontinuity parameter, scalar or vector
;       Hbeta - H-beta line strength index.  Set  Hbeta to 0 if it is not 
;            known, and UVBYBETA will estimate a value based on by, m1,and c1.
;            Hbeta is not used for stars in group 8.
;       n -  Integer (1-8), scalar or vector,  giving approximate stellar 
;            classification
;
;       (1) B0 - A0, classes III - V, 2.59 < Hbeta < 2.88,-0.20 <   c0  < 1.00
;       (2) B0 - A0, class   Ia     , 2.52 < Hbeta < 2.59,-0.15 <   c0  < 0.40
;       (3) B0 - A0, class   Ib     , 2.56 < Hbeta < 2.61,-0.10 <   c0  < 0.50
;       (4) B0 - A0, class   II     , 2.58 < Hbeta < 2.63,-0.10 <   c0  < 0.10
;       (5) A0 - A3, classes III - V, 2.87 < Hbeta < 2.93,-0.01 < (b-y)o< 0.06
;       (6) A3 - F0, classes III - V, 2.72 < Hbeta < 2.88, 0.05 < (b-y)o< 0.22
;       (7) F1 - G2, classes III - V, 2.60 < Hbeta < 2.72, 0.22 < (b-y)o< 0.39
;       (8) G2 - M2, classes  IV _ V, 0.20 < m0   < 0.76, 0.39 < (b-y)o< 1.00
;
;
; OPTIONAL INPUT KEYWORD:
;       Eby_in - numeric scalar specifying E(b-y) color to use.   If not
;             supplied, then E(b-y) will be estimated from the Stromgren colors
;       NAME - scalar or vector string giving name(s) of star(s).  Used only 
;               when writing to  disk for identification purposes.
;       /PROMPT - if set, then uvbybeta.pro will prompt for Stromgren indicies
;                interactively
;       TEXTOUT  -  Used to determine output device.  If not present, the
;               value of the !TEXTOUT system variable is used (see TEXTOPEN)
;               textout=1       Terminal with /MORE (if a tty)
;               textout=2       Terminal without /MORE
;               textout=3       uvbybeta.prt   (output file)
;               textout=4       Laser Printer 
;               textout=5       User must open file         
;               textout=7       Append to existing uvbybeta.prt file
;               textout = filename (default extension of .prt)
;      /PRINT - if set, then force display output information to the device 
;               specified by !TEXTOUT.    By default, UVBYBETA does not display
;               information if output variables are supplied (and TEXTOUT is
;               not set). 
;
; OPTIONAL OUTPUTS:
;       Te - approximate effective temperature
;       MV - absolute visible magnitude
;       Eby - Color excess E(b-y)
;       delm0 - metallicity index, delta m0, (may not be calculable for early
;               B stars).
;       radius - Stellar radius (R/R(solar))
; EXAMPLE:
;       Suppose 5 stars have the following Stromgren parameters
;
;       by = [-0.001 ,0.403, 0.244, 0.216, 0.394 ]
;       m1 = [0.105, -0.074, -0.053, 0.167, 0.186 ]
;       c1 = [0.647, 0.215, 0.051, 0.785, 0.362] 
;       hbeta = [2.75, 2.552, 2.568, 2.743, 0 ]
;       nn = [1,2,3,7,8]              ;Processing group number
;
;       Determine stellar parameters and write to a file uvbybeta.prt
;       IDL> uvbybeta, by,m1,c1,hbeta, nn, t=3
;            ==> E(b-y) = 0.050    0.414   0.283  0.023  -0.025
;                Teff =   13060    14030   18420  7250    5760
;                M_V =    -0.27    -6.91   -5.94  2.23    3.94
;                radius=  2.71     73.51    39.84 2.02    1.53
; SYSTEM VARIABLES:
;       The non-standard system variables !TEXTOUT and !TEXTUNIT will be  
;       automatically defined if they are not already present.   
;
;       DEFSYSV,'!TEXTOUT',1
;       DEFSYSV,'!TEXTUNIT',0
;
; NOTES:
;       (1) **This procedure underwent a major revision in January 2002
;       and the new calling sequence may not be compatible with the old** (NAME
;       is now a keyword rather than a parameter.)
;
;       (2) Napiwotzki et al. (1993, A&A, 268, 653) have written a FORTRAN
;           program that updates some of the Moon (1985) calibrations.  These
;           updates are *not* included in this IDL procedure.
; PROCEDURES USED:
;       DEREDD, TEXTOPEN, TEXTCLOSE
; REVISION HISTORY:                                           
;       W. Landsman          IDL coding              February, 1988
;       Keyword textout added, J. Isensee, July, 1990
;       Made some constants floating point.   W. Landsman    April, 1994
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Added Eby_in, /PROMPT keywords, make NAME a keyword and not a parameter
;                 W. Landsman      January 2002

; NAME:
;	VACTOAIR
; PURPOSE:
;	Convert vacuum wavelengths to air wavelengths
; EXPLANATION:
;	Corrects for the index of refraction of air under standard conditions.  
;	Wavelength values below 2000 A will not be altered.  Accurate to 
;	about 0.005 A 
;
; CALLING SEQUENCE:
;	VACTOAIR, WAVE
;
; INPUT/OUTPUT:
;	WAVE - Wavelength in Angstroms, scalar or vector
;		WAVE should be input as vacuum wavelength(s), it will be
;		returned as air wavelength(s).  WAVE is always converted to
;		double precision
;
; EXAMPLE:
;	If the vacuum wavelength is  W = 2000, then 
;
;	IDL> VACTOAIR, W 
;
;	yields an air wavelength of W = 1999.353 Angstroms
;
; METHOD:
;	An approximation to the 4th power of inverse wavenumber is used
;	See IUE Image Processing Manual   Page 6-15.
;
; REVISION HISTORY
;	Written, D. Lindler 1982 
;	Documentation W. Landsman  Feb. 1989
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME: 
;     VALID_NUM
; PURPOSE:               
;     Check if a string is a valid number representation.
; EXPLANATION:              
;     The input string is parsed for characters that may possibly
;     form a valid number.  It is more robust than simply checking
;     for an IDL conversion error because that allows strings such
;     as '22.3qwert' to be returned as the valid number 22.3
;     See also the original NUM_CHK which returns the status in 
;     the opposite sense.
;
; CALLING SEQUENCE: 
;     IDL> status = valid_num(string  [,value]  [,/integer])
;    
; Inputs      : string  -  the string to be tested
;               
; Opt. Inputs : None
;               
; Outputs     : The function returns 1 for valid, 0 for invalid number
;               
; Opt. Outputs: value	- The value the string decodes to.  This will be
;			  returned as a double precision number unless /INTEGER
;			  is present, in which case a long integer is returned.
;               
; Keywords    : Integer   -  if present code checks specifically for an integer.
;
; Calls       : None
;               
; Restrictions: None
;               
; Category    : Utilities, Numerical
;               
; Prev. Hist. : Small changes from NUM_CHK by Andrew Bowen, 
;                                             Tessella Support Services, 8/3/93
;
; Written     : CDS version by C D Pike, RAL, 24-May-93
;               
; Modified    : Version 1, C D Pike, RAL, 24-May-93
;		Version 2, William Thompson, GSFC, 14 October 1994
;			Added optional output parameter VALUE to allow
;			VALID_NUM to replace STRNUMBER in FITS routines.
;
; Version     : Version 1  24-May-93
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;   VALUE_LOCATE
;
; AUTHOR:
;   Craig B. Markwardt, NASA/GSFC Code 662, Greenbelt, MD 20770
;   craigm@lheamail.gsfc.nasa.gov
;
; PURPOSE:
;
;   Locate one or more values in a reference array (IDL LE 5.2 compatibility)
;
; CALLING SEQUENCE:
;
;   INDICES = VALUE_LOCATE(REF, VALUES)
;
; DESCRIPTION: 
;
;   VALUE_LOCATE locates the positions of given values within a
;   reference array.  The reference array need not be regularly
;   spaced.  This is useful for various searching, sorting and
;   interpolation algorithms.
;
;   The reference array should be a monotonically increasing or
;   decreasing list of values which partition the real numbers.  A
;   reference array of NBINS numbers partitions the real number line
;   into NBINS+1 regions, like so:
;
;
; REF:           X[0]         X[1]   X[2] X[3]     X[NBINS-1]
;      <----------|-------------|------|---|----...---|--------------->
; INDICES:  -1           0          1    2       3        NBINS-1
;
;
;   VALUE_LOCATE returns which partition each of the VALUES falls
;   into, according to the figure above.  For example, a value between
;   X[1] and X[2] would return a value of 1.  Values below X[0] return
;   -1, and above X[NBINS-1] return NBINS-1.  Thus, besides the value
;   of -1, the returned INDICES refer to the nearest reference value
;   to the left of the requested value.
;
;   If the reference array is monotonically decreasing then the
;   partitions are numbered starting at -1 from the right instead (and
;   the returned INDICES refer to the nearest reference value to the
;   *right* of the requested value).  If the reference array is
;   neither monotonically increasing or decreasing the results of
;   VALUE_LOCATE are undefined.
;
;   VALUE_LOCATE appears as a built-in function in IDL v5.3 and later.
;   This version of VALUE_LOCATE should work under IDL v4 and later,
;   and is intended to provide a portable solution for users who do
;   not have the latest version of IDL.  The algrorithm in this file
;   is slower but not terribly so, than the built-in version.
;
;   Users should be able to place this file in their IDL path safely:
;   under IDL 5.3 and later, the built-in function will take
;   precedence; under IDL 5.2 and earlier, this function will be used.
;
; INPUTS:
;
;   REF - the reference array of monotonically increasing or
;         decreasing values.
;
;   VALUES - a scalar value or array of values to be located in the
;            reference array.
;
;
; KEYWORDS:
;
;   L64 - (ignored) for compatibility with built-in version. 
;
;   NO_CROP - if set, and VALUES is outside of the region between X[0]
;             and X[NBINS-1], then the returned indices may be *less
;             than* -1 or *greater than* NBINS-1.  The user is the
;             responsible for cropping these values appropriately.
;
; RETURNS:
;
;   An array of indices between -1L and NBINS-1.  If VALUES is an
;   array then the returned array will have the same dimensions.
;
;
; EXAMPLE:
;
;   Cast random values into a histogram with bins from 1-10, 10-100,
;   100-1000, and 1000-10,000.
;
;     ;; Make bin edges - this is the ref. array
;     xbins = 10D^dindgen(5)  
;
;     ;; Make some random data that ranges from 1 to 10,000
;     x     = 10D^(randomu(seed,1000)*4)
;
;     ;; Find the bin number of each random value
;     ii    = value_locate(xbins, x)
;
;     ;; Histogram the data
;     hh    = histogram(ii)
;
;
; SEE ALSO:
;
;   VALUE_LOCATE (IDL 5.3 and later), HISTOGRAM, CMHISTOGRAM
;
;
; MODIFICATION HISTORY:
;   Written and documented, 21 Jan 2001
;   Case of XBINS having only one element, CM, 29 Apr 2001
;   Handle case of VALUES exactly hitting REF points, CM, 13 Oct 2001
; 
;  $Id: value_locate.pro,v 1.5 2001/10/13 17:59:34 craigm Exp $
;

; NAME:
;	VECT
; PURPOSE:
;	Print a set of numbers as a string with delimiters included
; EXPLANATION:
;	This function returns the given vector in parenthesized coordinates
;	as in the form (X,Y).  No limit on the number of dimensions.  Also
;	note that the vector does not need to be numbers.  It may also be a
;	string vector.  e.g. ['X','Y']
;
; CALLING SEQEUNCE:
;	tmp = VECT( vctr, [ form, FORMAT = , DELIM =  ] )
; INPUT:
;	VCTR      The vector to be displayed  e.g. [56,44]
;
; OPTIONAL KEYWORD INPUT:
;	FORMAT    This KEYWORD allows the specification of a format for the
;		elements.  e.g.: VECT([2,3],format='(f7.1)') gives '(2.0,3.0)'
;	DELIM     This KEYWORD specifies the delimeter.  The default is ',' but
;		other useful examples might be ', ' or ':'
;
; OPTIONAL INPUT
;	FORM      This parameter may be used instead of the keyword FORMAT
;
; OUTPUT:
;	tmp       A returned string of the parenthesized vector
;
; Other Procedures/Functions Called:
;	STRN
;
; HISTORY:
;	03-JUL-90 Version 1 written by Eric W. Deutsch
;	24-AUG-91 Format='' keyword added (E. Deutsch)
;	29-AUG-91 FORM parameter added (E. Deutsch)
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;       VSYM
;
; PURPOSE:
;       Create "Mongo"-like polygonal plot symbols
; EXPLANATION:
;       This procedure generates a subset of Mongo-like plot symbols.
;       The symbols are the rotationally symmetric ones that have
;       a specified number of vertices and are either open or filled.
;       (The half-filled symbols are not included.)     After defining the
;       plot symbol with VSYM, make the call to PLOT (or PLOTS or OPLOT) with 
;       PSYM=8.
;
; CATEGORY:
;       Graphics
;
; CALLING SEQUENCE:
;       VSYM, Nvert
;
; INPUT POSITIONAL PARAMETERS:
;       Nvert:     Number of vertices in plot symbol.  Maximum value
;                  used is 24.
;
; INPUT KEYWORD PARAMETERS:
;       STAR:      Set this flag to get a star.  E.g., 
;                  vsym, 5,/star gets you a pentagram.
;       SKELETON:  Set this flag to get an asterisk-like symbol, where
;                  the center is connected to each vertex.  E.g.,
;                  vsym, 4, /skel gets you an X.
;       POLYGON:   Set this flag to get a regular polygon.  This is
;                  the default symbol type.
;       FILL:      Set this flag to get filled symbol.  Default=open
;       ROT:       Rotation of symbol about center, in degrees.
;                  E.g., vsym, 4, rot=45 gets you a diamond, whereas
;                  vsym, 4 gets you a square.
;       THICK:     Line thickness of symbol.  Default=!P.thick
;
; MODIFICATION HISTORY:
;       Written by:     R. S. Hill, RITSS, 2 Oct 98

; NAME:
;     WCSSPH2XY 
; PURPOSE:
;     Convert spherical coordinates to x and y (map) angular coordinates
; EXPLANATION:
;     Convert spherical (longitude and latitude -- sky) coordinates to x 
;     and y (map) angular coordinates.  This procedure is the inverse of 
;     WCSXY2SPH.    See WCS_DEMO for example of use.
;
;     This is a lower level procedure -- given a FITS header, the user will 
;     usually use ADXY which will then call WCSSPH2XY with the appropriate 
;     parameters.
; CATEGORY:
;     Mapping and Auxiliary FITS Routine
;
; CALLING SEQUENCE:
;      wcssph2xy, longitude, latitude, x, y, [ map_type , CTYPE = ,
;               FACE =,PROJP1 = , PROJP2= , CRVAL = , CRXY = , LONGPOLE = ,
;               LATPOLE = , NORTH_OFFSET =, SOUTH_OFFSET =, BADINDEX =]
;
; INPUT PARAMETERS:
;     longitude - longitude of data, scalar or vector, in degrees 
;     latitude - latitude of data, same number of elements as longitude, 
;               in degrees
;     map_type - optional positional parameter, numeric scalar (0-25) 
;               corresponding to a particular map projection.  This is not a 
;               FITS standard, it is simply put in to allow function similar 
;               to that of less general map projection procedures (eg AITOFF).
;               The following list gives the map projection types and their 
;               respective numbers.
;
;  FITS  Number  Name                       Comments
;  code   code
;  ----  ------  -----------------------    -----------------------------------
;   DEF     0    Default = Cartesian
;   AZP     1    Zenithal perspective       projp1 required
;   TAN     2    Gnomic                     AZP w/ projp1 = 0
;   SIN     3    Orthographic               AZP w/ projp1 = Infinity (>10^14)
;   STG     4    Stereographic              AZP w/ projp1 = 1
;   ARC     5    Zenithal Equidistant
;   ZPN     6    Zenithal polynomial        prop1-projp9 required, useless
;   ZEA     7    Zenithal equal area
;   AIR     8    Airy                       projp1 required
;   CYP     9    Cylindrical perspective    projp1 and projp2 required
;   CAR    10    Cartesian
;   MER    11    Mercator
;   CEA    12    Cylindrical equal area     projp1 required
;   COP    13    Conical perspective        projp1 and projp2 required
;   COD    14    Conical equidistant        projp1 and projp2 required
;   COE    15    Conical equal area         projp1 and projp2 required
;   COO    16    Conical orthomorphic       projp1 and projp2 required
;   BON    17    Bonne's equal area         projp1 required
;   PCO    18    Polyconic
;   SFL    19    Sanson-Flamsteed
;   PAR    20    Parabolic
;   AIT    21    Hammer-Aitoff
;   MOL    22    Mollweide
;   CSC    23    Cobe Quadrilateralized     convergence of inverse is poor
;                Spherical Cube
;   QSC    24    Quadrilateralized 
;                Spherical Cube
;   TSC    25    Tangential Spherical Cube
;
; OPTIONAL INPUT KEYWORD PARAMETERS:
;
;     CTYPE - One, two, or three element vector containing 8 character 
;              strings corresponding to the CTYPE1, CTYPE2, and CTYPE3 
;              FITS keywords: 
;
;               CTYPE[0] - first four characters specify standard system
;               ('RA--','GLON' or 'ELON' for right ascension, Galactic 
;               longitude or ecliptic longitude respectively), second four 
;               letters specify the type of map projection (eg '-AIT' for 
;               Aitoff projection)
;               CTYPE[1] - first four characters specify standard system
;               ('DEC-','GLAT' or 'ELAT' for declination, galactic latitude
;               or ecliptic latitude respectively; these must match 
;               the appropriate system of ctype1), second four letters of 
;               ctype2 must match second four letters of ctype1.
;               CTYPE[2] - if present must be the 8 character string,'CUBEFACE',
;                only used for spherical cube projections to identify an axis 
;               as containing the face on which each x and y pair of 
;               coordinates lie.
;       PROJP1 - scalar with first projection parameter, this may
;               or may not be necessary depending on the map projection used
;       PROJP2 - scalar with second projection parameter, this may
;               or may not be necessary depending on the map projection used
;       CRVAL - 2 element vector containing standard system coordinates (the 
;               longitude and latitude) of the reference point
;       CRXY - 2 element vector giving the x and y coordinates of the 
;               reference point, if this is not set the offset is [0,0]
;               This is not a FITS standard -- it is similar to CRPIX but in 
;               angular X,Y coordinates (degrees) rather than pixel coordinates
;       LATPOLE -  native latitude of the standard system's North Pole
;       LONGPOLE - native longitude of standard system's North Pole, default
;               is 180 degrees for Zenithal systems
;       NORTH_OFFSET - offset (radians) added to input points near north pole.
;       SOUTH_OFFSET - offset (radians) added to input points near south pole.
;       BADINDEX     - vector, list of transformed points too close to poles.
;
;
; OUTPUT PARAMETERS:
;
;       x - x coordinate of data, same number of elements as longitude, in 
;               degrees; if CRXY is set, then x will be returned offset by 
;               crxy(0).  NOTE: x in all map projections increases to the 
;               left, not the right.
;       y - y coordinate of data, same number of elements as longitude, in 
;               degrees; if CRXY is set, y will be returned offset by crxy[1]
;       bad - vector returning index to transformed points close to pole.
;
; OPTIONAL OUTPUT KEYWORD PARAMETERS:
;       FACE - a output variable used for spherical cube projections to 
;               designate the face of the cube on which the x and y 
;               coordinates lie.   Will contain the same number of elements as
;               X and Y.    Must contain at least 1 arbitrary element on input
;               If FACE is NOT defined on input, it is assumed that the
;               spherical cube projection is laid out over the whole sky
;               in the "sideways T" configuration.
; NOTES:
;       The conventions followed here are described in more detail in 
;       "Representations of Celestial Coordinates in FITS" by Mark Calabretta
;       and Eric Greisen (2002, A&A, 395, 1077; also  see  
;       http://www.aoc.nrao.edu/~egreisen).  The general 
;       scheme outlined in that article is to first use WCS_ROTATE to convert 
;       coordinates in one of three standard systems (celestial, galactic, 
;       or ecliptic) into a "native system" of latitude and longitude.  The 
;       latitude and longitude are then converted into x and y coordinates 
;       which depend on the map projection which is performed.   The rotation 
;       from standard to native coordinates can be skipped if one so desires.
;       This procedure necessitates two basic sections.  The first converts 
;       "standard" coordinates to "native" coordinates while the second converts
;       "native" coordinates to x and y coordinates.  The first section is 
;       simply a call to WCS_ROTATE, while the second contains the guts of 
;       the code in which all of the map projection is done.  This procedure 
;       can be called in a form similar to AITOFF, EQPOLE, or QDCB by calling 
;       wcssph2xy with a fifth parameter specifying the map projection by 
;       number and by not using any of the keywords related to the map 
;       projection type (e.g. CTYPE).
;
; PROCEDURE:
;
;       The first task of the procedure is to do general error-checking to 
;       make sure the procedure was called correctly and none of the 
;       parameters or keywords conflict.  This is particularly important 
;       because the procedure can be called in two ways (either using 
;       FITS-type keywords or using a number corresponding to a map projection
;       type).  All variables are converted into double precision values and 
;       angular measurements are converted from degrees into radians.
;       If necessary, longitude values are converted into the range -pi to pi.
;       Any latitude points close to the  of the poles are mapped to a specific
;       latitude of  from the pole so that the map transformations become
;       completely invertible.  The magnitude of this correction is given by 
;       the keywords NORTH_OFFSET and SOUTH_OFFSET and a list of affected 
;       points is optionally returned in the "badindex" output parameter.
;       The next task of the procedure is to convert the "standard" 
;       coordinates to "native" coordinates by rotating the coordinate system.
;       This rotation is performed by the procedure WCS_ROTATE and is governed
;       by the keywords CRVAL and LONGPOLE.   The final task of the WCSSPH2XY 
;       is to take "native" latitude and longitude coordinates and convert 
;       them into x and y coordinates.  Any map specific error-checking is 
;       done at this time.  All of the equations were obtained from 
;       "Representations of Celestial Coordinates in FITS" and cases needing 
;       special attention are handled appropriately (see the comments with 
;       individual map projections for more information on special cases). 
;
;       Note that a further transformation (using the CD matrix) is required
;       to convert the (x,y) coordinates to pixel coordinates. 
; COMMON BLOCKS:
;
;       none
;
; PROCEDURES CALLED:
;       WCS_ROTATE
;
; COPYRIGHT NOTICE:
;
;       Copyright 1993, The Regents of the University of California. This
;       software was produced under U.S. Government contract (W-7405-ENG-36)
;       by Los Alamos National Laboratory, which is operated by the
;       University of California for the U.S. Department of Energy.
;       The U.S. Government is licensed to use, reproduce, and distribute
;       this software. Neither the Government nor the University makes
;       any warranty, express or implied, or assumes any liability or
;       responsibility for the use of this software.
;
; AUTHOR:
;
;       Rick Balsano
;
; MODIFICATIONS/REVISION LEVEL:
;
;       1.1     8/31/93
;       2.3     9/15/93  W. Landsman (HSTX) Update quad cube coords, vectorize
;                        keywords
;       2.4     12/29/93 I. Freedman (HSTX) Eliminated LU decomposition
;       2.5     1/5/93   I. Freedman (HSTX) Offset keywords / bad point index
;       2.6     Dec 94   Compute pole for transformations where the reference
;                       pixel is at the native origin    W. Landsman (HSTX)
;       2.7     May 95  Change internal variable BETA for V4.0 compatibility
;       2.8     June 95 Change loop indices from integer to long
;       2.9     3/18/96 Change FACE usage for cube projections to match WCSLIB
;                       C/FORTRAN software library.
;       Converted to IDL V5.0   W. Landsman   September 1997
;       2.10    02/18/99 Fixed implementation of ARC algorithm
;       2.11    June 2003 Update conic projections, add LATPOLE keyword
;	2.12	Aug 2003, N.Rich - Fix pre-V5.5 bug from previous update
;       2.13    Sep 2003, W. Landsman CTYPE keywords need not be 8 characters

; NAME:
;      WCSXY2SPH  
;
; PURPOSE:
;      Convert x and y (map) coordinates to spherical coordinates
; EXPLANATION:
;      To convert x and y (map) coordinates to spherical (longitude and 
;      latitude or sky) coordinates.    This procedure is the inverse of
;      WCSSPH2XY.
;
;     This is a lower level procedure -- given a FITS header, the user will 
;     usually use XYAD which will then call WCSXY2SPH with the appropriate 
;     parameters.
; CATEGORY:
;      Mapping and Auxilary FITS Routine
;
; CALLING SEQUENCE:
;
;      wcsxy2sph, x, y, longitude, latitude, [map_type], [ CTYPE = ,$
;             FACE = ,PROJP1 = , PROJP2 = ,CRVAL =, CRXY =, LONGPOLE=, LATPOLE=]
;
; INPUT PARAMETERS:
;
;       x - x coordinate of data, scalar or vector, in degrees, NOTE: x 
;               increases to to the left, not the right
;       y - y coordinate of data, same number of elements as x, in degrees
;       map_type - optional positional parameter, scalar corresponding to a 
;               particular map projection.  This is not a FITS standard, it is 
;               simply put in to allow function similar to that of less general 
;               map projection procedures (eg AITOFF).  The following list gives
;               the map projection types and their respective numbers.
;
;  FITS  Number  Name                       Comments
;  code   code
;  ----  ------  -----------------------    -----------------------------------
;   DEF     0    Default = Cartesian
;   AZP     1    Zenithal perspective       projp1 required
;   TAN     2    Gnomic                     AZP w/ projp1 = 0
;   SIN     3    Orthographic               AZP w/ projp1 = Infinity (>10^14)
;   STG     4    Stereographic              AZP w/ projp1 = 1
;   ARC     5    Zenithal Equidistant
;   ZPN     6    Zenithal polynomial        prop1-projp9 required, useless
;   ZEA     7    Zenithal equal area
;   AIR     8    Airy                       projp1 required
;   CYP     9    Cylindrical perspective    projp1 and projp2 required
;   CAR    10    Cartesian
;   MER    11    Mercator
;   CEA    12    Cylindrical equal area     projp1 required
;   xy    13    Conical perspective        projp1 and projp2 required
;   COD    14    Conical equidistant        projp1 and projp2 required
;   COE    15    Conical equal area         projp1 and projp2 required
;   COO    16    Conical orthomorphic       projp1 and projp2 required
;   BON    17    Bonne's equal area         projp1 required
;   PCO    18    Polyconic
;   SFL    19    Sanson-Flamsteed
;   PAR    20    Parabolic
;   AIT    21    Hammer-Aitoff
;   MOL    22    Mollweide
;   CSC    23    Cobe Quadrilateralized     inverse converges poorly
;                Spherical Cube
;   QCS    24    Quadrilateralized
;                Spherical Cube
;   TSC    25    Tangential Spherical Cube
;
; OPTIONAL KEYWORD PARAMETERS:
;
;       CTYPE - One, two, or three element vector containing 8 character 
;               strings corresponding to the CTYPE1, CTYPE2, and CTYPE3 
;               FITS keywords: 
;
;               CTYPE[0] - first four characters specify standard system
;               ('RA--','GLON' or 'ELON' for right ascension, galactic 
;               longitude or ecliptic longitude respectively), second four 
;               letters specify the type of map projection (eg '-AIT' for 
;               Aitoff projection)
;               CTYPE[1] - first four characters specify standard system
;               ('DEC-','GLAT' or 'ELAT' for declination, galactic latitude
;               or ecliptic latitude respectively; these must match 
;               the appropriate system of ctype1), second four letters of 
;               ctype2 must match second four letters of ctype1.
;               CTYPE[2] - if present must be the 8 character string,'CUBEFACE',
;                only used for spherical cube projections to identify an axis 
;               as containing the face on which each x and y pair of 
;               coordinates lie.
;       FACE - a input variable used for spherical cube projections to 
;               designate the face of the cube on which the x and y 
;               coordinates lie.   Must contain the same number of elements
;               as X and Y.
;       CRVAL - 2 element vector containing standard system coordinates (the 
;               longitude and latitude) of the reference point
;       CRXY - 2 element vector giving the x and y coordinates of the 
;               reference point, if this is not set the offset of the x 
;               coordinate is assumed to be 0.
;       LATPOLE -  native latitude of the standard system's North Pole
;       LONGPOLE - native longitude of standard system's North Pole, default
;               is 180 degrees, numeric scalar
;       PROJP1 - scalar with first projection parameter (PV2_1), this may
;               or may not be necessary depending on the map projection used
;       PROJP2 - scalar with second projection parameter (PV2_2), this may
;               or may not be necessary depending on the map projection used
;
; OUTPUT PARAMETERS:
;
;       longitude - longitude of data, same number of elements as x, in degrees
;       latitude - latitude of data, same number of elements as x, in degrees
;
; NOTES:
;       The conventions followed here are described in more detail in the paper
;      "Representations of Celestial Coordinates in FITS" by Calabretta &
;       Greisen (2002, A&A, 395, 1077, also see 
;       http://www.aoc.nrao.edu/~egreisen).   The general scheme 
;       outlined in that article is to convert x and y coordinates into a 
;       "native" longitude and latitude and then rotate the system into one of 
;       three generally recognized systems (celestial, galactic or ecliptic).
;
;       This procedure necessitates two basic sections.  The first converts 
;       x and y coordinates to "native" coordinates while the second converts 
;       "native" to "standard" coordinates.  The first section contains the 
;       guts of the code in which all of the map projection is done.  The 
;       second step is performed by WCS_ROTATE and only involves rotation of 
;       coordinate systems.  WCSXY2SPH can be called in a form similar to 
;       AITOFF, EQPOLE, or QDCB by calling wcsxy2sph with a fifth parameter 
;       specifying the map projection by number and by not using any of the 
;       keywords related to the map projection type (eg ctype1 and ctyp2).
;
; PROCEDURE:
;       The first task of the procedure is to do general error-checking to 
;       make sure the procedure was called correctly and none of the 
;       parameters or keywords conflict.  This is particularly important 
;       because the procedure can be called in two ways (either using 
;       FITS-type keywords or using a number corresponding a map projection 
;       type).  All variables are converted into double precision values.
;
;       The second task of the procedure is to take x and y coordinates and 
;       convert them into "native" latitude and longitude coordinates.  
;       Map-specific error-checking is done at this time.  All of the 
;       equations were obtained from "Representations of Celestial 
;       Coordinates in FITS" and cases needing special attention are handled 
;       appropriately (see the comments with individual map projections for 
;       more information on special cases).     WCS_ROTATE is then called to 
;       convert the "native" coordinates to "standard" coordinates by rotating
;       the coordinate system.  This rotation is governed by the keywords 
;       CRVAL, and LONGPOLE.  The transformation is a straightforward 
;       application of euler angles.  Finally, longitude values are converted 
;       into the range from 0 to 360 degrees.
;
; COMMON BLOCKS:
;       none
; PROCEDURES CALLED:
;       WCS_ROTATE
;
; COPYRIGHT NOTICE:
;
;       Copyright 1991, The Regents of the University of California. This
;       software was produced under U.S. Government contract (W-7405-ENG-36)
;       by Los Alamos National Laboratory, which is operated by the
;       University of California for the U.S. Department of Energy.
;       The U.S. Government is licensed to use, reproduce, and distribute
;       this software. Neither the Government nor the University makes
;       any warranty, express or implied, or assumes any liability or
;       responsibility for the use of this software.
;
; AUTHOR:
;
;       Rick Balsano
;
; MODIFICATIONS/REVISION LEVEL:
;
; 1.1    8/31/93
; 1.2    9/12/93   W. Landsman Vectorized CRXY, CRVAL, CTYPE
; 1.3    29/12/93  I. Freedman Eliminated LU decomposition
; 1.4    22/09/94  W. Landsman If scalar input, then scalar output
; 1.5    02/03/05  W. Landsman Change variable name BETA for V4.0 compatibility
; 1.6    06/07/05  W. Landsman Change loop index from integer to long
;       Converted to IDL V5.0   W. Landsman   September 1997
; 1.7    02/18/99  W. Landsman Fixed implementation of ARC algorithm
; 1.8    June 2003 W. Landsman Update conic projections, add LATPOLE keyword
; 1.81   Sep 2003 W. Landsman Avoid divide by zero 
; 1.82   Sep 2003 W. Landsman CTYPE keywords need not be 8 characters
; 1.83   Sep 2003 W. Landsman Preserve input array sizes

; NAME:
;       WCS_DEMO
;
; PURPOSE:
;       Demonstrate the basic capabilities of procedures WCSSPH2XY & WCSXY2SPH
;
; CATEGORY:
;       Mapping and Auxilary FITS Demo Routine
;
; CALLING SEQUENCE:
;
;       .run wcs_demo: compiles wcs_demo and the supporting demo routines
;       wcs_demo: run the demo
;
; INPUT PARAMETERS:
;
;       none
;
; OUTPUT PARAMETERS:
;       none
;
; PROCEDURE:
;
;       This is a demo program which is meant to call the routines 
;       wcssph2xy.pro and wcsxy2sph.pro.  Since the purpose of this
;       routine is both to show what the routines can do and what the
;       user has to do, a file is created with all of the commands 
;       needed to complete the desired operation.  Wcs_demo actually 
;       executes this command file, so the user can exactly duplicate
;       the results by simply re-executing this file.  Also, this 
;       allows a user to edit an already existing file which calls 
;       wcssph2xy.pro and wcsxy2sph.pro properly and extend the file's
;       usefulness.  This demo program allows several possible tests.
;       The first option is to simply draw a grid of evenly spaced
;       latitude and longitude lines in a particular map transformation.
;       Another possibility is to do a full loop, creating a Cartesian
;       grid of latitude and longitude lines and calling wcssph2xy.pro
;       to convert them to a particular map.  Then, wcsxy2sph.pro is
;       called to invert the process and the difference between the
;       original and final latitudes and longitudes can be plotted.
;       This allows one to assess the level of the numerical errors
;       introduced by the mapping routines.  A third possible option is to
;       look at some of the map transformations and include rotations of
;       the reference points so that a different perspective is given.
;
; COMMON BLOCKS:
;       none
;
; PROCEDURES CALLED:
;       SPHDIST(), WCSXY2SPH, WCSSPH2XY
; COPYRIGHT NOTICE:
;
;       Copyright 1991, The Regents of the University of California. This
;       software was produced under U.S. Government contract (W-7405-ENG-36)
;       by Los Alamos National Laboratory, which is operated by the
;       University of California for the U.S. Department of Energy.
;       The U.S. Government is licensed to use, reproduce, and distribute
;       this software. Neither the Government nor the University makes
;       any warranty, express or implied, or assumes any liability or
;       responsibility for the use of this software.
;
; AUTHOR:
;
;       Rick Balsano
;
; MODIFICATIONS/REVISION LEVEL:
;
;       1.1     8/31/93
;       1.2     3/19/96 - J. Bloch - LANL
;                        - Made compatible with wcslib-2.2 by Calabretta.
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Updated for conical projections W. Landsman  July 2003

; NAME:
;       WCS_GETPOLE 
;
; PURPOSE:
;       Compute the coordinates of the native pole for a non-polar projection
; EXPLANATION:
;       For non-polar (cylindrical or conic) projections, the native pole is
;       not at the reference point, and WCS_GETPOLE is used to determine the
;       position of the native pole.    See section 2.4 of the paper 
;       "Representation of Celestial Coordinates in FITS" by Calabretta 
;       Greisen (2002, A&A, 395, 1077, also available at  
;       http://www.aoc.nrao.edu/~egreisen    Called by WCS_ROTATE
;
; CALLING SEQUENCE:
;       WCS_GETPOLE,  crval, lonpole, theta0, alpha_p, delta_p, LATPOLE= ]
;
; INPUT PARAMETERS:
;       crval - 2 element vector containing standard system coordinates (the 
;               longitude and latitude) of the reference point in degrees
;       lonpole - native longitude of the celestial North Pole (degrees)
;       theta0 - native latitude of the fiducial point
; OUTPUT PARAMETERS:
;       alpha_p, delta_p - celestial longitude and latitude of the native pole
;               (degrees)
; OPTIONAL KEYWORD INPUT PARAMETERS:
;       LATPOLE - native latitude of the celestial North Pole (degrees)
; REVISION HISTORY:
;       Written    W. Landsman               June, 2003

; NAME:
;       WCS_ROTATE 
;
; PURPOSE:
;       Rotate between standard (e.g. celestial) and native coordinates
; EXPLANATION:
;       Computes a spherical coordinate rotation between native coordinates 
;       and  standard celestial coordinate system (celestial, Galactic, or
;       ecliptic).   Applies the equations in Appendix A of the paper 
;       "Representation of Celestial Coordinates in FITS" by Calabretta 
;       Greisen (2002, A&A, 395, 1077).    Also see 
;       http://www.aoc.nrao.edu/~egreisen
;
; CATEGORY:
;       Mapping and Auxiliary FITS Routine
;
; CALLING SEQUENCE:
;       WCS_ROTATE, longitude, latitude, phi, theta, crval, 
;               [LONGPOLE = , LATPOLE = , /REVERSE, /ORIGIN ]
;
; INPUT PARAMETERS:
;       crval - 2 element vector containing standard system coordinates (the 
;               longitude and latitude) of the reference point
;
; INPUT OR OUTPUT PARAMETERS
;       longitude - longitude of data, scalar or vector, in degrees, in the
;               standard celestial coordinate system
;       latitude - latitude of data, same number of elements as longitude, 
;               in degrees
;       phi - longitude of data in the native system, in degrees, scalar or
;               vector
;       theta - latitude of data in the native system, in degrees, scalar or
;               vector
;
;       If the keyword(REVERSE) is set then phi and theta are input parameters
;       and longitude and latitude are computed.    Otherwise, longitude and
;       latitude are input parameters and phi and theta are computed.
;
; OPTIONAL KEYWORD INPUT PARAMETERS:
;
;      ORIGIN - If this keyword is set and non-zero, then the reference point
;               given by CRVAL in the native system is assumed to be at the
;               origin of the coordinates, rather than at the North Pole.
;               ORIGIN should be set for cylindrical projections (Cylindrical
;               perspective-CYP, Cartesian - CAR, Mercator - MER, Cylindrical
;               Equal area - CEA) and conventional projections (Bonne's equal
;               area - BON, Polyconic - PCO, Sinusoidal - GLS, Parabolic - PAR,
;               Aitoff - AIT, Mollweide - MOL, COBE quadrilateralized sphere -
;               CSC, Quadrilateralized Spherical Cube - QSC, and Tangential
;               Spherical Cube - TSC)
;
;       LONGPOLE - native longitude of standard system's North Pole, default
;               for a Zenithal system is 180 degrees
;       LATPOLE -  native latitude of the standard system's North Pole
;       /REVERSE - if set then phi and theta are input parameters and longitude
;                  and latitude are computed.    By default, longitude and
;                  latitude are input parameters and phi and theta are computed.
; REVISION HISTORY:
;       Written    W. Landsman               December, 1994
;       Fixed error in finding North Pole if /ORIGIN and LONGPOLE NE 180
;       Xiaoyi Wu and W. Landsman,   March, 1996
;       Fixed implementation of March 96 error, J. Thieler,  April 1996
;       Updated to IDL V5.0   W. Landsman    December 1997
;       Fixed determination of alpha_p if /ORIGIN and LONGPOLE EQ 180
;               W. Landsman    May 1998
;       Ensure argument of ASIN() is -1
; NAME: 
;    WEBGET()
;
; PURPOSE: 
;    Use the IDL SOCKET procedure to get data from http servers
;
; EXPLANATION: 
;     WEBGET() can access http servers - even from behind a firewall - 
;     and perform simple downloads. Currently, text and FITS files can be 
;     accessed.    Requires IDL V5.4 or later on Unix or Windows, V5.6 on
;     Macintosh
;
; CALLING SEQUENCE: 
;      a=webget(URL)
;
; INPUTS: 
;      URL - scalar string giving a fully qualified url of the form
;          'http://server.eso.org/path/file.html'.    WEBGET() can
;          also use other valid URLs that contain 'GET'-codes.
;
; OPTIONAL INPUT KEYWORD PARAMETERS: 
;       COPYFILE - if set to a valid filename (file must have write permission),
;            the data contents of the web server's answer is copied to that 
;            file. 
;       /SILENT - If set, the information error messages are suppressed
; OUTPUTS: A structure with the following fields:
;
;            .Header - the HTTP header sent by the server
;
;            .Text   - The text part of the downloaded file. If the
;                     content type of the file was not of class
;                     'text',  this will be an empty string.
;
;            .ImageHeader - Header file of a FITS-image. FITS images
;                          are read when the content type is
;                          'image/fits' or 'application/octet-stream'
;                          (for dss-access). If the file is not a FITS
;                          image,  this will be an empty string.
;
;            .Image - The FITS image read from the server. If the file
;                    did not contain a FITS image,  this will be zero.
;
;
; RESTRICTIONS: 
;     The mime-type recognition is extremely limited. Only the content-type is 
;     determined. Any text-file  will be stored in out.Text. The only other 
;     category which can be fetched is FITS files,  which will be stored in 
;     out.Image and out.ImageHeader.
;
;     PROXY: If you are behind a firewall and have to access the net through a 
;         Web proxy,  set the environment variable 'http_proxy' to point to 
;         your proxy server and port, e.g. 
;         'setenv http_proxy=http://web-proxy.mpia-hd.mpg.de:3128'
;
;               The URL *MUST* begin with "http://".
;
; PROCEDURE: 
;     Open a socket to the webserver and download the header. After deciding 
;     whether it is text or binary, either store the text or try to read a 
;     FITS file.
;
; EXAMPLE: 
;      IDL> a=webget('http://www.mpia.de/index.html')
;      IDL> print,a.Text
;      or
;
;          > PointingRA=0.0
;          > PointingDE=30.0
;          > QueryURL = strcompress("http://archive.eso.org/dss/dss/image?ra="+$
;          >                          string(PointingRA)+$
;          >                          "&dec="+$
;          >                          string(PointingDE)+$
;          >                          "&x=10&y=10&Sky-Survey=DSS1&mime-type=download-fits", $
;          >                          /remove)
;          > a=webget(QueryURL)
;          > tvscl,a.Image
;          > print,a.ImageHead
;
;
;
; MODIFICATION HISTORY: 
;     Written by M. Feldt, Heidelberg, Oct 2001 
;     Use /swap_if_little_endian keyword to SOCKET  W. Landsman August 2002
;     Less restrictive search on Content-Type   W. Landsman   April 2003
;

; NAME:
;   WFPC2_METRIC
; PURPOSE:
;   Compute the distortion in a WFPC2 image and optionally return coordinates
; EPLANATION:
;   Uses the distortion solution of Anderson & King (2003, PASP, 115, 113)
;   Pixel 424, 424 on each chip remains fixed, and other pixel positions are
;   mapped to remove nonlinearities.   If /GLOBAL is set, then all chips are
;   put on the same reference frame where pixel 424, 424 in the WF3 chip 
;   remains fixed. 
; CALLING SEQUENCE:
;      WFPC2_METRIC, xin, yin, xout, yout, [ChipNum, HEADER=, /GLOBAL
;                                           YEAR =, FILTER=
;                            or
;      WFPC2_METRIC, xin, yin, a, d, HEADER=, /RAdec, /GLOBAL ]
; INPUTS:
;     XIN, YIN - X,Y positions (0-799) on a WFPC2 chip in 
;               IDL convention (first pixel is 0,0), scalar or vectors
; OUTPUTS:
;     XOUT, YOUT - X,Y positions in the distorted frame, same number of 
;                  elements as XIN, YIN
;                          or if /RADEC is set
;     AA, DD  - Right ascension and declination (in degrees) corresponding 
;               to the input coordinates after distortion correction.
; OPTIONAL INPUT:
;     ChipNum - Integer  1, 2, 3, or 4  specifying the WFPC2 chip number
;             1-PC, 2-WF2, 3-WF3, 4-WF4.   If not supplied, then WFPC2_METRIC
;             will try to read the value from the DETECTOR in the FITS header.
; OPTIONAL INPUTS:
;     /GLOBAL - If set, then positions are returned in a master reference 
;              frame with pixel 424,424 of WF3 remaining fixed.   Thus, 
;              information  concerning the  interchip separation and 
;              orientation (with a weak dependence on time and filter) is 
;              incorporated. 
;     Header - FITS header with astrometry for a particular chip.
;             If both /RADec and /Global are set, then the header must be
;             from the WF3 chip. 
;     /RADec - If set, then astrometry information in the FITS header (which
;             must be supplied as a keyword) is used to convert the output
;             to Right Ascension and declination (both in degrees).
;     FILTER - Filter name needed if /GLOBAL is set, must be either 'F300W'
;             'F336W', 'F439W', 'F555W' or 'F814W'; otherwise the plate scale
;             for F555W is assumed.   WFPC2_METRIC will try to read this 
;             value from the FITS header if not supplied as a keyword.
;     YEAR -  Observation year including fraction (e.g. 1998.56) needed if
;             /GLOBAL is set.  WFPC2_METRIC will try to read this value from 
;             the FITS header if not supplied as a keyword.  The time 
;             correction is currently applied through the year 2002; later 
;             dates will use the year 2002 correction.              
; EXAMPLES:
;     (1) Find the undistorted X,Y coordinates of position 682.3,234.2 on chip 1 
;         (the PC chip).
;          IDL> WFPC2_METRIC, 682.3, 234.2, xout, yout, 1 
;             ==> xout = 681.13   yout = 235.05
;
;     (2) Determine the RA and Dec of position 682.3, 234.2 on chip 1 on the 
;         WFPC2 image U2Z30201T
;         IDL> WFPC2_READ, 'u2z30201t.c0h', im,h   ;Get header for chip 1
;         IDL> WFPC2_METRIC, 682.3, 234.2, aa, dd, header= h,/RADec
;         IDL> print, adstring(aa,dd,2)
;         05 20 53.572  -69 35 18.17
;
;         Note that a chip number did not need to be specified since its value
;         is in the FITS header
;
;     (3) As above, but now compute coordinates in the global frame, needed
;         for example, to compute the distance between stars on two different
;         chips. 
;
;        First get headers for chips 1 and 3
;        IDL> WFPC2_READ, 'u2z30201t.c0h', im1,h1, im3,h3,num=[1,3]   
;        IDL> WFPC2_METRIC, 682.3, 234.2, aa, dd, 1, header=h3,/RADec,/GLOBAL
;        IDL> print, adstring(aa,dd,2)
;         05 20 53.513  -69 35 17.98
;
;        Note that with /GLOBAL set, that the header must be for WF3, even
;        though coordinates are being computed for chip 1.   Also note that
;        the time and filter will be read from the FITS header.   Finally,
;        note that the coordinates given in examples (2) and (3) differ
;        slightly, because the chip separations incorporated in the FITS 
;        headers differ slightly from those in the Anderson & King solution.   
; PROCEDURES USED:
;     LINTERP, SXPAR(), XYAD, YMD2DN()
; REVISION HISTORY:
;     Written     W. Landsman         March 2003

; NAME:
;    WFPC2_READ
;
; PURPOSE:
;   Read WFPC2 images in either FITS or STSDAS format into IDL variables.
;
; EXPLANATION:
;   This a versatile procedure for reading Wide Field Planetary Camera 2 
;   (WFPC2) images.   One can read either FITS or STSDAS format, and specific 
;   chip or chips.    One can also read all four chips into a "batwing" mosaic--
;   so-called because the PC chip (chip 1) has a plate scale of 0.045", while
;   the other three WF chips have a plate scale of 0.1"
; 
; CALLING SEQUENCE:
;    WFPC2_READ,filename,chip1,hdr1,chip2,hdr2,chip3,hdr3,chip4,hdr4
;                   or
;    WFPC2_READ,filename,chip,hdr, NUM_CHIP = [1,2,3,4], [/TRIM, PATH = ]
;                   or
;    WFPC2_READ,filename,image,hdr,/BATWING
;
; INPUTS:
;    filename - Name of FITS or STSDAS file with a stack of images from
;            the four WF/PC-2 chips, followed by a FITS ASCII
;            table with header parameters for each chip.    If the file
;            name extension ends in 'h' then it is assumed to be an
;            STSDAS file.   If no extension is supplied, and the file is
;            is not found, then WFPC2_READ first tries appending a '.fits'
;            extension, and then tries appending a '.c0h' extension.  
;
;            The file may be gzip compressed (with a .gz extension) for IDL
;            V5.3 or later.
; INPUT KEYWORD PARAMETERS:
;    NUM_CHIP - Integer scalar or vector, subset of 1, 2, 3, 4, specifying 
;               particular chip numbers to read.    Outputs will be in same 
;               order as specification of subset.   (See Example 2.)
;    /TRIM   - If set, trim off areas with no image and re-orient so that
;              all  the chips have a common orientation suitable for insertion 
;               into "bat-wing" mosaic (no image distortion removal, however).
;    PATH   -   scalar string specifying a !PATH-like list of directories
;               in which to search for the file.   Default is to look only
;               in the current directory.
;    /BATWING -  Return a 1600 x 1600 array containing all four chips in a
;               "bat wing" mosaic formation.     This image is mainly for 
;               display  purposes, since the PC chip is compressed to match the plate 
;               scale of the WF chips.    In addition, a small astrometry error
;               is introduced since chips do not have the same rotation, nor    
;               are they aligned at the integer pixel level.
; OUTPUTS:
;    chipN    - 800 X 800 image from chip N.   If /TRIM is set then the output
;               size is somewhat smaller (e.g. 756 x 757)
;    headerN  - Individual FITS header for chip N with correct astrometry.
;
; PROCEDURES USED:
;     For FITS I/O: FITS_CLOSE, FITS_OPEN, FITS_READ
;     For STSDAS I/O: EXTGRP, FTGET(), SXOPEN, SXREAD()
;     Other procedures:  CHECK_FITS, FDECOMP, FIND_WITH_DEF(), FREBIN, HEXTRACT, 
;           HROTATE, SXADDHIST, SXADDPAR, SXPAR()
; EXAMPLE: 
;    (1) Read all four chips of the FITS file u2ou0201t_c0f.fits
; 
;    IDL> wfpc2_read,'u2ou0201t_c0f',c1,h1,c2,h2,c3,h3,c4,h4
;
;     (2) Note that supplying the .fits extension is optional.   Now read only
;     chips 1 (the PC chip) and 3.   Trim off portions of the arrays where
;     there is no image.   
;
;    IDL> wfpc2_read,'u2ou0201t_c0f',c1,h1,c3,h3,num=[1,3],/trim
;
;      (3) Note that with the /TRIM option the output chip sizes are no longer
;          800 x 800 but odd sizes such as 770 by 753.    Now read all 4 chips
;          into a 1600 x 1600 "batwing" mosaic
;
;    IDL> wfpc2_read,'u2ou0201t_c0f',im,h,/batwing
;
; MODIFICATION HISTORY:
;     Written by W. Landsman, Raytheon STX, for IDL V5.0     June 1998
;     Based on code by Robert Hill, Raytheon STX
;     Better astrometry of PC image in "batwing" configuration, W. Landsman
;                August 1999
;     Use vector call to SXADDHIST  W. Landsman   March 2003

; NAME:
;       WFPCREAD
; PURPOSE:
;       Read designated header and chip of a WFPC1 image
; EXPLANATION:
;       This procedure is designed to read the designated header and chip of a
;       WFPC image.  If the PAR input parameter is supplied, then the group
;       PARameter byte array is is returned.  If it is not, then the  header 
;       is modified by placing all the group parameters in the header as data 
;       cards.
;
;       Use the procedure WFPC2_READ to read WFPC2 images.
; CALLING SEQUENCE:
;       WFPCREAD, file, chip, wfhdr, wfimg, par
;
; INPUT:
;       FILE - The filename of the Header file of the image
;       CHIP - The chip number to read (usually 0-3)
;
; OUTPUT:
;       WFHDR -  Returned WF/PC header in a string array
;       WFIMG -  Returned WF/PC float image array
;
; OPTIONAL OUTPUT:
;       PAR  -  PARameter byte array (for group format header)
;
; HISTORY:
;       25-JUN-1990 Version 1 written
;       2-APR-1992 Added code to add CAM and CHIP onto the FILTNAM1    EWD
;       27-JUL-1992 Proper Header finally added  (E. Deutsch)
;       Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;      WHERENAN
; PURPOSE:
;      Find the indices of all IEEE NaN values in an array.
; EXPLANATION: 
;      Find the positions of all values within an array that correspond to the
;      IEEE NaN (not-a-number) special values.
;
;      This routine is designed to be used on data which is in external data
;      representation, not host representation.  Its purpose is to catch all
;      NaN special values before converting (IEEE_TO_HOST) from external to
;      host format, e.g. when reading a FITS file.
;
;      To identify IEEE values in the *host* representation, one can use
;          result = where(array NE array)
;      If this notation seems too bizarre, then since V5.2 one can use the /NAN
;      keyword to the FINITE function
;          result = where( finite(array,/NAN) )
;
; CALLING SEQUENCE:
;      Result = WHERENAN( ARRAY [, COUNT ] )
;
; INPUT PARAMETERS:
;      ARRAY   = Array to test against the IEEE NaN special values.  Must be
;                of either floating point, double-precision, or complex type.
;
; OUTPUTS:
;      The result of the function is the indices of all values of ARRAY
;      corresponding to the IEEE NaN specification, similar to the IDL WHERE
;      function.
;
; OPTIONAL OUTPUT PARAMETERS:
;      COUNT   = Number of values found corresponding to IEEE NaN.
;
; SIDE EFFECTS:
;      If no NaN values are found, or if ARRAY is not of type float, double
;      precision, or complex, then -1 is returned, and COUNT is set to 0.
;
; RESTRICTIONS:
;      ARRAY must be of type float, double-precision, or complex.
;
; PROCEDURE:
;      The bit patterns of the numbers being tested are compared against the
;      IEEE NaN standard.
;
; MODIFICATION HISTORY:
;      William Thompson, Feb. 1992.
;      William Thompson, Oct. 1992, fixed bug regarding order of bytes on VAX
;              machines.
;      Converted to IDL V5.0   W. Landsman   September 1997

; NAME: 
;      WHERE_NEGZERO()
;
; PURPOSE:      
;      Find positions of IEEE -0.0 values.
;
; EXPLANATION : 
;       Finds the positions of all values within an array that correspond to the
;       IEEE value -0.0, as determined from the bit pattern.  Prior to IDL V5.1,
;       the VMS operating system had trouble coping with these values.  If using
;       any other operating system, then no action is performed.
;
; CALLING SEQUENCE:     
;       Result = WHERE_NEGZERO( ARRAY [, COUNT, /QUIET ] )
;
; INPUTS:       
;       ARRAY   = Array to test against the IEEE -0.0 value.  Must be
;               either floating point or double-precision.
;
; OUTPUTS:      
;       The result of the function is the indices of all values of
;       ARRAY corresponding to the IEEE -0.0 value, similar to the IDL
;       WHERE function.
;
; OPTIONAL  OUTPUT:     
;       COUNT   = Number of values found corresponding to IEEE -0.0.
;
; OPTIONAL INPUT KEYWORD:       
;       /QUIET  = If set, then warning messages are not printed out.
;
; RESTRICTIONS: 
;       ARRAY must be of type float or double-precision.
;
; SIDE EFFECTS: 
;       If no -0.0 values are found, or if ARRAY is not of type float,
;       or double precision, or if the operating system is something
;       other than VMS, then -1 is returned, and COUNT is set to 0.
;
; REVISION HISTORY:
;       Written,  31-Jan-1997, William Thompson, GSFC
;        Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;	WHERE_TAG
; PURPOSE:
;	Like WHERE but works on structure tag names
; EXPLANATION:
;	Obtain subscripts of elements in structure array for which
;	a particular Tag has values in a range or matching specified values.
;	Like the WHERE function but for use with structures
; CATEGORY:
;			Structures
; CALLING SEQUENCE:
;	 w = where_tag( struct, [ Nfound,  TAG_NAME=, TAG_NUMBER = , RANGE =, 
;				VALUES =, RANGE =, ISELECT =, /NOPRINT ]
;
; INPUTS:
;	Struct = structure array to search.
;
; INPUT KEYWORDS:
;	User *must* specify (1) TAG_NAME or TAG_NUMBER to search, and (2)
;		the VALUES or RANGE to search on
;
;	TAG_NAME = Scalar string specifying Tag Name
;	TAG_NUMBER = otherwise give the Tag Number,
;	RANGE = [min,max] range to search for in Struct,
;	VALUES = one or array of numbers to match for in Struct,
;	ISELECT= specifies indices to select only part of structure array,
;		(use it to recycle subscripts from previous searches).
;	/NOPRINT = suppress informational messages about nothing found.
;
; OUTPUTS:
;	Nfound = # of occurences found.
;
; RESULT:
;	Function returns subscripts (indices) to desired elements.
;
; EXAMPLES:
;	Suppose STR is a structure with tags CAT_NO:indgen(10), and 
;		NAME:strarr(10).   Find the indices where STR.CAT_NO is
;		between 3 and 5.
;
;	IDL> print, WHERE_TAG( str, TAG_NAME = 'CAT_NO', VALUE = [3,4,5] )  ;or
;	IDL> print, WHERE_TAG( str, TAG_NUM = 0, RANGE = [3,5]) 
;
; PROCEDURE:
;	Get tag number and apply the WHERE function appropriately.
;
; MODIFICATION HISTORY:
;	written 1990 Frank Varosi STX @ NASA/GSFC
;	Stop printing "Tag  not found" with /NOPRINT, CD Pike 8-Jun-93

; NAME:
;       WRITEFITS
; PURPOSE:
;       Write IDL array and header variables to a disk FITS file.    
;
; EXPLANATION:
;       A minimal FITS header is created if not supplied.
;       WRITEFITS works for all types of FITS files except random groups
;
; CALLING SEQUENCE:
;       WRITEFITS, filename, data [, header, /APPEND, /CHECKSUM] 
;
; INPUTS:
;       FILENAME = String containing the name of the file to be written.
;
;       DATA = Image array to be written to FITS file.    If DATA is 
;              undefined or a scalar, then only the FITS header (which
;              must have NAXIS = 0) will be written to disk
;
; OPTIONAL INPUT:
;       HEADER = String array containing the header for the FITS file.
;                If the variable HEADER is not supplied, the program will 
;                generate a minimal FITS header.
;
; OPTIONAL INPUT KEYWORD:
;       /APPEND - If this keyword is set then the supplied header and data
;                array are assumed to be an extension and are appended onto
;                the end of an existing FITS file.    If the file does not 
;                exist, then WRITEFITS will create one with a minimal primary
;                header (and /EXTEND keyword) and then append the supplied
;                extension header and array.     Note that the primary
;                header in an existing file must already have an EXTEND
;                keyword to indicate the presence of an FITS extension.
;      /Checksum - If set, then the CHECKSUM keywords to monitor data integrity
;                 will be included in the FITS header.    For more info, see
;                  http://heasarc.gsfc.nasa.gov/docs/heasarc/fits/checksum.html
; OUTPUTS:
;       None
;
; RESTRICTIONS:
;       (1) It recommended that BSCALE and BZERO not be used (or set equal
;           to 1. and 0) with REAL*4 or REAL*8 data.
;       (2) WRITEFITS will remove any group parameters from the FITS header
;
; EXAMPLE:
;       Write a randomn 50 x 50 array as a FITS file creating a minimal header.
;
;       IDL> im = randomn(seed, 50, 50)        ;Create array
;       IDL> writefits, 'test', im             ;Write to a FITS file "test"
;
; PROCEDURES USED:
;       CHECK_FITS, FITS_ADD_CHECKSUM, MKHDR, MRD_HREAD, SXDELPAR, SXADDPAR, 
;       SXPAR()
;
; MODIFICATION HISTORY:
;       WRITTEN, Jim Wofford, January, 29 1989
;       MODIFIED, Wayne Landsman, added BITPIX = -32,-64 support for UNIX
;       Use new BYTEODER keywords 22-Feb-92
;       Modify OPENW for V3.0.0   W. Landsman       Dec 92
;       Work for "windows"   R. Isaacman            Jan 93
;       More checks for null data                   Mar 94
;       Work for Linux  W. Landsman                 Sep 95
;       Added call to IS_IEEE_BIG()  W. Landsman  Apr 96
;       Make sure SIMPLE is written in first line of header  W. Landsman Jun 97
;       Use SYSTIME() instead of !STIME    W. Landsman  July 97
;       Create a default image extension header if needed W. Landsman June 98
;       Converted to IDL V5.0   W. Landsman         June 98
;       Write unsigned data types W. Landsman       December 1999
;       Correct BZERO value for unsigned data  W. Landsman   July 2000
;       Assume at least V5.1 remove NANValue keyword W. Landsman July 2001
;       Use FILE_SEARCH for V5.5 or later     W. Landsman    April 2002
;       Create the file if not already present and /APPEND is set
;                                             W. Landsman    September 2002
;       Fix MRD_HREAD call if /APPEND is set  W. Landsman    December 2002
;       Added /CHECKSUM keyword              W. Landsman     December 2002

; NAME:
;       XMEDSKY
;
; PURPOSE:
;       Subtract sky from an image as a 1-D function of X
; EXPLANATION:
;       This procedure is designed to remove the sky from slitless spectra.
;       The sky is assumed to vary with wavelength (along a row) but not with
;       position (along a column).    The sky is computed as the 
;       column-by-column median of pixels within 3 sigma of the image global 
;       median.   This procedure is called by the cosmic ray rejection routine
;       CR_REJECT
;
; CALLING SEQUENCE:
;       XMEDSKY, Image, Bkg, [ CLIP=[x0, x1, y0, y1], NSIG= ]
;
; INPUTS:
;       Image:  Input image for which sky vector is to be computed.
;	
; INPUT KEYWORD PARAMETERS:
;       CLIP:   [x0, x1, y0, y1]: region of image to be used for all
;               statistical computations.    Default is to use the entire
;               image.   For STIS 1024 x 512 slitless spectra, the suggested
;               value is CLIP = [32,1023,12,499]
;       NSIG:   Postive scalar giving the number of sigma a pixel must be above
;               the global median to be reject.   Default is 3 sigma.
; OUTPUT PARAMETER:
;       Bkg:    Vector of sky values.
;
; PROCEDURE CALLS:
;	STDEV() - In /obsolete directory of standard IDL distribution
;       If since V5.1 then the STDDEV function is used instead.
;
; MODIFICATION HISTORY:
; 	Written by:	R. S. Hill, Hughes STX, 20 Oct. 1997
;       Converted to V5.0, use STDDEV()   W. Landsman   June 1998
;       Check for valid WHERE, added NSIG keyword  W. Landsman   December 2000 

; NAME:
;     XY2AD
;
; PURPOSE:
;     Compute R.A. and Dec from X and Y and a FITS astrometry structure
; EXPLANATION:
;     The astrometry structure must first be extracted by EXTAST from a FITS
;     header.   The procedure WCSXY2SPH is used to compute native coordinates,
;     and the CD matrix is then used to compute RA and Dec (or longitude and
;     latitude).   Angles are returned in 
;     degrees.   XY2AD is meant to be used internal to other procedures.  
;     For interactive purposes use XYAD.
;
; CALLING SEQUENCE:
;     XY2AD, x, y, astr, a, d   
;
; INPUTS:
;     X     - row position in pixels, scalar or vector
;     Y     - column position in pixels, scalar or vector
;           X and Y 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 EXTAST procedure containing:
;        .CD   -  2 x 2 array containing the astrometry parameters CD1_1 CD1_2
;               in DEGREES/PIXEL                                   CD2_1 CD2_2
;        .CDELT - 2 element vector giving physical increment at reference pixel
;        .CRPIX - 2 element vector giving X and Y coordinates of reference pixel
;               (def = NAXIS/2)
;        .CRVAL - 2 element vector giving R.A. and DEC of reference pixel 
;               in DEGREES
;        .CTYPE - 2 element vector giving projection types 
;        .LONGPOLE - scalar longitude of north pole
;        .LATPOLE - scalar giving native latitude of the celestial pole  
;        .PROJP1 - Scalar parameter needed in some projections, FITS keyword
;                  PV2_1
;        .PROJP2 - Scalar parameter needed in some projections, FITS keyword
;                  
;
; 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
;
; 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.
;
; REVISION HISTORY:
;       Written by R. Cornett, SASC Tech., 4/7/86
;       Converted to IDL by B. Boothman, SASC Tech., 4/21/86
;       Perform CD  multiplication in degrees  W. Landsman   Dec 1994
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Understand reversed X,Y (X-Dec, Y-RA) axes,   W. Landsman  October 1998
;       Consistent conversion between CROTA and CD matrix W. Landsman Oct. 2000
;       No special case for tangent projection W. Landsman June 2003

; NAME:
;       XYAD
; PURPOSE:
;       Use a FITS header to convert pixel (X,Y) to astronomical coordinates
; EXPLANATION: 
;       Use astrometry in a FITS image header to compute astronomical
;       coordinates in decimal degrees from X and Y.  
;
; CALLING SEQUENCE:
;       XYAD, HDR               ;Prompt for X and Y positions
;       XYAD, HDR, X, Y, A, D, [ /PRINT, /Galactic, /Celestial, /Ecliptic, 
;                                ALT = ]
; INPUTS:
;       HDR - FITS Image header containing astrometry info
;
; OPTIONAL INPUTS:
;       X     - row position in pixels, scalar or vector
;       Y     - column position in pixels, scalar or vector
;
;       X and Y should be in IDL convention, (first pixel is (0,0)).
;
; OPTIONAL OUTPUT:
;       A - Output longitude in decimal DEGREES, same number of elements as
;               X and Y.    For celestial coordinates, this is the right 
;               ascension.
;       D - Output latitude in decimal DEGREES.   For celestial coordinates,
;               this is the declination.
; OPTIONAL KEYWORD INPUT:
;       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.;      
;       /PRINT - If this keyword is set and non-zero, then results are displayed
;               at the terminal.in both decimal and sexigesimal notation.
;
;       The default for XYAD is to return the coordinate system present in
;       in the FITS header.    However, the following mutually exclusive 
;       keywords can be used to convert to a particular coordinate system:
;
;       /CELESTIAL - Output is Right Ascension and declination
;       /ECLIPTIC - Output is Ecliptic longitude and latitude
;       /GALACTIC - Output is Galactic longitude and latitude
;    
; OPERATIONAL NOTES:
;       If less than 5 parameters are supplied, or if the /PRINT keyword is
;       set, then the computed astronomical coordinates are displayed at the 
;       terminal.
;
;       If this procedure is to be used repeatedly with the same header,
;       then it would be faster to use XY2AD.
;
; EXAMPLE:
;       A FITS header, hdr, contains astrometric information in celestial
;       coordinates.   Find the RA and Dec corresponding to position X=23.3
;        Y = 100.2 on an image
;        IDL> xyad, hdr, 23.3, 100.2      ;Displays results at the terminal
;       To display the results in Galactic coordinates
;        IDL> xyad, hdr, 23.3, 100.2, /GALACTIC
; PROCEDURES CALLED
;       ADSTRING(), EULER, EXTAST, GSSSXYAD, REPCHR(),  XY2AD
;
; REVISION HISTORY:
;       W. Landsman                 STX          Jan, 1988
;       Use astrometry structure  W. Landsman    Jan, 1994
;       Recognize GSSS header  W. Landsman       June, 1994
;       Changed ADSTRING output format   W. Landsman    September 1995
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Use vector call to ADSTRING() W. Landsman February 2000
;       Added ALT input keyword  W. Landsman June 2003

; NAME:
;	XYXY
; PURPOSE:
;	To use a pair of headers to convert X/Y positions from one frame
;	to another.
; CALLING SEQUENCE:
;	XYXY, hdra, hdrb, xa, ya, [ xb, yb ]
; INPUTS:
;	hdra - The header containing the plate solution describing the
;	       frame of reference being converted FROM.
;	hdra - The header containing the plate solution describing the
;	       frame of reference being converted TO.
;	xa   - A scalar or vector containing the x coordinate(s) to convert.
;	ya   - A scalar or vector containing the y coordinate(s) to convert.
;	       Must have the same number of elements as 'xa'.
; OUTPUTS:
;	xb   - The converted x coordinate(s).  If this parameter is not
;	       specified, it is returned through 'xa'.
;	yb   - The converted y coordinate(s).  If this parameter is not
;	       specified, it is returned through 'ya'.
; PROCEDURE:
;	The procedures 'xyad' and 'adxy' are used to perform the 
;       conversion.     The equinoxes of each header are checked with
;       "get_equinox" to make sure that they are identical, and "precess"
;       is used if they are not
;
;       Note that all X,Y coordinates are in the IDL convention (starting with
;       0,0) and not the FITS convention (first pixel is 1,1)
; PROCEDURES USED:
;	GET_EQUINOX(), EXTAST, XYAD, ADXY, PRECESS
; MODIFICATION HISTORY:
;	Written by Michael R. Greason, Hughes-STX, 13 April 1992.
;	Updated to use ASTROMETRY structures.  J.D.Offenberg, HSTX, Jan 1993
;	Converted to IDL V5.0   W. Landsman   September 1997

; NAME:
;       XYZ
; PURPOSE:
;       Calculate geocentric X,Y, and Z  and velocity coordinates of the Sun
; EXPLANATION:
;       Calculates geocentric X,Y, and Z vectors and velocity coordinates 
;       (dx, dy and dz) of the Sun.   (The positive X axis is directed towards 
;       the equinox, the y-axis, towards the point on the equator at right 
;       ascension 6h, and the z axis toward the north pole of the equator).
;       Typical position accuracy is <1e-4 AU (15000 km).
;
; CALLING SEQUENCE:
;       XYZ, date, x, y, z, [ xvel, yvel, zvel, EQUINOX = ]
;
; INPUT:
;       date: reduced julian date (=JD - 2400000), scalar or vector
;
; OUTPUT:
;       x,y,z: scalars or vectors giving heliocentric rectangular coordinates
;                 (in A.U) for each date supplied.    Note that sqrt(x^2 + y^2
;                 + z^2) gives the Earth-Sun distance for the given date.
;       xvel, yvel, zvel: velocity vectors corresponding to X, Y and Z.
;
; OPTIONAL KEYWORD INPUT:
;       EQUINOX: equinox of output. Default is 1950.
;
; EXAMPLE:
;       What were the rectangular coordinates and velocities of the Sun on 
;       Jan 22, 1999 0h UT (= JD 2451200.5) in J2000 coords? NOTE:
;       Astronomical Almanac (AA) is in TDT, so add 64 seconds to 
;       UT to convert.
;
;       IDL> xyz,51200.5+64.d/86400.d,x,y,z,xv,yv,zv,equinox = 2000
;
;       Compare to Astronomical Almanac (1999 page C20)
;                   X  (AU)        Y  (AU)     Z (AU)
;       XYZ:      0.51456871   -0.76963263  -0.33376880
;       AA:       0.51453130   -0.7697110   -0.3337152
;       abs(err): 0.00003739    0.00007839   0.00005360
;       abs(err)
;           (km):   5609          11759         8040 
;
;       NOTE: Velocities in AA are for Earth/Moon barycenter
;             (a very minor offset) see AA 1999 page E3
;                  X VEL (AU/DAY) YVEL (AU/DAY)   Z VEL (AU/DAY)
;       XYZ:      -0.014947268   -0.0083148382    -0.0036068577
;       AA:       -0.01494574    -0.00831185      -0.00360365
;       abs(err):  0.000001583    0.0000029886     0.0000032077
;       abs(err)
;        (km/sec): 0.00265        0.00519          0.00557
;
; PROCEDURE CALLS:
;       PRECESS_XYZ
; REVISION HISTORY
;       Original algorithm from Almanac for Computers, Doggett et al. USNO 1978
;       Adapted from the book Astronomical Photometry by A. Henden
;       Written  W. Landsman   STX       June 1989
;       Correct error in X coefficient   W. Landsman HSTX  January 1995
;       Added velocities, more terms to positions and EQUINOX keyword,
;          some minor adjustments to calculations 
;          P. Plait/ACC March 24, 1999

; NAME:
;       YDN2MD
; PURPOSE:
;       Convert from year and day number of year to month and day of month.       
; CALLING SEQUENCE:
;       YDN2MD,yr,dy,m,d
; INPUTS:
;       yr = 4 digit year (like 1988), integer scalar
;       dy = day number in year (like 310), integer scalar or vector
;
; OUTPUTS:
;       m = month number (1-12, e.g. 11 = Nov)   
;       d = day of month (like 5).          
;       Note: On error returns m = d = -1.
;
; EXAMPLE:
;       Find the month/day of days 155 and 255 in the year 2001
;
;       IDL> ydn2md, 2001, [155,255], m, d
;         ==> m = [6,9]   & d = [4,12]        ; = June 4 and September 12 
;       
; NOTES:
;       In V5.3 or later uses the intrinisc VALUE_LOCATE function.   
;       Otherwise, uses the Astronomy Library procedure value_locate.pro
; MODIFICATION HISTORY:
;       Adapted from Johns Hopkins University/Applied Physics Laboratory
;       Update to use VALUE_LOCATE,   W. Landsman    January 2001  

; NAME:
;       YMD2DN
; PURPOSE:
;       Convert from year, month, day to day number of year.
; CATEGORY:
; CALLING SEQUENCE:
;       dy = ymd2dn(yr,m,d)
; INPUTS:
;       yr = year (like 1988).      scalar or vector
;       m = month number (like 11 = Nov).   scalar or vector
;       d = day of month (like 5).        scalar or vector
; KEYWORD PARAMETERS:
; OUTPUTS:
;       dy = day number in year (like 310).  out
; COMMON BLOCKS:
; NOTES:
; MODIFICATION HISTORY:
;       Written by R. Sterner, 20 June, 1985.
;       Johns Hopkins University Applied Physics Laboratory.
;       RES 18 Sep, 1989 --- converted to SUN
;       R. Sterner, 1997 Feb 3 --- Made work for arrays.
;
; Copyright (C) 1985, 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.
;	Converted to IDL V5.0   W. Landsman  2-Jan-1998

; NAME:
;       ZANG
; PURPOSE:
;       Determine the angular size of an object as a function of redshift
; EXPLANATION:
;       Requires an input size in kpc and returns an angular size in arc seconds
;       Default cosmology has a Hubble constant of 70 km/s/Mpc, Omega (matter)
;       =0.3 and a normalized cosmological constant Lambda = 0.7; however these
;       values can be changed with apropriate keywords.
;
; CALLING SEQUENCE:
;       angsiz = zang( dl, [ z, H0 =, Omega_m =, Lambda0 = , q0 = , k =, 
;                               /SILENT] )
;
; INPUTS:
;       dl - linear size of the object *in kpc*, non-negative scalar or vector
;       z - redshift of object, postive  scalar or vector
;           Either dl and z must have the same number of elements, or at least
;           one of them must be a vector.
; OPTIONAL INPUT KEYWORDS
;    H0 -  Hubble constant in km/s/Mpc, default is 70
;
;        No more than two of the following four parameters should be
;        specified.    None of them need be specified, default values are given
;    k - curvature constant, normalized to the closure density.   Default is
;        0, indicating a flat universe
;    Omega_m -  Matter density, normalized to the closure density, default
;        is 0.3.   Must be non-negative
;    Lambda0 - Cosmological constant, normalized to the closure density,
;        default is 0.7
;    q0 - Deceleration parameter, numeric scalar = -R*(R'')/(R')^2, default
;        is -0.5
;
;    Note that Omega_m + lambda0 + k = 1 and q0 = 0.5*omega_m - lambda0
; OUTPUT:
;       angsiz - Angular size of the object at the given redshift in 
;               arc seconds 
; EXAMPLE:
;  (1) What would be the angular size of galaxy of diameter 50 kpc at a redshift
;      of 1.5 in an open universe with Lambda = 0 and Omega (matter) = 0.3.
;      Assume the default Hubble constant value of 70 km/s/Mpc.
;      
;      IDL> print,zang(50,1.5, Lambda = 0,omega_m = 0.3)
;             ====> 6.58 arc seconds
;
;  (2) Now plot the angular size of a 50 kpc diameter galaxy as a function of 
;      redshift for the default cosmology (Lambda = 0.7, Omega_m=0.3) up to 
;      z = 0.5
;      IDL> z = findgen(50)/10. + 0.1    ;Angular size undefined at z = 0
;      IDL> plot,z,zang(50,z),xtit='z',ytit='Angular Size (")'
; NOTES:
;      This procedure underwent a major revision in April 2000 to allow for a 
;      cosmological constant, ***including a change of the calling sequence***
;
;      Be sure to supply the input linear size dl in units of kpc.
; PROCEDURES CALLED:
;      LUMDIST() -- Calculates the luminosity distance
; REVISION HISTORY:
;      Written    J. Hill   STX           July, 1988
;      Converted to IDL V5.0   W. Landsman   September 1997
;      Major rewrite to call LUMDIST function  W. Landsman   April 2000     

; NAME:
;     ZBRENT
; PURPOSE:
;     Find the zero of a 1-D function up to specified tolerance.
; EXPLANTION:
;     This routine assumes that the function is known to have a zero.
;     Adapted from procedure of the same name in "Numerical Recipes" by
;     Press et al. (1992), Section 9.3
;
; CALLING:
;       x_zero = ZBRENT( x1, x2, FUNC_NAME="name", MaX_Iter=, Tolerance= )
;
; INPUTS:
;       x1, x2 = scalars, 2 points which bracket location of function zero,
;                                               that is, F(x1) < 0 < F(x2).
;       Note: computations are performed with
;       same precision (single/double) as the inputs and user supplied function.
;
; REQUIRED INPUT KEYWORD:
;       FUNC_NAME = function name (string)
;               Calling mechanism should be:  F = func_name( px )
;               where:  px = scalar independent variable, input.
;                       F = scalar value of function at px,
;                           should be same precision (single/double) as input.
;
; OPTIONAL INPUT KEYWORDS:
;       MAX_ITER = maximum allowed number iterations, default=100.
;       TOLERANCE = desired accuracy of minimum location, default = 1.e-3.
;
; OUTPUTS:
;       Returns the location of zero, with accuracy of specified tolerance.
;
; PROCEDURE:
;       Brent's method to find zero of a function by using bracketing,
;       bisection, and inverse quadratic interpolation,
;
; EXAMPLE:
;       Find the root of the COSINE function between 1. and 2.  radians
;
;        IDL> print, zbrent( 1, 2, FUNC = 'COS')
;
;       and the result will be !PI/2 within the specified tolerance
; MODIFICATION HISTORY:
;       Written, Frank Varosi NASA/GSFC 1992.
;       FV.1994, mod to check for single/double prec. and set zeps accordingly.
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Use MACHAR() to define machine precision   W. Landsman September 2002

; NAME:
;       ZENPOS
; PURPOSE:
;       Return the zenith RA and Dec in radians for a given Julian date.
;
; CALLING SEQUENCE:
;       ZENPOS, Date, Ra, Dec
;
; INPUT:
;       Date  The Julian date, in double precision, of the date and time
;               for which the zenith position is desired, scalar or vector.
;
; OUTPUTS:
;       Ra    The right ascension in RADIANS of the zenith.
;       Dec   The declination in RADIANS of the zenith.
;
; PROCEDURE:
;       The local sidereal time is computed; this is the RA of the zenith.
;       It and the observatories latitude (corresponding to the Dec.) are
;       converted to radians and returned as the zenith direction.
;
; PROMPTS:
;       ZENPOS will prompt for the following 3 parameters if they are not
;       defined in the common block SITE (see below)
;
;       LAT,LNG - north latitude and east longitude of the desired location 
;               in DEGREES
;       TZONE - Time Zone (in hours) of the desired location (e.g. 4 = EDT,
;               5 = EST)
;
; COMMON BLOCKS:
;       SITE - This common block should contain the three scalars LAT, LNG
;               and TZONE
;
; PROCEDURE CALLS:
;       CT2LST - Convert to Local Mean Sidereal Time
; MODIFICATION HISTORY:
;       Written by Michael R. Greason, STX, 14 October 1988.
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Update documentation, longitude now *east* of Greenwich W.L. July 2000

; NAME:
;      ZOOM_XY
; PURPOSE:
;       Converts X, Y position on the image array to the the X,Y position 
;       in the current window.   (These  positions are identical 
;       only for an unroamed, zoomed image with with pixel (0,0) of the 
;       image placed at position (0,0) on the TV.)
;
; CALLING SEQUENCE:
;      ZOOM_XY, Xim,Yim,Xtv,Ytv, [ OFFSET =, ZOOM = ]
;
; INPUTS:
;      XIM - Scalar or vector giving X position(s) as read on the image
;            display (e.g. with CURSOR,XIM,YIM,/DEVICE)
;      YIM - Like XTV but giving Y position(s) as read on the image display.
;
;      If only 2 parameters are supplied then XIM and YIM will be modfied
;      on output to contain the converted coordinates.
;
; OPTIONAL KEYWORD INPUT:
;      OFFSET - 2 element vector giving the location of the image pixel (0,0) 
;               on the window display.   OFFSET can be positive (e.g if the 
;               image is centered in a larger window) or negative (e.g. if the
;               only the central region of an image much larger than the window
;               is being displayed. 
;               Default value is [0,0], or no offset.
;
;       ZOOM - Scalar specifying the magnification of the window with respect
;               to the image variable.
; OUTPUTS:
;      XTV,YTV - REAL*4 X and Y coordinates of the image corresponding to the
;            cursor position on the TV display.   Same number of elements as
;            XIM, YIM.
;
; NOTES:
;       The integer value of a pixel is assumed to refer to the *center*
;       of a pixel.
; REVISON HISTORY:
;       Adapted from MOUSSE procedure of the same name W. Landsman HSTX Mar 1996
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Properly include ZOOM keyword  W. Landsman   May 2000

; NAME:
;       ZPARCHECK
; PURPOSE:
;       Routine to check user parameters to a procedure
;
; CALLING SEQUENCE:
;       zparcheck, progname, parameter, parnum, types, dimens, [ message ]
;
; INPUTS:
;       progname  - scalar string name of calling procedure
;       parameter - parameter passed to the routine
;       parnum    - integer parameter number
;       types     - integer scalar or vector of valid types
;                1 - byte        2 - integer   3 - int*4
;                4 - real*4      5 - real*8    6 - complex
;                7 - string      8 - structure 9 - double complex
;               10 - pointer    11 - object ref 12 - Unsigned integer
;               13 - unsigned int*4 
;               14 - int*8  
;               15 - Unsigned int*8
;       dimens   - integer scalar or vector giving number
;                     of allowed dimensions.
; OPTIONAL INPUT:
;       message - string message describing the parameter to be printed if an 
;               error is found
;
; OUTPUTS:
;       none
;
; EXAMPLE:
;       IDL> zparcheck, 'HREBIN', hdr, 2, 7, 1, 'FITS Image Header'
;
;       This example checks whether the parameter 'hdr' is of type string (=7)
;       and is a vector (1 dimension).   If either of these tests fail, a 
;       message will be printed
;               "Parameter 2 (FITS Image Header) is undefined"
;               "Valid dimensions are 1"
;               "Valid types are string"        
;
; SIDE EFFECTS:
;       If an error in the parameter is a message is printed
;       a RETALL issued
;
; HISTORY
;       version 1  D. Lindler  Dec. 86
;       documentation updated.  M. Greason, May 1990.
;       Recognize double complex datatype    W. Landsman   September 1995
;       Converted to IDL V5.0   W. Landsman   September 1997
;       Check for new data types (e.g. unsigned) W. Landsman February 2000