Group K Library

This page is a listing of the entire contents of this library for IDL. This listing is the long version. Viewing the much more compact listing may be handier.

[Go Back to Main IDL Libraries Search Page]


Last modified: Thu Dec 21 21:19:38 2000.

List of Routines


Routine Descriptions

ACNVRT

[Next Routine] [List of Routines]
 NAME:
        ACNVRT

 PURPOSE:
        This function converts the HEAO A-1 quasi-logarithmic numbers
        to HEAO A-1 Science Data and vice versa.

        HEAO A-1 quasi-logarithmic number format:
        (8 BITS) - CCCMMMMM (C=CHARACTERISTIC, M=MANTISSA)

        These quasi-logarithmic numbers are the result of the onboard
        HEAO A-1 quasi-logarithmic scalars and are present in the raw
        2.1 kbps A-1 portion of the NRZ data.

 CATEGORY:
        HEAO.

 CALLING SEQUENCE:

        Result = ACNVRT( Data )

 INPUTS:
        Data:     Array of any dimensions containing either the HEAO A-1
                  quasi-logarithmic numbers OR the HEAO A-1 Science
                  Data.

 OPTIONAL INPUT KEYWORD PARAMETERS:

        INVERSE:  Set this keyword to convert A-1 Science Data to
                  HEAO A-1 quasi-logarithmic numbers, (0=Default).

 OUTPUTS:
        This function returns A-1 Science Data converted from the input
        Data array or A-1 quasi-logarithmic numbers, if the INVERSE keyword
        is set.

 MODIFICATION HISTORY:
        Written by:    Daryl J. Yentis, Naval Research laboratory, SSD 1980.
        13-JUN-1994    H.C. Wen - Adapted to IDL; added INVERSE keyword.

(See /host/bluemoon/usr2/idllib/contrib/groupk/acnvrt.pro)


ARR2STR

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        ARR2STR

 PURPOSE:
        Converts an array of numbers to a string of numbers separated
        by commas.

 CATEGORY:
        STRLIB.

 CALLING SEQUENCE:

        Result = ARR2STR( Array [, Nsig ] )

 INPUTS:
        Array:    Array of numbers to convert.

 OPTIONAL INPUTS:
        Nsig:     Number of significant figures to keep when converting
                  each number to a string.

 OUTPUTS:
        Returns a string containing the elements of the Array parameter
        separated by commas.

 MODIFICATION HISTORY:
        Written by:    Han Wen, October 1994.
        23-APR-1995    Convert byte arrays to integers before applying the STRING
                       function.
        31-OCT-1995    Added ON_ERROR,2
        19-NOV-1995    Remove leading/trailing blank spaces.

(See /host/bluemoon/usr2/idllib/contrib/groupk/arr2str.pro)


AVG_LC

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        AVG_LC

 PURPOSE:
        Plots the average light curves for a source, customized to
        the HEAO A-1 data.

 CATEGORY:
        HEAO A-1.

 INPUTS:

   Time:     Array of times in SECONDS since 1/1/77, [dblarr( npts )].

   Flux:     Array of corresponding intensities for the source,
             [fltarr( npts )] in units specified by the FLUX_UNITS keyword.

   Err:      Array of corresponding uncertainties for each intensity
             [fltarr( npts )] in units specified by the FLUX_UNITS keyword.

   SrcName:  The name of the source, [string].

 OPTIONAL INPUT PARAMETERS:

   FLUX_UNITS:    The units of the given intensities, [string], (''=Default).

   BINSIZE:       Time binsize of the average light curve in DAYS.

 OUTPUTS:

        This routine makes light curves of the HEAO A-1 data and sends
        them to the graphic device if the USER selects it from the widget
        menu.

 MODIFICATION HISTORY:
   September, 1994          H.C. Wen
   12-JAN-1995              Added the BINSIZE keyword
   01-FEB-1995              Implemented XPLOT, XOPLOT
   08-FEB-1995              Eliminated the HALF keyword for simplicity.

(See /host/bluemoon/usr2/idllib/contrib/groupk/avg_lc.pro)


BARYCORR

[Previous Routine] [Next Routine] [List of Routines]
        FUNCTIONAL DESCRIPTION:

        Function calculates the satellite's position in barycentric
        coordinates, then calculates a time correction based no the
        projection of the satellite's position vector into the source
        direction (from the Earth).  Thus the time is corrected to a
        fixed point on the Earth-source line, such that the line joining
        that point to the barycenter is pependicular to the Earth-source
        line.

 INPUT PARAMETERS:

        SRCVEC  floating-point array giving the unit 3-vector to from the
             Earth to the source object, in celestial coordinates.

        SATVEC  floating-point array giving the satellite's position
             3-vector relative to Earth-center, in kilometers.

        JTIME     double-precision modified Julian date for which the
             correction is to be calculated (JD1950) in days.

 OUTPUT PARAMETERS:

        None.

 RETURNS:

        BARY_CORR = (double-precision) delta-time (seconds) which, when
                 added to JTIME, gives the time at the correction point
                 discussed above.

 NOTES:

        This code based on SUBROUTINE BARYTIME written by Lynn Cominsky.

 AUTHOR/DATE:          K.H. Fairfield,           04-DEC-1992

(See /host/bluemoon/usr2/idllib/contrib/groupk/barycorr.pro)


CAPTURE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        CAPTURE

 PURPOSE:
        Captures the current graphics screen and saves it to an image file.

 CATEGORY:
        I/O.

 CALLING SEQUENCE:

        CAPTURE

 OPTIONAL INPUT KEYWORD PARAMETERS:

        BMP:      Set this keyword to send a BMP image to the printer, (1=Default).

        GIF:      Set this keyword to send a GIF image to the printer, (0=Default).

        JPEG:     Set this keyword to send a JPEG image to the printer, (0=Default).

        FILENAME: Filename of the image file (picnnn.bmp,gif,jpg=Default).

 PROCEDURE:
        The current graphics screen is saved to an image file.

 EXAMPLE:
        plot,indgen(100),xtitle='This is the x-axis',ytitle='Y-Axis'
        xyouts, 0.3, 0.94, 'Title.. So What.. Big Deal', CHARSIZE=1.4, /NORMAL
        CAPTURE

 MODIFICATION HISTORY:
        Written by:    Han Wen, July 1995.

(See /host/bluemoon/usr2/idllib/contrib/groupk/capture.pro)


CK_VER

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        CK_VER

 PURPOSE:
        This function checks the validity of the Version number of a DATA
        structure created by the FIDUCIAL routine.

 CATEGORY:
        HEAO A-1.

 CALLING SEQUENCE:

        Result = CK_VER( Data )

 INPUTS:
        Data:     Structure created by the FIDUCIAL routine and saved to
                  an IDL SAVE session file (*.sav).

 OPTINOAL INPUT KEYWORD PARAMETERS:

        VERSION:  The version number of the Data structure must be greater
                  than or equal to this value (3=Default).

 OUTPUTS:
        Returns a 1 if the structure is a valid DATA structure created by
        FIDUCIAL version=VERSION or later, or a 0 otherwise.


 MODIFICATION HISTORY:
        Written by:    Han Wen, February 1995.

(See /host/bluemoon/usr2/idllib/contrib/groupk/ck_ver.pro)


CLEAN_UP

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        CLEAN_UP

 PURPOSE:
        Cleans up "garbage" log files created by the
        NEW_JOURNAL routine.

 CATEGORY:
        I/O.

 CALLING SEQUENCE:

        CLEAN_UP, LogPath

 INPUTS:

        LogPath:  Path to your existing NEW_JOURNAL log files,
                  (e.g. 'd:\rsi\idl40\bob\log\')

 OPTIONAL INPUT KEYWORD PARAMETERS:

        TODAY:    Mark all log files created today for possible deletion, (0=Default).
                  If this keyword is set then the CUTOFF keyword is ignored.

        CUTOFF:   The largest NEW_JOURNAL log file in BYTES to potentially
                  delete, (1000=Default).

        ALL:      Set this keyword to mark ALL log files found, (0=Default).

        NOCONFIRM:     Set this keyword to AUTOMATICALLY delete any
                  NEW_JOURNAL log files smaller than CUTOFF.  The USER
                  will NOT be notified, (0=Default).

 PROCEDURE:
        A list of NEW_JOURNAL files that are smaller than CUTOFF is displayed
        to the USER.  The USER may then select any of these files to view
        their contents and either keep or delete the log files.

 RESTRICTIONS:
        Currently the only OS platforms supported by this routine
        are: Windows/DOS and Unix.

 MODIFICATION HISTORY:
        Written by:    Han Wen, August 1995.
        21-AUG-1995    Keep string lengths < 80 characters, added TODAY keyword,
                       delete log files together.
        27-SEP-1995    Eliminated text-wrap for efficiency.  Read in text more
                       efficiently into arrays; concatenation is VERY inefficient.
                       Added ALL keyword.
        29-SEP-1995    Only display first 900 lines of text for efficiency.  A
                       More ... line will appear if the log file is > 900 lines.
                       Check for 0-length files.
        06-DEC-1995    Forgot to close any 0-length files before attempting to
                       delete them.
        07-AUG-1996    Eliminate call to VERSION().

(See /host/bluemoon/usr2/idllib/contrib/groupk/cleanup.pro)


CLEAR_SCAN

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        CLEAR_SCAN

 PURPOSE:

        Resets all the common block structure to 0.

 CATEGORY:
       I/O

 CALLING SEQUENCE:

        CLEAR_SCAN

 RESTRICTIONS:
        Remember, when you exit an IDL routine or program, any common
        block variables are still defined!

 MODIFICATION HISTORY:
        Written by:  H.C. Wen, May, 1994.
        15-MAY-1994  Added an end-of-file flag for each file buffer, eofb.
        26-JUN-1994  Reduced the multi-common, multi-variables to ONE common
                     and ONE structure, buf.
        01-AUG-1994  Formerly called CLEAR_BUF

(See /host/bluemoon/usr2/idllib/contrib/groupk/init_scan.pro)


COLLDIRS

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        COLLDIRS

 PURPOSE:
        This procedure determines the viewing direction(s) of one
        of the HEAO A-1 collimators.

 CATEGORY:
        HEAO A-1 Geometry.

 CALLING SEQUENCE:
        COLLDIRS, Module,RAY,DEY,RAZ,DEZ [,RAc,DECC]

 INPUTS:
       Module:    Module number of the collimator (1-7), [integer].
      RAY,DEC:    The RA,DEC  of the satellite's Y-axis in RADIANS, [float(nbin)].

 OPTIONAL OUTPUTS:
     RAc,DECc:    The RA,DEC of the collimator viewing direction, [float(nbin)].

 OPTIONAL KEYWORD OUTPUTS:
           RC:    The unit direction vector in spherical coordinates of the
             collimator viewing direction, [float(3,nbin)].

 RESTRICTIONS:
        NOTE: you can also call this routine with scalar input arguments.

 EXAMPLE:
        let's choose a RA,DEC near the poles and determine the
        viewing direction for collimator 3.

        RA = 75.5*!dtor
        DEC= 89.8*!dtor

        COLLDIRS, 3, RA, DEC, RA_M3, DEC_M3, RC=Vec_M3

 MODIFICATION HISTORY:
        Written by:    Han Wen, June 1994.

(See /host/bluemoon/usr2/idllib/contrib/groupk/colldirs.pro)


COLLF

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        COLLF

 PURPOSE:
        Function to return the HEAO A-1 collimator response function,
        that is, transmission or efficiency, for a given detector module.

 CATEGORY:
        Collimator.

 CALLING SEQUENCE:
        Result = COLLF( Module,Ras,Des,Ray,Dey,Raz,Dez [,Theta,Phi])

 INPUTS:
       Module:    Module number, in range 1-7, [integer].

      Ras,Des:    The RA, DEC of the source in RADIANS, [float].

      Ray,Dey:    The RA, DEC of the +Y axis in RADIANS, [float] or [float(nbin)].

      Raz,Dez:    The RA, DEC of +Z axis in RADIANS, [float] or [float(nbin)].

 OUTPUTS:
        This function returns the collimator response function (transmission)
        for the given direction(s) specified by the aspect information,
        [float] or [float(nbin)].

 OPTIONAL OUTPUTS:
    Theta,Phi:    The collimator position angles defined in COLLMATR
             in RADIANS, [float] or [float(nbin)].

 MODIFICATION HISTORY:
        Written by:    Daryl J. Yentis, Naval Research Laboratory, SSD 1980.
        12-NOV-1992    K.H. Fairfield, change to IMPLICIT NONE; use
                       Fortran 77 block structure.
        22-JUN-1994    H.C. Wen, converted into an IDL routine, vectorized
                       routine to accept vector inputs.

(See /host/bluemoon/usr2/idllib/contrib/groupk/collf.pro)


COLLINIT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        COLLINIT

 PURPOSE:

     To convert this into IDL code, the COMMON CLLMTR is needed to store
     these coefficients as static variables.

                       H.C. Wen, 22-JUN-1994

     NRLDIR:COLLMAT.INC
     ==================

     Include file which declares the coefficient arrays, A,B,C,D,E,F,G,H,
     and WT,WP, TF, and PF, used in the function COLLMATR to calculate
     the collimator transmission function.  Comments below from the
     original NRL code.  The orignal was a SUBROUTINE with DATA initiali-
     zation statements for the arrays in COMMON /CLLMTR/.  This INCLUDE
     file obviates the need for a COMMON, which has been removed.

                       K.H. Fairfield, 12-NOV-1992

 Original Comments:

     06/29/77 KINZER-MEEKINS
     03/29/78 JALAL SAMIMI----MODIFIED USING CRAB OBSERVATIONS.
     08/29/78 SNYDER
     10/25/78 MEEKINS

     For more information than is contained herein see the paper,
     Kinzer, HEAO Collimators Monte-Carlo Simulation.  This routine (sic)
     is used to both act as a single repository of collimator data and
     to supply this data to the user if desired.  Note that this routine
     should be called before any data in the COMMON BLOCK, CLLMTR, is
     used.  The collimator number, I, identifies the collimator:
     I=1(4x1), =2(2x8), =3(1/2x1), =4(1/2x1), =5(SUM 4x1s). Values given
     are for one keV, values for energies up to 20 keV are identical.
     THETA is the angle to coll zenith in the plane of the coll zenith
     and the s/c spin axis.

     PHI is the angle to collimator zenith in the plane orthogonal to
     the spin axis.  Offsets in both THETA and PHI have been included
     (TF and PF) in order that intentional or unintentional
     misalignments with the s/c look direction (Y-axis) be treated.
     THETA is positive when toward the spin axis, PHI is positive in
     direction of spin. The collimator response has been fit to cubic
     polynomials.  An algorithm for calculating the collimator response,
     CR, for a look angle (TH,PH, measured wrt the Y-axis) might be as
     follows (T is equiv. to THETA and P is equiv. to PHI):

         T=ABS(THETA-TF)
         P=ABS(PHI-PF)
         CRT=A+T*(B+T*(C+T*D))
         CRP=E+P*(F+P*(G+P*H))
         CR=CRT*CRP
         IF((P.GT.WP).OR.(T.GT.WT)) CR=0.

     Note that THETA and PHI must be in radians and that WT,TF,WP, and
     PF are in radians.

 CATEGORY:
        Collimator.

 CALLING SEQUENCE:
        COLLINIT

 INPUTS:     None.

 OUTPUTS:
        This routine initializes the CLLMTR common so that the routines,
        COLLMATR and COLLF may be subsequently used.

 COMMON BLOCKS:
        CLLMTR:   Coefficient arrays which hold information needed to
             calculate the collimator transmission function.

 RESTRICTIONS:
        You must call this routine before using COLLMATR or COLLF.  Currently,
        COLLMATR automatically calls COLLINIT if the WT variable has not
        been initialized.

 MODIFICATION HISTORY:
        Written by:    See Above.
        22-JUN-1994    H.C. Wen, converted include file into an IDL routine.
        15-AUG-1995    Comment bugfix: removed extraneous ;+ and ;-.

(See /host/bluemoon/usr2/idllib/contrib/groupk/collinit.pro)


COLLMATR

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        COLLMATR

 PURPOSE:

        For a given collimator (module) index, and given angle with
        respect to the collimator axis, calculates the transmission
        function.  See original comments below.

 CATEGORY:
        Collimator.

 CALLING SEQUENCE:
        Result = COLLMATR( I,TH,PH )

 INPUTS:
       I:    An integer giving the collimator index, in the range 1-5.

      TH:    A real value giving the angle THETA in RADIANS (see below).

      PH:    A real value giving the angle PHI in RADIANS (see below).


 OUTPUTS:
        This function returns the value(s) of the transmission function
        for the provided angles relative to the collimator axis
        in the range 0.0 to 1.0.

 COMMON BLOCKS:
        CLLMTR:   Coefficient arrays which hold information needed to
             calculate the collimator transmission function.

 MODIFICATION HISTORY:

  NOTES:

     The original comments refer to "ENTRY XXXX", while,
     in fact, there were NO entry points.  Instead, there is a computed
     GOTO which jumps (supposedly) to particular labels ("entry points").
     However, the GOTO variable, IENT, was LOCAL and defined to be zero
     on entry to this procedure, so ONLY the Collimator function was
     returned.   The other functions in the package were unavailable.
     See revision of 11/12/92 below.

  AUTHOR/DATE:         Meekins,       25-JUL-1979

  REVISIONS:

   H.C. Wen,           22-JUN-1994:
        Converted into an IDL routine, restored COMMON CLLMTR
        15-AUG-1995    Comment bugfix: removed extraneous ;+ and ;-.

   K.H. Fairfield,     12-NOV-1992:
       Changed to IMPLICIT NONE.  Removed COMMON /CLLMTR/ in favor of
   INCLUDE file data initailization of coefficient arrays.  Edited
   original comments.

       Separated each "entry" into its own function, each includes the
       coefficient-array data initialization file.  Makes the image
       smaller after linking; makes the "entry" points available to
       callers again.


  ORIGINAL COMMENTS:
  =================

     INSTRUMENT, HEAO-A1, COLLIMATOR.  CODED FOR CDC3800.

     This routine is used to find the following:

       Collimator function (entry COLLMATR)

       First Derivative of the collimator function wrt THETA (entry DCOLLDTH)

       First Derivative of the collimator function wrt PHI (entry DCOLLDPH)

       Integral of the collimator function over THETA, from
          -Infinity to THETA (entry COLLITH)

       Integral of the collimator function over PHI, from
          -Infinity to PHI (entry COLLIPH)

       Integral of the collimator function over THETA and PHI from
          -Infinity to THETA and PHI (entry COLLINT)


     All functions are evaluated at the angles THETA=TH and PHI=PH.
     Note that TH and PH must be in radians and that all functions are
     determined in radians. The collimator number, I, corresponds to
     the collimators as follows:

     I=1(4x1), =2(2x8), =3(1/2x1), =4(1/2x1), =5(ave of 4x1s)

     TH is the angle wrt the s/c Y-axis in the X-Y plane,
     PH is the angle wrt the s/c Y-axis in the Y-Z plane.

     Y-axis is the nominal detector look direction.
     X-axis is the roll axis.

     THETA is positive when toward the X-axis,
     PHI is positive in the direction of spin.

     Note that the COMMON BLOCK, CLLMTR, is used.  The data in this
     COMMON BLOCK are provided by the SUBROUTINE COLLMAT, which must
     be called before using this routine.

     WT (WP) and TF (PF) are the width and offset of the collimator in
     the THETA (PHI) directions.

        15-AUG-1995    Comment bugfix: removed extraneous ;+ and ;-.

(See /host/bluemoon/usr2/idllib/contrib/groupk/collmatr.pro)


CTIFMT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        CTIFMT

 PURPOSE:

        This routine concatenates and corrects all the data contained
        in a PTI file (created by HBRFMT).  All Adjacent Photon Events (APE)
        and any photons in BAD minor frames are removed.  A BAD minor frame
        occurs when there are one or more HBRSYNC errors (e.g. missing MNFs,
        Clock TicTok errors, sync loss, etc).  This concatenated and corrected
        data is then written to a binary file in the Concatenated Time
        Interval (CTI) format.

 CATEGORY:
        HEAO HBR.

 CALLING SEQUENCE:

        CTIFMT, FILES=Files, PTIPATH=PTIPath, CTIPATH=CTIpath

 INPUT KEYWORD PARAMETERS:

        FILES:    A array of filenames for each raw HBR digitized file.

        PTIPATH:  Path to the specified input PTI files, (''=Default).

        CTIPATH:  Path to the output CTI files, (''=Default).

 OPTIONAL INPUT KEYWORD PARAMETERS:

        QUIET:    Suppress all print messages to the display, (0=Default).

 OUTPUTS:
        The Concatenated Time Interval (CTI) format consists of 19 variable
        length records.  The first record contains a sequence of numbers:
        [0,1,2...511] that may be used to determine the byte order of the
        binary file relative to your current platform. Each subsequent
        record contains a 4-byte record header followed by data.  The record
        header should be read into a long integer and it contains the length
        of the data in BYTES. The 19 records are defined as follows:

        Record  Variable/         Description
        Number  Array
        ______  ______________  ______________________________________________

          0     intarr(512)     Numbered sequence: [0,1,2...511].  This record
                                may be used to determine the byte order of the
                                CTI binary file.  Namely, if it is Big Endian
                                or Little Endian.
          1     bytarr(nb)*     Name associated with this HBR data file,
                                SSS_TT_FF.  SSS=NRL sequence number,
                                TT=NRL tape number, FF=NRL file number on the
                                tape.
          2     bytarr(nb)      Name of the celestial target that the HBR
                                data is taken from.
          3     bytarr(nb)      Name of IDL procedure that created the CTI
                                file, 'CTIFMT.PRO'.
          4     bytarr(nb)      Date/time of CTI creation, SYSTIME().
          5     bytarr(nb)      Filename of the PTI file, including path.
          6     bytarr(nb)      IDL platform used to create CTI file, !VERSION.
          7     bytarr(nb)      Date/time of the HBR data acquisition.
          8     integer         Revolution number of the HEAO satellite during
                                HBR data acquisition.
          9     intarr(3)       Various HEAO A-1 electronics modes:
                                intarr(0):  Which modules selected for the
                                            random encoder -> HBR data:
                                            3  - modules 1-4
                                            7  - module 7
                                intarr(1):  Mode of the NRZ data:
                                            5  - 5 msec
                                            320- 320 msec
                                intarr(2):  Mode of the HEAO satellite:
                                            0  - scanning/spinning
                                            1  - pointing
         10     lonarr(nb/4)    Major frame numbers.
         11     intarr(512,nm)  Major frame headers** created by HBRFMT,
                                nm = nb/(512*2).
         12     intarr(16,nn)   Minor frame headers** created by HBRFMT,
                                nn = nb/(16*2).
         13     integer         Overall Global Data Validity flag (0=Ok, NO
                                HBRSYNC errors detected in entire data file).
         14     intarr(128,nr)  Normal 6.4 kbps telemetry data (NRZ),
                                nr = nb/(128*2).
         15     lonarr(nb/4)    Corrected photon time intervals.
         16     lonarr(nb/4)    Corresponding photon times relative to the
                                beginning of the minor frame containing the
                                first photon.
         17     lonarr(2,na)    The beginning and end of time regions where
                                one or more HBRSYNC error were detected.
                                The times are relative to the beginning of the
                                MNF containing the 1st photon, na = nb/(2*4).
         18     intarr(nb/2)    Number of Adjacent Photon Events (APE) found
                                in each MJF.


        *nb = the length of the data in BYTES, i.e. 4-byte record header.
        *All of the byte arrays are strings converted to their ASCII numbers
         equivalent.  To extract the string corresponding to a byte array,
         apply the string function, (e.g. str = string(b) where b=bytarr(nb))

        **For a complete description of the headers, see DEF_HBRH.PRO.

 RESTRICTIONS:

        The def_hbrh.pro routine must be previously compiled.

 COMMON BLOCKS:
        DEF_HBRH: Holds all the MJF and MNF PTI pointers, (see def_hbrh.pro).

 PROCEDURE:
        The PTI file is read in one MJF block of data at a time.  Adjacent
        Photon Events (APE) are removed using KILLAPE.PRO and any photons
        falling within BAD minor frame regions are also excluded.  The
        corrected PTIs are subsequently concatenated with the overall PTI
        array.  The MJF and MNF headers as well as the NRZ blocks are similarly
        concatenated.  Once all the MJF blocks have been read in and processed,
        the concatenated arrays are then written to binary file in the CTI
        format described above.

 MODIFICATION HISTORY:
        Written by:    Han Wen, September 1995.
        18-SEP-1995    Bugfix: Eliminate non-existing NRZ data associated with
                       each MNF header containing missing MNFs.
        26-SEP-1995    Added the DBS tag.
        27-SEP-1995    Moved Date & File tags into Origin; expanded Origin tag;
                       added Name and GDV tag.
        29-SEP-1995    Take care of possible 16-bit overflows in DELBEG and DELEND.
        30-SEP-1995    Transferred to task of removing non-existing NRZ data to
                       READPTI; take care of missing MJF possibility; changed
                       version tag from named (!version) to anonymous structure
                       to avoid incompatibilities across different versions of IDL.
        09-OCT-1995    Formerly, CATPTI.  Write out binary file in CTI format
                       instead of saving a structure variable to an IDL save
                       session.

(See /host/bluemoon/usr2/idllib/contrib/groupk/ctifmt.pro)


CUBIC

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        CUBIC

 PURPOSE:
        Solve for the roots of a cubic polynomial OR
        find the value(s) of a cubic polynomial (INVERSE)

 CATEGORY:
        Math.

 CALLING SEQUENCE:

        Result = CUBIC( X, Coeff )

 INPUTS:
        X:   For the forward transform, it is the VALUE of the cubic
             polynomial. If the INVERSE keyword is set then it is
             the ARGUMENT of the cubic polynomial.

        Coeff:    Array of coefficients of the cubic polynomial, fltarr(4).

 KEYWORD PARAMETERS:

        INVERSE:  Set this keyword to determine the value of the cubic
             polynomial, (0=Default).

 OUTPUTS:
        Returns the ARGUMENT of a cubic polynomial for the forward
        transform or the VALUE of a cubic polynomial for the inverse
        transform (if the INVERSE keyword is set).

 MODIFICATION HISTORY:
        Written by:    Han Wen, October 1994.

(See /host/bluemoon/usr2/idllib/contrib/groupk/cubic.pro)


CUSPOLYN

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
   CUSPOLYN

 PURPOSE:
   This function returns a "cusp" polynomial determined by a given set of
   coefficients.

 CATEGORY:
   Curve and surface fitting.

 CALLING SEQUENCE:
   Result = CUSPOLYN( Degree, X, Y, Coeff [,/MATRIX])

 INPUTS:

   Degree:   The degree (in one dimension) of the 2D polynomial, [integer].

      X,Y:   The x- and y-vectors [double(npt)].

    Coeff:   The vector of coefficients for the cusp-polynomial,
         which is dimensioned as [double( (Degree+1)^2 )]. (See SFITCUSP)

 INPUT KEYWORDS:

   MATRIX:   Treat X as a "row" vector and Y as a "column" vector and find
         the cusp-polynomial matrix associated with this XY-matrix.

 OUTPUT:
   This function returns the values of the cusp-polynomial at the values
   set by the X and Y vectors, [double(npt)] OR [double(nx,ny)] if MATRIX
   keyword is set.

 PROCEDURE:
   The cusp-polynomial is defined as:
       F(x,y) = Sum over i and j of coeff(i*(degree+1)+j) * abs( x^i * y^j )

 MODIFICATION HISTORY:
   July, 1994               H.C. Wen
   24-AUG-1994              Added MATRIX keyword to return a fit "matrix"
                            Return a fit "matrix" whose x-component is
                            defined by the x array and y-component is defined
                            by the y array. (i.e. fit_matrix( x, y ))

(See /host/bluemoon/usr2/idllib/contrib/groupk/cuspolyn.pro)


DEADCORR

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        DEADCORR

 PURPOSE:
        This function corrects for dead time in the HEAO A-1 detector.
        The dead time and collimator response function were fitted for
        using the data on the Crab from module 3 ONLY.

 CATEGORY:
        HEAO A-1 Scanning.

 CALLING SEQUENCE:

        Result = DEADCORR( Mode, Cts )

 INPUTS:
        Mode:     Scanning timing mode in MILLISECONDS (320 ms or 5 ms).

        Cts:      Array of HEAO A-1 counts, UNCORRECTED for dead time.

 OPTIONAL INPUT KEYWORD PARAMETERS:

        EXTENDED: Set this keyword to specify extended or paralyzable
                  dead time corrections.  Otherwise, NON-extended or
                  NON-paralyzable dead time corrections will be made, namely,
                  (0=Default).

 OUTPUTS:
        An array of counts, CORRECTED for dead time is returned.

 OPTIONAL INPUT KEYWORD PARAMETERS:

        OTAU:     Dead time used to correct the data in MICROSECONDS.

        ONC:      Charged particle rate assumed in COUNTS/mode.

 COMMON BLOCKS:
        DEADCORR:   Dead times and charged particle rates used by this
             routine. See DEADINIT.

 RESTRICTIONS:
        The dead time used in this routine (14.4 microsec, NON-extended)
        has been determined by studying ONLY collimator module 3 data on
        the Crab.

 MODIFICATION HISTORY:
        Written by:    Han Wen, 10-3-94.

(See /host/bluemoon/usr2/idllib/contrib/groupk/deadcorr.pro)


DEADINIT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        DEADINIT

 PURPOSE:
        This procedures defines the dead times and charged particle rates
        used to correct HEAO A-1 scanning counts for dead time.

 CATEGORY:
        HEAO A-1 Scanning.

 CALLING SEQUENCE:

        DEADINIT

 COMMON BLOCKS:
        DEADCORR:   Dead times and charged particle rates defined here.

 RESTRICTIONS:
        The dead time used in this routine (14.4 microsec, NON-extended)
        has been determined by studying ONLY collimator module 3 data on
        the Crab.

 PROCEDURE:
        This routine is automatically called by DEADCORR.  The USER does
        not have to call this routine.

 MODIFICATION HISTORY:
        Written by:    Han Wen, 10-3-94.

(See /host/bluemoon/usr2/idllib/contrib/groupk/deadinit.pro)


DEF_HBRDBS

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        DEF_HBRDBS

 PURPOSE:
        This routine defines the HEAO HBR database containing info on each
        HEAO HBR data file.

 CATEGORY:
        HEAO HBR.

 CALLING SEQUENCE:

        DEF_HBRDBS

 OPTIONAL INPUT KEYWORD PARAMETERS:

        VERBOSE:  Set this keyword to output a detailed listing of the
                  HBR database structure.

 OUTPUTS:
        A common block structure variable, HBRDBS_ gets defined. HBRDBS_ is
        an array of structures, one element for each HBR data file. The tags
        of each structure are defined as follows:

             SLAC:     Structure describing the location of the file in
                       the SLAC silos. The tags of this structure are:

                       volser:   Volume serial number
                       seq:      Sequence number

             NRL:      Structure describing the location of the file at NRL.
                       The tags of this structure are:

                       seq:      Sequence number of the ANALOG tape ..
                       tape:     Tape number of the DIGITIZED tape ..
                       file:     File number on the DIGITIZED tape ..
                                 .. containing this HBR data file.

             chron:    Structure describing when the HBR data was downlinked
                       to the ground station. The tags of this structure are:

                       dd:       Day of the month (1-31)
                       mn:       Month (1-12)
                       yy:       Year (1977-1978)
                       hh:       Hour (0:23)
                       mm:       Minute (0:59)
                       ss:       Seconds (0:59)
                       doy:      Day of the year (1:365)
                       JD:       Julian day number, long

             mode:     Structure describing the current modes of the HEAO
                       electronics and satellite. The tags of this structure are:

                       config:   String describing K. Woods configuration notes
                       HBR:      Mode of HEAO Random Decommutator,
                                 {'bit','frame' or 'word')
                       PM:       Describes which modules have been selected for
                                 HBR data,(3 = Scan modules, 1-4; 7 = Module 7).
                       NRZ:      Mode of the NRZ data, (5 = 5ms; 320 = 320ms).
                       sat:      Describes the state of the satellite,
                                 ('S' = spinning/scanning; 'P' = pointing)

             rev:      HEAO satellite revolution number, integer.

             pass:     Ground station pass abbreviation, ('H' = Hawaii;
                       'G' = 'Guam';...).

             length:   Length of the data in MINUTES, float.

             target:   Description of the celestial target, string.

             comments: Miscellaneous comments, string.

 COMMON BLOCKS:
        DEF_HBRDBS:    This common block holds all the info on each HEAO HBR
                  data file in its structure array, HBRDBS_.

 PROCEDURE:
        The HBRDBS.SAV file, which contains the HBRDBS_ structure is restored.

 MODIFICATION HISTORY:
        Written by:    Han Wen, September 1995.
        06-AUG-1996    Simplified directory structure, added VERBOSE keyword.

(See /host/bluemoon/usr2/idllib/contrib/groupk/def_hbrdbs.pro)


DEF_HBRH

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        DEF_HBRH

 PURPOSE:
        This routine defines all the pointers and bits to the Major Frame
        and Minor Frame headers for the Photon Time Interval (PTI) format.

 CATEGORY:
        HEAO HBR.

 CALLING SEQUENCE:

        DEF_HBRH

 OUTPUTS:
        A common block gets filled with pointer and bit values.  See below
        for definition of the common block.

 COMMON BLOCKS:
        DEF_HBRH: This common block holds all the pointers and bits to the
                  MJF and MNF headers.

                  NWMJFH:   Length of a MJF header in WORDS
                  MJFptr_:  A structure containing the index values and their
                            associated names of all the pointers to the MJF
                            header.
                  MJFbit_:  A structure containing the bit values and their
                            associated names of the MJF Flags variable.
                  MJFmark:  Value of the MJF marker.

                  NWMNFH:   Length of a MNF header in WORDS
                  MNFptr_:  A structure containing the index values and their
                            associated names of all the pointers to the MNF
                            header.
                  MNFbit_:  A structure containing the bit values and their
                            associated names of the MNF Flags variable.
                  MNFmark:  Value of the MNF marker.

        (*Note: For a description of each pointer or bit, see DEF_HBRH.pro)

 MODIFICATION HISTORY:
        Written by:    Han Wen, July 1995.

(See /host/bluemoon/usr2/idllib/contrib/groupk/def_hbrh.pro)


DEF_MJF

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        DEF_MJF

 PURPOSE:
        Defines the anonymous major frame data structure appropriate
        for the given data file.

 CATEGORY:
        I/O

 CALLING SEQUENCE:
        Result = DEF_MJF( Unit [, FORMAT=Format] )

 INPUTS:
         Unit:    Logical unit associated with the data file.

 INPUT KEYWORD PARAMETERS:
       FORMAT:     String describing the format of the data file.
             The following formats are defined:

             ================================================================
             ASPECTS  :  This is the "current" data format (11/14/94)
                         used by FMT_IDL.  The resulting structure tags
                         or members are defined as follows:
             ----------------------------------------------------------------

             Format   :  Name of the file format = 'ASPECTS'

             Mjf      :  Major frame number, [long integer].

             Mode     :  Timing mode of the scan in milliseconds (320 or 5).

             Module   :  Module number (3, 4, 5, 6 or 7).

             T77i,T77f:  Integer,fraction of time at the start of major frame in seconds
                         since 1977, [long integer, double].

             T77c     :  Barycentric time correction for the primary source
                         at the beginning and end of the major frame in
                         seconds, [ double(2,nsrc) ].

             Raz,Dez  :  The RA,DEC of the satellite's Z-axis at the start of
                         this major frame in DEGREES, [double].

             Sat      :  Structure holding information about the satellite's
                         position with the following tags defined:

                         xyz     : Satellite 3-vector from the earth at
                                   the beginning and end of the major frame,
                                   [ float( 3,2 )].
                         aspects : Structure holding the aspects of the
                                   satellite at each bin with the following
                                   tags defined:

                                   y  : The RA and DEC of the y-axis
                                        in RADIANS, [ float( 2, nbin )]
                                   z  : The RA and DEC of the z-axis
                                        in RADIANS, [ float( 2, nbin )]

             Ray,Dey  :  The RA of the satellite's Y-axis at the start of
                         this major frame in DEGREES, [double].

             Nsrc     :  Number of sources = 1 (Kept to maintain backward
                         compatibility with the STANDARD format).

             Srcnam   :  Name of the primary source, [string].

             SrcRA    :  RA of the primary source in DEGREES, [ double ].

             SrcDEC   :  DEC of the primary source in DEGREES, [ double ].

             Nbin     :  Number of bins in each major frame.

             Cts      :  An array holding the counts for this major frame,
                         [ float(nbin) ].

             Trns     :  A 1 x nbin array holding the transmission
                         functions of the primary source for this major frame,
                         [float( 1, nbin )].

             ================================================================
             STANDARD :  This is the "standard" data format most
                         commonly used by FMT_SRCDATA.  This format contains
                         information for multiple sources specified by
                         the user in FMT_SRCDATA. It is identical to the
                         ASPECTS format with the omission of the tags:
                                      ( sat, format )
                         and modifications to the following tags:
             ----------------------------------------------------------------

             T77c     :  Barycentric time correction for each source at the
                         beginning and end of the major frame in seconds,
                         [ double(2,nsrc) ].

             Nsrc     :  The number of sources for which transmission
                         functions are given in the data, (1-20).

             Srcnam   :  A string array of the names of the sources,
                         [string( Nsrc)].
             SrcRA    :  An array of the source RA's in DEGREES, [ double( Nsrc ) ].

             SrcDEC   :  An array of the source DEC's in DEGREES, [ double( Nsrc ) ].

             Trns     :  A (Nsrc) x nbin array holding the transmission
                         functions of each source for this major frame,
                         [float( nsrc, nbin )].

             ================================================================
             NOBARY   :  This is an older data format whose structure is
                         identical to the STANDARD format except for the
                         omission of the T77c member.

             ================================================================
             DIRS     :  This format is identical to the NOBARY format
                         except for the addition of two new members:
             ----------------------------------------------------------------

             Phis     :  The scan longitude in RADIANS for each bin in the
                         major frame [double(nbin)].

             Thts     :  The scan latitude in RADIANS for each bin in the
                         major frame [double(nbin)].

 OUTPUTS:
        Returns the anonymous major frame data structure as described
        above under the FORMAT keyword specification.

 COMMON BLOCKS:
      MJF_COM:   Holds a copy of the data structure in the MJFstruc variable
             so that other routines can copy this anonymous structure. This
             method was chosen over a NAMED data structure because the
             dimension of some of the members or tags may change depending
             on different data files.

 RESTRICTIONS:
        This routine must be called before any calls to READ_MJF.

 EXAMPLE:

 EXAMPLE:
        Let's create some arrays and read in the first major frame of
        a data file with data from the Crab pulsar at 320 ms mode.

        openr,unit,'crab.idl',/GET_LUN
        MJFstrucvar = DEF_MJF( Unit )

        ISS = READ_MJF( Unit, DATA=Data )

 MODIFICATION HISTORY:
        Written by:    Han Wen, August, 1994.
        25-AUG-1994    Added the DIRS format for response function
                       calibration.

(See /host/bluemoon/usr2/idllib/contrib/groupk/def_mjf.pro)


DEVICE_MGR

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        DEVICE_MGR

 PURPOSE:

        Manages the graphics device for two "standard" orientations,
        LANDSCAPE (default) and PORTRAIT.

 CATEGORY:
        I/O.

 CALLING SEQUENCE:

        DEVICE_MGR [, Dev]

 OPTIONAL INPUTS:

        Dev:      Name of the graphics device,[string]. If this argument
           is not provided then the graphics device defaults to
           'WIN' or 'X' depending on the OS.  Devices currently
           supported are: 'WIN','X','PS','PCL'

 OPTIONAL INPUT KEYWORD PARAMETERS:

        ORIENTATION:    Orientation of the graphics device output, either
                  'LANDSCAPE' (default) or 'PORTRAIT', [string].

        WINDOW:   If the graphics device is 'WIN' or 'X', this
                  keyword specifies the window number, 0=Default.

        CLOSE:    Set this keyword to close the current graphics
                  device.  If the curent graphics device is non-display,
                  then setting this keyword = 2 will additionally delete
                  the output file.

        PRINT:    Set this keyword to close the current output file and
                  send it to the printer as defined by the environment
                  variable, PRINTER.  Setting this keyword to 2 will
                  additionally delete the output file.

        QUERY:    If the graphics device is 'WIN' or 'X' and
                  the CLOSE keyword is set, then setting this keyword
                  will cause the USER to be queried for the deletion
                  of each open window.

        FILENAME: Filename and path of the output file for non-display
                  graphics devices.  If this keyword is not specified then
                  a TMP file is created in the appropriate tmp directory,
                  idl##### where ##### is a random number between 00000-99999.

        APPEND:   Appends the graphics device output to the current
                  output file.  The graphics device cannot be 'X' nor 'WIN'.

        SILENT:   Set this keyword if you do not want any informational
                  messages printed to the display. (0=Default)

        QUEUE:    String defining the printer device name, (e.g. 'ek_ps').
                  [Default=GETENV('PRINTER')]

        OTHER_KEYWORDS: Any other additional keywords are passed via
                  the _EXTRA keyword to either the WINDOW or the DEVICE
                  routine depending upon the graphics device.

 OUTPUTS:
        Output of the graphics device is either sent to the screen
        in a LANDSCAPE or PORTRAIT window, or to an output file depending
        upon the graphics device.

 OPTIONAL OUTPUT KEYWORD PARAMETERS:

        OFILENAME:     Filename and path of the output file for non-display
                  graphics devices.  This is useful if you did not specify
                  the FILENAME keyword and would like to know the name of the
                  TMP file created.

 COMMON BLOCKS:
        DEVMGR_COM:    This common block holds the filename of the
                       graphics output, dvmgr_fn.

 RESTRICTIONS:
        Currently the only OS platforms supported by this routine
        are: Windows/DOS and Unix.

 EXAMPLE:
        Create a simple plot and output it to both a window and an
        output file.

             x    = findgen(100)
             y    = 100.*exp(-((x-50.)/20.)^2. )
             DEVICE_MGR,'WIN'
             plot,x,y
             DEVICE_MGR,'PS'
             plot,x,y
             DEVICE_MGR,'PS',/close
             DEVICE_MGR,'WIN',/close


 MODIFICATION HISTORY:
        Written by:    Han Wen, November 1994.
        03-JAN-1995    Replaced INQUIRE with XQUERY.
        21-JAN-1995    Replaced XQUERY with YNCANCEL. (Added WSHOW before
                       and after YNCANCEL).
        23-JAN-1995    Added the RESET keyword
        25-JAN-1995    Renamed the common block variable names to more
                       obscure names (i.e. unlikely to be used by the USER).
        28-JAN-1995    Fixed a few minor bugs when closing multiple Windows.
        30-JAN-1995    Added the SILENT keyword, and CLOSE=2 option.
        08-FEB-1995    Changed default output filename from idltmpnn.ps to
                       idlnnnnn.ps
        29-APR-1995    Added the OFILENAME keyword.  I could have passed this
                       value to the FILENAME keyword, but I did not want to
                       overload its functionality.
        03-MAY-1995    >Added the ANONYMOUS_ keyword to avoid a very subtle/
                       rare bug with _EXTRA keyword. (Has no functionality
                       for the USER -> Internal user only.)
                       >Moved spawn print command to PRINT_FILE
        02-JUN-1995    Implemented VERSION routine.
        14-JUN-1995    Use WINDOW_STATE keyword to keep track of open
                       windows instead of devmgr_com.
        21-JUN-1995    Do NOT use SET_PLOT,dev if dev is the current device.
        19-OCT-1995    Added the PRINTER keyword.
        29-JUL-1996    Changed PRINTER keyword name to QUEUE. Added the PRINT
                       keyword.  HARDCOPY keyword now obsolete; although it
                       will still work to maintain backward compatibility.
        07-AUG-1996    Remove calls to VERSION(). Check OS platform.

(See /host/bluemoon/usr2/idllib/contrib/groupk/device_mgr.pro)


DIR_EXIST

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        DIR_EXIST

 PURPOSE:
        This function tests for the presence of a directory.

 CATEGORY:
        I/O.

 CALLING SEQUENCE:

        Result = DIR_EXIST( Dir )

 INPUTS:
        Dir       String holding the name of the directory you want to
                  test the existence of.

 OUTPUTS:
        This function returns 1 if the specified directory exists or
        0 if the specified directory does NOT exist.

 EXAMPLE:
        To check the existence of a '\TMP' directory type:

        iss = DIR_EXIST('\TMP')
        if (iss eq 1) then print,'TMP directory EXISTs.' $
        else print,'TMP directory does NOT exist.'

 MODIFICATION HISTORY:
        Written by:    Han Wen, June 1995.
                       Copied from !News TECH TIPS.

(See /host/bluemoon/usr2/idllib/contrib/groupk/dir_exist.pro)


DTPOIDEV

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        DTPOIDEV
 PURPOSE:
        Return an integer random deviate drawn from a dead-time-distorted
        Poisson distribution with a specified mean.  Adapted from POIDEV
        procedure in "Numerical Recipes" by Press et al. (1986), Section 7.3
        and IDL Astronomy User's library routine of the same name by
        Wayne Landsman.

 CALLING SEQUENCE:
        result = DTPOIDEV( Xm, Npts, Tinterval, Deadtime, [ SEED = ] )

 INPUTS:
        Xm:       Mean of the ORIGINAL (undistorted) Poisson distribution.

        Npts:     Number of deviates to generate.

        Tinterval:The length of the measuring time bin.

        Deadtime: The length of the NON-EXTENDED dead time in the SAME units
                  as Tinterval.

 OUTPUT:
        An array of deviates, [LONARR(Npts)].

 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 dead-time-distorted Poisson noise to an integral image array, im
             IDL> imnoise = POIDEV( im, 100, tbin, tau)

        (2) Verify the expected mean  and sigma for an input value of 81
             IDL> p = POIDEV( 81, 10000,1,1e-3) ;Test for 10,000 points
             IDL> print,avg(p),sigma(p)
        Average and sigma of the 10000 points should be close to
        81/(1+81*1e-3)=75 and (1+81*1e-3)^(-3/2)*9=8.

 RESTRICTIONS:
        Negative values in the input array will be returned as zeros.
        Note: there are very subtle correlations between sequential time bins
        in the presence of dead time.  The time interval between the beginning
        of a bin and the first count is correlated to the interval between
        the last count of the previous bin.  This correlation occurs when
        the time interval between the last count of the previous bin and the
        end of the time bin is less than the dead time.

 PROCEDURE:
        For small values (observed counts < 20) independent exponential
        deviates offset by a dead time are generated until their sum exceeds
        the specfied mean, the number of events required is returned as the
        Poisson deviate.   For large (observed counts > 20) values, uniform
        random variates are compared with a Lorentzian distribution function.

 REVISION HISTORY:
        Adapted from Landsman, POIDEV:     Han Wen, July 1996.
        26-JUL-1996    Bugfix: Lorentzian distribution function falls below
                       d-t-d Poisson distribution at low observed counts and
                       low means. Reapplied technique of independent exponential
                       deviates (with a dead time offset) for cases when the
                       observed counts falls below 20.

(See /host/bluemoon/usr2/idllib/contrib/groupk/dtpoidev.pro)


EATOM

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        EATOM

 PURPOSE:
        Generate rotation matrix given 3 euler angles

 CATEGORY:
        Analytic geometry.

 CALLING SEQUENCE:
        EATOM, A, B, C, D

 INPUTS:
            A:    First euler angle in radians, [float] or [float(nbin)].
            B:    Second euler angle in radians, [float] or [float(nbin)].
            C:    Third euler angle in radians, [float] or [float(nbin)].

        THE EULER ROTATION IS DEFINED AS FOLLOWS:
        1) ROTATE CCW BY ANGLE A ABOUT Z-AXIS GIVING X', Y', Z'-AXES
        2) ROTATE CCW BY ANGLE B ABOUT X'-AXIS GIVING X", Y", Z"-AXES
        3) ROTATE CCW BY ANGLE C ABOUT Z"-AXIS


 OUTPUTS:
            D:    Returned 3x3 rotation matrix as a 1-D array, [float(3,3)]
                  or [float(3,3,nbin)].

        REFERENCE:
        CLASSICAL MECHANICS, H. GOLDSTEIN, ADDISON WESLEY, 1950, P 107 FF
         The three euler angles define a coordinate system rotation
         from the original axes to a new set of axes.  The rotation
         matrix returned by EATOM rotates the coordinates of a vector
         in the original axes to the coordinates in the new set.
          x' = Dx


 MODIFICATION HISTORY:
        Written by:    K.H. Fairfield, 1993.
        06-JUN-94:     Modified into an IDL routine, H.C. Wen.
        22-JUN-94:     Vectorized routine to accept vector inputs

(See /host/bluemoon/usr2/idllib/contrib/groupk/eatom.pro)


END_SCAN

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        END_SCAN

 PURPOSE:

        Closes the data file used by GET_SCAN to extract
        HEAO A-1 data.

 CATEGORY:
       I/O

 CALLING SEQUENCE:

        END_SCAN

 INPUT KEYWORD PARAMETERS:

       NOWARN:    Suppress printing of warning messages to screen.

          LOG:    Output warning messages to log file.

 OUTPUTS:
        Closes the current data file associated with the buffer.

 MODIFICATION HISTORY:
        Written by:  H.C. Wen, May, 1994.
        15-MAY-1994  Changed logical unit to file pointer.
        26-JUN-1994  Eliminated multiple file option. Change file pointer
                     back to logical unit.
        01-AUG-1994  Formerly named CLOSE_BUF
        09-AUG-1994  Added the close statement

(See /host/bluemoon/usr2/idllib/contrib/groupk/init_scan.pro)


EQUIV

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        EQUIV

 PURPOSE:
        This procedure equates arrays of different integer types, similar to
        Fortran's Equivalence function.

 CATEGORY:
        I/O.

 CALLING SEQUENCE:

        EQUIV, Target, Source [, iTar, iSrc]

 INPUTS:
        Target:   Target array.

        Source:   Source array.

 OPTIONAL INPUTS:

        iTar:     Starting index of the target array.  If this parameter is
                  not provided, 0 is the default.

        iSrc:     Starting index of the source array.  If this parameter is
                  not provided, 0 is the default.

 OUTPUTS:
        Starting from index, iTar, the Target array gets filled with "equivalent"
        elements from the Source array starting from the Source index, iSrc up
        until the end of the Source or Target array depending upon which one ends
        first.

 PROCEDURE:
        Assuming iTar and iSrc = 0, if the Target is an integer array and the Source
        is a longword integer array, then the least significant 16-bits of Source are
        put into the "even" elements of Target, while the most signficant 16 bits of
        Source are put into the "odd" elements of Target.  If the situation is reversed,
        then the "even" elements of Source are put into the least significant 16-bits
        of Target, while the "odd" elements are put into the most significant 16-bits
        of Target.

 EXAMPLE:
        a = 1234567890L
        b = intarr(2)

        EQUIV,b,a

 MODIFICATION HISTORY:
        Written by:    Han Wen, July 1995.

(See /host/bluemoon/usr2/idllib/contrib/groupk/equiv.pro)


EULER2

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        EULER2
 PURPOSE:
        Transform between galactic, celestial, and ecliptic coordinates.
        Use the procedure ASTRO to use this routine interactively

 CALLING SEQUENCE:
        EULER, AI, BI, AO, BO, [ SELECT ]

 INPUTS:
        AI - Input Longitude in RADIANS, 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 RADIANS

 OPTIONAL INPUT:
        SELECT - Integer (1-6) specifying type of coordinate transformation.

        SELECT     From          To     |   SELECT      From            To
        1     RA-DEC(1950)   GAL.(ii)   |     5       ECLIPTIC       GAL.(ii)
        2     GAL.(ii)       RA-DEC     |     6       GAL.(ii)       ECLIPTIC
        3     RA-DEC         ECLIPTIC   |     7       System A       System B
        4     ECLIPTIC       RA-DEC     |     8       System B       System A

        If omitted, program will prompt for the value of SELECT

 OUTPUTS:
        AO - Output Longitude in RADIANS
        BO - Output Latitude in RADIANS

 REVISION HISTORY:
        Written W. Landsman,  February 1987
        Adapted from Fortran by Daryl Yentis NRL
        22-JUN-1994:   H.C. Wen, change angle units from degrees to radians.
                       Added SETSYB keyword, and 2 more conversion options:

                       System A to System B
                       ========    ========
                           System B:  z-axis = alongz,alatz
                               x-axis = alongx,alatx = zero azimuth (longitude)

                           PSI,THETA,PHI = F(alongz,alatz,alongx,alatx)
                                    initialized at ENTRY SETSYB.
                                             ----- ------
                           SYASYB, alongz,alatz,alongx,alatx
                           EULER2, along,alat,blong,blat, 7

                       System B to System A
                       ========    ========
                           PSI,THETA,PHI = F(alongz,alatz,alongx,alatx)
                                    initialized at ENTRY SETSYB.
                                             ----- ------
                           EULER2, blong,blat,along,alat, 8

        15-AUG-1995    Comment bugfix: removed extraneous ;+ and ;-.

(See /host/bluemoon/usr2/idllib/contrib/groupk/euler2.pro)


EXPDEV[1]

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        EXPDEV

 PURPOSE:
        Returns an exponentially distributed, positive, random deviate
        using RAN2( seed ) as the source of uniform deviates. The
        default unit mean and zero offset of the deviates may be modified
        by setting the appropriate keywords.

 CATEGORY:
        Math.

 CALLING SEQUENCE:

        Result = EXPDEV( Seed [,N] )

 INPUTS:
        Seed:     Seed for the random number generator. (It can be undefined)

 OPTIONAL INPUTS:
        N:        Number of deviates to return, (1=Default).

 OPTIONAL INPUT KEYWORD PARAMETERS:
        MEAN:     Mean of the deviates, (1=Default).

        OFFSET:   Offset of the deviates, (0=Default).  The resulting
                  exponential distribution and its mean is offset by
                  this amount.

        SUM:      Open upper limit to the sum of all the deviates,
                  (i.e. TOTAL(EXPDEV(Seed,..)) < SUM), (0=Default).
                  Deviates will be generated until their sum is equal to
                  or greater than this cutoff. If this keyword is specified,
                  then the number of deviates generated is returned in the
                  optional argument, N.

        CUTOFF:   Minimum possible value of the deviates, (1e-37=Default).
                  If set, this value MUST be > 0.

 MODIFICATION HISTORY:
        Written by:    Han Wen, October 1995.
        02-NOV-1995    Formerly, EXPDT, changed keywords TAU -> OFFSET,
                       AVG -> MEAN, added CUTOFF keyword.
        24-NOV-1995    Return a scalar when called with 1 argument,
                       (i.e. EXPDEV(Seed)).
        03-JAN-1996    Bugfixes: TOTAL(dts)->TOTAL(dts,/DOUBLE),
                       N = round(N) -> round(N) > 1
        28-MAR-1996    This SPECIAL version for the AIX utilized RAN2
                       instead of RANDOMU.

(See /host/bluemoon/usr2/idllib/contrib/groupk/expdev.pro)


EXPDEV[2]

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        EXPDEV

 PURPOSE:
        Returns an exponentially distributed, positive, random deviate
        using RANDOMU( seed ) as the source of uniform deviates. The
        default unit mean and zero offset of the deviates may be modified
        by setting the appropriate keywords.

 CATEGORY:
        Math.

 CALLING SEQUENCE:

        Result = EXPDEV( Seed [,N] )

 INPUTS:
        Seed:     Seed for the random number generator. (It can be undefined)

 OPTIONAL INPUTS:
        N:        Number of deviates to return, (1=Default).

 OPTIONAL INPUT KEYWORD PARAMETERS:
        MEAN:     Mean of the deviates, (1=Default).

        OFFSET:   Offset of the deviates, (0=Default).  The resulting
                  exponential distribution and its mean is offset by
                  this amount.

        SUM:      Open upper limit to the sum of all the deviates,
                  (i.e. TOTAL(EXPDEV(Seed,..)) < SUM), (0=Default).
                  Deviates will be generated until their sum is equal to
                  or greater than this cutoff. If this keyword is specified,
                  then the number of deviates generated is returned in the
                  optional argument, N.

        CUTOFF:   Minimum possible value of the deviates, (1e-37=Default).
                  If set, this value MUST be > 0.

 MODIFICATION HISTORY:
        Written by:    Han Wen, October 1995.
        02-NOV-1995    Formerly, EXPDT, changed keywords TAU -> OFFSET,
                       AVG -> MEAN, added CUTOFF keyword.
        24-NOV-1995    Return a scalar when called with 1 argument,
                       (i.e. EXPDEV(Seed)).
        03-JAN-1996    Bugfixes: TOTAL(dts)->TOTAL(dts,/DOUBLE),
                       N = round(N) -> round(N) > 1

(See /host/bluemoon/usr2/idllib/contrib/groupk/expdev_PC.pro)


FACPRIME

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        FACPRIME

 PURPOSE:
        Factor a number into its prime numbers.

 CATEGORY:
        Math.

 CALLING SEQUENCE:

        Result = FACPRIME( N, SUM=Sum )

 INPUTS:
        N:        Number to factor into primes.

 OUTPUTS:
        Returns a two dimensional array, LONARR(2,nprime) where nprime
        is the number of unique prime numbers.  The first dimension holds
        the value of each unique prime, Result(0,*) and the second
        dimension holds the frequency or number of times that prime
        occurs, Result(1,*).

 COMMON BLOCKS:
        FACPRIME:  Holds an array containing the first 100000 prime numbers.

 RESTRICTIONS:
        The number to be factored must be < 1299709.

 EXAMPLE:

        pnums = FACPRIME( 63500 )          ; Factor 63500 into it pnums
        help, pnums                        ; pnums       LONG = Array(2,3)
        print,REFORM(pnums(0,*)            ; 2 5 127
        print,REFORM(pnums(1,*)            ; 2 3 1
        ck   = 1L                          ; (2^2)(5^3)(127) = 63500
        for i=0,2 do $
             ck=ck*long(pnums(0,i))^pnums(1,*)

 MODIFICATION HISTORY:
        Written by:    Han Wen, August 1996.
        11-Aug-1996    Missing prime number, 2 in factoring, eliminate
                       prime number, 1 from result.

(See /host/bluemoon/usr2/idllib/contrib/groupk/facprime.pro)


FASPER

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        FASPER

 PURPOSE:
        Given abscissas x (which need not be equally spaced) and ordinates
        y, and given a desired oversampling factor ofac (a typical value
        being 4 or larger). this routine creates an array wk1 with a
        sequence of nout increasing frequencies (not angular frequencies)
        up to hifac times the "average" Nyquist frequency, and creates
        an array wk2 with the values of the Lomb normalized periodogram at
        those frequencies.  The arrays x and y are not altered.  This
        routine also returns jmax such that wk2(jmax) is the maximum
        element in wk2, and prob, an estimate of the significance of that
        maximum against the hypothesis of random noise. A small value of prob
        indicates that a significant periodic signal is present.

 CATEGORY:
        Numerical Recipes routines.

 CALLING SEQUENCE:

        FASPER, X, Y, Ofac, Hifac, Wk1, Wk2 [, Nout, Jmax, Prob]

 INPUTS:
        X:       Abscissas array, (e.g. an array of times).

        Y:       Ordinates array, (e.g. an array of corresponding counts).

        Ofac:     Oversampling factor.

        Hifac:    Hifac * "average" Nyquist frequency = highest frequency
                  for which values of the Lomb normalized periodogram will
                  be calculated.

 OUTPUTS:
        Wk1:      An array of Lomb periodogram frequencies.

        Wk2:      An array of corresponding values of the Lomb periodogram.

 OPTIONAL OUTPUTS:
        Nout:     The dimension of Wk1 and Wk2, i.e. the number of frequencies
                  calculated.

        Jmax:     The array index corresponding to the MAX( Wk2 ).

        Prob:     The False Alarm Probability (FAP) of the largest value of
                  of Lomb normalized periodogram.

 MODIFICATION HISTORY:
        Written by:    Han Wen, December 1994. (Adapted from a Numerical
                       Recipes routine with the same name).
        15-AUG-1996    Andrew Lee, Modified spread and fasper to use arrays
                       starting at 0 instead of 1, and fixed some bugs where
                       int was used instead of long.

(See /host/bluemoon/usr2/idllib/contrib/groupk/fasper.pro)


FFINDSRC

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        FFINDSRC

 PURPOSE:
        Interactively finds all x-ray sources around a primary source
        within the field of view of any HEAO A-1 scan in an IDL data
        FILE. (FF abbreviation for FILE FIND)

 CATEGORY:
        Database.

 CALLING SEQUENCE:

        FFINDSRC [, Srclist]

 OUTPUTS:
        This function first finds all the sources around a primary source
        and within the field of view of any scan in the IDL data file
        by searching the XXX database. Only those sources the USER interactively
        specifies will be written out to a file containing information
        about the Name, RA in DEGREES and DEC in DEGREES for each source
        selected.

 OPTIONAL OUTPUT:

        Srclist:  The same information written out to the file but
                  packaged into an ARRAY of structures with tags
                  defined as:

                  Name:     The name of the source, string.
                  RA:       The RA of the source in DEGREES.
                  DEC:      The DEC of the source in DEGREES.

                  If no sources are accepted by the USER then -1 is returned.


 PROCEDURE:
        (See description in FINDSRC).

 MODIFICATION HISTORY:
        Written by:    Han Wen, November, 1994.
        30-DEC-1994    Widgitized this routine, FFINDSRC -> FFINDSRC;
                       also added the Additional Source(s) file output option
                       used the XFIDUCIAL.
        22-JAN-1995    Moved FFINDSRC->OBSOLETE directory. Renamed
                       XFFINDSRC->FFINDSRC
        06-AUG-1996    Check if !DATA_PATH system variable is defined.

(See /host/bluemoon/usr2/idllib/contrib/groupk/ffindsrc.pro)


FIDCUTS1

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        FIDCUTS1

 PURPOSE:
        Applies various fiducial or "quality" cuts on an IDL HEAO A-1 data
        file, extracts relevant scan characteristics into a data structure
        and saves this structure to an IDL session file.  The USER is able
        to interactively select which scans to accept or reject, respective
        or irrespective of the fiducial cuts.

 CATEGORY:
        HEAO A-1 scanning.

 OPTIONAL INPUTS:

        Former "command line" options such as the input IDL data filename
        are now handled interactively within FIDCUTS1.  You may select the
        appropriate IDL data file by selecting the File pulldown submenu
        on the Fiducial Main Menu.

 OPTIONAL INPUT KEYWORDS:

        All of the former optional input keywords may now be configured
        interactively in FIDCUTS1 by selecting the Options pulldown submenu
        on the Fiducial Main Menu.

 CALLING SEQUENCE:
        FIDCUTS1

 OPTIONAL OUTPUTS:

        The USER may interactively select to save the results of the
        data analysis to an IDL session file (*.sav).  The contents of this
        saved file is one structure variable, named "data". The tags of this
        data structure are defined as follows: (NOTE: Only signal region
        data is saved!)

        structure: data
        tags:
                                                                     Data file
   Name      Description                         Type(Size)          formats
   --------- ------------------------------      ------------------  ----------
   mode      Timing mode (320 ms or 5 ms).       integer             All
   module    Module number (1-7).                integer             All
   npass     Number of scans that passed         integer             All
             the fiducial or quality cuts
   nfail     Number of scans that failed         integer             All
             the fiducial or quality cuts.
   nscan     Total number of scans in data file  integer             All
   nbin      Total number of data points.        integer             All
   nsig      The number of bins in each scan     intarr(npass)       All
             where the total transmission from
             summing all sources is > 0.
   nsig_src  The number of bins in each scan     intarr(npass,nsrc)  All
             where the transmission from each
             source is > 0.
   nsrc      Number of sources in data.          integer             All
             (for each scan if number of         intarr(npass)       All
             sources vary)
   name      Name of each source in the data.    strarr(nsrc)        All
   degree    Degree of polynomial used to        integer             All
             fit the background
   mjfs      First major frame number in         lonarr(npass)       All
             each scan.
   nmjfs     Number of major frames in each      intarr(npass)       All
             scan.
   sig       The signal = cts - background       fltarr(nbin)        All
             at each bin where the trans. > 0
             for each scan.
   cts       The detector counts, cts in the     fltarr(nbin)        All
             signal region for each scan.
   bkd       The fitted background in the        fltarr(nbin)        All
             signal region for each scan.
   bkd_coeff The coefficients of the fitted      fltarr(npass,       All
             background                                degree)
   trns      The transmissions of each source    fltarr(nbin,nsrc)   All
             in the signal region for each scan.
   phis      The scan longitude in the signal    dblarr(nbin)        DIRS
             region for each scan in RADIANS.
   thts      The scan latitude in the signal     dblarr(nbin)        DIRS
             region for each scan in RADIANS.
   intensity The fitted intensity, assuming      fltarr(npass,nsrc)  ASPECTS,
             constant sources, for each source.                      STANDARD,
                                                                     NOBARY
   sigma     The sigma uncertainties associated  fltarr(npass,nsrc)  ASPECTS,
             with each fitted intensity.                             STANDARD,
                                                                     NOBARY
   pk_bins   The bins where the transmission     intarr(npass,nsrc)  All
             is a max. for each source and each
             scan.
   pk_trns   The tranmission max. for each       fltarr(npass,nsrc)  All
             and each scan.
   overlap   The fraction of each sourc trans.   fltarr(npass,nsrc)  All
             overlapped by the sum of all the
             other sources' trans.
   t77i      The integer time in seconds since   lonarr(npass,nsrc)  All
             1977 at the peak trans. bin for
             for each scan and each source.
   t77f      The fraction of a second since      dblarr(npass,nsrc)  All
             1977 at the peak trans. bin for
             for each scan and each source.
   tcorr     The barycentric time correction     dblarr(2,npass,     ASPECTS,
             at the beginning and end of the                  nsrc)  STANDARD
             transmission function for each
             scan and for each source.
   aspects   A structure containing the                              ASPECTS
             satellite's aspects at the beginning
             of each scan.  This structure
             contains two tags defined as:
             y : The RA and DEC of the Y-axis    dblarr(2,npass)
                 in DEGREES for each scan.
             z : The RA and DEC of the Z-axis    dblarr(2,npass)
                 in DEGREES for each scan.
   MJF_RNG   range of major frames selected by   lonarr(2)           All
             USER, 0 if none.
   BAD_MJFS  list of bad major frames selected   lonarr(nbad)        All
             by the USER, 0 if none.
   FORMAT    format of the IDL data file         string              All
   NOTRNS    flag to exclude transmission        integer             All
             regions in fit of the scan, 1=yes
   DEADTIME  type of dead time correction        integer             All
             applied to the cts data:
             = 0, No dead time corrections
             = 1, NON-Extended or NON-Paralyzable
                  dead time corrections made
             = 2, Extended or Paralyzable
                  dead time corrections made
   VERSION   version number of the FIDCUTS1      float               ASPECTS
             routine that created the save file

        Another output option is for Fiducial to write out the first major
        frame number of every scan that was EXCLUDED; FAILED the fiducial
        cuts; or optionally, REJECTED by the USER (*.bad).  The USER
        interactively chooses the name of this output file.

 COMMON BLOCKS:
     These common block are for INTERNAL USE ONLY.

     DATA_COM:    Common block holding the structure, data. This structure
                  contains all relevant scan characteristics for those scans
                  that pass the fiducial cuts.
     INIT_COM:    This common block holds all the settings configurable
                  by the USER.  The variables within this common block
                  used to be optional keyword inputs to the Fiducial routine.
     LC_COM:      This common block holds the scan data for the current
                  scan for use of displaying or printing its light curve.
     XF_CUT_COM:  Keeps track of the Widget Identifier for the Main Menu.

 MODIFICATION HISTORY:
   August, 1994             H.C. Wen
   06-SEP-1994              Changed PK_BINS to give bins relative to the
                            SAVED signal region, NOT relative to the 128 or
                            8192 bins!  Eliminated PK_TRNS, PK_CTS and PK_THTS.
   09-SEP-1994              Added the DEADTIME keyword to make deadtime corrections
                            to the data.
   15-NOV-1994              Added the ASPECTS format.
   20-NOV-1994              Additional sources may be added INTERACTIVELY.
   21-NOV-1994              Mark bad MJFs for ALL failed scans, not just
                            those rejected interactively under FINAL CUT.
   23-DEC-1994              Converted FIDCUTS1 into a widget routine
                            => FIDCUTS1.
   05-JAN-1995              Removed glitch cuts for 5ms data, added FILE
                            keyword to PICKFILE calls.
   07-JAN-1995              Read in .dbs file (if available) to determine
                            MAX_NSCAN and MAX_NBIN.
   11-JAN-1995              Bugfix: fixed warning messages when buffer full
                            and at end of data file.
   17-JAN-1995              Bugfix: t77i = fltarr() => lonarr(). Also changed
                            t77f, tcorr = fltarr() => dblarr().
   18-JAN-1995              Changed t77i,t77f from time at beginning of signal
                            region to time at peak trns. of each source.
                            Transposed all structure tags from ( nsrc,npass )
                            -> (npass, nsrc) (i.e. pk_bins, intensity, sigma,
                            tcorr and trns). Also added the version tag to
                            indicate which version of FIDCUTS1 created the
                            save file. (version 3.0)
   19-JAN-1995              Bugfix: idl.max_nbin = nscan*nbin => nmjf*nbin
                            Added the YNCANCEL widget when quitting back to
                            the Fiducial Main Menu. (version 3.1)
   22-JAN-1995              Moved FIDCUTS1 to the OBSOLETE directory and
                            renamed XFIDCUTS1 -> FIDCUTS1. (still version 3.1)
   22-JAN-1995              Bugfix: made data.name = strarr(1) if nsrc=1,
                            previously=scalar string. (version 3.2)
   27-JAN-1995              Bugfix: small bug if data only contains one scan,
                            cannot transpose a scalar => 1-D array = [scalar]
   08-FEB-1995              Bugfix: data.name was incorrectly filled with
                            extra blank array elements between the primary
                            sources in the .idl data file and the sources
                            from the .add file. (version 3.4)
   11-FEB-1995              Utilized CREATE_STRUCT when saving data structure,
                            added the PK_TRNS and ASPECTS tags, (version 4.0)
   14-FEB-1995              Added the NSIG_SRC and OVERLAP tags, (version 5.0)
   15-FEB-1995              Added the Passed after MJF cutoff option in the
                            light curves option menu, (version 5.1)
   16-FEB-1995              Added the BKD_COEFF, FIDCUTS1 tags, (version 6.0)
                            Rename this routine FIDUCIAL -> FIDCUTS1, free
                            up memory when I can.
   06-AUG-1996              Check if !SAVE_PATH, !DATA_PATH system variables
                            are defined.

(See /host/bluemoon/usr2/idllib/contrib/groupk/fidcuts1.pro)


FIDCUTS2

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        FIDCUTS2

 PURPOSE:
        Apply second round of fiducial cuts to the HEAO A-1 Scanning data.

 CATEGORY:
        HEAO A-1 Scanning.

 CALLING SEQUENCE:

        FIDCUTS2 [,Cuts]

 OPTIONAL INPUTS:

        Cuts:     A 4-element array of cuts to be applied to the data, with
                  the following definitions:

                  Cuts(0) =    Cut on the |background slope|
                  Cuts(1) =    Cut on the number of signal bins
                  Cuts(2) =    Cut on the overlap fraction
                  Cuts(3) =    Cut on the transmission peak minimum

 OUTPUTS:
        This procedure writes out a new IDL SAVE session file containing the
        scans which have passed the second round of fiducial cuts. The USER
        is prompted for the filename of this IDL SAVE session file.

 MODIFICATION HISTORY:
        Written by:    Han Wen, February 1995.
        06-AUG-1996    Check if !SAVE_PATH system variable is defined.

(See /host/bluemoon/usr2/idllib/contrib/groupk/fidcuts2.pro)


FIDUCIAL

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        FIDUCIAL

 PURPOSE:
        Applies various fiducial or "quality" cuts on an IDL HEAO A-1 data
        file, extracts relevant scan characteristics into a data structure
        and saves this structure to an IDL session file.  The USER is able
        to interactively select which scans to accept or reject, respective
        or irrespective of the fiducial cuts.

 CATEGORY:
        HEAO A-1 scanning.

 OPTIONAL INPUTS:

        Former "command line" options such as the input IDL data filename
        are now handled interactively within FIDUCIAL.  You may select the
        appropriate IDL data file by selecting the File pulldown submenu
        on the Fiducial Main Menu.

 OPTIONAL INPUT KEYWORDS:

        All of the former optional input keywords may now be configured
        interactively in FIDUCIAL by selecting the Options pulldown submenu
        on the Fiducial Main Menu.

 CALLING SEQUENCE:
        FIDUCIAL

 OPTIONAL OUTPUTS:

        The USER may interactively select to save the results of the
        data analysis to an IDL session file (*.sav).  The contents of this
        saved file is one structure variable, named "data". The tags of this
        data structure are defined as follows: (NOTE: Only signal region
        data is saved!)

        structure: data
        tags:
                                                                     Data file
   Name      Description                         Type(Size)          formats
   --------- ------------------------------      ------------------  ----------
   mode      Timing mode (320 ms or 5 ms).       integer             All
   module    Module number (1-7).                integer             All
   npass     Number of scans that passed         integer             All
             the fiducial or quality cuts
   nfail     Number of scans that failed         integer             All
             the fiducial or quality cuts.
   nscan     Total number of scans in data file  integer             All
   nbin      Total number of data points.        integer             All
   nsig      The number of bins in each scan     intarr(npass)       All
             where the total transmission from
             summing all sources is > 0.
   nsig_src  The number of bins in each scan     intarr(npass,nsrc)  All
             where the transmission from each
             source is > 0.
   nsrc      Number of sources in data.          integer             All
             (for each scan if number of         intarr(npass)       All
             sources vary)
   name      Name of each source in the data.    strarr(nsrc)        All
   degree    Degree of polynomial used to        integer             All
             fit the background
   mjfs      First major frame number in         lonarr(npass)       All
             each scan.
   nmjfs     Number of major frames in each      intarr(npass)       All
             scan.
   sig       The signal = cts - background       fltarr(nbin)        All
             at each bin where the trans. > 0
             for each scan.
   cts       The detector counts, cts in the     fltarr(nbin)        All
             signal region for each scan.
   bkd       The fitted background in the        fltarr(nbin)        All
             signal region for each scan.
   bkd_coeff The coefficients of the fitted      fltarr(npass,       All
             background                                degree)
   trns      The transmissions of each source    fltarr(nbin,nsrc)   All
             in the signal region for each scan.
   phis      The scan longitude in the signal    dblarr(nbin)        DIRS
             region for each scan in RADIANS.
   thts      The scan latitude in the signal     dblarr(nbin)        DIRS
             region for each scan in RADIANS.
   intensity The fitted intensity, assuming      fltarr(npass,nsrc)  ASPECTS,
             constant sources, for each source.                      STANDARD,
                                                                     NOBARY
   sigma     The sigma uncertainties associated  fltarr(npass,nsrc)  ASPECTS,
             with each fitted intensity.                             STANDARD,
                                                                     NOBARY
   pk_bins   The bins where the transmission     intarr(npass,nsrc)  All
             is a max. for each source and each
             scan.
   pk_trns   The tranmission max. for each       fltarr(npass,nsrc)  All
             and each scan.
   overlap   The fraction of each sourc trans.   fltarr(npass,nsrc)  All
             overlapped by the sum of all the
             other sources' trans.
   t77i      The integer time in seconds since   lonarr(npass,nsrc)  All
             1977 at the peak trans. bin for
             for each scan and each source.
   t77f      The fraction of a second since      dblarr(npass,nsrc)  All
             1977 at the peak trans. bin for
             for each scan and each source.
   tcorr     The barycentric time correction     dblarr(2,npass,     ASPECTS,
             at the beginning and end of the                  nsrc)  STANDARD
             transmission function for each
             scan and for each source.
   aspects   A structure containing the                              ASPECTS
             satellite's aspects at the beginning
             of each scan.  This structure
             contains two tags defined as:
             y : The RA and DEC of the Y-axis    dblarr(2,npass)
                 in DEGREES for each scan.
             z : The RA and DEC of the Z-axis    dblarr(2,npass)
                 in DEGREES for each scan.
   MJF_RNG   range of major frames selected by   lonarr(2)           All
             USER, 0 if none.
   BAD_MJFS  list of bad major frames selected   lonarr(nbad)        All
             by the USER, 0 if none.
   FORMAT    format of the IDL data file         string              All
   NOTRNS    flag to exclude transmission        integer             All
             regions in fit of the scan, 1=yes
   DEADTIME  type of dead time correction        integer             All
             applied to the cts data:
             = 0, No dead time corrections
             = 1, NON-Extended or NON-Paralyzable
                  dead time corrections made
             = 2, Extended or Paralyzable
                  dead time corrections made
   VERSION   version number of the FIDUCIAL      float               ASPECTS
             routine that created the save file

        Another output option is for Fiducial to write out the first major
        frame number of every scan that was EXCLUDED; FAILED the fiducial
        cuts; or optionally, REJECTED by the USER (*.bad).  The USER
        interactively chooses the name of this output file.

 COMMON BLOCKS:
     These common block are for INTERNAL USE ONLY.

     DATA_COM:    Common block holding the structure, data. This structure
                  contains all relevant scan characteristics for those scans
                  that pass the fiducial cuts.
     INIT_COM:    This common block holds all the settings configurable
                  by the USER.  The variables within this common block
                  used to be optional keyword inputs to the Fiducial routine.
     LC_COM:      This common block holds the scan data for the current
                  scan for use of displaying or printing its light curve.
     XF_CUT_COM:  Keeps track of the Widget Identifier for the Main Menu.

 MODIFICATION HISTORY:
   August, 1994             H.C. Wen
   06-SEP-1994              Changed PK_BINS to give bins relative to the
                            SAVED signal region, NOT relative to the 128 or
                            8192 bins!  Eliminated PK_TRNS, PK_CTS and PK_THTS.
   09-SEP-1994              Added the DEADTIME keyword to make deadtime corrections
                            to the data.
   15-NOV-1994              Added the ASPECTS format.
   20-NOV-1994              Additional sources may be added INTERACTIVELY.
   21-NOV-1994              Mark bad MJFs for ALL failed scans, not just
                            those rejected interactively under FINAL CUT.
   23-DEC-1994              Converted FIDUCIAL into a widget routine
                            => FIDUCIAL.
   05-JAN-1995              Removed glitch cuts for 5ms data, added FILE
                            keyword to PICKFILE calls.
   07-JAN-1995              Read in .dbs file (if available) to determine
                            MAX_NSCAN and MAX_NBIN.
   11-JAN-1995              Bugfix: fixed warning messages when buffer full
                            and at end of data file.
   17-JAN-1995              Bugfix: t77i = fltarr() => lonarr(). Also changed
                            t77f, tcorr = fltarr() => dblarr().
   18-JAN-1995              Changed t77i,t77f from time at beginning of signal
                            region to time at peak trns. of each source.
                            Transposed all structure tags from ( nsrc,npass )
                            -> (npass, nsrc) (i.e. pk_bins, intensity, sigma,
                            tcorr and trns). Also added the version tag to
                            indicate which version of FIDUCIAL created the
                            save file. (version 3.0)
   19-JAN-1995              Bugfix: idl.max_nbin = nscan*nbin => nmjf*nbin
                            Added the YNCANCEL widget when quitting back to
                            the Fiducial Main Menu. (version 3.1)
   22-JAN-1995              Moved FIDUCIAL to the OBSOLETE directory and
                            renamed XFIDUCIAL -> FIDUCIAL. (still version 3.1)
   22-JAN-1995              Bugfix: made data.name = strarr(1) if nsrc=1,
                            previously=scalar string. (version 3.2)
   27-JAN-1995              Bugfix: small bug if data only contains one scan,
                            cannot transpose a scalar => 1-D array = [scalar]
   08-FEB-1995              Bugfix: data.name was incorrectly filled with
                            extra blank array elements between the primary
                            sources in the .idl data file and the sources
                            from the .add file. (version 3.4)
   11-FEB-1995              Utilized CREATE_STRUCT when saving data structure,
                            added the PK_TRNS and ASPECTS tags, (version 4.0)
   14-FEB-1995              Added the NSIG_SRC and OVERLAP tags, (version 5.0)
   15-FEB-1995              Added the Passed after MJF cutoff option in the
                            light curves option menu, (version 5.1)
   16-FEB-1995              Added the BKD_COEFF tag, (version 6.0)
   06-AUG-1996              Check if !SAVE_PATH, !DATA_PATH system variables
                            are defined.

(See /host/bluemoon/usr2/idllib/contrib/groupk/fiducial.pro)


FINDSRC

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        FINDSRC

 PURPOSE:
        Interactively finds all x-ray sources around a primary source
        within the field of view of a HEAO A-1 scan. Uses the XXX database.

 CATEGORY:
        Database.

 CALLING SEQUENCE:

        Result = FINDSRC( Module, Cts, Src, Sat )

 INPUTS:
        Module:   Collimator module number.

        Cts:      Counts of the scan, fltarr(nbin).

        Src:      Structure containing information about the primary source.
                  Its must have the following tags defined:

                  RA:  The RA of the primary source in DEGREES.
                  DEC: The DEC of the primary source in DEGREES.
                  trn: The collimator transmissions of the primary source
                       across the scan, fltarr(nbin).

        Sat:      Structure containing information about the satellite's
                  position. It must have the following tags defined:

                  RAY,DEY:  The RA,DEC of the Y-axis of the satellite
                            in RADIANS at either the beginning of each
                            major frame, fltarr( nmjfs ) or at each
                            bin, fltarr( nbin ).
                  RAZ,DEZ:  The RA,DEC of the Z-axis of the satellite
                            in RADIANS at either the beginning of each
                            major frame, fltarr( nmjfs ) or at each
                            bin, fltarr( nbin ).

 OPTIONAL INPUT KEYWORD PARAMETERS:

        DEGREES:  Set this keyword to interactively input the RA and
                  DEC of any additional USER-defined sources not
                  found in the database in DEGREES. ((hh mm ss) and
                  (dd mm ss)] = Default).

        FLUX_CUTOFF:   Minimum flux requirement in MICROJY for any
                  source found in the database, (i.e. you want to find
                  all sources with its max. flux > FLUX_CUTOFF). (0=Default)

        MJFS:     List of major frame numbers for this scan, lonarr( nmjf ).

        USERSRC:  ARRAY of structures holding information about each
                  USER-defined source to be plotted and returned
                  in addition to those found by the database. It must
                  have the following tags defined for each structure.

                  Name:     The name of the source, string.
                  RA:       The RA of the source in DEGREES.
                  DEC:      The DEC of the source in DEGREES.

                  (See example below for implementation).

 OUTPUTS:
        This function first finds all the sources around a primary source
        and within the field of view of a scan by searching a database.
        Only those sources the USER interactively specifies will be
        returned in an ARRAY of structures with tags defined as:

        Name:     The name of the source, string.
        RA:       The RA of the source in DEGREES.
        DEC:      The DEC of the source in DEGREES.

        If no sources are accepted by the USER then -1 is returned.

 RESTRICTIONS:
        There are TWO PRECONDITIONS that must be satisfied before calling
        this routine, 1) That the XXX database is currently opened using
        the Astronomy Library routine DBOPEN; and 2) The light curve
        color table has already been loaded by calling the LCLOADCT routine.
        (See example below).

 PROCEDURE:
        When you call this routine, a database is first searched for all
        sources within a cone about the primary source, defined by the
        Src structure. The (1/2) separation or polar angle defining this
        cone is the larger of the two angles between the source position
        on the scan and the bin edges of the scan added in quadrature with
        8 degrees to account for the collimator's acceptance.

        For each source found, its corresponding transmissions are
        calculated across the scan. The transmissions for this source
        as well as for the primary source are then plotted over the
        light curve for this scan.  The USER is then prompted about
        whether to add this source to the list that will eventually be
        returned.

 EXAMPLE:
        Let's say we want to find all the sources around 1H1741-32
        that will actually show up in the scan because they're within
        the acceptance of the collimator module.

        name = '1H1741-32'
        src  = { RA:265.4, DEC:-32.2, Trn:trn }
        sat  = { RAY:RAY, DEY:DEY, RAZ:RAZ, DEZ:DEZ }

        Let's additionally say we already know two sources, 1H1715-321
        and 1H1728-334.A that will show up; so we want them plotted
        immediately:

        othersrc = { name:'', RA:0.0, DEC:0.0 }
        othersrc = REPLICATE( othersrc, 2)
        othersrc( 0).name =
        othersrc( 0).RA   =  258.885
        othersrc( 0).DEC  =  -32.1261
        othersrc( 1).name = '
        othersrc( 1).RA   =  262.165
        othersrc( 1).DEC  =  -33.7969

        We must first open the XXX database, and load the light curve
        color table:

        DBOPEN,'xxx'
        LCLOADCT

        Now, we can go ahead and interactively get the list:

        list = FINDSRC( Module, Cts, Src, Sat, USERSRC=othersrc )

        You will find, in addition to those you accept:

        list(0).name   = 1H1715-321
        list(1).name   = 1H1728-334.A

        ..etc

 MODIFICATION HISTORY:
        Written by:    Han Wen, November, 1994.
        30-DEC-1994    Widgetized this routine FINDSRC->FINDSRC.
        10-JAN-1995    Fixed small typo bug.
        22-JAN-1995    Moved FINDSRC -> OBSOLETE directory. Renamed
                       XFINDSRC->FINDSRC

(See /host/bluemoon/usr2/idllib/contrib/groupk/findsrc.pro)


FITSCAN

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        FITSCAN

 PURPOSE:
        Fits for the source intensities and background in a scan assuming
        constant intensities and a polynomial background.  The method of
        multiple linear regression is employed.

 CATEGORY:
        Curve fitting.

 CALLING SEQUENCE:

        FITSCAN, Cts, Trns, Ndegree

 INPUTS:
          Cts:    Counts or "data" in each bin of the scan, [float(nbin)]

         Trns:    A nsrc x nbin array of transmission functions, [float( nsrc, nbin )].

      Ndegree:    The degree of the polynomial to be fitted to the background.

 OPTIONAL INPUT KEYWORD PARAMETERS:

       NOTRNS:    If this keyword is set, then the transmissions are ignored,
             and ONLY the background regions are fitted.  All variables
             associated with the transmissions are either set to 0 or -1.
             ( Note: if all sources fit for negative intensities then this
             mode is automatically set! )

      MIN_TRN:    Sets the minimum transmission peak allowed for all
             sources.  Sources which fall below this minimum have their
             intensities set to 0 and are excluded from the fitting.
             The default value is 0, and must be GE 0 and LE 1.

     MAX_FDER:    The fractional derivative cut used in the routine GLITCH for
             removing glitches from the background data, [float].

       NOWARN:    Suppress printing of warning messages.

          LOG:    Write warning messages to log file.

 OUTPUT KEYWORD PARAMETERS:


       OCOEFF:    Structure holding all the coefficients of the fit. Its tags
             are defined as follows:

             intensity :  fitted intensities for each source, [float( nbin )].
                   bkd :  coefficients of the polynomial background fit,
                       starting from the constant term, ending at the
                       Cn * bin^ndegree term, [float( ndegree+1 )].

             (NOTE:if source fits for a negative intensity, the intensity is
              set to 0, but its corresponding uncertainty, OSIGMA.intensity
              is kept)

       OSIGMA:    Structure holding the sigmas associated with each of the
             fitted coefficients defined in OCOEFF.  Its tags are defined as
             follows:

             intensity :  sigmas of OCOEFF.intensity, [float( nbin )].
                   bkd :  sigmas of OCOEFF.bkd, [float( ndegree+1 )].

         OFIT:    Structure holding the fit of the scan at each bin. Its tags
             are defined as follows:

                  data :  overall fit to the data at each bin, [float( nbin )].
                   bkd :  polynomial fit to the background, [float( nbin )].
                   sig :  sum of Intensity * Transmission over all the
                       sources at each bin, [float( nbin )].

     OREGRESS:    Structure holding some of the "tests of fit" results from
             the multiple linear regression. Its tags are defined as follows:

                 Ftest :  value of F for test of fit.
                     R :  vector of linear correlation coefficient.
                  Rmul :  multiple linear correlation coefficient.
                    CL :  confidence level of the overall reduced chi-squared
                       per degree of freedom.

      ORCHISQ:    Structure holding the reduced chi-squared per degree of
             freedom for the various regions of fitting.  All bins with
             glitches are excluded. Its tags are defined as follows:

                  data :  overall reduced chi-squared over all the bins.
                   bkd :  reduced chi-squared for the background region.
                   sig :  reduced chi-squared for the signal region where
                       transmissions > 0.

      OGLITCH:    Structure holding all glitches found in the data for the
             various regions of fitting. Its tags are defined as follows:

               nglitch :  number of glitches found in the data.
                  nbkd :  number of glitches found in the background region.
                  nsig :  number of glitches found in the signal region.
              here_bkd :  array of indices pointing to glitch bins in the
                       background region. (Set to -1 if there are no glitches.)
              here_sig :  array of indices pointing to glitch bins in the
                       signal region. (Set to -1 if there are no glitches.)

 EXAMPLE:

   Let's create some fake data...

   Define our fake sources

    nsrc = 5
    nbin = 512
    nglitch = 10
    here_bin = indgen(nbin)
    ctrs = [50, 100, 110, 250, 300]
    sigs = [10,  20,  30,  15,  10]
    Amps = [0.8, 0.6, 0.4, 0.9, 0.2]
    Ins = [100., 450., 210., 230., 120.]

   Create gaussain transmission sources

    trns = fltarr( nsrc, nbin )
    for i=0,nsrc-1 do begin
         trns( i,* ) = Amps(i) * exp( -( here_bin - ctrs(i) )^2./sigs(i)^2. )
         here_ltcut  = WHERE( trns( i,* ) lt 0.01, nltcut )
         if nltcut gt 0 then trns( i,here_ltcut ) = 0.0
    endfor

   Put in montonically increasing background with normally distributed noise

    A0   = 50.
    slope= 0.05
    bkd  = A0 + slope * here_bin + 5. * randomn( seed, nbin )

   Add the background and the signal

    cts  = bkd + TRANSPOSE(Ins # trns)

   Put in zero and overflow glitches

    here_glitch = intarr( nglitch )
    for i=0,nglitch/2 -1 do begin
         j = fix( randomu( seed ) * (nbin-1) )
         cts(j) = cts(j) + 1000.
         here_glitch(i) = j
    endfor

    for i=nglitch/2,nglitch-1 do begin
         j = fix( randomu( seed ) * (nbin-1) )
         cts(j) = 0.0
         here_glitch(i) = j
    endfor

    plot,bkd,/xstyle & wshow & pause
   for i=0,nsrc-1 do begin
         plot,trns(i,*),/xstyle
         pause
    endfor
    plot,cts,psym=10,/xstyle & pause

   Fit the data!

    FITSCAN, cts, trns, 1, OCOEFF=Ocoeff, OSIGMA=Osigma, OFIT=Ofit, $
              ORCHISQ=Orchisq, OGLITCH = Oglitch

    oplot,ofit.bkd  & pause
    oplot,ofit.sig  & pause
    oplot,Ofit.data & pause
    wdelete,0

    print,'Real Intensities:',Ins
    print,'Fit  Intensities:',ocoeff.intensity
    print,'Fit  sigmas     :',osigma.intensity
    pause

    print,'Real background:',A0,' + ',slope,' * bins'
    print,'Fit  background:',ocoeff.bkd
    print,'Fit  sigmas    :',osigma.bkd
    pause

    print,'Real glitches:', here_glitch
    print,'Fit  glitches: number:',oglitch.nglitch
    print,'          bkd: number:',oglitch.nbkd
    print,'                 bins:',oglitch.here_bkd
    print,'          sig: number:',oglitch.nsig
    print,'                 bins:',oglitch.here_sig


 MODIFICATION HISTORY:
        Written by:    Han Wen, May 1994.
        10-MAY-1994:   Removes glitches from underneath non-zero transmission
                       regions and excludes these data points from the fitting.
        19-MAY-1994:   Adapted from CT_RATE, restricting to regression analysis;
                       Fit signal and background simultaneously; If fitted
                       intensities are negative, set to 0, exclude from analysis
                       and refit the data.
        09-JUN-1994:   Minor bug fixes for improbable cases, added BADFIT label.
        20-JUL-1994:   Bug fix: the ZERO_ONLY/CUT keywords were switched between
                       background/peak GLITCH calls!
        28-AUG-1994:   Formerly named, INTENSITY. Changed optional outputs
                       to output KEYWORD structures. Made code more intelligible
                       and readable.  Added the NOTRNS keyword.
        19-SEP-1994:   Added the Confidence level for the overall fit, CL.
        19-NOV-1994:   Bug fix: problem with properly zeroing transmissions
                       corresponding to negative fitted intensities.
        15-DEC-1994:   Added the BADFIT label for the case of NO good bkd bins.
        10-JAN-1995:   Bug fix: include case when nsig=0.

(See /host/bluemoon/usr2/idllib/contrib/groupk/fitscan.pro)


FIT_BKD

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        FIT_BKD

 PURPOSE:
        Perform a least-square polynomial fit to the background of a major
        frame with optional error estimates.

        This routine uses matrix inversion.  A newer version of this routine,
        SVDFIT, uses Singular Value Decomposition.  The SVD technique is more
        flexible, but slower.

        Another version of this routine, POLYFITW, performs a weighted
        least square fit.

 CATEGORY:
        Curve fitting.

 CALLING SEQUENCE:
        Result = FIT_BKD(Cts, Trns [, NDegree ,Yfit, Yband, Sigma, A, Chisq] )

 INPUTS:
      Cts:    An array holding the counts for this major frame, [float( nbin )].

     Trns:    A nsrc x nbin array holding all the transmission functions
         for this major frame.

 OPTIONAL INPUT KEYWORDS:
  NDegree: The degree of the polynomial to fit. If the USER does not
         specify this, NDegree defaults to 1.
         NOTE: if the USER sets NDegree= 0 then the background
         is simply the weighted average, assuming Poisson statistics,
         (i.e. sigma2 = Counts )

      CUT:    The fractional derivative cut used in the routine GLITCH for
        removing glitches from the background data, [float].

 OUTPUTS:
        FIT_BKD returns a vector of coefficients with a length of NDegree+1.

 OPTIONAL OUTPUT PARAMETERS:

     Yfit: The vector of calculated Y's.  These values have an error
      of + or - Yband.

    Yband: Error estimate for each point = 1 sigma

    Sigma: The standard deviation in Y units.

        A: Correlation matrix of the coefficients.

    Chisq: The Chi-squared for this fit, assuming poisson statistics.

 OPTIONAL OUTPUT KEYWORDS:

 GLITCHES: A list of bins where glitches were found in the background.
        Returns a -1 if no glitches were found, [integer( nbad )]

   BIN_PK: A list of bins where the transmissions are a maximum, [integer( nsrc )].

   BKD_PK: The fitted background values at the bins where the transmissions
        are a maximum, [float( nsrc )].

 EXAMPLE:
       Let's find the background for some major frame in 320ms mode with 2 sources
       in the field of view:


       let's generate random background and data:

       cts = randomn( seed, 128 )
       trns = fltarr( 2, 128 )
       for i=20,80 do  trns( 0,i ) = randomn( seed )
       for i=50,100 do trns( 1,i ) = randomn( seed )

       coeff = FIT_BKD( Cts, Trns, 1, Bkd, ErrBars )

 MODIFICATION HISTORY:
   Written by:    H. C. Wen, April, 1994.
   27-APR-1994    Changed the name from GET_BKD and added the option to fit the
                  background to a polynomial.
   04-MAY-1994    For Ndegree=0, changed the average background to a
                  weighted average, where sigma2 = counts.
   05-MAY-1994    Added Chisq as an optional output. Converted the
                  for/do loops into matrix algebra.
   08-MAY-1994    Removed glitches from the background data with GLITCH routine.

(See /host/bluemoon/usr2/idllib/contrib/groupk/fit_bkd.pro)


FOLD_LC

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        FOLD_LC

 PURPOSE:
        Folds the light curves for a source using a USER provided
        period and plots the resulting folded light curves.

 CATEGORY:
        Plotting.

 INPUTS:

   Time:     Array of times in SECONDS since 1/1/77, [dblarr( npts )].

   Flux:     Array of corresponding intensities for the source,
             [fltarr( npts )] in units specified by the FLUX_UNITS keyword.

   Err:      Array of corresponding uncertainties for each intensity
             [fltarr( npts )] in units specified by the FLUX_UNITS keyword.

   Period:   Folding period in HOURS.

   SrcName:  The name of the source, [string].

 OPTIONAL INPUT PARAMETERS:

   FLUX_UNITS:    The units of the given intensities, [string], (''=Default).

 OUTPUTS:

        This routine makes light curves of the HEAO A-1 data and sends
        them to the graphic device if the USER selects it from the widget
        menu.

 MODIFICATION HISTORY:
   September, 1994          H.C. Wen
   02-FEB-1995              Implemented XPLOT, XOPLOT
   08-FEB-1995              Eliminated the HALF keyword for simplicity.

(See /host/bluemoon/usr2/idllib/contrib/groupk/fold_lc.pro)


GET_ASPECTS

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        GET_ASPECTS

 PURPOSE:
        Subroutine interpolates, or extrapolates, the aspect angles, right
        ascension and declination (alpha, delta), for the Y- and Z-axes
        given the initial and final value for these angles.  The Z-axis is
        assumed to be the spin axis.

        The interpolation (or extrapolation) is done by first converting
        alpha,delta to celestial cartesian coordinates, then cartesian
        coordinates to Euler angles.  The Euler angles are interpolated to
        the desired number of intermediate points, then converted back to
        cartesian coordinates, and finally to alphas and deltas.

        Note that the aspects are interpolated, or extrapolated, to the
        middle of each bin, and that the initial and final aspects
        supplied in the input arguments bound the beginning of the first
        bin and the end of the last bin, respectively.


 CATEGORY:
        Interpolation

 CALLING SEQUENCE:

        GET_ASPECTS, Mode, Bins, Ry,Dy, Rz,Dz, Y_asp, Z_asp

 INPUTS:
         Mode:    The interpolation "mode", [integer].
             If MODE=0, aspects are INTERPOLATED for values between
             the initial and final aspects.
             If MODE=1, aspects are EXTRAPOLATED beyond the final
             aspects given.

         Bins:    The number of intermediate or extrapolated bins
             between the initial and final aspects, [integer].

           Ry:    The initial and final values of the Y-axis
             right ascension, [float(2)].

           Dy:    The initial and final values of the Y-axis
             declination, [float(2)].

           Rz:    The initial and final values of the Z-axis
             right ascension, [float(2)].

           Dz:    The initial and final values of the Z-axis
             declination, [float(2)].

 OPTIONAL INPUT KEYWORDS:
       OFFSET:    The number of bins from the bin edge where the aspects
             are calculated.  The default is 0.5 bin, namely, the center
             of each bin, [float].

 OUTPUTS:
        Y_asp:    The interpolated (or extrapolated) Y-axis right
             ascension and declination for each of BINS points, [float(2,Bins)].

        Z_asp:    The interpolated (or extrapolated) Z-axis right
             ascension and declination for each of BINS points, [float(2,Bins)].

 MODIFICATION HISTORY:
        Written by:    K.H. Fairfield,  02-DEC-1992.
        09-FEB-93:     Changed the meaning of the BINS input argument to be
                  the actual number of bins between the bounding aspects,
                  rather than the number of intermediate points, so as to
                  calculate the returned aspects at the center of each bin
                  rather than the bin edge.

                  N.B. Because of these changes, calling programs must be
                       modified accordingly.
        06-JUN-1994:   Adapted routine into an IDL procedure, H.C. Wen.
        22-JUN-1994:   Vectorized routine to eliminate for loops.
                       Added the OFFSET keyword.
        15-AUG-1995    Comment bugfix: removed extraneous ;+ and ;-.

(See /host/bluemoon/usr2/idllib/contrib/groupk/get_aspects.pro)


GET_DATA

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        GET_DATA

 PURPOSE:
        This function restores an IDL SAVE Session file created by the
        FIDUCIAL routine and returns the saved DATA structure.

 CATEGORY:
        I/O

 CALLING SEQUENCE:

        Result = GET_DATA( [Filename] )

 OPTIONAL INPUTS:
        Filename: The filename (including path) of the IDL save session file.
                  If this parameter is not provided by the USER, then the
                  USER will be prompted to select the desired file from a
                  widget menu.

 OPTIONAL INPUT KEYWORD PARAMETERS:
        TITLE:    The title of the widget window that displays information
                  to the USER ('Get_DATA'=Default)

        VERSION:  The Version number that the DATA structure must be greater
                  than or equal to. (3=Default)

 OUTPUTS:
        The DATA structure saved in the IDL SAVE session file is returned.
        If the DATA structure is invalid or the USER aborts selecting a
        file by pressing the Cancel button, then a 'NULL' structure is
        returned {NULL:0}

 OPTIONAL OUTPUT KEYWORD PARAMETERS:

        OFILE:    The filename (including path) of the IDL save session file
                  restored.

 RESTRICTIONS:
        The IDL SAVE session file must have been created by the FIDUCIAL
        routine.

 MODIFICATION HISTORY:
        Written by:    Han Wen, February 1995.
        08-FEB-1995    Added the OFILE keyword.
        06-AUG-1996    Check if !SAVE_PATH system variable is defined.

(See /host/bluemoon/usr2/idllib/contrib/groupk/get_data.pro)


GET_FMT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        GET_FMT

 PURPOSE:
        This function extracts the name of the format of an IDL data file.

 CATEGORY:
        I/O.

 CALLING SEQUENCE:

        Result = GET_FMT( File )

 INPUTS:
        File:     Name of the IDL data file. If none is provided, the
                  USER will be prompted for it via PICKFILE().

 OUTPUTS:
        The format name is returned.  If the format of the IDL data file
        is not among the currently recognized data formats, then a
        null string, '' is returned. The list of currently recognized
        data format is a follows:

                       'ASPECTS'
                       'STANDARD'
                       'NOBARY'

 EXAMPLE:
        ;Let's say we have the IDL data file, 1755-33.IDL and we would
        ;like to determine the format of this file:

        fmt = GET_FMT( !DATA_PATH+'1755-33.IDL' )

        ;The value of fmt will be: 'ASPECTS'

 MODIFICATION HISTORY:
        Written by:    Han Wen, December 1994.
        06-AUG-1996    Make File a required input parameter.

(See /host/bluemoon/usr2/idllib/contrib/groupk/get_fmt.pro)


GET_NSRC

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        GET_NSRC

 PURPOSE:
        This function extracts the number of sources in an IDL data file.

 CATEGORY:
        I/O.

 CALLING SEQUENCE:

        Result = GET_NSRC( File )

 INPUTS:
        File:     Name of the IDL data file.

 OUTPUTS:
        The number of sources in the IDL data file is returned.

 MODIFICATION HISTORY:
        Written by:    Han Wen, December 1994.
        06-AUG-1996    Make File a required input parameter.

(See /host/bluemoon/usr2/idllib/contrib/groupk/get_nsrc.pro)


GET_PEAK

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        GET_PEAK

 PURPOSE:
        Finds the bin(s) where the transmission curves are a maximum.

 CATEGORY:
        Curve fitting.

 CALLING SEQUENCE:
        Result = GET_PEAK( Trns )

 INPUTS:
         Trns:    A nsrc x nbin array of transmission functions, [float( nsrc, nbin )].

 OUTPUTS:
        This functions returns the bin numbers where the transmission
        curves are a maximum, [integer(nsrc)].

 MODIFICATION HISTORY:
        Written by:    Han Wen, May, 1994.
        17-MAY-1994:   Restricted the functionality of this routine to ONLY
                       returning the bins; moved other characteristics, like
                       the fitted background @ peak to the routine(s) which
                       calculate these values.

(See /host/bluemoon/usr2/idllib/contrib/groupk/get_peak.pro)


GET_SCAN

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        GET_SCAN

 PURPOSE:

        This function reads in major frame(s) of the HEAO A-1 data from a
        data file into buffers.  Each buffer contains a set of sequential
        major frames and may be referred to as a "scan".  The number of
        sequential major frames may vary according to the number of
        sequential major frames found in the data file.

 CATEGORY:
       I/O

 CALLING SEQUENCE:

    Result = GET_SCAN( Move [, PICKMJF=Pickmjf, DATA=Data, NOWARN=Nowarn, LOG=Log] )

 INPUTS:
         Move:    Buffer command to tell which buffer to retreive:
                        1   ->   Get the next buffer.
                        0   ->   Get the current buffer.
                       -1   ->   Get the previous buffer.
             If the buffer pointer is at the top of the buffer stack and
             Move = 1, then the next major frame buffer is read from the data file.

 INPUT KEYWORD PARAMETERS:

      PICKMJF:    Get the major frame buffer with the major frame number
             specified by PICKMJF by searching forward.  NOTE: Move must
             be set to 1 if the PICKMJF keyword is set, [long].

       NOWARN:    Suppress printing of warning messages to screen.

          LOG:    Output warning messages to log file.

 OUTPUTS:
       This function serves to both read major frames from file into buffers
       and return buffer elements to the USER through output keywords.  When
       BOTH the end of file has been reached and the buffer for that file
       is empty, then this function returns 1, otherwise it returns 0.
       In other words, it returns the EOFB (end of file and buffer) status.

 OUTPUT KEYWORD PARAMETERS:

         DATA:    Array of MJF data structures with dimension equal to the
             number of sequential major frames in the scan.  (See DEF_MJF
             for the definition of the MJF data structure.)

 RESTRICTIONS:
       Data file must be in the proper IDL format as defined by the
       FMT_SRCDATA program.

 EXAMPLE:
       Assume we have a data file named crab.idl:

       unit = INIT_SCAN( 'crab.idl' )

       eofb = GET_SCAN( 1, DATA=Data )

       nmjf = n_elements( data )
       nbin = nmjf*data.nbin(0)
       cts  = reform( data.cts, nbin )
       trns = reform( data.trns, data.nsrc(0), nbin )

       for i=0,nbin-1 do $
          print, cts(i), trns(*,i)

 MODIFICATION HISTORY:
        Written by:  H.C. Wen, May, 1994.
        15-MAY-1994  Added an end-of-file flag for each file buffer, eofb.
                     Changed logical unit to file pointer.
                     Properly empty the contents of the buffers to the
                     USER after the end of file has been reached.
        18-MAY-1994  Before, data in buffers were physically moved using
                     SHIFT, (e.g. buf.mjf  = SHIFT( buf.mjf,1  ) ), extremely
                     inefficient! Now, only the POINTERS to the buffer elements
                     get shifted, buf.ptr = SHIFT( buf.ptr,1 ).
        09-JUN-1994  Added the NOWARN and LOG keywords.
        26-JUN-1994  Formerly, READ_BUF; changed the variable keywords
                     to structure keywords and the multiple commons with
                     variables to one common with one structure variable.
                     Eliminated multiple file option change file pointer
                     back to logical unit.
        01-AUG-1994  Formerly called GET_BUF; moved the specific definition
                     of data structure to DEF_MJF. Had to add another element
                     to SCAN_COM, bufdata, because IDL doesn't allow structures
                     to have anonymous structure members.
        09-AUG-1994  Bugfixes: set pickmjf_=0 after 1st time call to READ_MJF.
                     Check if PICKMJF buffer is already in look ahead buffer.

(See /host/bluemoon/usr2/idllib/contrib/groupk/init_scan.pro)


GET_TRNS

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        GET_TRNS

 PURPOSE:
        Calculates the collimator transmission function given the aspects
        of the satellite at the beginning of two or more sequential major
        frames and the aspect of the source.

 CATEGORY:
        Collimator.

 CALLING SEQUENCE:
        Result = GET_TRNS(Module, Nbin, RAs, DECs, RAY, DEY, RAZ, DEZ)

 INPUTS:
       Module:    The module number in range 1 to 7, [integer].

         Nbin:    The total number of bins for all the sequential major
             frames, [integer].

     RAs,DECs:    The RA,DEC of the source in RADIANS, [float].

      RAY,DEY:    The RA,DEC of the satellite's Y-axis in RADIANS
             at the beginning of each sequential major frame, [float(nmjf)].

      RAZ,DEZ:    The RA,DEC of the satellite's Z-axis in RADIANS
             at the beginning of each sequential major frame, [float(nmjf)].

 OPTIONAL INPUT KEYWORDS:
       OFFSET:    The number of bins from the bin edge where the aspects
             are calculated.  The default is 0.5 bin, namely, the center
             of each bin, [float].

 OUTPUTS:
        This function returns the collimator response function of the source
        for the specified collimator module over all the bins of the
        sequential major frames, [float(nbin)].

 RESTRICTIONS:
        You must provide at least two or more major frames;
        i.e. N_ELEMENTS( RAY ) > 1.

 MODIFICATION HISTORY:
        Written by:    Han Wen, June 1994.

(See /host/bluemoon/usr2/idllib/contrib/groupk/get_trns.pro)


GET_XPALETTE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       GET_XPALETTE

 PURPOSE:
       This is just XPALETTE modified into a function to return the
       color index currently selected before the USER selects the
       DONE button.

       Interactively create color tables using the RGB, CMY, HSV, and
       HLS color systems using the mouse, three sliders, and a cell
       for each color index. Single colors can be defined or multiple
       color indices between two endpoints can be interpolated.

 CATEGORY:
       Color tables, widgets.

 CALLING SEQUENCE:
       color_index = GET_XPALETTE()

 INPUTS:
       No explicit inputs.  The current color table is used as a starting
       point.

 KEYWORD PARAMETERS:
       None.

 OUTPUTS:
       None.

 COMMON BLOCKS:
       COLORS: Contains the current RGB color tables.
       XP_COM: Private to this module.

 SIDE EFFECTS:
       GET_XPALETTE uses two colors from the current color table as
       drawing foreground and background colors. These are used
       for the RGB plots on the left, and the current index marker on
       the right. This means that if the user set these two colors
       to the same value, the GET_XPALETTE display could become unreadable
       (like writing on black paper with black ink). GET_XPALETTE minimizes
       this possibility by noting changes to the color map and always
       using the brightest available color for the foreground color
       and the darkest for the background. Thus, the only way
       to make GET_XPALETTE's display unreadable is to set the entire color
       map to a single color, which is highly unlikely. The only side
       effect of this policy is that you may notice GET_XPALETTE redrawing
       the entire display after you've modified the current color.
       This simply means that the change has made GET_XPALETTE pick new
       drawing colors.

       The new color tables are saved in the COLORS common and loaded
       to the display.

 PROCEDURE:
       The GET_XPALETTE widget has the following controls:

       Left:   Three plots showing the current Red, Green, and Blue vectors.

       Center: A status region containing:
               1) The total number of colors.
               2) The current color. GET_XPALETTE allows changing
                  one color at a time. This color is known as
                  the "current color" and is indicated in the
                  color spectrum display with a special marker.
               3) The current mark index. The mark is used to
                  remember a color index. It is established by
                  pressing the "Set Mark Button" while the current
                  color index is the desired mark index.
               4) The current color. The special marker used in
                  color spectrum display prevents the user from seeing
                  the color of the current index, but it is visible
                  here.

               A panel of control buttons, which do the following when
               pressed:

               Done:   Exits GET_XPALETTE, returns the current color index
                       selected.

         Predefined:   Starts XLOADCT to allow selection of one of the
                       predefined color tables. Note that when you change
                       the color map via XLOADCT, GET_XPALETTE is not always
                       able to keep its display accurate.  This problem can
                       be overcome by pressing the GET_XPALETTE "Redraw" button
                       after changing things via XLOADCT.

               Help:   Supplies help information similar to this header.

               Redraw: Completely redraws the display using the current
                       state of the color map.

             Set Mark: Set the value of the mark index to the
                       current index.

          Switch Mark: Exchange the mark and the current index.

         Copy Current: Every color lying between the current
                       index and the mark index (inclusive) is given
                       the current color.

          Interpolate: The colors lying between the current
                       index and the mark index are interpolated linearly
                       to lie between the colors of two endpoints.

       Three sliders (R, G, and B) that allow the user to modify the
       current color.

       Right:  A display which shows the current color map as a series of
               squares. Color index 0 is at the upper left. The color index
               increases monotonically by rows going left to right and top
               to bottom.  The current color index is indicated by a special
               marker symbol. There are 4 ways to change the current color:
                       1) Press any mouse button while the mouse
                          pointer is over the color map display.
                       2) Use the "By Index" slider to move to
                          the desired color index.
                       3) Use the "Row" Slider to move the marker
                          vertically.
                       4) Use the "Column" Slider to move the marker
                          horizontally.

 MODIFICATION HISTORY:
       July 1990, AB.          Based on the PALETTE procedure, which does
                               similar things using only basic IDL graphics
                               commands.

       7 January 1991, Re-written for general use.
       1 April 1992, Modified to use the CW_RGBSLIDER and CW_COLORSEL
               compound widgets. The use of color systems other than
               RGB is now supported.
       15 June 1992, Modified to use the CW_FIELD and CW_BGROUP compound
               widgets.
       7 April 1993, Removed state caching. Fixed a bug where switching
        the current index and the mark would fail to update the
        current index label.

       31 January 1995, Fixed small bug with Number Of Colors line (H.C.Wen)
       09 May 1995, H.C. Wen, check only first 3 characters of !VERSION.OS.

(See /host/bluemoon/usr2/idllib/contrib/groupk/get_xpalette.pro)


GLITCH

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        GLITCH

 PURPOSE:
        Looks for "glitches" in the data by calculating the changes
        in count rate across a major frame. When it finds a major
        frame with a "glitch", its bin number is added to a list.

 CATEGORY:
        Data Analysis.

 CALLING SEQUENCE:

        BIN_LIST = GLITCH( Cts, [, Nglitch, CUT=Cut, /ZERO_ONLY, /NOWARN] )

 INPUTS:
          Cts:    Array containing the data, [float( nbin )].

 OPTIONAL INPUTS:

      Nglitch:    Number of bins with glitches, [integer].

 OPTIONAL KEYWORD INPUTS:

          CUT:    The cutoff fractional derivative used to determine if the
             counts in a bin is a glitch, [float].

    ZERO_ONLY:    Only look for zero bins in the Cts array.

       NOWARN:    Suppress printing of warning messages.

          LOG:    Write warning messages to log file.

 OUTPUTS:
        This function returns a list of bins where glitches have been found.

 EXAMPLE:
        Let's say you have an array of counts and want to find which
        bins have glitches:

        Cts = randomu( seed, 128 ) + 100
        Cts(20) = 5000
        Cts(90) = 0

        list = GLITCH( Cts )
        print, list

 MODIFICATION HISTORY:
        Written by:    Han Wen, May, 1994.
        20-JUL-1994    Bugfix: moved the min. 3 data pts cutoff to after
                       the check for 0 bins.
        10-JAN-1995    Bugfix: (nNOzero eq 0) -> (nNOzero le 1) because
                       we need at least 2 points to determine the
                       count derivative

(See /host/bluemoon/usr2/idllib/contrib/groupk/glitch.pro)


GRPKPATH

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        GRPKPATH

 PURPOSE:
        This function returns the path to a Group K library.

 CATEGORY:
        I/O.

 CALLING SEQUENCE:

        Result = GRPKPATH()

 OUTPUTS:
        Returns a string containing the path to the specified Group K
        Library.

 COMMON BLOCKS:
        GRPKPATH: For internal use only.

 MODIFICATION HISTORY:
        Written by:    Han Wen, August 1996.

(See /host/bluemoon/usr2/idllib/contrib/groupk/grpkpath.pro)


HBREAD

[Previous Routine] [Next Routine] [List of Routines]
   HBR digitized 9-track tape read routine (used by HBRFMT)

   Written by Daryl J. Yentis, Naval Research Laboratory, SSD 02/08/83.
   Adapted to IDL by H.C. Wen, 4/18/95

(See /host/bluemoon/usr2/idllib/contrib/groupk/hbread.pro)


HBRFMT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        HBRFMT

 PURPOSE:

        This routine processes and re-formats the raw High-Bit-Rate
        digitized files into the Photon Time Interval (PTI) format.

 CATEGORY:
        HEAO HBR.

 CALLING SEQUENCE:

        HBRFMT,   FILES=Files, RECORDS=Records

 INPUT KEYWORD PARAMETERS:

        FILES:    A array of filenames for each raw HBR digitized file.

        RECORDS:  A two dimensional array (2,nfiles) holding the first record
                  number, (0,*) and last record number (1,*) to be processed
                  for each each of the specified files. (Run HBRECS to determine
                  these start/stop records.)

 OPTIONAL INPUT KEYWORD PARAMETERS:

        PATH:     Optional path to the specified input files, (''=Default).

        PTIPATH:  Optional path to the output PTI file, (PATH=Default).

        QUIET:    Suppress all print messages to the display, (0=Default).

 OUTPUTS:
        Each specified raw HBR digitized file is processed into the Photon
        Time Interval (PTI) format and written to a file in the same directory
        where the HBR file resides.  The filename of this PTI file has the same
        prefix as the HBR file and an extension of pti. A log file is also created
        with the name ptiNNNNN.log.

        The format of the PTI file is as follows:

        Byte order record   (512 words, sequence:[0,1,2...511])

        MJF Header record   (512 words)
        NRZ Data block      (32 512-word records = 4 MNFs/record)
        DATA records        (512-word records)

            Dynamic format: a MNF header followed by time intervals between
                            photon events, Deltat's or PTIs

             MNF Header:    (16 words)
                 Events:    Deltat's between events, 1,...,MNFNDT
                 Header:
                 Events:
                    .
                    .
                    .
                 Header:
                 Events:

        For a complete description of the MJF and MNF headers, see DEF_HBRH.PRO

 RESTRICTIONS:

        The def_hbrh.pro routine must be previously compiled.

 COMMON BLOCKS:
        DEF_HBRH: See DEF_HBRH.PRO for a description.
        HBRSYNC:  See HBRSYNC.PRO for a description.
        HBRFMT:   Holds NOVA tape pointers.

 PROCEDURE:
        There is a possibility which leads to NEGATIVE photon time intervals,
        or PTIs. Since, DATA records is a 16-bit integer array, the largest
        possible POSITIVE number it can hold is 2^15-1 = 32767.  However, the
        MSB bit (the sign bit) allows us to effectively extend the range of
        numbers to [0-65535].

        Each MNF is 320 msec long.  At 7.8125 usec time bins, the largest
        possible PTI within a MNF is 40960.  Any PTIs > 32767 overflow
        to their negative complement, namely, -2^16 + PTI.  This means that
        PTIS = [32768,40960] are mapped to their NEGATIVE overflow values
        = [-32768,-24576].

 MODIFICATION HISTORY:
        Written by:    Han Wen, July 1995 (Adapted from HBRFMT.FOR, Yentis & Co.).
        09-AUG-1995    Added NRL mag.tape error codes.  Eliminated hard-coded IDL
                       error code.
        20-AUG-1995    Added QUIET keyword.
        28-AUG-1995    Take care of special case, 1 photon/MNF.
                       Added the PTIPATH keyword.
        29-AUG-1995    Bugfix: Skip next record when next MJF13 number is different
                       from the previous by more than 1. Do not increment expected
                       MNF number for garbage data.
        29-SEP-1995    Added the PROCEDURE comments about possible 16-bit integer
                       overflows of the time intervals, PTIs.
        07-OCT-1995    Eliminated XDR and BINARY keywords. Create binary files with
                       .pti extension.  Added byte order record to Check Endian-type.
                       Converted existing XDR files -> .pti using XDR2PTI.PRO.

(See /host/bluemoon/usr2/idllib/contrib/groupk/hbrfmt.pro)


HBRINFO

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        HBRINFO

 PURPOSE:
        This function returns a structure or an array of structures containing
        information about the HBR data file(s) the USER has requested.

 CATEGORY:

        HEAO HBR.

 CALLING SEQUENCE:

        Result = HBRINFO()

 OPTIONAL INPUT KEYWORD PARAMETERS:

        The following are SEARCH keywords the USER may specify to find
        entries in the HBR database.  The wildcard character, '*'
        is allowed in all keywords.  See the PROCEDURE below for a more
        detailed description.

        FILE:     Names of the HBR data files, string or strarr().
                  The format of each name must be, SSS_TN_FN, where
                  SSS = NRL sequence number, TN = NRL mag. tape number,
                  and FN = File number on that mag. tape. Paths and/or
                  extensions (e.g. \data\001_1_1.dat) are allowed.

        SLACVOL:  SLAC volume serial number(s) of the SLAC silo cartridges
                  containing the HBR data file(s), string or strarr().
                  (e.g. RY2070)

        SLACSEQ:  SLAC sequence number(s) of the HBR data file(s) residing on
                  the SLAC silo cartridges, fix or intarr().

        NRLseq:   NRL sequence number(s) of the HBR data file(s) associated
                  with the NRL ANALOG tapes, fix or intarr().

        NRLtape:  NRL magnetic tape number(s) of the HBR data file(s)
                  associated with with NRL DIGITIZED tapes, fix or intarr().

        NRLfile:  NRL file number(s) of the HBR data file(s) residing on the
                  the NRL DIGITIZED tapes, fix or intarr().

        DATE:     The date of the HBR data file(s), string.  It must be of the
                  form, MN-DD-YY, where MN=month, DD=day, YY=year.  The wildcard
                  character is also allowed here by replacing MN, DD and/or YY
                  with '*',(e.g. '*-*-77', '1-*-78').

        TIME:     The time of the HBR data file(s), string.  It must be of the
                  form, HH-MM-SS, where HH=hour, MM=month, SS=second.  The
                  wildcard character is also allowed here by replacing HH, MM
                  and/or SS with '*', (e.g. '15-*-*').

        DOY:      Day(s) of the year, fix or intarr().

        HBRM:     HBR mode(s), string or strarr(), ('B'=Bit, 'F'=Frame, 'W'=Word).

        NRZM:     NRZ mode(s), fix or intarr(2), (5=5ms, 320=320ms).

        SATM:     HEAO satellite mode(s), string or starr(2), ('P'=Pointing,
                  'S'=Scanning).

        SELECT:   Specify which modules have been selected for the HBR data,
                  fix or intarr(2), (3=Modules 1-4, 7=Module 7)

        REV:      HEAO satellite revolution number(s), fix or intarr().

        TARGET:   Name(s) of celestial targets, string or strarr().
                  (e.g. 'Cyg X-1')

 OUTPUTS:
        A structure or an array of structures is returned for each requested HBR
        data file found in the database.  The tags of this structure are:

             SLAC:     Structure describing the location of the file in
                       the SLAC silos. The tags of this structure are:

                       volser:   Volume serial number
                       seq:      Sequence number

             NRL:      Structure describing the location of the file at NRL.
                       The tags of this structure are:

                       seq:      Sequence number of the ANALOG tape ..
                       tape:     Tape number of the DIGITIZED tape ..
                       file:     File number on the DIGITIZED tape ..
                                 .. containing this HBR data file.

             chron:    Structure describing when the HBR data was downlinked
                       to the ground station. The tags of this structure are:

                       dd:       Day of the month (1-31)
                       mn:       Month (1-12)
                       yy:       Year (1977-1978)
                       hh:       Hour (0:23)
                       mm:       Minute (0:59)
                       ss:       Seconds (0:59)
                       doy:      Day of the year (1:365)
                       JD:       Julian day number, long

             mode:     Structure describing the current modes of the HEAO
                       electronics and satellite. The tags of this structure are:

                       config:   String describing K. Woods configuration notes
                       HBR:      Mode of HEAO Random Decommutator,
                                 {'bit','frame' or 'word')
                       PM:       Describes which modules have been selected for
                                 HBR data,(3 = Scan modules, 1-4; 7 = Module 7).
                       NRZ:      Mode of the NRZ data, (5 = 5ms; 320 = 320ms).
                       sat:      Describes the state of the satellite,
                                 ('S' = spinning/scanning; 'P' = pointing)

             rev:      HEAO satellite revolution number, integer.

             pass:     Ground station pass abbreviation, ('H' = Hawaii;
                       'G' = 'Guam';...).

             length:   Length of the data in MINUTES, float.

             target:   Description of the celestial target, string.

             comments: Miscellaneous comments, string.

 COMMON BLOCKS:
        DEF_HBRDBS:    Contains the HBR database information.

 RESTRICTIONS:
        The DEF_HBRDBS routine must be called once, before calling
        this routine, to set up the HBR database.

 PROCEDURE:
        If a search keyword is specified by an array, then all array elements
        are ORed together in the database search.  Multiple keywords, if they
        are so specified, are ANDed together in the database search.
        If NO parameter is provided, then HBRINFO switches to interactive mode.
        A widget menu will appear allowing the USER to specify various search
        parameters. If any entries are found following the aformentioned
        search prescription, then the associated structure(s) are returned.
        If NO entries are found, then a -1 is returned.

 MODIFICATION HISTORY:
        Written by:    Han Wen, August, 1995.
        26-SEP-1995    Replaced hbrsilo.dat with hbrdbs.sav; changed pro ->
                       function. Eliminated NRL and SLAC output keywords.
                       Added multiple search keywords and interactive mode.
        27-SEP-1995    Improved search algorithm; search for sub-text
                       instead of exact matches.
        07-AUG-1996    Eliminate call to VERSION().

(See /host/bluemoon/usr2/idllib/contrib/groupk/hbrinfo.pro)


HBRSYNC

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        HBRSYNC

 PURPOSE:
        This routine processes the HBRB data (High-Bit-Rate in Bit telemetry
        mode) and extracts the 128 kbps and 6.4 kbps datastream for a
        minor frame.

 CATEGORY:
        HEAO HBR.

 CALLING SEQUENCE:

        HBRSYNC, Buf [, HBR, NRZ, MJF, MNF, Flags]

 INPUTS:
        Buf  :    A concatenation of two HBR records, the earlier one
                  first.  Namely, a 2*4096 element 2-byte array, intarr(8192).

 INPUT KEYWORD PARAMETERS:

        INIT :    Set this keyword to initialize various parameters used in
                  subsequent calls to this routine.

 OPTIONAL OUTPUTS:

        HBR  :    The 128 kbps datastream packed into 4096 words, intarr(4096)
                  containing a minor frame (320ms) of data.

        NRZ  :    The 6.4 kbps datastream packed into 128 words, intarr(128)
                  containing a minor frame (320ms) of data.

        MJF  :    The major frame number, long.

        MNF  :    The minor frame number, integer [0-127].

        Flags:    A 3-element integer array containing possible error flags:

                  Flags(0)  : Error code
                                 0,        Success.
                                 2,        Failure to find 6.4 kb DCS lock.
                                 3,        Bad or missing synch pattern.
                                 4,        Alternate failure(s) in NRZ clock.
                                 5,        Minor frame is not 4096 words long.
                                 6,        DCS bit lock lost somewhere in frame
                                 7,        Minor frame is out of Buf array boundary.

                  Flags(1)  : if Flags(0) =
                                 3,        Word offset to the start of the minor
                                             frame with a bad or missing synch
                                             pattern.  This offset is relative to
                                             the next DCS synch bit transition to 0.
                                 4,        Number of tick tock errors.
                                 5,        Word offset to the next DCS synch bit
                                             transition to 0.
                                 6,        Word offset to the lost DCS bit lock.
                                 7,        Word offset to the end of the minor frame.

                              ** Unless stated otherwise, all word offsets are
                                 relative to the start of the buffer.

                  Flags(2)  : Word offset in Buf array to the "real" start of
                              the minor frame for the NRZ data.

 COMMON BLOCKS:

        HBRSYNC:  This common blocks holds various parameters and static
             variables used in repeated calls to this routine.

 PROCEDURE:
        You must call first this routine with the INIT keyword set to define
        various parameters.


 MODIFICATION HISTORY:

 MODIFIED 3 31 83 TO CORRECT FOR OBSERVED TICKTOCK ERRORS ON SOME TAPES
 INIT ENTRY ADDED.
  MODULE TO CONTAIN BIT SHOVING STUFF FOR HEAO HIGH BIT RATE DATA
  D P MCNUTT  1 26 83    -    NO RIGHTS RESERVED

 THE FOLLOWING ASSEMBLY PARAMETER AFFECTS THE TIMING OF THE MINOR FRAME
 DATA RETURNED.  FAZEF=0 WILL USE THE EARLIER OF THE TWO AVAILABLE COPIES OF
 A MINOR FRAME, FAZEF=1 WILL USE THE LATER.

   **** I will use the convention that BIT 0 is the LEAST significant bit.
   **** All numbers will be in base 10, unless stated otherwise.

   We will assume that the data is in BIG Endian convention since this
   routine was written for the Data Generals which used this convention.

   "Ported" to IDL from Data
   General Eclipse assembly      : Han Wen, April 1995.
        23-APR-1995              Bugfix: NRZ was returning as a long integer (4-byte)
                                 instead of a (2-byte) integer.
        08-JUL-1995              Changed word offset (Flags(1)) for BITSBAD error
                                 relative to start of buffer instead of start of minor
                                 frame.

(See /host/bluemoon/usr2/idllib/contrib/groupk/hbrsync.pro)


HEAO

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        HEAO

 PURPOSE:
        This is the main driver routine for all data analysis routines
        related to the HEAO A-1 scanning data.  From its widget button
        menu, you may select various types of analysis like looking
        at light curves, selecting good scans, etc.

 CATEGORY:
        HEAO A-1 Scanning.

 CALLING SEQUENCE:
        HEAO

 MODIFICATION HISTORY:
        Written by:    Han Wen, January 1995.

(See /host/bluemoon/usr2/idllib/contrib/groupk/heao.pro)


HEAOEFF

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        HEAOEFF

 PURPOSE:
        This function returns the HEAO A-1 detector efficiences for the
        specified energies.

 CATEGORY:
        HEAO A-1.

 CALLING SEQUENCE:

        Result = HEAOEFF( HVmode, keV )

 INPUTS:

        HVmode:   String specifying one of two high-voltage modes,
                  'AGCL' for High Gain mode, or 'AGCP' for the Low Gain mode.

        keV:      A scalar or array of energies in KEV.

 OUTPUTS:
        The HEAO A-1 detector efficiencies at each of the energies specified
        by the USER.

 COMMON BLOCKS:
        HEAOEFF:  Holds the detector efficiency data. (For internal use only).

 PROCEDURE:
        The detector efficiency data is a digitization of a scan of the HEAO
        A-1 catalog fig. 7.  In order to optimize for speed, no interpolation
        is performed.  Instead, we rely on a set of detector efficiency data
        finely binned in logarithmic energy.

 EXAMPLE:

        energy         = 100.*(findgen(1000)/1000.)
        efficiencies   = HEAOEFF( 'AGCL', energy )

 MODIFICATION HISTORY:
        Written by:    Han Wen, May 1995.
        06-AUG-1996    Simplified directory structure.

(See /host/bluemoon/usr2/idllib/contrib/groupk/heaoeff.pro)


HIST1D

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        HIST1D

 PURPOSE:
        Returns the weighted histogram of a 1D array.

 CATEGORY:
        Image processing, statistics, probability.

 CALLING SEQUENCE:
        Result = HIST1D( Array [, Weight, OBIN=Obin, ..other HISTOGRAM keywords] )

 INPUTS:
        Array:    1D array which holds the data to be histogrammed.

 OPTIONAL INPUTS:
       Weight:    1D array of the same dimension as Array which holds the
             weighted values associated with each Array element.

 INPUT KEYWORD PARAMETERS:
      BINSIZE:    The size of the bin to use. If this keyword is not specified,
             a bin size of 1 is used.

        INPUT:    1D array to be added to the output of HIST1D.

          MAX:    The maximum value to consider in the histogram.  If this
             keyword is not specified, Array is searched for its largest value.

          MIN:    The minimum value to consider in the histogram.  If this
             keyword is not specified, and Array is of type byte, 0 is used.
             If this keyword is not specified and Array is not of byte type,
             Array is searched for its smallest value.

      BINEDGE:    This keyword specfies the location of the bin values returned
             by OBIN. The values are:

                  0 : Center of each bin, [DEFAULT].
                 -1 : Left  or lower edge of each bin.
                  1 : Right or upper edge of each bin.

 OUTPUTS:
        1D weighted histogram of Array using the Weight array.  If Weight
        is not specified, then the usual 1D histogram or density function
        is returned.

 OUTPUT KEYWORD PARAMETERS:

      DENSITY:    Density function of Array; i.e. the unweighted 1D histogram.

         OBIN:    An array holding the bin values of the histogram.

         OMAX:    A named variable that, upon exit, contains the maximum data
             value used in constructing the histogram.

         OMIN:    A named variable that, upon exit, contains the minimum data
             value used in constructing the histogram.

 REVERSE_INDICES: Set this keyword to a named variable in which the list of
             reverse indices is returned.  This list is returned as a longword
             vector whose number of elements is the sum of the number of elements
             in the histogram, N, and the number of array elements included in
             the histogram.

             The subscripts of the original array elements falling in the
             ith bin, 0 le i lt N, are given by the expression: R(R(i):R(i+1)-1),
             where, R is the reverse index list.  If R(i) is equal to R(i+1),
             no elements are present in the ith bin.

 EXAMPLE:
        Here'a a very simple example of a weighted histogram:

        z = indgen(10)
        w = z
        y = HIST1D( z,w,OBIN=x)
        plot,x,y,psym=10

 MODIFICATION HISTORY:
        Written by:    Han Wen, July, 1994.
        01-AUG-1994    Forced H to be double, H=double(Density) avoids
                       the intermittent bug when H returns as a INTEGER
                       histogram!
        31-JAN-1995    Added the ANONYMOUS_ keyword to avoid a very subtle/
                       rare bug with _EXTRA keyword. (Has no functionality
                       for the USER -> Internal user only.)
        21-FEB-1995    Bugfix: didn't add Input to histogram for 1D,
                       UN-weighted histogram. Also made use of TEMPORARY.
        09-JAN-1995    Bugfix: change for loop index to long instead of fix.
                       Improperly indexed R(R(i)) pointers.
        28-FEB-1996    Added the BINEDGE keyword.
        06-APR-1996    Assume the data type of the Weight parameter if
                       specified. (previously defaulted to double)

(See /host/bluemoon/usr2/idllib/contrib/groupk/hist1d.pro)


HIST2D

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        HIST2D

 PURPOSE:
        Return the weighted density function (histogram) of two variables.

 CATEGORY:
        Image processing, statistics, probability.

 CALLING SEQUENCE:
        Result = hist2d(V1, V2 [,Weight, ...histogram keywords])
 INPUTS:
        V1 and V2 = arrays containing the variables.  They MAY be
             of ANY type, and MAY contain negative elements.

 OPTIONAL INPUTS:
       Weight:    1D array of the same dimension as V1 and V2 which holds the
             weighted values associated with each V1 and V2 element.

 INPUT KEYWORD PARAMETERS:
     BINSIZEn:    The size of the bin to use for the Vn array. If this
             keyword is not specified, a bin size of 1 is used. (n = 1,2)

        INPUT:    2D array to be added to the output of HIST2D.

         MAXn:    The maximum value to consider in the histogram of the Vn
             array.  If this keyword is not specified, Vn is searched for
             its largest value. (n = 1,2)

         MINn:    The minimum value to consider in the histogram of the Vn
             array.  If this keyword is not specified, and Vn is of type
             byte, 0 is used. If this keyword is not specified and Vn is
             not of byte type, Vn is searched for its smallest value. (n=1,2)

     BINEDGEn:    This keyword specfies the location of the bin values returned
             by OBINn. The values are:

                  0 : Center of each bin, [DEFAULT].
                 -1 : Left  or lower edge of each bin.
                  1 : Right or upper edge of each bin.

 OUTPUTS:
        The two dimensional weighted density function of the two variables.
        If Weight is not specified, then the usual, unweighted 2D histogram
        is returned.

 OUTPUT KEYWORD PARAMETERS:

      DENSITY:    Density function of V1 and V2; i.e. the unweighted 2D histogram.

        OBINn:    An array holding the bin values of the histogram of Vn. (n=1,2)

        OMAXn:    A named variable that, upon exit, contains the maximum data
             value used in constructing the histogram of Vn. (n=1,2)

        OMINn:    A named variable that, upon exit, contains the minimum data
             value used in constructing the histogram of Vn. (n=1,2)

 COMMON BLOCKS:
        None.
 SIDE EFFECTS:
        None.
 RESTRICTIONS:
        None.

 EXAMPLE:
        Return the 2D histogram of two byte images:
             R = HIST_2D(image1, image2)
        Return the 2D histogram made from two floating point images
        with range of -1 to +1, and with 100 bins:
             R = HIST_2D(f1,f2)

 MODIFICATION HISTORY:
        Written by:
        DMS, Sept, 1992     Written, IDL
        28-JUL-1994         H.C. Wen, Formerly, HIST_2D, Expanded input
                            array types, added weight option and added
                            HISTOGRAM keywords
        28-FEB-1996         Added the BINEDGE1, BINEDGE2 keywords.

(See /host/bluemoon/usr2/idllib/contrib/groupk/hist2d.pro)


INIT_SCAN

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        INIT_SCAN

 PURPOSE:

        Initializes all the common block variables to their
        appropriate values before you run the GET_SCAN routine.

 CATEGORY:
       I/O

 CALLING SEQUENCE:

        Result = INIT_SCAN( Newfile, [, NBUFFERS=NBuffers, FORMAT=Format] )

 INPUT KEYWORD PARAMETERS:

     NBUFFERS:    The number of major frames you want retained in the
             buffer arrays, [integer].(See RESTRICTIONS below)

       FORMAT:    String describing format of the data file. (See READ_MJF)

 OUTPUT:
        This function returns the value of the file pointer associated
        with Newfile.

 RESTRICTIONS:
        You MUST call this routine BEFORE calling GET_SCAN!
        One of the buffer elements is reserved for "looking ahead"
        for sequential major frames. (i.e. the USER actually has
        nbuffers - 1 buffers available.

 MODIFICATION HISTORY:
        Written by:  H.C. Wen, May, 1994.
        15-MAY-1994  Added an end-of-file flag for each file buffer, eofb.
        26-JUN-1994  Replace multiple commons with multi-variables/arrays
                     with one common and one structure.
                     Merged OPEN_BUF, eliminated multiple files.
        01-AUG-1994  Formerly called INIT_BUF; Added FORMAT keyword, shifted
                     definition of data structure to a separate routine,
                     DEF_MJF so that all xxx_SCAN routines will be independent
                     of any modifications to the data structure.

(See /host/bluemoon/usr2/idllib/contrib/groupk/init_scan.pro)


INQUIRE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        INQUIRE

 PURPOSE:
        This function asks the USER to respond to a question (usually Y/N)
        and then return the USER's response as a boolean.

 CATEGORY:
        STRLIB.

 CALLING SEQUENCE:

        Result = INQUIRE( Question [, ansY, ansN ] )

 INPUTS:
        Question: String containing the question to be asked to the USER.

 OPTIONAL INPUTS:

        ansY, ansN:    The ASCII character of the USER's response which
                  will return this function as TRUE, FALSE, respectively.

 EXAMPLE:
        if INQUIRE( 'Are you happy? (y/n) ' ) then $
             print,'Good for you!' $
        else $
             print,'That''s too bad.'

        if INQUIRE( 'Which do you prefer, (E)at or (S)leep? ', 'E', 'S' ) $
        then begin
             print,'You need to lose some weight!'
        endif else begin
             print,'Wake up too early this morning?'
        endelse

 MODIFICATION HISTORY:
        Written by:    Han Wen, October, 1994.
        01-JUN-1995    Eliminated call to PROMPT routine.

(See /host/bluemoon/usr2/idllib/contrib/groupk/inquire.pro)


IUPHBR

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        IUPHBR

 PURPOSE:
        This function extracts the 10 bins of 7.8125 usec High-Bit-Rate
        data from the input word(s).  Starting from the LSB at bit 0,
        bits 0-5 and 8-11 of the input word(s) are returned as bits 0-9.

 CATEGORY:
        HEAO HBR.

 CALLING SEQUENCE:

        Result = IUPHBR( HBRwords )

 INPUTS:
        HBRwords: A word or array of words containing High-Bit-Rate RAW data.

 OUTPUTS:
        Defining bit 0 as the Least Significant Bit (LSB), bits 0-9 of the
        returned value(s) are filled with bits 0-5 and bits 8-11 of HBRwords.

 MODIFICATION HISTORY:
        Written by:    Han Wen, July 1995.

(See /host/bluemoon/usr2/idllib/contrib/groupk/iuphbr.pro)


KILLAPE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        KILLAPE

 PURPOSE:
        This routine removes Adjacent Photon Events (APEs) from a MJF block
        of HBR PTI data.  An APE is defined as two photons occurring in adjacent
        8 usec bins ACROSS sequential HBR data words.  Namely, the first photon
        occurs in time bin 9 and the second photon occurs in time bin 0 of the
        next word.  These events occur in the HBR PTI data for roughly 3-4% of
        all photons lying in time bin 0 or 9.  They are considered  UNPHYSICAL
        due to the deadtime of the detector (>16 usec) and the consistent
        occurrance of these events ONLY across sequential HBR data words.

 CATEGORY:
        HEAO HBR.

 CALLING SEQUENCE:

        KILLAPE, PTIblock, Fixes

 INPUTS:
        PTIblock: Structure variable holding the next MJF block of PTI data.
                  It is one of the outputs of the READPTI routine.

 OUTPUTS:
        Fixes:    This structure variable holds the corrected time intervals.
                  Its tags are defined as follows:

                  nAPE:     The number of APEs found in this MJF block.
                  hAPE:     Array of indices pointing to elements in the orginal
                            Photon Time Interval array, PTIblock.PTI where APEs
                            were found. (= -1 if nAPE=0).
                  pti:      The corrected PTIs with APEs removed and neighboring
                            PTIs corrected. (= -1 if no photons in MJF block).

 PROCEDURE:
        This routine first finds any APEs by determining which PTIs = 1
        occur across adjacent HBR data words.  The PTIs corresponding to any
        APEs found are marked and later removed.  The neighboring PTIs before
        and after the APEs are subsequently corrected by adding a 1 to the
        smaller of the two PTIs.  If the two PTIs are equal, then the 1 goes to
        the PTI before the APE.  This algorithm leads to a roughly equal
        distribution of corrections before and after the APEs.

 EXAMPLE:

        OPENPTI, lu, !DATA_PATH+'086_7_7.xdr'   ; Open a HBR PTI data file
        READPTI, lu, block                      ; Read in a MJF block
        KILLAPE, block, fixes                   ; Remove APEs

        h    = hist1d( fixes.pti, MIN=0, MAX=100 )
        plot,h,psym=10,xrange=[0,100]

 COMMON BLOCKS:
        DEF_HBRH: Holds all the MJF and MNF PTI pointers, (see def_hbrh.pro).

 MODIFICATION HISTORY:
        Written by:    Han Wen, September 1995.
        09-OCT-1995    Return short integer for fixes.nAPE instead of long integer

(See /host/bluemoon/usr2/idllib/contrib/groupk/killape.pro)


KSTWO

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        KSTWO

 PURPOSE:
        Given an array data1, and an array data2, this routine returns
        the Kolmogorov-Smirnov statistic d, and the significance level
        prob for the null hypothesis that two given data sets are drawn
        from the same distribution.  Small values of prob show that the
        cumulative distribution function of data1 is significantly
        different from that of data2.  The arrays data1 and data2 are
        modified by being sorted into ascending order

        (Adapted from a routine of the same name in Numerical Recipes in C,
        Second edition).

 CATEGORY:
        Math.

 CALLING SEQUENCE:

        KSTWO, Data1, Data2, D, Prob

 INPUTS:
        Data1/2:  First/second data array.

 OUTPUTS:

        Data1/2:  Original Data1/2 array sorted into ascending order.

        D:        K-S statistic.

        Prob:     K-S significance level.

 MODIFICATION HISTORY:
        Written by:    Han Wen, August 1996.

(See /host/bluemoon/usr2/idllib/contrib/groupk/kstwo.pro)


LANDSCAPE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        LANDSCAPE

 PURPOSE:
        Graphics Device Manager for Landscape mode.
        (see DEVICE_MGR routine)

 CATEGORY:
        Graphics.

 MODIFICATION HISTORY:
        Written by:    Han Wen, November 1994.

(See /host/bluemoon/usr2/idllib/contrib/groupk/landscape.pro)


LCLEGEND

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        LCLEGEND

 PURPOSE:
        Returns the Standard Light Curve legend.

 CATEGORY:
        String manipulation.

 CALLING SEQUENCE:

        Result = LCLEGEND( Srcnames, Cts [, Sigma ] )

 INPUTS:
      Srcnames:   An array of source names, [string( nsrc )].

           Cts:   The fitted intensities for each source, Counts/bin, [float( nsrc )].

 OPTIONAL INPUTS:
         Sigma:   The uncertainties of these fitted intensity values, [float( nsrc )].

 OUTPUTS:
        An array of strings summarizing the fitted intensities for each source.

 MODIFICATION HISTORY:
        Written by:    Han Wen, May, 1994.
        18-NOV-1994    Made the sigma input optional

(See /host/bluemoon/usr2/idllib/contrib/groupk/lclegend.pro)


LCLOADCT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        LCLOADCT

 PURPOSE:
        Defines the color palette used by LIGHT_CURVE and other plotting routines.

 CATEGORY:
        Image Display.

 CALLING SEQUENCE:

        LCLOADCT

 OPTIONAL INPUT KEYWORDS:

        UNLOAD    : Set this keyword to unload the LIGHT_CURVE color table
                    and restore the B-W LINEAR color table.

 MODIFICATION HISTORY:
        Written by:    Han Wen, May 1994.

(See /host/bluemoon/usr2/idllib/contrib/groupk/lcloadct.pro)


LCSUBTITLE

[Previous Routine] [Next Routine] [List of Routines]

 NAME:
        LCSUBTITLE

 PURPOSE:
        Returns the Standard Light Curve subtitle.

 CATEGORY:
        String manipulation.

 CALLING SEQUENCE:

        Result = LCSUBTITLE( Srcname, Bin_pk, Trn_pk, Cts_pk, Bkd_pk )

 INPUTS:
       Srcname:   The name of the source, [string].

        Bin_pk:   The bin where the transmission is a max. for this source, [integer].

        Trn_pk:   The transmission max. for this source, [float].

        Cts_pk:   The counts in bin, Bin_pk, [float].

        Bkd_pk:   The fitted background value at bin, Bin_pk, [float].

 OUTPUTS:
        A subtitle string summarizing the characteristics of a source.

 MODIFICATION HISTORY:
        Written by:    Han Wen, May, 1994.
        19-MAY-1994:   Change source#1 info summary to fit summary

unction LCSUBTITLE, Chisq, Chisq_pk, Chisq_bk

(See /host/bluemoon/usr2/idllib/contrib/groupk/lcsubtitle.pro)


LCTITLE

[Previous Routine] [Next Routine] [List of Routines]

 NAME:
        LCTITLE

 PURPOSE:
        Returns the Standard Light Curve title.

 CATEGORY:
        String manipulation.

 CALLING SEQUENCE:

        Result = LCTITLE( Mjf )

 INPUTS:
           Mjf:   A list of sequential major frame numbers, [long(nmjf)].

 OUTPUTS:
        A title string containing a list of sequential major frame numbers.

 MODIFICATION HISTORY:
        Written by:    Han Wen, May, 1994.

unction LCTITLE, mjf

(See /host/bluemoon/usr2/idllib/contrib/groupk/lctitle.pro)


LCU

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        LCU

 PURPOSE:
        Interactively displays the light curves of an IDL data file for
        each scan.  Other light curve utilities include: searching for a
        particular scan; printing the displayed light curves; and creating
        a list of major frame numbers by individually marking each scan.

 CATEGORY:
        Widgets.

 CALLING SEQUENCE:

        LCU

 RESTRICTIONS:
        Assumes that the data file is in the proper IDL format as defined by
        the FMT_IDL or FMT_SRCDATA program.

 MODIFICATION HISTORY:
        Written by:    Han Wen, April, 1994.
        06-MAY-1994    Absorbed the fitting calculations previously
                       done in LIGHT_CURVE.  Off-loaded these calculations
                       onto the CT_RATE routine which is called in this routine.
        10-MAY-1994    Off-loaded all buffering of data into separate routines,
                       READ_BUF, INIT_BUF, OPEN_BUF, CLOSE_BUF, CLEAR_BUF. The
                       buffering is much more sophisticated: can open multiple files;
                       concatenate ANY number of sequential major frames.
        14-MAY-1994    Added a print option to plot the graph with a white background.
        19-MAY-1994    Fit background and signal simultaneously, INTENSITY().
        23-MAY-1994    Display light curve in [counts/sec] instead of [counts/bin].
        13-JUN-1994    Load default B-W IDL color table when exiting routine.
                       Expose plotting window; delete plotting window when exiting routine.
        26-JUN-1994    Changed READ_BUF -> GET_BUf.
        18-JUL-1994    Change output of outfile to all fitted mjf data params.
        01-AUG-1994    Changed GET_BUF -> GET_SCAN.
        19-AUG-1994    Added Window to define a large plotting region
        14-SEP-1994    Added a print to PCL file option.
        15-NOV-1994    Changed PCL -> PS => LANDSCAPE
        18-NOV-1994    Changed 'WIN' -> !D.NAME, only WSHOW for 'WIN'
        13-DEC-1994    Used WIDED to make LCU into a widget application => LCU
        07-JAN-1994    Added message box when clicking Mark button
        22-JAN-1995    Moved LCU -> OBSOLETE directory, Renamed XLCU->LCU
        06-AUG-1996    Check if !DATA_PATH system variable is defined.

(See /host/bluemoon/usr2/idllib/contrib/groupk/lcu.pro)


LEGEND2

[Previous Routine] [Next Routine] [List of Routines]
 Name:
       LEGEND2
 Purpose:
   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).
 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
 Usage:
   legend[,items][,keyword options]
 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.
   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. PSYM(i) = 8 corresponds to a circle 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)
   delimiter = embedded character(s) between symbol and text (D=none)
   colors = array of colors for plot symbols/lines (D=!color)
   textcolors = array of colors for text (D=!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)
   charsize = just like !p.charsize for plot labels
   position = data coordinates of the upper left 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. (D=square)
   /fill = flag to fill the usersym or PSYM=5,6 or 9
   /left = flag to place legend snug against left side of plot window (D)
   /right = 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 = 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.
 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.
   - Data and device coordinate specification of position (done 17 jan 94)
   - 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.
   - It might be nice to force the legend to be placed at hardwired
     locations in the plot, e.g., with keywords like /left/bottom for
     lower left.  Allowing this requires knowing the width of the text
     before it is printed, which is difficult. (done on 18 Jun 93)
 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
   18-JAN-1996    Added option to use FILL keyword on PSYM = 5 (triangle),
                  6 (square) and 9 (circle).  Added PSYM=9 (circle). HCW.

(See /host/bluemoon/usr2/idllib/contrib/groupk/legend2.pro)


LIGHT_CURVE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        LIGHT_CURVE

 PURPOSE:
        Generates a light curve of the data along with the transmission
        function(s) normalized to the area under the light curve.

 CATEGORY:
        Data Analysis.

 CALLING SEQUENCE:

        LIGHT_CURVE, Cts, [ Trns, Trn_fit, LEGEND=legend, ..other plotting keywords ]

 INPUTS:
          Cts:    Array holding the counts for the current major frame, [float( nbin )].

 OPTIONAL INPUTS

         Trns:    A nsrc x nbin array of transmission functions, [float( nsrc, nbin )].

      Trn_fit:    An array containing the total transmission function fitted
             to the counts of the the light curve, float(nbins).

 OPTIONAL INPUT KEYWORD PARAMETERS:

       LEGEND:    Adds a legend to the plot, [string(nsrc)].

       LTITLE:    A string array specifying the text to include
             in the legend, [string()].

        TITLE:    Specifies a title to the plot, [string].

     SUBTITLE:    Subtitle below the x-axis title, [string].

       XTITLE:    Title along the x-axis,[string].

       YTITLE:    Title along the y-axis,[string].

       XRANGE:    Specifies an range along the x-axis for the plot,[float(2)].

         PSYM:    Specifies the symbol type for plotting the counts,[integer].

    WHITE_BKD:    Plot graph with a white background instead of black.

 OPTIONAL OUTPUTS:

 RESTRICTIONS:
        LCLOADCT must be called once before calling this routine
        to load the appropriate color table.
        If you want a legend to be plotted you must include the Trns
        array input.

 EXAMPLE:
        Let's say our current major frame is in 320ms mode and we have
        two sources within the field of view.  Let's plot the light curve
        for this major frame onto the screen.

        nbin = 128
        cutoff = 0.05
        A    = [0.8, 0.5]
        ctr  = [60., 80.]
        sig  = [5. , 10.]

        Cts  = 10 * abs(randomn( seed, nbin )) + 50
        Trns = fltarr( 2, nbin )

        Let's generate two "gaussian" transmission functions

        for i=0, nbin-1 do begin

             for j=0,1 do begin
                  trns(j,i) = A(j) * exp( -((i-ctr(j))/sig(j) )^2. )
                  if trns(j,i) lt cutoff then trns(j,i) = 0.
                  cts(i) = cts(i) + 100. * trns(j,i)
             endfor

        endfor

        LIGHT_CURVE, Cts, Trns, /PLOT, /LEGEND

 MODIFICATION HISTORY:
        Written by:    Han Wen, April 1994.
        28-APR-1994    Added the LEGEND keyword.
        01-MAY-1994    Added overlaying transmission functions
                       normalized to lie underneath the light curve.
        02-MAY-1994    Overlayed transmission functions now plotted
                       with different colors.
        05-MAY-1994    Reduced/simplified the scope of LIGHT_CURVE;
                       off-loaded all fitting calculations to a
                       separate routine, CT_RATE.
        10-MAY-1994    Removed zeroing of the y-axis for counts.
                       Scaled transmission to full range;
                       plot its axis on the right side.
        15-MAY-1994    Define color table in LCLOADCT procedure. Added
                       WHITE_BKD keyword to generate printable plot.

(See /host/bluemoon/usr2/idllib/contrib/groupk/light_curve.pro)


LOGREBIN

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        LOGREBIN

 PURPOSE:
        Rebins a XYdY distribution into equal logarithmic (base 10)
        intervals in X.

 CATEGORY:
        Math.

 CALLING SEQUENCE:

        LOGREBIN, X, Y, Dy, Ny, Nbins, DlogX

 INPUTS:
        X:        Array of abcissae.

        Y:        Array of Y values.

        Dy:       Array of 1 sigma error bars along Y.

        Ny:       Number of points used to determine each Dy, LONG.

        Nbins:    Number of bins of the rebinned XYdY distribution.

 OUTPUTS:
        X,Y,Dy:   The X-Y-dY distribution rebinned into Nbins equal
                  logarithmic intervals in X, Array(Nbins)

        Ny:       Number of points used to determine each rebinned Dy,
                  LONARR(Nbins).

        DlogX:    The width or bin size of each equal logarithmic
                  interval in X.

 RESTRICTIONS:
        Each input data point, X, Y, Dy is assumed to be derived from
        averaging Ny distributions of XY.

 EXAMPLE:
        ; Create some simple data from a SIN wave
        X = FINDGEN(100)+50
        Y = ABS(SIN(X/10))
        dY= SQRT(Y/10)
        ny= 5
        nbins = 30

        ; Plot original and rebinned XYdY distributions as log-scalar plots
        ploterr,  X, Y, Dy, PSYM=3, /XTYPE, XRANGE=[MIN(X,MAX=mx),mx]
        LOGREBIN, X, Y, Dy, Ny, Nbins, DlogX
        oploterr, X, Y, Dy

 MODIFICATION HISTORY:
        Written by:    Han Wen, August 1996.
        19-AUG-1996    Corrected numerical round off errors and the case
                       when Ny=1, leading to negative or NaNQ variances.
                       Location of the last bin edge defined to be
                       consistent with [min,max) convention.

(See /host/bluemoon/usr2/idllib/contrib/groupk/logrebin.pro)


LPGM_LC

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        LPGM_LC

 PURPOSE:
        Calculates the Lomb Normalized Periodogram of the light curves
        for a source, customized to the HEAO A-1 data.

 CATEGORY:
        HEAO A-1.

 INPUTS:

   Time:     Array of times in SECONDS since 1/1/77, [dblarr( npts )].

   Flux:     Array of corresponding intensities for the source,
             [fltarr( npts )] in units specified by the FLUX_UNITS keyword.

   SrcName:  The name of the source, [string].

 OPTIONAL INPUT PARAMETERS:

   OFAC:          Oversampling factor of the periodogram, (4=Default).

   HIFAC:         Hifac * "average" Nyquist frequency = highest frequency
                  for which values of the Lomb normalized periodogram will
                  be calculated, (1=Default)
 OUTPUTS:

        This routine makes periodograms of the light curves of the HEAO A-1
        data and sends them to the graphic device if the USER selects it from the widget
        menu.

 MODIFICATION HISTORY:
   February, 1994          H.C. Wen
        06-AUG-1996    Check if !SAVE_PATH system variable is defined.

(See /host/bluemoon/usr2/idllib/contrib/groupk/lpgm_lc.pro)


MAIN_SCAN

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        MAIN_SCAN

 PURPOSE:
        This is the main driver routine to loop through the major frame buffers
        from IDL data files.  It serves to take care of the overhead of reading
        major frames into the buffer and then accessing that buffer; i.e.
        redundant code which every routine that accesses the data must have.
        Each major frame buffer consists of a block of sequential major frames.

 CATEGORY:
        I/O

 CALLING SEQUENCE:
        MAIN_SCAN [,File]

 OPTIONAL INPUTS:
         File:    The path/filename of the IDL data file you wish to access, [string].
             If this option is not provided or there is a problem finding this
             file, then the USER will interactively select the file.

 OPTIONAL INPUT KEYWORD PARAMETERS:
    USER_INIT:    Name of the function used to initialize USER variables,
             open USER files, etc., [string].

      USER_IO:    Name of the function used to determine the I/O operation
             to be performed on the next access of the buffer; i.e. get
             the next/previous major frame buffer, etc., [string].

    USER_DATA:    Name of the function to pass all the variables from the
             major frame buffer you selected using USER_IO. The USER may
             use these variables for their analysis, [string].

     USER_END:    Name of the function to clean-up any USER variables,
             open files, etc., [string].

     NBUFFERS:    The maximum number of major frames to be held in the buffer, [integer].

       FORMAT:    String describing the format of the data file. (See DEF_MJF).

       _EXTRA:    Any number of additional keywords may be added.  They are
             passed to the USER_INIT routine (see example below).


 OUTPUT KEYWORD PARAMETERS:

       OUTPUT:    A scalar, array or structure containing outputted
             results from USER_END

 RESTRICTIONS:
        The functions defined by the above INPUTS must have the following
        form:

                  function USER_INIT [, USER keywords ]
                  function USER_IO, Move, PickMJF, Nowarn, Log $
                                 [, USER keywords ]
                  function USER_DATA,Data, [, USER keywords ]
                  function USER_END,  OUTPUT=Output[, USER keywords ]

        while the names can be anything the USER choses.
        Data is a structure variable holding all the data of the major
        frame buffer retrieved.  Its tags or members are defined in DEF_MJF.

        NOTE: If any of these function returns a 0 value then MAIN_SCAN aborts by
        closing the IDL data file and clearing all buffers.

 EXAMPLE:
        Let's say you want to look at the light curves from an IDL
        data file.  You may want to create a routine, LIGHT_CURVE:

                pro LIGHT_CURVE, file, TEXT=Text
                     MAIN_SCAN, file, USER_DATA='LC_DATA',USER_END='LC_END',$
                           USER_INIT='LC_INIT',TEXT=Text
                end

        AND the following USER routines:

                function LC_INIT, FORMAT=Format, TEXT=Text
                       print,Text
                       return, 1
                end

                function LC_DATA, Data, FORMAT=Format, TEXT=Text

                    plot, data.cts, psym=10  ;plot data in histogram format
                    return, 1
                end

                function LC_END, FORMAT=Format, TEXT=Text
                    wdelete ;close plotting window
                    return, 1
                end

        NOTE: The TEXT keyword is an "extra" keyword to MAIN_SCAN and is
              passed to the LC_INIT routine.

 MODIFICATION HISTORY:
        Written by:    Han Wen, June 1994.
        03-AUG-1994    Removed OUTPUT keyword from USER_DATA.
        29-AUG-1994    Implemented the !DATA_PATH system variable defined
                       in HEAO.RUN
        30-AUG-1994    Changed Init_params to USER_keywords and passed this
                       using the _EXTRA keyword to ALL USER routines. The
                       FORMAT keyword is also now passed to ALL USER routines.
        30-DEC-1994    Added the GET_FMT function to determine the format
                       of the data file if the FORMAT keyword is not specified.
        31-JAN-1995    Added the ANONYMOUS_ to avoid a subtle/rare bug with the
                       _EXTRA keyword. (Has no functionality for the USER
                       -> i.e. for internal use only).
        06-AUG-1996    Check if !DATA_PATH system variable is defined.

(See /host/bluemoon/usr2/idllib/contrib/groupk/main_scan.pro)


MAKEDBS

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        MAKEDBS

 PURPOSE:
        This function extracts the (#MJF header line of each major frame
        in an IDL data file an writes it out to a "database" file.

 CATEGORY:
        I/O.

 CALLING SEQUENCE:

        MAKEDBS [, Datafile, Dbsfile]

 OPTIONAL INPUTS:

        Datafile: Name (including path) of the IDL data file.

        Dbsfile:  Name (including path) of the output database file.

 OUTPUTS:
        Creates a .dbs file that may be used by XFiducial to determine
        various scan buffer parameters.

 MODIFICATION HISTORY:
        Written by:    Han Wen, January 1995.
        06-AUG-1996    Check if !DATA_PATH system variable is defined.

(See /host/bluemoon/usr2/idllib/contrib/groupk/makedbs.pro)


MK_AVGLC

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        MK_AVGLC

 PURPOSE:
        Processes the data structure returned by FIDUCIAL to generate
        plots of the average & weighted average light curves of
        the HEAO A-1 data.

 CATEGORY:
        HEAO A-1.

 OUTPUTS:

        This routine generates postscript files of light curve plots of
        the HEAO A-1 data and then sends these files to the printer
        defined by the PRINTER environment variable.

 COMMON:
        MK_AVGLC:  For internal use only.

 MODIFICATION HISTORY:
   September, 1994          H.C. Wen
   20-JAN-1995              Made compatible with .SAV format of XFiducial 3.1
   22-JAN-1995              Widgetized all options.
   01-FEB-1995              Implemented XPLOT, XOPLOT
   06-FEB-1995              Implemented GET_DATA, added TRN_CUT option
   07-FEB-1995              Bugfix: didn't find lc for source index > 0 properly
                            Also moved restore of DATA structure to File.
                            Units of error bars incorrect
   08-FEB-1995              Got rid of GETHALVES, simplified to using WHEREGION

(See /host/bluemoon/usr2/idllib/contrib/groupk/mk_avglc.pro)


MK_FOLDLC

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        MK_FOLDLC

 PURPOSE:
        Processes the data structure returned by FIDUCIAL to generate
        plots of the folded light curves of the HEAO A-1 data.

 CATEGORY:
        HEAO A-1.

 OUTPUTS:

        This routine generates postscript files of FOLDED light curve plots of
        the HEAO A-1 data and then sends these files to the printer
        defined by the PRINTER environment variable.

 COMMON:
        MK_FOLDLC:  For internal use only.

 MODIFICATION HISTORY:
   February, 1994          H.C. Wen
   06-FEB-1995              Implemented GET_DATA, added TRN_CUT option
   08-FEB-1995              Got rid of GETHALVES, simplified to using WHEREGION

(See /host/bluemoon/usr2/idllib/contrib/groupk/mk_foldlc.pro)


MK_LPGM

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        MK_LPGM

 PURPOSE:
        Processes the data structure returned by FIDUCIAL to generate
        plots of the Lomb Normalized Periodogram of the HEAO A-1 data.

 CATEGORY:
        HEAO A-1 Scanning.

 CALLING SEQUENCE:

        MK_LPGM

 OUTPUTS:

        This routines generates periodograms and sends the output to
        either the display or to a postscript file.  If the postscript
        output is chosen, then the USER may additional choose to send
        the postscript file to the printer defined by the PRINTER
        environment variable.

 COMMON:
        MK_LPGM:  For internal use only.

 MODIFICATION HISTORY:
   January, 1995            H.C. Wen
   03-FEB-1995              Bugfix: Start of date correction.
   06-FEB-1995              Implemented GET_DATA, added TRN_CUT option,
                            subtracted out average before calculating the
                            periodogram.
   08-FEB-1995              Adopted changes in MK_AVGLC and MK_FOLDLC

(See /host/bluemoon/usr2/idllib/contrib/groupk/mk_lpgm.pro)


MRG_DATA

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        MRG_DATA

 PURPOSE:
        Merges two or more DATA structures stored in IDL SAVE session files.
        These files must have been created by FIDCUTS1 version 6.0 or later.

 CATEGORY:
        HEAO A-1.

 CALLING SEQUENCE:

        MRG_DATA
 OUTPUTS:
        The merged DATA structure is saved to a file specified interactively
        by the USER.

 PROCEDURE:
        This procedure is useful if you have had to break up your IDL data file
        (.idl) on a particular source into multiple files, creating an IDL
        SAVE session file (.sav) for each separate file and would like to
        combine all these .sav files into one file. (e.g. LMC X-1)

 MODIFICATION HISTORY:
        Written by:    Han Wen, February 1995.
        06-AUG-1996    Check if !SAVE_PATH system variable is defined.

(See /host/bluemoon/usr2/idllib/contrib/groupk/mrg_data.pro)


MRK_LINE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        MRK_LINE

 PURPOSE:
        Allows the USER to interactively position a line on an existing plot.

 CATEGORY:
        Graphics.

 CALLING SEQUENCE:

        Result = MRK_LINE( [Window] )

 OPTIONAL INPUTS:

        Window:   Index of the plot window that the line is to be drawn in.

 OPTIONAL INPUT KEYWORD PARAMETERS:

        STATUS:   Set this keyword to display the coordinates of the current
                  cursor position in the lower left-hand corner of the plot
                  window. (0=Default)

        ERASE:    Set this keyword to erase the line and status coordinates
                  after the position of the line has been selected. (0=Default)

        HELP:     Set this keyword to display a instruction window on how
                  to interactively position the line on the plot. (0=Default)

        VERTICAL: Set this keyword to position a vertical line. (0=Default)

        HORIZONTAL:    Set this keyword to position a horizontal line. (0=Default)

        DATA:     Set this keyword to display and return line position in
                  data coordinates. (1=Default)

        NORMAL:   Set this keyword to display and return line position in
                  normalized coordinates. (0=Default)

        DEVICE:   Set this keyword to display and return line position in
                  device coordinates. (0=Default)

 OUTPUTS:
        Returns the position of the line in the coordinates specified by the
        USER (DATA=Default) as a (2,2) dimensioned array or a scalar if
        the horizontal or vertical keyword is set.  If a vertical line is selected,
        then the X-coordinate of that line is returned.  If a horizontal line is
        selected then the Y-coordinate of that line is returned. Otherwise, the
        (*,0) array specifies the position, (X0,Y0) of the "LEFT" endpoint, and
        the (*,1) array specifies the position, (X1,Y1) of the "RIGHT" endpoint.

 EXAMPLE:
        plot,indgen(100)
        x_position = MRK_LINE(/VERTICAL,/HELP)

 MODIFICATION HISTORY:
        Written by:    Han Wen, June 1995.
        07-SEP-1996    Draw an ARBITRARY line by default.
        10-SEP-1996    Display status before setting point.

(See /host/bluemoon/usr2/idllib/contrib/groupk/mrk_line.pro)


MRK_RECT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        MRK_RECT

 PURPOSE:
        Allows the USER to interactively position and size a rectangle
        on an existing plot.

 CATEGORY:
        Graphics.

 CALLING SEQUENCE:

        Result = MRK_RECT( [Window] )

 OPTIONAL INPUTS:

        Window:   Index of the plot window that the rectangle is to be drawn in.

 OPTIONAL INPUT KEYWORD PARAMETERS:

        STATUS:   Set this keyword to display the coordinates of the current
                  cursor position in the lower left-hand corner of the plot
                  window. (0=Default)

        ERASE:    Set this keyword to erase the rectangle and status
                  coordinates after the position and size of the rectangle
                  has been selected. (0=Default)

        HELP:     Set this keyword to display a instruction window on how
                  to interactively position the rectangle on the plot.
                  (0=Default)

        DATA:     Set this keyword to display and return rectangle position
                  in data coordinates. (1=Default)

        NORMAL:   Set this keyword to display and return rectangle position
                  in normalized coordinates. (0=Default)

        DEVICE:   Set this keyword to display and return rectangle position
                  in device coordinates. (0=Default)

 OUTPUTS:
        Returns the position of the rectanlge in the coordinates specified
        USER (DATA=Default).  Result(*,0) = [X0,Y0] is the position of the
        first corner.  Result(*,1) = [X1,Y1] is the position of the
        diagonally opposite corner.

 EXAMPLE:
        plot,indgen(100)
        rect_position = MRK_LINE(/HELP)

 MODIFICATION HISTORY:
        Written by:    Han Wen, June 1995.
        17-JUN-1995    Small bug-fix, TITLE of instructions incorrect (Mrk_Line)
        10-SEP-1996    Display status before setting point.

(See /host/bluemoon/usr2/idllib/contrib/groupk/mrk_rect.pro)


MTOEA

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        MTOEA

 PURPOSE:
        Computes the euler angles to transform body axes to space axes,
        given the transformation matrix from the body axes to the space axes.

 CATEGORY:
        Analytic Geometry.

 CALLING SEQUENCE:
        MTOEA, Matrix,A,B,C


 INPUTS:
       Matrix:    The 3x3 rotation matrix, [float(9)].

 OUTPUTS:
            A:    First euler angle in radians, -PI < A < PI, [float].

            B:    Second euler angel in radians, 0 < B < PI, [float].

            C:    Third euler angle in radians, -PI < C < PI, [float].

 RESTRICTIONS:
        NOTE: There is a replacement routine in this library,
         called dmtoea().  Besides being a double-precision
         version, it uses a more robust transformation algorithm
         --johnf, 7 March 1989

 MODIFICATION HISTORY:
        Written by:    John F., 1/30/75
        06-JUN-94:     Adapted into an IDL routine, H.C. Wen.
        15-AUG-1995    Comment bugfix: removed extraneous ;+ and ;-.

(See /host/bluemoon/usr2/idllib/contrib/groupk/mtoea.pro)


MULTIPSD

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        MULTIPSD

 PURPOSE:
        Given an array of times, ts divide the data into equal time segments,
        calculate the FFT power spectra of these segments and average
        the power spectra.

 CATEGORY:
        Math.

 CALLING SEQUENCE:

        Result = MULTIPSD( Ts, Bin, Nbin, Npsd, Mean, Sigma )

 INPUTS:
        Ts:       An array of times with starting time, Ts(0)=0.

        Bin:      The length of one time bin in the same UNITS as the Ts array.

        Nbin:     The number of time bins in each time segment.

 OPTIONAL INPUT KEYWORD PARAMETERS:

        VERBOSE:  Setting the keyword will display messages updating the user
                  on which time segment the routine is currently processing.

 OUTPUTS:
        This function returns the average FFT power spectra and the standard
        deviations about each average in an array, FLTARR((nbin/2), 2). The
        first column, (*,0) holds the power spectra
        averaged over Npsd time segments and the second column (*,1) holds the
        standard deviations about those averages.

 OPTIONAL OUTPUTS:

        Npsd:     The number of equal time segments the data was divided into.

        Mean:     Average number of counts/bin over all times FFTed.

        Sigma:    Sqrt of the variance of the counts/bin about the Mean over
                  all times FFTed.

 PROCEDURE:

        The average power spectra is usually normalized in one of two ways:
        Leahy or fractional RMS amplitude.  The Leahy normalized power is
        determined by multiplying (2/) with the results of this function:

        Pwrarray  = MULTIPSD( Ts, Bin, Nbin, Npsd, Mean, Sigma )
        Ncts      = Mean*Nbin
        Pleahy    = (2/Ncts)*Pwrarry(*,0)

        where Ncts is the average total number of counts in one time segment.

        The fractional RMS amplitude is a dimensionaless quantity defined as
        the square root of the variance of the counts/bin divided by the
        average counts/bin. Its normalization can be determined by dividing
        the Leahy normalized power by the average intensity, :

        Iavg      = Mean/Bin
        Prms      = Pleahy/Iavg

        To relate Prms to the actual fractional RMS amplitude, (Sigma/Mean):

        rms       = Sigma/Mean
        dFreq     = 1/(Bin*Nbin)
        TOTAL(Prms)= rms^2/dFreq

 EXAMPLE:

        The input parameters, nbin and bin are related to the limits of the FFT
        frequencies in the following manner:

        1/(nbin*bin)   = Minimum frequency
        1/(2*bin)      = Nyquist frequency

        Given a time array, ts=LONARR(500000)=[0,1000000], determine the average
        power spectra if Bin = 50 and Nbin = 4096.

        Bin  = 50
        Nbin = 1024    -> Npsd = 19 time segments

        pwr_result = MULTIPSD( Ts, Bin, Nbin, Npsd, RMS, /VERB )

 MODIFICATION HISTORY:
        Written by:    Han Wen, August 1996.
        14-AUG-1996    Eliminated LEAHY, RMS keywords, added RMS output parameter,
                       check number of parameters.
        15-AUG-1996    Removed RMS parameter, added Mean and Sigma parameters.
        30-AUG-1996    Bugfix: return sigma instead of variance.

(See /host/bluemoon/usr2/idllib/contrib/groupk/multipsd.pro)


NEWLINE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        NEWLINE

 PURPOSE:
        Print a blank line or line of a particular ASCII character
        to screen or other output device.

 CATEGORY:
        STRLIB.

 CALLING SEQUENCE:

        NEWLINE, [Luns]


 OPTIONAL INPUTS:
        Luns:     Array of logical units corresponding to the device(s) this
                  procedure outputs to, (Default=-1=Screen).

 OPTIONAL INPUT KEYWORD PARAMETERS:

        CHAR:     Charactor for which a line will be drawn, (Default=space).
                  If the output device is not the screen (i.e. a file) then
                  a semicolon, ; is at the beginning of the line.

 OUTPUTS:
        Prints a line to the screen (default) or the devices specified by
        the Luns parameter.  If the CHAR keyword is not specified, then
        a blank line is outputted, otherwise a line of CHAR characters is
        outputted.


 MODIFICATION HISTORY:
        Written by:    Han Wen, November 1994.

(See /host/bluemoon/usr2/idllib/contrib/groupk/newline.pro)


NEW_JOURNAL

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        NEW_JOURNAL

 PURPOSE:
        Closes any open journal file and opens a new one.

 CATEGORY:
        I/O.

 CALLING SEQUENCE:

        NEW_JOURNAL [,Name]

 OPTIONAL INPUTS:
        Name:     A string containing the name of the journal file to be opened.
                  If Name is not supplied then the system's time is used to
                  construct the name of the form: MNDDHHMM.log where,
                  MN=Month (01-12), DD=Day (01-31), HH=Hour (00-23)
                  and MM=Minutes (00-59).

 OPTIONAL INPUT KEYWORD PARAMETERS:
        PATH      A string containing the path of the new journal file.  The PATH
                  string is appended to the beginning of the Name string and the
                  resulting string is used as the argument to the JOURNAL routine.
                  (''=Default)

 EXAMPLE:
        To begin journaling a "daily" journal file, enter:

        NEW_JOURNAL

        Any commands entered at the IDL prompt are recorded in the file until
        IDL is exited or the JOURNAL command is entered without an argument.

 MODIFICATION HISTORY:
        Written by:    Han Wen, June 1995.

(See /host/bluemoon/usr2/idllib/contrib/groupk/new_journal.pro)


NRZUNPAK

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        NRZUNPAK

 PURPOSE:
        This function "unpacks" the raw 6.4 kbps NRZ data by extracting
        its 2.1 kbps HEAO A-1 component and storing it into a structure
        variable.

 CATEGORY:
        HEAO.

 CALLING SEQUENCE:

        Result = NRZUNPAK( NRZblock, Mode )

 INPUTS:
        NRZblock: An array holding a block of NRZ data, intarr(128,nMNF).
                  Each Minor Frame (MNF) of NRZ data contains 128 bytes.

        Mode:     An integer describing the telemetry mode of the data in
                  MILLISECONDS, (=5 or 320).

 OUTPUTS:
        This function returns a structure containing the HEAO A-1 component
        of the NRZ data.  Its tags depends on the Mode specified and are
        defined as follows:

        Mode = 320 ms

             nMNFs     :    Number of Minor Frames
             MNFs      :    Minor frame numbers, intarr(nMNFs)
             TCnt1_6   :    Total counts for Modules 1-6, intarr(6,nMNFs)
             TCnt7     :    Total counts for Module 7, intarr(nMNFs)
             SChT      :    Counts in 16-Channels for Mods 1-4, intarr(16,nMNFs)
             SCh5      :    Counts in 16-Channels for Mod 5, intarr(16,nMNFs)
             SCh6      :    Counts in 16-Channels for Mod 6, intarr(16,nMNFs)
             SCh7      :    Counts in 16-Channels for Mod 7, intarr(16,nMNFs/8)
             FCh       :    Counts in 40-Channels, intarr(40,nMNFs/2)
             Chmask    :    16-Channel MASKS, intarr(16,no. MNF #s = 119)
             AGC       :    Auto Gain Control structure:
                            HV   :    Monitor HV/Module, fltarr(7,nMJFs)
                            Loop :    Loop setting/Module, fltarr(7,nMJFs)
                            Gain :    Gain/Module, fltarr(7,nMJFs)
             Data      :    HEAO A-1 2.1 kbps data, intarr(256,nMNFs)

        Mode = 5 ms

             nMNFs     :    Number of Minor Frames
             MNFs      :    Minor frame numbers, intarr(nMNFs)
             PtMd      :    Counts for Modules 1-4, intarr(64,nMNFs)
             FCh       :    Counts in 40-Channels, intarr(40,nMNFs/2)
             Data      :    HEAO A-1 2.1 kbps data, intarr(256,nMNFs)

 RESTRICTIONS:
        This routines assumes that the block of NRZ data is contiguous in
        time. Namely, there are no MISSING MNFs.

 MODIFICATION HISTORY:
        Written by:    Han Wen, June 1995.
        21-SEP-1995    Added comments; replaced POINT and SCAN keywords
                       with Mode parameter.
        22-SEP-1995    Changed Chmask tag to MskS and added Msk7 tag.

(See /host/bluemoon/usr2/idllib/contrib/groupk/nrzunpak.pro)


OKCANCEL

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        OKCANCEL

 PURPOSE:
        This function prompts USER with a widget window with OK and
        Cancel buttons. Use this function to let the USER allow some
        subsequent action that you are going to take (described by the
        Msgs parameter) once this widget is destroyed.

 CATEGORY:
        Widgets.

 CALLING SEQUENCE:

        Result = OKCANCEL( [Msgs] )

 INPUTS:
        Msgs:     A string or array of strings containing message(s)
             to be displayed.

 OPTIONAL KEYWORD INPUTS:

        TITLE:    A string containing the title of the widget window,
                  ('IDL'=Default)

        ALIGN:    Set this keyword to left align each message string,
                  by default, each message string is centered (0=Default).

        RIGHT:    Display widget in the right corner of the display.

        LEFT:     Display widget in the left corner of the display.

        BOTTOM:   Display widget in the bottom corner of the display.

        TOP:      Display widget in the top corner of the display.

        CENTER:   Display widget in the center of the display (DEFAULT).

        GROUP:    The widget ID of an existing widget that serves as
                  "group leader" for this message widget.

 OUTPUTS:
        This function will return a 1 if the OK button is selected and a 0
        if the Cancel button is selected.

 COMMON BLOCK:
        OKCANCEL: For internal use only.

 MODIFICATION HISTORY:
        Written by:    Han Wen, January 1994.
        02-AUG-1995    Added scrollbar if number of messages exceeds 15.
        27-SEP-1995    Improved algorithm to determine width of widget in pixels.

(See /host/bluemoon/usr2/idllib/contrib/groupk/okcancel.pro)


OPENPTI

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        OPENPTI

 PURPOSE:
        This routine opens a Photon Time Interval (PTI) file.

 CATEGORY:
        HEAO HBR.

 CALLING SEQUENCE:

        OPENPTI, LU, File

 INPUTS:

        LU:       The logical unit to be associated with the opened PTI file.
                  If LU is undefined then the GET_LUN procedure is automatically
                  used to set its value.

 OPTIONAL INPUTS:

        File:     A string containing the name of the PTI file to be opened.
                  If this parameter is not provided, then the PICKFILE routine
                  is used to allow the USER to interactively select the name
                  of the PTI file.

 OPTIONAL INPUT KEYWORD PARAMETERS:

        GET_LUN:  Force the GET_LUN procedure to be called to defined LU if
                  LU is undefined or redefine LU if it is.

 OPTIONAL OUTPUT KEYWORD PARAMETERS:

        NRECORDS: The total number of 512 byte records in the opened PTI file.

 COMMON BLOCKS:
        DEF_HBRH:      Holds all the MJF and MNF PTI pointers, (see def_hbrh.pro).
        PTI_ENDIAN:    Holds variable that determines whether or not to swap bytes.

 PROCEDURE:
        Opens a PTI file and reads in the first record to determine the byte order.

 MODIFICATION HISTORY:
        Written by:    Han Wen, August 1995.
        29-SEP-1995    Added GET_LUN keyword.
        08-OCT-1995    Eliminated XDR and BINARY keywords; check for byte order;
                       made compatible with vers 4.0.1.
        09-OCT-1995    Moved Win 4.0.1 specific keywords to WINOPEN function.

(See /host/bluemoon/usr2/idllib/contrib/groupk/openpti.pro)


OVERLAP

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        OVERLAP

 PURPOSE:
        This function determines the fraction of transmission function for
        each source that is overlapping with the sum of the transmission
        functions from all other sources.

 CATEGORY:
        HEAO A-1.

 CALLING SEQUENCE:

        Result = OVERLAP( Trns )

 INPUTS:
        Trns:     A 2-d array holding the transmission values for each
                  bin of the scan and for each source, [fltarr(nsrc,nbin)].

 OUTPUTS:
        The function returns a fltarr(nsrc) array, giving the overlap fraction
        for each source.

 PROCEDURE:
        This function is used by the FIDUCIAL routine.

 MODIFICATION HISTORY:
        Written by:    Han Wen, February, 1995.

(See /host/bluemoon/usr2/idllib/contrib/groupk/overlap.pro)


PAUSE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        PAUSE

 PURPOSE:
        Pauses until the USER presses the ENTER or 'Q' key.

 CATEGORY:
        STRLIB.

 CALLING SEQUENCE:

        PAUSE

 OUTPUTS:
        Changes the prompt to 'Press ENTER to continue...' and waits
        for the USER to press the ENTER key.  Once the USER completes
        this request, the prompt is restored to its default appearance.

        If however, the USER presses the 'Q' key, then this routine
        aborts with a USER-BREAK error message.

 PROCEDURE:
        This is good for debugging.

 MODIFICATION HISTORY:
        Written by:    Han Wen, October 1994.
        01-JUN-1995    Eliminated call to PROMPT routine.
        31-OCT-1995    Added ON_ERROR,2.

(See /host/bluemoon/usr2/idllib/contrib/groupk/pause.pro)


PERIOD

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        PERIOD

 PURPOSE:
        Given data points with abscissas x (which need not be equally spaced)
        and ordinates y, and given a desired oversampling factor ofac (a
        typical value being 4 or larger), this routine fills array px
        with an increasing sequence of frequencies (not angular frequencies)
        up to hifac times the "average" Nyquist frequency, and fills array
        py with the values of the Lomb normalized periodogram at those
        frequencies.  The arrays x and y are not altered. The routine also
        returns jmax such that py(jmax) is the maximum element in py, and
        prob, an estimate of the significance of that maximum against the
        hypothesis of random noise.  A small value of prob indicates that
        a significant periodic signal is present.

        (Adapted from routine of the same routine in Numerical Recipes in C,
        Second edition).

 CATEGORY:
        Math.

 CALLING SEQUENCE:

        PERIOD, X, Y, Ofac, Hifac, Px, Py, Nout, Jmax, Prob

 INPUTS:
        X:        The abscissas of the data points.

        Y:        The ordinates of the data points.

        Ofac:     Oversampling factor.

        Hifac:    Maximum frequency of Px = Hifac * "average" Nyquist
                  frequency,.

 OUTPUTS:
        Px:       The frequencies of the Lomb normalized periodogram.

        Py:       The spectral powers of the Lomb normalized periodogram.

        Nout:     The number of elements of the Px or Py array.

        Jmax:     Index to the maximum element in Py.

        Prob:     Significance of Py(Jmax) against the hypothesis of
                  random noise.

 MODIFICATION HISTORY:
        Written by:    Han Wen, August 1996.
        07-AUG-1996    Eliminated redundant variables.

(See /host/bluemoon/usr2/idllib/contrib/groupk/period.pro)


PK_TRNS

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        PK_TRNS

 PURPOSE:
        Extracts the peak transmissions for each scan stored in the DATA
        structure.

 CATEGORY:
        HEAO A-1.

 CALLING SEQUENCE:

        Result = PK_TRNS( Data [,SrcIndex] )

 INPUTS:
        Data:     The DATA structure created by FIDUCIAL version 3.0 or later.

 OPTIONAL INPUTS:
        SrcIndex: The index number of the source you want peak transmissions
                  for, (0=Default).

 OUTPUTS:
        This function returns an 1-D array of NSCAN elements, where NSCAN
        is the number of scans in the DATA structure.  Each element contains
        the corresponding peak transmission for that scan and source index
        specified by the SrcIndex parameter.

 MODIFICATION HISTORY:
        Written by:    Han Wen, February 1995.
        08-FEB-1995:   Bugfix:incorrectly extracted pk_bins for srcindex>0

(See /host/bluemoon/usr2/idllib/contrib/groupk/pk_trns.pro)


PLOTSYM2

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
   PLOTSYM2
 PURPOSE:
   Define useful plotting symbols not in the standard !PSYM definitions.
   After symbol has been defined with PLOTSYM, a plotting command should
   follow with either PSYM = 8 or !P.PSYM = 8 (see USERSYM)

 CALLING SEQUENCE:
   PLOTSYM, PSYM,[ PSIZE, /FILL]

 INPUTS:
   PSYM -  The following integer values of PSYM will create the
        corresponding plot symbols
        0 - circle
        1 - downward arrow (upper limit), base of arrow begins at plot
             value
        2 - upward arrow (lower limt)
        3 - 5 pointed star
        4 - triangle
        5 - upside down triangle
        6 - left pointing arrow
        7 - right pointing arrow
        8 - square
   Arrows are defined such that their base begins at their origin.

 OPTIONAL INPUTS:
   PSIZE - Size of the plotting symbol in multiples of the default size
        (default PSIZE=1).  Does not need to be an integer

 OPTIONAL INPUT KEYWORD:
   FILL -  Parameter indicating whether to fill the symbol (see USERSYM)
        The default is 0, unfilled symbol.  Does not affect arrows
        or character symbols.

 OUTPUTS:
   None

 EXAMPLES:
   Plot Y vs. X with filled stars as the symbol, twice the default size
   IDL> PLOTSYM, 3 ,2, /FILL        ;Plotting symbol is a filled star,
                       ;twice default size
   IDL> PLOT,X,Y,PSYM=8             ;Set PSYM = 8 to get star symbol

   Now plot Y vs. X with open circle as the symbol
   IDL> PLOTSYM, 0               ;Plotting symbol is a circle
   IDL> PLOT,X,Y,PSYM=8

 METHOD:
   Appropiate X,Y vectors are used to define the symbol and passed to the
   USERSYM command.

 REVISION HISTORY
   Written       W. Landsman         June 1992
   18-JAN-1996    Added a square symbol, HCW.

(See /host/bluemoon/usr2/idllib/contrib/groupk/plotsym2.pro)


PLUSMINUS

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        PLUSMINUS

 PURPOSE:
        Returns the ASCII plus/minus character.

 CATEGORY:
        STRLIB.

 CALLING SEQUENCE:

        Result = PLUSMINUS()

 MODIFICATION HISTORY:
        Written by:    Han Wen, September 1994.

(See /host/bluemoon/usr2/idllib/contrib/groupk/plusminus.pro)


POIDEAD

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        POIDEAD

 PURPOSE:
        This function calculates the probability of detecting N counts in a
        given measuring time bin for a non-extended dead-time-distorted
        poisson process.  The algorithm uses formulae from Muller,
        "Some Formulae for a Dead-Time-Distorted Poisson Process", NIM 117
        (1974) 401.

 CATEGORY:
        Math.

 CALLING SEQUENCE:

        Result = POIDEAD( Ncount, Mean [, Tinterval, Deadtime ])

 INPUTS:
        Ncount:   A scalar or array of number of counts DETECTED in the given
                  measuring time bin.

        Mean:     A scalar or array of TRUE mean number of counts in the given
                  measuring time bin due to the ORIGINAL Poissonian process.

 OPTIONAL INPUTS:

        Tinterval:The length of the measuring time bin, (Default=1).

        Deadtime: The length of the non-extended dead time in the SAME units
                  as Tinterval, (Default=0).

 OUTPUTS:
        An scalar or array is returned giving the probability of detecting
        the counts specified in each element of Ncount and/or Mean.

 RESTRICTIONS:
        If Ncount and Mean are both arrays, they must have the same number
        of elements.
        Negative values in the input array will be returned as zeros.

 EXAMPLE:
        To determine the probability of detecting 0..100 counts in a 10 msec
        time bin if the true mean is 50 and the dead time is 20 usec, do the
        following:

        N    = lindgen(101)
        mu   = 50.0
        bin  = 10.0
        tau  = 20e-3
        Prob = POIDEAD( N, mu, bin, tau )
        plot,N,Prob,psym=10

 MODIFICATION HISTORY:
        Written by:    Han Wen, March 1996.
        15-JUL-1996    Suppress underflow error messages.
                       Bugfix: corrected roundoff error in Kappa
        17-JUL-1996    Accept an array argument for the Mean parameter.

(See /host/bluemoon/usr2/idllib/contrib/groupk/poidead.pro)


PORTRAIT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        PORTRAIT

 PURPOSE:
        Graphics Device Manager for Portrait mode.
        (see DEVICE_MGR routine)

 CATEGORY:
        Graphics.

 MODIFICATION HISTORY:
        Written by:    Han Wen, November 1994.

(See /host/bluemoon/usr2/idllib/contrib/groupk/portrait.pro)


PRINTFS

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        PRINTFS

 PURPOSE:
        Print to multiple devices with multiple formats. This is essentially
        an extension to the PRINTF routine.

 CATEGORY:
        IO.

 CALLING SEQUENCE:

        PRINTFS, luns [, v1,  v2, .... etc ]

 INPUTS:
        luns:     An array of logical units, (-1 = display).

 OPTIONAL INPUTS:

        v1, v2, etc:   Usual parameters passed to the PRINT or PRINTF routine,
                  (i.e. strings, floats, integers, arrays, etc.)

 OPTIONAL INPUT KEYWORD PARAMETERS:

        FORMAT:   An array of format specifications for each logical unit
                  of the luns array. If scalar, then this format is assumed
                  for all logical units specified.

        PROMPT:   Set the prompt to the string value of the v1 parameter.

        WAIT:     Number of seconds to wait after printing [0=Default]

 OUTPUTS:
        Prints to the devices of each logical unit specified by the luns array.

 OPTIONAL OUTPUTS:

        If the PROMPT keyword is set then the prompt is set to the string
        value of the first optional input parameter.

 MODIFICATION HISTORY:
        Written by:    Han Wen, November 1994.
        16-APR-1995    Bugfix: FORMAT does not work properly, tacked on nA0
        01-JUN-1995    Eliminated call to PROMPT routine.
        04-JUN-1995    Added the WAIT keyword.
        20-JUL-1995    Simplified routine: pass variable number of pars to printf
                       instead of fixed number with variable number of null strings.

(See /host/bluemoon/usr2/idllib/contrib/groupk/printfs.pro)


PRINT_FILE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        PRINT_FILE

 PURPOSE:
        Spawns a print command to print a file.

 CATEGORY:
        I/O.

 CALLING SEQUENCE:

        PRINT_FILE, File

 INPUTS:
        File:     Name of the file you want to print.

 OPTIONAL INPUT KEYWORDS:

        PRINTER:  String defining the printer device name, (e.g. 'ek_ps').
                  [Default=GETENV('PRINTER')]

        SILENT:        Set this keyword if you do not want any informational
                  messages printed to the display. (0=Default)

 PROCEDURE:
        The spawned print command is:
             lpr -Pprinter file            ;UNIX and Windows
             print/queue=printer file      ;VMS

 EXAMPLE:

        SET_PLOT,'PS'
        DEVICE,FILENAME='/tmp/junk.ps'
        PLOT,indgen(100),TITLE='This is a test'
        DEVICE,/CLOSE
        PRINT_FILE,'/tmp/junk.ps'

 MODIFICATION HISTORY:
        Written by:    Han Wen, May 1995.
        12-JUN-1995    Define default PRINTER environment variable.
        07-AUG-1996    Eliminate call to VERSION()

(See /host/bluemoon/usr2/idllib/contrib/groupk/print_file.pro)


RAN0

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        RAN0

 PURPOSE:
        The RAN0 function returns one or more uniformly-
        distributed, floating-point, pseudo-random numbers in the
        range 0 LE Y < 1.0.

        The random number generator is taken from: "Numerical Recipes in C"
        2nd Edition.  It is the "minimal" random number generator of
        Park and Miller (with the MASK removed) and is IDENTICAL to the
        IDL RANDOMU function.

 CATEGORY:
        Math.

 CALLING SEQUENCE:

        Result = RAN0(Seed [, D1, ..., Dn])

 INPUTS:
         Seed:    A named variable containing the seed value for
                  random number generation. Seed is updated by RAN0
                  once for each random number generated. The initial
                  value of Seed should be set to different values in
                  order to obtain different random sequences. If Seed
                  is undefined, it is derived from the system clock.

 OPTIONAL INPUTS:
        Di:       The dimensions of the result. The dimension
                  parameters can be any scalar expression. Up to eight
                  dimensions can be specified. If no dimensions are
                  specified, RAN0 returns a scalar result

 OUTPUTS:
        This function returns uniform random deviates between 0.0 and 1.0
        (exclusive of the endpoint values) with array dimensions given
        by the input parameters, D1, ..., Dn.

 RESTRICTIONS:
        Currently only available on the AIX platform.

 PROCEDURE:
        This function uses CALL_EXTERNAL to call an external sharable
        C object (ran0_.lib).  This was done because coding the routine
        entirely in IDL would resulted in an unacceptably slow algorithm
        due to unavoidable for loops.

 MODIFICATION HISTORY:
        Written by:    Han Wen, March 1996.

(See /host/bluemoon/usr2/idllib/contrib/groupk/ran0.pro)


RAN1

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        RAN1

 PURPOSE:
        The RAN1 function returns one or more uniformly-
        distributed, floating-point, pseudo-random numbers in the
        range 0 LE Y < 1.0.

        The random number generator is taken from: "Numerical Recipes in C"
        2nd Edition.  It is the "minimal" random number generator of
        Park and Miller with Bays-Durham shuffle and added safeguards.
        Call with Seed a NEGATIVE OR UNDEFINED NUMBER TO INITIALIZE;
        thereafter, do not alter Seed between successive deviates in a sequence.

 CATEGORY:
        Math.

 CALLING SEQUENCE:

        Result = RAN1(Seed [, D1, ..., Dn])

 INPUTS:
         Seed:    A named variable containing the seed value for
                  random number generation. Seed is updated by RAN1
                  once for each random number generated. The initial
                  value of Seed should be set to different NEGATIVE values in
                  order to obtain different random sequences. If Seed
                  is undefined, it is derived from the system clock and
                  is treated as an initial value.

 OPTIONAL INPUTS:
        Di:       The dimensions of the result. The dimension
                  parameters can be any scalar expression. Up to eight
                  dimensions can be specified. If no dimensions are
                  specified, RAN1 returns a scalar result

 OUTPUTS:
        This function returns uniform random deviates between 0.0 and 1.0
        (exclusive of the endpoint values) with array dimensions given
        by the input parameters, D1, ..., Dn.

 RESTRICTIONS:
        Currently only available on the AIX platform.

 PROCEDURE:
        This function uses CALL_EXTERNAL to call an external sharable
        C object (ran1_.lib).  This was done because coding the routine
        entirely in IDL would resulted in an unacceptably slow algorithm
        due to unavoidable for loops.

 MODIFICATION HISTORY:
        Written by:    Han Wen, March 1996.

(See /host/bluemoon/usr2/idllib/contrib/groupk/ran1.pro)


RAN2

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        RAN2

 PURPOSE:
        The RAN2 function returns one or more uniformly-
        distributed, floating-point, pseudo-random numbers in the
        range 0 LE Y < 1.0.

        The random number generator is taken from: "Numerical Recipes in C"
        2nd Edition.  It is long period (>2 x 10^18) random number
        generator of L'Ecuyer with Bays-Durham shuffle and added safeguards.
        Call with Seed a NEGATIVE OR UNDEFINED NUMBER TO INITIALIZE;
        thereafter, do not alter Seed between successive deviates in a sequence.

 CATEGORY:
        Math.

 CALLING SEQUENCE:

        Result = RAN2(Seed [, D1, ..., Dn])

 INPUTS:
         Seed:    A named variable containing the seed value for
                  random number generation. Seed is updated by RAN2
                  once for each random number generated. The initial
                  value of Seed should be set to different NEGATIVE values in
                  order to obtain different random sequences. If Seed
                  is undefined, it is derived from the system clock and
                  is treated as an initial value.

 OPTIONAL INPUTS:
        Di:       The dimensions of the result. The dimension
                  parameters can be any scalar expression. Up to eight
                  dimensions can be specified. If no dimensions are
                  specified, RAN2 returns a scalar result

 OUTPUTS:
        This function returns uniform random deviates between 0.0 and 1.0
        (exclusive of the endpoint values) with array dimensions given
        by the input parameters, D1, ..., Dn.

 RESTRICTIONS:
        Currently only available on the AIX platform.

 PROCEDURE:
        This function uses CALL_EXTERNAL to call an external sharable
        C object (ran2_.lib).  This was done because coding the routine
        entirely in IDL would resulted in an unacceptably slow algorithm
        due to unavoidable for loops.

 MODIFICATION HISTORY:
        Written by:    Han Wen, March 1996.

(See /host/bluemoon/usr2/idllib/contrib/groupk/ran2.pro)


READCTI

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        READCTI

 PURPOSE:

        This routine opens and reads in a Concatenated Time Interval
        (CTI) file into the structure variable, cat.

 CATEGORY:
        HEAO HBR.

 CALLING SEQUENCE:

        READCTI, Name, Cat

 INPUTS:
        Name:     Name of the CTI file, including the path.

 OUTPUTS:
        Cat:      Structure variable holding all the information read in
                  from the CTI file.  Its tags are defined as follows:

                  Name :    Name associated with this HBR data file, SSS_TT_FF.
                            SSS=NRL sequence number, TT=NRL tape number,
                            FF=NRL file number on the tape.
                  Target:   Name of the celestial target that the HBR data
                            is taken from.
                  IDL:      Structure holding miscellaneous IDL info:

                            Routine:  Name of the IDL procedure that created
                                      the CTI file, 'CTIFMT.PRO'
                            Date:     Date/time of CTI creation, SYSTIME().
                            Version:  IDL version, !VERSION.
                            File:     Filename of the PTI file, including path.

                  HEAO:     Structure holding miscellaneous HEAO satellite and
                            A-1 electronics info:

                            Date:     Date/time of HBR data acquisition.
                            Rev:      Revolution number of the HEAO satellite
                                      during the HBR data acquisition.
                            mode:     Various HEAO A-1 electronics modes:

                                      mode(0):  Which modules selected for the
                                                random encoder -> HBR data:
                                                3  - modules 1-4
                                                7  - module 7
                                      mode(1):  Mode of the NRZ data:
                                                5  - 5 msec
                                                320- 320 msec
                                      mode(2):  Mode of the HEAO satellite:
                                                0  - scanning/spinning
                                                1  - pointing

                  MJFH:     Major frame headers* created by HBRFMT,
                            intarr(512,nMJFH)
                  MNFH:     Minor frame headers* created by HBRFMT,
                            intarr(16,nMNFH)
                  nMJFH:    Number of major frame headers in the PTI file.
                  nMNFH:    Number of minor frame headers in the PTI file.
                  nNRZ:     Number of NRZ block in the PTI file.
                  nPTI:     Number of time intervals in the CTI file.
                  nbad:     Number of time regions with BAD minor frames.
                  nAPE:     Number of Adjacent Photon Events (APE) found
                            in each MJF, intarr(nMJFH).
                  MJFs:     Major frame numbers, lonarr(nMJFH).
                  GDV:      Overall Global Data Validity flag (0=Ok, NO
                            HBRSYNC errors found in entire data file).
                  NRZ:      Normal 6.4 kbps telemetry data (NRZ),
                            intarr(128, nNRZ).
                  PTI:      Corrected photon time intervals, lonarr(nPTI).
                  ts:       Corresponding photon time relative to the
                            beginning of the minor frame containing the
                            first photon, lonarr(nPTI+1).
                  tbad:     The beginning and end of time regions where
                            one or more HBRSYNC error were detected,
                            lonarr(2,nbad). The times are relative to the
                            beginning of the MNF containing the 1st photon.

        *For a complete description of the headers, see DEF_HBRH.PRO.

 RESTRICTIONS:

        The def_hbrh.pro routine must be previously compiled.

 COMMON BLOCKS:
        DEF_HBRH: Holds all the MJF and MNF PTI pointers, (see def_hbrh.pro).

 MODIFICATION HISTORY:
        Written by:    Han Wen, October 1995.

(See /host/bluemoon/usr2/idllib/contrib/groupk/readcti.pro)


READPTI

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        READPTI

 PURPOSE:
        This routine reads in the next MJF block of Photon Time Interval (PTI)
        file and supplies it to the USER in a structure variable.

 CATEGORY:
        HEAO HBR.

 CALLING SEQUENCE:

        READPTI, LU, Block

 INPUTS:

        LU:       Logical unit associated with the current PTI file.

 OUTPUTS:

        Block:    Structure variable holding the next MJF block of PTI data.
                  The tags are defined as follows:

                  MJFH:     An array holding the MJF header, intarr(512).
                  MNFH:     An array holding the MNF header for each MNF
                            present in this MJF block, intarr(16,nMNFH*).
                  NRZ:      An array holding the NRZ data**, intarr(128,nMNF*).
                  PTI:      An array holding all the photon time intervals** in
                            7.8125 usec bins in this MJF block, lonarr(ndt).
                            (E.g. A value of 1 means that two photons occurred
                            within adjacent 7.8125 usec bins.)

        * (see PROCEDURE below for definitions).
        **(see PROCEDURE below for caveats).

 OUTPUT KEYWORD PARAMETERS:

        ERROR:    Error status code:
                       0,   Success.
                       1,   End of File.
                       2,   Could not find MJF marker.
                       3,   Cound not find MNF marker.
                  !error,   I/O error.

 COMMON BLOCKS:
        DEF_HBRH: Holds all the MJF and MNF PTI pointers, (see def_hbrh.pro).

 PROCEDURE:
        * There are several HBR data files where there are one or more missing
        MNFs.  For each contiguous section of missing MNFs (e.g. missing
        MNFs = [23,24,25]) one MNFH header is written out.  No PTI or NRZ data
        is associated with this header.  Therefore,

        nMISS                         , Number of missing MNFs in this MJF.
        nsect                         , Number of contiguous section(s) of
                                        missing MNFs, (e.g. missing MNFs =
                                        [23,24,25, 100] => nMISS_sec = 2)
        nMNFH = 128 - nMISS + nsect   , Number of actual MNF headers written out
        nMNF  = 128 - nMISS           , Number of MNFs present (i.e. NOT missing)
                                        in the MJF of data.

        ** If there are NO photons in a MJF then NRZ = PTI = -1.  This can
        happen if an entire MJF is missing or if NO counts are actually detected
        in a MJF.

 MODIFICATION HISTORY:
        Written by:    Han Wen, August 1995.
        31-AUG-1995    Let PTI=-nMNFw if no photons in entire MJF.
        28-SEP-1995    Added negative numbers due to overflow comments; check
                       for PTIs > 32767 across adjacent MNFs.
        29-SEP-1995    Eliminated any negative PTIs due to overflows or
                       missing MNFs by converting the PTI array output to a
                       long integer array.
        30-SEP-1995    Eliminated non-existent NRZ data from Block.NRZ due
                       to one or more missing MNFs.

(See /host/bluemoon/usr2/idllib/contrib/groupk/readpti.pro)


READ_MJF

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        READ_MJF

 PURPOSE:

       This function reads in a major frame of HEAO A-1 data from a data file
       and returns as a keyword a structure containing all the data.

 CATEGORY:
       I/O

 CALLING SEQUENCE:

    Result = READ_MJF( Unit [, PICKMJF=pickmjf, FORMAT=Format, DATA=data] )

 INPUTS:
         Unit:    Logical unit associated with the data file.

 INPUT KEYWORD PARAMETERS:

       PICKMJF:   The major frame number associated with the major frame
             to be returned. Reads the file until it reaches this major frame
             or the end-of-file.

        FORMAT:   String describing the format of the data file. (See DEF_MJF.)

 OUTPUTS:
       This function returns the end of file status for the current
       file begin read.

 OUTPUT KEYWORD PARAMETERS:

         DATA:    A structure containing all of the data of the major frame
             read from file.  (See DEF_MJF for definition.)

 RESTRICTIONS:

       The data structure, MJFstruc must be defined prior to calling
       this routine using the DEF_MJF routine. The data file must be
       in the proper IDL format as defined by the FMT_SRCDATA program.

 EXAMPLE:
       Let's create some arrays and read in the first major frame of a data file with
       data from the Crab pulsar at 320 ms mode.

       openr,unit,'crab.idl',/GET_LUN
       S   = DEF_MJF( Unit )

       ISS = READ_MJF( Unit, DATA=Data )

       print, data.mjf, data.mode, data.module, data.t77i, data.t77f
       print, data.raz, data.dez,  data.ray,    data.dey,  data.nsrc

 MODIFICATION HISTORY:
        Written by:  H.C. Wen, April, 1994.
        22-APR-1994: Moved the parsing of the header into a separate
                     function called PARSE_HEADER. I also created a simple
                     function to return the major frame length in number
                     of bins for a given timing mode, READ_MJF_LEN.
        26-APR-1994: Changed the required outputs to OPTIONAL keywords.
        08-MAY-1994: Simplified reading in of data by using FORTRAN-like
                     format statements; READELE, PARSE_HEADER, PARSE_SOURCE
                     and PARSE_DATA are now obsolete. Keywords no longer
                     need to be initialized to a non-zero value to be filled.
        09-MAY-1994: Added the GETMJF keyword to read file until desired
                     major frame has been reached.
        15-MAY-1994: Zero all output keyword parameters if end of file has been reached.
        26-JUN-1994: Formerly, READ_MJF. Changed keyword outputs to keyword structure.
                     Changed the GETMJF keyword to PICKMJF.
        01-AUG-1994: Data structure defined in DEF_MJF
        25-AUG-1994: Added the DIRS format, divided different formats into CASE
                     statements to improve readability at a cost of redundancy.
        15-NOV-1994: Added the ASPECTS format.
        05-JAN-1994: Small bugfix read bin number I5 instead of I4 for cases
                     when > 9999, e.g. sequential 5ms major frams, > 8192.

(See /host/bluemoon/usr2/idllib/contrib/groupk/read_mjf.pro)


REGRESS2

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        REGRESS2

 PURPOSE:
        Multiple linear regression fit.
        Fit the function:
        Y(i) = A(0)*X(0,i) + A(1)*X(1,i) + ... +
             A(Nterms-1)*X(Nterms-1,i)

 CATEGORY:
        G2 - Correlation and regression analysis.

 CALLING SEQUENCE:
        Result = REGRESS(X, Y, W [, YFIT, SIGMA, FTEST, R, RMUL, CHISQ])

 INPUTS:
        X:   array of independent variable data.  X must
             be dimensioned (Nterms, Npoints) where there are Nterms
             coefficients to be found (independent variables) and
             Npoints of samples.

        Y:   vector of dependent variable points, must have Npoints
             elements.

        W:   vector of weights for each equation, must be a Npoints
             elements vector.  For instrumental weighting
             w(i) = 1/standard_deviation(Y(i)), for statistical
             weighting w(i) = 1./Y(i).   For no weighting set w(i)=1,
             and also set the RELATIVE_WEIGHT keyword.

 OUTPUTS:
        Function result = coefficients = vector of
        Nterms elements.  Returned as a column vector.

 OPTIONAL OUTPUT PARAMETERS:
        Yfit:     array of calculated values of Y, Npoints elements.

        Sigma:    Vector of standard deviations for coefficients.

        Ftest:    value of F for test of fit.

        Rmul:     multiple linear correlation coefficient.

        R:        Vector of linear correlation coefficient.

        Chisq:    Reduced chi squared.

 KEYWORDS:
RELATIVE_WEIGHT: if this keyword is non-zero, the input weights
             (W vector) are assumed to be relative values, and not based
             on known uncertainties in the Y vector.    This is the case for
             no weighting W(*) = 1.

 PROCEDURE:
        Adapted from the program REGRES, Page 172, Bevington, Data Reduction
        and Error Analysis for the Physical Sciences, 1969.

 MODIFICATION HISTORY:
        Written, DMS, RSI, September, 1982.
        Added RELATIVE_WEIGHT keyword, W. Landsman, August 1991
        29-AUG-1994:   H.C. Wen - Used simpler, clearer algorithm to determine
                       fit coefficients. The constant term, A0 is now just one
                       of the X(iterms,*) vectors, enabling the algorithm to
                       now return the sigma associated with this constant term.
                       I also made a special provision for the case when
                       Nterm = 1; namely, "inverting" a 1x1 matrix, i.e. scalar.
        26-MAR-1996:   Added the DOUBLE and CHECK keywords to the call to DETERM.
        02-APR-1996:   Test matrix singularity using second argument in INVERT
                       instead of call to DETERM.

(See /host/bluemoon/usr2/idllib/contrib/groupk/regress2.pro)


SCANPHI

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        SCANPHI

 PURPOSE:
        Finds the scan longitude or PHI corresponding the a response
        function value, assuming that the scan latitude = 0 by inverting
        the collimator response function.

 CATEGORY:
        HEAO.

 CALLING SEQUENCE:

        Result = SCANPHI( Trns )

 INPUTS:
        Trns:     The peak value of the response function.

 OPTIONAL INPUT KEYWORD PARAMETERS:

        DEGREES:  Return the scan longitude in DEGREES, (default=RADIANS).

 OUTPUTS:
        Returns the scan longitude in RADIANS unless the DEGREES keyword
        is set, corresponding to the peak of the Response Function
        at scan latitude = 0.

 MODIFICATION HISTORY:
        Written by:    Han Wen, June 1994.

(See /host/bluemoon/usr2/idllib/contrib/groupk/scanphi.pro)


SCANTHT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        SCANTHT

 PURPOSE:
        Finds the scan latitude or THETA corresponding the a response
        function value, assuming that the scan longitude = 0 by inverting
        the collimator response function.

 CATEGORY:
        HEAO.

 CALLING SEQUENCE:

        Result = SCANTHT( Trns )

 INPUTS:
        Trns:     The peak value of the response function.

 OPTIONAL INPUT KEYWORD PARAMETERS:

        DEGREES:  Return the scan latitude in DEGREES, (default=RADIANS).

 OUTPUTS:
        Returns the scan latitude in RADIANS unless the DEGREES keyword
        is set, corresponding to the peak of the Response Function
        at scan longitude = 0.

 MODIFICATION HISTORY:
        Written by:    Han Wen, June 1994.

(See /host/bluemoon/usr2/idllib/contrib/groupk/scantht.pro)


SEPANGLE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        SEPANGLE

 PURPOSE:
        This function calculates the separation angle in RADIANS from a source
        direction as specified by their RA and DEC.

 CATEGORY:
        Trigonometry.

 CALLING SEQUENCE:
        Result = SEPANGLE( RAs, DECs, RAc, DECc )

 INPUTS:
          RAs:    Right ascension of the source in radians, [float].

         DECs:    Declination of the source in radians, [float].

          RAc:    Right ascension of the second direction in radians.
             This may be either a scalar, [float] or a vector, [float(nbin)].

         DECc:    Declination of the second direction in radians.
             This may be either a scalar, [float] or a vector, [float(nbin)].

 OUTPUTS:
        The separation angle is returned in radians, [float] or [float(nbin)].


 MODIFICATION HISTORY:
        Written by:    Han Wen, June 1994.
        22-JUN-1994:   Vectorized routine to accept vector input arguments
                       for the "collimator" aspects, RAc and DECc.

(See /host/bluemoon/usr2/idllib/contrib/groupk/sepangle.pro)


SETSYB

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        SETSYB
 PURPOSE:
        Set SYSTEM B parameters.

 CALLING SEQUENCE:
        SETSYB, AI, BI, AO, BO

 INPUTS:
        AI - Longitude of Z-axis in RADIANS, scalar or vector.
        BI - Latitude of Z-axis in RADIANS
        AO - Longitude of X-axis in RADIANS
        BO - Latitude of X-axis in RADIANS

 OUTPUTS:
        Sets the SYSTEM B data common.

 REVISION HISTORY:
        Adapted from Fortran by Daryl Yentis NRL
        22-JUN-1994:   H.C. Wen, adapted into IDL routine.
        15-AUG-1995    Comment bugfix: removed extraneous ;+ and ;-.

(See /host/bluemoon/usr2/idllib/contrib/groupk/setsyb.pro)


SFIT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
   SFIT

 PURPOSE:
   This function determines a polynomial fit to a surface.

 CATEGORY:
   Curve and surface fitting.

 CALLING SEQUENCE:
   Result = SFIT(Data, Degree)

 INPUTS:
   Data:     The two-dimensional array of data to fit. The sizes of
        the dimensions may be unequal.

   Degree:   The maximum degree of fit (in one dimension).

 OUTPUT:
   This function returns a fitted array.

 OUTPUT KEYWORDS:
   Kx:  The array of coefficients for a polynomial function
        of x and y to fit data.
        This parameter is returned as a (Degree+1) by (Degree+1)
        element array.

 PROCEDURE:
   Fit a 2D array Z as a polynomial function of x and y.
   The function fitted is:
       F(x,y) = Sum over i and j of kx(j,i) * x^i * y^j
   where kx is returned as a keyword.

 MODIFICATION HISTORY:
   July, 1993, DMS          Initial creation

(See /host/bluemoon/usr2/idllib/contrib/groupk/sfit2.pro)


SFITCUSP

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
   SFITCUSP

 PURPOSE:
   This function determines a "cusp" polynomial weighted fit to a surface.

 CATEGORY:
   Curve and surface fitting.

 CALLING SEQUENCE:
   Result = SFITCUSP( Degree, X, Y, Z, W)

 INPUTS:

   Degree:   The maximum degree of fit (in one dimension), [integer].

      X,Y:   The x- and y-coordinates for each data point, [double(npt)].

        Z:   The surface value for each data point, [double(npt)].

        W:   The weight associated with each data point, [double(npt)].
         For poisson statistics use 1/sigma2 = 1/Z.

 INPUT KEYWORDS:

 DEADTIME:   Set this keyword to include a dead time correction in the fit.

 OUTPUT:
   This function returns a fitted array, [double(npt)].

 OUTPUT KEYWORDS:
    COEFF:   The array of coefficients for a cusp-polynomial function
         of x and y to fit data.
         This parameter is returned as a (Degree+1)^2 element [double] array.

      ERR:   The error matrix of dimension (Degree+1)^2 x (Degree+1)^2
         containing the variances and covariances of the fitted coefficients.

 PROCEDURE:
   Fit a 1D array Z as a polynomial function of x and y.
   The function fitted is:
       F(x,y) = Sum over i and j of coeff(i*(degree+1)+j) * abs( x^i * y^j )
   where coeff is returned as a keyword.

   The deadtime correction is of the form
       D(z)   = - coeff * cts^2
   where coeff = (deadtime)/(timing mode=(320 or 5 ms)
   WARNING: This functional form for the deadtime correction is only an


 MODIFICATION HISTORY:
   July, 1994               H.C. Wen
   07-SEP-1994              Added the DEADTIME keyword.

(See /host/bluemoon/usr2/idllib/contrib/groupk/sfitcusp.pro)


SIGN

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        SIGN

 PURPOSE:
        Mimics the intrinsic FORTRAN function, SIGN.

 CATEGORY:
        Math.

 CALLING SEQUENCE:

        Result = SIGN( A [, B ] )

 OUTPUTS:
        If ONE parameter is specified then

        returns -1 if A < 0, +1 if A > 0.

        If TWO parameters are specified then

        returns A if B >= 0 or -A if B<0

 MODIFICATION HISTORY:
        Written by:    Han Wen, August 1994.
        8-DEC-1994:    Accepts A, B as vectors.
        16-JUN-1995:   Bugfix: if A is a scalar, return a scalar
                       instead of a 1-element vector.

(See /host/bluemoon/usr2/idllib/contrib/groupk/sign.pro)


STRINSERT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        STRINSERT

 PURPOSE:
        The STRINSERT procedure inserts the contents of one string into
        another WITHOUT overwriting any existing characters.  The source
        string, Source is inserted into the destination string,
        Destination between the given positions, Position-1 and Position.
        The length of the destination string is increased by the length
        of the source string, Source. If the insertion position extends
        beyond the length of Destination, then Source is appended to the
        end of Destination.

 CATEGORY:
        String Processing.

 CALLING SEQUENCE:

        STRINSERT, Destination, Source [, Position]

 INPUTS:
        Destination:   The named string variable into which Source
                  is inserted.  Destination must be a named variable of
                  type string.  If it is an array, Source is inserted
                  into every element of the array.

        Source:   A scalar string to be inserted into Destination.
                  If this argument is not a string, it is converted
                  using IDL's default formatting rules.

 OPTIONAL INPUTS:

        Position: The character position before which the insertion
                  is begun.  If Position is omitted, the insertion
                  begins before the first character (character
                  position 0).  If Position is less than zero, zero
                  is used for the initial position.

 EXAMPLE:

        If the variable A contains the string "IBM is fun", the
        substring "'s OS/2 Warp' can be inserted after "IBM"
        by entering:

        STRINSERT, A, '''s OS/2 Warp', 3

 MODIFICATION HISTORY:
        Written by:    Han Wen, June 1995.

(See /host/bluemoon/usr2/idllib/contrib/groupk/strinsert.pro)


STRLETTER

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        STRLETTER

 PURPOSE:

        The STRLETTER function returns a copy of Strings with all
        non-alphabetical characters completely removed.

 CATEGORY:
        String Processing.

 CALLING SEQUENCE:

        Result = STRLETTER( Strings )

 INPUTS:
        Strings:  The string or array of strings to be processed.

 EXAMPLE:
        Create a string variable S and S2 by entering:

        S = 'This is a string with !@#$% in it.'
        S2= ['So what','Big !@#%%ing Deal.']

        Now print S and S2 with all the non-alphabetical
        characters removed by entering:

        PRINT, STRLETTER(S)
        PRINT, STRLETTER(S2)

        IDL prints:

        Thisisastringwithinit
        Sowhat BigDeal

 MODIFICATION HISTORY:
        Written by:    Han Wen, June 1995.

(See /host/bluemoon/usr2/idllib/contrib/groupk/strletter.pro)


STRPAD

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        STRPAD

 PURPOSE:
        This function returns the source string padded with leading
        and/or trailing white-space characters.

 CATEGORY:
        STRLIB.

 CALLING SEQUENCE:

        Result = STRPAD( Source, Length [, Pos] )

 INPUTS:
        Source:   A string or number you want padded with white-space
                  characters.

        Length:   The total length of the returned padded string.

 OPTIONAL INPUTS:

        Pos:      Position of the Source string within the returned
                  padded string. [0=Default]

 OUTPUTS:
        The source parameter is returned as a string with leading
        and/or trailing white-space characters.

 RESTRICTIONS:
        The Length and Pos parameters must be in the range [0-255].

 EXAMPLE:
        Let's say you want 'bob' to have a length of 10 characters
        with spaces padded after 'bob':

        bob10 = STRPAD( 'bob', 10 )

        Or if you want 'bob' to be at the end:

        bobend= STRPAD( 'bob', 10, 7 )

 MODIFICATION HISTORY:
        Written by:    Han Wen, December 1994.

(See /host/bluemoon/usr2/idllib/contrib/groupk/strpad.pro)


STRPARSE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        STRPARSE

 PURPOSE:

        This function parses a string using the space (' ') token.

 CATEGORY:
        String Processing.

 CALLING SEQUENCE:

        Result = STRPARSE( String )

 INPUTS:
        String:  The string to be parsed.

 EXAMPLE:
        Create a string variable S:

        S = 'This is a string with !@#$% in it.'

        Now parse S by entering:

        ss = STRPARSE(S)
        help,ss
        print,TRANSPOSE(ss)

        IDL prints:

        SS              STRING    = Array(8)
        This
        is
        a
        string
        with
        !@#$%
        in
        it.

 MODIFICATION HISTORY:
        Written by:    Han Wen, May 1996.

(See /host/bluemoon/usr2/idllib/contrib/groupk/strparse.pro)


STRREPLACE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        STRREPLACE

 PURPOSE:
        The STRREPLACE procedure replaces the contents of one string
        with another.  The first occurrence of the search substring, Find
        within the source string, String is replaced by the string,
        Replacement.

 CATEGORY:
        String Processing.

 CALLING SEQUENCE:

        STRREPLACE, String, Find, Replacement

 INPUTS:
        String:   The string to have substring(s) replaced.  If String is
                  an array, Find is replaced by Replacement in the first
                  occurrence of Find of every element of the array.

        Find:     The scalar substring to be replaced. If this argument is
                  not a string, it is converted using IDL's default
                  formatting rules.

        Replacement:   A scalar string to replace the Find substring. If
                  this argument is not a string, it is converted using IDL's
                  default formattting rules.

 EXAMPLE:

        If the variable A contains the string "IBM is fun", the
        substring "IBM" can be replaced with the string "Microsoft"
        by entering:

        STRREPLACE, A, 'IBM', 'Microsoft'

 MODIFICATION HISTORY:
        Written by:    Han Wen, June 1995.

(See /host/bluemoon/usr2/idllib/contrib/groupk/strreplace.pro)


SYSTEM

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        SYSTEM

 PURPOSE:
        This is an alternative to the SPAWN routine.  It is similar in both
        inputs and keywords as SPAWN, except that it returns ONLY after the
        spawned process has been completed.

 CATEGORY:
        I/O.

 CALLING SEQUENCE:

        SYSTEM [, Commands]

 INPUTS:
        Commands: A string or ARRAY of strings of DOS commands..

 OPTIONAL INPUT KEYWORD PARAMETERS:

        DT:  The time interval in SECONDS to wait for before checking whether
             the spawned process is complete, (Number of Commands=Default).

        TIMEOUT:  The maximum time to wait in SECONDS for the specified DOS
             command(s) to be completed, (inf=Default).

 PROCEDURE:

        A batch file is created containing the specified DOS command(s).
        An additional command is added at the end of this file that deletes
        the batch file.  This serves as "clean up" housekeeping as well as a
        signature that the batch process is complete.  The batch file is then
        executed using the spawn command. This routine returns control to the
        USER when the batch file has been deleted or,  if the TIMEOUT keyword
        is set, when the process time has has exceed the timed out period.

 RESTRICTIONS:

        This routine may be currently used ONLY on Windows or Unix.
        Calls to batch files in Windows must have the CALL batch command
        preceeding the name of the batch file, (e.g. CALL dothis.bat).

 MODIFICATION HISTORY:
        Written by:    Han Wen, July 1995.
        14-JUL-1995    The string(13b), i.e. carriage return characters is to
                       counter a IDL 4.0 bug has writing out text files.
        04-AUG-1995    Put command to delete batch file in the batch file itself.
        14-AUG-1995    Bugfix: Suppress newline (CR-LF) characters for last batch
                       command, 'del batchfile' to prevent "batch file not found"
                       error.
        15-AUG-1995    Eliminated the need for a Signature File (SYSTEM.TXT) by
                       searching instead, for the deletion of the batch file.
        15-AUG-1995    Added ability to run on Unix.
        06-DEC-1995    Eliminated the CALL prefix.
        07-AUG-1996    Use TMPFILE() to generate batch file name, eliminate
                       calls to VERSION().

(See /host/bluemoon/usr2/idllib/contrib/groupk/system.pro)


TAB

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        TAB

 PURPOSE:
        Returns the ASCII tab character.

 CATEGORY:
        Put a category (or categories) here.  For example:
        Widgets.

 CALLING SEQUENCE:

        Result = TAB()


 MODIFICATION HISTORY:
        Written by:    Han Wen, June, 1994.

(See /host/bluemoon/usr2/idllib/contrib/groupk/tab.pro)


TMPFILE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        TMPFILE

 PURPOSE:
        Get the filename and path of a temporary file.

 CATEGORY:
        IO.

 CALLING SEQUENCE:

        Result = TMPFILE( [Prefix, Suffix, Ndigits] )

 OPTIONAL INPUTS:

        Prefix:   The prefix of the filename, ('tmp'=default).

        Suffix:   The suffix of the filename, (''=default).

        Ndigits:  The number of digits to append to the Prefix, (3=default).

 OPTIONAL INPUT KEYWORD PARAMETERS:

        SEED:     The seed used by the random number generator to determine
             the number to append to the Prefix.

 OUTPUTS:
        The file specification returned is:

             tmp_dir+Prefix+NNN+Suffix

        where NNN is a random LONG integer with number of digits = Ndigits.
        This routine also searches the tmp_dir for this filename. If a
        duplicate filename is found, then another random number is chosen.

        tmp_dir is the path to the /tmp directory (see FILEPATH).

        If a Suffix is provided, then a '.' is appended.


 EXAMPLE:
        Let's create a temp filename myNNNN.ps:

             tmp_file = TMPFILE('my','ps',4)

 MODIFICATION HISTORY:
        Written by:    Han Wen, November 1994.
        08-FEB-1995    Fixed minor bug, random integer -> random LONG integer
        12-JUN-1995    Check existence of TMP directory and create it if no
                       such directory exists.
        01-JUL-1995    Use DIR_EXIST to check existence of TMP directory.
        07-AUG-1996    Use TMPPATH (hacked version of FILEPATH) to determine
                       TMP directory.

(See /host/bluemoon/usr2/idllib/contrib/groupk/tmpfile.pro)


TOPDRAW

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        TOPDRAW

 PURPOSE:
        Interprets a TOP DRAWER file and makes plots to the display
        and/or printer output.

 CATEGORY:
        Graphics.

 CALLING SEQUENCE:

        TOPDRAW [, File]

 OPTIONAL INPUTS:
        File:     Name of the TOP DRAWER file.  If this parameter is not
                  specified then the USER will be prompted for a TOP DRAWER
                  file.

 OPTIONAL INPUT KEYWORD PARAMETERS:

        PATH:     String specifying the path to look for TOP DRAWER files.

        PRINT:    Set this keyword to ONLY print one TOP DRAWER file.
                  The TOP DRAWER plot will not be sent to the display.
                  (0=Default).

 COMMON BLOCKS:
        XYOUTS_:  For internal use only.

 RESTRICTIONS:
        You must have the IDL Astronomy Users Library installed.  Three of
        their routines are called: PLOTERR, OPLOTERR and OS_FAMILY.

        Not all TOP DRAWER commands are available.  For the ones that are,
        some of them do not have the full functionality of the original
        commands.  See handout, "Top Drawer for IDL" for further details
        on what commands are available and their restrictions.

 EXAMPLE:
        Create the following simple text file, called example.top:

        1    10
        2    15
        3    32.03
        5    20.3
        6    0.23
        7    1.3
        8    3.5
        10   5
        12   6
        JOIN

        and and the IDL prompt, type:

        TOPDRAW,'example.top'

        You will see a simple xy-plot of the data with a widget menu
        providing the option to print the plot.

 MODIFICATION HISTORY:
        Written by:    Han Wen, May 1996.

(See /host/bluemoon/usr2/idllib/contrib/groupk/topdraw.pro)


WHEREGION

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        WHEREGION

 PURPOSE:
        This function returns an array of indices corresponding to the
        array elements that lie within a region marked interactively
        by the USER.

 CATEGORY:
        Graphics.

 CALLING SEQUENCE:

        Result = WHEREGION( [X,] Y [,Count] )

 INPUTS:
        Y:        1-D array.

 OPTIONAL INPUTS:
        X:        1-D array of same dimension as Y.

 OPTIONAL INPUT KEYWORD PARAMETERS:

        HELP:     Set this keyword to display a instruction window on how
                  to interactively position the rectangle on the plot.
                  (0=Default)

        Any KEYWORDS provided will be directly passed to the PLOT routine.
        Thus, any of PLOT's graphics keywords may be used.

 OUTPUTS:
        Returns an array of indices pointing to the array elements that
        lie within the USER specified region. (Similar to the WHERE function.)

 OPTIONAL OUTPUTS:

        Count:    A named variable that, on exit, is set to the number of
                  array elements that lie within the USER specified region.
                  This value is returned as a longword integer.

 EXAMPLE:
        ;Define an array of times
        t = findgen(100)

        ;Now select region between 0 and 50 by clicking in the
        ;appropriate plotting region.
        here = WHEREGION( t )

 MODIFICATION HISTORY:
        Written by:    Han Wen, February 1995.
        17-JUN-1995    Rewritten to use MRK_RECT and to do multiple selections.
                       Used _EXTRA keyword to pass all graphics keywords to PLOT.
        31-OCT-1995    Added the Count output variable.
        10-SEP-1996    Allow USER-defined XRANGE and YRANGE keywords, added HELP
                       keyword

(See /host/bluemoon/usr2/idllib/contrib/groupk/wheregion.pro)


WIDGET_POSITION

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        WIDGET_POSITION

 PURPOSE:
        Realizes a widget hierachy and displays the top-level base
        widget at the center or corner of the display.

 CATEGORY:
        Widgets.

 CALLING SEQUENCE:

        WIDGET_POSITION, Widget_ID

 INPUTS:
        Widget_ID:     The widget ID of the widget to be manipulated.

 OPTIONAL INPUT KEYWORDS:

        RIGHT:    Display widget in the right corner of the display.

        LEFT:     Display widget in the left corner of the display (DEFAULT).

        BOTTOM:   Display widget in the bottom corner of the display.

        TOP:      Display widget in the top corner of the display (DEFAULT).

        CENTER:   Display widget in the center of the display.

        RANDOM:   Display widget randomly in the display.

        MAP:      Set this keyword to 1 to display positioned widget (DEFAULT),
                  set to 0 to HIDE the positioned widget.

 OUTPUTS:
        Displays the widget centered in or at the corner of
        the display device.

 COMMON BLOCKS:
        WIDGET_POSITION:    For internal use only.  Holds seed for randomizer.

 PROCEDURE:
        Replaces WIDGET_CONTROL, Widget_ID, /REALIZE

 MODIFICATION HISTORY:
        Written by:    Han Wen, December 1994.
        3-MAY-1995     Added the RANDOM keyword

(See /host/bluemoon/usr2/idllib/contrib/groupk/widget_position.pro)


WINOPEN

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        WINOPEN

 PURPOSE:
        This function returns the additional keywords needed to calls to
        the OPEN procedure in IDL for Windows, version 4.0.1 and later.

 CATEGORY:
        I/O.

 CALLING SEQUENCE:

        Result = WINOPEN(TEXT=Text, BINARY=Binary)

 OPTIONAL INPUT KEYWORD PARAMETERS:

        TEXT:     Set this keyword to specify that the file should be opened
                  as a text file, (0=Default).

        BINARY:   Set this keyword to specify that the file should be opened
                  as a binary file, (0=Default).

 OUTPUTS:
        If you are running IDL for Windows, version 4.0.1 and later,
        this function returns an anonymous structure that may be used in
        conjunction with the _EXTRA keyword in the OPEN procedure to properly
        open files.  If you are running IDL with an earlier version or a
        different platform, or if neither keywords are set, then an undefined
        variable is returned.

 RESTRICTIONS:
        This routine ONLY needs to be used with calling the OPEN procedure
        with IDL for Windows, version 4.0.1 and later.

 EXAMPLE:
        To open a binary file, do:

        OPENR, lu1, 'bob', /GET_LUN, _EXTRA=WINOPEN(/BINARY)
        OPENW, lu2, 'joe', /GET_LUN, _EXTRA=WINOPEN(/BINARY)

        or to open a text file, do:

        OPENR, lu1, 'bob', /GET_LUN, _EXTRA=WINOPEN(/TEXT)
        OPENW, lu2, 'joe', /GET_LUN, _EXTRA=WINOPEN(/TEXT)


 MODIFICATION HISTORY:
        Written by:    Han Wen, October 1995.

(See /host/bluemoon/usr2/idllib/contrib/groupk/winopen.pro)


WSHOW_ACTIVE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        WSHOW_ACTIVE

 PURPOSE:

        This function exposes or hides the current window if its window
        index matches the input argument.

 CATEGORY:
        Widgets.

 CALLING SEQUENCE:

        Result = WSHOW_ACTIVE, Window_index [, Show]

 INPUTS:
        Window_index:  The window index of the window you would
                  like to expose or hide.

 OPTIONAL INPUTS:
        Show:     Set Show to 0 to hide the window. Omit this
                  argument or set it to 1 to expose the window.

 OPTIONAL INPUT KEYWORD PARAMETERS:
        ICONIC:   Set this keyword to iconify the window. Set
                  ICONIC to 0 to de-iconify the window.

 OUTPUTS:
        This function returns a 1 if the window index of the current
        window matches the Window_index parameter and a 0 if it does
        not.

 PROCEDURE:
        This routine was created to offset an annoying side-effect of
        creating or destroying IDL widgets.  Namely, any existing windows
        are usually hidden behind the IDL Main window.  You can use WSHOW
        to expose these windows, but what if they no longer exist? Namely,
        what if the USER has already closed the window?  Applying WSHOW
        to a non-existing window will generate an error.  This routine
        checks the current windows existence by comparing the !D.WINDOW
        system variable with the Window_index parameter and then does a
        WSHOW if the two window indices agree.

 MODIFICATION HISTORY:
        Written by:    Han Wen, January 1995.

(See /host/bluemoon/usr2/idllib/contrib/groupk/wshow_active.pro)


XBUTTON

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        XBUTTON

 PURPOSE:
        Query the USER via a column or row of widget button(s).

 CATEGORY:
        Widgets.

 CALLING SEQUENCE:

        Result = XBUTTON( Button [, Value] )

 INPUTS:
        Button:   An array of strings containing the text of each button.

 OPTIONAL INPUTS:
        Value:    The result returned for each button; this can be an array
                  of integers, floats, strings, etc. If this parameter
                  is not specified then an integer index is returned when
                  the USER clicks a button starting from 0 for the leftmost
                  or topmost button, incrementing by one for each button to
                  the right or lower.

 KEYWORD PARAMETERS:

        TITLE:    A string containing the title of the widget window,
                  (''=Default)

        ROW:      Set this keyword to form a "row" of buttons (Default).

        COLUMN:   Set this keyword to form a "column" of buttons.

        RIGHT:    Display widget in the right corner of the display.

        LEFT:     Display widget in the left corner of the display (DEFAULT).

        BOTTOM:   Display widget in the bottom corner of the display.

        TOP:      Display widget in the top corner of the display (DEFAULT).

        CENTER:   Display widget in the center of the display.

        GROUP:    The widget ID of an existing widget that serves as
                  "group leader" for this message widget.

 OUTPUTS:
        This function returns a value specified by the Value input array
        or an integer index.

 COMMON BLOCKS:
        XB_COM:   For intenal use only.

 EXAMPLE:

        ;Try this one:
        buttons = ['Hey','This','Is','Really','Cool!']
        values  = ['H','T','I','R','C' ]

        ;The following should generate a COLUMN of 5 buttons
        rp   = xbutton( buttons, /COLUMN )

        ;If you click on the 'Cool' button, then the value of rp = 4

        ;The following should generate a ROW of 5 buttons
        rp   = xbuttons( buttons, values, /ROW )

        ;If you click on the 'Cool' button again, the value of rp='C'
        ;as defined by the values array.

 MODIFICATION HISTORY:
        Written by:    Han Wen, December 1994.
        22-JAN-1995    Added /INPUT_FOCUS keyword so that the button
                       widget window is highlighted.
        28-JAN-1995    Added the GROUP keyword.

(See /host/bluemoon/usr2/idllib/contrib/groupk/xbutton.pro)


XHELPMSG

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        XHELPMSG

 PURPOSE:
        This routine displays help messages in a widget format
        similar to the IDL Help facility.

 CATEGORY:
        Widgets.

 CALLING SEQUENCE:

        XHELPMSG, Topics, Descriptions, Nlines

 INPUTS:
        Topics:   An array of strings describing the topics of the help
                  message, strarr( ntopics ).

        Descriptions:  An array of strings describing each of the topics.

        Nlines:   The number of "lines" or string array elements of
                  description for each topic, fltarr( ntopics ).

 OPTIONAL INPUT KEYWORDS:

        TITLE:    Title of this XHELPMSG widget, ('XHelp Message'=Default)

        YSIZE:    The height of the help widget in number of lines,
                  (20=Default).

        GROUP:    The widget ID of an existing widget that serves as
                  "group leader" for this message widget.

 OUTPUTS:
        Displays a help widget similar to the one provided by the IDL help
        facility appears; i.e. two columns: help topics and a description of
        currently highlighted topic.

 COMMON BLOCKS:
        XHELPMSG_COM:  This is for internal use only.

 EXAMPLE:
        ;Here's a simple example:

        Topics=['Joe','Widgeting']
        Descriptions=['Makes a sloppy burger',$
                      'Always inviting others to his restaurant.',$
                      'Can be a real pain in the butt..',$
                      'unless you have cool canned X routines..',$
                      'such as this one!']

        Nlines=[2,3]
        XHELPMSG, Topics, Descriptions, Nlines

 MODIFICATION HISTORY:
        Written by:    Han Wen, December 1994.

(See /host/bluemoon/usr2/idllib/contrib/groupk/xhelpmsg.pro)


XLIST

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        XLIST

 PURPOSE:
        This function returns the value or index of an item from
        a list that the USER interactively selects from.

 CATEGORY:
        Widgets.

 CALLING SEQUENCE:

        Result = XLIST( List )

 INPUTS:
        List:     An array of items of ANY type to choose from.

 OPTIONAL INPUT KEYWORD PARAMETERS:

        VALUE:    Set this keyword to return the value of the item selected,
                  (1=Default).

        INDEX:    Set this keyword to return the index of the item selected,
                  (0=Default).

        HEADER:   An array of strings containing the header that will be
                  placed above the list of items, (''=Default).

        TITLE:    A string containing the title of the widget window,
                  ('Select Item'=Default)

        RIGHT:    Display widget in the right corner of the display.

        LEFT:     Display widget in the left corner of the display.

        BOTTOM:   Display widget in the bottom corner of the display.

        TOP:      Display widget in the top corner of the display.

        CENTER:   Display widget in the center of the display (DEFAULT).

        RANDOM:   Display widget randomly in the display.

        GROUP:    The widget ID of an existing widget that serves as
                  "group leader" for this message widget.

 OUTPUT:

        By default or if the VALUE keyword is set, this function returns the
        value of the item selected, preserving its type.  If the INDEX keyword
        is set, then the array index of this item is returned.

 COMMON BLOCKS:

        XLIST:    For internal use only.

 EXAMPLE:

        list = ['Why is','IBM','so incompetent','in','marketing','OS/2','?']
        str  = XLIST(list)
        ; select 'OS/2'
        print, str
        ; the value should be 'OS/2'

        index= XLIST(list)
        ; select 'OS/2' again
        print,index
        ; the index should be 5

 MODIFICATION HISTORY:
        Written by:    Han Wen, August 1995.
        27-SEP-1995    Improved algorithm to determine width of widget in pixels.

(See /host/bluemoon/usr2/idllib/contrib/groupk/xlist.pro)


XMSG

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        XMSG

 PURPOSE:
        Displays message(s) in a widget window with an optional OK button.

 CATEGORY:
        Widgets.

 CALLING SEQUENCE:

        XMSG, Msgs

 INPUTS:
        Msgs:     An array of message(s) of ANY type to be displayed.

 OPTIONAL KEYWORD INPUTS:

        TITLE:    A string containing the title of the widget window,
                  ('IDL'=Default)

        ALIGN:    Set this keyword to left align each message string,
                  by default, each message string is centered (0=Default).

        RIGHT:    Display widget in the right corner of the display.

        LEFT:     Display widget in the left corner of the display.

        BOTTOM:   Display widget in the bottom corner of the display.

        TOP:      Display widget in the top corner of the display.

        CENTER:   Display widget in the center of the display (DEFAULT).

        RANDOM:   Display widget randomly in the display.

        NOBUTTON: Set this keyword to NOT display an OK button.  If this
                  keyword is set, then control is returned to the USER
                  after this message widget is displayed, (0=Default).

        GROUP:    The widget ID of an existing widget that serves as
                  "group leader" for this message widget.

        MSG_ID:   The widget ID of this XMSG widget.

 MODIFICATION HISTORY:
        Written by:    Han Wen, December 1994.
        09-JAN-1995    Added the NOBUTTON and MSG_ID keywords.
        02-AUG-1995    Added scrollbar if number of messages exceeds 15.
        16-AUG-1995    Input array parameter can be of ANY type instead of
                       only strings.
        27-SEP-1995    Improved algorithm to determine width of widget in pixels.

(See /host/bluemoon/usr2/idllib/contrib/groupk/xmsg.pro)


XOPLOT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        XOPLOT

 PURPOSE:
        This procedure is a "superset" of OPLOT and OPLOTERR with the
        additional feature of allowing the USER to interactively change
        many of its settings "on the fly" (e.g. plotting symbol and
        linestyle) via various widget menus.  It accepts ALL of the
        keywords used by OPLOT and OPLOTERR and some additional keywords
        described below.  The USER may also print the plot directly
        under the File pulldown menu, (it can handle multiple
        plots/window).

 CATEGORY:
        Plotting and Widgets.

 CALLING SEQUENCE:

        XOPLOT, [X,] Y, [DX, [DY]]

 INPUTS:
        Y:        The ordinate data to be plotted. This argument
                  is converted to single-precision floating-point
                  before plotting.

 OPTIONAL INPUTS:

        X:        A vector argument. If X is not specified, Y is
                  plotted as a function of point number (starting at
                  zero). If both arguments are provided, Y is plotted
                  as a function of X.

                  This argument is converted to single-precision
                  floating-point before plotting. Plots created with
                  PLOT are limited to the range and precision of sin-
                  gle-precision floating-point values.

        DX:       A vector of error bar values along the X-axis.

        DY:       A vector of error bar values along the Y-axis.

 OPTIONAL INPUT KEYWORD PARAMETERS:

        All of the keywords accepted by OPLOT and OPLOTERR may be used as
        well as the following additional keywords:

        LANDSCAPE:     Set this keyword to specify that the window the plot
                  is drawn in should be in landscape mode (1=Default).

        PORTRAIT: Set this keyword to specify that the window the plot is
                  drawn in should be in portrait mode (0=Default).

 COMMON BLOCKS:
        XPLOT:    Keep tracks of USER keywords, PostScript file parameters,
                  etc.  For internal use only.

 RESTRICTIONS:
        If you are interested in sending the plots to the printer, do not
        mix usage of XPLOT, PLOT, PLOTERR and XOPLOT, OPLOT, OPLOTERR.  XPLOT
        and XOPLOT cannot keep track of plots made using the PLOT, PLOTERR,
        OPLOT or OPLOTERR routines.

 PROCEDURE:

        Okay, here's a typical situation when it comes to IDL plotting:
        you run PLOT or PLOTERR with various graphic keywords, look at the
        resulting plot and.. oops, need to change the x-axis range..
        change the y-axis title.. etc.  So, you rerun PLOT or PLOTERR with
        the modified keywords and repeat this cycle of plotting until
        you've gotten your plot right.  Once you have that done you then have to
        REPEAT all of this song and dance for EACH additional data set you want
        to overplot using OPLOT or OPLOTERR.  Okay, so how about printing this
        thing?  Well, then you have to change the output device using SET_PLOT,
        then repeat typing in all the PLOT and/or PLOTERR and/or OPLOT and/or
        OPLOTERR commands with all the hard-fought graphic keywords.
        Sound familiar?

        XOPLOT has been designed to make this process more "interactive"
        and less tedious.  You may use XOPLOT just as you would OPLOT or
        OPLOTERR, specifying on the command line all of the graphic
        keywords accepted by OPLOT or OPLOTERR.  Now, however, along with
        the usual plot comes a nice widget menu.  From this widget menu,
        you may modify most of the available OPLOT and OPLOTERR settings,
        right "there".  You may additionally SAVE this plot to a
        PostScript file and send it to the printer, right "there" from the
        widget menu.

        If you want to overplot data on an existing plot, there are four
        simple steps to follow: 1) Run XOPLOT on you data; 2) Fiddle with the
        settings INTERACTIVELY until you've gotten it right; 3) Select
        Save under the File pulldown menu to save the plot to a PostScript
        file; and 4) Select either Close or Print under the File pulldown
        menu.  Either commands will close the PostScript file.  Print will
        additionally spawn a print command on this PostScript file.


 EXAMPLE:
        x    = findgen(100)
        y    = sin(x/20)
        y2   = cos(x/15)

        XPLOT,x,y,TITLE='Title',XTITLE='X-Axis',YTITLE='Y-Axis'
        XOPLOT,x,y2

 MODIFICATION HISTORY:
        Written by:    Han Wen, January 1995.
        01-FEB-1995    Added the NO_MENU keyword. (1.01)
        02-FEB-1995    Save printer output system variables to XPLOT
                       common. (1.20)
                       Small bug fix, initialize CLOSE (1.21)
                       Small bug fix, reseting printer output system variables
                       back to their defaults when exiting (1.22)
        08-FEB-1995    Added the NOCLIP keyword and HISTOGRAM plotting
                       symbol. (1.30)
        08-FEB-1995    Verified GRIDLINE option w/ XPLOT will work with XOPLOT
        29-APR-1995    >Cosmetic changes; Got rid of Current in Display Current Settings,
                       etc.  Put it in originally to force window wide enough to read
                       the window title.
                       >Deleting Plot Window will NOT delete PS TMP file if Print Plot
                       Window has been previously selected.
        03-MAY-1995    Completely rewrote the GUI by utilizing WIDED.  Added more
                       flexibility by adding the File pulldown menu. (3.0)
        07-MAY-1995    Make sure USER supplied two or more points to plot for
                       X,Y overplots. (3.01)
        09-MAY-1995    Check only first 3 characters of !VERSION.OS. (3.02)
        16-MAY-1995    Bugfix: Made sure !P.MULTI(0) stays constant. (3.03)
        06-JUN-1995    Check to see if input arrays are defined. (3.04)
        12-JUN-1995    Replaced XOPLOT_ERASE -> tvrd(), tv. (3.05)
        14-JUN-1995    Plot updated after each USER modification. (3.1)
        20-JUN-1995    Bugfix: Don't mess with !P.MULTI(0). (3.11)
        21-JUN-1995    Bugfix: Preserve any changes to the color indices when leaving
                       XOplot. (3.12)
        29-SEP-1995    Set DEVICE keyword, DECOMPOSED=0 for systems with > 256
                       colors. (3.14)
        07-AUG-1996    Eliminate calls to VERSION(). (3.15)

(See /host/bluemoon/usr2/idllib/contrib/groupk/xoplot.pro)


XPLOT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        XPLOT

 PURPOSE:
        This procedure is a "superset" of PLOT and PLOTERR with the
        additional feature of allowing the USER to interactively change
        many of its settings "on the fly" (e.g. x-axis range, plotting
        symbol, etc.) via various widget menus.  It accepts ALL of the
        keywords used by PLOT and PLOTERR and some additional keywords
        described below.  The USER may also print the plot directly
        under the File pulldown menu, (it can handle multiple
        plots/window).

 CATEGORY:
        Plotting and Widgets.

 CALLING SEQUENCE:

        XPLOT, [X,] Y, [DX, [DY]]

 INPUTS:
        Y:        The ordinate data to be plotted. This argument
                  is converted to single-precision floating-point
                  before plotting.

 OPTIONAL INPUTS:

        X:        A vector argument. If X is not specified, Y is
                  plotted as a function of point number (starting at
                  zero). If both arguments are provided, Y is plotted
                  as a function of X.

                  This argument is converted to single-precision
                  floating-point before plotting. Plots created with
                  PLOT are limited to the range and precision of sin-
                  gle-precision floating-point values.

        DX:       A vector of error bar values along the X-axis.

        DY:       A vector of error bar values along the Y-axis.

 OPTIONAL INPUT KEYWORD PARAMETERS:

        All of the keywords accepted by PLOT and PLOTERR may be used as
        well as the following additional keywords:

        LANDSCAPE:     Set this keyword to specify that the window the plot
                  is drawn in should be in landscape mode (1=Default).

        PORTRAIT: Set this keyword to specify that the window the plot is
                  drawn in should be in portrait mode (0=Default).

        WINDOW:   Window number of the window to create and draw the plot
                  in.  If the window already exists, then any existing
                  plots in the window will be erased (0=Default).

        RESET:    Resets the XPLOT common block.

 COMMON BLOCKS:
        XPLOT:    Keep tracks of USER keywords, PostScript file parameters,
                  etc.  For internal use only.

 RESTRICTIONS:
        If you are interested in sending the plots to the printer, do not
        mix usage of XPLOT, PLOT, PLOTERR and XOPLOT, OPLOT, OPLOTERR.  XPLOT
        and XOPLOT cannot keep track of plots made using the PLOT, PLOTERR,
        OPLOT or OPLOTERR routines.

 PROCEDURE:

        Okay, here's a typical situation when it comes to IDL plotting:
        you run PLOT or PLOTERR with various graphic keywords, look at the
        resulting plot and.. oops, need to change the x-axis range..
        change the y-axis title.. etc.  So, you rerun PLOT or PLOTERR with
        the modified keywords and repeat this cycle of plotting until
        you've gotten your plot right.  Okay, so how about printing this
        thing?  Well, then you have to change the output device using
        SET_PLOT, then repeat typing in all the PLOT and PLOTERR commands
        with all the hard-fought graphic keywords.  Sound familiar?

        XPLOT has been designed to make this process more "interactive"
        and less tedious.  You may use XPLOT just as you would PLOT or
        PLOTERR, specifying on the command line all of the graphic
        keywords accepted by PLOT or PLOTERR.  Now, however, along with
        the usual plot comes a nice widget menu.  From this widget menu,
        you may modify most of the available PLOT and PLOTERR settings,
        right "there".  You may additionally SAVE this plot to a
        PostScript file and send it to the printer, right "there" from the
        widget menu.

        Okay, so how do I do this?  For single plots/page, there are four
        simple steps. 1) Run XPLOT on you data; 2) Fiddle with the
        settings INTERACTIVELY until you've gotten it right; 3) Select
        Save under the File pulldown menu to save the plot to a PostScript
        file; and 4) Select either Close or Print under the File pulldown
        menu.  Either commands will close the PostScript file.  Print will
        additionally spawn a print command on this PostScript file.

        For multiple plots/page, repeat steps 1) - 3) for each plot.  For
        each plot, except the last, select Exit under the File pulldown
        menu when you're done with the plot.  For the last plot, instead
        of selecting Exit, select either Close or Print in order to close
        the PostScript file.  Once the PostScript file is closed, you can
        no longer make any modifications to it from within XPLOT.

        Finally, if you want to overplot data on an existing plot, first
        use XPLOT to create the first plot following steps 1) - 3)
        described above and then Exit XPLOT.  Use XOPLOT for each data set
        you want to overplot, following setps 1) - 3) again (using XOPLOT
        instead of XPLOT, of course) and then Exit XOPLOT except for the
        last data set.  For the last one, select Close or Print from the
        File pulldown menu to close the PostScript File.


 EXAMPLE:
        x    = findgen(100)
        y    = sin(x/20)

        XPLOT,x,y,TITLE='Title',XTITLE='X-Axis',YTITLE='Y-Axis'

 MODIFICATION HISTORY:
        Written by:    Han Wen, January 1995.
        01-FEB-1995    Added the NO_MENU keyword. (1.01)
        02-FEB-1995    Save printer output system variables to XPLOT
                       common. (1.20)
        02-FEB-1995    Small bug fix, initialize CLOSE (1.21)
                       Small bug fix, reseting printer output system variables
                       back to their defaults when exiting (1.22)
        08-FEB-1995    Added the NOCLIP keyword and HISTOGRAM plotting
                       symbol. (1.30)
                       Added GRIDLINES option. (1.40)
                       Bugfix: Improperly displayed gridlines settings (1.41)
        21-FEB-1995    Bugfix: Did not reset current window if !D.WINDOW ne
                       -1, (1.42)
        29-APR-1995    >Cosmetic changes; Got rid of Current in Display Current Settings,
                       etc.  Put it in originally to force window wide enough to read
                       the window title.
                       >Deleting Plot Window will NOT delete PS TMP file if Print Plot
                       Window has been previously selected.
                       >Added Output Settings and Encapsulate PostScript options.
        03-MAY-1995    Completely rewrote the GUI by utilizing WIDED.  Added more
                       flexibility by adding the File pulldown menu. (3.0)
        06-MAY-1995    Rearranged Settings widget layout.  Don't have to press Enter
                       when modifying titles, limits or font sizes. (3.1)
        07-MAY-1995    Make sure USER supplied two or more points to plot. (3.11)
        09-MAY-1995    Check only first 3 characters of !VERSION.OS. (3.12)
        15-MAY-1995    Reset IDL system variables if RESET keyword is set. (3.13)
        17-MAY-1995    Bugfix: Make sure x,y scale is linear upon entering Xplot,
                       unless USER specifies XTYPE,YTYPE keywords. (3.14)
        23-MAY-1995    Remembers path of current or previously saved PS file and
                       warn USER if overwriting existing PS file. (3.15)
        25-MAY-1995    Bugfix: Preserve any changes to !X.type or !Y.type in case
                       of subsequent XOplot calls. (3.16)
        06-JUN-1995    Bugfix: Changed max slider value from 255 -> !D.N_COLORS. (3.17)
        06-JUN-1995    Check to see if input arrays are defined. (3.18)
        08-JUN-1995    Check to see if ANY data in USER-selected range. (3.19)
        12-JUN-1995    Replaced XPLOT_ERASE -> tvrd(), tv. (3.20)
        14-JUN-1995    Added Select Region button, plot updated after each
                       USER modification. (3.3)
        19-JUN-1995    Bugfix: Don't check for valid range if !X.range=0. (3.31)
        20-JUN-1995    Bugfix: Save/restore existing plot settings if closing an
                       old print file. (3.32)
        21-JUN-1995    Bugfix: Preserve any changes to the color indices when leaving
                       XOplot. (3.33)
        29-SEP-1995    Set DEVICE keyword, DECOMPOSED=0 for systems with > 256
                       colors. (3.34)
        07-AUG-1996    Eliminate calls to VERSION(). (3.35)

(See /host/bluemoon/usr2/idllib/contrib/groupk/xplot.pro)


XQUERY

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        XQUERY

 PURPOSE:
        Reply to a list of questions via a widget window.

 CATEGORY:
        Widgets.

 CALLING SEQUENCE:

        Result = XQUERY( Question )

 INPUTS:
        Question: A string or array of strings describing the question(s)
                  to be asked to the USER.

 OPTIONAL INPUTS:

        Default:  An array of numbers or strings containing the default
                  answers for each of the corresponding questions.  If this
                  parameter is not provided each answer is defaulted to a
                  NULL string.

 OPTIONAL INPUT KEYWORDS:

        TITLE:    Title of this XQUERY widget, ('XQUERY'=Default)

        GROUP:    The widget ID of an existing widget that serves as
                  "group leader" for this message widget.

        OK:       Set this keyword to set the button text to 'OK' for
                  the button which destroys this widget. ('Done'=Default)

        XSIZE:    An array of numbers giving the width of each "answer"
                  widget in characters, fltarr( N_ELEMENTS( Question ) )

        RIGHT:    Display widget in the right corner of the display.

        LEFT:     Display widget in the left corner of the display.

        BOTTOM:   Display widget in the bottom corner of the display.

        TOP:      Display widget in the top corner of the display.

        CENTER:   Display widget in the center of the display (DEFAULT).

 OUTPUTS:
        This function returns an array or scalar containing the answers to each
        corresponding questions.  If the Default input parameter is provided
        then its TYPE is preserved in the returned array/scalar.  Otherwise,
        the returned array/scalar will be of STRING type.

 RESTRICTIONS:

        Complex numbers or arrays are treated as strings.

 COMMON BLOCKS:
        XQUERY_COM:  This is for internal use only.

 EXAMPLE:

        ; Try this one

        result = XQUERY(['Is this Cool? ','Or What? '], $
                        DEFAULT=['Yes..','Indeed.'])

        ; If you only press DONE then result will have the following values:
        ; result(0) = 'Yes..'
        ; result(1) = 'Indeed.'

 MODIFICATION HISTORY:
        Written by:    Han Wen, December 1994.
        09-JAN-1995    Small bugfix: returned null strarr when pressing
                       Cancel -> return DEFAULT strarr if keyword is defined.
        29-JAN-1995    Added the RIGHT,LEFT,TOP,BOTTOM,CENTER keywords.
        19-JUL-1995    If Question is a scalar, return a scalar instead of a
                       1-element array.
        24-JUL-1995    Changed the functionality of the Cancel button to be
                       consistent with other widget routines; namely, returning
                       a -1.  Added a new Undo button to replace the former
                       functionality of Cancel, except that the widget is now
                       reset to its defaults instead of being destroyed.  Also
                       moved the DEFAULTS keyword to the second input parameter
                       to be consistent with XBUTTON. (However, DEFAULTS keyword
                       will still be available to maintain backward compatibility.)
        17-AUG-1995    Preserve type defined by the Default input parameter.
        18-AUG-1995    Bugfix: Removed wset, windex; unnecessary.

(See /host/bluemoon/usr2/idllib/contrib/groupk/xquery.pro)


XSURFACE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        XSURFACE

 PURPOSE:
        This routine provides a graphical interface to the SURFACE and
        SHADE_SURFACE commands.  Different controls are provided to change
        the viewing angle and other plot parameters.  The command used to
        generate the resulting surface plot is shown in a text window.

 CATEGORY:
        Widgets.

 CALLING SEQUENCE:
        XSURFACE, Data [, X, Y ]

 INPUT PARAMETERS:
        Data:     The two-dimensional array to display as a wire-mesh or
             shaded surface.

 OPTIONAL INPUT PARAMETERS:

           X:  A vector or two-dimensional array specifying the
               X coordinates of the grid. If this argument is a
               vector, each element of X specifies the X coordinate
               for a column of Z (e.g., X(0) specifies the X coor-
               dinate for Z(0,*)). If X is a two-dimensional array,
               each element of X specifies the X coordinate of the
               corresponding point in Z (Xij specifies the X coordi-
               nate for Zij).

               This argument is converted to single-precision
               floating-point before plotting.

           Y:  A vector or two-dimensional array specifying the
               Y coordinates of the grid. If this argument is a
               vector, each element of Y specifies the Y coordinate
               for a row of Z (e.g., Y(0) specifies the Y coordi-
               nate for Z(*,0)). If Y is a two-dimensional array,
               each element of Y specifies the Y coordinate of the
               corresponding point in Z (Yij specifies the Y coordi-
               nate for Zij).

               This argument is converted to single-precision
               floating-point before plotting.

 OPTIONAL INPUT KEYWORD PARAMETERS:

          AX:  This keyword specifies the angle of rotation,
               about the X axis, in degrees towards the viewer.
               This keyword is effective only if !P.T3D is not set.
               If !P.T3D is set, the three-dimensional to two-
               dimensional transformation used by SURFACE is taken
               from the 4 by 4 array !P.T.

               The surface represented by the two-dimensional
               array is first rotated, AZ (see below) degrees about
               the Z axis, then by AX degrees about the X axis,
               tilting the surface towards the viewer (AX > 0), or
               away from the viewer.

               The AX and AZ keyword parameters default to +30
               degrees if omitted and !P.T3D is 0.

               The three-dimensional to two-dimensional trans-
               formation represented by AX and AZ, can be saved in
               !P.T by including the SAVE keyword.

           AZ: This keyword specifies the counterclockwise
               angle of rotation about the Z axis. This keyword is
               effective only if !P.T3D is not set. The order of
               rotation is AZ first, then AX.

           BOTTOM:    The color index used to draw the bottom surface.
               If not specified, the bottom is drawn with the same
               color as the top.

           HORIZONTAL:    A keyword flag which if set causes SURFACE to
               only draw lines across the plot perpendicular to the
               line of sight. The default is for SURFACE to draw
               both across the plot and from front to back.

           LEGO:    Set this keyword to produce "Lego" style plots.
               Each data value is rendered as a box covering the XY
               extent of the cell and with a height proportional to
               the Z value.

           LOWER_ONLY:    Set this keyword to draw only the lower surface
               of the object. By default, both surfaces are drawn.

           MAX_VALUE:    The largest data value to be plotted. Data
               larger than this value are treated as missing data
               and are not plotted.

           SAVE:   Set this keyword to save the 3D to 2D transfor-
               mation matrix established by SURFACE in the system
               variable field !P.T. Use this keyword when combining
               the output of SURFACE with additional output from
               other routines in the same plot.

               When used with AXIS, the SAVE keyword parameter
               saves the scaling parameters established by the call
               in the appropriate axis system variable, !X, !Y, or
               !Z. This causes subsequent overplots to be scaled to
               the new axis.

               Example

               To display a two-dimensional array using SUR-
               FACE, and to then superimpose contours over the sur-
               face (this example assumes that !P.T3D is zero, its
               default value.), enter the following commands:

               SURFACE, Z, /SAVE	Make a surface plot and save the
               transformation.

               CONTOUR, Z, /NOERASE, /T3D	Make contours, don't erase, use the
               3D to 2D transform placed in !P.T
               by SURFACE.

               To display a surface and to then display a flat
               contour plot, registered above the surface:

               SURFACE, Z, /SAVE	Make the surface, save transform.

               CONTOUR, Z, /NOERASE, /T3D, ZVALUE=1.0
               Now display a flat contour plot, at
               the maximum Z value (normalized
               coordinates). You can display the
               contour plot below the surface with
               by using a ZVALUE of 0.0.

           SHADES:    This keyword allows user-specified coloring of
               the mesh surfaces. Set this keyword to an array that
               specifies the color index of the lines emanating
               from each data point toward the top and right.

           SKIRT:    This keyword represents a Z-value at which to
               draw a skirt around the array. The Z value is
               expressed in data units. The default is no skirt.

               If the skirt is drawn, each point on the four
               edges of the surface is connected to a point on the
               skirt which has the given Z value, and the same X
               and Y values as the edge point. In addition, each
               point on the skirt is connected to its neighbor.

           UPPER_ONLY:    Set this keyword to draw only the upper surface
               of the object. By default, both surfaces are drawn.

           XTYPE:    Set this keyword to specify a logarithmic X
               axis.

           YTYPE:    Set this keyword to specify a logarithmic Y
               axis.

           ZAXIS:    This keyword specifies the placement of the Z
               axis for the SURFACE plot.

               By default, SURFACE draws the Z axis at the
               upper left corner of the axis box. To suppress the Z
               axis, use ZAXIS=-1 in the call. The position of the
               Z axis is determined from the value of ZAXIS as fol-
               lows: 1 = lower right, 2 = lower left, 3 = upper
               left, and 4 = upper right.

   Graphics Keywords Accepted

       See Chapter 2, Graphics Keywords and System
       Variables, for the description of graphics and plot-
       ting keywords not listed above. BACKGROUND CHANNEL
       CHARSIZE CHARTHICK CLIP COLOR DATA DEVICE FONT LINE-
       STYLE NOCLIP NODATA NOERASE NORMAL POSITION SUBTITLE
       T3D THICK TICKLEN TITLE XCHARSIZE XMARGIN XMINOR
       XRANGE XSTYLE XTHICK XTICKLEN XTICKNAME XTICKS
       XTICKV XTICK_GET XTITLE YCHARSIZE YMARGIN YMINOR
       YRANGE YSTYLE YTHICK YTICKLEN YTICKNAME YTICKS
       YTICKV YTICK_GET YTITLE ZCHARSIZE ZMARGIN ZMINOR
       ZRANGE ZSTYLE ZTHICK ZTICKLEN ZTICKNAME ZTICKS
       ZTICKV ZTICK_GET ZTITLE ZVALUE.

 KEYWORD PARAMETERS:
        GROUP:    The widget ID of the widget that calls XSURFACE.  When this
             keyword is specified, the death of the caller results in the
             death of XSURFACE.

 SIDE EFFECTS:
        The XMANAGER is initiated if it is not already running.

 RESTRICTIONS:
        XSURFACE does not accept any of the keywords that the IDL command
        SURFACE does.

 PROCEDURE:
        Create and register the widget with the XMANAGER and then exit.

 MODIFICATION HISTORY:
        Created from a template written by: Steve Richards, January, 1991.

(See /host/bluemoon/usr2/idllib/contrib/groupk/xsurface.pro)


XXYOUTS

[Previous Routine] [Next Routine] [List of Routines]

 NAME:
        XXYOUTS

 PURPOSE:
        This procedure is a "superset" of OPLOT and OPLOTERR with the
        addtional feature of allowing the USER to interactively change
        many of its settings "on the fly" (e.g. line style, plotting
        symbol, etc.) via various widget menus.  It accepts ALL of the
        keywords used by OPLOT and OPLOTERR and some additional keywords
        described below.  The USER may also print the plot directly
        from the main widget menu, (it can handle multiple plots/window).

 CATEGORY:
        Plotting and Widgets.

 CALLING SEQUENCE:

        XXYOUTS, [X,] Y, [DX, [DY]]

 INPUTS:
        Y:        The ordinate data to be plotted. This argument
                  is converted to single-precision floating-point
                  before plotting.

 OPTIONAL INPUTS:

        X:        A vector argument. If X is not specified, Y is
                  plotted as a function of point number (starting at
                  zero). If both arguments are provided, Y is plotted
                  as a function of X.

                  This argument is converted to single-precision
                  floating-point before plotting. Plots created with
                  PLOT are limited to the range and precision of sin-
                  gle-precision floating-point values.

        DX:       A vector of error bar values along the X-axis.

        DY:       A vector of error bar values along the Y-axis.

 OPTIONAL INPUT KEYWORD PARAMETERS:

        All of the keywords accepted by PLOT and PLOTERR may be used as
        well as the following additional keywords:

        LANDSCAPE:     Set this keyword to specify that the window the plot
                  is drawn in should be in landscape mode (1=Default).

        PORTRAIT: Set this keyword to specify that the window the plot is
                  drawn in should be in portrait mode (0=Default).

        WINDOW:   Window number of the window to create and draw the plot
                  in.  If the window already exists, then any existing
                  plots in the window will be erased (0=Default).

        NO_MENU:  Set this keyword to suppress the appearance of a widget
                  menu after the plot has been made (0=Default).

        NO_HARDCOPY:   Normally, when you press the Print Plot Window button,
                  the printer output is sent directly to the printer. Set this
                  keyword to suppress sending the printer output to the
                  printer. (0=Default)

 OPTIONAL OUTPUTS:
        The USER may select to send the plot to the printer if the NO_HARDCOPY
        keyword is not set. A temporary printer output file is created for
        each plot created.  This file is deleted if the USER selects the
        Delete Plot Window button and kept if the Quit button is selected.

 RESTRICTIONS:
        You MUST call XPLOT before calling this routine.  (Do NOT try to
        compile this routine before running XPLOT)

        If you are interested in sending the plots to the printer, do not
        mix usage of XPLOT, PLOT, PLOTERR and XXYOUTS, OPLOT, OPLOTERR.  XPLOT
        and XXYOUTS cannot keep track of plots made using the PLOT, PLOTERR,
        OPLOT or OPLOTERR routines.

 PROCEDURE:
        Use this routine EXACTLY as you would use OPLOT or OPLOTERR.  This
        routine handles printing multiple plots by creating a temporary
        printer output file everytime the USER selects the Quit button.
        If you do NOT want this file deleted, then select the Quit button
        to exit this routine.  Selecting Delete Plot Window will DELETE
        any temporary printer output file created.

 EXAMPLE:
        x    = findgen(100)
        y    = sin(x/20)
        y2   = cos(x/10)

        XPLOT,x,y,TITLE='Title',XTITLE='X-Axis',YTITLE='Y-Axis'
        XXYOUTS,x,y2

 MODIFICATION HISTORY:
        Written by:    Han Wen, January 1995.
        01-FEB-1995    Added the NO_MENU keyword. (1.01)
        02-FEB-1995    Save printer output system variables to XPLOT
                       common. (1.20)

ro XXYOUTS, X, Y, String, TEXT_OBJECT=Text_object, $

(See /host/bluemoon/usr2/idllib/contrib/groupk/xxyouts.pro)


YNCANCEL

[Previous Routine] [List of Routines]
 NAME:
        YNCANCEL

 PURPOSE:
        This function prompts USER with a widget window with Yes, No and
        Cancel buttons. Use this function to let the USER decide upon some
        subsequent action that you are going to take (described by the Msgs
        parameter) once this widget is destroyed.

 CATEGORY:
        Widgets.

 CALLING SEQUENCE:

        Result = YNCANCEL( [Msgs] )

 INPUTS:
        Msgs:     A string or array of strings containing message(s)
             to be displayed.

 OPTIONAL KEYWORD INPUTS:

        TITLE:    A string containing the title of the widget window,
                  ('IDL'=Default)

        ALIGN:    Set this keyword to left align each message string,
                  by default, each message string is centered (0=Default).

        RIGHT:    Display widget in the right corner of the display.

        LEFT:     Display widget in the left corner of the display.

        BOTTOM:   Display widget in the bottom corner of the display.

        TOP:      Display widget in the top corner of the display.

        CENTER:   Display widget in the center of the display (DEFAULT).

        GROUP:    The widget ID of an existing widget that serves as
                  "group leader" for this message widget.

 OUTPUTS:
        This function will return:
             1 if the Yes button is selected.
             0 if the No  button is selected.
            -1 if the Cancel button is selected.

 COMMON BLOCK:
        YNCANCEL: For internal use only.

 MODIFICATION HISTORY:
        Written by:    Han Wen, January 1994.
        02-AUG-1995    Added scrollbar if number of messages exceeds 15.
        27-SEP-1995    Improved algorithm to determine width of widget in pixels.

(See /host/bluemoon/usr2/idllib/contrib/groupk/yncancel.pro)