Local IDL Routines

This page was created by a MODIFICATION of the IDL library routine mk_html_help. For more information on this routine, refer to this page or type:

     doc_library, 'mk_html_help'

at the IDL command line prompt.

List Last updated: Fri Feb 13 14:09:17 2009.

You may download a g-zipped tar file of all these files.


Routines by Category

[Alphabetical Listing of Routines]


Routine Descriptions


Category: 2-D Plotting

[List of Routines]


EFITPLUSCAMMDS

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

 PURPOSE:
       Plot  Camera images along with EFIT field 
	lines, and also plot Ip, Pnb, and H-alpha (or another) signal vs. time.

 CATEGORY:
       2-D Plotting, Animation, NSTX, EFIT
 CALLING SEQUENCE:
	IDL> efitpluscammds, shot, timeRame=[time1,time2]
 INPUTS:
       shot = nstx shot number  
	If you want to use diverter camera data, it must be moved manually 
       to linux. Examples are
	at /p/nstxusr2/uppercam/114333 and /p/nstxusr2/divcam/114333.
	A .cih file must also be in each directory for the timing information
 KEYWORD PARAMETERS:
    Keywords:
	timeRame - 2-element array for animation; single value for one frame
		   (in SECONDS)
                  alternately, minMsec and maxMsec may be used.
	animate - if set to 0, will NOT make a movie in an IDL XINTERANIMATE window.
                 if a time range is specified, multiple images will be plotted
		  to the default IDL window.
	maxFrames - max # of frames over time range -- necessary if X-memory 
		    is limited (default is 2000).
	imSmooth - amount to median smooth images (default=0)
	nSmooth - amount to median smooth sigName (default=0)
	sigName - if set, will not show Fast Camera images, but this
		  signal vs. time (defaults to \passivespec::BAYC_DALF_HAIFA)
	sigT1 - starting time of signal vs. time plot. Defaults to timerange[0]
	sigT2 - ending time of signal vs. time plot. Defaults to timerange[1]
	sigTitle - if set, will be displayed above sigName plot,
		   else tries to get label from MDSplus
	EFITversion - EFIT version to use. Defaults to largest available.
	FCimgScale - can multiply by each frames's data to brigten images
 OUTPUTS:
       none

 EXAMPLES:
    for a quick demo that doesn't consume too many resources:
	   animate=1 uses X-interanimate VCR-like controls,
          animate=0 just redraws multiple plots to the same window
	IDL> efitpluscammds, 115431, animate=0, time=[.16,.17]
	IDL> efitpluscammds, 115431, animate=1, nskip=5,time=[.16,.20]
	IDL> efitpluscammds, 115431, time=[.18,.2], sigT1=.18,sigT2=.20, /verbose

    to make a series of .ppm files for use with another 
	IDL> efitpluscammds, 115431, pixmap=1, animate=0, ppmout=1, /verbose

	   To get a postscript frame printed:
	IDL>efitpluscammds,114333,time=0.01,thom=0,sigT1=.005,sigT2=.02,anim=0,/postscript

   if the FC images are too light, you can make them 4 times as bright:
	IDL> efitpluscammds, 112608, FCimgScale=4

   to get an animation with no more than 40 frames between 50 and 317 msec:
	IDL> efitpluscammds, shot, time=[0.05,0.317],max=40
 
 LIMITATIONS:
       MPEG movies created from widget are poor.
	Fast Camera data is expected to be in MDS -- only started April, 2005 
	When DISPLAY=1, all the frames requested are download to your
	X-server's memory. If you run out of this memory, you will see:
	   % WINDOW: Unable to create X windows pixmap (BadAlloc (insufficient resources
                    for operation)).
 NOTES:
 MODIFICATION HISTORY:
	21-Mar-2007 added camsig keyword to get other signal names
	30-Mar-2005 convert from fcdcmovies
	05-Aug-2004 Added two Hiroshima cameras
	23-Jul-04 added ExtendEFITtime keyword to continue animation after efit
	05-May-04 Adapted from EfitMovies for Fast Camera data plus x-y plots
	Original EFIT animation written by Dave Gates

(See src/idl_cvs/efitpluscammds.pro)


EFITPLUSCAM

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

 PURPOSE:
       Plot  Camera images along with EFIT field 
	lines, and also plot Ip, Pnb, and H-alpha (or another) signal vs. time.

 CATEGORY:
       2-D Plotting, Animation, NSTX, EFIT
 CALLING SEQUENCE:

    for a quick demo that doesn't consume too many resources:
	IDL> efitpluscam, 111877, animate=1, nskip=5,time=[.16,.20]

	IDL> efitpluscam, 111877, pixmap=1, animate=0, ppmout=1, /verbose, $
			tmpdisk='/p/nstxusr2/user/tmp/NEW'

	IDL> efitpluscam, 111877, pixmap=1, animate=0, ppmout=1, /verbose, $
			maxframes=5000
	IDL> efitpluscam, 111877, pixmap=1, animate=0, ppmout=1, /verbose, $
			time=[.3,.5], tmpdisk='/p/nstxusr2/tmp'
	IDL> efitpluscam, 111827, time=[.18,.2], sigT1=.18,sigT2=.20, /verbose
	IDL> efitpluscam, 111827, pixmap=1, animate=0, ppmout=1, /verbose

	IDL> efitpluscam, 114333,time=[.008,.012],thom=0, sigT1=.005,sigT2=.020

	   To get a postscript frame printed:
	IDL>efitpluscam,114333,time=0.01,thom=0,sigT1=.005,sigT2=.02,anim=0,/postscript

   if the FC images are too light, you can make them 4 times as bright:
	IDL> efitpluscam, 112608, FCimgScale=4

   to get an animation with no more than 40 frames between 50 and 317 msec:
	IDL> efitpluscam, shot, time=[0.05,0.317],max=40
 
 INPUTS:
       shot = nstx shot number  
	diverter camera data must be moved manually to linux. Examples are
	at /p/nstxusr2/uppercam/114333 and /p/nstxusr2/divcam/114333.
	A .cih file must also be in each directory for the timing information
 KEYWORD PARAMETERS:
    Keywords:
	time - 2-element array for animation; single value for one frame
	animate - if set to 0, will NOT make a movie in an IDL XINTERANIMATE window.
	maxFrames - max # of frames over time range -- necessary if X-memory
	imSmooth - amount to median smooth images (default=3)
		    is limited (default is 200).
	sigName - if set, will not show Fast Camera images, but this
		  signal vs. time (defaults to \passivespec::BAYC_DALF_HAIFA)
	sigT1 - starting time of signal vs. time plot
	sigT2 - ending time of signal vs. time plot
	sigTitle - if set, will be displayed above sigName plot,
		   else tries to get label from MDSplus
 OUTPUTS:
       none

 LIMITATIONS:
       MPEG movies created from widget are poor.
	All Fast Camera data is on VMS, but can be mounted from petrel084 to
	petrel092. Only what has been moved manually 
	is on Unix. 
 NOTES:

   you need to use /save to get Mpeg  quality=100 (but it's not clear there's
	any improvement in the Mpeg.

   to get tiff files from the fastcamera system into the right taurus directory:
	FTP them from the KODAK directory, or one of it's subdirectories, on VMS
 MODIFICATION HISTORY:
	30-Mar-2005 convert from fcdcmovies
	05-Aug-2004 Added two Hiroshima cameras
	23-Jul-04 added ExtendEFITtime keyword to continue animation after efit
	05-May-04 Adapted from EfitMovies for Fast Camera data plus x-y plots
	Original EFIT animation written by Dave Gates

(See src/idl_cvs/efitpluscam.pro)


SHADE_SURFRANGE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       shade_surfrange
 PURPOSE:
       make SHADE_SURF plots with x & y ranges (correctly)
 CATEGORY:
	2-D Plotting
 CALLING SEQUENCE:
        shade_surfrange, f, x, y, XRANGE=xrange, YRANGE=yrange, _EXTRA =_extra
 INPUTS:
       f, x & y are just as for surf      in
 KEYWORD PARAMETERS 
	Input:
	  XRANGE - array containing min x & max x
	  YRANGE - array containing min y & max y
	  ZRANGE - array containing min y & max y
	  _EXTRA - standard idl EXTRA keyworrd
 OUTPUTS:
	none
 EXAMPLE:
	x=findgen(100)
	y=x 
	f=DIST(100)
	_EXTRA = { title: 'My Title', $		; pass any extra SHADE_SURF keywords here
	           xtitle: 'seconds', $
		   ax : 40  }
	shade_surfrange, f, x, y, xrange=[20,40], yrange=[50,70],  _EXTRA =_EXTRA
 COMMON BLOCKS:
 NOTES:
	If your are using color tables with reserved colors at the the top,
	e.g., if you use mk_color, you should first call:
	  IDL> dum=mk_color(n_nonfixed=ncolors)
	  IDL> set_shading, values=[0,ncolors-1]
 MODIFICATION HISTORY:
     09-Jul-02 Handle when yrange or xrange reversed (i.e., first > last)
     17-Aug-01 Handle correctly when !z.range set
     17-Oct-00 Written by Bill Davis

(See src/idl_cvs/shade_surfrange.pro)


SHOW3M

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

 PURPOSE:
	Show a 2D array three ways in a display that combines SURFACE, 
	CONTOUR, and an image (color/gray scale pixels).

 CATEGORY:
	2-D Plotting, Graphics, Image Processing.

 CALLING SEQUENCE:
	SHOW3m, Image [, INTERP = Interp, SSCALE = Sscale]

 INPUTS:
	Image:	The 2-dimensional array to display.

 OPTIONAL INPUTS:
	X = a vector containing the X values of each column of Image.
		If omitted, columns have X values 0, 1, ..., Ncolumns-1.
	Y = a vector containing the Y values of each row of Image.
		If omitted, columns have Y values 0, 1, ..., Nrows-1.
 KEYWORD PARAMETERS:
	INTERP:	Set this keyword to use bilinear interpolation on the pixel 
		display.  This technique is slightly slower, but for small 
		images, it makes a better display.

	SSCALE:	Reduction scale for surface. The default is 1.  If this
		keyword is set to a value other than 1, the array size 
		is reduced by this factor for the surface display.  That is, 
		the number of points used to draw the wire-mesh surface is
		reduced.  If the array dimensions are not an integral multiple
		of SSCALE, the image is reduced to the next smaller multiple.
	E_CONTOUR: a structure containing additional keyword parameters
		that are passed to the CONTOUR procedure.  See the example
		below.
	E_SURFACE: a structure containing additional keyword parameters
		that are passed to the SURFACE procedure.  See the example
		below.
       TITLE: Top plot title
       XTITLE: x-axis title
       YTITLE: y-axis title
       FLOOR: if = 0, will not show color contours on floor
       CHARTHICK;  character thickness on color bar
       DRAWLINES: draw lines to indicate a region of interest
       DRAWBOX : draw box around region of interest
       BOXYMID: y-mid point of box, an line location (default=0.1)
       BOXXMID: x-mid point of box, an line location (default=1)
       BOXWIDTH: width of box (default=0.1)
       BAR: if = 0, will not draw color bar
       C_COLOR:   colors for contours
 OUTPUTS:
	No explicit outputs.

 EXAMPLE:
	IDL> gp, '/u/bdavis/MarthRedi/kineticballooning.txt'

 SIDE EFFECTS:
	A new plot is generated.

 RESTRICTIONS:
	The display gets too "busy" when displaying larger (say 50 by 50),
	images, especially if they are noisy.  It can be helpful to use
	the SSCALE keyword or the SMOOTH and/or REBIN functions to smooth the 
	surface plot.

	You might want to modify the calls to CONTOUR and SURFACE slightly
	to customize the display to your tastes, i.e., with different colors,
	skirts, linestyles, contour levels, etc.

 PROCEDURE:
	First, do a SURFACE with no data to establish the 3D to 2D scaling.
	Then convert the coordinates of the corner pixels of the array to
	2D.  Use POLYWARP to get the warping polynomial to warp the
	2D image into the area underneath the SURFACE plot.  Output the image,
	output the surface (with data) and then output the contour plot at
	the top (z=1).

 EXAMPLES:
	A = BESELJ(SHIFT(DIST(30,20), 15, 10)/2.,0)  ;Array for example
	SHOW3, A		;Show it with default display.
	SHOW3, A, SQRT(FINDGEN(30))  ;Make X axis proportional to sqrt
	SHOW3, A, E_CONTOUR={C_CHARSIZE:2, DONW:1} ;Label CONTOUR lines with
		double size characters, and include downhill tick marks.
	SHOW3, A, E_SURFACE={SKIRT:-1, ZRANGE:[-2,2]}  ;Draw a surface with
		a skirt and scale Z axis from -2 to 2.
 MODIFICATION HISTORY:
	DMS. Jan, 1988.
	Added fudges for PostScript, April, 1988.
	Fixed bug where contour plot was occasionally clipped. Dec, 1990.
	Added optional axis variables, and _EXTRA keywords for CONTOUR,
		and SURFACE.  Jan, 1996.
	DD.  Added code to ignore !ORDER for the TV of the image.  Mar 1997.
       SJL  Fixed bug from scaling with polywarp. July, 1998.
	DD.  Add better support for TrueColor devices.
	     Honor !P.BACKGROUND (rather than assuming black or white
            background).  Sept, 2000.
    	Feb/2005 hacked by Bill Davis for Martha Redi:
	     better scaling of bottom image. Added lines and a square to indicate region.
	     When bottom values are zero, make white (transparent). Add color bar.

(See src/idl_cvs/show3m.pro)


SURFRANGE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       surfrange
 PURPOSE:
       make SURF plots with x & y ranges (correctly)
 CATEGORY:
	2-D Plotting
 CALLING SEQUENCE:
        surfrange, f, x, y, XRANGE=xrange, YRANGE=yrange, _EXTRA =_extra
 INPUTS:
       f, x & y are just as for surf      in
 KEYWORD PARAMETERS 
	Input:
	  XRANGE - array containing min x & max x
	  YRANGE - array containing min y & max y
	  ZRANGE - array containing min y & max y
	  _EXTRA - standard idl EXTRA keyworrd
 OUTPUTS:
	none
 EXAMPLE:
	x=findgen(100)
	y=x 
	f=DIST(100)
	_EXTRA = { title: 'My Title', $		; pass any extra SURF keywords here
	           xtitle: 'seconds', $
		   ax : 40  }
	surfrange, f, x, y, xrange=[20,40], yrange=[50,70],  _EXTRA =_EXTRA
 COMMON BLOCKS:
 NOTES:
	logic is still not perfect. See, e.g., 
	AUSER4:[BDAVIS.TEST.NDD]NDD3D.PRO for a working example of overlaying
	surface plot on a shaded surface plot with ranges set.
 MODIFICATION HISTORY:
     09-Jul-02 Handle when yrange or xrange reversed (i.e., first > last)
     17-Aug-01 Handle correctly when !z.range set
     17-Oct-00 Written by Bill Davis

(See src/idl_cvs/surfrange.pro)


TH_IMAGE_CONT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       TH_IMAGE_CONT
 PURPOSE:
       Plot contours of Images with both contour lines and colors
 CATEGORY:
	2-D Plotting
 USAGE:
******************** HIGH FREQUENCY RADAR DIVISION, SRL **********************
*************************** Ionospheric Effects ******************************
HELP
1 TH_IMAGE_CONT
	Overlays an image and a contour plot and optionally adds a scale bar.
	Based on the IDL USERLIB routine IMAGE_CONT. This routine supersedes 
	the USERLIB one, having far more functionality, yet capable of EXACTLY
	reproducing the effect of IMAGE_CONT. Scale bar appears on the 
	right-hand-side unless /NOBAR is set. NB: the scale bar is
	automatically created by a recursive call to this routine using the
	same colour and image parameters 

 Format:
	In its simplest form (allowing all parameters to default)

    IDL> TH_IMAGE_CONT, IMAGE

	or,

    IDL> TH_IMAGE_CONT, IMAGE, X, Y

	And in its most complex form, specifying ALL parameter

    IDL> TH_IMAGE_CONT, IMAGE, $
		ASPECT=aspect, $
		BADPTS=badpts,$
     		BAR_LABEL_LENGTH=bar_label_length, $
		BAR_RANGE=bar_range, $
		BAR_SEPARATION=bar_separation, $
		BAR_TICKLEN=bar_ticklen, $
		BAR_TICKNAME=bar_tickname, $
		BAR_TICKS=bar_ticks, $
		BAR_TICKV=bar_tickv,$
		BARSZ_CHARS=barsz_chars, $
		BOTTOMCOLOUR=bottomcolour,$
		C_COLORS=c_colors,$
		C_LINESTYLE=c_linestyle, $
		C_THICK=c_thick, $
		CONGRID=congrid, $
		CONT=cont, $
		CRANGE=crange, $
		CT=ct, $
		CUBIC=cubic, $
		DEBUG=debug, $
		EXACT=exact, $
		RAISE_PTITLE=raise_ptitle
		IMAGE_WINDOW=image_window, $
		INTERP=interp,$
		LEVELS=levels,$
		MAX_VALUE=max_value, $
		NLEVELS=nlevels, $
		NOBAR=nobar, $
		NOCONT=nocont, $
		NOERASE=noerase,$
		TOPCOLOUR=topcolour,$
		TSIZE=tsize, $
		WINDOW_SCALE=window_scale, $
		XRANGE=xrange, $
		YRANGE=yrange
 
2	IMAGE
		2-dimensional array to display as an image.

2	/ASPECT
		set to retain image's aspect ratio.  Assumes square
		pixels.  If /WINDOW_SCALE is set, the aspect ratio is retained.

2	BADPTS
		indices into IMAGE data which define the bad points.
		These will not be contoured

2 BAR_LABEL_LENGTH
     the space, in characters (default = 2), for the bar label
2	BAR_RANGE	
	 	set the range limits for the colour scale bar
		(same as CRANGE, defaults to autoscaling if
		 BAR_TICKV not set)

2	BAR_SEPARATION	
		the separation, in characters (default = 2), between the scale
		bar and the image. Note that the |y-ticklength| will be added
		to this value if y-ticklength < 0.
		Both the image and the colour bar need to fit 
		into the space allowed for the plot window, otherwise an
		informative message will be printed and unpredictable results
		may occur for the displayed image 

2	BAR_TICKS
		set the number of tick intervals for the labelling
		of the scale bar 
		(defaults to !z.ticks)

2	BAR_TICKV
		the values to label on the scale bar. If this is set
		then the scale bar will have AT LEAST this range
		(defaults to !z.tickv)

2	BAR_TICKNAME
		the labels to use on the scale bar 
		(defaults to !z.range)

2	BAR_TICKLEN
		the length of the ticks on the scale bar  in fractions of tick
		bar window, (defaults to !z.ticklen)

2	BARSZ_CHARS
		the size of the scale bar in characters (default = 2). 
		Both the image and the colour bar need to fit 
		into the space allowed for the plot window, otherwise an
		informative message will be printed and unpredictable results
		may occur for the displayed image. If the value of this
		keyword is <=0 then no bar will be displayed BUT the scaling
		and window size will be calculated as those a colour bar is to
		be used. This is useful when doing multiple plots per page
		where only some scale bars are not required but you want the
		plots to all be the same size. Set BARSZ_CHARS = -#chars to
		allow room for a bar of #chars size but not to put a scale bar
		on the plot. Then set BARSZ_CHARS = +#chars to plot the bar on
		alongside another plot, to end up with images of the same
		size. Useful in collaboration with the SIDES procedure (which
		will set flags for when the plot is on the Left,Right,Top and
		Bottom of the plot window).


2	BOTTOMCOLOUR
		Set this keyword to the colour index of the desired bottom
		colour (range from 0 to TOPCOLOUR-1).
		Note that the default value for this keyword is 1,
		which allows the colour of the image to
		be independent of the background and axes colours
		(!P.background and !P.color). If the user sets this keyword
		then allowance should be made for these colours as they are
		generally swapped for POSTSCRIPT and X-Window devices

2	/CONGRID 	
		if the image has to be resampled then use the USERLIB CONGRID
		routine 

2	/CONT 	
		only do the contouring (no image)

2	CRANGE	
		set the range limits for the colour scale bar
		(same as BAR_RANGE, defaults to autoscaling if
		 BAR_TICKV not set)

2	CT	
		load a color table (uses LOADCT via MK_COLOR)

2	/CUBIC	
		if the image has to be resampled AND interpolated then use the
		CUBIC interpolation rather than the bi-linear (see INTERP
		Keyword) 

2	/DEBUG	
		write out some inforamtion as it goes


2	/EXACT
 
		When set this will force the contour routine to fit to the
		exact positions relative to the image.
		When data is displayed as an image each datum is expanded out
		to fill a pixel of finite dimensions. The assignment of where
		the "data value" resides within this space is open to debate,
		but is most appropriately (to this author) assigned to the
		geometric centre of the pixel. Most defaults assign this
		position to be at the bottom left-hand corner of the
		pixel. Contour will fit to the 2-d plane assuming that the
		data value is associated with the bottom left-hand corner. To
		reconcile this with the notion of the value being in the
		middle of the pixel the contour call is made with the x/y
		values and ranges for the image adjusted (effectively by half
		a pixel in the x/y directions). This is the EXACT mapping. By
		default, the mapping will be the default contour one.

2	RAISE_PTITLE
		Raise the plot title by this many character units above the
		plot to allow room to put a label on the top x-axis. Default
		is raise by 1 char. If not called then the default y-position
		is 1 char unit above plot (allowing room for xticks, and
		scaled by !P.charsize)

2	IMAGE_WINDOW
		the position of the image window. Can be used to set
		!p.position so you can over-plot the image.
		(Only useful when the scale-bar has been used)

2	/INTERP 
		set to bi-linear interpolate if image is resampled.
		(see also the CUBIC keyword)

2	/NOBAR 
		dont put a scale bar on the right-hand-side

2	/NOCONT
		only do the imaging (no contours)

2	/NOERASE
		dont erase the previous plot
       /NOLOAD
		if set, do not load color table

2	TOPCOLOUR
		Set this keyword to the colour index of the desired bottom
		colour (range from BOTTOMCOLOUR+1 to !D.n_colors-1). Note that
		the default value for this keyword is !D.n_colors-2, which
		allows the colour of the image to be independent of the
		background and axes colours (!P.background and !P.color). If
		the user sets this keyword then allowance should be made for
		these colours as they are generally swapped for POSTSCRIPT and
		X-Window devices 

2	TSIZE	
		size of the plot title (default = 1)
 
2	/WINDOW_SCALE
		set to scale the window size to the image size,
		otherwise the image size is scaled to the window size.
		Ignored when outputting to devices with scalable pixels.

2	XRANGE
		will set the ranges for the x-axes labelling

2	YRANGE
		will set the ranges for the y-axes labelling

2	Contour
		most of the CONTOUR parameters are passed directly

2 Examples
 IDL>   th_image_cont, image

 IDL>	th_image_cont, image, /nocont, /nobar

 IDL>	!p.title = "!17 This is an example of what can be done"
 IDL>	!x.title = "X Title"	& !y.title = "Y Title"	& !z.title = "Z Title"
 IDL>	!x.ticklen = -0.02	& !y.ticklen = -0.02	& !z.ticklen = -0.02
 IDL>	!p.charsize = 1.5
 IDL>	levels = findgen(5)*2
 IDL>	image = findgen(20,20)/40.
 IDL>	th_image_cont, image, crange=[0,10], /follow, level=levels, $
			tsize=1.5*!p.charsize, bar_tickv=levels, c_char=1.5

2 Error_responses
 Returns to the calling procedure on an error

2 Limitations/Assumptions 
	The currently selected display is affected.
	If the device has scalable pixels then the image is written over
	the plot window.
	As with all TV style image displays, the axes range is independent of 
	the image, so it is up to the user the ensure correct labelling of the
	axes.
	NOTE: if the user aborts while this routine is processing then the 
	system variables (in particular !p.position) will have 
	been changed, causing subsequent plots to appear different. Issue the 
	command "resetplt,/all" to reset all the system variables back to the 
	startup state.

	NOTE: if x or y does not have a constant interval, the image will be
		wrong. Instead, use contour, /fill...
2 References 
 	See USERLIB IMAGE_CONT

2 Keywords
	Graphics images contours

2 MODIFICATIONS:
  -------------
  06-Jun-2006 several changes including adding x & ytickformat keywords
  06-Apr-2006 limit max dimension of interpolated postscript plots to 2000 pixels
  14-Mar-2006 added zrange keyword [BD]
  25-Oct-01 Made Contours work when /ASPECT set. Made Contours work when
	     XRANGE or YRANGE set.
  18-Apr-00 Made interpolated image align with data. /EXACT does not give
		  an exact representation. Warn if style=2
  06-Dec-99 Added another pixel to TV image size, so it fills the grid square
  23-Aug-99 Allow Contour, Z, X, Y format. Use MK_COLOR
  07-Jan-98 BD allow more space at the bottom and right-hand side for text
               (keyword BAR_LABEL_LENGTH added)
  07-Aug-97 Bill Davis- v. 2.24
                [1] added _extra call to main CONTOUR and removed
                    it from those making the bar.
 (more modifications in file)

(See src/idl_cvs/th_image_cont.pro)


VECTORSURF

[Previous Routine] [List of Routines]
 NAME:
       vectorsurf

 PURPOSE:
       Shows a fancy way to plot irregulary spaced data from x,y & z vectors.

 CATEGORY:
	2-D Plotting, Example

 CALLING SEQUENCE:
        vectorsurf, x, y, z

 INPUTS:
       tag - MDSplus tag or node name      in

 KEYWORD PARAMETERS 
    Input:
	DRAWXSIZE = drawXsize
	DRAWYSIZE = drawYsize
       BG_COLOR = bg_color

 OUTPUTS:
	none

  EXAMPLE:
     IDL> x=[4,6,1,7,1,8,5,2,4]
     IDL> y=[3,3,1,6,4,5,6,8,1]
     IDL> z=sqrt((x-3)^2+(y-2)^2)+randomn(seed)+2 
     IDL> vectorsurf, x, y, z

  MODIFICATION HISTORY:
       05-Sep-97 Written by Bill Davis
                 from IDL's d_mathstat.pro in the IDL 5.0 release
                 Written by:  DC, RSI,  1995

(See src/idl_cvs/vectorsurf.pro)


Category: Animation

[List of Routines]


ANIM2CINE

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

 PURPOSE:
    Create an mpeg or avi movie from two .cin files from Phantom 7 Cameras.
    The data can be color or monochrome

 CATEGORY:
    animation

 CALLING SEQUENCE:
    anim2cine, CineFile1, CineFile2, outFile=outfile, t1=t1, t2=t2
   or

 INPUTS:
	CineFile1 - cine file
	CineFile2 - 
	 - 
 OPTIONAL KEYWORD PARAMETERS:
	outFile - name of output MPEG file (will default to a nice name), or 
	prefix - what would precede _shot_t1_t2 (in msec) in the output filename
	t1 - start time of animation in seconds
	t2 - end time of animation in seconds
	VIEW - if set, just displays images, and does not make an mpeg
   	ndups - if given means repeat every image 'ndups' times
   	despeckle - if set call despeckle routine (slow, but less "intrusive" 
		    than median)
	nSmooth - number input to median smoothing routine
	topPixels -
	botPixels - 
	charsize - character size for plots. Default=2
	ctb - color table for non-color image 
	label1 - label on plot for CineFile1 (default='Monochrome')
	label2 -  label on plot for CineFile2 (default='Color')
	verbose - if set will print out info as it works
 OUTPUTS: 
	an MPEG file named by outFile keyword

 PROCEDURE:
   will assume Phantom 7 camera is the fastest
 EXAMPLE:

    anim2cine, '/p/nstxusr2/nstxphantom7/NSTX_130389.cin', $
		'/p/nstxusr2/miro/MIRO_130389.cin', $
		t1=0.02, t2=1.5, /verbose                        , /debug

    anim2cine, '/p/nstxusr2/nstxphantom7/NSTX_130387.cin', $
		'/p/nstxusr2/miro/MIRO_130387.cin', $
		t1=0.02, t2=1.4, /verbose                      

    anim2cine, shot=130370, t1=0.05, t2=0.58, /verbose, /view    , /debug

    anim2cine, '/p/nstxusr2/nstxphantom7/NSTX_130388.cin', $
		'/p/nstxusr2/phantom4/NSTX_130388.cin', $
		t1=0, t2=2, ctb=0, /verbose                    , /debug

    anim2cine, shot=130375, /nonGlobal, $
		t1=0, t2=2, ctb=0, /verbose                    , /debug

   mv files to /w/nstx.pppl.gov/htdocs/nstx/Software/Diagnostics/Miro for web viewing at
   http://nstx.pppl.gov/nstx/Software/Diagnostics/Miro/

 MODIFICATION HISTORY:
	12-Nov-2008 mods because cineload now assuming frame 0 is beginning of data
	16-Jul-2008 Use Z-buffer, even when viewing, for smoother displays
	15-Jul-2008 Written by Bill Davis

(See src/idl_cvs/anim2cine.pro)


ANIMXYPLOT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       animxyplot
 PURPOSE:
       Animate X-Y plot of a 2-D array
 CATEGORY:
       Animation
 CALLING SEQUENCE:
       IDL> animxyplot, data2d, x, time [, ....]
 INPUTS:
       data2d - 2 d array (1st dimension like x, 2nd like time)
	x - array for x-axis of x-yplot
	time
 KEYWORD PARAMETERS:
	(can have any keywords used in PLOT command -- will be passed on)
 	mpeg - if set, will create an mpeg of animation
	filename - name of mpeg file (default =  'plotanimation.mpg')
	rep - # number of times to repeat frames (to slow down mpeg) default=0
	t1 - time to start animation (indexes into time array) (default=start)
	t2 - time to end animation (default=end)
	xtitle -    
	ytitle -    
	xsize - xsize of window in pixels
	ysize - ysize of window in pixels 
	flip - if set, will flip mpeg image    
	timeTitle - appended to indication of time on plot (def='Sec.')
	pause - # of seconds to pause between plotted frames when creating
	verbose - if set, will print many informational messages
	debug - if set, debug output will be printed
 OUTPUTS:
       NONE; just the mpeg file, if specified
 EXAMPLE:
	nframes = 20
	nPts = 1000
	data2d = fltarr(npts, nframes)
	time = findgen(nFrames)/1000 +0.2
	x =findgen(npts)/npts*150 + 50
	for i=0,nframes-1 do data2d[0,i]=sin(x*5/max(x)+i/10.)*exp(1.-x/100-i/10.)
	animxyplot, data2d, x, time, xtitle='Radii', ytitle='Value', /mpeg
 NOTES:
 MODIFICATION HISTORY:
       18-Jan-2008 Written by Bill Davis, PPPL

(See src/idl_cvs/animxyplot.pro)


CINE2MPEG

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

 PURPOSE:
    Create an mpeg movie from a .cin files from Phantom 7 Cameras.
    The data can be color or monochrome

 CATEGORY:
    animation

 CALLING SEQUENCE:
      cine2mpeg, CineFile1, outFile=outfile, t1=t1, t2=t2, ndups=ndups
   or
      cine2mpeg, shot=shot, t1=t1, t2=t2, /verbose

 INPUTS:
	CineFile1 - a cine filename
 OPTIONAL KEYWORD PARAMETERS:
	outFile - name of output MPEG file (will default to a nice name), or 
	prefix - what would precede _shot_t1_t2 (in msec) in the output filename
	t1 - start time of animation in seconds
	t2 - end time of animation in seconds
	VIEW - if set, just displays images, and does not make an mpeg
   	ndups - if given means repeat every image 'ndups' times
   	despeckle - if set call despeckle routine (slow, but less "intrusive" 
		    than median)
	nSmooth - number input to median smoothing routine
	topPixels -
	botPixels - 
	charsize - character size for plots. Default=2
	ctb - color table for non-color image 
	label1 - label on plot 
	verbose - if set will print out info as it works
 OUTPUTS: 
	an MPEG file named by outFile keyword

 PROCEDURE:
 EXAMPLE:

    cine2mpeg, '/p/nstxusr3/miro/MIRO_130389.cin', $
		t1=0.02, t2=0.0300, /verbose                        , /debug

    cine2mpeg, shot=130277, t1=0.100, t2=0.200, /verbose, /view    , /debug

    cine2mpeg, '/p/nstxusr2/phantom4/GDNex10usFps27000DC110maP1.98torr-1.cin', $
		outfile='Ne110us.mpg', t1=.0007, t2=0.0017, ndups=4, mag=3

   mv files to /w/nstx.pppl.gov/htdocs/nstx/Software/Diagnostics/Miro/GlobalMPEGs 
	for web viewing at
       http://nstx.pppl.gov/nstx/Software/Diagnostics/Miro/GlobalMPEGs

 MODIFICATION HISTORY:
	12-Nov-2008 mods because cineload now assuming frame 0 is beginning of data
	18-Sep-2008 mods to magnify keyword
	05-Aug-2008 Written by Bill Davis

(See src/idl_cvs/cine2mpeg.pro)


DISPLAYFCMDS

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

 PURPOSE:
	Animate Fast Camera images from MDSplus with the time overlayed

 CATEGORY:
       Animation

 CALLING SEQUENCE:

	IDL> displayfcmds, shot
 INPUTS:
       shot = nstx shot number  

 KEYWORD PARAMETERS:
    Keywords:
	minmsec - min time in msec to include
	maxmsec - max time in msec to include
	loop - number of times to loop through animation (default=1)
	pause - time in seconds to pause between frames (default=0)
	minToPlot - min value for bytscl of image
	maxToPlot - max value for bytscl of image
	skip - frames to skip between those displayed (default=0)
	magnify - magnification factor ( note that bigger movies are slower)
	charThick - 
	charsize -  
	debug -  
  	mpg - 
	xpos -
	ypos -
	mds - if set, look for data in MDS plus (little there as of Jul/04)
 OUTPUTS:
       none

 LIMITATIONS:
       MPEG movies created from widget are poor.
 EXAMPLE:
	IDL> displayfcmds,shot=113723,minms=140,maxms=170, loop=10, pause=.3
	IDL> displayfcmds, 127179, loop=10000L, minmsec=150, maxmsec=300, $
			   trig=0, mult=2

 MODIFICATION HISTORY:
	21-Feb-08 replaced openmdsshot with mdsopen
	05-MAR-07 Assume all shots in MDSplus
	10-Apr-06 more keywords. Be able to work from cameras2 tree
	16-Aug-05 added xpos and ypos keywords for use on wall [BD]
	31-May-05 Read timing module trigger time from MDSplu
	16-Mar-05 Only read in times within times requested
	29-Jul-04 access /v/kodak area from Unix
	22-Jul-04 Added mpg creation [DM]
      Written by Bill Davis, PPPLmax

(See src/idl_cvs/displayfcmds.pro)


DISPLAYFCTIFFS

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

 PURPOSE:
	Animate Fast Camera images with the time overlayed

 CATEGORY:
       Animation

 CALLING SEQUENCE:

	IDL> displayfctiffs, shot
 INPUTS:
       shot = nstx shot number  

 KEYWORD PARAMETERS:
    Keywords:
	minmsec - min time in msec to include
	maxmsec - max time in msec to include
	loop - number of times to loop through animation (default=1)
	pause - time in seconds to pause between frames (default=0)
	minToPlot - min value for bytscl of image
	maxToPlot - max value for bytscl of image
	skip - frames to skip between those displayed (default=0)
	magnify - magnification factor ( note that bigger movies are slower)
	charThick - 
	charsize -  
	debug -  
  	mpg - 
	mds - if set, look for data in MDS plus (little there as of Jul/04)
 OUTPUTS:
       none

 LIMITATIONS:
       MPEG movies created from widget are poor.
 EXAMPLE:
	IDL> displayfctiffs,shot=113723,minms=140,maxms=170

 MODIFICATION HISTORY:
	16-Mar-05 Only read in times within times requested
	29-Jul-04 access /v/kodak area from Unix
	22-Jul-04 Added mpg creation [DM]
      Written by Bill Davis, PPPL

(See src/idl_cvs/displayfctiffs.pro)


EFITMOVIES

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

 PURPOSE:
       Plot EFIT field lines, Thomson Scattering Density and Temperature 
	and, optionally, Fast Camera images. Instead of Fast Camera, can
	plot H-alpha (or another) signal vs. time.

 CATEGORY:
       Animation, EFIT, 2-D Plotting, NSTX, Thomson Scattering

 CALLING SEQUENCE:
   to get a single frame:
	IDL> shot=130000
	IDL> efitmovies, shot, time=0.2, /thom, signame='\wf::ip',  $
                        sigt1=0, sigt2=.4

   to get a single frame with flux surfaces on both sides:
       IDL> efitmovies, 121048, time=.2, /double

   to get a single frame with fast camera image on the left:
       IDL> efitmovies, 120200, time=.2

   to get an animation:
	IDL> efitmovies,120200,time=[0.05,0.317],/thom,max=40

   to get an animation with H-alpha time trace instead of Fast Camera images:
	IDL> efitmovies,107314,/thom, time=[.05,.5], $
			/signame,sigtitle='H-alpha',max=40

   to see what shots have fast camera data in the tree:
 	IDL> MDSnodeChanges,'\fc3d',shot1=119120,shot2=119230,tree='cameras',/after
 INPUTS:
       shot = nstx shot number  

 KEYWORD PARAMETERS:
    Keywords:
	ndups - number of times each frame of movie is duplicated (default=0)
	time - 2-element array for animation; single value for one frame
	thomson - if set, will plot Thomson Te and Ne below EFIT contours
	animate - if set to 0, will plot individual frames instead of movie.
	maxFrames - max # of frames over time range -- necessary if X-memory
		    is limited (default is 200).
	pixMap - if set, will not send each frame to the screen (faster)
 	double - plot efit color contours on both sides of center stack
	sigName - if set, will not show Fast Camera images, but this
		  signal vs. time (defaults to \passivespec::BAYC_DALF_HAIFA)
	sigT1 - starting time of signal vs. time plot
	sigT2 - ending time of signal vs. time plot
	sigTitle - if set, will be displayed above sigName plot,
		   else tries to get label from MDSplus
	overlayTe - overlay Thomson Te and Ne, instead of on left and right
	window - starting window number (default=0)
	efitVersion - the efit version to display. Defaults to the highest
			available less than 5.
	LRDfitVersion - the LRDfit version to display. If non-blank, will override
		        efitVersion keyword used.
 OUTPUTS:
       none

 LIMITATIONS:
       Some reds are green on printer.
 NOTES:
   to create an FLC animation out of ppm files:

       IDL> efitmovies,106892,/pixmap,time=[0.05,0.317],/thom,max=400,;
	alias ppm2fli '/u/bdavis/FTP/ppm2fli-2.1/ppm2fli'
	cd /tmp/idl2ppm.frames/
	/bin/ls -1 *.ppm > pics.list
	ppm2fli -g 600x600 -s 180 pics.list ~/public_html/movies/xsec106892.fli

     the -g parameter specifies the size
     -s is the "rate" (bigger is slower)

   to get tiff files from the fastcamera system into the right taurus directory:
	IDL> .run /u/bdavis/Anim/get_tifs
	IDL> get_tifs,  shot
 MODIFICATION HISTORY:
	02-May-06 added ndups keyword
  	26-Jan-06 No longer e-mail to 'USER' if username not specified. 
		  Tidy up screen message for postscript output
	27-Sep-2005 fix bug for sub-msec timing for single plots
	19-Aug-2005 improve selection of efit version
	17-Jul-2005 Assure black lines on plots
	03-Sep-04 Better logic for missing Thomson data.
	15-Apr-04 Fixed bug for full time with lots of frames
		  made default max frames 200.
	23-Oct-03 Use spline Te and Ne from Thomson
	23-Aug-03 Adds for efitflux.html
	23-May-03 Added keywords for Web Plotting
	01-May-03 Added /double keyword
       28-May-02 Added /signame keyword and overlayTe
	Original written by Dave Gates

(See src/idl_cvs/efitmovies.pro)


EFITPLUSRF

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

 PURPOSE:
       Plot  Camera images along with EFIT field 
	lines, and also plot Ip, Pnb, and H-alpha (or another) signal vs. time.

 CATEGORY:
       Animation, 2-D Plotting, NSTX, EFIT, RF Heating

 CALLING SEQUENCE:
	IDL> efitplusrf, 115775,time=[.1,.2],xsize=300,ysize=250
	IDL> efitplusrf,115775,time=[.1,.2], cx1=115,cx2=440, cy1=20, cy2=300
	IDL> efitplusrf,115775,time=[.1,.2], cx1=115,cx2=440, cy1=20, cy2=300, $
		mindata=50, maxdata=270

	IDL> efitplusrf, 115651, cx1=85,cx2=375, cy1=0, cy2=260
	IDL> efitplusrf, 112117, pixmap=1, animate=0, ppmout=1, /verbose, /debug

	IDL> efitplusrf, 111827, time=[.18,.2], sigT1=.18,sigT2=.20, /verbose
	IDL> efitplusrf, 111827, pixmap=1, animate=0, ppmout=1, /verbose

	IDL> efitplusrf, 114333,time=[.008,.012],thom=0, sigT1=.005,sigT2=.020

	   To get a postscript frame printed:
	IDL>efitplusrf,114333,time=0.01,thom=0,sigT1=.005,sigT2=.02,anim=0,/postscript

   if the FC images are too light, you can make them 4 times as bright:
	IDL> efitplusrf, 112608, FCimgScale=4

   to get an animation with no more than 40 frames between 50 and 317 msec:
	IDL> efitplusrf, shot, time=[0.05,0.317],max=40
 
 INPUTS:
       shot = nstx shot number  
	diverter camera data must be moved manually to linux. Examples are
	at /p/nstxusr2/uppercam/114333 and /p/nstxusr2/divcam/114333.
	A .cih file must also be in each directory for the timing information
 KEYWORD PARAMETERS:
    Keywords:
	time - 2-element array for animation; single value for one frame
	animate - if set to 0, will NOT make a movie in an IDL XINTERANIMATE window.
	maxFrames - max # of frames over time range -- necessary if X-memory
	imSmooth - amount to median smooth images (default=3)
		    is limited (default is 200).
	sigName - if set, will not show Fast Camera images, but this
		  signal vs. time (defaults to \passivespec::BAYC_DALF_HAIFA)
	sigT1 - starting time of signal vs. time plot
	sigT2 - ending time of signal vs. time plot
	sigTitle - if set, will be displayed above sigName plot,
		   else tries to get label from MDSplus
	ndups - number of times each frame of movie is duplicated (default=0)
 OUTPUTS:
       none

 LIMITATIONS:
       MPEG movies created from widget are poor.
	All Fast Camera data is on VMS, but can be mounted from petrel084 to
	petrel092. Only what has been moved manually 
	is on Unix. 
 NOTES:

   you need to use /save to get Mpeg  quality=100 (but it's not clear there's
	any improvement in the Mpeg.

   to get tiff files from the fastcamera system into the right taurus directory:
	spc them from the KODAK directory, or one of it's subdirectories, on VMS
 MODIFICATION HISTORY:
	01-Mar-2007 removed flip of image, per Lane Roquemore 
  	13-Apr-2006 camera times off by 2 time steps. Add triggerTime keyword
	11-Aug-2005 Handle smaller xsize & ysize (not great, but can see)
	25-Jul-2005 Get Ip and Pnb from EFIT, if WF tree not there.
	30-Mar-2005 convert from fcdcmovies
	05-Aug-2004 Added two Hiroshima cameras
	23-Jul-04 added ExtendEFITtime keyword to continue animation after efit
	05-May-04 Adapted from EfitMovies for Fast Camera data plus x-y plots
	Original EFIT animation written by Dave Gates

(See src/idl_cvs/efitplusrf.pro)


FCDCMOVIES

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

 PURPOSE:
       Plot Fast Camera and Divertor Camera images along with EFIT field 
	lines, and, optionally, Thomson Scattering Density and Temperature. 
	You may also plot H-alpha (or another) signal vs. time.

 CATEGORY:
        Animation, NSTX, EFIT, Thomson Scattering

 CALLING SEQUENCE:

	IDL> fcdcmovies, 114333,time=[.008,.012],thom=0, sigT1=.005,sigT2=.020

	   To get a postscript frame printed:
	IDL>fcdcmovies,114333,time=0.01,thom=0,sigT1=.005,sigT2=.02,anim=0,/postscript

   if the FC images are too light, you can make them 4 times as bright:
	IDL> fcdcmovies, 112608, FCimgScale=4

   to get an animation with no more than 40 frames between 50 and 317 msec:
	IDL> fcdcmovies, shot, time=[0.05,0.317],max=40
 
 INPUTS:
       shot = nstx shot number  
	diverter camera data must be moved manually to linux. Examples are
	at /p/nstxusr2/uppercam/114333 and /p/nstxusr2/divcam/114333.
	A .cih file must also be in each directory for the timing information
 KEYWORD PARAMETERS:
    Keywords:
	half - if set, only show left half of fast camera image
	time - 2-element array for animation; single value for one frame
	thomson - if set to 0, will NOT plot Thomson Te and Ne below EFIT contours
	animate - if set to 0, will NOT make a movie in an IDL XINTERANIMATE window.
	maxFrames - max # of frames over time range -- necessary if X-memory
	imSmooth - amount to median smooth images (default=3)
		    is limited (default is 200).
	sigName - if set, will not show Fast Camera images, but this
		  signal vs. time (defaults to \passivespec::BAYC_DALF_HAIFA)
	sigT1 - starting time of signal vs. time plot
	sigT2 - ending time of signal vs. time plot
	sigTitle - if set, will be displayed above sigName plot,
		   else tries to get label from MDSplus
 OUTPUTS:
       none

 LIMITATIONS:
       MPEG movies created from widget are poor.
	All Fast Camera data is on VMS, but can be mounted from petrel084 to
	petrel092. Only what has been moved manually 
	is on Unix. 
 NOTES:

   you need to use /save to get Mpeg  quality=100 (but it's not clear there's
	any improvement in the Mpeg.

   to get tiff files from the fastcamera system into the right taurus directory:
	scp them from the KODAK directory, or one of it's subdirectories, on VMS

	Postscript files can be huge; may try making separate one with only Fast Camera image.

 MODIFICATION HISTORY:
       03-Sep-04 Fixed bug in times of Thomson when animating partial shot
	05-Aug-2004 Added two Hiroshima cameras
	23-Jul-04 added ExtendEFITtime keyword to continue animation after efit
	15-Jul-04 Make default to do animation and include Thomson data
	13-Jul-04 Made the default be to show whole fast camera image
	05-May-04 Adapted from EfitMovies for Fast Camera data plus x-y plots
	Original EFIT animation written by Dave Gates

(See src/idl_cvs/fcdcmovies.pro)


FCMOVIES

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

 PURPOSE:
       Plot EFIT field lines, Thomson Scattering Density and Temperature 
	and Fast Camera images. Can also
	plot H-alpha (or another) signal vs. time.

 CATEGORY:
       Animation, NSTX, EFIT, Thomson Scattering

 CALLING SEQUENCE:
      good demo:
	DL> fcmovies, 120477

	IDL> fcmovies, 112606

   if the FC images are too light, you can scale them up:
	IDL> fcmovies, 112608, FCimgScale=4

   to get an animation:
	IDL> fcmovies, 107994,time=[0.05,0.317],max=40
 
	IDL> fcmovies, 113723,time=[.14,.3],thom=0, /pixmap
 INPUTS:
       shot = nstx shot number  

 KEYWORD PARAMETERS:
    Keywords:
	NREPS - number of frames to repeat when creating mpeg (1 means no dups)
	half - if set, only show left half of fast camera image
	time - 2-element array for animation; single value for one frame
	thomson - if set to 0, will NOT plot Thomson Te and Ne below EFIT contours
	animate - if set to 0, will NOT make a movie in an IDL XINTERANIMATE window.
	maxFrames - max # of frames over time range -- necessary if X-memory
		    is limited (default is 500).
	sigName - if set, will not show Fast Camera images, but this
		  signal vs. time (defaults to \passivespec::BAYC_DALF_HAIFA)
	sigT1 - starting time of signal vs. time plot
	sigT2 - ending time of signal vs. time plot
	sigTitle - if set, will be displayed above sigName plot,
		   else tries to get label from MDSplus
	FCimageScale - factor to multiply image frames by.
 OUTPUTS:
       none

 LIMITATIONS:
       MPEG movies created from widget are poor.
	All data is on VMS. Only what has been moved manually is on Unix.
 NOTES:

   !!!!! you need to use /save to get quality=100

 MODIFICATION HISTORY:
	02-May-06 added nreps keyword
	27-Apr-06 added FcFromMDS keyword, so could get from files, even
		  if data in MDSplus.
	16-Aug-05 be able to read from MDSplus and default to color table 3
	13-Sep-04 Handle missing waveforms. Assure that overlayed signals on 
		  same timebase. 
		  Added a kludy check for bug in some DALF timing (e.g., 114446) 
	03-Sep-04 Fixed bug in times of Thomson when animating partial shot
	23-Jul-04 added ExtendEFITtime keyword to continue animation after efit
	15-Jul-04 Make default to do animation and include Thomson data
	13-Jul-04 Made the default be to show whole fast camera image
	05-May-04 Adapted from EfitMovies for Fast Camera data plus x-y plots
	15-Apr-04 Fixed bug for full time with lots of frames
		  made default max frames 200.
	23-Oct-03 Use spline Te and Ne from Thomson
	23-Aug-03 Adds for efitflux.html
	23-May-03 Added keywords for Web Plotting
	01-May-03 Added /double keyword
       28-May-02 Added /signame keyword and overlayTe
	Original EFIT animation written by Dave Gates

(See src/idl_cvs/fcmovies.pro)


FCTIFFSVCR

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

 PURPOSE:
	animate Fast Camera tiffs with VCR-like controls.
	from the resulting widget, you may write an Mpeg file

 CATEGORY:
       Animation

 CALLING SEQUENCE:

	IDL> fctiffsvcr, shot
 INPUTS:
       shot = nstx shot number  (Optional - you can navigate for a shot)

 KEYWORD PARAMETERS:
    Keywords:
	minmsec - min time in msec to include
	maxmsec - max time in msec to include
	minToPlot - min value for bytscl of image
	maxToPlot - max value for bytscl of image
	skip - frames to skip between those displayed (default=0)
	magnify - magnification factor ( note that bigger movies are slower)
	InitPath - Initial Path of Fast Camera data
	rate - initial display rate
	verbose - if set, will print info as it progresses
	charThick - 
	charsize -  
	debug -  
	mds - if set, look for data in MDS plus (little there as of Jul/04)
 OUTPUTS:
       none

 LIMITATIONS:
  	as of 29-Jul-2004, FC data just available on NSTX Petrels,
	the VMS cluster.
       MPEG movies created from widget are poor.
 EXAMPLE:
	IDL> fctiffsvcr,shot=113723,minms=140,maxms=170
	IDL> fctiffsvcr, frame1=1000, skip=5, maxframes=100, $
		files='/p/camdata/dust/120325_TIFF/*.tif', mag=3, /debug

 MODIFICATION HISTORY:
      29-Jul-2004 Written by Bill Davis, PPPL

(See src/idl_cvs/fctiffsvcr.pro)


FCVCR

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

 PURPOSE:
       Plot Fast Camera images with a VCR-like interface

 CATEGORY:
       Animation, Fast Camera

 CALLING SEQUENCE:

   to get an animation with a maximum of 40 frames (spaced with time selection):
	IDL> fcvcr, 128030, time=[0.05,0.317], max=40

   to see what shots have fast camera data in the tree:
 	IDL> MDSnodeChanges,'\fc3d', shot1=119120, shot2=119330, tree='cameras'
 INPUTS:
       shot = nstx shot number  

 KEYWORD PARAMETERS:
    Keywords:
	ndups - number of times each frame of movie is duplicated (default=0)
	time - 2-element array for animation; single value for one frame
	animate - if set to 0, will plot individual frames instead of movie.
	maxFrames - max # of frames over time range -- necessary if X-memory
		    is limited (default is 200).
	pixMap - if set, will not send each frame to the screen (faster)
 OUTPUTS:
       calls XIA, from which you can save pictures of frames, or an mpeg file
 LIMITATIONS:
 NOTES:
 MODIFICATION HISTORY:
	28-Mar-2008 written by Bill Davis

(See src/idl_cvs/fcvcr.pro)


MK_MPEG

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

 PURPOSE: 
    Write a sequence of images from a 3-D array, or a series of tiff
    files, as an mpeg movie.

 CATEGORY: 
    animation

 CALLING SEQUENCE:
    mk_mpeg, 'movie.mpg' ,ims
	or
    mk_mpeg, 'movie.mpg', files=files

 INPUTS:
     ims: sequence of images as a 3D array with dimensions [sx, sy, nims]
          where sx = xsize of images
                sy = ysize of images
                nims = number of images

 OPTIONAL INPUTS:

 KEYWORD PARAMETERS:
	delafter:  if set delete temporary array after movie was created
                you should actually always do it otherwise you get
                problems with permissions on multiuser machines (since
                /tmp normally has the sticky bit set)
	rep:     if given means repeat every image 'rep' times
                (as a workaround to modify replay speed). i.e., if = 2, make 2 copies of
		 each frame.
	files:   file list. If just one value, needs to include a wild card
	justone: just plot D-alpha
	despeckle : if set call despeckle routine (slow, but less "intrusive" than median)
 OUTPUTS: None

 OPTIONAL OUTPUTS:

 COMMON BLOCKS:

 SIDE EFFECTS:
	creates some files in TMPDIR which are only removed when
	the delafter keyword is used

 RESTRICTIONS:
	depends on the program mpeg_encode from University of
	California, Berkeley, which must be installed in /usr/local/bin

 PROCEDURE:
	writes a parameter file based on the dimensions of the image
	array + the sequence of images in ppm format into a
	temporary directory; finally spawns mpeg_encode to build the
	movie

 EXAMPLE:
 	IDL> shot = 111840
 	IDL> f = findfile( '/p/nstxusr2/divcam/'+strtrim(shot,2)+'/*.tif')
 	IDL> mk_mpeg, strtrim(shot,2)+'_divcam'+'.mpg',files=f,shot=shot,/fliphoriz

 LIMITATIONS:
	mpeg_encode must be in your path (not currently on PPPL Linux)

 MODIFICATION HISTORY:
	22-Apr-04 lots of kludges to make nice movies of camera data
		  from Hiroshima University on NSTX. [BD]
	29-Apr-02 Modified write_mpeg to accept a filelist or wildcard spec [BD].
	Mon Nov 18 13:13:53 1996, Christian Soeller
	

	grabbed original from the net and made slight modifications

(See src/idl_cvs/mk_mpeg.pro)


MPEG_FROM_SCREEN

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

 PURPOSE:
       Example of creating a color Mpeg animation with text overlayed.
	Works on both 8-bit and 24-bit monitors. Can read from files, but those
	returning 24-bit data will not have the text overlaying option.

 CATEGORY:
       Animation

 CALLING SEQUENCE:
	IDL> mpeg_from_screen
    or
	IDL> mpeg_from_screen, data3d=data3D, mpeg_filename='mymovie.mpg'
    or
	IDL> mpeg_from_screen, ndups=5,  $
		files=['out1.jpg','out2.jpg','out3.jpg','out4.jpg','out5.jpg']
 INPUTS:
       none required 

 KEYWORD PARAMETERS:
    All optional inputs:
	data3D - optional 3-D array ( nx, ny, nFrames )
	nFrames - # of frames when using dummy data.
	files - a string array of filenames. 
		Can be of type 'jpg','tif','tif','bmp','jpeg,'png', or 'gif'
	mpeg_filename - output filename for mpeg movie
	ndups - number of times each frame of movie is duplicated (default=3)
	showFrame - if =0, will not show frame around image (irrelevant for rgb files)
	useScreen - if=0, don't bother using screen for output (i.e., no text to overlay)
			(irrelevant for rgb files)
	border - # of pixels around data (default=25)
	ctb - color table to use (default=39)
	charsize - character size (default=1.5)
	charthick - character thickness (default=2)
	pixMap - if = 0, will write and read each frame from screen (much slower)

 OUTPUTS:
       mpeg file

 MODIFICATION HISTORY:
	20-Oct-2004 Optionally operate off a list of files
	15-Oct-2004 Written by Bill Davis

(See src/idl_cvs/mpeg_from_screen.pro)


MPTSCAM

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       mptscam
 PURPOSE:
	Animate several plots, including MPTS variables
 CATEGORY:
	Animation, MPTS
 CALLING SEQUENCE:
       IDL>   mptscam, shot, xSize=xSize, ySize=ySize, sideSigs=sideSigs, $
              MAX_COLORS_TO_USE = max_colors_to_use, 	$
              noSides=noSides, colortable=colortable, $
	      mpegFile=mpegFile, rf=rf, nb=nb, pixMap=pixMap, $
	      gaps=gaps
 INPUTS:
	shot - NSTX shot # to display
 KEYWORD PARAMETERS:
    Optional Inputs:
	...
 OUTPUTS:
       can create mpegs
 EXAMPLE: for output example, see 
	http://nstx.pppl.gov/nstx/Software/Diagnostics/MPTS/mptsdata.html
 NOTES:
	This routine has not been tested for many combinations of signals

   To get frames from the fastcam PC, contact Bill Davis
 MODIFICATION HISTORY:
  	16-Nov-01 Fine tuned for xsize=600, ysize=400 (for publication)
        Written by Bill Davis

(See src/idl_cvs/mptscam.pro)


WRITE_MPEG

[Previous Routine] [Next Routine] [List of Routines]
+
 NAME: 
        WRITE_MPEG

 PURPOSE: 
        Write a sequence of images as an mpeg movie

 CATEGORY: 
	animation

 CALLING SEQUENCE:
        WRITE_MPEG,'movie.mpg',ims

 INPUTS:
     ims: sequence of images as a 3D array with dimensions [sx, sy, nims]
 	   where sx = xsize of images
 		 sy = ysize of images
 		 nims = number of images

 OPTIONAL INPUTS:

 KEYWORD PARAMETERS:
     delaft:   if set delete temporary array after movie was created
               you should actually always do it otherwise you get
               problems with permissions on multiuser machines (since
               /tmp normally has the sticky bit set)
     rep:      if given means repeat every image 'rep' times
               (as a workaround to modify replay speed)

 OUTPUTS: None
 OPTIONAL OUTPUTS:

 COMMON BLOCKS:

 SIDE EFFECTS:
      creates some files in TMPDIR which are only removed when
      the DELAFT keyword is used

 RESTRICTIONS:
     depends on the program mpeg_encode from University of
     California, Berkeley, which must be installed in /usr/local/bin

 PROCEDURE:
     writes a parameter file based on the dimensions of the image
     array + the sequence of images in ppm format into a
     temporary directory; finally spawns mpeg_encode to build the
     movie

 EXAMPLE:
    IDL> s=openmdsshot('efit',112800)
    IDL> data3d=mdsvalue('\efit01::psirz')
    IDL> write_mpeg, 'efit_112800.mpg', bytscl(congrid(data3d,65*8,65*8,128))
  or 
    IDL>write_mpeg,'test.mpg',reform([[dist(100)],[dist(100)],[dist(100)]],100,100,3)

 MODIFICATION HISTORY:
     15-Jul-04 warn if file not 3d [BD]
     Mon Nov 18 13:13:53 1996, Christian Soeller
     

     grabbed original from the net and made slight modifications

(See src/idl_cvs/write_mpeg.pro)


XEASYANIM

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

 PURPOSE:
       animate 3-D array and optionally make MPEG Movie

 CATEGORY:
       Animation, MPEG

 KEYWORDS:
	nreps - number of frames to repeat when creating mpeg (1 means no dups)
	xSize - 
	ySize - 
	rate -            
	MAX_COLORS_TO_USE  - 
	magnification - 
	xpos - 
	ypos - 
	colortable - color table for movie
	ctbFile - color table file (for personal color tables)
	noLoad - if set, do not load any color table 
	SCALEEACHFRAME - 
	bottom -  if set, then position window at bottom of screen
	despeckle - 
	XWIN - 
	YWIN - 
	STDEV_MULT
	ctbfile - color table file (for personal color tables)
 EXAMPLE:
	IDL> Array3D_In = REFORM(DIST(600,200),200,200,3)
	IDL> XEasyAnim, Array3D_In,  /bottom

    you may wish to the following:

	IDL> dum=MK_COLOR(N_NONFIXED=ncolors)
	IDL> Array3D = BYTSCL( Array3D, TOP=ncolors )
	IDL> XEasyAnim, Array3D
 Modifications:
	12-May-2008 added noLoad and ctbFile keywords
	02-Aug-2007 add gamma keyword [BD]
	02-May-06 added nreps keyword
	14-Apr-06 added xpos & ypos keywords
	06-Mar-02 Added printing, resizing of array, added despeckling [BD]

(See src/idl_cvs/xeasyanim.pro)


XIA

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

 PURPOSE:
	Display an animated sequence of images using X-windows Pixmaps.
	The speed and direction of the display can be adjusted using 
	the widget interface.

 CATEGORY:
	Animation, Image display, widgets.

 CALLING SEQUENCE:
	To initialize:
		XIA, SET = [Sizex, Sizey, Nframes]

	To load a single image:
		XIA, IMAGE = Image, FRAME = Frame_Index

	To load a single image that is already displayed in an existing window:
		XIA, FRAME = Frame_index, $
			WINDOW = [Window_Number [, X0, Y0, Sx, Sy]]
	(This technique is much faster than reading back from the window.)

	To display the animation after all the images have been loaded:
		XIA [, Rate] 

	To close and deallocate the pixmap/buffer (which also takes place
	automatically when the user presses the "Done With Animation"
	button or closes the window with the window manager):
		XIA, /CLOSE

 OPTIONAL INPUTS:
	Rate:	A value between 0 and 100 that represents the speed of the 
		animation as a percentage of the maximum display rate.
		The fastest animation is with a value of 100 and the slowest
		is with a value of 0.  The default animation rate is 100.  
		The animation must be initialized using the SET
		keyword before calling XIA with a rate value.

 KEYWORD PARAMETERS:
	BOTTOM: If set, window will be at bottom of screen or parent window
	CLOSE:	Set this keyword to delete the offscreen pixwins and Widget, 
		freeing storage.

	CYCLE: If set, cycle.  Normally, frames are displayed going either
		forward or backwards.  If CYCLE is set, reverse direction
		after the last frame in either direction is displayed.
		Provide this keyword with the SET keyword.

	FRAME:	The frame number when loading frames.  This keyword only has
		an effect when used in conjunction with the SET keyword.
		FRAME must be set to a number in the range 0 to Nframes-1.

	GROUP:	The widget ID of the widget that calls XIA.  When 
		this ID is specified, the death of the caller results in the 
		death of XIA.

	IMAGE:	A single image to be loaded at the animation position given 
		by FRAME.  The keyword parameter FRAME must also be specified.

	KEEP_PIXMAPS: If TRUE, XIA doesn't destroy the animation
		pixmaps when it is killed. Calling it again without
		going through the SET and LOAD steps will cause the same
		animation to play without the overhead of creating
		the pixmaps.
	BLOCK:  Set this keyword to have XMANAGER block when this
		application is registered.  By default the Xmanager
               keyword NO_BLOCK is set to 1 to provide access to the
               command line if active command 	line processing is available.
               Note that setting BLOCK for this application will cause
		all widget applications to block, not only this
		application.  For more information see the NO_BLOCK keyword
		to XMANAGER.
	ORDER:	Set this keyword to display images from the top down instead
		of the default bottom up.  This keyword is only used when 
		loading images.
       MODAL:  If set, then XIA runs in "modal" mode, meaning that
               all other widgets are blocked until the user quits
               XIA.
       MPEG_OPEN: Set this keyword to open an MPEG file.
       MPEG_FILENAME: Set this keyword equal to a string for the desired
               MPEG filename.  If not set, idl.mpg is used.
       MPEG_CLOSE: Set this keyword to write the MPEG file.
	NREPS - number of frames to repeat when creating mpeg (1 means no dups)
       SHOWLOAD:	Set this keyword (in conjunction with the SET keyword) to 
		display each frame and update the frame slider as frames are 
		loaded.

	SET:	This keyword initializes XIA.  SET should be equated
		to a 3-element integer vector containing the following 
		parameters:
		  Sizex, Sizey:	The width and height of the images to be 
				displayed, in pixels.

		  Nframes:	The number of frames in the animated sequence 
				(since XIA is an animation routine, 
				Nframes must be at least 2 frames).

	TITLE:	A string to be used as the title of the widget.  If this 
		keyword is not specified, the title is set to "XIA" 
		This keyword has an effect only when used in conjunction with
		the SET keyword).

	TRACK: If set, the frame slider tracks the current frame.  Default
		is not to track.  Provide this keyword with the SET keyword.

	WINDOW:	When this keyword is specified, an image is copied from an 
		existing window to the animation pixmap.  When using X 
		windows, this technique is much faster than reading
		from the display and then calling XIA with a 2D 
		array.

		The value of this parameter is either an IDL window
		number (in which case the entire window is copied),
		or a vector containing the window index and the rectangular 
		bounds of the area to be copied, for example:
		WINDOW = [Window_Number, X0, Y0, Sx, Sy]

      XOFFSET:	The horizontal offset, in pixels from the left of the frame, 
		of the image in the destination window.

      YOFFSET:	The vertical offset, in pixels from the bottom of the frame,
		of the image in the destination window.

 OUTPUTS:
	No explicit outputs.

 COMMON BLOCKS:
	XIA_COM: a private common block.

 SIDE EFFECTS:
	A pixmap and widget are created.

 RESTRICTIONS:
	Only a single copy of XIA can run at a time.

 PROCEDURE:
	When initialized, this procedure creates an approximately square
	pixmap or memory buffer, large enough to contain Nframes of
	the requested size.  Once the images are loaded, using the 
	IMAGE and FRAME keywords, they are displayed by copying the images 
	from the pixmap or buffer to the visible draw widget.

 EXAMPLE:
	Enter the following commands to open the file ABNORM.DAT (a series
	of images of a human heart) and animate the images it contains using
	XIA.  For a more detailed example of using XIA, 
	see the example in the "Using IDL Widgets" chapter of "IDL Basics".
	Read the images into the variable H by entering:

		OPENR, 1, FILEPATH('abnorm.dat', SUBDIR = 'examples/data')
		H = BYTARR(64, 64, 16)
		READU, 1, H
		CLOSE, 1
		H = REBIN(H, 128, 128, 16)

	Initailize XIA with the command:

		XIA, SET=[128, 128, 16], /SHOWLOAD
		
	Load the images into XIA and play the animation by entering:

		FOR I=0,15 DO XIA, FRAME = I, IMAGE = H[*,*,I]
		XIA

 MODIFICATION HISTORY:
	02-May-06 added nreps keyword
	14-Apr-06 added xpos & ypos, bottom & right keywords
	02-Aug-01 modified XInterAnimate to have printing [Bill Davis]

(See src/idl_cvs/xia.pro)


XYANIM

[Previous Routine] [List of Routines]
 NAME:
       xyanim
 PURPOSE:
	Animate a series of X-Y plots.
       Makes an animation in a XINTERANIMATE window. An MPEG file
	can then be saved, or the movie can be played with VCR-like 
	controls
 CATEGORY:
       Animation
 CALLING SEQUENCE:
       IDL> xyanim, Radii, YvsT, times, xSize=xSize, ySize=ySize
 INPUTS:
       Radii - 1-D array of Radii (for example)
       YvsT  - 2-D array of Independent axis vs. time
	times - times for which an x-y plot will be made (defaults to 1/frame)
 KEYWORD PARAMETERS:
       Keywords:
	  xSize - x size of resulting output frame (default=400)
	  ySize - y size of resulting output frame (default=xSize)
 OUTPUTS:
       just the XinterAnimate window. MPEGs can be made from that widget.
 COMMON BLOCKS:
       NONE
 EXAMPLE:
	See /u/bdavis/cvs/idl_cvs/testxyanim.pro 
 MODIFICATION HISTORY:
       12-Jun-01 Written by Bill Davis, PPPL

(See src/idl_cvs/xyanim.pro)


Category: Bits

[List of Routines]


BITS

[Next Routine] [List of Routines]
 NAME:
       bits
 PURPOSE:
       Given a byte or integer, return a vector of 8 or 16 values
       which are the binary representation of the value.
 CATEGORY:
       bits, hardware
 INPUT:
       invalue - The byte or integer value to check
 OUTPUT:
       bitarr  - The 8-element array with values set
                 if the bit is set
 EXAMPLE:
	IDL> BITS, invalue, BITARR
 HISTORY:
       Written 1988 by M.Morrison
       13-Nov-92 (MDM) - Modified to allow integer*2 values
                         and to allow an array of values.
        7-Apr-94 (MDM) - Allow integer*4 values
       15-Aug-94 (MDM) - Corrected error from 7-Apr-94 mod which
                         did not allow an array of inputs

(See src/idl_cvs/bits.pro)


BTEST

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

 PURPOSE:
    To test bit N in FIX(X)

 CATEGORY:
    Bits, Hardware

 CALLING SEQUENCE:
    YesNo = btest( X, N )

 PARAMETERS:  
    Inputs:
    	X      (REQ) (I) (0 1) (I  F)
           	X is the variable to be tested
   
    	N      (REQ) (I) (0) (I)
           	The bit of X to be tested
     Returned:
    	YESNO  (REQ) (O) (0 1) (I)
           	The result of the test. 1(true) if bit N is set, 0(false)
           	otherwise.

 EXAMPLES:

        YESNO = btest( !X.STYLE, 4 )
        IF YESNO THEN PRINT,'X-axis suppressed' $
                 ELSE PRINT,'Draw X-axis'

        To find points in NEWSIPS which are outside calibrated region:
        YESNO = btest( ABS(NU),1 )             ; look for nu flag = -2
        IND = WHERE (YESNO EQ 0)            ; keep points where yesno = 0
        PLOT,W(IND),F(IND)                  ; plot calibrated points
        
 NOTES:

     Note that negative integers are stored in twos complement form.
     Therefore, the left-most bits are ON rather than OFF as they are for 
     positive numbers. Input the absolute value of X is negative numbers 
     to avoid this problem. 

     This procedure can be used to check the values of complex
     IDL system variables such as ![XYZ].STYLE.

 PROCEDURE:

     Checks whether (FIX(X) OR (NOT 2^N)) = -1 to set the output
     flag YESNO.

 MODIFICATION HISTORY:
	26-Oct-99 Convert from btest to make a function (like FORTRAN)
     Mar  6 1983 RJP GSFC initial program
     Aug 24 1987 RWT GSFC add PARCHECK
     Mar  7 1988 CAG GSFC all VAX RDAF-style prolog
     Jul 13 1990 RWT GSFC Sun mods: use examples pertinent to SUN IDL
                 and add listing of procedure call statement
     Jun 19 1991 PJL GSFC cleaned up; tested on SUN and VAX; updated prolog
     Mar  8 1993 RWT GSFC modify to allow X & YESNO to be vectors and 
                 add documentation about negative numbers.

(See src/idl_cvs/btest.pro)


DECODE_GRAY

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       DECODE_GRAY
 PURPOSE:
  	Convert a gray-code value to an integer
 CATEGORY:
       Bits, CAMAC, Hardware, Stepper Motor Control
 CALLING SEQUENCE:
       IDL> int = DECODE_GRAY(grayCode)
 INPUTS:
       grayCode = number in gray code.  
 KEYWORD PARAMETERS:
     Optional Input:
	  NBits - # of bits to decode; defaults to 8
 OUTPUTS:
       int = returned integer                 			out
 COMMON BLOCKS:
       NONE
 EXAMPLES:
	IDL> print,DECODE_GRAY(1)
	       1
	IDL> print,DECODE_GRAY(2)
	       3
	IDL> print,DECODE_GRAY(255)
	     170
	IDL> print,DECODE_GRAY(255+512)
	     170
	IDL> print,DECODE_GRAY(255+512,nbits=16)
	     853
 NOTES:
	This can probably be sped up considerably.
 MODIFICATION HISTORY:
       26-Oct-99 Written by Bill Davis, PPPL

(See src/idl_cvs/decode_gray.pro)


MK_BITARRAY

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       mk_bitarray
 PURPOSE:
       Create an array of 1's & 0's corresponding to input bits set
	(works for negative numbers, too, unlike similar routines)
 CATEGORY:
       Bits
 CALLING SEQUENCE:
       IDL> array= mk_bitarray( input )
       IDL> array= mk_bitarray( input, nbits=5 )
 INPUTS:
       input = whatever; might be something like !X.STYLE  
 KEYWORD PARAMETERS:
	NBITS=nbits - length of returned array (default to input type)
	PRINT - if set, will print bits in groups of fours.
 OUTPUTS:
       Byte array containing 1's and 0's               	out
 COMMON BLOCKS:
       NONE
 EXAMPLE:
	IDL> print,mk_bitarray(3, nbits=8)
	   1   1   0   0   0   0   0   0
	IDL> dum = mk_bitarray( 1025, /print )'
	 1 0 0 0   0 0 0 0   0 0 1 0   0 0 0 0
 LIMITATION:
	Only works on a scalar.
 MODIFICATION HISTORY:
	05-Jun-00 default nbits to input type. add print keyword.
       30-Mar-99 Written by Bill Davis, PPPL

(See src/idl_cvs/mk_bitarray.pro)


SHOWBITS

[Previous Routine] [List of Routines]
  NAME:
       showbits
  PURPOSE:
       Given a byte or integer, return a vector of 8 or 16 values
       which are the binary representation of the value.
  CATEGORY:             
	Bits, Hardware
  USAGE:
	bitarr = SHOWBITS( invalue, /print )
  INPUT:
       invalue - The byte or integer value to check
  OUTPUT:
       bitarr  - The 8-element array with values set
                 if the bit is set
  KEYWORDS:
    (Optional)
	NtoShow - # of bits to show
  HISTORY:
	29-Oct-99 Converted to Function by Bill Davis, ntoshow added
       Written 1988 by M.Morrison
       13-Nov-92 (MDM) - Modified to allow integer*2 values
                         and to allow an array of values.
        7-Apr-94 (MDM) - Allow integer*4 values
       15-Aug-94 (MDM) - Corrected error from 7-Apr-94 mod which
                         did not allow an array of inputs
  LIMITATIONS:
	Only works for non-negative, fixed-point numbers

(See src/idl_cvs/showbits.pro)


Category: Colors

[List of Routines]


BETTERRAINBOW

[Next Routine] [List of Routines]
 NAME:
       betterrainbow
 PURPOSE:
       Loads a rainbow color palette with 6 evenly-spaced (roughly) colors
 CATEGORY:
      Colors,  Graphics
 CALLING SEQUENCE:
       IDL> betterrainbow
 INPUTS:
       NONE  
 KEYWORD PARAMETERS:
    Optional Keywords:
	BAR - if set, will draw a color bar on plot
	nColors - # of colors to load (Defaults to !D.TABLE_SIZE)
	lessRed - if set, rainbow will have a smaller red region
	WhiteBottom - if set, there will be a white region at the bottom
	topColor - can be an index or 'white' or 'black'
	botColor - can be an index or 'white' or 'black'
	linePlots - if set, top color will be black and bottom color will be white
	noYellow - if set, don't have yellow (because doesn't show up well on white)
 OUTPUTS:
       NONE (color table changed)
 LIMITATIONS:
	always starts at the bottom of color palette.
 MODIFICATION HISTORY:
	18-Jun-2008 added NoYellow keyword
	02-Aug-2007 fix bug for /lineplot and ncolors<256; 
		    if /linePlots keyword set, reset !p.color & !p.background
	30-Apr-2007 added linePlots keyword
	26-May-2006 added ncolors and whiteBottom keywords
	14-Feb-2005 add topColor and botColor keywords
       15-Jul-02 Written by Bill Davis, PPPL

(See src/idl_cvs/betterrainbow.pro)


COLORBAR

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

 PURPOSE:
       The purpose of this routine is to add a color bar to the current
       graphics window.

 CATEGORY:
      Colors,  Graphics

 CALLING SEQUENCE:
       COLORBAR

 INPUTS:
       None.

 KEYWORD PARAMETERS:
       BOTTOM:       The lowest color index of the colors to be loaded in
                     the bar.
       CHARSIZE:     The character size of the color bar annotations. Default is 1.0.
       COLOR:        The color index of the bar outline and characters. Default
                     is !P.Color..
       DIVISIONS:     The number of divisions to divide the bar into. There will
                     be (divisions + 1) annotations. The default is 6.
       FONT:         Sets the font of the annotation. Hershey: -1, Hardware:0, True-Type: 1.
       FORMAT:       The format of the bar annotations. Default is '(I5)'.
       INVERTCOLORS: Setting this keyword inverts the colors in the color bar.
       MAXRANGE:     The maximum data value for the bar annotation. Default is
                     NCOLORS.
       MINRANGE:     The minimum data value for the bar annotation. Default is 0.
       MINOR:        The number of minor tick divisions. Default is 2.
       NCOLORS:      This is the number of colors in the color bar.
       POSITION:     A four-element array of normalized coordinates in the same
                     form as the POSITION keyword on a plot. Default is
                     [0.88, 0.10, 0.95, 0.90] for a vertical bar and
                     [0.10, 0.88, 0.90, 0.95] for a horizontal bar.
       RANGE:        A two-element vector of the form [min, max]. Provides an
                     alternative way of setting the MINRANGE and MAXRANGE keywords.
       RIGHT:        This puts the labels on the right-hand side of a vertical
                     color bar. It applies only to vertical color bars.
       TICKNAMES:    A string array of names or values for the tick marks.
       TITLE:        This is title for the color bar. The default is to have
                     no title.
       TOP:          This puts the labels on top of the bar rather than under it.
                     The keyword only applies if a horizontal color bar is rendered.
       VERTICAL:     Setting this keyword give a vertical color bar. The default
                     is a horizontal color bar.

 COMMON BLOCKS:
       None.

 SIDE EFFECTS:
       Color bar is drawn in the current graphics window.

 RESTRICTIONS:
       The number of colors available on the display device (not the
       PostScript device) is used unless the NCOLORS keyword is used.

 EXAMPLE:
       To display a horizontal color bar above a contour plot, type:

       LOADCT, 5, NCOLORS=100
       CONTOUR, DIST(31,41), POSITION=[0.15, 0.15, 0.95, 0.75], $
          C_COLORS=INDGEN(25)*4, NLEVELS=25
       COLORBAR, NCOLORS=100, POSITION=[0.15, 0.85, 0.95, 0.90]

 MODIFICATION HISTORY:

       Written by: David W. Fanning, 10 JUNE 96.
       [...]
       3/18/00. Moved a block of code to prevent a problem with color decomposition. DWF.
       4/28/00. Made !P.Font default value for FONT keyword. DWF.
       9/26/00. Made the code more general for scalable pixel devices. DWF.
       1/16/01. Added INVERTCOLORS keyword. DWF.
       5/11/04. Added TICKNAME keyword. DWF.
 AUTHOR:

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

(See src/idl_cvs/colorbar.pro)


COLORSEARCH

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

 PURPOSE:
       Return color index (or closest available) from the color name.

 CATEGORY:
      Colors,  Graphics

 CALLING SEQUENCE:
	index = colorSearch( colorName )

 INPUT:
       colorName: A string with the name of the color. 'WHITE','BLACK','YELLOW',
		'RED','GREEN','BLUE','MAGENTA','YELLOW','ORANGE', 'PURPLE', 
		'DARKGREEN','LTBLUE', or 'GREY'

       (colorName is NOT case sensitive)

	Synonyms are handled as follows:
         'GREY' = 'GRAY'
         'DARKGRAY' = 'GRAY'
         'CHARCOAL' = 'GRAY'
         'AQUAMARINE' = 'GREEN'
         'SKYBLUE' = 'LTBLUE'
         'LT_BLUE' = 'LTBLUE'
         'CYAN' = 'LTBLUE'
         'DKBLUE' = 'BLUE'
         'DARKBLUE' = 'BLUE'
         'DK_BLUE' = 'BLUE'
         'VIOLET' = 'MAGENTA'

    or, if colorName = 
          'FOREGROUND' then simply return, !p.color
          'BACKGROUND' then simply return, !p.background

 KEYWORD PARAMETERS:
	INIT - if set, will load color table 39 (rainbow with Black and white),
	       and !p.color will be set to black, and !p.background to white.
	       *** NOTE that the SET_PLOT command can change !p.color and !p.background.
 	debug - if set, will print informational messages
	quiet - if set, will not warn if color found is not close to that asked for
	status - if = 1, then color was found, else 0

 RESTRICTIONS:
	If match is not found it will return the index of the "closest" table location, and
	status=0, and, if /quiet is not set, it will print a warning.
	

       Note that the SET_PLOT command (from IDL Help):
          "sets the default color !P.COLOR to the maximum color index minus one or, 
	    in the case of devices with white backgrounds, such as PostScript, to 0 (black)."
	After calling SET_PLOT,'X' or SET_PLOT,'Z' you will have to re-call a=colorSearch( /init )
	to return to plotting black lines on a white background.
 EXAMPLES:
	plot, indgen(10), color=colorSearch( /init )
	oplot, indgen(10)/2, color=colorSearch('red')
 
 MODIFICATION HISTORY:
	26-Jan-2007 Written by Bill Davis, PPPL

(See src/idl_cvs/colorsearch.pro)


MK_COLOR

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

 PURPOSE:
       Create color tables with 12 fixed colors at the top. These colors
	can be referenced by name.

 CATEGORY:
      Colors,  Graphics

 CALLING SEQUENCE:
	index = mk_color( color )
	index = mk_color( color, TABLE=5, MAX_COLORS_TO_USE = 128 )
 OPTIONAL INPUTS:
       COLOR: A string with the name of the color. 'WHITE','BLACK','YELLOW',
                 'RED','GREEN','BLUE','MAGENTA','LTBLUE', and (if device
		   supports more than 8 colors) 'GREY' are allowed.
	       Alternately, COLOR may be an integer from 0 - 8.
              If the COLOR input is anything else, or not present, an index
	          for yellow is returned.
 KEYWORD PARAMETERS:
	LOAD:	If set, return a structure containing all 8 colors.
		e.g. IDL> c=MK_COLOR(/load)
		     IDL> plot,x,y,color=c.red
       MAX_COLORS_TO_USE: The maximum number of colors to use for all of
		IDL . The default
		is 64 so IDL doesn't grab all the colors on a 256-color
		monitor. If an IDL window, or a call to LOADCT, was made
		before the first call to mk_color, the number of colors
	        will already have been allocated.
	TABLE: The number of the pre-defined color table to load, from 0 to 40.
	       The same as for LOADCT. The default is 0.
	FILE:  If present, will load color table from this file.
	        These colors will be squeezed into the number of
		colors used for the palette (N_NONFIXED colors).
	N_NONFIXED (returned) number of colors other than the nine fixed ones.
		e.g., MAX_COLORS_TO_USE-12.
	SILENT: If this keyword is set, the Color Table message is suppressed.
	SEARCH - if set, will do a least squares fit to color table to find
		 closest index to color -- good if color table was set outside
	  	 of mk_color
	GAcolors - if set create a color table with colors beginning at zero, 
		   in the same order as GA color_setup routine.
 COMMON BLOCKS:
       mk_color_local

 SIDE EFFECTS:
       Limits the maximum number of colors for this IDL session.
	(The default is 64 colors).
 RESTRICTIONS:
	Reserving the right number of colors only works if this is called
	before any IDL window is drawn, and before LOADCT is called.

	Good Luck if you try and run with 24-bit color.

	If a device allows less than 12 colors (like Tek), the colors beyond
	the number allowed will not be available.
 EXAMPLES:
    Simply:
	plot,indgen(100),color=mk_color('red'),background=mk_color('white')
    or:
	plot,[0,1],[0,10]-1
	for i=0,8 do oplot,[i,i],color=mk_color(i)	; to see all colors
    x-y overlays:
	PLOT,INDGEN(100),/NODATA, COLOR=MK_COLOR('blue')	; axes in blue
	PLOT,INDGEN(100), COLOR=MK_COLOR('red')			; data in red
	OPLOT,INDGEN(100)/2, COLOR=MK_COLOR('yellow')		; overlay yellow

    Using color contours AND x-y plots:
	array_2D = DIST(150)	; generate a test array
	yellow_index = mk_color( TABLE=5, MAX_COLORS_TO_USE = 128, $
		N_NONFIXED = n_nonfixed)
	WINDOW,  XSIZE=400, YSIZE=250				; make wide window
	TV, BYTSCL( array_2D, TOP = n_nonfixed-1 ), 25, 50  	; plot scaled 2-D image
	PLOT, HISTOGRAM(array_2D), COLOR=mk_color('LtBlue'),  $	; lt. blue axes
	   POSITION=[0.55, 0.15, 0.95, 0.95], /NOERASE, /NODATA
	OPLOT, HISTOGRAM(array_2D) > 10, COLOR=mk_color('Magenta')	; data in magenta
	whatever = mk_color(TABLE=39)	; change colors of contours, but not lines
 NOTES:
	Tek Colors are 0=black, 1=white, 2=red, 3=green, 4=blue,
		5=cyan, 6=magenta, 7=yellow, 8=orange.
 MODIFICATION HISTORY:
	24-May-04   moved creation of X-window when Z-buffer the device
		    (necessary when mk_color first called with PS or Z.)
	22-Apr-2004 fixed bug when Z-buffer set on first call.
	14-Nov-03 - fixed new bug for Tek colors.
	13-Mar-03 - if requested color not found, try to find black (instead of yellow)
		    if ask for 'FOREGROUND' or 'BACKGROUND' return !p values.
		    GAcolor Keyword for doing colors like GA (same order and position)
	20-Aug-02 - set !p.color & !p.background to previous colors (closest
		    r,g,b value), when called the first time, or when changing
		    color tables.  Add FILE keyword
	07-Mar-02 - Change !d.n_colors to !d.table_size
	08-May-01 - When in Tek, make !p.color=black (was going to index 15)
	23-Apr-01 - added three more colors (orange, purple, darkgreen)
	26-Jan-01 - limit structure returned to !d.n_colors (e.g., when=2).
	28-Sep-00 - Added bottom keyword (passes straight through to loadct)
	24-Jan-00 - If color found at multiple indices, return highest valid one
	02-Jan-00 - Both /LOAD and individual colors return valid indices in
		    24-bit mode.
	05-Oct-99 - BD Synonyms & Structure return as in new D. Fanning routine.
	09-Jun-99 - BD If desired color not found, return index of nearest color.
 	11-May-99 - BD make return valid values for 24-bit (decomposed) color
	28-Jan-99 - BD handle device with less than 9 colors.
	14-Dec-98 - BD allow COLOR input to be an integer from 0-8.
		        Return index of 0 when color not found in table.
	04-Dec-98 - Bill Davis changed GETCOLORS to load color table, return color
			index, etc.  Colors were added.
       GETCOLORS Written by: David Fanning, 10 February 96.

(See src/idl_cvs/mk_color.pro)


STRETCHSTEPS

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

 PURPOSE:
       stretch parts of the color tables into steps.

 CATEGORY:
       Colors, Image processing

 CALLING SEQUENCE:
       stretchsteps, Low, High, steps=n [, /CHOP]

 INPUTS:
       Low:    The lowest pixel value to use.  If this parameter is omitted,
               0 is assumed.  Appropriate values range from 0 to the number 
               of available colors-1.

       High:   The highest pixel value to use.  If this parameter is omitted,
               the number of colors-1 is assumed.  Appropriate values range 
               from 0 to the number of available colors-1.

 OPTIONAL INPUTS:
       Gamma:  Gamma correction factor.  If this value is omitted, 1.0 is 
               assumed.  Gamma correction works by raising the color indices
               to the Gamma power, assuming they are scaled into the range 
               0 to 1.
       steps:  number of steps/colors of the resulting color table (default=16)
 KEYWORD PARAMETERS:
       CHOP:   If this keyword is set, color values above the upper threshold
               are set to color index 0.  Normally, values above the upper 
               threshold are set to the maximum color index.

 OUTPUTS:
       No explicit outputs.

 COMMON BLOCKS:
       COLORS: The common block that contains R, G, and B color
               tables loaded by LOADCT, HSV, HLS and others.

 SIDE EFFECTS:
       Image display color tables are loaded.

 RESTRICTIONS:
       Common block COLORS must be loaded before calling stretchsteps.

 PROCEDURE:
       New R, G, and B vectors are created by linearly interpolating
       the vectors in the common block from Low to High.  Vectors in the 
       common block are not changed.

       If NO parameters are supplied, the original color tables are
       restored.

 EXAMPLE:
       Load the STD GAMMA-II color table by entering:

               LOADCT, 5

       Create and display and image by entering:

               TVSCL, DIST(300)

       Now adjust the color table with stretchsteps.  Make the entire color table
       fit in the range 0 to 70 by entering:

               stretchsteps, 0, 70

       Notice that pixel values above 70 are now colored white.  Restore the
       original color table by entering:

               stretchsteps

 MODIFICATION HISTORY:
	26-May-2006 Fixed green & blue switch & get color table rather than
		relying on common block [BD]
	18-Dec-2002 Modified RSI STRETCH.PRO [BD]
       DMS, RSI, Dec, 1983.
       DMS, April, 1987.       Changed common.
       DMS, October, 1987.     For unix.
       DMS, RSI, Nov., 1990.   Added GAMMA parameter.

(See src/idl_cvs/stretchsteps.pro)


WHITEOUT

[Previous Routine] [List of Routines]
 NAME:
       whiteout
 PURPOSE:
 	white-out a portion of the color table 
	-- defaults to the 5 lowest locs.
 CATEGORY:
      Colors,  Graphics
 CALLING SEQUENCE:
       IDL> whiteout
 INPUTS:
       NONE  
 KEYWORD PARAMETERS:
    Optional Keywords:
	loc - index within color table to start whiting out (Default=0)
	nlocs - number of locations to whiteout (Default=5
 OUTPUTS:
       NONE (color table changed)
 LIMITATIONS:
	Reloading color table will undo this.
 MODIFICATION HISTORY:
	May-2006 Written by Bill Davis, PPPL

(See src/idl_cvs/whiteout.pro)


Category: Compound widgets

[List of Routines]


CW_BGROUP3_6

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

 PURPOSE:
	CW_BGROUP3_6 is a compound widget that simplifies creating
	a base of buttons. It handles the details of creating the
	proper base (standard, exclusive, or non-exclusive) and filling
	in the desired buttons. Events for the individual buttons are
	handled transparently, and a CW_BGROUP3_6 event returned. This
	event can return any one of the following:
		- The Index of the button within the base.
		- The widget ID of the button.
		- The name of the button.
		- An arbitrary value taken from an array of User values.

 CATEGORY:
	Compound widgets.

 CALLING SEQUENCE:
		Widget = CW_BGROUP3_6(Parent, Names)

	To get or set the value of a CW_BGROUP3_6, use the GET_VALUE and
	SET_VALUE keywords to WIDGET_CONTROL. The value of a CW_BGROUP3_6
	is:

		-----------------------------------------------
		Type		Value
		-----------------------------------------------
		normal		None
		exclusive   	Index of currently set button
		non-exclusive	Vector indicating the position
				of each button (1-set, 0-unset)
		-----------------------------------------------


 INPUTS:
       Parent:		The ID of the parent widget.
	Names:		A string array, containing one string per button,
			giving the name of each button.

 KEYWORD PARAMETERS:

	BUTTON_UVALUE:	An array of user values to be associated with
			each button and returned in the event structure.
	COLUMN:		Buttons will be arranged in the number of columns
			specified by this keyword.
	EVENT_FUNCT:	The name of an optional user-supplied event function 
			for buttons. This function is called with the return
			value structure whenever a button is pressed, and 
			follows the conventions for user-written event
			functions.
	EXCLUSIVE:	Buttons will be placed in an exclusive base, with
			only one button allowed to be selected at a time.
	FONT:		The name of the font to be used for the button
			titles. If this keyword is not specified, the default
			font is used.
	FRAME:		Specifies the width of the frame to be drawn around
			the base.
	IDS:		A named variable into which the button IDs will be
			stored, as a longword vector.
	LABEL_LEFT:	Creates a text label to the left of the buttons.
	LABEL_TOP:	Creates a text label above the buttons.
	MAP:		If set, the base will be mapped when the widget
			is realized (the default).
	NONEXCLUSIVE:	Buttons will be placed in an non-exclusive base.
			The buttons will be independent.
	NO_RELEASE:	If set, button release events will not be returned.
	RETURN_ID:	If set, the VALUE field of returned events will be
			the widget ID of the button.
	RETURN_INDEX:	If set, the VALUE field of returned events will be
			the zero-based index of the button within the base.
			THIS IS THE DEFAULT.
	RETURN_NAME:	If set, the VALUE field of returned events will be
			the name of the button within the base.
	ROW:		Buttons will be arranged in the number of rows
			specified by this keyword.
	SCROLL:		If set, the base will include scroll bars to allow
			viewing a large base through a smaller viewport.
	SET_VALUE:	The initial value of the buttons. This is equivalent
			to the later statement:

			WIDGET_CONTROL, widget, set_value=value

	SPACE:		The space, in pixels, to be left around the edges
			of a row or column major base. This keyword is
			ignored if EXCLUSIVE or NONEXCLUSIVE are specified.
	UVALUE:		The user value to be associated with the widget.
	XOFFSET:	The X offset of the widget relative to its parent.
	XPAD:		The horizontal space, in pixels, between children
			of a row or column major base. Ignored if EXCLUSIVE
			or NONEXCLUSIVE are specified.
	XSIZE:		The width of the base. 
	X_SCROLL_SIZE:	The width of the viewport if SCROLL is specified.
	YOFFSET:	The Y offset of the widget relative to its parent.
	YPAD:		The vertical space, in pixels, between children of
			a row or column major base. Ignored if EXCLUSIVE
			or NONEXCLUSIVE are specified.
	YSIZE:		The height of the base. 
	Y_SCROLL_SIZE:	The height of the viewport if SCROLL is specified.

 OUTPUTS:
       The ID of the created widget is returned.

 SIDE EFFECTS:
	This widget generates event structures with the following definition:

		event = { ID:0L, TOP:0L, HANDLER:0L, SELECT:0, VALUE:0 }

	The SELECT field is passed through from the button event. VALUE is
	either the INDEX, ID, NAME, or BUTTON_UVALUE of the button,
	depending on how the widget was created.

 RESTRICTIONS:
	Only buttons with textual names are handled by this widget.
	Bitmaps are not understood.

 MODIFICATION HISTORY:
	15 June 1992, AB
	7 April 1993, AB, Removed state caching.

(See src/idl_cvs/cw_bgroup3_6.pro)


CW_PDLIST

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

 PURPOSE:
	CW_PDList is a compound widget that simplifies creating
	pulldown menus. It has a simpler interface than the XPDMENU
	procedure, which it is intended to replace. Events for the
	individual buttons are handled transparently, and a CW_PDList
	event returned. This event can return any one of the following:
               - The Index of the button within the base.
               - The widget ID of the button.
               - The name of the button.
		- The fully qualified name of the button. This allows
		  different sub-menus to contain buttons with the same
		  name in an unambiguous way.


 CATEGORY:
	Compound widgets.

 CALLING SEQUENCE:
	widget = CW_PDList(Parent, Desc)

 INPUTS:
       Parent:	The ID of the parent widget.
	Desc:	An array of strings or structures.  Each element contains
		a menu description with two fields, a flag field, and
		the name of the item.  If a structure, each element
		is defined as follows:
			{ CW_PDList_S, flags:0, name:'' }

		The name tag gives the name of button. The flags
		field is a two-bit bitmask that controls how the button is
		interpreted:

		    Value	   Meaning
		    -------------------------------------------
		     0     This button is neither the beginning
			   nor the end of a pulldown level.
		     1     This button is the root of a
                          sub-pulldown menu. The sub-buttons
			   start with the next button.
		     2     This button is the last button at the
			   current pulldown level. The next button
			   belongs to the same level as the current
			   parent button.
			   If none or empty string is specified as a
			   the name, the button is not created, but
			   the next button belongs to the upward level.
		     3     This button is the root of a sub-pulldown
			   menu, but it is also the last entry of
			   the current level.
		     4     Same as 0, above, except that this button will
			   be preceeded by a separator as with the SEPARATOR
			   keyword to WIDGET_BUTTON.
		     5     Same as 1, above, except that this button will
			   be preceeded by a separator.
		     6     Same as 2, above, except that this button will
			   be preceeded by a separator.
		     7     Same as 3, above, except that this button will
			   be preceeded by a separator.

	If Desc is a string, each element contains the flag field
	followed by a backslash character, followed by the menu item's
	contents.  See the example below.

	EVENT PROCEDURES:  An event procedure may be specified for an
	element and all its children, by including a third field
	in Desc, if Desc is a string array.  Events for buttons without
	an event procedure, are dispatched normally.
	See the example below.

 KEYWORD PARAMETERS:
	DELIMITER:        The character used to separate the parts of a
			  fully qualified name in returned events. The
			  default is to use the '.' character.
	FONT:		  The name of the font to be used for the button
			  titles. If this keyword is not specified, the
			  default font is used.
	HELP:		  If MBAR is specified and one of the buttons on the
			  menubar has the label "help" (case insensitive) then
			  that button is created with the /HELP keyword to
			  give it any special appearance it is supposed to
			  have on a menubar. For example, Motif expects
			  help buttons to be on the right.
	IDS:		  A named variable into which the button IDs will
			  be stored as a longword vector.
	MBAR:		  if constructing a menu-bar pulldown, set this
			  keyword.  In this case, the parent must be the 
			  widget id of the menu bar of a top-level base,
			  returned by WIDGET_BASE(..., MBAR=mbar).
	RETURN_ID:	  If present and non-zero, the VALUE field of returned
			  events will be the widget ID of the button.
	RETURN_INDEX:	  If present and non-zero, the VALUE field of returned
			  events will be the zero-based index of the button
			  within the base. THIS IS THE DEFAULT.
	RETURN_NAME:	  If present and non-zero, the VALUE field of returned
			  events will be the name of the selected button.
	RETURN_FULL_NAME: If present and non-zero, the VALUE field of returned
               	  events will be the fully qualified name of the
			  selected button. This means that the names of all
			  the buttons from the topmost button of the pulldown
			  menu to the selected one are concatenated with the
			  delimiter specified by the DELIMITER keyword. For
			  example, if the top button was named COLORS, the
			  second level button was named BLUE, and the selected
			  button was named LIGHT, the returned value would be

			  COLORS.BLUE.LIGHT

			  This allows different submenus to have buttons with
			  the same name (e.g. COLORS.RED.LIGHT).
	UVALUE:		  The user value to be associated with the widget.
       UNAME:            The user name to be associated with the widget.
	XOFFSET:	  The X offset of the widget relative to its parent.
	YOFFSET:	  The Y offset of the widget relative to its parent.

 OUTPUTS:
       The ID of the top level button is returned.

 SIDE EFFECTS:
	This widget generates event structures with the following definition:

		event = { ID:0L, TOP:0L, HANDLER:0L, VALUE:0 }

	VALUE is either the INDEX, ID, NAME, or FULL_NAME of the button,
	depending on how the widget was created.

 RESTRICTIONS:
	Only buttons with textual names are handled by this widget.
	Bitmaps are not understood.

 EXAMPLE:
	The following is the description of a menu bar with two buttons,
	"Colors" and "Quit". Colors is a pulldown containing the colors
	"Red", "Green", Blue", "Cyan", and "Magenta". Blue is a sub-pulldown
	containing "Light", "Medium", "Dark", "Navy", and "Royal":

		; Make sure CW_PDList_S is defined
		junk = { CW_PDList_S, flags:0, name:'' }

		; The description
		desc = [ { CW_PDList_S, 1, 'Colors' }, $
			     { CW_PDList_S, 0, 'Red' }, $
			     { CW_PDList_S, 0, 'Green' }, $
			     { CW_PDList_S, 5, 'Blue\BLUE_EVENT_PROC' }, $
			         { CW_PDList_S, 0, 'Light' }, $
			         { CW_PDList_S, 0, 'Medium' }, $
			         { CW_PDList_S, 0, 'Dark' }, $
			         { CW_PDList_S, 0, 'Navy' }, $
			         { CW_PDList_S, 2, 'Royal' }, $
			       { CW_PDList_S, 4, 'Cyan' }, $
			       { CW_PDList_S, 2, 'Magenta\MAGENTA_EVENT_PROC' }, $
			 { CW_PDList_S, 2, 'Quit' } ]

	The same menu may be defined as a string by equating the Desc parameter
	to the following string array:
	
	desc =[ '1\Colors' , $
		'0\Red' , $
		'0\Green' , $
		'5\Blue\BLUE_EVENT_PROC' , $
		'0\Light' , $
		'0\Medium' , $
		'0\Dark' , $
		'0\Navy' , $
		'2\Royal' , $
		'4\Cyan' , $
		'2\Magenta\MAGENTA_EVENT_PROC' , $
		'2\Quit'  ]


	The following small program can be used with the above description
	to create the specified menu:


		base = widget_base()
		menu = CW_PDList(base, desc, /RETURN_FULL_NAME)
		WIDGET_CONTROL, /REALIZE, base
		repeat begin
		  ev = WIDGET_EVENT(base)
		  print, ev.value
		end until ev.value eq 'Quit'
		WIDGET_CONTROL, /DESTROY, base
		end

	Note that independent event procedures were specified for
	the multiple Blue buttons (blue_event_proc), and the Magenta button 
	(magenta_event_proc).

 MODIFICATION HISTORY:
	18 June 1992, AB
	16 Jan 1995, DMS, Added MBAR keyword, event procedures,
			and menu descriptor strings.
	2 July 1995, AB, Added HELP keyword.
	3 September 1996, LP, Added button-less end of current level
	Apirl, 2003 copied from CW_PDMENU. added xsize & event_pro keywords.
		    setting showSelection keyword will cause the menu
		    selection to be displayed as the title of the button [BD]

(See src/idl_cvs/cw_pdlist.pro)


CW_PDMENU

[Previous Routine] [List of Routines]
 NAME:
	CW_PDMENU

 PURPOSE:
	CW_PDMENU is a compound widget that simplifies creating
	pulldown menus. It has a simpler interface than the XPDMENU
	procedure, which it is intended to replace. Events for the
	individual buttons are handled transparently, and a CW_PDMENU
	event returned. This event can return any one of the following:
               - The Index of the button within the base.
               - The widget ID of the button.
               - The name of the button.
		- The fully qualified name of the button. This allows
		  different sub-menus to contain buttons with the same
		  name in an unambiguous way.


 CATEGORY:
	Compound widgets.

 CALLING SEQUENCE:
	widget = CW_PDMENU(Parent, Desc)

 INPUTS:
       Parent:	The ID of the parent widget.
	Desc:	An array of strings or structures.  Each element contains
		a menu description with two fields, a flag field, and
		the name of the item.  If a structure, each element
		is defined as follows:
			{ CW_PDMENU_S, flags:0, name:'' }

		The name tag gives the name of button. The flags
		field is a two-bit bitmask that controls how the button is
		interpreted:

		    Value	   Meaning
		    -------------------------------------------
		     0     This button is neither the beginning
			   nor the end of a pulldown level.
		     1     This button is the root of a
                          sub-pulldown menu. The sub-buttons
			   start with the next button.
		     2     This button is the last button at the
			   current pulldown level. The next button
			   belongs to the same level as the current
			   parent button.
			   If none or empty string is specified as a
			   the name, the button is not created, but
			   the next button belongs to the upward level.
		     3     This button is the root of a sub-pulldown
			   menu, but it is also the last entry of
			   the current level.
		     4     Same as 0, above, except that this button will
			   be preceeded by a separator as with the SEPARATOR
			   keyword to WIDGET_BUTTON.
		     5     Same as 1, above, except that this button will
			   be preceeded by a separator.
		     6     Same as 2, above, except that this button will
			   be preceeded by a separator.
		     7     Same as 3, above, except that this button will
			   be preceeded by a separator.

	If Desc is a string, each element contains the flag field
	followed by a backslash character, followed by the menu item's
	contents.  See the example below.

	EVENT PROCEDURES:  An event procedure may be specified for an
	element and all its children, by including a third field
	in Desc, if Desc is a string array.  Events for buttons without
	an event procedure, are dispatched normally.
	See the example below.

 KEYWORD PARAMETERS:
	DELIMITER:        The character used to separate the parts of a
			  fully qualified name in returned events. The
			  default is to use the '.' character.
	FONT:		  The name of the font to be used for the button
			  titles. If this keyword is not specified, the
			  default font is used.
	HELP:		  If MBAR is specified and one of the buttons on the
			  menubar has the label "help" (case insensitive) then
			  that button is created with the /HELP keyword to
			  give it any special appearance it is supposed to
			  have on a menubar. For example, Motif expects
			  help buttons to be on the right.
	IDS:		  A named variable into which the button IDs will
			  be stored as a longword vector.
	MBAR:		  if constructing a menu-bar pulldown, set this
			  keyword.  In this case, the parent must be the 
			  widget id of the menu bar of a top-level base,
			  returned by WIDGET_BASE(..., MBAR=mbar).
	RETURN_ID:	  If present and non-zero, the VALUE field of returned
			  events will be the widget ID of the button.
	RETURN_INDEX:	  If present and non-zero, the VALUE field of returned
			  events will be the zero-based index of the button
			  within the base. THIS IS THE DEFAULT.
	RETURN_NAME:	  If present and non-zero, the VALUE field of returned
			  events will be the name of the selected button.
	RETURN_FULL_NAME: If present and non-zero, the VALUE field of returned
               	  events will be the fully qualified name of the
			  selected button. This means that the names of all
			  the buttons from the topmost button of the pulldown
			  menu to the selected one are concatenated with the
			  delimiter specified by the DELIMITER keyword. For
			  example, if the top button was named COLORS, the
			  second level button was named BLUE, and the selected
			  button was named LIGHT, the returned value would be

			  COLORS.BLUE.LIGHT

			  This allows different submenus to have buttons with
			  the same name (e.g. COLORS.RED.LIGHT).
	UVALUE:		  The user value to be associated with the widget.
       UNAME:            The user name to be associated with the widget.
	XOFFSET:	  The X offset of the widget relative to its parent.
	YOFFSET:	  The Y offset of the widget relative to its parent.

 OUTPUTS:
       The ID of the top level button is returned.

 SIDE EFFECTS:
	This widget generates event structures with the following definition:

		event = { ID:0L, TOP:0L, HANDLER:0L, VALUE:0 }

	VALUE is either the INDEX, ID, NAME, or FULL_NAME of the button,
	depending on how the widget was created.

 RESTRICTIONS:
	Only buttons with textual names are handled by this widget.
	Bitmaps are not understood.

 EXAMPLE:
	The following is the description of a menu bar with two buttons,
	"Colors" and "Quit". Colors is a pulldown containing the colors
	"Red", "Green", Blue", "Cyan", and "Magenta". Blue is a sub-pulldown
	containing "Light", "Medium", "Dark", "Navy", and "Royal":

		; Make sure CW_PDMENU_S is defined
		junk = { CW_PDMENU_S, flags:0, name:'' }

		; The description
		desc = [ { CW_PDMENU_S, 1, 'Colors' }, $
			     { CW_PDMENU_S, 0, 'Red' }, $
			     { CW_PDMENU_S, 0, 'Green' }, $
			     { CW_PDMENU_S, 5, 'Blue\BLUE_EVENT_PROC' }, $
			         { CW_PDMENU_S, 0, 'Light' }, $
			         { CW_PDMENU_S, 0, 'Medium' }, $
			         { CW_PDMENU_S, 0, 'Dark' }, $
			         { CW_PDMENU_S, 0, 'Navy' }, $
			         { CW_PDMENU_S, 2, 'Royal' }, $
			       { CW_PDMENU_S, 4, 'Cyan' }, $
			       { CW_PDMENU_S, 2, 'Magenta\MAGENTA_EVENT_PROC' }, $
			 { CW_PDMENU_S, 2, 'Quit' } ]

	The same menu may be defined as a string by equating the Desc parameter
	to the following string array:
	
	desc =[ '1\Colors' , $
		'0\Red' , $
		'0\Green' , $
		'5\Blue\BLUE_EVENT_PROC' , $
		'0\Light' , $
		'0\Medium' , $
		'0\Dark' , $
		'0\Navy' , $
		'2\Royal' , $
		'4\Cyan' , $
		'2\Magenta\MAGENTA_EVENT_PROC' , $
		'2\Quit'  ]


	The following small program can be used with the above description
	to create the specified menu:


		base = widget_base()
		menu = cw_pdmenu(base, desc, /RETURN_FULL_NAME)
		WIDGET_CONTROL, /REALIZE, base
		repeat begin
		  ev = WIDGET_EVENT(base)
		  print, ev.value
		end until ev.value eq 'Quit'
		WIDGET_CONTROL, /DESTROY, base
		end

	Note that independent event procedures were specified for
	the multiple Blue buttons (blue_event_proc), and the Magenta button 
	(magenta_event_proc).

 MODIFICATION HISTORY:
	18 June 1992, AB
	16 Jan 1995, DMS, Added MBAR keyword, event procedures,
			and menu descriptor strings.
	2 July 1995, AB, Added HELP keyword.
	3 September 1996, LP, Added button-less end of current level
	Apirl, 2003 added xsize & event_pro keywords. [BD]
	July, 2003 removed setting ids in structure in UVALUE

(See src/idl_cvs/cw_pdmenu.pro)


Category: Database

[List of Routines]


DB_COLUMNS

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

  PURPOSE:
	list database tables and columns in which the column name 
	contains a string.

  CATEGORY:
	Database

  USE: 
       IDL> info = db_columns( wildCard='te')
    or IDL> info = db_columns( 'te', /print)

  KEYWORDS:
	wildCard - string to match 
		  (do not include *'s or other wildcard strings)
	dataBase - database to search. Defaults to nstxlogs.
	print	 - if set, will print tables and columns fitting criteria

  WRITTEN Oct-2002 by Bill Davis

(See src/idl_cvs/db_columns.pro)


LOGBOOK_LIST_PLUS

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       logbook_list_plus
 PURPOSE:
       List info from the NSTX logbook (to a screen or file)
 CATEGORY:
       Database, NSTX
 CALLING SEQUENCE:
       IDL> logbook_list_plus, shot1=shot1, shot2=shot2, XP=XP,  $
		rundate=rundate, username=username,  $
		str1=str1, str2=str2, str3=str3, logical1=logical1, logical2=logical2, $
		database=database, include=include, outFile=outFile
 INPUTS:
	(none required)
 KEYWORD PARAMETERS:
   (all optional)
       shot1 - beginning shot, e.g., 120200
	shot2 - ending shot (if missing, will just search shot1) 
	XP - Typically the XP #, e.g., 5
	rundate - run date (YYYYMMDD), e.g., 20060426
	username - computer username of person who made the entry, e.g. 'KAYE'
	str1, str2, str3 - strings that must be in the comments for a shot to be included
	logical1, logical2, 'AND' or 'OR' between str1, 2, & 3
	include - if NOT=0 and USERNAME specified then include any entries satisfying 
		other criteria for which TOPIC='PHS OPS' or 'SESSION LEADER'
	database - defaults to 'NSTXLOGS'
	break - if set, lines longer than 72 characters will be broken at an earlier space
	outFile - string (if not present, data listed to screen)
 OUTPUTS:
       data to screen or file, if specified
 COMMON BLOCKS:
       NONE
 EXAMPLE:
	IDL> logbook_list_plus, shot1=120200		
	IDL> logbook_list_plus, rundate=20060426	; all shots from April 25, 2006
	IDL> logbook_list_plus, shot1=120200, shot2=130000, username='PAUL'
	IDL> logbook_list_plus, shot1=120200, /verb, /debug, outfile='temp.html'
 MODIFICATION HISTORY:
	25-Jul-2008  Removed RunID keyword, and added XP [BD]
	10-Jul-2008  Added "order by shot" to query, so all shots shown
	29-Nov-2007  Had to change supersep to wrap long lines
	28-Nov-2007  Written by Bill Davis, PPPL (some code from Josh Stillerman)

(See src/idl_cvs/logbook_list_plus.pro)


LOGBOOK_LIST

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       logbook_list
 PURPOSE:
       List info from the NSTX logbook (to a screen or file)
 CATEGORY:
       Database, NSTX
 CALLING SEQUENCE:
       IDL> logbook_list, shot1=shot1, shot2=shot2, runID=runID,  $
		rundate=rundate, username=username,  $
		str1=str1, str2=str2, str3=str3, logical1=logical1, logical2=logical2, $
		database=database, include=include, outFile=outFile
 INPUTS:
	(none required)
 KEYWORD PARAMETERS:
   (all optional)
       shot1 - beginning shot, e.g., 120200
	shot2 - ending shot (if missing, will just search shot1) 
	runID - Typically the XP #, e.g., 5
	rundate - run date (YYYYMMDD), e.g., 20060426
	username - computer username of person who made the entry, e.g. 'KAYE'
	str1, str2, str3 - strings that must be in the comments for a shot to be included
	logical1, logical2, 'AND' or 'OR' between str1, 2, & 3
	include - if NOT=0 and USERNAME specified then include any entries satisfying 
		other criteria for which TOPIC='PHS OPS' or 'SESSION LEADER'
	database - defaults to 'NSTXLOGS'
	break - if set, lines longer than 72 characters will be broken at an earlier space
	outFile - string (if not present, data listed to screen)
 OUTPUTS:
       data to screen or file, if specified
 COMMON BLOCKS:
       NONE
 EXAMPLE:
	IDL> logbook_list, shot1=120200		
	IDL> logbook_list, rundate=20060426	; all shots from Apri. 25, 2006
	IDL> logbook_list, shot1=120200, shot2=130000, username='PAUL'
 MODIFICATION HISTORY:
	29-Nov-2007  Had to change supersep to wrap long lines
	28-Nov-2007  Written by Bill Davis, PPPL (some code from Josh Stillerman)

(See src/idl_cvs/logbook_list.pro)


SYB_ENTRY

[Previous Routine] [List of Routines]
 NAME: SYB_ENTRY

 PURPOSE : Display/modify/create entries in the NSTX logbook database.

 CATEGORY:
	Database

 CALLING SEQUENCE:  
	IDL> SYB_ENTRY
	IDL> syb_entry, font=find_font(/courier,/bold, size=12)

 KEYWORD PARAMETERS: 
	DEFAULT='save_file' to restore settings.
	FONT = a font
	WARNING - if=0, will not display intial warning of  "RUN_INFO has not been run today"
	INITAL_QUERY - the initial query of the database, e.g. 
		'rundate=20070523 and VOIDED IS NULL'
	        defaults to current user, last day with 
		entries, topic in ('PHYS OPS','SESSION LEADER')) and  VOIDED IS NULL


 LIMITATIONS 

 About

  - ENTRY_DISPLAY is a widget based IDL procedure for
   looking at entries in the LOGBOOK database.  Its primary
   purpose is to display an up-to-date set of logbook entries
   during a run.

   The user specified the record selection criteria

   (Options->Display Options).  Whenever a new logbook
   entry is made, the display is automatically updated to
   include the new record(s) if they meet the criteria 
   (unless one is in a blocking entry widget).

   This tool allows the user to create new logbook entries.
   Chose 'Make Final Entry' from the Entry menu.

   In addition this tool can be used to void and edit
   existing logbook entries.  Select part of an entry in
   main display, and then choose 'Edit Entry' or
   'Void Entry' from the Entry menu.
   NOTE:  you may only void or edit entries which you have
          entered into the database! Send email to dbadmin to have other 
	   entries changed.
 
 NOTES
   To get a white background on text, you need certain commands in a .Xresources
   file. You can have these loaded under the file menu in syb_entry.

 MODIFICATION HISTORY:
	02-Oct-2008 only do an mdsconnect if mds_event_server not defined.
	20-May-2008 fixed Make Entry Options.
	12-May-2008 calling mdssetevent breaks the connection needed for the widget to 
		    recognize events, so now just spawn "setevent".
		    Requires that environmental variable mds_event_target be set.
		    (e.g. to birch.pppl.gov:8501) Tidied up several other issues
		    like consistancy of "Auto Updates" checkbox.
	27-Jul-2007 Added WARNING and INITIAL_QUERY keywords.
		    Added UPDATE button to MAKE_ENTRY widget, so entries can be made
		    in steps. Help added to CUSTOM QUERY window to aid searches.
	02-May-2007 changed default printing to your default printer. Added debug printing
	30-Apr-2007 fixed auto updates on Linux
	09-Apr-2007 Get Current shot from MDSplus, rather getting the largest
		    shot number from the database [BD]
	05-Mar-2007 Allow text with special characters 
		    ('%', '^', '$', '*', '@', '#', '(', '!', ')', '?', ';') to go 
		    into the logbook.
		    added some color buttons. [BD]
	22-Jan-2007 Make sure connect to an event server (default to europa:8501).
	18-Jul-2005 change !version.os to !version.os_family to pick up linux
	05-Mar-2004 Upon startup update the screen with a query [BD]
	02-Mar-2004 Font keyword added, and changed options to ascending order and
		    auto scroll = off (Bill Davis)
       Josh Stillerman 9/20/96  initial version
       Lew Randerson 1999-11-04 Convert from ENTRY_DISPLAY to SYB_ENTRY by 
                                  mimicking Stan Kaye's mods to create VMS SYB_ENTRY
                                ... Convert entry_display to syb_entry (*** default file = $HOME/SybEntry.dat ***)
                                                                       (*** strayed from sk default file handling ***)
                                ... Add GetCurrentDate
       Lew Randerson 1999-11-08 Change 'logbook' to 'nstxlogs'
       Lew Randerson 1999-11-16 Check for os when handling print options
	Lew Randerson 1999-11-17 Add event handling stuff
	Lew Randerson 2000-01-11 Fix typo in get_entry_text parameters
	Lew Randerson 2000-01-11 Put back 'RUN_INFO' check
	Lew Randerson 2000-01-11 Handle unix printing
                                Check hand.key exists

(See src/idl_cvs/syb_entry.pro)


Category: Dates

[List of Routines]


DATE2JD

[Next Routine] [List of Routines]
 NAME:
       DATE2JD
 PURPOSE:
       Convert a date string to Julian Day number.
 CATEGORY:
	Dates
 CALLING SEQUENCE:
       jd = date2jd(date)
 INPUTS:
       date = date string, e.g., '6/17/1951', '1951/6/17', or 19510617    
 KEYWORD PARAMETERS:
 OUTPUTS:
       jd = Returned Julian Day number.   out
 COMMON BLOCKS:
 NOTES:
       Note: date must contain month as a name of 3 or more leeters.
 MODIFICATION HISTORY:
	12-Feb-2008 handle input date of form 19510617 (yyymmdd)
	27-Nov-2006 Handle date of form 2006/4/28 [Bill Davis, PPPL]
       R. Sterner, 1996 Sep 15

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

(See src/idl_cvs/date2jd.pro)


DATE2YMD

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       DATE2YMD
 PURPOSE:
       Date text string to the numbers year, month, day.
 CATEGORY:
	Dates
 CALLING SEQUENCE:
       date2ymd,date,y,m,d, dateString=dateString
 INPUTS:
       date = date string.             in
 KEYWORD PARAMETERS:
	dateString - (OPTIONAL OUTPUT) of form yyyymmdd (e.g., 20030613)
 OUTPUTS:
       y = year number.                out
       m = month number.               out
       d = day number.         out
 COMMON BLOCKS:
 NOTES:
       Notes: The format of the date is flexible except that the
         month must be month name.
         Dashes, commas, periods, or slashes are allowed.
         Some examples: 23 sep, 1985     sep 23 1985   1985 Sep 23
         23/SEP/85   23-SEP-1985   85-SEP-23   23 September, 1985.
         Doesn't check if month day is valid. Doesn't
         change year number (like 86 does not change to 1986).
         Dates may have only 2 numeric values, year and day. If
         both year & day values are < 31 then day is assumed first.
         systime() can be handled: date2ymd,systime(),y,m,d
         For invalid dates y, m and d are all set to -1.
 MODIFICATION HISTORY:
   12-Feb-2008 handle input date of form 19510617 (yyymmdd)
   17-Apr-2006 - added keyword longDate for return of 20051014.
   14-Oct-2005 - fix to allow dates like 10/14/2005
   13-Jun-2003 - added keyword output of composite string of form
   		    yyyymmdd (e.g., 20030613)
   R. Sterner, 1994 Mar 29 --- Modified to handle arrays.
   RES 18 Sep, 1989 --- converted to SUN.
   25-Nov-1986 --- changed to REPCHR.
   Written by R. Sterner, 29 Oct, 1985.
   Johns Hopkins University Applied Physics Laboratory.

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

(See src/idl_cvs/date2ymd.pro)


FILETIME2DBTIME

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       fileTime2dbTime
 PURPOSE:
 	Return times in filetimes format in database format 
 CATEGORY:
	Dates, times
 CALLING SEQUENCE:
       seconds = filetime2dbtime( time )
 INPUTS:
       time - string in military style  '11:04' or '23:59' (no double quotes!)
 KEYWORDS
	addminutes - minutes to add (can be negative, but cannot cross midnight)
 OUTPUT
	time - string with AM or PM after it (no space between). This is the
	       format SQL queries want.
 EXAMPLE: 

	IDL> print,filetime2dbtime( '6:08',addminutes=-10)
	5:58AM
	IDL> print,filetime2dbtime( '13:35')
	1:35PM

 MODIFICATION HISTORY:
 	WRITTEN by 27-Nov-2006 Bill Davis

(See src/idl_cvs/filetime2dbtime.pro)


FROMIDLTIME

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	fromidltime
       
 PURPOSE:
       Convert from IDL-syle time (output from SYSTIME(0),
	to form of '06/14/2004 11:04:52'
 CATEGORY:
	Dates
 CALLING SEQUENCE:
       date_time = fromidlTIME( idldatetime )
 INPUTS:
       idldatetime - like Fri Oct 14 09:28:10 2005 (DEFAULTS to now)
 KEYWORD PARAMETERS:
	monthString - if set, return dateString as 1-Jan-1970
    optional output:
	secondsSince - seconds since 1/1/1970
	datestr - just the date string
 OUTPUTS:
	date_time - string line  '06/14/2004 11:04:52' (no double quotes!)
       
 NOTES:

 EXAMPLE: 
	IDL> print,fromidltime('Fri Oct 14 09:28:10 2005')
	10/14/2005 09:28:10

 MODIFICATION HISTORY:

	12-Feb-2008 added secondsSince and monthString keywords
 	WRITTEN 14-Oct-2005 by Bill Davis

(See src/idl_cvs/fromidltime.pro)


ISOTIME

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       ISOtime
 PURPOSE:
       Return time in ISO 8601 standard, assuming US East Coast. 
	(handles Daylight Savings time)
 CATEGORY:
       Dates
 CALLING SEQUENCE:
       IDL> timeStr = ISOtime( DateTime )
 INPUTS:
        DateTime - like "06/14/2004 11:04:52"
 KEYWORD PARAMETERS:
       Keywords:
 OUTPUTS:
       timeStr - like 2004-06-14T11:04:52.0-4:00
 COMMON BLOCKS:
       NONE
 EXAMPLE:
   IDL> print,isotime('06/14/2004 11:04:52')
	2004-06-14T11:04:52.0-4:00
 NOTES:
   The ISO standard includes the adjustment to Grenwich Mean Time, so
   you need to know whether Daylight Savings time is in affect.
   This includes routines to find last and first Sunday of a month.
   Assumes no fractions of seconds.
 MODIFICATION HISTORY:
       WRITTEN 19-Jan-2005 by Bill Davis, PPPL

(See src/idl_cvs/isotime.pro)


JD2DATE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       JD2DATE
 PURPOSE:
       Convert a Julian Day number to a date string.
 CATEGORY:
	dates
 CALLING SEQUENCE:
       date = jd2date(jd)
 INPUTS:
       jd = Julian Day number.       in
 KEYWORD PARAMETERS:
       Keywords:
         FORMAT = format string.  Allows output date to be customized.
            The following substitutions take place in the format string:
         Y$ = 4 digit year.
         y$ = 2 digit year.
         N$ = full month name.
         n$ = 3 letter month name.
         d$ = day of month number.
         W$ = full weekday name.
         w$ = 3 letter week day name.
 OUTPUTS:
       date = returned date string.  out
 COMMON BLOCKS:
 NOTES:
       Notes:
         The default format string is 'd$-n$-Y$' giving 24-Sep-1989
         Example: FORMAT='w$ N$ d$, Y$' would give 'Mon 
 MODIFICATION HISTORY:
       R. Sterner, 27 Feb, 1991

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

(See src/idl_cvs/jd2date.pro)


JD2YMD

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       JD2YMD
 PURPOSE:
       Find year, month, day from julian day number.
 CATEGORY:
	Dates
 CALLING SEQUENCE:
       jd2ymd, jd, y, m, d, dateString=dateString
 INPUTS:
       jd = Julian day number (like 2447000).     in
 KEYWORD PARAMETERS:
	dateString - (OPTIONAL OUTPUT) of form yyyymmdd (e.g., 20030613)
 OUTPUTS:
       y = year (like 1987).                      out
       m = month number (like 7).                 out
       d = day of month (like 23).                out
 COMMON BLOCKS:
 NOTES:
 MODIFICATION HISTORY:
	12-Feb-2008 added dateString optional output keyword
       Theo Brauers, 21 Sep, 1997 long loop index i
       R. Sterner, 30 Apr, 1993 --- cleaned up and allowed arrays.
       R. Sterner.  21 Aug, 1986.
       Johns Hopkins Applied Physics Lab.

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

(See src/idl_cvs/jd2ymd.pro)


LONG64DATE2STR

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       long64date2str
 PURPOSE:
 	Return date from a 64-bit longword, like 1112308040, as returned
	from file_info, in a more conventional format.
 CATEGORY:
	Dates
 CALLING SEQUENCE:
       dateString = long64date2str( long64date )
 INPUTS:
       long64date returned from file_ingo, e.g., 1112308040
 RETURNED:
       dateString - conventional date string, e.g. 02/18/2006
 KEYWORDS
	delim - (string) delimeter used for output (Default is /)
	twoDigitsForYear - if set, year will be last two digits of year
	filetime - time of day of file, e.g. 14:32:59
	year - year of file
	month - numerical month of file
	day - numerical day of file
 EXAMPLES: 

	IDL> print,long64date2str( 1112308040 )
	03/31/2005

	IDL> print,long64date2str( 1112308040, /twoDigitsForYear )
	03/31/05

 MODIFICATION HISTORY:
 	WRITTEN 3-Jan-2007 by Bill Davis

(See src/idl_cvs/long64date2str.pro)


LONGDATE2STR

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       longdate2str
 PURPOSE:
 	Return date from a longword, like 20060218, in a more conventional 
	format
 CATEGORY:
	Dates
 CALLING SEQUENCE:
       dateString = longdate2str( longDate )
 INPUTS:
       date in form yyyymmdd, e.g., 20060218
 RETURNED:
       dateString - conventional date string, e.g. 02/18/2006
 KEYWORDS
	delim - (string) delimeter used for output (Default is /)
	twoDigitsForYear - if set, year will be last two digits of year
 EXAMPLES: 

	IDL> print,longdate2str( 20060218 )
	02/18/2006

	IDL> print,longdate2str( 19951229, /twoDigitsForYear )
	12/29/95

 MODIFICATION HISTORY:
 	WRITTEN by 1-May-2006 Bill Davis

(See src/idl_cvs/longdate2str.pro)


MDSTIME2DBTIME

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       mdsTime2dbTime
 PURPOSE:
 	Convert date & time from MDSplus to database format 
 CATEGORY:
	Dates, times
 CALLING SEQUENCE:
       sqltime = mdsTime2dbTime( time )
 INPUTS:
       time - from MDSplus, e.g. '10-MAR-2008 09:50:46.36'
 KEYWORDS
 OUTPUT
	sqltime - in SQL format, e.g., Mar 10 2008 09:50AM
 EXAMPLE: 

	IDL> print,mdsTime2dbTime( '10-MAR-2008 09:50:46.36')
	MAR 10 2008 09:50AM

 MODIFICATION HISTORY:
 	WRITTEN by 10-Mar-2008 Bill Davis

(See src/idl_cvs/mdstime2dbtime.pro)


MONTHNAMES

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       MONTHNAMES
 PURPOSE:
       Returns a string array of month names.
 CATEGORY:
	Dates
 CALLING SEQUENCE:
       mnam = monthnames()
 INPUTS:
	monthNum - if present, just the name for this month returned
 KEYWORD PARAMETERS:
	nchars - max number of characters in month names
 OUTPUTS:
       mnam = string array of 13 items:     out
         ['Error','January',...'December']
 COMMON BLOCKS:
 NOTES:
 MODIFICATION HISTORY:
	28-Jan-2009 Added nchars keyword
	22-Feb-2006 Added monthNum optional input [BD]
       R. Sterner, 18 Sep, 1989

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

(See src/idl_cvs/monthnames.pro)


MONTHNUMBER

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       monthnumber
 PURPOSE:
       Returns a month number given a month name.
 CATEGORY:
	Dates
 CALLING SEQUENCE:
       monthNum = monthnumber(monthStr)
 INPUTS:
	monthStr - e.g., 'Dec', or 'MAR'
 KEYWORD PARAMETERS:
 OUTPUTS:
       monthNum = number of month, 1-12, or -1 if not found     	out
 COMMON BLOCKS:
 NOTES:
 MODIFICATION HISTORY:
       29-Jan-00 Written by Bill Davis

(See src/idl_cvs/monthnumber.pro)


TOIDLTIME

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	toidltime
       
 PURPOSE:
       Convert a date string to IDL time (output from SYSTIME(1),
	i.e., seconds since 1/1/1970
 CATEGORY:
	Dates
 CALLING SEQUENCE:
       seconds = TOIDLTIME( date_time )
 INPUTS:
       date_time - string line  '06/14/2004 11:04:52' (no double quotes!)
 KEYWORD PARAMETERS:
 OUTPUTS:
       seconds since 1/1/1970 (type long64)
 NOTES:

 EXAMPLE: 
	IDL> print, systime(0), long64(systime(1))
       Fri Oct 14 09:10:43 2005            1129295443
	IDL> print, TOIDLTIME('10/14/2005 09:10:43')

 MODIFICATION HISTORY:

 	WRITTEN 14-Oct-2005 by Bill Davis

(See src/idl_cvs/toidltime.pro)


WEEKDAY

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       WEEKDAY
 PURPOSE:
       Compute weekday given year, month, day.
 CATEGORY:
	Dates
 CALLING SEQUENCE:
       wd = weekday(y,m,d,[nwd])
 INPUTS:
       y, m, d = Year, month, day (Like 1988, 10, 31).      in
 KEYWORD PARAMETERS:
 OUTPUTS:
       wd = Returned name of weekday.                       out
       nwd = optional Weekday number.                       out
 COMMON BLOCKS:
 NOTES:
 MODIFICATION HISTORY:
       R. Sterner. 31 Oct, 1988.
       Johns Hopkins University Applied Physics Laboratory.
       RES 18 Sep, 1989 --- converted to SUN

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

(See src/idl_cvs/weekday.pro)


YMD2DATE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       YMD2DATE
 PURPOSE:
       Convert from year, month, day numbers to date string.
 CATEGORY:
	Dates
 CALLING SEQUENCE:
       date = ymd2date(Y,M,D)
 INPUTS:
       y = year number (like 1986).                         in
       m = month number (1 - 12).                           in
       d = day of month number (1 - 31).                    in
 KEYWORD PARAMETERS:
       Keywords:
         FORMAT = format string.  Allows output date to be customized.
            The following substitutions take place in the format string:
         Y$ = 4 digit year.
         y$ = 2 digit year.
         N$ = full month name.
         n$ = 3 letter month name.
         d$ = day of month number.
         0d$ = day of month number with leading 0 if < 10.
         W$ = full weekday name.
         w$ = 3 letter week day name.
	  dateStr - alternate input, like '20070931'
 OUTPUTS:
       date = returned date string (like 24-May-1986).      out
 COMMON BLOCKS:
 NOTES:
       Notes:
         The default format string is 'd$-n$-Y$' giving 24-Sep-1989
         Example: FORMAT='w$ N$ d$, Y$' would give 'Mon 
 MODIFICATION HISTORY:
	28-NOV-2007 Added DateStr keyword [ Bill Davis, PPPL ]
       ...
       RES 18 Sep, 1989 --- converted to SUN
       R. Sterner.  16 Jul, 1986.
       Johns Hopkins University Applied Physics Laboratory.

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

(See src/idl_cvs/ymd2date.pro)


YMD2JD

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       YMD2JD
 PURPOSE:
       From Year, Month, and Day compute Julian Day number.
 CATEGORY:
	Dates
 CALLING SEQUENCE:
       jd = ymd2jd(y,m,d)
 INPUTS:
       y = Year (like 1987).                    in
       m = month (like 7 for July).             in
       d = month day (like 23).                 in
 KEYWORD PARAMETERS:
 OUTPUTS:
       jd = Julian Day number (like 2447000).   out
 COMMON BLOCKS:
 NOTES:
 MODIFICATION HISTORY:
       R. Sterner,  23 June, 1985 --- converted from FORTRAN.
       Johns Hopkins University Applied Physics Laboratory.
       RES 18 Sep, 1989 --- converted to SUN

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

(See src/idl_cvs/ymd2jd.pro)


YRMONTHDAY

[Previous Routine] [List of Routines]
 NAME:
       yrmonthday
 PURPOSE:
       Return a string of YYYYMMDD from a date string.
 CATEGORY:
       Dates
 CALLING SEQUENCE:
       IDL> dateNumberString = yrmonthday(dateString)
 INPUTS:
       dateString = date in one of these formats:
			  '7-jun-2001'
			  'Mon Jan 14 15:22:05 2002'
			  '08Aug2002'
			  'Jun 30 2005'
	   (defaults to today) 
 OUTPUTS:
       dateNumberString = 8-character string of numbers:
		YYYYMMDD
 KEYWORDS
	time - returns time like  08:41:55
 EXAMPLE:
	IDL> print,yrmonthday()
	20020114
	IDL> print,yrmonthday('5-jun-2001')
	20010605
 NOTES:
 MODIFICATION HISTORY:
	31-Mar-06 allow form of 'Jun 30 2005' or 'June 30, 2005'
	16-Nov-04 added time keyword
	15-Jan-02 Allow for 2-digit years
       14-Jan-02 Written by Bill Davis, PPPL
	15-Aug-02 Modified for UNIX date format by Stan Kaye

(See src/idl_cvs/yrmonthday.pro)


Category: EPICS Channel Access Interface

[List of Routines]


CAGETCOUNTANDTYPE

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

 PURPOSE:
	This function returns the number of elements and data type of a
       Channel Access process variable.

 CATEGORY:
	EPICS Channel Access Interface

 CALLING SEQUENCE:
	Status = caGetCountAndType(pvname, count, type)

 INPUTS:
	pvname:	The name of the process variable for which information is to
               be returned.

 OUTPUTS:
	count:  The number of elements in the process variable. This is 1 for
               scalar process variables and more than 1 for arrays.

       type:   This is a 3 element array containing information about the data
               type of the process variable.
               type(0) = Channel access data type as defined in "cadef.h"
               type(1) = EZCA data type as defined in "ezca.h"
               type(2) = IDL/PV-WAVE data type as defined in size()
               These data types are as follows:

               Name    Channel Access      EZCA        IDL/PVWAVE
               String      0                 1             7
               Short       1                 2             2
               Float       2                 4             4
               Enum        3                 2 (short)     2 (short)
               Byte        4                 0             1
               Long        5                 3             3
               Double      6                 5             5

   The function return value of caGetCountAndType is a status value.  The
   status is 0 if the routine was successful (i.e. the process variable exists)
   and non-zero if the routine failed.

 SIDE EFFECTS:
	This routine will cause a Channel Access search to take place if this is
       the first time this process variable has been referenced.

 RESTRICTIONS:
       The channel access data type enum is mapped to EZCA and IDL short
       data types.  However, application programs can use this routine to
       determine if the native channel access data type is enum, and then
       use caGet(pvname, value, /string) to read the string equivalent of the
       process variable. Programs can also use
       caGetEnumStrings(pvname, strings) to read the strings for the all of
       the possible values of an enum process variable.

 PROCEDURE:
	This routine uses ezcaPvToChid() and then ca_element_count() and
       ca_field_type().
       Note that this routine always returns its values "immediately", even
       if it is called between a caStartGroup and caEndGroup.

 EXAMPLE:
       IDL> status = caGetCountAndType('test_mca1.VAL', count, type)
       IDL> print, status
       0                       ; Status = success
       IDL> print, count
       2048                    ; Array with 2048 elements
       IDL> print, type
           5       3       3   ; Long data type
 MODIFICATION HISTORY:
 	Written by:	Mark Rivers
	June 28, 1995

(See src/idl_cvs/ezcaIDL.pro)


CAGET

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

 PURPOSE:
	This function reads the value of a Channel Access process variable.

 CATEGORY:
	EPICS Channel Access Interface

 CALLING SEQUENCE:
	Status = caGet(pvname, value, /string, max=n)

 INPUTS:
	pvname:	The name of the process variable for which the value is to
               be returned.

 KEYWORD PARAMETERS:
	STRING:	Set this flag to force caGet to return a string, rather than
               a number.  This flag is particularly useful when the native
               channel access data type is ENUM (3), since the string is
               more descriptive than the number.

	MAX:    This keyword parameter is used to limit the number of
               values returned by caGet. caGet normally returns the native
               element count for a process variable. Setting MAX to a
               number less than this will cause caGet to return only the
               first MAX values in the array.

 OUTPUTS:
	value:  The value of the process variable. By default, caGet returns
               "value" with the native data type and number of elements
               of the process variable. It determines this information by
               calling caGetCountAndType().  Note that if caGet is called
               after calling caStartGroup but before calling caEndGroup then
               the IDL variable "value" is created, but will not actually
               contain the data until caEndGroup is called.

       The function return value of caGet is a status value.  The
       status is 0 if the routine was successful (i.e. the process variable
       exists) and non-zero if the routine failed.  If caGet is called from
       within an asynchronous group then the status return only indicates
       whether the operation was successfully queued.

 COMMON BLOCKS:
       EZCA_COMMON contains a flag (ingroup) which indicates if we
       are currently in an asynchronous group. This routine tests that flag.

 SIDE EFFECTS:
	This routine will causes a channel access search to take place if
       this is the first time this process variable has been referenced. It
       performs a ca_get, unless called as part of an asynchronous group.

 RESTRICTIONS:
       There are two important restrictions which must be kept in mind when
       calling caGet from inside a "group", i.e. after calling caStartGroup
       and before calling caEndGroup.

       1) The IDL "value" variable (i.e. the second parameter
       passed to caGet) must not be "re-used" or deleted before the call to
       caEndGroup. The reason for this is that EZCA has been passed the
       address of this variable as the location in which the data is to be
       copied when caEndGroup is called. Thus, this location must still
       point to a valid memory location when caEndGroup is called.
       If the "value" variable is re-used then IDL's behavior is
       unpredictable, and bus errors/access violations could occur.

       2) When using caGet to read strings, the data type returned will be
       a byte array, rather than a string.  The reason has to do with the
       manner in which IDL passes strings, which requires that EZCA actually
       be passed pointers to byte arrays. When caGet is called outside of a
       group it automatically converts the byte array to a string before
       returning the value. However when caGet is called inside of a group
       it cannot perform this conversion, since it cannot be done until after
       the data is read, which does not occur until caEndGroup is called.
       Thus, it is the user's responsibility to convert the data from a byte
       array to a string after calling caEndGroup. This is done very simply
       with the string() function. For more information see the example below.

 PROCEDURE:
	This routine uses ezcaGet().

 EXAMPLES:
       IDL> ; The following is an example of a single caGet
       IDL> status = caGet('test_mca1.VAL', value)

       IDL> ; The following is an example of a valid grouped operation
       IDL> ; It also shows how to handle strings.
       IDL> caStartGroup
       IDL> status = caGet('test_mca1.VAL', mca_value)
       IDL> status = caGet('test_vme1.DESC', vme_desc) ; This is a string PV
       IDL> status = caEndGroup()
       IDL> vme_desc = string(vme_desc)    ; Convert from byte array to string

       IDL> ; The following is an example of an INVALID grouped operation
       IDL> caStartGroup
       IDL> status = caGet('test_mca1.VAL', mca_value)
       IDL> status = caGet('test_vme1.VAL', vme_value)
       IDL> mca_value=0
       IDL> ; We have redefined mca_value, so the previous location is
       IDL> ; undefined. NO NOT DO THIS!
       IDL> status = caEndGroup()

 MODIFICATION HISTORY:
 	Written by:	Mark Rivers
	June 28, 1995

(See src/idl_cvs/ezcaIDL.pro)


CAGETTIMEOUT

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

 PURPOSE:
	This function returns the value of the EZCA Timeout parameter. This
       value determines the time parameter passed to ca_pend_io() in EZCA.
       In conjunction with the EZCA RetryCount parameter it determines how
       long EZCA will try to connect to a process variable before giving up.

 CATEGORY:
	EPICS Channel Access Interface

 CALLING SEQUENCE:
	timeout = caGetTimeout()

 INPUTS:
	None.

 OUTPUTS:
       The function return value of caGetTimeout is the floating point
       value of the EZCA Timeout parameter, in seconds.

 PROCEDURE:
	This routine uses ezcaGetTimeout().

 EXAMPLES:
       IDL> print, caGetTimeout()
       0.0500000

 MODIFICATION HISTORY:
 	Written by:	Mark Rivers
	June 28, 1995

(See src/idl_cvs/ezcaIDL.pro)


CASETTIMEOUT

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

 PURPOSE:
	This procedure sets the value of the EZCA Timeout parameter. This
       value determines the time parameter passed to ca_pend_io() in EZCA.
       In conjunction with the EZCA RetryCount parameter it determines how
       long EZCA will try to connect to a process variable before giving up.

 CATEGORY:
	EPICS Channel Access Interface

 CALLING SEQUENCE:
	caSetTimeout, timeout

 INPUTS:
	Timeout:  The timeout value in seconds (floating point).

 OUTPUTS:
       None

 PROCEDURE:
	This routine uses ezcaSetTimeout().

 EXAMPLES:
       IDL> caSetTimeout, .001

 MODIFICATION HISTORY:
 	Written by:	Mark Rivers
	June 28, 1995

(See src/idl_cvs/ezcaIDL.pro)


CAGETRETRYCOUNT

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

 PURPOSE:
	This function returns the value of the EZCA retry count parameter.
       In conjunction with the EZCA Timeout parameter it determines how
       long EZCA will try to connect to a process variable before giving up.

 CATEGORY:
	EPICS Channel Access Interface

 CALLING SEQUENCE:
	RetryCount = caGetRetryCount()

 INPUTS:
	None.

 OUTPUTS:
       The function return value of caGetRetryCount is the integer
       value of the EZCA RetryCount parameter.

 PROCEDURE:
	This routine uses ezcaGetRetryCount().

 EXAMPLES:
       IDL> print, caGetRetryCount()
       599

 MODIFICATION HISTORY:
 	Written by:	Mark Rivers
	June 28, 1995

(See src/idl_cvs/ezcaIDL.pro)


CASETRETRYCOUNT

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

 PURPOSE:
	This procedure sets the value of the EZCA RetryCount parameter.
       In conjunction with the EZCA Timeout parameter it determines how
       long EZCA will try to connect to a process variable before giving up.

 CATEGORY:
	EPICS Channel Access Interface

 CALLING SEQUENCE:
	caSetRetryCount, retrycount

 INPUTS:
	RetryCount: The integer retry count.

 OUTPUTS:
       None

 PROCEDURE:
	This routine uses ezcaSetRetryCount().

 EXAMPLES:
       IDL> caSetRetryCount, 100

 MODIFICATION HISTORY:
 	Written by:	Mark Rivers
	June 28, 1995

(See src/idl_cvs/ezcaIDL.pro)


CAPUT

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

 PURPOSE:
	This procedure writes a new value to a channel access process variable.

 CATEGORY:
	EPICS Channel Access Interface

 CALLING SEQUENCE:
	status = caPut(pvname, value)

 INPUTS:
	pvname:	The name of the process variable for which the new value
               is to be written

       value:  The new value to be written. In general this can be a scalar
               or array of any data type.  There are of course restrictions
               in that certain strings cannot be written to certain process
               variables, and some process variables cannot be passed arrays.

 KEYWORD PARAMETERS:
	WAIT:	Set this flag to force caPut to wait for a channel access
               callback.  The default is not to wait for a callback, using the
               ezca function ezcaPutOldCa.  The WAIT keyword results in a
               call to ezcaPut, which uses channel access callbacks.

 OUTPUTS:
       The function return value of caPut is a status value.  The
       status is 0 if the routine was successful (i.e. the process variable
       exists and a valid value was written) and non-zero if the routine
       failed.

 PROCEDURE:
	This routine uses ezcaPut(). The "nelem" and "type" parameters passed
       to ezcaPut are determined from the IDL data type and number of elements
       of the "value" parameter passed to caPut(). Strings are converted to
       to byte arrays before being passed.

 RESTRICTIONS:
       None.   caPut can be called inside a group, i.e. after calling
               caStartGroup and before calling caEndGroup.  The "value"
               variable passed to caPut can be immediately re-used when
               inside a group, since EZCA copies it to a private location.

 EXAMPLES:
       IDL> ; Put a linear ramp (findgen()) to a waveform process variable.
       IDL> status = caPut('my_waveform.VAL', findgen(100))

 MODIFICATION HISTORY:
 	Written by:	Mark Rivers
	June 28, 1995
       Sept. 16, 1998  Mark Rivers  Added WAIT keyword, made non-callback
                                    version of caput the default

(See src/idl_cvs/ezcaIDL.pro)


CASTARTGROUP

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

 PURPOSE:
	This procedure starts an "asynchronous group".  Within an asynchronous
       group all calls to caGet and caPut are asynchronous, i.e. they queue
       a request and return immediately without waiting for a reply from
       the channel access servers. Calling caEndGroup causes the queue to be
       flushed and waits for the replies. The use of asynchronous
       groups can greatly improve the efficiency of channel access. The user
       must be aware of the restrictions on caGet outlined under the
       description of that routine.

 CATEGORY:
	EPICS Channel Access Interface

 CALLING SEQUENCE:
	caStartGroup

 INPUTS:
	None.

 OUTPUTS:
       None

 COMMON BLOCKS:
       EZCA_COMMON contains a flag (ingroup) which indicates if we
       are currently in an asynchronous group. This routine sets that flag.

 PROCEDURE:
	This routine uses ezcaStartGroup().

 EXAMPLES:
       IDL> caStartGroup
       IDL> status = caget('test_ao1.SCAN', scan)
       IDL> status = caget('test_mca1.ERTM', ertm)
       IDL> ; Print out values - they will be zero.
       IDL> help, scan, ertm
       IDL> status = caEndGroup()
       IDL> ; Print out values after executing caEndGroup, they are non-zero
       IDL> help, scan, ertm
       Output:
           SCAN            INT       =        0
           ERTM            FLOAT     =      0.000000
           SCAN            INT       =        6
           ERTM            FLOAT     =       7.10000

 MODIFICATION HISTORY:
 	Written by:	Mark Rivers
	June 28, 1995

(See src/idl_cvs/ezcaIDL.pro)


CAENDGROUP

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

 PURPOSE:
	This function ends an "asynchronous group". See caStartGroup for more
       information on asynchronous groups.
       caEndGroup flushes the queue of caGet and caPut calls and waits for
       replies from the channel access servers.

 CATEGORY:
	EPICS Channel Access Interface

 CALLING SEQUENCE:
	stat = caEndGroup(status)

 INPUTS:
	None.

 OUTPUTS:
       The function return value is 0 if the operation was successful,
       otherwise it is the first encountered non-successful return code.
       The optional status parameter can be used to return the status code
       of each operation in the group.

 OPTIONAL OUTPUT PARAMETERS:
       status: If this optional parameter is present then it returns a
               array of status information, one for each channel access
               call in the group.

 COMMON BLOCKS:
       EZCA_COMMON contains a flag (ingroup) which indicates if we
       are currently in an asynchronous group. This routine clears that flag.

 PROCEDURE:
	If the status parameter is present then this routine uses
       ezcaEndGroupWithReport().  If the parameter is not present then
       the routine calls ezcaEndGroup().

 RESTRICTIONS:
       When the status parameter is present, and ezcaEndGroupWithReport() is
       called, there is no way to know in advance how many status values
       will be returned.  This routine passes a status array with 1024
       elements, and then truncates it to the actual length.  The maximum
       number of status values which can be retrieved is thus 1024. No errors
       will occur if an asynchronous group has more than 1024 calls, but
       only the first 1024 status values can be obtained.
       This is probably sufficient for most applications!

 EXAMPLES:
       IDL> caStartGroup
       IDL> status = caget('test_ao1.SCAN', scan)
       IDL> status = caget('test_mca1.ERTM', ertm)
       IDL> ; Print out values - they will be zero.
       IDL> help, scan, ertm
       IDL> status = caEndGroup()
       IDL> ; Print out values after executing caEndGroup, they are non-zero
       IDL> help, scan, ertm
       Output:
           SCAN            INT       =        0
           ERTM            FLOAT     =      0.000000
           SCAN            INT       =        6
           ERTM            FLOAT     =       7.10000

 MODIFICATION HISTORY:
 	Written by:	Mark Rivers
	June 28, 1995

(See src/idl_cvs/ezcaIDL.pro)


CASETMONITOR

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

 PURPOSE:
	This procedure sets a monitor on the specified process variable.
       This causes a channel access callback to execute whenever the value
       of that process variable changes.  Subsequent calls to caGet() after
       calling caSetMonitor will read the values provided by the callbacks,
       rather than reading from the IOC.

 CATEGORY:
	EPICS Channel Access Interface

 CALLING SEQUENCE:
	status = caSetMonitor(pvname)

 INPUTS:
	pvname: The name of the process variable on which to set the monitor.

 OUTPUTS:
       The function return value of caSetMonitor is a status value.  The
       status is 0 if the routine was successful (i.e. the process variable
       exists) and non-zero if the routine failed.

 PROCEDURE:
	This routine uses ezcaSetMonitor(). The "type" parameter required
       by ezcaSetMonitor is the native EZCA data type as determined
       by caGetCountAndType().

 EXAMPLES:
       IDL> status = caSetMonitor('test_ao1')
       IDL> status = caGet('test_ao1', value)

 MODIFICATION HISTORY:
 	Written by:	Mark Rivers
	June 28, 1995

(See src/idl_cvs/ezcaIDL.pro)


CACLEARMONITOR

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

 PURPOSE:
	This procedure clears a monitor on the specified process variable.
       It cancels the effect of caSetMonitor().

 CATEGORY:
	EPICS Channel Access Interface

 CALLING SEQUENCE:
	status = caClearMonitor(pvname)

 INPUTS:
	pvname: The name of the process variable on which to clear the monitor.

 OUTPUTS:
       The function return value of caClearMonitor is a status value.  The
       status is 0 if the routine was successful (i.e. the process variable
       exists) and non-zero if the routine failed.

 PROCEDURE:
	This routine uses ezcaClearMonitor(). The "type" parameter required
       by ezcaClearMonitor is the native EZCA data type as determined
       by caGetCountAndType().

 EXAMPLES:
       IDL> status = caClearMonitor('test_ao1')

 MODIFICATION HISTORY:
 	Written by:	Mark Rivers
	June 28, 1995

(See src/idl_cvs/ezcaIDL.pro)


CACHECKMONITOR

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

 PURPOSE:
	This function returns a non-zero value if there is a new (unread)
       monitor for this process variable, otherwise it returns zero.
       This function is particularly useful when a caGet() operation is
       expensive in time, e.g. reading large arrays.

 CATEGORY:
	EPICS Channel Access Interface

 CALLING SEQUENCE:
	state = caCheckMonitor(pvname)

 INPUTS:
	pvname: The name of the process variable on which to check the monitor.

 OUTPUTS:
       The function return value is zero if no new monitor value is available,
       and non-zero if a new monitor value is available.

 PROCEDURE:
	This routine uses ezcaNewMonitorValue(). The "type" parameter required
       by ezcaNewMonitorValue() is the native EZCA data type as determined
       by caGetCountAndType().

 EXAMPLES:
       IDL> state = caCheckMonitor('test_ao1',event)

 MODIFICATION HISTORY:
 	Written by:	Mark Rivers
	June 28, 1995

(See src/idl_cvs/ezcaIDL.pro)


CADEBUG

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

 PURPOSE:
	This procedure turns the EZCA debugging flag on or off. Turning on
       the debugging flag prints lots of information, which is mainly
       useful to developers.

 CATEGORY:
	EPICS Channel Access Interface

 CALLING SEQUENCE:
	caDebug, state

 INPUTS:
	state:  state=1 turns debugging on, state=0 turns debugging off.

 OUTPUTS:
       None

 PROCEDURE:
	This routine uses ezcaDebugOn() and ezcaDebugOff().

 EXAMPLES:
       IDL> caDebug, 1     ; Turn on debugging
       setting Debug
       IDL> status = caGet('test_ao1', value)
       ca_pend_event(0.000010)
       --start end-of-prologue() report
       ****** Start State:
       AutoErrorMessage T InGroup F Debug T Trace F ErrorLocation LastOnly ListPrint
       LastOnly TimeoutSeconds 0.050000
       Workp : 9cf970 trashme F (nxt 0)
       Channel_avail_hdr 0 :
       ...
       ...
       IDL> caDebug, 0 ; Turn off debugging

 MODIFICATION HISTORY:
 	Written by:	Mark Rivers
	June 28, 1995

(See src/idl_cvs/ezcaIDL.pro)


CATRACE

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

 PURPOSE:
	This procedure turns the EZCA trace flag on or off. Turning on
       the trace flag prints lots of information which is mainly useful
       to developers.  Setting the trace flag results in less
       verbose output than setting the debug flag (see caDebug).

 CATEGORY:
	EPICS Channel Access Interface

 CALLING SEQUENCE:
	caTrace, state

 INPUTS:
	state:  state=1 turns trace on, state=0 turns trace off.

 OUTPUTS:
       None

 PROCEDURE:
	This routine uses ezcaTraceOn() and ezcaTraceOff().

 EXAMPLES:
       IDL> caTrace, 1     ;Turn on trace
       setting Trace
       IDL> status = caGet('test_ao1', value)
       ca_pend_event(0.000010)
       find_channel() found >test_ao1<
       get_channel(): was able to find_channel()
       ca_pend_event(0.000010)
       ...
       ...
       IDL> caTrace, 0     ; Turn off trace

 MODIFICATION HISTORY:
 	Written by:	Mark Rivers
	June 28, 1995

(See src/idl_cvs/ezcaIDL.pro)


CAGETENUMSTRINGS

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

 PURPOSE:
	This function returns all of the choice strings associated with a
       Channel Access "enum" process variable. It is particularly useful
       for building menus of options.

 CATEGORY:
	EPICS Channel Access Interface

 CALLING SEQUENCE:
	Status = caGetEnumStrings(pvname, strings)

 INPUTS:
	pvname:	The name of the process variable for which the enum strings
               are to be returned. The native channel access data type of
               this process variable must be enum (3).

 OUTPUTS:
	strings: A string array containing the strings for each possible
               value of the enum variable.

       The function return value of caGetEnumStrings is a status value.  The
       status is 0 if the routine was successful (i.e. the process variable
       exists and is of type enum) and non-zero if the routine failed.

 SIDE EFFECTS:
	This routine causes a channel access read. It does not use the
       grouping mechanism of EZCA, i.e. it always executes immediately.

 RESTRICTIONS:
       There must be less than 16 enum strings and they must each be less
       than 26 characters.

 PROCEDURE:
	This routine uses ezcaPvToChid and then ca_get() with a request type
       of DBR_GR_ENUM.  The functionality required by this routine is not
       presently provided directly in EZCA, although it should probably be
       added.

 EXAMPLES:
       IDL> status = caGetEnumStrings('test_mca1.SCAN', strings)
       IDL> for i=0, n_elements(strings)-1 do print, strings(i)
       Passive
       Event
       I/O Intr
       10 second
       5 second
       2 second
       1 second
       .5 second
       .2 second
       .1 second

 MODIFICATION HISTORY:
 	Written by:	Mark Rivers
	June 28, 1995

(See src/idl_cvs/ezcaIDL.pro)


CAGETCONTROLLIMITS

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

 PURPOSE:
	This procedure reads the control limits for the specified channel
       access process variable.

 CATEGORY:
	EPICS Channel Access Interface

 CALLING SEQUENCE:
	status = caGetControlLimits(pvname, low, high)

 INPUTS:
	pvname: The name of the process variable from which to read the
               control limits.

 OUTPUTS:
       low:    The low control limit (double).

       high:   The high control limit (double).

       The function return value of caGetControlLimits is a status value.  The
       status is 0 if the routine was successful (i.e. the process variable
       exists) and non-zero if the routine failed.

 PROCEDURE:
	This routine uses ezcaGetControlLimits().

 EXAMPLE:
       IDL> status = caGetControlLimits('test_ao1', low, high)

 MODIFICATION HISTORY:
 	Written by:	Mark Rivers
	June 28, 1995

(See src/idl_cvs/ezcaIDL.pro)


CAGETGRAPHICLIMITS

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

 PURPOSE:
	This procedure reads the graphic limits for the specified channel
       access process variable.

 CATEGORY:
	EPICS Channel Access Interface

 CALLING SEQUENCE:
	status = caGetGraphicLimits(pvname, low, high)

 INPUTS:
	pvname: The name of the process variable from which to read the
               graphic limits.

 OUTPUTS:
       low:    The low graphic limit (double).

       high:   The high graphic limit (double).

       The function return value of caGetGraphicLimits is a status value.  The
       status is 0 if the routine was successful (i.e. the process variable
       exists) and non-zero if the routine failed.

 PROCEDURE:
	This routine uses ezcaGetGraphicLimits().

 EXAMPLE:
       IDL> status = caGetGraphicLimits('test_ao1', low, high)

 MODIFICATION HISTORY:
 	Written by:	Mark Rivers
	June 28, 1995

(See src/idl_cvs/ezcaIDL.pro)


CAGETPRECISION

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

 PURPOSE:
	This procedure reads the precision for the specified channel
       access process variable.

 CATEGORY:
	EPICS Channel Access Interface

 CALLING SEQUENCE:
	status = caGetPrecision(pvname, precision)

 INPUTS:
	pvname: The name of the process variable from which to read the
               precision.

 OUTPUTS:
       precision:  The precision (short).

       The function return value of caGetPrecision is a status value.  The
       status is 0 if the routine was successful (i.e. the process variable
       exists) and non-zero if the routine failed.

 PROCEDURE:
	This routine uses ezcaGetPrecision().

 EXAMPLE:
       IDL> status = caGetPrecision('test_ao1', precision)

 MODIFICATION HISTORY:
 	Written by:	Mark Rivers
	June 28, 1995

(See src/idl_cvs/ezcaIDL.pro)


CAGETSTATUS

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

 PURPOSE:
	This procedure reads the status parameters for a channel access
       process variable.

 CATEGORY:
	EPICS Channel Access Interface

 CALLING SEQUENCE:
	status = caGetStatus(pvname, timestamp, status, severity)

 INPUTS:
	pvname: The name of the process variable from which to read the
               status parameters.

 OUTPUTS:
       timestamp: The timestamp of the last time the record was processed
               lonarr(2).

       status: The status flag (int).

       severity: The severity flag (int).

       The function return value of caGetStatus is a status value.  The
       status is 0 if the routine was successful (i.e. the process variable
       exists) and non-zero if the routine failed.

 PROCEDURE:
	This routine uses ezcaGetStatus().

 EXAMPLE:
       IDL> status = caGetStatus('test_ao1', timestamp, status, severity)

 MODIFICATION HISTORY:
 	Written by:	Mark Rivers
	June 28, 1995

(See src/idl_cvs/ezcaIDL.pro)


CAGETUNITS

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

 PURPOSE:
	This procedure reads the units string for the specified channel
       access process variable.

 CATEGORY:
	EPICS Channel Access Interface

 CALLING SEQUENCE:
	status = caGetUnits(pvname, units)

 INPUTS:
	pvname: The name of the process variable from which to read the units.

 OUTPUTS:
       units:  The units (string).

       The function return value of caGetUnits is a status value.  The
       status is 0 if the routine was successful (i.e. the process variable
       exists) and non-zero if the routine failed.

 COMMON BLOCKS:
       EZCA_COMMON contains a flag (ingroup) which indicates if we
       are currently in an asynchronous group. This routine tests that flag.

 PROCEDURE:
	This routine uses ezcaGetUnits().

 EXAMPLE:
       IDL> status = caGetUnits('test_ao1', units)

 MODIFICATION HISTORY:
 	Written by:	Mark Rivers
	June 28, 1995

(See src/idl_cvs/ezcaIDL.pro)


CAERROR

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

 PURPOSE:
	This procedure controls error printing and returns error strings.

 CATEGORY:
	EPICS Channel Access Interface

 CALLING SEQUENCE:
	caError, err_string, /ON, /OFF, /PRINT, prefix=prefix

 INPUTS:
       None

 KEYWORD PARAMETERS:
       /ON
           Setting this switch turns on automatic error message printing
           on stdout.  Automatic printing is initially enabled.

       /OFF
           Setting this switch turns off automatic error message printing
           on stdout.

       /PRINT
           Setting this switch prints the last error message on stdout.

       prefix=prefix
           The prefix keyword can be used to pass a string which is prefixed
           to error messages printed with /PRINT or fetched via the optional
           output parameter.

 OPTIONAL OUTPUT PARAMETERS:
	err_string:
           If this parameter is present then it will contain the text of the
           last error message.

 COMMON BLOCKS:
       EZCA_COMMON contains a flag (ingroup) which indicates if we
       are currently in an asynchronous group. This routine tests that flag.

 PROCEDURE:
	This routine uses ezcaPerror(), ezcaAutoErrorMessageOn(),
       ezcaAutoErrorMessageOff(), and ezcaGetErrorString()

 EXAMPLE:
       IDL> ; Define a prefix and turn on error messages
       IDL> caError, prefix='My program', /ON
       IDL> ; Fetch the last error message
       IDL> caError, err_string

 MODIFICATION HISTORY:
 	Written by:	Mark Rivers
	June 28, 1995

(See src/idl_cvs/ezcaIDL.pro)


CAVERSION

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

 PURPOSE:
       This function returns the string of current version information
       about ezcaIDL

 CATEGORY:
       EPICS Channel Access Interface

 CALLING SEQUENCE:
       string = caVersion()

 INPUTS:
       None.

 OUTPUTS:
       Return the string which gives the version information about
       ezcaIDL, ezca, Ezca, and EPICS base verion number.

 PROCEDURE:
	This routine uses Ezca_version() from the ezcaScan library.

 EXAMPLE:
       IDL> print, caVersion()

 MODIFICATION HISTORY:
       Written by:     Ben-chin Cha   Dec, 1995

(See src/idl_cvs/ezcaIDL.pro)


CAINIT

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

 PURPOSE:
	This routine sets the channel access timeout used by list array
       functions defined in ezcaScan library.

 CATEGORY:
	EPICS Channel Access Interface

 CALLING SEQUENCE:
	caInit [,flag] [,help=help]

 INPUTS:
	flag:	Optional flag, if set to -1  ezcaScan library default timeout
               settings will be used.

 KEYWORD PARAMETERS:
     HELP:  If ,/HELP is set, on-line help will be displayed.

 OUTPUTS:
       None.

 COMMON BLOCKS:
       None.

 SIDE EFFECTS:
       This routine set the channel access timeout values used in the
       ezcaScan library.  This routine set the timeout to 3 seconds for
       lists of process variables, and sets the timeout for
       ca_pend_event to 0.001 second.

       If a value of -1 is specified for the flag, the default value
       of 10 seconds for lists of process variables will be used.

 RESTRICTIONS:
       None.

 PROCEDURE:
	This routine uses Ezca_init() from the ezcaScan library.

 EXAMPLES:
       IDL> caInit

 MODIFICATION HISTORY:
 	Written by:	Ben-chin Cha     Dec, 1995

(See src/idl_cvs/ezcaIDL.pro)


CAPENDEVENT

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

 PURPOSE:
	This function causes the Ezca to call channel access ca_pend_event
       function.

 CATEGORY:
	EPICS Channel Access Interface

 CALLING SEQUENCE:
	caPendEvent [,time=0.001] [,help=help]

 INPUTS:
       None.

 KEYWORD PARAMETERS:
       TIME:  This keyword parameter is used to reset the timeout in seconds
              used by ca_pend_event in ezcaScan library.

       HELP:  If ,/HELP is set, on-line help will be displayed.

 OUTPUTS:
       None.

 COMMON BLOCKS:
       None.

 SIDE EFFECTS:
       This routine sets the timeout for event monitor routines used in
       ezcaScan library and calls the ca_pend_event.

 RESTRICTIONS:
	Positive time must be used.

 PROCEDURE:
	This routine uses Ezca_setPendTime() from the ezcaScan library.

 EXAMPLES:
       IDL> caPendEvent, time=0.0001

 MODIFICATION HISTORY:
 	Written by:	Ben-chin Cha      Dec, 1995

(See src/idl_cvs/ezcaIDL.pro)


CAPENDIO

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

 PURPOSE:
	This routine sets the timeout used by ca_pend_io in array get/
       put used in ezcaScan library.

 CATEGORY:
       EPICS Channel Access Interface

 CALLING SEQUENCE:
       caPendIO, time=time, list_time=list_time

 INPUTS:
       None.

 KEYWORD PARAMETERS:
	TIME:   Use the TIME=time keyword to set the timeout waiting for
               channel access I/O for single process variable name.

	LIST_TIME: Use the LIST_TIME=list_time keyword to set the timeout
               waiting for channel access I/O for a list of PV names.

       HELP:   If ,/HELP is specified, on line help will be displayed.

 OUTPUTS:
       None.

 COMMON BLOCKS:
       None.

 SIDE EFFECTS:
       These times will be used in array get/put from then on in all
       ca_pend_io calls in ezcaScan library.

 RESTRICTIONS:
       Positive real times should be used in those keywords.

 PROCEDURE:
	This routine uses Ezca_setPendTime() from the ezcaScan library.

 EXAMPLES:
       IDL> caPendIO, time=0.1, list_time=3.
       IDL> caPendIO, /help

 MODIFICATION HISTORY:
 	Written by:	Ben-chin Cha      Dec, 1995

(See src/idl_cvs/ezcaIDL.pro)


CATIMESTAMP

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

 PURPOSE:
       This function returns the time stamp of corresponding value for
       the specified record name.

 CATEGORY:
	EPICS Channel Access Interface

 CALLING SEQUENCE:
	string = caTimeStamp(pvname)

 INPUTS:
       pvname:	The name of the process variable for which the timestamp is to
               be returned.

 KEYWORD PARAMETERS:
       None.

 OUTPUTS:
	string:  The function returns the time stamp string for the requested
                PV name.

 COMMON BLOCKS:
       None.

 SIDE EFFECTS:
	This routine will causes a channel access search to take place if
       this is the first time this process variable has been referenced.

 RESTRICTIONS:
       Only single PV name is allowed in input.

 PROCEDURE:
	This routine uses Ezca_timeStamp() from the ezcaScan library.

 EXAMPLES:
       IDL> print,caTimeStamp('chademoai1')

 MODIFICATION HISTORY:
 	Written by:	Ben-chin Cha      Dec, 1995

(See src/idl_cvs/ezcaIDL.pro)


CASEARCH

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

 PURPOSE:
       This function searches for a list of process variable names.
       It returns 0 if successful, returns -1 if failed.

 CATEGORY:
       EPICS Channel Access Interface

 CALLING SEQUENCE:
       Status = caSearch(pvname)

 INPUTS:
      pvname: The variable for a list of process variables for which the
              channel access search to be done.

 KEYWORD PARAMETERS:
       None.

 OUTPUTS:
       None.

 COMMON BLOCKS:
       None.

 SIDE EFFECTS:
       This routine will causes a channel access search to take place if
       this is the first time pvnames has been referenced.

 RESTRICTIONS:
       None.

 PROCEDURE:
       This routine uses Ezca_search_list() from the ezcaScan library.

 EXAMPLES:
       IDL> print,caSearch('chademoai1')
       IDL> x = ['chademoai1','chademoai2']
       IDL> status = caSearch(x)

 MODIFICATION HISTORY:
       Written by:	Ben-chin Cha      Dec, 1995
      04-11-96   bkc   Fix typo error names to name

(See src/idl_cvs/ezcaIDL.pro)


CAGETERROR

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

 PURPOSE:
       This function get CA return codes for a list of process variable names.
       Return code can be 0 or -1, 0 for success, -1 for failure.

 CATEGORY:
       EPICS Channel Access Interface

 CALLING SEQUENCE:
       Status = caGetError(Pvname,Err)

 INPUTS:
      Pvname: The variable for a list of process variables for which the
              channel access return code to be checked.

 KEYWORD PARAMETERS:
       None.

 OUTPUTS:
       Err:  The corresponding return code(s) for the Pvname(s) are returned.
             Returns array of 0 or 1. 0 indicates success, 1 indicates failed.

 COMMON BLOCKS:
       None.

 SIDE EFFECTS:
       This routine will causes a channel access search to take place if
       this is the first time pvnames has been referenced.

 RESTRICTIONS:
       None.

 PROCEDURE:
       This routine uses Ezca_get_error_array() from the ezcaScan library.

 EXAMPLES:
       IDL> print,caGetError('chademoai1')
       IDL> x = ['chademoai1','chademoai2']
       IDL> status = caGetError(x)

 MODIFICATION HISTORY:
       Written by:	Ben-chin Cha      Dec, 1995

(See src/idl_cvs/ezcaIDL.pro)


CAGETARRAY

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

 PURPOSE:
       This function reads values for a list of Channel Access process
       variable. It returns 0 if successful, returns -1 if failed.

 CATEGORY:
       EPICS Channel Access Interface

 CALLING SEQUENCE:
       Status = caGetArray(names,pdata,max=no,type=i,/TYPE,/EVENT)

 INPUTS:
       names:	The variable for a list of channel access PV names for which
               the array of data is to be returned.

 KEYWORD PARAMETERS:
      MAX:    Default to 1 for a list of PV names. If more than one values
              to be returned for a list of array type PV names, this keyword
              must be specified. If the `no' specified is greater than the
              native count, zeros will be padded in the output array.

              If only one PV name is input, then caGetArray returns
              the native element count for the process variable. Setting
              MAX to a number less than the native count this will cause
              caGetArray to return only the first MAX values for the PV.

      TYPE:   This keyword specifies the IDL data type to be returned by
              the output array. If not specified, it defaults to 5, i.e.
              double precision type of data will be returned by the
              output array.

                1 - byte      2 - short       3 - long      4 - float
                5 - double    7 - string

     /TYPE    Instead of type=i a user can use the IDL data type keyword
              directly, the data type keyword supercedes the type=i
              specification. Valid types given below

                            /double
                            /float
                            /string
                            /long
                            /short
                            /byte

    /EVENT    If specified use the ca_array_get_callback otherwise use
              the ca_array_get

 OUTPUTS:
     pdata:  The output variable,  pdata(max,noNames), returns the data
             array for the requested list of PV names. The `max' is the no
             of values specified by the keyword MAX, the `noNames' is the
             number of PV names in the input variable names.

 COMMON BLOCKS:
       None.

 SIDE EFFECTS:
       This routine will causes a channel access search to take place if
       this is the first time this process variable has been referenced.

 RESTRICTIONS:
       Only one type of data can be requested for a list of PV names.

 PROCEDURE:
	This routine uses Ezca_getArray() from the ezcaScan library.

 EXAMPLES:
       Three examples are given below.
       The first caGetArray call returns only the first value for each PV
       name, the second and third caGetArray call both returns 10 float
       values for each PV name

       IDL> names=['chademowf7','chademowf8']
       IDL> st = caGetArray(names,pdata)
       IDL> st = caGetArray(names,pdata,max=10,/float)
       IDL> st = caGetArray(names,pdata,max=10,type=4)

 MODIFICATION HISTORY:
       Written by:	Ben-chin Cha      Dec, 1995
      04-11-96     bkc    If array get failed, only the pvnames not found are
                          reported
      04-22-96     bkc    Replace caError by caGetError

(See src/idl_cvs/ezcaIDL.pro)


CAPUTARRAY

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

 PURPOSE:
       This function writes an array of data to a list of Channel Access
       process variable. It returns 0 if successful, else retuns -1.

 CATEGORY:
       EPICS Channel Access Interface

 CALLING SEQUENCE:
       Status = caPutArray(pvname, pdata, /event)

 INPUTS:
       pvname:	The variable specifies a list of process variables for
               which the input array of data is to be written to IOC.
       pdata:  Input data array. The data array must be consistant with
               the number of PV names defined in the pvname.

 KEYWORD PARAMETERS:
      EVENT:   If specified use the ca_array_put_callback otherwise
               use the ca_array_put.

 OUTPUTS:
      None.

 COMMON BLOCKS:
      None.

 SIDE EFFECTS:
       This routine will causes a channel access search to take place if
       this is the first time this process variable has been referenced.

 RESTRICTIONS:
       Thus, it is the user's responsibility to make sure the adequate
       pdata is provided for the pvname.

 PROCEDURE:
	This routine uses Ezca_putArray() from the ezcaScan library.

 EXAMPLES:
       In the following example write a string value '11' to two PV
       names: chademomask1.VAL  and chademoai2.VAL

       IDL> x = ['chademomask1', 'chademoai2']
       IDL> y = make_array(1, 2, /string)
       IDL> y(0) = '11'
       IDL> y(1) = '11'
       IDL> status = caPutArray(x,y)

       In the following example write values [1,2,3] to two waveform records
       names: chademowf2  and chademowf5

       IDL> x = ['chademowf2','chademowf5']
       IDL> y = make_array(3, 2)
       IDL> y(0,0) = [1,2,3]
       IDL> y(0,1) = [1,2,3]
       IDL> print,caPutArray(x,y)
       IDL> print,caGetArray(x,pd,max=10)
       IDL> print,pd

 MODIFICATION HISTORY:
       Written by:	Ben-chin Cha      Dec, 1995

(See src/idl_cvs/ezcaIDL.pro)


CASCAN

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

 PURPOSE:
       This function provides add/get/zero/clear monitor features on a
       scan record and a set of PV names.

 CATEGORY:
       EPICS Channel Access Interface

 CALLING SEQUENCE:
       Status = caScan(name,pvnames,nonames,npts,vals,op_keyword,max=no)

 INPUTS:
       name:   The name of the process variable which has control of
               triggering scan, e.g. the scan record name.
       pvnames: A list of detector process variables for which the values
                are to be monitored by the trigger name.

 KEYWORD PARAMETERS:
      ADD:     Set this flag /ADD  to add a complete set of monitor for
               name and pvnames.
               Return 0 if successful, -1 if failed, 1 if old monitor
               already existed. If succeeds, the output variable npts
               is set to the number of data to be detected, and the
               nonames is set to the number of PVs in pvnames.

      CLEAR:   Set this flag /CLEAR to clear the monitor set by add.
               Return 0 if successful, -1 if failed.

      GET:     Set this flag /GET to get scan array of monitor values back.
               Return -1 if failed, return 1 if scan is properly set up but
               not triggered yet, return >1 if real data detected.
               If succeeds, the npts is set to the number of data so far
               detected.

      ZERO:    Set this flag /ZERO to zero the allocated space.
               Return 0 for success, -1 for failure.

      MAX:     Specifies the max number of monitor values to be returned.
               If the trigger name is not a scan record, the max=no must
               be provided for this function.

 OUTPUTS:
     nonames:  This variable returns the number of PVs in pvnames.
     npts:     This variable returns the current number of data points
               detected by the scan record.
     vals:     This detector data array buff, vals(nonames,max), stores
               the detected data so far captured.

 COMMON BLOCKS:
       None.

 SIDE EFFECTS:
       This routine will causes a channel access search to take place if
       this is the first time this process variable has been referenced.

 RESTRICTIONS:
       None.

 PROCEDURE:
       This routine uses Ezca_scanAddMonitor(), Ezca_scanClearMonitor(),
       Ezca_scanGetMonitor(), and Ezca_scanZeroMonitor() from the Ezca
       library.

 EXAMPLES:
      For scan record type triggered scan

       IDL> print,caScan('name',pvnames,/add)
       IDL> print,caScan('name',pvnames,nonames,npts,vals,/get)
       IDL> print,caScan('name',pvnames,/zero)
       IDL> print,caScan('name',pvnames,/clear)

      For non-Scan record type triggered scan

       IDL> print,caScan('name',pvnames,/add,max=100)
       IDL> print,caScan('name',pvnames,nonames,npts,vals,/get,max=100)
       IDL> print,caScan('name',pvnames,/zero,max=100)
       IDL> print,caScan('name',pvnames,/clear,max=100)

 MODIFICATION HISTORY:
       Written by:	Ben-chin Cha      Dec, 1995

(See src/idl_cvs/ezcaIDL.pro)


CAMONITOR

[Previous Routine] [List of Routines]
 NAME:
       caMonitor

 PURPOSE:
       This function provides Add/Get/Check/Clear monitor features on a
       single PV or a list of PV names.

 CATEGORY:
       EPICS Channel Access Interface

 CALLING SEQUENCE:
       Status = caMonitor(name, vals, num, overflow, op_keyword,type_keyword, max=no)

 INPUTS:
       name:	The variable for a PV or a list of PV names.

 KEYWORD PARAMETERS:
     ADD:      Set /ADD to add CA monitor for the specified name.
               Return 0 for success, -1 for failure.

     CLEAR:    Set /CLEAAR to clear CA monitor for the specified name.
               Return 0 for success, -1 for failure.

     CHECK:    Set /CHECK to check for new event for the specified name.
               Return 0 for success, -1 for failure.
               The ouput variable 'vals' contains the return event flags.
                 0 - flags no new event detected
                 1 - flags new event detected

     GET:      Set /GET to get monitor values back for the specified name.
               Different type of monitor returns different vals array.
               If non queue type monitor set, the vals array returns a
               single value for each PV in the name variable.
               If the kewword /QUEUE is specified, in addition of vals,
               both num and overflow variables are also returned.

     QUEUE:	Set /QUEUE flag to queue the value change event for the
               monitored single channel until the user gets them.

     MAXQUEUE: The MAXQUEUE=no must be specified if /QUEUE is specified.

     MODE:     This flag indicates what type of monitor queue is desired.
               The MODE=i where i can be 1/2/3, it defaults to 1. The
               MODE=1 or 2 monitor fills the QUEUE buff until it is fulled.
               If MODE=1, the /GET will clear the QUEUE buff.
               IF MODE=2, the /GET will not clear the QUEUE buff.
               The MODE=3 uses the circulat buffer, it keeps the most
               current MAXQUEUE values in the queue buffer.

               Default Vals returned in double precision form.
     /INT      Return Vals converted to integer
     /LONG     Return Vals converted to long integer
     /BYTE     Return Vals converted to byte type 
     /FLOAT    Return Vals converted to float type 
     /STRING   Return Vals converted to string type

 OUTPUTS:
     vals:     Returns the array of data if either keyword /GET or /CHECK
               is specified

     num:      Returns the real number of data in the vals array for the
               /QUEUE mode

     overflow: Returns the buffer full indicator for the /QUEUE mode
               0 - vals queue buff is not full
               1 - vals queue buff is full

 COMMON BLOCKS:
       None.

 SIDE EFFECTS:
       This routine will causes a channel access search to take place if
       this is the first time this process variable has been referenced.

 RESTRICTIONS:
       All the PVs are monitored as double values in this function
       unless the PV is a DBR_STRING type then monitored as string type.
       For getting the monitored queue array, only a single PV name can
       be specified.  For non queue type monitor, only the first value
       for a PV can be returned by this function.  Use caGet to get
       array type of values back.

 PROCEDURE:
	This routine uses Ezca_monitorArrayAdd(), Ezca_monitorArrayGet(),
       Ezca_monitorArrayCheck(), Ezca_monitorArrayClear(), Ezca_queueAdd(),
       Ezca_queueGet(),Ezca_queueZero(), and Ezca_queueClear()
       from the ezcaScan library.

 EXAMPLES:
    Single value monitor

       IDL> print,caMonitor('chademoai1',/add)
       IDL> print,caMonitor('chademoai1',vals,/get)
       IDL> print,caMonitor('chademoai1',/clear)

    Use queue array monitor with maxqueue=100

       IDL> print, caMonitor('chademoai1',/add,/queue,maxqueue=100)
       IDL> print, caMonitor('chademoai1',vals,num,overflow,/get,/queue,maxqueue=100)
       IDL> print, caMonitor('chademoai1',/clear,/queue)

 MODIFICATION HISTORY:
       Written by:	Ben-chin Cha      Dec, 1995
       04-12-96    bkc   Modified on line help syntax
       04-07-99    bkc   Return monitor values specification:
                         /byte,/int,/long,/float,/string 

(See src/idl_cvs/ezcaIDL.pro)


Category: Events

[List of Routines]


EXECONEVENT

[Next Routine] [List of Routines]
 NAME:
       execonevent
 PURPOSE:
       Widget to spawn an executable (with shot as argument) when an MDSplus event occurs.
 CATEGORY:
       Events, MDSplus
 CALLING SEQUENCE:
	IDL> execOnEvent, kickOffEvent='bdtest', executable='/u/bdavis/cvs/idl_cvs/echoarg.exe'
       IDL> execonevent, events=['NSTX_SOC', 'my_event' ]
	IDL> execonevent, emailTo=['vlad@pppl.gov, joeshmoe@pppl.gov'], $
		events=['NSTX_ACQ_DONE', 'CAM1_DONE',  $
			'CAM2_DONE','CAM3_DONE','CAM4_DONE' ]
    to get e-mail when really important events are missed, e.g., :
	IDL>  execonevent,add=['TS_RAW_READY','PHOENIXGO_P1','MPTS_FIT_DONE', $
			       'TFMON_ACQ_DONE'], emailTo='joeshmoe@pppl.gov'
 INPUTS:
       none.  
 KEYWORD PARAMETERS:
    (optional) 
	TEST - if set, appends TEST to all events
       EVENTS_WANTED - Character array of events to watch for.
			defaults to ['NSTX_SOC', 'CAM1_DONE',
			'CAM2_DONE','CAM3_DONE','CAM4_DONE' ]
	EMAIL - email address for message if all events listed not set before next shot..
	NOCLEAR - if set, will not clear events when first event is recognized
	PRINT - if set, will print messages when events are recognized
	TIME - if set, will display time-of-day when event was declared
	add_events - if set, will add these event(s) to the default
	BIG - if set, fonts are big
	WALL - if set, events of interest for display wall, and big font
       GROUP_LEADER - Group_Leader ID
 OUTPUTS:
       none.
 NOTES:
       The time of day will be printed for the first event, and the other times
       will be cleared. Then the time difference will be printed as mm:ss, 
       so :12 would mean it came 12 seconds after the first event. 
 TESTING
	IDL> execonevent, EVENTS_WANTED=['MY_TEST_EVENT_1','MY_TEST_event_2'], $
			/Shots
	   and from a VMS computer:  
	IDL> SetMDSShotEvent,'MY_TEST_EVENT_1', 999999
 COMMON BLOCKS:
       none
 ROUTINES USED:
	MK_COLOR, usingXwindows, MDSEVENT
 EXAMPLE:
	IDL> execonevent
 LIMITATION:
	Shot numbers are only returned  when running on VMS currently.
 NOTES:
	As the events are declared, the boxes turn color.
 	When the first event in the list is recognized, the other boxes are
	set to yellow (unless /noClear was set). Shot numbers declared with 
	the events may optionally be displayed.
       The status fields are initially the background color.
	A program calling this routine, might want to save !D.WINDOW 
	before the TV commands and restore it immediately afterwards.
 MODIFICATION HISTORY:
	01-Oct-2008 Removed MDSconnect
	06-Mar-2006 Written by Bill Davis, PPPL

(See src/idl_cvs/execonevent.pro)


MONEVENTS VERSION TO RUN IN BATCH MODE.

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       monevents version to run in batch mode.
 PURPOSE:
       Widget to monitor occurrence of MDSplus events & optional Shot #,
	if passed with the event declaration. The time of the event can also
	be displayed.
 EXPLANATION:
	Lists various events related to an NSTX shot cycle (as a default). 
	As the events are declared, the boxes turn color.
 	When the first event in the list is recognized, the other boxes are
	set to yellow (unless /noClear was set). Shot numbers declared with 
	the events may optionally be displayed.
 CATEGORY:
       Events, MDSplus, Monitoring Widget
 CALLING SEQUENCE:
       IDL> monevents
  to get a small # of key events:
     IDL> monevents, EVENTS_WANTED=['NSTX_SOC',	      $
       	      'NSTX_TMINUS60',  'NSTX_SOD',	      $
       	      'NSTX_ACQ_STARTED' ,'PC_908C16N08_ACQ', $       ; Digitizer that EFIT needs
       	      'MPTS_FIT_DONE', 'NSTX_ACQ_DONE' ,      $
       	      'SFLIP_IN_TREE' ],		      $
       	      /SHOT, /NoClear
  to get Diagnostic events and labels:
     IDL> monevents_noxmanager, file_input='/u/bdavis/cvs/idl_cvs/eventlabelsdiags.txt', $
		      	tabs=0, maxper=12, /shot,  /noclear, /WebGifs, $
			outFile='NSTX_Diagnostic_Status.gif'

     IDL> monevents_noxmanager, file_input='/u/bdavis/cvs/idl_cvs/eventlabelssmall.txt', $
		      	tabs=0, maxper=12, /shot,  /noclear, /WebGifs, $
			outFile='NSTX_Diagnostic_Status_Example.gif'

  to get all MPTS-relevant events:
     IDL>  monevents,/shot,add=['NSTX_ABC', 'MPTS_FORCEFIT', $
             'NSTX_ABS','NSTX_KLC','TS_RAW_READY']
  to see all QCS at once:
     IDL> monevents,/qcs,tabs=0,maxper=22, /shot, clear_event='NSTX_SOC' ,/noclear
  for QCS testing:
     IDL>  monevents,/shot,add=['sflip_files','test2','qcs_test'],tabs=0,/nocle, $
                     logfile='$HOME/ShotCycleEvents.log'
  for watching TF timing:
     IDL>  monevents,/shot,tabs=0,/nocle, $
          EVENTS_WANTED=['NSTX_SOD','PC_908C36N02_ACQ','PC_908C36N06_ACQ',  $
		   'PC_908C36N10_ACQ','PC_908C36N14_ACQ','TFMON_ACQ_DONE'];  for monitoring TF joint events, with a logfile in your home directory:
  for watching EFIT timing:
     IDL> monevents,/shot,/noclear,tabs=0, $
          EVENTS_WANTED=['NSTX_SOD','PC_908C16N08_ACQ', 'FDIA_CALC_DONE', $
                  'OP_H908_01_ACQUIRED', 'OP_H908_02_ACQUIRED', 'OP_H908_04_ACQUIRED',   $
                  'OP_H908_05_ACQUIRED', 'OP_H908_07_ACQUIRED', 'OP_H908_08_ACQUIRED',   $
                  'OP_H908_09_ACQUIRED', 'OP_H908_11_ACQUIRED', 'OP_H908_13_ACQUIRED',   $
		   'PHOENIXGO_P1', 'MPTS_FIT_DONE', 'PHOENIXGO_P2V1',  $
		   'phoenixDone_p1', $
		   'NSTX_ACQ_DONE',   $
		   'phoenixDone_p2' ],  $
       	   logfile='$HOME/EfitEvents.log'

 INPUTS:
       none.  
 KEYWORD PARAMETERS:
    (optional) 
       EVENTS_WANTED - String array of events to watch for
	LABELS - strings array to display instead of events
	FILE_INPUT - a text file of events to watch for (labels can follow each, in quotes)
	   format like:
		NSTX_SOC	       "Start of Cycle"
		BA_L8212_01_ACQ	       "Bolometers"
		GS_908C28N14_ACQ       "Gas Injection"
               ...
	CLEAR_EVENT - event to clear green lights on (default to EVENTS_WANTED[0]
	ADD_EVENTS - these events will be added to default events.
	QCS - if set, will read the file for QCS events, and use all there.
	LogFile - will log events to this file.
	LogEvents - if set, and LogFile not set, will log events to MonEvens.log
	nCols - number of columns wanted. Will default to 15 per column
	maxPerCol - another way to determine # of columns. Default=15.
	tabs - will default to tabs if more than one column. if=0, all on 1.
	NOCLEAR - if set, will not clear text boxes when first event is recognized
	PRINT - if set, will print messages when events are recognized
	SHOWSHOTS - if set, will display shot numbers declared with the events
	TIME - if set, will display time-of-day when event was declared
	BIG - if set, fonts are big
	WALL - if set, events of interest for display wall, and big font
	GIFseconds - seconds between writes of GIF file of window contents
		(good for making web-accessible displays). If not present, don't make files
	WebGifs - if set, will create a gif (to be read from the web) whenever widget is
		  updated (DEFAULT=0)
       GROUP_LEADER - Group_Leader ID
	VERBOSE - if set, lots of information is output
 OUTPUTS:
       none.
 TESTING
	IDL> monevents, EVENTS_WANTED=['MY_TEST_EVENT_1','MY_TEST_event_2'], $
			/Shots
	   and from a VMS computer:  
	IDL> SetMDSShotEvent,'MY_TEST_EVENT_1', 999999
 COMMON BLOCKS:
       none
 ROUTINES USED:
	MK_COLOR, usingXwindows, MDSEVENT
 EXAMPLE:
	IDL> monevents
 LIMITATION:
	Shot numbers are only returned  when running on VMS currently.
 NOTES:
       The time of day will be printed for the first event, and the other times
       will be cleared. Then the time difference will be printed as mm:ss, 
       so :12 would mean it came 12 seconds after the first event. 

       The status fields are initially the background color.
	A real program might want to save !D.WINDOW before the TV commands
	and restore it immediately afterwards.
 MODIFICATION HISTORY:
	01-Oct-2008 Removed mdsconnect [BD]
	18-Aug-2008 Added labels to be displayed instead of events, if desired.
		    added WebGifs & GifSeconds keywords. Add
	10-Jul-2008 made logging of events clearer
	21-Feb-07 added /logevents and logfile as keywords
	08-Feb-06 Added clear_event keyword, and made it show up 1st in list
	09-Nov-05 added tabs and QCS keyword
	03-Feb-04 added wall keyword
	10-Feb-03 added keyword add_event [BD]
	14-Jun-01 Default to showing time
       20-Jul-00 Written by Bill Davis, PPPL

(See src/idl_cvs/monevents_noxmanager.pro)


MONEVENTS

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       monevents
 PURPOSE:
       Widget to monitor occurrence of MDSplus events & optional Shot #,
	if passed with the event declaration. The time of the event can also
	be displayed.
 EXPLANATION:
	Lists various events related to an NSTX shot cycle (as a default). 
	As the events are declared, the boxes turn color.
 	When the first event in the list is recognized, the other boxes are
	set to yellow (unless /noClear was set). Shot numbers declared with 
	the events may optionally be displayed.
 CATEGORY:
       Events, MDSplus, Monitoring Widget
 CALLING SEQUENCE:
       IDL> monevents
  to get a small # of key events:
     IDL> monevents, EVENTS_WANTED=['NSTX_SOC',	      $
       	      'NSTX_TMINUS60',  'NSTX_SOD',	      $
       	      'NSTX_ACQ_STARTED' ,'PC_908C16N08_ACQ', $       ; Digitizer that EFIT needs
       	      'MPTS_FIT_DONE', 'NSTX_ACQ_DONE' ,      $
       	      'SFLIP_IN_TREE' ],		      $
       	      /SHOT, /NoClear
  to get Diagnostic events and labels:
     IDL> monevents, file_input='/u/bdavis/cvs/idl_cvs/eventlabelsdiags.txt', $
		      tabs=0, maxper=12, /shot,  /noclear, /WebGifs

  to get all MPTS-relevant events:
     IDL>  monevents,/shot,add=['NSTX_ABC', 'MPTS_FORCEFIT', $
             'NSTX_ABS','NSTX_KLC','TS_RAW_READY']
  to see all MEMS at once:
     IDL> monevents,/MEMS,tabs=0, maxper=22, /shot, clear_event='NSTX_SOC' ,/noclear
  for MEMS testing:
     IDL>  monevents,/shot,add=['sflip_files','test2','qcs_test'],tabs=0,/nocle, $
                     logfile='$HOME/ShotCycleEvents.log'
  for watching TF timing:
     IDL>  monevents,/shot,tabs=0,/nocle, $
          EVENTS_WANTED=['NSTX_SOD','PC_908C36N02_ACQ','PC_908C36N06_ACQ',  $
		   'PC_908C36N10_ACQ','PC_908C36N14_ACQ','TFMON_ACQ_DONE'];  for monitoring TF joint events, with a logfile in your home directory:
  for watching EFIT timing:
     IDL> monevents,/shot,/noclear,tabs=0, $
          EVENTS_WANTED=['NSTX_SOD','PC_908C16N08_ACQ', 'FDIA_CALC_DONE', $
                  'OP_H908_01_ACQUIRED', 'OP_H908_02_ACQUIRED', 'OP_H908_04_ACQUIRED',   $
                  'OP_H908_05_ACQUIRED', 'OP_H908_07_ACQUIRED', 'OP_H908_08_ACQUIRED',   $
                  'OP_H908_09_ACQUIRED', 'OP_H908_11_ACQUIRED', 'OP_H908_13_ACQUIRED',   $
		   'PHOENIXGO_P1', 'MPTS_FIT_DONE', 'PHOENIXGO_P2V1',  $
		   'phoenixDone_p1', $
		   'NSTX_ACQ_DONE',   $
		   'phoenixDone_p2' ],  $
       	   logfile='$HOME/EfitEvents.log'

 INPUTS:
       none.  
 KEYWORD PARAMETERS:
    (optional) 
       EVENTS_WANTED - String array of events to watch for
	LABELS - strings array to display instead of events
	FILE_INPUT - a text file of events to watch for (labels can follow each, in quotes)
	   format like:
		NSTX_SOC	       "Start of Cycle"
		BA_L8212_01_ACQ	       "Bolometers"
		GS_908C28N14_ACQ       "Gas Injection"
               ...
	CLEAR_EVENT - event to clear green lights on (default to EVENTS_WANTED[0]
	ADD_EVENTS - these events will be added to default events.
	MEMS - if set, will read the file for MEMS events, and use all there.
	LogFile - will log events to this file.
	LogEvents - if set, and LogFile not set, will log events to MonEvens.log
	nCols - number of columns wanted. Will default to 15 per column
	maxPerCol - another way to determine # of columns. Default=15.
	tabs - will default to tabs if more than one column. if=0, all on 1.
	NOCLEAR - if set, will not clear text boxes when first event is recognized
	PRINT - if set, will print messages when events are recognized
	SHOWSHOTS - if set, will display shot numbers declared with the events
	TIME - if set, will display time-of-day when event was declared
	BIG - if set, fonts are big
	WALL - if set, events of interest for display wall, and big font
	GIFseconds - seconds between writes of GIF file of window contents
		(good for making web-accessible displays). If not present, don't make files
	WebGifs - if set, will create a gif (to be read from the web) whenever widget is
		  updated (DEFAULT=0)
	BD - display events favored by a certain programmer.
       GROUP_LEADER - Group_Leader ID
	VERBOSE - if set, lots of information is output
 OUTPUTS:
       none.
 TESTING
	IDL> monevents, EVENTS_WANTED=['MY_TEST_EVENT_1','MY_TEST_event_2'], $
			/Shots
	   and from a VMS computer:  
	IDL> SetMDSShotEvent,'MY_TEST_EVENT_1', 999999
 COMMON BLOCKS:
       none
 ROUTINES USED:
	MK_COLOR, usingXwindows, MDSEVENT
 EXAMPLE:
	IDL> monevents
 LIMITATION:
	Shot numbers are only returned  when running on VMS currently.
 NOTES:
       The time of day will be printed for the first event, and the other times
       will be cleared. Then the time difference will be printed as mm:ss, 
       so :12 would mean it came 12 seconds after the first event. 

       The status fields are initially the background color.
	A real program might want to save !D.WINDOW before the TV commands
	and restore it immediately afterwards.
 MODIFICATION HISTORY:
	01-Oct-2008 Removed mdsconnect [BD]
	18-Aug-2008 Added labels to be displayed instead of events, if desired.
		    added WebGifs & GifSeconds keywords. Add
	10-Jul-2008 made logging of events clearer
	21-Feb-07 added /logevents and logfile as keywords
	08-Feb-06 Added clear_event keyword, and made it show up 1st in list
	09-Nov-05 added tabs and QCS keyword
	03-Feb-04 added wall keyword
	10-Feb-03 added keyword add_event [BD]
	14-Jun-01 Default to showing time
       20-Jul-00 Written by Bill Davis, PPPL

(See src/idl_cvs/monevents.pro)


WATCHEVENTS

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       watchevents
 PURPOSE:
       Widget to monitor occurrence of MDSplus events. 
	If all events do not happen before next occurance of first event, 
	send e-mail.
 CATEGORY:
       Events, MDSplus
 CALLING SEQUENCE:
       IDL> watchevents, events=['NSTX_SOC', 'my_event' ]
	IDL> watchevents, emailTo=['vlad@pppl.gov, joeshmoe@pppl.gov'], $
		events=['NSTX_ACQ_DONE', 'CAM1_DONE',  $
			'CAM2_DONE','CAM3_DONE','CAM4_DONE' ]
    to get all MPTS-relevant events:
	IDL>  watchevents,/shot,/show,add=['NSTX_ABC', 'MPTS_FORCEFIT', $
		'NSTX_ABS','NSTX_KLC','TS_RAW_READY']
 INPUTS:
       none.  
 KEYWORD PARAMETERS:
    (optional) 
	TEST - if set, appends TEST to all events
       EVENTS_WANTED - Character array of events to watch for.
			defaults to ['NSTX_SOC', 'CAM1_DONE',
			'CAM2_DONE','CAM3_DONE','CAM4_DONE' ]
       GROUP_LEADER - Group_Leader ID
	NOCLEAR - if set, will not clear events when first event is recognized
	PRINT - if set, will print messages when events are recognized
	SHOWSHOTS - if set, will display shot numbers declared with the events
	TIME - if set, will display time-of-day when event was declared
	add_events - if set, will add these event(s) to the default
	BIG - if set, fonts are big
	WALL - if set, events of interest for display wall, and big font
 OUTPUTS:
       none.
 NOTES:
       The time of day will be printed for the first event, and the other times
       will be cleared. Then the time difference will be printed as mm:ss, 
       so :12 would mean it came 12 seconds after the first event. 
 TESTING
	IDL> watchevents, EVENTS_WANTED=['MY_TEST_EVENT_1','MY_TEST_event_2'], $
			/Shots
	   and from a VMS computer:  
	IDL> SetMDSShotEvent,'MY_TEST_EVENT_1', 999999
 COMMON BLOCKS:
       none
 ROUTINES USED:
	MK_COLOR, usingXwindows, MDSEVENT
 EXAMPLE:
	IDL> watchevents
 LIMITATION:
	Shot numbers are only returned  when running on VMS currently.
 NOTES:
	As the events are declared, the boxes turn color.
 	When the first event in the list is recognized, the other boxes are
	set to yellow (unless /noClear was set). Shot numbers declared with 
	the events may optionally be displayed.
       The status fields are initially the background color.
	A program calling this routine, might want to save !D.WINDOW 
	before the TV commands and restore it immediately afterwards.
 MODIFICATION HISTORY:
	08-Sep-08 removed mdsconnect.
	10-Jun-05 Converted from Monevents.pro for Vlad.
	03-Feb-04 added wall keyword
	10-Feb-03 added keyword add_event [BD]
	14-Jun-01 Default to showing time
       20-Jul-00 Written by Bill Davis, PPPL

(See src/idl_cvs/watchevents.pro)


WMHDWATCH

[Previous Routine] [List of Routines]
 NAME:
       wmhdwatch
 PURPOSE:
       Widget to monitor occurrence of MDSplus events. 
	If all events do not happen before next occurance of first event, 
	send e-mail.
 CATEGORY:
       Events, MDSplus
 CALLING SEQUENCE:
       IDL> wmhdwatch, events=['NSTX_SOC', 'my_event' ]
	IDL> wmhdwatch, emailTo=['vlad@pppl.gov, joeshmoe@pppl.gov'], $
		events=['NSTX_ACQ_DONE', 'CAM1_DONE',  $
			'CAM2_DONE','CAM3_DONE','CAM4_DONE' ]
    to get all MPTS-relevant events:
	IDL>  wmhdwatch,/shot,/show,add=['NSTX_ABC', 'MPTS_FORCEFIT', $
		'NSTX_ABS','NSTX_KLC','TS_RAW_READY']
 INPUTS:
       none.  
 KEYWORD PARAMETERS:
    (optional) 
	TEST - if set, appends TEST to all events
       EVENTS_WANTED - Character array of events to watch for.
			defaults to ['NSTX_SOC', 'CAM1_DONE',
			'CAM2_DONE','CAM3_DONE','CAM4_DONE' ]
       GROUP_LEADER - Group_Leader ID
	NOCLEAR - if set, will not clear events when first event is recognized
	PRINT - if set, will print messages when events are recognized
	SHOWSHOTS - if set, will display shot numbers declared with the events
	TIME - if set, will display time-of-day when event was declared
	add_events - if set, will add these event(s) to the default
	BIG - if set, fonts are big
	WALL - if set, events of interest for display wall, and big font
 OUTPUTS:
       none.
 NOTES:
       The time of day will be printed for the first event, and the other times
       will be cleared. Then the time difference will be printed as mm:ss, 
       so :12 would mean it came 12 seconds after the first event. 
 TESTING
	IDL> wmhdwatch, EVENTS_WANTED=['MY_TEST_EVENT_1','MY_TEST_event_2'], $
			/Shots
	   and from a VMS computer:  
	IDL> SetMDSShotEvent,'MY_TEST_EVENT_1', 999999
 COMMON BLOCKS:
       none
 ROUTINES USED:
	MK_COLOR, usingXwindows, MDSEVENT
 EXAMPLE:
	IDL> wmhdwatch
 LIMITATION:
	Shot numbers are only returned  when running on VMS currently.
 NOTES:
	As the events are declared, the boxes turn color.
 	When the first event in the list is recognized, the other boxes are
	set to yellow (unless /noClear was set). Shot numbers declared with 
	the events may optionally be displayed.
       The status fields are initially the background color.
	A program calling this routine, might want to save !D.WINDOW 
	before the TV commands and restore it immediately afterwards.
 MODIFICATION HISTORY:
	01-Oct-2008 Removed mdsconnect [BD]
	10-Jun-05 Converted from Monevents.pro for Vlad.
	03-Feb-04 added wall keyword
	10-Feb-03 added keyword add_event [BD]
	14-Jun-01 Default to showing time
       20-Jul-00 Written by Bill Davis, PPPL

(See src/idl_cvs/wmhdwatch.pro)


Category: files

[List of Routines]


FDECOMP

[Next Routine] [List of Routines]
 NAME:
	FDECOMP
 PURPOSE:
	Routine to decompose a file name for any operating system

 CATEGORY:
	Files, OS Specific, Strings
 CALLING SEQENCE:
	FDECOMP, filename, disk, dir, name, qual, version, [OSFamily = ]

 INPUT:
	filename - string file name, scalar

 OUTPUTS:
	All the output parameters are scalar strings
	disk - disk name, always '' on a Unix machine, scalar string
	dir - directory name, scalar string
	name - file name, scalar string
	qual - qualifier, set equal to the characters beyond the last "."
	version - version number, always '' on a non-VMS machine, scalar string

 OPTIONAL INPUT KEYWORD:
	OSFamily - one of the four scalar strings specifying the operating 
		system:  'vms','windows','MacOS' or 'unix'.    If not supplied,
		then OS_FAMILY() is used to determine the operating system.
 EXAMPLES:
	Consider the following file names 

	Unix:    file = '/rsi/idl40/avg.pro' 
	VMS:     file = '$1$dua5:[rsi.idl40]avg.pro;3
	Mac:     file = 'Macintosh HD:Programs:avg.pro'
	Windows: file =  'd:\rsi\idl40\avg.pro'
	
	then IDL> FDECOMP,  file, disk, dir, name, qual, version
	will return the following

		  Disk             Dir          Name        Qual     Version
	Unix:      ''            '/rsi/idl40/'  'avg'       'pro'       ''
	VMS:     '$1$dua5'       '[RSI.IDL40]'  'avg'       'pro'       '3'
	Mac:     'Macintosh HD'  ':Programs:'   'avg'       'pro'       ''
	Windows:    'd:'         \rsi\idl40\    'avg'       'pro'       ''

 NOTES:
	(1) All tokens are removed between
		1) name and qual  (i.e period is removed)
		2) qual and ver   (i.e. VMS semicolon is removed)
	(2) On VMS the filenames "MOTD" and "MOTD." are distinguished by the 
	    fact that qual = '' for the former and qual = ' ' for the latter.

 ROUTINES CALLED:
	Function GETTOK(), OS_FAMILY()
	Users with V4.0 or later can replace OS_FAMILY() with !VERSION.OS_FAMILY
 HISTORY
	version 1  D. Lindler  Oct 1986
	Include VMS DECNET machine name in disk    W. Landsman  HSTX  Feb. 94
	Converted to Mac IDL, I. Freedman HSTX March 1994
          

(See src/idl_cvs/fdecomp.pro)


GETFILETIME

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       getfiletime
 PURPOSE:
       return creation date and time of a file
 CATEGORY:
       files
 CALLING SEQUENCE:
       IDL> times = getfiletime(files=files)
 INPUTS:
      files - string array of filenames, needed unless list used
      list - alternate way: filename containing a list of files
      dir - if present, is prepended to filenames before finding
       
 KEYWORD PARAMETERS:
      print - if present, will print results
 OUTPUTS:
       times - string array of creation date and times of files, 
		e.g., 
 COMMON BLOCKS:
       NONE
 EXAMPLE:
	% /bin/ls -1 * > list.txt
	idl
	IDL> times = getfiletime( list='list.txt',/print )
	camerasbig Tue Oct  2 11:35:37 2007
	cpp Fri Nov  9 16:28:02 2007
	dothis.csh Tue Oct  2 11:33:37 2007
	...
 NOTES:
       When the routine is called with no parameters, or with the
	keyword hlp set, help information is printed.
 MODIFICATION HISTORY:
       16-Apr-2008 Written by Bill Davis, PPPL

(See src/idl_cvs/getfiletime.pro)


GETNEXTFILE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       getNextFile
 PURPOSE:
 	get next file in a directory, defaulting to alphabetic search
 CATEGORY:
       Files
 CALLING SEQUENCE:
       IDL> nextFile = getNextFile( inFile )
 INPUTS:
       input = filename with or without directory prefix
 KEYWORD PARAMETERS:
	numeric - if set will try to sort files numerically, so *_9.ext will
		   come before *_10.ext 
	back - if set will go back one in list
 OUTPUTS:
       nextFile               			out
 EXAMPLE:
	IDL> infile='/p/camdata/fastsoftxray/NSTX_119761/Frame_287.tif'
	IDL> nextFile = GetNextFile( inFile)

	IDL> infile='/p/camdata/fast_camera/shot000119681/NSTX000119681_35.tif'
	IDL> print, GetNextFile( inFile, /numeric)
 NOTES:
   	finds all files of the form AAAAAA_*.ext (if no "_" in file, just
	return next in alphabetical order)
 MODIFICATION HISTORY:
	29-Jun-2006 added back keyword
       20-Apr-2006 Written by Bill Davis, PPPL

(See src/idl_cvs/getnextfile.pro)


MKDATEDIR

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       mkdatedir
 PURPOSE:
       Make a directory of the form YYYYMMDD (if it doesnt't exist)
	and move files there if the files were last modified on that date. 
 CATEGORY:
       Files, Dates
 CALLING SEQUENCE:
       IDL> mkdatedir, path=path, prefix=prefix, ext=ext, date=date
 INPUTS:
       none
 KEYWORD PARAMETERS:
       PATH - directory
       PREFIX - file prefix for deletion
       EXT - file extension for deletion; file search will be path+prefix+'*.'+ext 
       DATE - date for search, of form yyyymmdd, e.g., 20050617 (default=TODAY)
	ALL - if set, all files will be moved to the right directory (overrides DATE)
       VERBOSE - if set, will print informational output
 OUTPUTS:
       none
 COMMON BLOCKS:
       NONE
 EXAMPLE:
	IDL> 
 NOTES:
 LIMITATIONS
	Only works on Unix/Linux
 MODIFICATION HISTORY:
	07-Mar-2007 Added keyword all
       22-Aug-2005 Written by Bill Davis, PPPL

(See src/idl_cvs/mkdatedir.pro)


MK_FILENAME

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       mk_filename
 PURPOSE:
       File names with system independent symbolic directories.
 CATEGORY:
	Files, OS Specific, File I/O
 CALLING SEQUENCE:
       f = mk_filename(symdir, name)
 INPUTS:
       symdir = symbolic directory name.   in
       name = file name.                   in
 KEYWORD PARAMETERS:
       Keywords:
         /NOSYM means directory given is not a symbolic name.
         OPSYS=os specifiy operating system to over-ride
           actual.  Use VMS, WINDOWS, or MACOS.  UNIX is default.
	  SUBDIR=s  Subdirectory below the symdir, e.g., SUBDIR='dir1/dir2'
         DELIM=c delimiter character between directory and
           file name.  This is returned.
 OUTPUTS:
       f = file name including directory.  out
 COMMON BLOCKS:
 NOTES:
       Notes: symdir is a logical name for VMS and
         an environmental variable for UNIX and WINDOWS.  Ex:
         DEFINE IDL_IDLUSR d0:[publib.idl]  for VMS
         set IDL_IDLUSR=c:\IDL\LIB\IDLUSR   for WINDOWS.
         setenv IDL_IDLUSR /usr/pub/idl     for UNIX.
         Then in IDL: f=mk_filename('IDL_IDLUSR','tmp.tmp')
         will be the name of the file tmp.tmp in IDL_IDLUSR.
 MODIFICATION HISTORY:
       R. Sterner,  4 Feb, 1991
       R. Sterner, 27 Mar, 1991 --- added /NOSYM
       R. Sterner, 21 May, 1991 --- If not a listed opsys assume unix.
       R. Sterner,  4 Jun, 1991 --- added DOS.
       R. Sterner,  2 Jul, 1991 --- added DELIM.
       R. Sterner, 17 Jan, 1992 --- added OPSYS= and avoided double //
       R. Sterner, 1994 Feb 7 --- Added MacOS.
       R. Sterner, 1994 Feb 14 --- Changed DOS to windows.
       B. Davis - nenamed from filename.pro. Added SUBDIR keyword

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

(See src/idl_cvs/mk_filename.pro)


NUMLINES

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	NUMLINES
 PURPOSE:
	Return the number of lines in a file

 CATEGORY:
       Files
 CALLING SEQUENCE:
	nl = NUMLINES( filename )
 INPUT:
	filename = name of file, scalar string
 OUTPUT:
	nl = number of lines in the file, scalar longword
		Set to -1 if the number of lines could not be determined
 METHOD:
	If Unix then spawn to wc; otherwise read 1 line at a time and count

 PROCEDURE CALLS:
	OS_FAMILY() - Determine if a unix system; Users with IDL V4.0 or later
		can replace this with !VERSION.OS_FAMILY
 MODIFICATION HISTORY:
	W. Landsman                              February 1996
 	07-Oct-98 BD Added StopOnError Keyword
				 in unix, handle stuff printed from .cshrc when spawning wc

(See src/idl_cvs/numlines.pro)


READ_ARRAY

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       read_array
 PURPOSE:
	Read a numeric array (1-D) from a text file
 CATEGORY:
       Files
 CALLING SEQUENCE:
       IDL> num_array = read_array(filename)
 INPUTS:
       filename = name of file containing lines of ascii data.
 KEYWORD PARAMETERS:
	nskip    - number of lines to skip before reading
	status - odd, if OK
 OUTPUTS:
       num_array = returned array of floating point values
 COMMON BLOCKS:
       NONE
 EXAMPLE:
	IDL> num_array = read_array( filename )
 NOTES:;
 MODIFICATION HISTORY:
       01-Aug-2008 Written by Bill Davis, PPPL

(See src/idl_cvs/read_array.pro)


READCOL

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

 PURPOSE:
	Read a free-format ASCII data file with columns of data into IDL 
	variables.  Lines of data not meeting the specified format (e.g. 
	comments) are ignored.  Columns may be separated by commas or spaces.
	Use READFMT to read a fixed-format ASCII file.   Use RDFLOAT for
	much faster I/O (but less flexibility).

 CATEGORY:
	Files

 CALLING SEQUENCE:
	READCOL, name, v1 [, v2, v3, v4, v5, ...  v25 , 
             FORMAT = , /DEBUG ,  /SILENT , SKIPLINE = , NUMLINE =, comment= ]

 INPUTS:
	NAME - Name of ASCII data file, scalar string.  In VMS, an extension of 
		.DAT is assumed, if not supplied.

 OPTIONAL INPUT KEYWORDS:
	FORMAT - scalar string containing a letter specifying an IDL type
		for each column of data to be read.  Allowed letters are 
		A - string data, B - byte, D - double precision, F- floating 
		point, I - integer, L - longword, and X - skip a column.
		(G & E equate to F)

		Columns without a specified format are assumed to be floating 
		point.  Examples of valid values of FMT are

	'A,B,I'        ;First column to read as 6 character string, then 
			1 column of byte data, 1 column integer data
	'L,L,L,L'       ;Four columns will be read as longword arrays.
	' '             ;All columns are floating point

	If a FORMAT keyword string is not supplied, then all columns are 
	assumed to be floating point.

	SILENT - Normally, READCOL will display each line that it skips over.
		If SILENT is set and non-zero then these messages will be 
		suppressed.
	DEBUG - If this keyword is non-zero, then additional information is
		 printed as READCOL attempts to read and interpret the file.
	SKIPLINE - Scalar specifying number of lines to skip at the top of file
		before reading.   Default is to start at the first line.
	COMMENT - skip if a line begins with this
	NUMLINE - Scalar specifying number of lines in the file to read.  
		Default is to read the entire file
	LINESSKIPPED - Ascii array of lines skipped
	TABDELIM - If set, then assume columns are delimitted by tabs

 OUTPUTS:
	V1,V2,V3,...V15 - IDL vectors to contain columns of data.
		Up to 25 columns may be read.  The type of the output vectors
		are as specified by FORMAT.

 EXAMPLES:
	Each row in a file POSITION.DAT contains a star name and 6 columns
	of data giving an RA and Dec in sexigesimal format.   Read into IDL 
	variables.     (NOTE: The star names must not contain internal spaces.)

	IDL> FMT = 'A,I,I,F,I,I,F'
	IDL> READCOL,'POSITION',F=FMT,name,hr,min,sec,deg,dmin,dsec  

	The HR,MIN,DEG, and DMIN variables will be integer vectors.

	Alternatively, all except the first column could be specified as
	floating point.

	IDL> READCOL,'POSITION',F='A',name,hr,min,sec,deg,dmin,dsec 

	To read just the variables HR,MIN,SEC
	IDL> READCOL,'POSITION',F='X,I,I,F',HR,MIN,SEC

 RESTRICTIONS:
	This procedure is designed for generality and not for speed.
	If a large ASCII file is to be read repeatedly, it may be worth
	writing a specialized reader.

	Columns to be read as strings must not contain spaces or commas, 
	since these are interpreted as column delimiters.  
	(UNLESS /TABDELIM is used). Use READFMT to read such files.

	Numeric values are converted to specified format.  For example,
	the value 0.13 read with an 'I' format will be converted to 0.

 PROCEDURES CALLED
	GETTOK(), NUMLINES(), REPCHR(), STRNUMBER(), ZPARCHECK

 REVISION HISTORY:
	16-Oct-2008 added status keyword
	24-Aug-99 Added LINESSKIPPED keyword
    10/99 Added TABDELIM keyword [Bill Davis]
	Written         W. Landsman                 November, 1988
	Modified	     J. Bloch 			June, 1991
	(Fixed problem with over allocation of logical units.)
	Added SKIPLINE and NUMLINE keywords  W. Landsman    March 92
	Read a maximum of 25 cols.  Joan Isensee, Hughes STX Corp., 15-SEP-93.
	Call NUMLINES() function W. Lansdman          Feb. 1996

(See src/idl_cvs/readcol.pro)


READ_FLOATS

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       read_floats
 PURPOSE:
      Read a list from a text file and return a floating-point array
 CATEGORY:
       Files
 CALLING SEQUENCE:
       IDL> floats = read_floats(filename)
 INPUTS:
       filename = name of file containing lines of ascii data.  
 KEYWORD PARAMETERS:
	HLP - When set, help information is printed.
	nskip - lines to skip 
	status - if even, then read was successful
 OUTPUTS:
       floats = returned array of floats - 1 per line             	out
 COMMON BLOCKS:
       NONE
 EXAMPLE:
	IDL> floats = read_floats( 'hans.txt', maxlines=500000 )
 NOTES:
 MODIFICATION HISTORY:
	26-Sep-2008 Written by Bill Davis, PPPL

(See src/idl_cvs/read_floats.pro)


READ_GENERIC

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       read_generic
 PURPOSE:
        read an image from a variety of types of files
 CATEGORY:
       Files, Graphics
 CALLING SEQUENCE:
       IDL> data2D = read_generic( filename )
 INPUTS:
       filename - file name to read in
		can be type 'jpg','tif','tif','bmp','jpeg,'png', 'ppm', 'pgm', or 'gif'
 KEYWORD PARAMETERS:
       Optional output:
	  extension - the file extension, eg., 'jpg'
 OUTPUTS:
       2-D data array from file               			out
 COMMON BLOCKS:
       NONE
 MODIFICATION HISTORY:
	30-Sep-2008 added channel keyword
	25-Apr-2007 added colortable keyword
	21-Feb-2007 added ppm file type
	19-Apr-2006 replaced keywords with args R,G,B 
	15-Oct-2004 Written by Bill Davis, PPPL 

(See src/idl_cvs/read_generic.pro)


READ_LIST

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       READ_LIST
 PURPOSE:
      Read a list from a text file and return a string array
 CATEGORY:
       Files
 CALLING SEQUENCE:
       IDL> str_array = READ_LIST(filename)
 INPUTS:
       filename = name of file containing lines of ascii data.  
 KEYWORD PARAMETERS:
	HLP - When set, help information is printed.
	nskip - lines to skip 
	status - if even, then read was successful
 OUTPUTS:
       str_array = returned array of strings - 1 per line             	out
 COMMON BLOCKS:
       NONE
 EXAMPLE:
	IDL> str_array = READ_LIST( filename )
 NOTES:
 MODIFICATION HISTORY:
	16-Aug-2008 added skipChar keyword
	01-Aug-2008 added nskip keyword
	13-Apr-2007 added status keyword
	11-Apr-06 added maxlines keyword [BD]
       1-Apr-99 Written by Bill Davis, PPPL

(See src/idl_cvs/read_list.pro)


READ_NUMBERS

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       read_numbers
 PURPOSE:
	Read a numeric array (1-D) from a text file
 CATEGORY:
       Files
 CALLING SEQUENCE:
       IDL> num_array = read_numbers(filename)
 INPUTS:
       filename = name of file containing lines of ascii data.
 KEYWORD PARAMETERS:
	nskip    - number of lines to skip before reading
	status - odd, if OK
 OUTPUTS:
       num_array = returned array of floating point values
 COMMON BLOCKS:
       NONE
 EXAMPLE:
	IDL> num_array = read_numbers( filename )
 NOTES:;
 MODIFICATION HISTORY:
       28-Feb-2002 Written by Bill Davis, PPPL

(See src/idl_cvs/read_numbers.pro)


READ_QUOTED

[Previous Routine] [Next Routine] [List of Routines]
  NAME:
	READ_QUOTED
  PURPOSE:
	Reads a file and returns anything between first two quotes.
 CATEGORY:
       Files
  CALLING SEQUENCE:
	IDL> comments = READ_QUOTED(filename)
 INPUT:        
	filename - e.g., "waveform.DAT"
  RETURNED:
	comments - string array with dimension = # of lines read (& not skipped)
 KEYWORDS
	delim - quote character, defaults to "
	nskip    - number of lines to skip before reading
 RETURNED:
	strings  - string array

 MODIFICATION HISTORY:
	16-Aug-2008 added skipChar & status keywords
 	26-Aug-00 WMD Written

(See src/idl_cvs/read_quoted.pro)


RMFILESBYDATE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       rmfilesbydate
 PURPOSE:
       Remove files not modified since a certain date
 CATEGORY:
       Files, Dates
 CALLING SEQUENCE:
       IDL> rmfilesbydate, path=path, prefix=prefix, ext=ext, date=date
 INPUTS:
       none
 KEYWORD PARAMETERS:
       path - directory
       prefix - file prefix for deletion
       ext - file extension for deletion; file search will be path+prefix+'*.'+ext 
       date - date for search, of form yyyymmdd, e.g., 20050617 (default=TODAY)
       daysbefore - optional additional number of days before date
       verbose - if set, will print informational output
       justprint - if set, will not remove files
 OUTPUTS:
       none
 COMMON BLOCKS:
       NONE
 EXAMPLE:
	IDL> 
 NOTES:
 	for safety, on Unix, you may wish to create a ~/Trash directory 
	and alias rm to
 	   /bin/mv !* ~/Trash
 LIMITATIONS
 MODIFICATION HISTORY:
       22-Aug-2005 Written by Bill Davis, PPPL

(See src/idl_cvs/rmfilesbydate.pro)


SPEC_DIR

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	SPEC_DIR
 PURPOSE:
	Provide a complete file specification by appending a default disk
	or directory if necessary.

 CATEGORY:
	Files, OS Specific, Strings
 CALLING SEQUENCE:                      
	File_spec = SPEC_DIR( filename, [ extension ] )
 INPUT:
	filename - character string giving partial specification of a file
		name.  Examples for different operating systems include the
			following:
		VMS: '$1$DUA5:TEST.DAT','[.SUB]TEST'
		Unix: pro/test.dat, $IDL_HOME/test
		MacOS: ':Programs:test'
		Windows: '\pro\test.dat','d:\pro\test'

 OPTIONAL INPUT:
	exten - string giving a default file name extension to be used if
		filename does not contain one.  Do not include the period.

 OUTPUT:
	File_spec - Complete file specification using default disk or 
		directory when necessary.  

 EXAMPLE:
	IDL> a = spec_dir('test','dat')

	is equivalent to the commands
	IDL> cd, current=cdir
	IDL> a = cdir + delim + 'test.dat'

	where delim is the OS-dependent separator 
 METHOD:
	SPEC_DIR() decomposes the file name using FDECOMP, and appends the 
	default directory (obtained from the CD command) if necessary.   
	Under VMS, SPEC_DIR() will also try to translate disk and directory 
	logical names.

	SPEC_DIR() does not check whether the constructed file name actually
	exists.
 PROCEDURES CALLED:
	FDECOMP, OS_FAMILY()
 REVISION HISTORY:
	Written W. Landsman         STX         July, 1987
	Added Unix compatibility, W.  Landsman, STX   August 1991
	Added Windows and Macintosh compatibility   W. Landsman  September 1995

(See src/idl_cvs/spec_dir.pro)


WRITE_GENERIC

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       write_generic
 PURPOSE:
        write an image to the appropriate type of file, based on 
	file extension
 CATEGORY:
       Files, Graphics
 CALLING SEQUENCE:
       IDL> write_generic, filename, data2D [,  R,G,B]
 INPUTS:
       filename - file name to read in
		can be type 'jpg','tif','tif','bmp','jpeg,'png', 'ppm', 'pgm', or 'gif'
 KEYWORD PARAMETERS:
    Optional inputs:
	extension - the file extension, eg., 'jpg'
	quality - jpeg quality [0-100, default is 75]
	order - JPEG/JFIF images are normally written in top-to-bottom order.
		If the image array is in the standard IDL order (i.e., from
		bottom-to-top) set ORDER to 0, its default value. If the image
		array is in top-to-bottom order, ORDER must be set to 1. 

 OUTPUTS:
       2-D data array from file               			out
 COMMON BLOCKS:
       NONE
 MODIFICATION HISTORY:
	18-Oct-2007 added quality keyword
	25-Apr-2007 added colortable keyword (not used!?!)
	21-Feb-2007 added ppm file type
	19-Apr-2006 replaced keywords with args R,G,B 
	15-Oct-2004 Written by Bill Davis, PPPL 

(See src/idl_cvs/write_generic.pro)


WRITE_TEXT

[Previous Routine] [List of Routines]
 NAME:
       write_text
 PURPOSE:
       Write data to a text file
 CATEGORY:
       files
 CALLING SEQUENCE:
       IDL> write_text, filename, data
 INPUTS:
	filename - filename for output (DEFAULT='outfile.txt')
	data - array of numbers
 KEYWORD PARAMETERS:
	header - text lines to put at the beginning of file
	verbose - if set, will echo message to screen with print command
 OUTPUTS:
       none
 COMMON BLOCKS:
       NONE
 EXAMPLE:
	IDL> write_text, 'myfilename.txt', findgen(100)
 NOTES:
 MODIFICATION HISTORY:
       12-Jun-2008 Written by Bill Davis, PPPL

(See src/idl_cvs/write_text.pro)


Category: GAplot

[List of Routines]


GA_DATA

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

 PURPOSE:
	A GA_Data object defines a dataset Y as a function of X. It can
	be drawn on a Plot defined by a GA_Plot object.

 CATEGORY:
	GAplot
 SUPERCLASSES:

 SUBCLASSES:
	GA_Data3
	GA_DataV

 CREATION:
	See GA_Data::Init

(See src/idl_cvs/ga_data__define.pro)


GA_DATA::GETXRANGE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Data::GetXRange

 PURPOSE:
	Retrieves the range of X data.

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Result = Obj->[GA_Data::]GetXRange()

 ARGUMENTS:

 KEYWORDS:

(See src/idl_cvs/ga_data__define.pro)


GA_DATA::GETYRANGE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Data::GetYRange

 PURPOSE:
	Retrieves the range of Y data.

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Result = Obj->[GA_Data::]GetYRange([XRANGE])

 ARGUMENTS:
	XRANGE	Returns Y range only for data points within XRANGE.

 KEYWORDS:
	ERRORBAR  Set to retrieve Y range with errorbars included.

(See src/idl_cvs/ga_data__define.pro)


GA_DATA::SETPROPERTY

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Data::SetProperty

 PURPOSE:
	Sets the value of a property or group of properties for the GA_Data.

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Obj->[GA_Data:]SetProperty

 ARGUMENTS:

 KEYWORDS:
	Any keyword to GA_Data::Init followed by "Set". In addition,
	HIDE		Set to hide this data set in Plot.
	PROPERTIES3D
	SELECTEDPOINT	Index of selected data point.
	STATUS
	XDATA		A vector argument to replace abscissa data X.
	YDATA		A vector argument to replace ordinate data Y.
	fitDegree	Degree of fit to display with data.
			0=none, 1=linear, 2=quadratic, 3=cubic
	fitThruZero	if=1 then fit forced to go through zero

 MODIFICATION HISTORY
	11-Mar-2005 Added fitDegree and fitThruZero keywords

(See src/idl_cvs/ga_data__define.pro)


GA_DATA::GETXNAME

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Data::GetXName

 PURPOSE:
	Retrieves the name of X vector.

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Result = Obj->[GA_Data::]GetXName()

 ARGUMENTS:

 KEYWORDS:

(See src/idl_cvs/ga_data__define.pro)


GA_DATA::GETFLAGAUTOLABEL

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Data::GetFlagAutoLabel

 PURPOSE:
	Retrieves value of FlagAutoLabel

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Result = Obj->[GA_Data::]GetFlagAutoLabel()

 ARGUMENTS:

 KEYWORDS:

(See src/idl_cvs/ga_data__define.pro)


GA_DATA::GETYNAME

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Data::GetYName

 PURPOSE:
	Retrieves the name of Y vector.

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Result = Obj->[GA_Data::]GetYName()

 ARGUMENTS:

 KEYWORDS:

(See src/idl_cvs/ga_data__define.pro)


GA_DATA::GETLABEL

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Data::GetLabel

 PURPOSE:
	Retrieves the label of this dataset. If not set, use YName.
	Can be overridden by subclasses to supply automatically generated
	label. FlagAutoLabel is provided to facilitate this.

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Result = Obj->[GA_Data::]GetLabel()

 ARGUMENTS:

 KEYWORDS:

(See src/idl_cvs/ga_data__define.pro)


GA_DATA::GETXDATA

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Data::GetXData

 PURPOSE:
	Retrieves abscissa vector X.

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Result = Obj->[GA_Data::]GetXData()

 ARGUMENTS:

 KEYWORDS:
	MARKER    >0, returns X values of   marked data points.
		  <0, returns X values of unmarked data points.
	RESAMPLE  Set to resample data before returning X.  Data is resampled 
		  to the maximum number of data points specified by member maxpts.

(See src/idl_cvs/ga_data__define.pro)


GA_DATA::GETYDATA

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Data::GetYData

 PURPOSE:
	Retrieves ordinate vector Y.

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Result = Obj->[GA_Data::]GetYData()

 ARGUMENTS:

 KEYWORDS:
	MARKER    >0, returns Y values of   marked data points.
		  <0, returns Y values of unmarked data points.
	RESAMPLE  Set to resample data before returning Y.  Data is resampled 
		  to the maxmum number of data points specified by member maxpts.
	ERRORBAR  A vector of same size of Y vector. Returns Y + ERRORBAR/2.

(See src/idl_cvs/ga_data__define.pro)


GA_DATA::GETCOLOR

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Data::GetColor

 PURPOSE:
	Retrieves the color index associated with this data set.

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Result = Obj->[GA_Data::]GetColor()

 ARGUMENTS:

 KEYWORDS:

(See src/idl_cvs/ga_data__define.pro)


GA_DATA::GETSYMBOL

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Data::GetSymbol

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Result = Obj->[GA_Data::]GetSymbol()

(See src/idl_cvs/ga_data__define.pro)


GA_DATA::GETSYMBOLSIZE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Data::GetSymbolSize

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Result = Obj->[GA_Data::]GetSymbolSize()

(See src/idl_cvs/ga_data__define.pro)


GA_DATA::GETLINESTYLE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Data::GetLineStyle

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Result = Obj->[GA_Data::]GetLineStyle()

(See src/idl_cvs/ga_data__define.pro)


GA_DATA::GETLINESTYLENONE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Data::GetLineStyleNone

 PURPOSE:
	Retrieves linestyle index for 'NONE' (no line).

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Result = Obj->[GA_Data::]GetLineStyleNone()

(See src/idl_cvs/ga_data__define.pro)


GA_DATA::GETPLOT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Data::GetPlot

 PURPOSE:
	Retrieves the GA_Plot object that contains this data object.

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Result = Obj->[GA_Data::]GetPlot()

(See src/idl_cvs/ga_data__define.pro)


GA_DATA::DRAW

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Data::Draw

 PURPOSE:
	Overplots this data set onto a Plot that has been established by
	a GA_Plot object.

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Obj->[GA_Data::]Draw

 ARGUMENTS:

 KEYWORDS:
	DRAGOFFSET
	ERASE

(See src/idl_cvs/ga_data__define.pro)


GA_DATA::ADD_TEXT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Data::Add_Text

 PURPOSE:
	Add a text annotation defined by GA_AnnotateText object that will be 
	drawn together with this data object onto the plot object.

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Obj->[GA_Data::]Add_Text(XPOS,YPOS,TEXT)

 ARGUMENTS:
	XPOS	X position of the text
	YPOS	Y position of the text
	TEXT	a string

 KEYWORDS:
	DRAW	Set to draw this data object after adding the text.
	USE	Set to 0 to hide or 1 to display this text annotation. Default=1

(See src/idl_cvs/ga_data__define.pro)


GA_DATA::DELETE_TEXT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Data::Delete_Text

 PURPOSE:
	Deletes a text member from the data object.

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Obj->Delete_Text,dataset

 ARGUMENTS:
	DATASET  Either a text object or the index of text objects starting
		 zero as the first one.

 KEYWORDS:
	DRAW	   Draw the data set upon deletion of the text object.
	NODESTROY  Set to not destroy the text object itself, only remove
		   from this data object. Default to destroy.

(See src/idl_cvs/ga_data__define.pro)


GA_DATA::SET_TEXT_PROPERTY

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Data::Set_Text_Property

 PURPOSE:
	Sets the parameters associated with a text annotation object.

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Obj->[GA_Data::]Set_Text_Property [,TEXTMEMBER]

 ARGUMENTS:
	TEXTMEMBER  Index number of text objects (0 being the first one).
		    If not specified, this methon applies to all text members.

 KEYWORDS:
	DRAW	Draw this data object after setting text properties.
	NOUSE	Set to not display the text.
	TEXT	A string to replace the text content.
	USE	Set to display the text.
	All properties settable by GA_AnnotateText::SetProperty.

(See src/idl_cvs/ga_data__define.pro)


GA_DATA::INIT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Data::Init

 PURPOSE:
	Initializes the GA_Data object.

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Obj = OBJ_NEW('GA_Data',[X,]Y)
	or 
	Result = Obj->[GA_Data::]Init([X,]Y)   (in a subclass' Init method only)

 ARGUMENTS:
	X - A vector or a pointer to a vector. If not specified, Y is defined 
	    as a function of point number starting at zero.  If both arguments 
	    are specified, Y is a function of X, and X and Y have to be of 
	    same data type.
	Y - The ordinate data or a pointer to the ordinate data.

 KEYWORDS:
	Properties retrieveable via GA_Data::Get{PropertyName} are 
	indicated by "Get" following the keyword.  Properties settable via 
	GA_Data::SetProperty are indicated by "Set" following the keyword.

	COLOR (Get,Set)		The color index for plotting this data set. Default=foreground
	DEBUG			Set to turn on debugging.
	ERRORBAR (Set)		A vector of errorbar values (+- errorbar/2).
	INTERPOLATE (Set)	Set to set editmode to interpolate (?)
	FLAGAUTOLABEL (Get,Set)	Set to automatically determine label from method call.
	LABEL (Get,Set)		Legend label
	LINESTYLE (Get,Set)	The linestyle of drawing this data. Default=0 (solid line)
	MARKCOLOR (Get,Set)	Color index for markers
	MARKER (Get,Set)	Set to indicate that data points can be marked.
	MARKFILL (Get,Set)	Set to fill marker symbols.
	MARKLABELS (Get,Set)	Label used for markers.
	MARKSIZE (Get,Set)	Size of mark symbols.
	MARKSYMBOL (Get,Set)	Symbol used for markers.
	PLOT (Get,Set)		The GA_Plot object that contains this object.
	SHIFT (Set)		Set to set editmode to shift (?)
	SYMBOL (Get,Set)	The symbol used for this data set.
	SYMFILL (Get,Set)	Set this keyword to fill the symbols.
	SYMFRAC (Get,Set)	The fraction (0-100) of symbols to plot. Default=0.
	SYMSIZE (Get,Set) 	The size of symbols. Default=1.
	XNAME (Get,Set)		A name associated with X.
	XSCALE (Get,Set)	Two elements arrary for X scaling. X=X*XSCALE[1]+XSCALE[0]
	YNAME (Get,Set)		A name associated with Y.
	YSCALE (Get,Set)	Two elements array for Y scaling. Y=Y*YSCALE[1]+YSCALE[0]

(See src/idl_cvs/ga_data__define.pro)


GA_PLOT

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

 PURPOSE:
	A GA_Plot object draws graphs of its data members. It is a container of
	GA_Data objects.  If it has more than one data object member, the data 
	members are overlayed. A plot object can be thought as a wrapper to 
	IDL's PLOT command, keyword values to the PLOT command are preserved as
	plot object's or data objects' members.  A plot object is plotted on a
	window created by a GA_Plot_Window object which may contain several plot
	objects.

 CATEGORY:
	GAplot
 SUPERCLASSES:

 SUBCLASSES:
	GA_Plot3

 CREATION:
	See GA_Plot::Init

 BASIC METHODS:
	GA_Plot::Add_Data
	GA_Plot::Add_Data_Object
	GA_Plot::Delete_Data
	GA_Plot::Select_Data
	GA_Plot::Set_Data_Property
	GA_Plot::Set_Plot_Property

(See src/idl_cvs/ga_plot__define.pro)


GA_PLOT::GETDATASELECTED

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Plot::GetDataSelected

 PURPOSE:
	Retrieves the selected data object. A data object can be selected
	by clicking near to the data points with Left-Mouse-Button in
	'Select' mode.

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Result = Obj->[GA_Plot::]GetDataSelected()

 KEYWORDS:
	INDEX	A named variable to recieve the index of the selected data object

(See src/idl_cvs/ga_plot__define.pro)


GA_PLOT::SELECT_DATA

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Plot::Select_Data

 PURPOSE:
	This method retrieves a particular data object associated with this
	plot object. A data can be selected by name or by index number.

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Result = Obj->[GA_Plot::]Select_Data([DATASET])

 ARGUMENTS:
	DATASET	  A string specifying the name of the data object, or an
		  integer specifying the index number, 0 being the 1st one.

(See src/idl_cvs/ga_plot__define.pro)


GA_PLOT::SET_DATA_PROPERTY

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Plot::Set_Data_Property

 PURPOSE:
 	This method allows you to change the parameters associated with a
 	particular data object. You must specify a particular data set by 
	passing the object reference to the data set. (This can be obtained 
	with the GA_Plot::Select_Data method.) If a data set object is not 
	specified as the data member, the first data set is used by default.

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Obj->[GA_Plot::]Set_Data_Property [,DATAMEMBER]

 ARGUMENTS:
	DATAMEMBER  A GA_Data object associated with this plot object.

 KEYWORDS:
	Any keywords acceptable to GA_Data::SetProperty, and
	AUTORANGE   Set to reset the data range automatically.
	DRAW	    Set to re-draw all datasets.
 EXAMPLES:
	oPlot->Set_Data_Property,oPlot->Select_Data(1),XData=x,Ydata=y

	This resets X and Y vectors for the 2nd dataset in the oPlot object.

(See src/idl_cvs/ga_plot__define.pro)


GA_PLOT::GET_DATA_PROPERTY

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Plot::Get_Data_Property

 PURPOSE:
 	This method allows you to retrieve the properties of a data member
 	belonging to the plot. Data member is identified by passing its
 	object reference (which can be obtained with the Select_Data method).
 	If a data member is not specified, the first data memeber is used
	as a default.

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Obj->[GA_Plot::]Get_Data_Property [,DATAMEMBER]

 ARGUMENTS:
	DATAMEMBER   A GA_Data object associated with this plot object.

 KEYWORDS:
	Keywords are named variables to receive retrieved values.
	At least one keyword should be provided.
	COLOR	   The color index of the data member.
	LINESTYLE  The linestyle of the data member.
	MARKER	   Used together with XDATA and/or YDATA.
	           >0 for marked data points, <0 for unmarked data points.
	SYMBOL
	SYMFILL
	SYMFRAC
	SYMSIZE
	XNAME
	XDATA	   Abscissa vector X of the data member.
	YNAME
	YDATA	   Ordinate vector Y of the data member.

 EXAMPLE:
	oPlot->Get_Data_Property,oPlot->Select_Data(1),XData=xdata,Marker=-1

	This retrives X values of the unmarked data points from the 2nd
	data member of this plot and stores the result in variable xdata.

(See src/idl_cvs/ga_plot__define.pro)


GA_PLOT::ADD_DATA_OBJECT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Plot::Add_Data_Object

 PURPOSE:
 	This method allows you to add a GA_DATA or GA_DATA3 object to
 	the plot object. The data object reference is returned.

	See also GA_Plot::Add_Data

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Result = Obj->[GA_Plot::]Add_Data_Object, NEWDATA

 ARGUMENTS:
	NEWDATA	  A GA_Data(3) object to be added.

 KEYWORDS:
	DRAW		Set to re-draw all datasets.
	NOAUTORANGE	Set to not reset the data range automatically.

(See src/idl_cvs/ga_plot__define.pro)


GA_PLOT::ADD_DATA

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Plot::Add_Data

 PURPOSE:
 	This method allows you to add another data object to
 	the plot object. Properties of the data object may be set with
 	the method's keywords. Extra carries any keywords acceptable
 	by Ga_Data[3]::Init.  A new data object will be created and
	the reference is returned.

	See also GA_Plot::Add_Data_Object

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Result = Obj->Add_Data([XDATA,] YDATA [,ZDATA]])

 ARGUMENTS:
	XDATA	X vector. If not specified, X will set to a point number
	        array starting at zero.
	YDATA	Y vector as a function of X if ZDATA is not specified.
	        If ZDATA is specified, YDATA is the 2nd independent data.
	ZDATA	A two dimensional array as a function of X and Y.
		If ZDATA is specified, a GA_Data3 will be created.

	See GA_Data::Init and GA_Data3::Init for acceptable inputs.

 KEYWORDS:
	Any keywords acceptable to GA_Data::Init or GA_Data3::Init, and
	DRAW		Set to re-draw all datasets.
	NOAUTORANGE	Set to not reset data ranges automatically.

 HISTORY:
	07-10-2002  Q.Peng - This method shouldn't have worked for adding a
	            GA_Data3 (with XDATA,YDATA,ZDATA) before. The order of 
		    arguments has just been corrected.

(See src/idl_cvs/ga_plot__define.pro)


GA_PLOT::DELETE_DATA

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Plot::Delete_Data

 PURPOSE:
 	This method allows you to delete a data set member from the Plot 
	Object. The data set may be specified by indicating its NAME, by 
	indicating its POSITION (index number), or by the data OBJECT itself. 
	(See the Select_Data method for more details about a data set's
 	NAME and POSITION.)

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Obj->[GA_Plot::]Delete_Data, DATASET

 ARGUMENTS:
	DATASET   A string for its name, or an integer for its position
		  (0 being the 1st), or a GA_Data object reference.

 KEYWORDS:
	DRAW		Set to re-draw all datasets.
	NOAUTORANGE	Set to not reset data ranges automatically.
	NODESTROY	Set to not destroy the deleted data object.

(See src/idl_cvs/ga_plot__define.pro)


GA_PLOT::AUTO_RANGE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Plot::Auto_Range

 PURPOSE:
	Set data ranges automatically according to data.
	This is needed for multiple data sets.
	Set both xrange and yrange by default.

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Obj->[GA_Plot::]Auto_Range

 KEYWORDS:
 	OVERRIDE  Set to ALWAYS autoscale both MIN and MAX regardless of 
		  the settings of xautorange and yautorange
	XONLY	  Set to only autoscale X range.
	YONLY	  Set to only autoscale Y range.
	ZONLY	  Set to only autoscale Z range.

(See src/idl_cvs/ga_plot__define.pro)


GA_PLOT::ADD_TEXT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Plot::Add_Text

 PURPOSE:
	This method adds a text annotation to a specified location on
	the plot.

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Obj->Add_Text, XPOS, YPOS, TEXT

 ARGUMENTS:
	XPOS	X coordinate of the text.
	YPOS	Y coordinate of the text.
	TEXT	A string.

 KEYWORDS:
	Any keywords acceptable to GA_AnnotateText::Init, and
	DRAW	Set to re-draw all datasets.
	USE	1 - display the text (default), 0 - do not display the text. 

(See src/idl_cvs/ga_plot__define.pro)


GA_PLOT::SET_TEXT_PROPERTY

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Plot::Set_Text_Property

 PURPOSE:
 	This method allows you to change the parameters associated with a
 	text annotaion object.  The textMember is the index number of the
 	text object.  All text members are used by default if no textMember
 	is specified.

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Obj->[GA_Plot::]Set_Text_Property [,TEXTMEMBER]

 ARGUMENTS:
	TEXTMEMBER  An integer specifying the index number of the text memeber.
		    0 is the 1st text.  If not specified, all texts are used.

 KEYWORDS:
	DRAW	Set to re-draw all datasets.
	NOUSE	Set to not display the text in the plot.
	TEXT	A string to replace the text value.
	USE	Set to display the text in the plot.
	Any keywords acceptable by GA_AnnotateText::SetProperty

(See src/idl_cvs/ga_plot__define.pro)


GA_PLOT::DRAW

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Plot::Draw

 PURPOSE:
 	This method draws the Plot Object, including all of the
 	data members included in the Plot Object. 

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Obj->[GA_Plot::]Draw

 KEYWORDS:
	NODATA	If set, only the plot axes and annotation are drawn.
	NOERASE keyword to PLOT.
	

(See src/idl_cvs/ga_plot__define.pro)


GA_PLOT::SETSLICEMODE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Plot::SetSliceMode

 PURPOSE:
	Set mode for data slicing. For a GA_Plot object, the plot can be used
	as a slicer to slice through other GA_Plot3 objects in the same
	window.  The data in this plot will not be sliced because there is
	no third dimension.

	See also GA_Plot3::SetSliceMode

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Obj->[GA_Plot::]SetSliceMode, MODE

 ARGUMENTS:
	MODE 	'A' - Can be used to slice through the 1st dimension of a
	              GA_Plot3 object with slicemode 'AB', or the 2nd dimension
		      of a GA_Plot3 object with slicemode 'BA'.
		'B' - Can be used to slice through the 2nd dimension of a
		      GA_Plot3 object with slicemode 'AB', or the 2nd dimension
		      of a GA_Plot3 object with slicemode 'AB'.
		'X' - Not a slicer. In 'Slice' mode, when cursor moves into
		      this plot, nothing happens.

(See src/idl_cvs/ga_plot__define.pro)


GA_PLOT::SET_PLOT_PROPERTY

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Plot::Set_Plot_Property

 PURPOSE:
 	This method allows you to set the standard Plot properties. If
 	the DRAW keyword is set, the plot will be drawn after the new
 	properties are set. (See the Init Method for a more complete
 	explanation of these Plot properties.)

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Obj->[GA_Plot::]Set_Plot_Property

 KEYWORDS:
	Any keywords to GA_Plot::Init followed by "Set", and
	DRAW
	LCHARSIZE
	NOXTICKS
	SETXRANGE
	SETYRANGE
	XAUTORANGE
	YAUTORANGE
	WINDOW

(See src/idl_cvs/ga_plot__define.pro)


GA_PLOT::GET_PLOT_PROPERTY

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Plot::Get_Plot_Property

 PURPOSE:
 	This method allows you to obtain the standard Plot properties
 	from the Plot Object. (See the Init Method for a more complete
 	explanation of these Plot properties.)

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Obj->[GA_Plot::]Get_Plot_Property

 KEYWORDS:
	Keywords are named variables to receive retrieved values.
	Any keywords to GA_Plot::Init followed by "Get", and
	NUMDATASETS
	NUMTEXT
	LCHARSIZE
	NOXTICKS
	SETXRANGE
	SETYRANGE
	XAXIS
	XAUTORANGE
	YAXIS
	YAUTORANGE

(See src/idl_cvs/ga_plot__define.pro)


GA_PLOT::GETWINDOW

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Plot::GetWindow

 PURPOSE:
 	This method returns the GA_Plot_Window object that the plot object 
	belongs to, for EditCallBack purpose.

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Result = Obj->[GA_Plot::]GetWindow()

(See src/idl_cvs/ga_plot__define.pro)


GA_PLOT::GETDATAOBJECTS

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Plot::GetDataObjects

 PURPOSE:
 	The method returns the array of data objects stored in this plot object.

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Results = Obj->[GA_Plot::]GetDataObjects()

(See src/idl_cvs/ga_plot__define.pro)


GA_PLOT::INIT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Plot::Init

 PURPOSE:
 	This method initializes a GA_Plot object. Standard properties
 	are set with positional and keyword parameters. The routine makes 
	GA_DATA objects from the data passed into the method. Use the 
	Add_Data method to add additional data sets and the Delete_Data 
	method to remove data sets from the Plot Object. Data inside the 
	data objects can be modified with the Set_Data_Property method. 
	Think of this initialization routine as a wrapper for the PLOT 
	command. Use keywords appropriate for the PLOT command 
	in making the call.

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Obj = OBJ_NEW('GA_Plot'[,X [,Y]])
	or
	Result = Obj->[GA_Plot::]Init([X [,Y]])   (in a subclass' Init method only)

 ARGUMENTS:
	X - If Y is specified, X, Y are the two arguments to GA_Data::Init
	    If Y is not specified, X can be a GA_Data or GA_DataV object,
	    or it can be the only argument to GA_Data::Init.
	Y - The 2nd argument to GA_Data::Init

 KEYWORDS:
	Properties retrieveable via GA_Plot::Get_Plot_Property are indicated
	by "Get" following the keyword.  Properties settable via
	GA_Plot::Set_Plot_Property are indicated by "Set".

	ASPECT (Get,Set)	Set to keep aspect ratio of plots.
	BACKGROUND (Get,Set)	The color index of background.
	CHARSIZE (Get,Set)	The character size for labels.
	COLOR (Get,Set)		The color index for axes and annotations.
	CONTOUR			Set to do contour plots.
	DATACOLOR		The color for plotting data created here.
	DEBUG(Set)		Set to turn on debugging.
	DEP_DATA_NAME		The name associated with dependent data (Y).
	FLAGLEGEND (Get,Set)	0 = do not show labels, 1 = show labels
	INDEP_DATA_NAME		The name associated with independent data (X).
	GRID (Get,Set)		A two-element array (columns,rows) for the layout of all plots
				in the GA_Plot_Window object to which this plot object belongs.
	LEVELS			The level vector for contour plot.
	NAME (Get,Set)		The name associated with this plot (used for plot selection).
	NUMBER (Get,Set)	The index number of this plot in window (starting at 0).
	OVERGRIDSTYLE (Get,Set)	Grid style for both X and Y axes.
	OVERLAYGRID (Get,Set)
	OVERLAYZERO (Get,Set)
	PSYM			The plot symbol used to display the data.
	SLICEMODE (Get,Set)
	SUBTITLE (Get,Set)
	SYMFRAC			The fraction (0-100) of symbols to be plotted.
	SYMSIZE			The plot symbol size.
	TICKSOUT (Get,Set)	If non 0, ticks appear on outside of the plot.
	TITLE (Get,Set)		The plot title.
	XCHARSIZE (Get,Set)
	XLOG (Get,Set)
	XMTICKS (Get,Set)	X minor ticks
	XRANGE (Get,Set)
	XSTYLE (Get,Set)
	XTICKFORMAT(Set)
	XTICKS (Get,Set)
	XTITLE (Get,Set)
	YCHARSIZE (Get,Set)
	YLOG (Get,Set)
	YMTICKS (Get,Set)	Y minor ticks
	YRANGE (Get,Set)
	YSTYLE (Get,Set)
	YTICKFORMAT(Set)
	YTICKS (Get,Set)
	YTITLE (Get,Set)
	WID (Get,Set)		The window index number of the window where this plot is displayed.

(See src/idl_cvs/ga_plot__define.pro)


GA_PLOT_WINDOW

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

 PURPOSE:
	A GA_Plot_Window is a compound widget with a draw window that 
	contains one or several GA_Plot[3] objects. Plots can be added
	or deleted. The window object handles plot layout, coordinates,
	preference and properties configurations, mouse events and
	draws all the plots through their own draw methods.

 CATEGORY:
	GAplot
 SUPERCLASSES:

 SUBCLASSES:

 CREATION:
	See GA_Plot_Window::Init

 BASIC METHODS:
	GA_Plot_Window::Add_Plot
	GA_Plot_Window::Delete_Plot
	GA_Plot_Window::SetCurrentTool
	GA_Plot_Window::Set_Crosshairs
	GA_Plot_Window::Set_Status_Window

(See src/idl_cvs/ga_plot_window__define.pro)


GA_PLOT_WINDOW::RESTOREPREFERENCES

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Plot_Window::RestorePreferences

 PURPOSE:
	Restore user's preferences from file specified by
	PreferencesFile. This file is always in user's HOME directory.

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Obj->[GA_Plot_Window::]RestorePreferences

(See src/idl_cvs/ga_plot_window__define.pro)


GA_PLOT_WINDOW::SAVEPREFERENCES

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Plot_Window::SavePreferences

 PURPOSE:
	Save the current settings to user's preferences file specified by
	PreferencesFile. This file is always in user's HOME directory.

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Obj->[GA_Plot_Window::]SavePreferences

(See src/idl_cvs/ga_plot_window__define.pro)


GA_PLOT_WINDOW::SETCHARSIZE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Plot_Window::SetCharsize

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Obj->[GA_Plot_Window::]SetCharsize, charsize

(See src/idl_cvs/ga_plot_window__define.pro)


GA_PLOT_WINDOW::SETCOLORFLAG

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Plot_Window::SetColorFlag

 PURPOSE:
	Resetting the color table.

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Obj->[GA_Plot_Window::]SetColorFlag, COLORFLAG

 ARGUMENTS:
	COLORFLAG   Flag used by Color_Setup to determine the type of color table.
		0 - greyscale color table,
		1 - color_list() color table,
		2 - black and white only.

 KEYWORDS:
	REVERSE	    Set to have white background. The default is with black background.

(See src/idl_cvs/ga_plot_window__define.pro)


GA_PLOT_WINDOW::GETPLOTLIST

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Plot_Window::GetPlotList

 PURPOSE:
	Retrieves the names of plots in this window object. A name is
	specified or a default is given when a plot object is created.

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Result = Obj->[GA_Plot_Window::]GetPlotList()

(See src/idl_cvs/ga_plot_window__define.pro)


GA_PLOT_WINDOW::GETPLOT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Plot_Window::GetPlot

 PURPOSE:
	Retrieves a plot object specified by its index number.

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Result = Obj->[GA_Plot_Window::]GetPlot(INDEX)

 ARGUMENTS:
	INDEX	An index number of the plot object in this window.
		0 = 1st plot object.

(See src/idl_cvs/ga_plot_window__define.pro)


GA_PLOT_WINDOW::USERSETGRID

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Plot_Window::UserSetGrid

 PURPOSE:
	Allows manually setting the grid layout of the plots.
	If howeve, the total number of plots is greater than
	GRID[0]*GRID[1], the grid is recalculated automatically.

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Obj->[GA_Plot_Window::]UserSetGrid, GRID

 ARGUMENTS:
	GRID	A two-element array specifying the layout of plots.
		GRID[0] = number of columns, GRID[1] = number of rows.

 KEYWORDS:
	DRAW	Set to re-draw all the plots.

(See src/idl_cvs/ga_plot_window__define.pro)


GA_PLOT_WINDOW::SETMAXGRID

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Plot_Window::SetMaxGrid

 PURPOSE:
	Set the maximum number of columns and rows for determining
	grid layout of plots automatically.

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Obj->[GA_Plot_Window::]SetMaxGrid, MAXGRID

 ARGUMENTS:
	MAXGRID	   A two-element array.
		   MAXGRID[0] = maxcols, MAXGRID[1] = maxrows.

(See src/idl_cvs/ga_plot_window__define.pro)


GA_PLOT_WINDOW::SETAUTOGRID

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Plot_Window::SetAutoGrid

 PURPOSE:
	Turn on or off the automatic grid layout calculation.

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Obj->[GA_Plot_Window::]SetAutoGrid, ONOFF

 ARGUMENTS:
	ONOFF	1 - turn on auto grid, 0 - turn off auto grid.

 KEYWORDS:
	DRAW	Set to re-draw all plots.

(See src/idl_cvs/ga_plot_window__define.pro)


GA_PLOT_WINDOW::CHECKPLOTNUMBERS

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Plot_Window::CheckPlotNumbers

 PURPOSE:
 	Goes through member plots and checks to ensure that they are
	sequentially numbered.  Renumbers them if they are not. Plots
	having the same number are overlayed and can cause confusing
	display results.  This routine is optional - to be used by
	the parent application if needed.
	It returns 0 if no plot has been renumbered, returns 1 otherwise.

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Result = Obj->[GA_Plot_Window::]CheckPlotNumbers()	

(See src/idl_cvs/ga_plot_window__define.pro)


GA_PLOT_WINDOW::REPLACE_PLOT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Plot_Window::Replace_Plot

 PURPOSE:
	This method replaces a current plot in the window with another plot.

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Obj->[GA_Plot_Window::]Replace_Plot, OPLOT

 ARGUMENTS:
	OPLOT	A replacement GA_Plot object.

 KEYWORDS:
	NUMBER	The index number of the plot to be replaced. 
		The first plot (0) is replaced if number if not specified.

(See src/idl_cvs/ga_plot_window__define.pro)


GA_PLOT_WINDOW::INSERT_PLOT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Plot_Window::Insert_Plot

 PURPOSE:
 	Inserts a new plot at a specified index number. The plot numbers
	are shifted by 1 (+1) from the inserted plot.

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Obj->[GA_Plot_Window::]Insert_Plot, OPLOT, NUMBER

 ARGUMENTS:
	OPLOT	A GA_Plot object to be inserted.
	NUMBER	The index number which the new plot is inserted to.

 KEYWORDS:
	NODRAW	Set to not re-draw all the plots. Useful when inserting
		more than one plot to complete insertion before re-draw.

(See src/idl_cvs/ga_plot_window__define.pro)


GA_PLOT_WINDOW::REMOVE_PLOT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Plot_Window::Remove_Plot

 PURPOSE:
	If the PLOT tag in EDITFLAGS structure is set, this method deletes
	the plot object specified by the index number. 
	A GA_Plot_Window::EditCallBack is generated.

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Obj->[GA_Plot_Window::]Remove_Plot

 ARGUMENTS:
	NUMBER	The index number of the plot to be deleted.

 KEYWORDS:
	Any keywords acceptable by GA_Plot_Window::Delete_Plot.

(See src/idl_cvs/ga_plot_window__define.pro)


GA_PLOT_WINDOW::DELETE_PLOT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Plot_Window::Delete_Plot

 PURPOSE:
 	This method deletes a plot from the list of plots within the window.
 	Plots are numbered from 1 to N and are in column order in the window.

 	NO EDITCALLBACK is generated by this method! For an EDITCALLBACK
 	use GA_Plot_Window::RemovePlot.

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Obj->[GA_Plot_Window::]Delete_Plot, NUMBER

 ARGUMENTS:
	NUMBER	The index number of the plot object to be deleted.

 KEYWORDS:
	NODRAW	   Set to not re-draw all plots. Useful when deleting
		   more than one plot to complete the deletion before
		   re-drawing what is left.
	NODESTROY  Set to not destroy the plot object being deleted from this window.
		   Default is to destroy the plot object.

(See src/idl_cvs/ga_plot_window__define.pro)


GA_PLOT_WINDOW::ADD_PLOT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Plot_Window::Add_Plot

 PURPOSE:
 	This method adds a plot to the window. A new column of plots
 	will be created if necessary to accomodate the new plot. A plot
 	object is required. If NoDuplicate keyword is set, check if newPlot
 	belongs to the window already. If so, return.

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Obj->[GA_Plot_Window::]Add_Plot, NEWPLOT

 ARGUMENTS:
	NEWPLOT	  A GA_Plot object to be added to the window.

 KEYWORDS:
	DRAW	      Set to re-draw all plots.
	NODUPLICATE   Set to make sure NEWPLOT is added to this 
		      window object only once.

(See src/idl_cvs/ga_plot_window__define.pro)


GA_PLOT_WINDOW::SET_CROSSHAIRS

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Plot_Window::Set_Crosshairs

 PURPOSE:
 	This method turns cursor crosshair tracking on or off.

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Obj->[GA_Plot_Window::]Set_Crosshairs, ONOFF

 ARGUMENTS
	ONOFF	1 - crosshair tracking on, 0 - crosshair tracking off.

(See src/idl_cvs/ga_plot_window__define.pro)


GA_PLOT_WINDOW::GETCURRENTTOOL

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Plot_Window::GetCurrentTool

 PURPOSE:
	Retrieves the name of the current mouse mode. Possible modes are
	['Select','Zoom','Edit','Cursor','Slice','Mark','Vector'] plus
	those defined by MOUSEMODES.

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Result = Obj->[GA_Plot_Window::]GetCurrentTool()

(See src/idl_cvs/ga_plot_window__define.pro)


GA_PLOT_WINDOW::SETCURRENTTOOL

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Plot_Window::SetCurrentTool

 PURPOSE:
	This method sets the current tool(mouse mode) to be used in the window.
	'SELECT'  - Seleting a data or a plot for manipulation, copying and deletion, etc.
	'ZOOM'    - Zoom and reset a plot, switch between multiple and single-plot displays.
	'EDIT'    - Add, delete or move data points.
	'CURSOR'  - Mark reference points, switch cursor readout from absolute to relative.
	'SLICE'   - Change the slices of the 3D data being plotted.
	'MARK'    - Mark a data point with a special symbol.
	'VECTOR'  - Change vector magnitute, data point resampling rate, etc.

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Obj->[GA_Plot_Window::]SetCurrentTool, TOOL

 ARGUMENTS:
	TOOL	  A string specifies the mode to set. See above for possible values.

(See src/idl_cvs/ga_plot_window__define.pro)


GA_PLOT_WINDOW::SET_STATUS_WINDOW

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Plot_Window::Set_Status_Window

 PURPOSE:
 	This method assigns a text or label widget ID to be the
 	status window. Cursor tracking reports are sent to the
 	status window.

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Obj->[GA_Plot_Window::]Set_Status_Window,WID

 ARGUMENTS:
	WID     The ID of a text or a label widget to report the cursor readouts
		and other status message.

(See src/idl_cvs/ga_plot_window__define.pro)


GA_PLOT_WINDOW::EDITCALLBACK

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Plot_Window::EditCallback

 PURPOSE:
	Perform an IDL procedure call upon certain editing action,

	    CALL_PROCEDURE,ProName,Parent,oData,oPlot,Action

	ProName is the procedure name specified by keyword EDITCALLBACK 
	when the window object is created (see GA_Plot_Window::Init).
	This procedure should expect four arguments.

	Parent	The parent widget of the PARENT argument specified in 
		GA_Plot_Window::Init.  If the GA_Plot_Window is
		created through CW_GAWindow, Parent will be the PARENT
		argument passed to CW_GAWindow.
	oData	A GA_Data object or a null object.
	oPlot	A GA_Plot object or a null object.
	Action	An action string such as 'ADD_DATA','DELETE_DATA',
		'DELETE_PLOT','REFERENCE_POINT',etc.

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Obj->[GA_Plot_Window::]EditCallback, oData, oPlot, Action

 ARGUMENTS: see above

(See src/idl_cvs/ga_plot_window__define.pro)


GA_PLOT_WINDOW::DRAW

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Plot_Window::Draw

 PURPOSE:
	Draws all the plots in this window by calling the plot objects
	Draw method.

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Obj->[GA_Plot_Window::]Draw

(See src/idl_cvs/ga_plot_window__define.pro)


GA_PLOT_WINDOW::DUMP

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GA_Plot_Window::Dump

 PURPOSE:
	Prints out pointers to plot objects and their associated data objects.
	For debugging purposes.

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Obj->[GA_Plot_Window::]Dump

(See src/idl_cvs/ga_plot_window__define.pro)


GA_PLOT_WINDOW::INIT

[Previous Routine] [List of Routines]
 NAME:
	GA_Plot_Window::Init

 PURPOSE:
	Initializes a GA_Plot_Window object. The window is conceived as a 
	compound widget via CW_GAWindow. When you get the "value" of the 
	compound widget, you are returned the window object. Instead of 
	"setting values" to the compound widget, you call window object 
	methods.

 CATEGORY:
	GAplot
 CALLING SEQUENCE:
	Obj = OBJ_NEW('GA_Plot_Window',PARENT)

 ARGUMENTS:
	PARENT	A parent widget ID in which the GA_Plot_Window object
	        draw widget will be build.

 KEYWORDS:
	ALLSAMEX	Set to draw all plots with the same X range. Default = 1.
	CHANGEMOUSEBITMAP Set to change cursor appearance in different modes. Default = 1.
	CURRENTTOOL	The index of currently selected mode from list
			['Select','Zoom','Edit','Cursor','Slice','Mark','Vector']
	COLOR		The color index for cursor in the window.
	DEBUG		Set to turn on debugging.
	EDITCALLBACK	A string specifies a procedure name to call when editing is performed.
	EDITFLAGS
	EMPTYMSG	A string array to display when there is no plot in the window.
	ERRORCALLBACK	A string specifies a procedure name to call when error occurs.
	EVENTCALLBACK	A string specifies a procedure name to call when WIDGET_DRAW event occurs.
	GRID		A two element array for plot layout. 
	        	GRID[0] = number of columns, GRID[1] = number of rows.
	IMAGE_COLORS
	MAXCOLS		Maximum number of columns when determining grid automatically.
	MAXROWS 	Maximum number of rows when determining grid automatically.
	MBAR		Widget ID of menubar for popup window.
	MOUSEMODES	A string array specifies additional mouse modes.
	PLOTS		A pointer to a vector of GA_Plot objects.
	POPUPOPTIONS	A 2xN string array specify entries for popup window.
			If not specified, the default options are used.
			POPUPOPTIONS[0,*] specify button names, 
			POPUPOPTIONS[1,*] specify event procedure names to call.
	PREFERENCESFILE	The file name for user preferences. File should be in user's HOME.
	STATUS		Set to include the status widget.
	TRACKING	Set to turn on cursor tracking.
	XSIZE		The X size of the draw widget display window.
	YSIZE		The Y size of the draw widget display window.

(See src/idl_cvs/ga_plot_window__define.pro)


Category: Graphics

[List of Routines]


BANGPW

[Next Routine] [List of Routines]
 NAME:
       bangPW
 PURPOSE:
       Widget to set interactively some !P values. Lists colors by name, 
	if mk_color used; otherwise finds "closest" index to named colors. 
	Allows selection of several custom plotting symbols (see PLOTSYM).
 CATEGORY:
       Graphics, Widgets
 CALLING SEQUENCE:
       IDL> bangPW
 INPUTS:
 KEYWORD PARAMETERS:
     Optional Keywords:
	  UPDATECALLBACK - a routine to call after struct system variable is set
	  GROUP_LEADER - This widget is destroyed if it's GL is destroyed
 OUTPUTS:
       The system variable !P is changed               	
 COMMON BLOCKS:
       NONE
 EXAMPLE:
	IDL> bangPW, UPDATECALLBACK='myReplotter'
 NOTES:
	If an application overrides !P.* parameters, or specifies them on
	the plot command, changing settings with this widget will not override.
	!P.SYMSIZE not controlled, because it seems to have no effect.
 MODIFICATION HISTORY:
	29-Apr-08 check for routine being compiled (vs. needing to be found)
		  added a "Refresh" button which, if a proper plotting routine
		  is provided, will replot with any changed settings.
	17-Aug-01 Allow lines with symbols [BD]
	30-Oct-00 Written by Bill Davis, PPPL

(See src/idl_cvs/bangpw.pro)


DRAWRECTANGLE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       drawrectangle
 PURPOSE:
  	draw a rectangle in data coordinates
 CATEGORY:
	Graphics
 USAGE:
	IDL> drawrectangle, x1, y1, x2, y2
 INPUTS:
       text - text string to write to window
 KEYWORD PARAMETERS:
	dropshadow - if set, make a drop shadow of thick=3 text
	color - color of text
	dscolor - color of drop-shadow text (defaults to black or white)
	nPixels - # of pixels to drop shadow

 MODIFICATION HISTORY:
       25-Sep-2006 Written by Bill Davis, PPPL

(See src/idl_cvs/drawrectangle.pro)


FSC_COLOR

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

 PURPOSE:

       The purpose of this function is to obtain drawing colors
       by name and in a device/decomposition independent way.
       The color names and values may be read in as a file, or 104 color
       names and values are supplied with the program. These colors were
       obtained from the file rgb.txt, found on most X-Window distributions.
       Representative colors were chosen from across the color spectrum. To
       see a list of colors available, type:

          Print, FSC_Color(/Names), Format='(6A18)'.

 AUTHOR:

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

 CATEGORY:

       Graphics, Color Specification.

 CALLING SEQUENCE:

       color = FSC_Color(theColor, theColorIndex)

 NORMAL CALLING SEQUENCE FOR DEVICE-INDEPENDENT COLOR:

       If you write your graphics code *exactly* as it is written below, then
       the same code will work in all graphics devices I have tested.
       These include the PRINTER, PS, and Z devices, as well as X, WIN, and MAC.

       In practice, graphics code is seldom written like this. (For a variety of
       reasons, but laziness is high on the list.) So I have made the
       program reasonably tolerant of poor programming practices. I just
       point this out as a place you might return to before you write me
       a nice note saying my program "doesn't work". :-)

       axisColor = FSC_Color("Green", !D.Table_Size-2)
       backColor = FSC_Color("Charcoal", !D.Table_Size-3)
       dataColor = FSC_Color("Yellow", !D.Table_Size-4)
       thisDevice = !D.Name
       Set_Plot, 'toWhateverYourDeviceIsGoingToBe', /Copy
       Device, .... ; Whatever you need here to set things up properly.
       IF (!D.Flags AND 256) EQ 0 THEN $
         POLYFILL, [0,1,1,0,0], [0,0,1,1,0], /Normal, Color=backColor
       Plot, Findgen(11), Color=axisColor, Background=backColor, /NoData, $
          NoErase= ((!D.Flags AND 256) EQ 0)
       OPlot, Findgen(11), Color=dataColor
       Device, .... ; Whatever you need here to wrap things up properly.
       Set_Plot, thisDevice

 OPTIONAL INPUT PARAMETERS:

       theColor: A string with the "name" of the color. To see a list
           of the color names available set the NAMES keyword. This may
           also be a vector of color names. Colors available are these:

           Active            Almond     Antique White        Aquamarine             Beige            Bisque
             Black              Blue       Blue Violet             Brown         Burlywood        Cadet Blue
          Charcoal        Chartreuse         Chocolate             Coral   Cornflower Blue          Cornsilk
           Crimson              Cyan    Dark Goldenrod         Dark Gray        Dark Green        Dark Khaki
       Dark Orchid          Dark Red       Dark Salmon   Dark Slate Blue         Deep Pink       Dodger Blue
              Edge              Face         Firebrick      Forest Green             Frame              Gold
         Goldenrod              Gray             Green      Green Yellow         Highlight          Honeydew
          Hot Pink        Indian Red             Ivory             Khaki          Lavender        Lawn Green
       Light Coral        Light Cyan        Light Gray      Light Salmon   Light Sea Green      Light Yellow
        Lime Green             Linen           Magenta            Maroon       Medium Gray     Medium Orchid
          Moccasin              Navy             Olive        Olive Drab            Orange        Orange Red
            Orchid    Pale Goldenrod        Pale Green            Papaya              Peru              Pink
              Plum       Powder Blue            Purple               Red              Rose        Rosy Brown
        Royal Blue      Saddle Brown            Salmon       Sandy Brown         Sea Green          Seashell
          Selected            Shadow            Sienna          Sky Blue        Slate Blue        Slate Gray
              Snow      Spring Green        Steel Blue               Tan              Teal              Text
           Thistle            Tomato         Turquoise            Violet        Violet Red             Wheat
             White            Yellow

           In addition, these system colors are available if a connection to the window system is available.

           Frame   Text   Active   Shadow   Highlight   Edge   Selected   Face

           The color WHITE is used if this parameter is absent or a color name is mis-spelled. To see a list
           of the color names available in the program, type this:

              IDL> Print, FSC_Color(/Names), Format='(6A18)'

       theColorIndex: The color table index (or vector of indices the same length
           as the color name vector) where the specified color is loaded. The color table
           index parameter should always be used if you wish to obtain a color value in a
           color-decomposition-independent way in your code. See the NORMAL CALLING
           SEQUENCE for details. If theColor is a vector, and theColorIndex is a scalar,
           then the colors will be loaded starting at theColorIndex.

        When the BREWER keyword is set, you must use more arbitrary and less descriptive color
        names. To see a list of those names, use the command above with the BREWER keyword set,
        or call PICKCOLORNAME with the BREWER keyword set:

               IDL> Print, FSC_Color(/Names, /BREWER), Format='(8A10)'
               IDL> color = PickColorName(/BREWER)

         Here are the Brewer names:

       WT1       WT2       WT3       WT4       WT5       WT6       WT7       WT8
      TAN1      TAN2      TAN3      TAN4      TAN5      TAN6      TAN7      TAN8
      BLK1      BLK2      BLK3      BLK4      BLK5      BLK6      BLK7      BLK8
      GRN1      GRN2      GRN3      GRN4      GRN5      GRN6      GRN7      GRN8
      BLU1      BLU2      BLU3      BLU4      BLU5      BLU6      BLU7      BLU8
      ORG1      ORG2      ORG3      ORG4      ORG5      ORG6      ORG7      ORG8
      RED1      RED2      RED3      RED4      RED5      RED6      RED7      RED8
      PUR1      PUR2      PUR3      PUR4      PUR5      PUR6      PUR7      PUR8
      PBG1      PBG2      PBG3      PBG4      PBG5      PBG6      PBG7      PBG8
      YGB1      YGB2      YGB3      YGB4      YGB5      YGB6      YGB7      YGB8
      RYB1      RYB2      RYB3      RYB4      RYB5      RYB6      RYB7      RYB8
       TG1       TG2       TG3       TG4       TG5       TG6       TG7       TG8

 RETURN VALUE:

       The value that is returned by FSC_Color depends upon the keywords
       used to call it, on the version of IDL you are using,and on the depth
       of the display device when the program is invoked. In general,
       the return value will be either a color index number where the specified
       color is loaded by the program, or a 24-bit color value that can be
       decomposed into the specified color on true-color systems. (Or a vector
       of such numbers.)

       If you are running IDL 5.2 or higher, the program will determine which
       return value to use, based on the color decomposition state at the time
       the program is called. If you are running a version of IDL before IDL 5.2,
       then the program will return the color index number. This behavior can
       be overruled in all versions of IDL by setting the DECOMPOSED keyword.
       If this keyword is 0, the program always returns a color index number. If
       the keyword is 1, the program always returns a 24-bit color value.

       If the TRIPLE keyword is set, the program always returns the color triple,
       no matter what the current decomposition state or the value of the DECOMPOSED
       keyword. Normally, the color triple is returned as a 1 by 3 column vector.
       This is appropriate for loading into a color index with TVLCT:

          IDL> TVLCT, FSC_Color('Yellow', /Triple), !P.Color

       But sometimes (e.g, in object graphics applications) you want the color
       returned as a row vector. In this case, you should set the ROW keyword
       as well as the TRIPLE keyword:

          viewobj= Obj_New('IDLgrView', Color=FSC_Color('charcoal', /Triple, /Row))

       If the ALLCOLORS keyword is used, then instead of a single value, modified
       as described above, then all the color values are returned in an array. In
       other words, the return value will be either an NCOLORS-element vector of color
       table index numbers, an NCOLORS-element vector of 24-bit color values, or
       an NCOLORS-by-3 array of color triples.

       If the NAMES keyword is set, the program returns a vector of
       color names known to the program.

       If the color index parameter is not used, and a 24-bit value is not being
       returned, then colorIndex is typically set to !D.Table_Size-1. However,
       this behavior is changed on 8-bit devices (e.g., the PostScript device,
       or the Z-graphics buffer) and on 24-bit devices that are *not* using
       decomposed color. On these devices, the colors are loaded at an
       offset of !D.Table_Size - ncolors - 2, and the color index parameter reflects
       the actual index of the color where it will be loaded. This makes it possible
       to use a formulation as below:

          Plot, data, Color=FSC_Color('Dodger Blue')

       on 24-bit displays *and* in PostScript output! Note that if you specify a color
       index (the safest thing to do), then it will always be honored.

 INPUT KEYWORD PARAMETERS:

       ALLCOLORS: Set this keyword to return indices, or 24-bit values, or color
              triples, for all the known colors, instead of for a single color.

       BREWER: Set this keyword if you wish to use the Brewer Colors, as defined
              in this reference:

              http://www.personal.psu.edu/cab38/ColorBrewer/ColorBrewer_intro.html

       DECOMPOSED: Set this keyword to 0 or 1 to force the return value to be
              a color table index or a 24-bit color value, respectively.

       CHECK_CONNECTION: If this keyword is set, the program will check to see if it can obtain
              a window connection before it tries to load system colors (which require one). If you
              think you might be using FSC_COLOR in a cron job, for example, you would want to set this
              keyword. If there is no window connection, the system colors are not available from the program.

       FILENAME: The string name of an ASCII file that can be opened to read in
              color values and color names. There should be one color per row
              in the file. Please be sure there are no blank lines in the file.
              The format of each row should be:

                  redValue  greenValue  blueValue  colorName

              Color values should be between 0 and 255. Any kind of white-space
              separation (blank characters, commas, or tabs) are allowed. The color
              name should be a string, but it should NOT be in quotes. A typical
              entry into the file would look like this:

                  255   255   0   Yellow

       NAMES: If this keyword is set, the return value of the function is
              a ncolors-element string array containing the names of the colors.
              These names would be appropriate, for example, in building
              a list widget with the names of the colors. If the NAMES
              keyword is set, the COLOR and INDEX parameters are ignored.

                 listID = Widget_List(baseID, Value=GetColor(/Names), YSize=16)


       NODISPLAY: Normally, FSC_COLOR loads "system" colors as part of its palette of colors.
              In order to do so, it has to create an IDL widget, which in turn has to make
              a connection to the windowing system. If your program is being run without a 
              window connection, then this program will fail. If you can live without the system 
              colors (and most people don't even know they are there, to tell you the truth), 
              then setting this keyword will keep them from being loaded, and you can run
              FSC_COLOR without a display. THIS KEYWORD NOW DEPRECIATED IN FAVOR OF CHECK_CONNECTION.

       ROW:   If this keyword is set, the return value of the function when the TRIPLE
              keyword is set is returned as a row vector, rather than as the default
              column vector. This is required, for example, when you are trying to
              use the return value to set the color for object graphics objects. This
              keyword is completely ignored, except when used in combination with the
              TRIPLE keyword.

       SELECTCOLOR: Set this keyword if you would like to select the color name with
              the PICKCOLORNAME program. Selecting this keyword automaticallys sets
              the INDEX positional parameter. If this keyword is used, any keywords
              appropriate for PICKCOLORNAME can also be used. If this keyword is used,
              the first positional parameter can be either a color name or the color
              table index number. The program will figure out what you want.

       TRIPLE: Setting this keyword will force the return value of the function to
              *always* be a color triple, regardless of color decomposition state or
              visual depth of the machine. The value will be a three-element column
              vector unless the ROW keyword is also set.

       In addition, any keyword parameter appropriate for PICKCOLORNAME can be used.
       These include BOTTOM, COLUMNS, GROUP_LEADER, INDEX, and TITLE.

 OUTPUT KEYWORD PARAMETERS:

       CANCEL: This keyword is always set to 0, unless that SELECTCOLOR keyword is used.
              Then it will correspond to the value of the CANCEL output keyword in PICKCOLORNAME.

       COLORSTRUCTURE: This output keyword (if set to a named variable) will return a
              structure in which the fields will be the known color names (without spaces)
              and the values of the fields will be either color table index numbers or
              24-bit color values. If you have specified a vector of color names, then
              this will be a structure containing just those color names as fields.

       NCOLORS: The number of colors recognized by the program. It will be 104 by default.

 COMMON BLOCKS:
       None.

 SIDE EFFECTS:
       None.

 RESTRICTIONS:

   Required programs from the Coyote Library:

      http://www.dfanning.com/programs/error_message.pro
      http://www.dfanning.com/programs/pickcolorname.pro

 EXAMPLE:

       To get drawing colors in a device-decomposed independent way:

           axisColor = FSC_Color("Green", !D.Table_Size-2)
           backColor = FSC_Color("Charcoal", !D.Table_Size-3)
           dataColor = FSC_Color("Yellow", !D.Table_Size-4)
           Plot, Findgen(11), Color=axisColor, Background=backColor, /NoData
           OPlot, Findgen(11), Color=dataColor

       To set the viewport color in object graphics:

           theView = Obj_New('IDLgrView', Color=FSC_Color('Charcoal', /Triple))

       To change the viewport color later:

           theView->SetProperty, Color=FSC_Color('Antique White', /Triple)

       To load the drawing colors "red", "green", and "yellow" at indices 100-102, type this:

           IDL> TVLCT, FSC_Color(["red", "green", and "yellow"], /Triple), 100

 MODIFICATION HISTORY:

       Written by: David W. Fanning, 19 October 2000. Based on previous
          GetColor program.
       Fixed a problem with loading colors with TVLCT on a PRINTER device. 13 Mar 2001. DWF.
       Added the ROW keyword. 30 March 2001. DWF.
       Added the PICKCOLORNAME code to the file, since I keep forgetting to
          give it to people. 15 August 2001. DWF.
       Added ability to specify color names and indices as vectors. 5 Nov 2002. DWF.
       Fixed a problem with the TRIPLE keyword when specifying a vector of color names. 14 Feb 2003. DWF.
       Fixed a small problem with the starting index when specifying ALLCOLORS. 24 March 2003. DWF.
       Added system color names. 23 Jan 2004. DWF
       Added work-around for WHERE function "feature" when theColor is a one-element array. 22 July 2004. DWF.
       Added support for 8-bit graphics devices when color index is not specified. 25 August 2004. DWF.
       Fixed a small problem with creating color structure when ALLCOLORS keyword is set. 26 August 2004. DWF.
       Extended the color index fix for 8-bit graphics devices on 25 August 2004 to
         24-bit devices running with color decomposition OFF. I've concluded most of
         the people using IDL don't have any idea how color works, so I am trying to
         make it VERY simple, and yet still maintain the power of this program. So now,
         in general, for most simple plots, you don't have to use the colorindex parameter
         and you still have a very good chance of getting what you expect in a device-independent
         manner. Of course, it would be *nice* if you could use that 24-bit display you paid
         all that money for, but I understand your reluctance. :-)   11 October 2004. DWF.
       Have renamed the first positional parameter so that this variable doesn't change
         while the program is running. 7 December 2004. DWF.
       Fixed an error I introduced on 7 December 2004. Sigh... 7 January 2005. DWF.
       Added eight new colors. Total now of 104 colors. 11 August 2005. DWF.
       Modified GUI to display system colors and removed PickColorName code. 13 Dec 2005. DWF.
       Fixed a problem with colorIndex when SELECTCOLOR keyword was used. 13 Dec 2005. DWF.
       Fixed a problem with color name synonyms. 19 May 2006. DWF.
       The previous fix broke the ability to specify several colors at once. Fixed. 24 July 2006. DWF.
       Updated program to work with 24-bit Z-buffer in IDL 6.4. 11 June 2007. DWF
       Added the CRONJOB keyword. 07 Feb 2008. DWF.
       Changed the CRONJOB keyword to NODISPLAY to better reflect its purpose. 7 FEB 2008. DWF.
       Added the BREWER keyword to allow selection of Brewer Colors. 15 MAY 2008. DWF.
       Added the CHECK_CONNECTION keyword and depreciated the NODISPLAY keyword for cron jobs. 15 MAY 2008. DWF.

(See src/idl_cvs/fsc_color.pro)


MK_JPEG

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       MK_JPEG
 PURPOSE:
        make a bit-map color jpeg file of an IDL window for (viewable)
	 insertion into MS Word, or Powerpoint documents.
 CATEGORY:
       Graphics, Publication
 CALLING SEQUENCE:
       IDL> mk_jpeg, FILENAME=filename, WINDOW=window, /VERBOSE
 INPUTS:
       None required 
 KEYWORD PARAMETERS:
       Optional Inputs:
	  filename - Name of output file; Default='idljpeg.jpg'
	  Window   - window number to dump to file
   	  VERBOSE - If set, print debugging information
 OUTPUTS:
       Just the file               			out
 COMMON BLOCKS:
       NONE
 EXAMPLE:
	IDL> LoadCT, 5
	IDL> TH_IMAGE_CONT, dist(400)	; make a color contour with color bar
	IDL> mk_jpeg, filename='myjpeg.jpg'
 NOTES:
 	do not call mk_color, or other things that limit the number of colors,
 	before running this, so you get 256 colors.

	You must have priviledges to write the file.
 MODIFICATION HISTORY:
	30-Aug-2004 Added test for truecolor (24-bit color), which seems
		    to be needed for Windows
       22-Feb-00 Written by Bill Davis, PPPL; with thanks to Dave Fanning 

(See src/idl_cvs/mk_jpeg.pro)


PICKCOLORNAME

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

 PURPOSE:

       The purpose of this program is to provide a blocking
       or modal widget interface for selecting a color "name".
       The program uses colors familiar to the FSC_COLOR program,
       and is often used to select a color name for passing to FSC_COLOR.

 AUTHOR:

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

 CATEGORY:

       Graphics, Color Specification.

 CALLING SEQUENCE:

       colorName = PickColorName(startColorName)

 OPTIONAL INPUT PARAMETERS:

       startColorName: A string with the "name" of the color. Colors available are these:

            Almond     Antique White        Aquamarine             Beige            Bisque             Black
              Blue       Blue Violet             Brown         Burlywood        Cadet Blue          Charcoal
        Chartreuse         Chocolate             Coral   Cornflower Blue          Cornsilk           Crimson
              Cyan    Dark Goldenrod         Dark Gray        Dark Green        Dark Khaki       Dark Orchid
          Dark Red       Dark Salmon   Dark Slate Blue         Deep Pink       Dodger Blue         Firebrick
      Forest Green              Gold         Goldenrod              Gray             Green      Green Yellow
          Honeydew          Hot Pink        Indian Red             Ivory             Khaki          Lavender
        Lawn Green       Light Coral        Light Cyan        Light Gray      Light Salmon   Light Sea Green
      Light Yellow        Lime Green             Linen           Magenta            Maroon       Medium Gray
     Medium Orchid          Moccasin              Navy             Olive        Olive Drab            Orange
        Orange Red            Orchid    Pale Goldenrod        Pale Green            Papaya              Peru
              Pink              Plum       Powder Blue            Purple               Red              Rose
        Rosy Brown        Royal Blue      Saddle Brown            Salmon       Sandy Brown         Sea Green
          Seashell            Sienna          Sky Blue        Slate Blue        Slate Gray              Snow
      Spring Green        Steel Blue               Tan              Teal           Thistle            Tomato
         Turquoise            Violet        Violet Red             Wheat             White            Yellow


       The color WHITE is used if this parameter is absent.

   If the BREWER keyword is set, you can use the Brewer Color names:

       WT1       WT2       WT3       WT4       WT5       WT6       WT7       WT8
      TAN1      TAN2      TAN3      TAN4      TAN5      TAN6      TAN7      TAN8
      BLK1      BLK2      BLK3      BLK4      BLK5      BLK6      BLK7      BLK8
      GRN1      GRN2      GRN3      GRN4      GRN5      GRN6      GRN7      GRN8
      BLU1      BLU2      BLU3      BLU4      BLU5      BLU6      BLU7      BLU8
      ORG1      ORG2      ORG3      ORG4      ORG5      ORG6      ORG7      ORG8
      RED1      RED2      RED3      RED4      RED5      RED6      RED7      RED8
      PUR1      PUR2      PUR3      PUR4      PUR5      PUR6      PUR7      PUR8
      PBG1      PBG2      PBG3      PBG4      PBG5      PBG6      PBG7      PBG8
      YGB1      YGB2      YGB3      YGB4      YGB5      YGB6      YGB7      YGB8
      RYB1      RYB2      RYB3      RYB4      RYB5      RYB6      RYB7      RYB8
       TG1       TG2       TG3       TG4       TG5       TG6       TG7       TG8

 INPUT KEYWORD PARAMETERS:

       BOTTOM: The colors used in the program must be loaded somewhere
           in the color table. This keyword indicates where the colors
           start loading. By default BOTTOM is set equal to !D.Table_Size-NCOLORS-1.

       BREWER: Set this keyword if you wish to use the Brewer Colors, as defined
              in this reference:

              http://www.personal.psu.edu/cab38/ColorBrewer/ColorBrewer_intro.html

       COLUMNS: Set this keyword to the number of columns the colors should
           be arranged in.

       FILENAME: The string name of an ASCII file that can be opened to read in
           color values and color names. There should be one color per row
           in the file. Please be sure there are no blank lines in the file.
           The format of each row should be:

              redValue  greenValue  blueValue  colorName

           Color values should be between 0 and 255. Any kind of white-space
           separation (blank characters, commas, or tabs) are allowed. The color
           name should be a string, but it should NOT be in quotes. A typical
           entry into the file would look like this:

               255   255   0   Yellow

       GROUP_LEADER: This identifies a group leader if the program is called
           from within a widget program. Note that this keyword MUST be provided
           if you want to guarantee modal widget functionality. (If you don't know
           what this means, believe me, you WANT to use this keyword, always.)

       INDEX: This keyword identifies a color table index where the selected color
           is to be loaded when the program exits. The default behavior is to restore
           the input color table and NOT load a color.

       TITLE: This keyword accepts a string value for the window title. The default
           is "Select a Color".

 OUTPUT KEYWORD PARAMETERS:

       CANCEL: On exit, this keyword value is set to 0 if the user selected
           the ACCEPT button. IF the user selected the CANCEL button, or
           closed the window in any other way, this keyword value is set to 1.

 COMMON BLOCKS:

       None.

 SIDE EFFECTS:

       Colors are loaded in the current color table. The input color table
       is restored when the program exits. This will only be noticable on
       8-bit displays. The startColorName is returned if the user cancels
       or destroys the widget before a selection is made. Users should
       check the CANCEL flag before using the returned color.

 EXAMPLE:

       To call the program from the IDL comamnd line:

         IDL> color = PickColorName("red") & Print, color

       To call the program from within a widget program:

         color = PickColorName("red", Group_Leader=event.top) & Print, color

 MODIFICATION HISTORY:

       Written by: David W. Fanning, 31 August 2000.
       Modified program to read colors from a file and to use more
         colors on 24-bit platforms. 16 October 2000. DWF.
       Added the COLUMNS keyword. 16 October 2000. DWF.
       Fixed a small problem with mapping a modal widget. 2 Jan 2001. DWF
       Now drawing small box around each color. 13 March 2003. DWF.
       Added eight new colors. Total now of 104 colors. 11 August 2005. DWF.
       Modified GUI to display system colors. 13 Dec 2005. DWF.
       Added BREWER keyword to allow Brewer Colors. 15 May 2008. DWF.

(See src/idl_cvs/pickcolorname.pro)


PSWINDOW

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

 PURPOSE:

    This function is used to calculate the size of a PostScript
    window that has the same aspect ratio (ratio of height to
    width) as the current display graphics window. It creates
    the largest possible PostScript output window with the
    desired aspect ratio. This assures that graphics output
    looks similar, if not identical, to PostScript output.

 AUTHOR:

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

 CATEGORY:

    Graphics.

 CALLING SEQUENCE:

    pageInfo = PSWINDOW()

 INPUTS:

    None.

 KEYWORD PARAMETERS:

    CM: Normally the structure value that is returned from this
    function reports its values in inches. Setting this keyword
    causes the return values to be in units of centimeters.

    FUDGE: A quick way to set symetrical XFUDGE and YFUDGE factors.
    If this keyword is set to a value, XFUDGE and YFUDGE keywords are
    set to the same value.

    LANDSCAPE: Normally this function assumes a PostScript window
    in Portrait mode. Setting this keyword assumes you want
    the graphic in Landscape mode.

    MARGIN:  The margin around the edges of the plot. The value must be
    a floating point value between 0.0 and 0.5. It is expressed in
    normalized coordinate units. The default margin is 0.15.

    PAGESIZE: Set this keyword to a string indicating the type
    of PostScript page size you want. Current values are "LETTER",
    "LEGAL", and "A4". Default is "LETTER".

    PRINTER: Set this keyword if the output will be used to
    configure the PRINTER device, rather than the PS device.
    (In the PRINTER device, offsets are always calculated from
    the lower-left corner of the page and do not rotate in
    Landscape mode, as they do with the PS device.) Note that
    the PRINTER device is only able to accept these keywords
    in IDL 5.1 and higher.

    XFUDGE: Printers calculate the offset point from the printable
    edge of the paper (sometimes), rather from the corner of the paper.
    For example, on my Lexmark printer, both X and Y offsets are
    calculated from a point 0.25 inches in from the edge. This keyword
    allows you to set a "fudge" factor that will be subtracted from
    the XOFFSET that is returned to the user. This allows you to create
    output that is centered on the page. The fudge factor should be in
    the same units as the returned size and offset values.

    YFUDGE: Printers calculate the offset point from the printable
    edge of the paper (sometimes), rather from the corner of the paper.
    For example, on my Lexmark printer, both X and Y offsets are
    calculated from a point 0.25 inches in from the edge. This keyword
    allows you to set a "fudge" factor that will be subtracted from
    the YOFFSET that is returned to the user. This allows you to create
    output that is centered on the page. The fudge factor should be in
    the same units as the returned size and offset values.

 OUTPUTS:

    pageInfo: The output value is a named structure defined like
    this:

      pageInfo = {PSWINDOW_STRUCT, XSIZE:0.0, YSIZE:0.0, $
         XOFSET:0.0, YOFFSET:0.0, INCHES:0, PORTRAIT:0, LANDSCAPE:0}

    The units of the four size fields are inches unless the CM
    keyword is set.

    The output can be used to immediately configure the PostScript
    or Printer device, like this:

       Set_Plot, 'PS' ; or 'PRINTER'
       Device, _Extra=pageInfo

 RESTRICTIONS:

    The aspect ratio of the current graphics window is calculated
    like this:

       aspectRatio = FLOAT(!D.Y_VSIZE) / !D.X_VSIZE

 EXAMPLE:

    To create a PostScript output window with the same aspect
    ratio as the curently active display window, type:

     pageInfo = PSWINDOW()
     SET_PLOT, 'PS'
     DEVICE, _Extra=pageInfo

     To configure the PRINTER device:

     pageInfo = PSWINDOW(/Printer, Fudge=0.25)
     SET_PLOT, 'PRINTER'
     DEVICE, _Extra=pageInfo

 MODIFICATION HISTORY:

    Written by: David Fanning, November 1996.
       Fixed a bug in which the YOFFSET was calculated incorrectly
          in Landscape mode. 12 Feb 97.
       Took out a line of code that wasn't being used. 14 Mar 97.
       Added correct units keyword to return structure. 29 JUN 98. DWF
       Fixed a bug in how landscape offsets were calculated. 19 JUL 99. DWF.
       Fixed a bug in the way margins were used to conform to my
          original conception of the program. 19 JUL 99. DWF.
       Added Landscape and Portrait fields to the return structure. 19 JUL 99. DWF.
       Added PageSize keyword, changed MARGIN keyword, and completely
          rewrote most of the intenal code. 9 FEB 2000. DWF.
       Fixed a bug in how I calculated the aspect ratio. 1 MAR 2000. DWF.
       Added PRINTER keyword to return proper offset values for the
          PRINTER device, where the offset location is not rotated. 1 MAR 2000. DWF.
       Added PRINTER fudge factors to take into account that printer offsets are
          calculated from the printable area of the paper, rather than the corner
          of the paper. 8 AUG 2000. DWF.
  07-Mar-02 made work for correctly for landscape/portrait

(See src/idl_cvs/pswindow.pro)


RIGHT_ASPECT

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

  PURPOSE: 
	Allow contour (or x-y) plots to have the aspect ratio of the data

  CATEGORY: 
	Graphics

  USE:
	IDL> RIGHT_ASPECT, xarray, yarray, IN_POSITION=in_position, $
                  MARGIN=margin, POSITION=position

  KEYWORD PARAMETERS:

     MARGIN: (INPUT)  The margin around the edges of the plot. The value 
    	must be a floating point value between 0.0 and 0.5. It is expressed 
    	in normalized coordinate units. The default margin is 0.15.
    	If margin is a 2-element array, the first value is the left and 
    	bottom margin, and the second is the right and top margin. Otherwise,
    	the right and top margin is set to 1/2 the value of margin.

     IN_POSITION: (INPUT) A 4-element floating array of normalized coordinates.
    	The order of the elements is [x0, y0, x1, y1], similar to the
    	!P.POSITION system variable or the POSITION keyword on any IDL
    	graphic command. Fit resulting contour plot within these limits.

     POSITION: (OUTPUT) A 4-element floating array of normalized coordinates.
    	The order of the elements is [x0, y0, x1, y1], similar to the
    	!P.POSITION system variable or the POSITION keyword on any IDL
    	graphic command. If not present, will set system variable !p.position.

     XRANGE_IN & YRANGE_IN: (INPUTS) - hese override ranges in data

  EXAMPLE: 
	IDL> xarray=FINDGEN(41) & yarray=FINDGEN(21)
	IDL> z = DIST(41,21)
	IDL> in_pos = [.1,.4,.9,.9]		; draw in top part of screen
	IDL> Right_Aspect, xarray, yarray, IN_POS=in_pos, POSITION=out_pos
       IDL> CONTOUR, z, xarray, yarray, XSTYLE=1,YSTYLE=1,  $
		      XMARGIN=[0,0], YMARGIN=[0,0], POSITION=out_pos

  LIMITATIONS: 
	if the POSITION keyword is not used, then the 
	!P.POSITION variable will be set after calling this routine. 
	So, after plotting, do this:  IDL> !P.POSITION = [0,0,0,0]

  MODIFICATIONS:
	07-Dec-2006 Added xrange_in & yrange_in keywords. These override ranges
		  in data
	28-May-03 Added keyword In_Position. Should now work when partial
		  screen specified.
	04-Apr-01 Do like David Fanning routine, ASPECT, so will work with 
		  A4 paper
	14-Mar-01 Take into account !p.multi settings when computing !p.position
		  Also remove adjustment for x & y pixel number differences.
		  Add POSITION keyword (not fully tested)

(See src/idl_cvs/right_aspect.pro)


RIGHTYAXISLIMITS

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       rightYaxisLimits
 PURPOSE:
       Widget to set some Y Axis values for the right-hand axis
	in mdsw
 CATEGORY:
       Graphics, Widgets
 CALLING SEQUENCE:
       IDL> rightYaxisLimits
 INPUTS:
       none required  
 KEYWORD PARAMETERS:
    Inputs (Optional):
	nPlots - # of plots to allow for (def=8)
	GROUP_LEADER - This widget is destroyed if it's GL is destroyed
 OUTPUTS:
 COMMON BLOCKS:
       rightAxis
 EXAMPLE:
	IDL> rightYaxisLimits
 NOTES:
	Upgrade could use a user-defined system variable rather than common
 MODIFICATION HISTORY:
	13-Feb-01 Added multiple axes settings
	07-Feb-01 Written by Bill Davis, PPPL

(See src/idl_cvs/rightyaxislimits.pro)


SETPMULTI

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

 PURPOSE:
  	partition the screen into different graphs

  if 7 or less plot boxes, then 1 column of plots
  if more than 7 plot boxes, then 2 columns of plots

 CATEGORY:
       Graphics, Color Specification.

 CALLING SEQUENCE:
	setpmulit, nboxes
	setpmulit, nboxes, /SameXTitles
	setpmulit, nboxes, /SameXTitles, /sameXlabels, /SamePTitles
 INPUTS:
       nboxes: number of plot boxes per page
 KEYWORD PARAMETERS:
	CharSize   : Value desired for !P.CHARSIZE, else guesses
       SameXTitles: If set and non-zero, just place xtitle at bottom
		     (This reserves less vertical space between plots)
       SamePTitles: If set and non-zero, just place title at top
		     (This reserves less vertical space between plots)
       SameXlabels: If set and non-zero, just label x-axis at bottom
		     (This reserves less vertical space between plots)
	NRows	   : Maximum number of rows (default is 7) 
 COMMON BLOCKS:
       SetPMulti_Local

 SIDE EFFECTS:
       Leaves !P.MULTI set unless you call UnSetPMulti.
	Changes character sizes, etc.
 MODIFICATION HISTORY:
	01-May-01 fix for # of rows and columns
	24-Jan-01 Don't force !x.margin[1] to 3. Only reduce this for multi-
		  columns if !x.margin[1] = 3.
	11-Jan-01 Undid setting of !y.ticks, because can't force axis then
	21-Nov-00 Fine tuned !y.multi values; if no columns, make x.margin[1]=3
	18-Sep-00 Corrected SamePtitle keyword use
	24-Jun-99 changed charsize when more than one plot (to 1.4 if rows or cols > 2)
	03-Jun-99 added CHARSIZE keyword [BD]
	Jan-99 - Written by Bill Davis

(See src/idl_cvs/setpmulti.pro)


SETUP_TEK

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

 PURPOSE:
   	Set system variables for tektronix device.
  	Use to direct plots to the Tek window in Versaterm, or to XTC.
 CATEGORY:
	Graphics, Cross-platform plotting

 CALLING SEQUENCE:  
   	setup_tek

 INPUTS:

 KEYWORD PARAMETERS:
    Optional Inputs:
	CharMagnification - magnify !p.charsize (or, if !p.charsize=0, use as charsize)
 OUTPUTS:
	none

 CALLING EXAMPLE:
   	 setup_tek
   	 plot,indgen(11)			; any number of plot commands
   	 unsetup_tek				; send to printer and back to X

 RELATED ROUTINES:
   	unsetup_tek

 LIMITATIONS:
	Y-axis ticklabels may overlay the axis. If so, you may use:
	   IDL> plot, x, y, YTICKFORMAT='betterticklabels', ...	
 SIDE EFFECTS:
	System variables are changed until unsetup_tek is called.

 NOTE:
 MODICATION HISTORY:
   12-Sep-2008 change "/bin/ps -auxw" to "/bin/ps auxw"
   28-Jun-2006 allow for different complier loading in .cshrc
   13-Feb-2006 add XTC calls
   26-Oct-2000 Written by Bill Davis

(See src/idl_cvs/setup_tek.pro)


WRITE_IN_BOX

[Previous Routine] [Next Routine] [List of Routines]
 NAME: 
	WRITE_IN_BOX 
 
 PURPOSE: 
	Writes a text message within a box in a graphics window. 

 CATEGORY: 
	Graphics
 
 Explanation : This procedure writes a short text message within a box-shaped 
               area in a graphics window.  The message may be split at word 
               boundaries into several lines, and the character size and 
               orientation may be adjusted for the text to fit within the box. 
 
 CALLING SEQUENCE:
	IDL> WRITE_IN_BOX, X1, X2, Y1, Y2, TEXT 
 
 Inputs      : X1, X2  = X coordinates of the box limits. 
               Y1, Y2  = Y coordinates of the box limits. 
               TEXT    = ASCII text string containing the message. 
 
 Opt. Inputs : None. 
 
 Outputs     : None. 
 
 Opt. Outputs: None. 
 
 Keywords    : DATA        = If set, then the coordinates are in data units. 
                             This is the default. 
               DEVICE      = If set, then the coordinates are in device units. 
               NORMAL      = If set, then the coordinates are in normalized 
                             units. 
               MAXCHARSIZE = The maximum character size to use in displaying 
                             the message.  If not passed, then determined from 
                             !P.CHARSIZE. 
               COLOR       = Color to use to display the text.  The default is 
                             !COLOR. 
               ALIGNMENT   = Controls the alignment of the text in the box.  A 
                             value of 0 means to left justify the text, 0.5 
                             means center it (default), and 1 stands for right 
                             justification. 
 
 Calls       : None. 
 
 Common      : None. 
 
 Restrictions: X2 must be greater than X1, and Y2 must be greater than Y1. 
 
 Side effects: The appearance of the displayed message may not be optimal if 
               any words are separated by multiple blanks, or by tab 
               characters. 
 
 Category    : Planning, Science. 
 
 Prev. Hist. : None. 
 
 Written     : William Thompson, GSFC, 7 July 1993. 
 
 Modified    : Version 1, William Thompson, GSFC, 7 July 1993. 
               Version 2, William Thompson, GSFC, 24 September 1993. 
                       Added ALIGNMENT keyword based on code provided by Jim 
                       Pendleton, GRO/OSSE NU. 
               Version 3, William Thompson, GSFC, 21 September 1994 
                       Added STRTRIM call. 
 
 Version     : Version 3, 21 September 1994 

(See src/idl_cvs/write_in_box.pro)


XAXISW

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       xAxisW
 PURPOSE:
       Widget to set some X Axis values via the system variable !X
 CATEGORY:
       Graphics, Widgets
 CALLING SEQUENCE:
       IDL> xAxisW
 INPUTS:
       input = whatever.  
 KEYWORD PARAMETERS:
       Optional Keywords:
	  UPDATECALLBACK - a routine to call after axis system variable is set
	  GROUP_LEADER - This widget is destroyed if it's GL is destroyed
 OUTPUTS:
       The system variable !X is changed               	out
 COMMON BLOCKS:
       NONE
 EXAMPLE:
	IDL> xAxisW,  UPDATECALLBACK='myAxisUpdating'
 NOTES:
 MODIFICATION HISTORY:
	29-Apr-08 check for routine being compiled (vs. needing to be found)
		  added a "Refresh" button which, if a proper plotting routine
		  is provided, will replot with any changed settings.
	08-Dec-04 Removed callback test because of compiling on PC
	22-Jan-01 Added Default and Auto Scale buttons [BD]
	20-Sep-00 Added TickLen & GridStyle fields [BD]
       30-Mar-99 Written by Bill Davis, PPPL

(See src/idl_cvs/xaxisw.pro)


YAXISW

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       yAxisW
 PURPOSE:
       Widget to set some Y Axis values via the system variable !Y
 CATEGORY:
       Graphics, Widgets
 CALLING SEQUENCE:
       IDL> yAxisW
 INPUTS:
       input = whatever.  
 KEYWORD PARAMETERS:
       Optional Keywords:
	  UPDATECALLBACK - a routine to call after axis system variable is set
	  GROUP_LEADER - This widget is destroyed if it's GL is destroyed
 OUTPUTS:
       The system variable !Y is changed               	out
 COMMON BLOCKS:
       NONE
 EXAMPLE:
	IDL> yAxisW, UPDATECALLBACK='myAxisUpdating'
 NOTES:
	If an application overrides !Y.* parameters, or specifies them on
	the plot command, changing settings with this widget will have no
	affect.
 MODIFICATION HISTORY:
	29-Apr-08 check for routine being compiled (vs. needing to be found)
		  added a "Refresh" button which, if a proper plotting routine
		  is provided, will replot with any changed settings.
	08-Dec-04 Removed callback test because of compiling on PC
	22-Jan-01 Added Default and Auto Scale buttons [BD]
	28-Sep-00 Correct the display of initial values [BD]
	20-Sep-00 Added TickLen & GridStyle fields [BD]
       30-Mar-99 Written by Bill Davis, PPPL

(See src/idl_cvs/yaxisw.pro)


ZAXISW

[Previous Routine] [List of Routines]
 NAME:
       zAxisW
 PURPOSE:
       Widget to set some Z Axis values via the system variable !Y
 CATEGORY:
       Graphics, Widgets
 CALLING SEQUENCE:
       IDL> zAxisW
 INPUTS:
       input = whatever.  
 KEYWORD PARAMETERS:
       Optional Keywords:
	  UPDATECALLBACK - a routine to call after axis system variable is set
	  GROUP_LEADER - This widget is destroyed if it's GL is destroyed
 OUTPUTS:
       The system variable !Y is changed               	out
 COMMON BLOCKS:
       NONE
 EXAMPLE:
	IDL> zAxisW, UPDATECALLBACK='mzAxisUpdating'
 NOTES:
	If an application overrides !Z.* parameters, or specifies them on
	the plot command, changing settings with this widget will have no
	affect.
 MODIFICATION HISTORY:
	17-Oct-00 Written by Bill Davis, PPPL

(See src/idl_cvs/zaxisw.pro)


Category: GUI

[List of Routines]


BITMAPBUTTONS

[Next Routine] [List of Routines]
 NAME:
       bitmapbuttons
 PURPOSE:
       Illustrate use of bitmapbuttons in IDL
 CATEGORY:
       GUI, buttons
 CALLING SEQUENCE:
       IDL> bitmapbuttons
    Then click on buttons and watch them change.
 COMMON BLOCKS:
       none
 NOTES:
	Requires IDL 5.2 or later.
 LIMITATIONS:
	This may not be the easiest way to manage button states
 MODIFICATION HISTORY:
	27-Jan-00 [BD]

(See src/idl_cvs/bitmapbuttons.pro)


COLOR_RESOURCE_EXAMPLE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       color_resource_example
 PURPOSE:
       Example of color buttons on a widget.
 CATEGORY:
       GUI, Color, Example
 CALLING SEQUENCE:
       IDL> color_resource_example
 INPUTS:
       none.  
 KEYWORD PARAMETERS:
       none.  
 OUTPUTS:
       none.  
 EXAMPLE:
	IDL> color_resource_example
 NOTES:
	For IDL color widgets, you need corresponding lines in your 
	~/.Xresources file (on the computer that is managing your X windows!), 
	e.g., :
          
          Idl*colorbuttons*blue*background:blue
          Idl*colorbuttons*red*background: red
          Idl*colorbuttons*lightblue*background: lightblue
          Idl*colorbuttons*green*background: green
          Idl*colorbuttons*purple*background: purple
          Idl*colorbuttons*yellow*background: yellow
          Idl*colorbuttons*white*background: white
          Idl*colorbuttons*gold*background: gold
          Idl*colorbuttons*black*background: black
          Idl*colorbuttons*magenta*background: magenta
          Idl*colorbuttons*orange*background: orange

 LIMITATIONS:
	This works consistantly on PPPL Solaris 2.6 computers. 
	Bug On Linux, the colors initially work, 
	but disappear on subsequent execution!

 MODIFICATION HISTORY:
       18-Apr-03 Written by Bill Davis, PPPL

(See src/idl_cvs/color_resource_example.pro)


COLOR_STATUS_EXAMPLE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       color_status_example
 PURPOSE:
       Example of color status fields on a widget.
 CATEGORY:
       GUI, Example, Color, Monitoring Application
 EXPLANATION:
	Makes two rows, each with two buttons to send a color to an
	adjacent status field. The status field is just a window in which
	the appropriate colors are drawn.  MK_COLOR, or a similar routine,
	should be used for consistant color display.
 CALLING SEQUENCE:
       IDL> color_status_example
 INPUTS:
       none.  
 KEYWORD PARAMETERS:
       none.  
 OUTPUTS:
       none.  
 COMMON BLOCKS:
       info
 ROUTINES USED:
	MK_COLOR
 EXAMPLE:
	IDL> color_status_example
 NOTES:
       The status fields are initially the background color.
	A real program might want to save !D.WINDOW before the TV commands
	and restore it immediately afterwards.
 MODIFICATION HISTORY:
       11-May-00 Written by Bill Davis, PPPL

(See src/idl_cvs/color_status_example.pro)


DIALOG_INPUT

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

 PURPOSE:
     A modal (blocking) dialog widget to input a line of text.
     The dialog must be dismissed, by entering text and pressing the
     Return key, or by clicking on the 'Ok' or 'Cancel' button before
     execution of the calling program can continue.

 TYPE:
     FUNCTION

 CATEGORY:
     GUI, Input, WIDGETS

 CALLING SEQUENCE:
     result = DIALOG_INPUT ()

 INPUTS:
     NONE

 KEYWORD PARAMETERS:

     PROMPT: Optional STRING or STRARR displayed on the widget.
         If the keyword NFIELDS is set, then PROMPT must be a
         STRARR of length NFIELDS.  If NFIELDS is not set, and PROMPT is
         a STRARR, each element of the array will appear on a separate line.

         If not supplied, default = 'Enter Text'

     TITLE: Window title [default = 'dialog_input']

     INITIAL: Initial value to show in the input area.  If PROMPT is 
         supplied, this must be a array of length FIELDS.

     XSIZE, YSIZE: The width and height of the dialog

     WIDTH: Set the width of the input field IN CHARACTERS.  

     NFIELDS: Show multiple input fields.  If PROMPT and/or INITIAL are
         supplied, they must be STRARR of length FIELDS.  
 
     FLOATING, INTEGER, LONG, DOUBLE - type of input
     DIALOG_PARENT: Set this keyword to the widget ID of a widget over
         which the message dialog should be positioned. When displayed,
         the DIALOG_INPUT dialog will be positioned over the specified
         widget. Dialogs are often related to a non-dialog widget tree.
         The ID of the widget in that tree to which the dialog is most
         closely related should be specified.

     RETURN_EVENTS:	
	Set this keyword to make cluster return an event when a
	 is pressed in a text field.  The default is
	not to return events.  

     OK: STRING label for the 'Ok' button (default = '  OK  ' )
     CANCEL: STRING label for the 'Cancel' button (default = 'Cancel')

 OUTPUTS:
     result: STRING or STRARR of input text, or '' if dialog is cancelled

 COMMON BLOCKS:
     NONE

 SIDE EFFECTS:
     Creates a modal widget

 RESTRICTIONS:
     NONE

 DEPENDENCIES:
     NONE

 MODIFICATION HISTORY:
     01-Jun-06 default to return events [BD]
     12-Sep-04 improvement for prompt on just one entry 
		Allow for no cancel button [BD]
     02-Jul-01 Fixed bug for floating point values [BD]
     13-Sep-00 Added RETURN_EVENTS keyword [BD]
     03-Feb-00 Added FLOATING, INTEGER and LONG keywords [BD]

     v1.03: RSM, Aug 1998, Added WIDTH keyword to set the width of the 
            input field IN CHARACTERS.  Fixed layout bug when using NFIELDS.

     v1.02: RSM, May 1998, Non-backward compatible changes to allow multiple
            input fields.

     v1.01: RSM, Mar 1998, fixed error when used with a modal toplevel base.

     v1.0:  Written, Robert.Mallozzi@msfc.nasa.gov, July 1997.

(See src/idl_cvs/dialog_input.pro)


EDITTABLE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       EDITTABLE
 PURPOSE:
       Edit a structure with a table where the second item in the structure 
	is on/off. You can set all items (but the first) on, off, or to a specific value.
	If there are more rows than will fit on your screen, it will make new columns.
 CATEGORY:
       GUI, Editor, Structures
 CALLING SEQUENCE:
       IDL> newStruct= editTable( struct )
 INPUTS:
       struct = structure where all tags have same number of elements, and the second
		 one is for on/off
 KEYWORD PARAMETERS:
	nrows - defaults to scFrac  of screen
	noFields - if set, do not show fields, other than on/off
	labels - labels of columns, else use tagnames
	scFrac= fraction (roughly) of y length to use
	title - window title
	col1Title - title of first column, else use tagname
	fieldSz - size of all numeric fields (defaults to 12)
	verbose - if set, print some info
	debug - if set, stop in the middle
 OUTPUTS:
       newStruct = edited structure
 EXAMPLE:

    items = replicate( '\OPERATIONS::F_FLEVVL', 40 )
    nitems = n_elements( items )
    for i=0,nitems-1 do items[i]=items[i]+string(i,format='(i2.2)')

    onoffs = replicate( 1, nitems )
    errvals = replicate( 1.e6, nitems )
    more = errvals
    third =replicate( 1, nitems )
    forth=third

    struct = { items : items, onoffs : onoffs, errvals : errvals, more:more, $
 		third:third, forth:forth}

    s= edittable( struct, title='My Dets')

 MODIFICATION HISTORY:
	WRITTEN 19-Jan-2005 by Bill Davis for Jon Menard 

(See src/idl_cvs/edittable.pro)


GET_TEXT_INPUT

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

 PURPOSE:
       Prompt the user for input with a question and
       return the text string typed by user.
       For X-windows the input is through a text widget, in the middle of 
       the screen, and the text widget waits until carriage return is entered.
       Otherwise input is in the terminal window, with a beep to alert user.

 CATEGORY:
       GUI, Input
 CALLING:
       text = get_text_input( question )

 INPUTS:
       question = string(s), prompt for input, default is null string.
               If an array is passed, each element is shown on its own line.

 KEYWORDS:
       DEFAULT_INPUT = optional string, setting the default response.

 OUTPUTS:
       Function returns the text string entered by user,
       with leading and trailing blanks removed.

 HISTORY:
       Written, Frank Varosi NASA/GSFC 1993.
       F.V.1997, question can be a string array, shown as multiple lines.

(See src/idl_cvs/get_text_input.pro)


MK_PDMENU

[Previous Routine] [List of Routines]
 NAME:
       mk_pdmenu

 PURPOSE:
       make a structure for a pull down menu for CW_PDMENU routine

 CATEGORY:
	GUI, Programming

 CALLING SEQUENCE:
        menu = mk_pdmenu( list )

 INPUTS:
       list - string array      in

 KEYWORD PARAMETERS:
	maxPerSubMenu = max # of menu items per sub-menu. If not specified,
			will try to limit max number to fit on screen.
	MenuTitle = menu title (Default=Select)

 OUTPUTS:
	menu - structure which can be input to CW_PDMenu

 EXAMPLE:
	pro test_pdmenu
	base = WIDGET_BASE()
	colID=WIDGET_BASE(base,/col)

	Printer_List = list_printer_unix( )
	Printer_List = Printer_List( sort( Printer_List ))

	printer_pdmenu = MK_PDMENU( Printer_List, maxPerSubMenu=20 )
	menu = CW_PDMENU(colID, printer_pdmenu, /RETURN_FULL_NAME, /MBAR)

	butID = WIDGET_BUTTON(colID, VALUE='Quit', UVALUE='Quit')
	WIDGET_CONTROL, /REALIZE, base
	repeat begin
	  ev = WIDGET_EVENT(base)
	  PRINT, ev.value
	end until ev.value eq 'Quit'
	WIDGET_CONTROL, /DESTROY, base
	stop
	end

 COMMON BLOCKS:

 NOTES:

 MODIFICATION HISTORY:
	11-Apr-03 make default maxPerSubMenu fit on screen, if not given
	27-Jan-03 Automatically make submenus when list of items is large
	26-Mar-99 by Bill Davis

(See src/idl_cvs/mk_pdmenu.pro)


Category: Image Processing

[List of Routines]


BIN2D

[Next Routine] [List of Routines]
 NAME:
       Bin2D
 PURPOSE:
       Create a density image (2D histogram) from arrays of (x,y) points,
       or create an image of a function from arrays of ( x, y, f(x,y) ) data.
       In first case each pixel counts # of (x,y) points falling into
       a 2D bin (box), thus forming an image of counters. In optional case,
       each pixel is the average of all f(x,y) data falling into the box.
       Boxes are determined by dividing the (x,y) range into a uniform grid.
 CATEGORY:
	Image Processing
 CALLING EXAMPLES:
       imh = Bin2D( x, y, NPIX=64, XRAN=[0,20], YRAN=[-5,5] )
       imz = Bin2D( x, y, FXY=z, NPIX=[200,100] )
 INPUTS:
       X = array (any dimension) of x values.
       Y = array of y values, should correspond to x array.
               optionally, x can be of the form [[x],[y]]
               containing both x and y coordinates as rows of matrix,
               and then argument y should not be specified.
 KEYWORDS:
       XRAN and YRAN : specify the x,y range to be mapped into the image.
                       Common Bin2D, xminc,xmaxc, yminc,ymaxc
                       can also specify the x,y range if keywords are not used,
                       otherwise the defaults = min-max ranges of x and y.
       NPIXELS = 1 or 2 element integer array specifying size of result,
                       (single value means square image), default = [64,64].
      /NOCLIP means do not bother checking if (x,y) are within range (faster).
       TYPE_VAR = type code specifying the IDL variable type of result,
               (1=byte, 2=short, 3=Long, 4=float,... default=2, short integer).
 KEYWORDS (optional):
       IMAGE_DENSITY = an existing image of counters (2D histogram)
                       to which the result is added (overrides NPIX=).
       FXY = array giving z = f(x,y) for the purpose of binning into an image
               however, bins with no (x,y) data points are left = zero.
               (NOTE: must specify XRAN and YRAN, or set /NOCLIP).
   if /BOTH is set and FXY=z is given, then the binned image of z=f(x,y) is
               returned by function, and an image of (x,y) density is
               returned via the keyword IMAGE_DENSITY.
 OUTPUTS:
       Result of function is an image of the density of (x,y) points, or an
       image of scalar field function if z values are given at (x,y) points.
 PROCEDURE:
       Binning is performed by finding number of (x,y) duplicates
       at each pixel,  using the IDL sort and where functions.
 HISTORY:
       written Frank Varosi, U.of MD., 1988.
               F.V. 1990, modif. for IDL-V2.

(See src/idl_cvs/bin2d.pro)


CINE_LOAD

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

  A MORE GENERAL VERSION OF THIS IS CALLED CINELOAD.PRO, which works for
	8-bit files, as well.

 NAME:
       cine_load
 PURPOSE:
       Read a frame from a .cin file from a Phantom 7 camera.
 CATEGORY:
       Image Processing
 CALLING SEQUENCE:
       IDL> image = cine_load( filename, framenum, exposure)
 INPUTS:
 KEYWORD PARAMETERS:
   INPUT:
       filename - a .cin file
       framenum - integer of frame number
       verbose - if set, will print informational output
       status - 1=OK, 0 means problem
   OUTPUT:
   fps - frames per seconc
   exposure - in microseconds (probably)
 OUTPUTS:
       none.
 COMMON BLOCKS:
       none
 EXAMPLE:
   IDL> cine_time,'/p/camdata/dust/nstx121048.cin',time

   IDL> img=cine_load( '/p/nstxusr2/phantom4/MIRO_130289.cin', 100 )

     for MIRO file:
       IDL> img=cine_load( '/p/camdata/dust/nstx121048.cin', 10, fps, exposure)
   help
   EXPOSURE        ULONG     =            9
   FPS             ULONG     =        68000
   IMG             UINT      = Array[128, 128]
   TIME            DOUBLE    = Array[27201]

 NOTES:
 MODIFICATION HISTORY:
   17-Jun-2008 check for existence of file 
   16-mar-2007 moved file info reas into initial file access code so don't have
         to be repeated for every frame
   29-Jan-2007 better error handling
       Written by Bill Davis, for Lane Roquemore, 31-May-2006
           from cine_display_range.pro written by Ricky Maqueda.

(See src/idl_cvs/cine_load.pro)


CINE_TIME

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       cine_time
 PURPOSE:
       Read a frame from a .cin file from a Phantom 7 camera.
 CATEGORY:
       Image Processing
 CALLING SEQUENCE:
       IDL> cine_load, filename, times, frames
 INPUTS:
 KEYWORD PARAMETERS:
   INPUT:
   	filename - a .cin file
   OUTPUT:
	times - array of times in seconds of frames
   	frames - array of frame numbers
	xsize - horizontal size of an image
	ysize - vertical size of an image
 EXAMPLE:
	IDL> cine_time,'/p/camdata/dust/nstx121048.cin', time

 NOTES:
 MODIFICATION HISTORY:
   17-Jul-2008 return FirstImage (first frame)
   17-Jun-2008 check for existence of file 
   27-Apr-2007 commented out time-correction code which was giving -NaN for
		/p/nstxusr2/phantom4/flipped_123648.cin (exposure time was changed)
   Written by Bill Davis, for Lane Roquemore, 31-May-2006
           from program written by Ricky Maqueda.

(See src/idl_cvs/cine_time.pro)


CLICKON7

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       clickon7
 PURPOSE:
       Allow recording of click locations on .cin files from a 
	Phantom 4 or 7 camera. Also displays files from the color Miro camera.
	Also, view animations and save frames at JPEG, GIF or TIFF files.
 CATEGORY:
       Image Processing
 CALLING SEQUENCE:
       IDL> clickon7, filename
 INPUTS:
       filename - a .cin file 
		(or will pop dialog box)
 KEYWORD PARAMETERS:
	nBG - number of background frames. If=0 (the default) no background subtraction is done
	bgFrame - the first frame of the background (default=0)
	ByteScale - if =0, will not byte scale image before displaying.
	box - if set, will try to handle two boxes that show up on one of Ricky's cameras
	drawXSize - the horizontal size in pixels of the image window
	INTERP - if =1, pixels will be smoothed, rather than replicated
	colorTable - default to IDL color table 3 (hot metal)
	gamma - gamma correction.
	startTime - start time in milliseconds
	maxPlayMinutes - defaults to 60
    (optional) 
	radius - 1/2 of square in pixels drawn around click point, setting the area
		to be used for the maxval calculation.
       GROUP_LEADER - Group_Leader ID
 OUTPUTS:
       none.
 COMMON BLOCKS:
       none
 ROUTINES USED:
	MK_COLOR, usingXwindows
 EXAMPLE:
	IDL> clickon7	; you will be prompted for a .cin file

    or IDL> clickon7,'/p/camdata/dust/nstx121048.cin',start=200
    or IDL> clickon7,'/p/nstxusr3/miro/MIRO_130708.cin',start=232
	IDL> clickon7,file='/p/nstxusr2/nstxphantom7/NSTX_130389.cin',starttime=194.974,/debug
	IDL> clickon7,file='/p/nstxusr3/miro/MIRO_130708.cin',starttime=232,/power,/debug
 NOTES:
 MODIFICATION HISTORY:
	10-Nov-2008 cleaned up incompatibility with tvimage. Added menu options for # of
		    background frames to subtract, start frame for background subtraction,
		    turn off/on byte scaling of image.
	04-Aug-2008 added Frame Time slider widget
	31-Jul-2008 Added imageproc option to Special menu & gamma setting to Edit menu.
		    Also added median smoothing option.
	16-Jul-2008 Can ungzip .gz files automatically
	14-Jul-2008 Added support for color images. Added GAMMA keyword.
	10-Jun-2008 Added XSectionW option. Changed default to no background subtraction
	15-May-2008 Added maxPlayMinutes, so movie won't run for ever (Default to 1 hour)
	12-May-2008 made advance and backup buttons more clear. Added noLoad keyword so
		    color palette loading can be surpressed.
	09-May-2008 Fixed bug when getting new file. Loop continously in movie mode
	15-Feb-2008 Add options to save as JPEG, GIF & TIFF
	27-Aug-2007 change Advance to Advance (so don't add one when incrementing)
	15-Mar-2007 add animation feature
	22-Oct-2006 fixed bug for Jump-to entry
	26-Oct-2006 added Advance-number-of-frames box
	19-Oct-2006 added BG subtraction and "box disquising"
       01-Jun-2006 Written by Bill Davis, PPPL

(See src/idl_cvs/clickon7.pro)


CLICKONW

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       clickonw
 PURPOSE:
       Allow recording of click locations on Tiff files.
	e.g., can be used for tracking dust particles from fast camera
	      images of plasmas
 CATEGORY:
       Image Processing
 CALLING SEQUENCE:
       IDL> clickonw, filename
 INPUTS:
       filename - an image file, such tiff, pbm, gif, etc. 
		(or will pop dialog box for TIFF file)
 KEYWORD PARAMETERS:
    (optional) 
	drawXSize - the horizontal size in pixels of the image window
	INTERP - if =0, pixels will be blown up as is, rather than being smoothed
	colorTable - default to IDL color table 3 (hot metal)
	startTime - start time in seconds
	radius - 1/2 of square in pixels drawn around click point, setting the area
		to be used for the maxval calculation.
       GROUP_LEADER - Group_Leader ID
 OUTPUTS:
       none.
 COMMON BLOCKS:
       none
 ROUTINES USED:
	MK_COLOR, usingXwindows
 EXAMPLE:
	IDL> clickonw	; you will be prompted for an image file
 NOTES:
	use clickon7 for files from Phantom 7 cameras.
 MODIFICATION HISTORY:
	29-Jun-2006 Fixed the back button when reading individual files
       20-Apr-2006 Written by Bill Davis, PPPL

(See src/idl_cvs/clickonw.pro)


CONVOLVE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       CONVOLVE
 PURPOSE:
       Convolution of an image with a Point Spread Function (PSF)
 CATEGORY:
	Image Processing, Math
 EXPLANATION:
       The default is to compute the convolution using a product of 
       Fourier transforms (for speed).

 CALLING SEQUENCE:

	psf = psf_Gaussian( NPIXEL=21, FWHM=5, /NORMALIZE )
       imconv = convolve( image1, psf, FT_PSF = psf_FT )
  or:
       correl = convolve( image1, image2, /CORREL )
  or:
       correl = convolve( image, /AUTO )

 INPUTS:
       image = 2-D array (matrix) to be convolved with psf
       psf = the Point Spread Function, (size < or = to size of image).

 OPTIONAL INPUT KEYWORDS:

       FT_PSF = passes out/in the Fourier transform of the PSF,
               (so that it can be re-used the next time function is called).
       FT_IMAGE = passes out/in the Fourier transform of image.

       /CORRELATE uses the conjugate of the Fourier transform of PSF,
               to compute the cross-correlation of image and PSF,
               (equivalent to IDL function convol() with NO rotation of PSF)

       /AUTO_CORR computes the auto-correlation function of image using FFT.

       /NO_FT overrides the use of FFT, using IDL function convol() instead.
               (then PSF is rotated by 180 degrees to give same result)
 METHOD:
       When using FFT, PSF is centered & expanded to size of image.
 HISTORY:
       written, Frank Varosi, NASA/GSFC 1992.
       Converted to IDL V5.0   W. Landsman   September 1997

(See src/idl_cvs/convolve.pro)


FILTER_IMAGE

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

 PURPOSE:
       Identical to MEDIAN or SMOOTH but handle edges and allow iterations.
 CATEGORY:
       Image Processing
 EXPLANATION:
       Computes the average and/or median of pixels in moving box,
       replacing center pixel with the computed average and/or median,
               (using the IDL smooth or median functions).
       The main reason for using this function is the option to
       also process the pixels at edges and corners of image, and,
       to apply iterative smoothing simulating convolution with Gaussian,
       and/or to convolve image with a Gaussian kernel.

 CALLING SEQUENCE:
       Result = filter_image( image, SMOOTH=box_width, /MEDIAN, /ALL )

 INPUT:
       image = 2-D array (matrix)

 OPTIONAL INPUT KEYWORDS:
       SMOOTH = scalar (odd) integer specifying the width of a square box 
               for moving average, in # pixels.
       /SMOOTH  means use box width = 3 pixels for smoothing.

       MEDIAN = scalar (odd) integer specifying the width of square moving 
               box for median filter, in # pixels.
       /MEDIAN  means use box width = 3 pixels for median filter.
   
       /ALL_PIXELS causes the edges of image to be filtered as well,
               accomplished by reflecting pixels adjacent to edges outward.

       /ITERATE means apply smooth(image,3) iteratively for a count of
               (box_width-1)/2 times (=radius), when box_width >= 5.
               This is equivalent to convolution with a Gaussian PSF
               of FWHM = 2 * sqrt( radius ) as radius gets large.
               Note that /ALL_PIXELS is automatically applied,
               giving better results in the iteration limit.
               (also, MEDIAN keyword is ignored when /ITER is specified).

       FWHM_GAUSSIAN = Full-width half-max of Gaussian to convolve with image. 
                       FWHM can be a single number (circular beam),
                       or 2 numbers giving axes of elliptical beam.

       /NO_FT_CONVOL causes the convolution to be computed directly,
               with IDL function convol.
               The default is to use FFT when factors of size are all LE 13.
               (note that external function convolve handles both cases)

 RESULT:
       Function returns the smoothed, median filtered, or convolved image.
       If both SMOOTH and MEDIAN are specified, median filter is applied first.

 EXAMPLES:
       To apply 3x3 moving median filter and
       then 3x3 moving average, both applied to all pixels:

               Result = filter_image( image, /SMOOTH, /MEDIAN, /ALL )

       To iteratively apply 3x3 moving average filter for 4 = (9-1)/2 times,
       thus approximating convolution with Gaussian of FWHM = 2*sqrt(4) = 4 :

               Result = filter_image( image, SMOOTH=9, /ITER )

       To convolve all pixels with Gaussian of FWHM = 3.7 x 5.2 pixels:

               Result = filter_image( image, FWHM=[3.7,5.2], /ALL )

 EXTERNAL CALLS:
       function psf_gaussian
       function convolve
       pro factor
       function prime          ;all these called only if FWHM is specified.

 PROCEDURE:
       If /ALL_PIXELS or /ITERATE keywords are set then
       create a larger image by reflecting the edges outward,
       then call the IDL median and/or smooth function on the larger image,
       and just return the central part (the orginal size image).
 HISTORY:
       Written, 1991, Frank Varosi, NASA/GSFC.
       FV, 1992, added /ITERATE option.
       FV, 1993, added FWHM_GAUSSIAN= option.
       Converted to IDL V5.0   W. Landsman   September 1997

(See src/idl_cvs/filter_image.pro)


GAMMA_RAISE

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

 PURPOSE:
	Apply gamma correction to an array, presumably an image.

 CATEGORY:
	Image Processing.

 CALLING SEQUENCE:
	newImage = GAMMA_RAISE(image, Gamma)

 INPUTS:
	Gamma:	The value of gamma correction.  A value of 1.0 indicates a
		linear ramp, i.e., no gamma correction.  Higher values of 
		gamma give more contrast.  Values less than 1.0 yield lower 
		contrast.

 KEYWORD PARAMETERS:

 OUTPUTS:
	A gamma-corrected image.

 RESTRICTIONS:
	None.

 PROCEDURE:
	The gamma correction is implemented as x^gamma.

 MODIFICATION HISTORY:
	Written 14-Jul-2008 by Bill Davis

(See src/idl_cvs/gamma_raise.pro)


GETIMAGE

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

 PURPOSE:
       The purpose of this function is to allow the user to open either
       regular or XDR binary image files of two or three dimensions.

 CATEGORY:
       Image Processing, Widgets, File I/O

 CALLING SEQUENCE:
       image = GETIMAGE(filename)

 INPUTS:
       filename: The name of the file to open for reading.

 KEYWORD PARAMETERS:

       CANCEL: An output variable that can be set to a named variable.
       The value of the return variable will be 1 if the user clicked
       the "Cancel" button or if there was a problem reading the file.

       DIRECTORY: The name of the directory the file is located in. By
       default the program looks in the "training" directory under the
       main IDL directory, if one exists. Otherwise, it defaults to the
       current directory.

       FRAMES: The 3rd dimension of a 3D data set. Defaults to 0.

       HEADER: The size of any header information in the file in BYTES.
       Default is 0.

       PARENT: The group leader for this widget program. The PARENT is
       required if GETIMAGE is called from another widget program.

       XDR: Set this keyword if the binary file is of XDR type.

       XOFFSET: This is the X offset of the program on the display. The
       program will be placed approximately in the middle of the display
       by default.

       XSIZE: The size of the 1st dimension of the data.

       YOFFSET: This is the Y offset of the program on the display. The
       program will be placed approximately in the middle of the display
       by default.

       YSIZE: The size of the 2nd dimension of the data.

 COMMON BLOCKS:
       None.

 SIDE EFFECTS:
       A "CANCEL" operation is indicated by a 0 return value.
       Any error in reading the file results in a 0 return value.

 RESTRICTIONS:
       None.

 EXAMPLE:
       To load the image "galaxy.dat" in the $IDL/examples/data
       directory, type:

       image = GETIMAGE('galaxy.dat', DIRECTORY=!DIR + '/examples/data', $
          XSIZE=256, YSIZE=256, Cancel=cancelled, Parent=event.top)
       IF NOT cancelled THEN TV, image

 MODIFICATION HISTORY:
       Written by: David Fanning, 3 February 96.
       Fixed bug that prevented reading INTEGER data. 19 Dec 96.
       Modifed program for IDL 5 MODAL operation. 19 Oct 97.
       Added CANCEL keyword. 27 Oct 97. DWF.
       Fixed CANCLE keyword spelling. Sigh... 29 JUN 98. DWF.

(See src/idl_cvs/getimage.pro)


IMAGEPROC

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

  PURPOSE:
       Demonstrate a few of IDL's image processing features:
       Fourier filtering, pixel scaling, pixel distribution
       (histogram), edge enhancement, dilate & erode,
       convolution, and zooming.

  CATEGORY:
       Image Processing, 2-D Plotting

  CALLING SEQUENCE: 
	IDL> imageproc
 INPUTS:
       input = a 2-D image (optional, otherwise will pop dialog for tiff file

 KEYWORD PARAMETERS:
	NColors - # of colors to use
	Bottom - value to add to bytescaled image
	magnification - magnification factor desired for image
	INTERP - if magnification set, INTERP=1 will cause interpolation
	XSIZE - xsize of displayed image
	YSIZE - ysize of displayed image
  REFERENCE: IDL Reference Guide, IDL User's Guide

  NAMED STRUCTURES:
       none.

  COMMON BLOCS:
       none.

  MODIFICATION HISTORY:
	July, 2004 a few more additions [BD]
	23-Jan-00 Modified from RSI d_imageproc by Bill Davis.
	d_imageproc Written by:  DC, RSI,  1995

(See src/idl_cvs/imageproc.pro)


SHOCKVSTIME

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       shockvstime
 PURPOSE:
       Stack plots of a line from the center of .cin file image at various times
	See http://nstx.pppl.gov/nstx/Software/Help/shockwaves.html for sample images.
	After plotting, ou will be prompted for times for which calculate the 
	speed of the leading edge of the shockwave.
 CATEGORY:
       Image Processing, CINE files.
 CALLING SEQUENCE:
       IDL> shockvstime, filename
 INPUTS:
       filename - a .cin file 
 KEYWORD PARAMETERS:
    INPUTS:
	filename - .cin filename
	title - will default to 'Shock Wave at various times'
	times - times entered in msec (are seconds in file)
	jline - vertical index in image to use for line plot. Defaults to 25
	addIn - vertical space between plots
	inc - increment between files to plot (defaults to 1, which plots all)
	gradient - if set, uses a gradient color palette
	flatFrac - see leadingedge.pro
	deltaPercent -  see leadingedge.pro
	edge - if set, draw symbol at leading edge of shockwave (defined by
		point of increase after a long flat portion.
	cmPerPixel - centimeters per  pixel (Default=0.2423)
	debug - if set, will stop
    RETURNED:
	allData - returns all the data within the time specified
 OUTPUTS:
       none.
 EXAMPLE:
       To get a postscript file:
           IDL> setup_ps, filename='shockvstime.ps', /color
           IDL> shockvstime
           IDL> unsetup_ps

       surftime=findgen(145)/145*(0.00119100-0.000773)*1000 +1.191
       surfx =findgen(128)
       surf = interpPeak(allData)
       for j=1,2 do surf = interpPeak(surf)
       save,surfx,surfTime,surf, file='Surf_50ma.sav'

       shockvstime, /edge, inc=3
 MODIFICATION HISTORY:
       18-Jun-2009 Written by Bill Davis, PPPL, for Lane Roquemore

(See src/idl_cvs/shockvstime.pro)


XSECTIONW

[Previous Routine] [List of Routines]
 NAME:
       xsectionw
 PURPOSE:
       Widget to display an image and x-y plots of cross-sections.
	Color palettes may be loaded, adjusted and saved. 
       Images can be saved as 'jpg','tif','tif','bmp','jpeg,'png', 'ppm', 
	'pgm', or 'gif'
 CATEGORY:
       Image Processing, 2-D Plotting, Files, Graphics
 CALLING SEQUENCE:
       IDL> xsectionw[[, image], x, y]
 INPUTS:
       image - a 2D array. If missing, and Keyword Filename not
	        specified, a dialog box will appear allowing browsing
		for a TIFF image.
	x & y are optional inputs for x & y axes. Must be same dimension as image.
 KEYWORD PARAMETERS:
    (optional) 
	filename - file to read (can be type 'jpg','tif','tif','bmp', 
		   'jpeg,'png','ppm', 'pgm', or 'gif')
	xvals - optional values for X axis
	yvals - optional values for Y axis
	title - title to display at top of plot (Defaults to filename, if relevant)
	xsize - horizontal size of window (default is 0.75 of screen, but > 800)
	ysize - vertical size of window
	xoffset - initial horizontal offset of the widget (DEFAULT=0)
	yoffset - initial vertical offset of the widget (DEFAULT=30)
       INTERP - if magnification set, INTERP=1 will cause interpolation,
		rather than pixel replication.
	max_colors - # used by display (Default is 256)
       NOLOAD - if set, do not load color table
	colorTable - color table to use. Default is 03 (Hot Metal)
	NoCont - if set, no contours are drawn (default)
	file - color table file (for personal color tables)
	(other keywords to th_image_cont.pro may be included)
       GROUP_LEADER - Group_Leader ID
 OUTPUTS:
       none.
 COMMON BLOCKS:
       none
 ROUTINES USED:
	MK_COLOR, usingXwindows, NWORDS, FLIP
 EXAMPLE:
	IDL> xsectionw, dist(200,200)

   For serious testing of zooming, etc.:
	IDL> x=findgen(120)/120
	IDL> y=findgen(50)*!PI
	IDL> d=sin(x*6+1)#cos(y/20+2)
	IDL> d[20:30,*]=-2
	IDL> d[*,35:40]=.5
	IDL> d=d*1000
	IDL> d=d-min(d)
	IDL> th_image_cont,d,x,y
	IDL> xsectionw,d,x,y

 NOTES:
	If you specify max_colors to be something other than 256, and
	want to change color tables, you need to do something like:
		IDL> dum=MK_COLOR( table=3 )
	Using XLOADCT, etc. won't work well, since it loads 256 colors.
 MODIFICATION HISTORY:
	30-Sep-2008 just use channel 0 of 24-bit images
	14-Jul-2008 Handle 24-bit color images (poorly, but doesn't bomb)
	25-Apr-07 Added more modify color table options, and option to save color table.
		  Support more kinds of image files. Can set background color from menu.
		  Can save image or window to files. Added Median Smoothing opt
	25-May-06 added noload keyword
	02-May-06 fixed x-y plot axis limits when zoomed in
	12-Apr-06 added x & y keywords, and made to work with resizing and drawing box
	03-Feb-03 Option to force lines to black or white
       11-Dec-01 Written by Bill Davis, PPPL

(See src/idl_cvs/xsectionw.pro)


Category: Math

[List of Routines]


DT_NICENUMBER

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

  PURPOSE:
 	Makes nice delta time numbers, by rounding to 3 significant digits
	Can be used if you want to know if you have a constant timebase.

 CATEGORY:
       Math, Graphics

 CALLING SEQUENCE:
        niceDts = dt_nicenumber( dts )

 INPUTS:
	dts - an array of numbers

 KEYWORD PARAMETERS:
    Optional Inputs:
	nSignificantDigits - number of significant digits to round to
				(defaults to 3)
    Optional Outputs:
       nDecimals - number of significant decimal places in returned value
  EXAMPLE:
	IDL> dt=[2.0003,2.15,.2003,.20009,22.0004,.250002,.5001,100000.1]
	IDL> print, dt_nicenumber(dt) 
	   2.00000    2.15000   0.200000   0.200000    22.0000   0.250000
	   0.500000    100000.

	IDL> print,  dt_nicenumber( -1.876e6 ) 
 NOTES:
	see nicenumber.pro to round to numbers like 1, 2, 2.5, 5, etc.,
	which might be time intervals for older digitizer rates.
  HISTORY:
	05-Nov-2008 corrected for numbers like -1.876e6
	26-Sep-2005 fixed nToShift for nums less than zero (like 0.0016)
	26-Jul-04 work OK for 0
  	03-Nov-00 Rewrote [BD]

(See src/idl_cvs/dt_nicenumber.pro)


FACTOR

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       FACTOR
 PURPOSE:
       Find prime factors of a given number.
 CATEGORY:
	Math
 CALLING SEQUENCE:
     FACTOR, x, p, n
 INPUTS:
      x = Number to factor, scalar positive integer
 OUTPUT PARAMETERS:
      p = Array of prime numbers.    
      n = Count of each element of p. 
 INPUT KEYWORD PARAMETER: 
      /HELP - Display help documentation
 PROCEDURES USED:
      PRIME()
      Also see numfactors, print_fact in the JHUAPL Library
 MODIFICATION HISTORY:
       R. Sterner.  4 Oct, 1988.
       RES 25 Oct, 1990 --- converted to IDL V2.
       Johns Hopkins University Applied Physics Laboratory.

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

(See src/idl_cvs/factor.pro)


GAUSSIAN

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       GAUSSIAN
 PURPOSE:
       Compute the 1-d Gaussian function and optionally the derivative
 CATEGORY:
       Math
 EXPLANATION:
       Compute the 1-D Gaussian function and optionally the derivative 
       at an array of points.

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

 INPUTS:
       xi = array, independent variable of Gaussian function.

       parms = parameters of Gaussian, 2 or 3 element array:
               parms(0) = maximum value (factor) of Gaussian,
               parms(1) = mean value (center) of Gaussian,
               parms(2) = standard deviation (sigma) of Gaussian.
               (if parms has only 2 elements then sigma taken from common).

 OPTIONAL OUTPUT:
       pderiv = optional output of partial derivatives,
               computed only if parameter is present in call.

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

       Function returns array of Gaussian evaluated at xi.

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

       IDL> f = gaussian( [0.5,1.5], [10,0,1], DERIV )
       ==> f= [8.825,3.25].   DERIV will be a 2 x 3 array containing the
       numerical derivative at the two points with respect to the 3 parameters.
 
 COMMON BLOCKS:
       common gaussian, sigma
 HISTORY:
       Written, Frank Varosi NASA/GSFC 1992.
       Converted to IDL V5.0   W. Landsman   September 1997

(See src/idl_cvs/gaussian.pro)


NICENUMBER

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       NICENUMBER
 PURPOSE:
       Find a "nice" number close to the given number. Actually, this
	is for older digitizers, so "rounds" to numbers like 
	1, 2, 2.5, 5, etc.
 CATEGORY:
	Math
 CALLING SEQUENCE:
       n = nicenumber(x)
 INPUTS:
       x = given number.              in
 KEYWORD PARAMETERS:
       Keywords:
         /FLOOR finds next nice number le to X.
         /CEIL finds the next nice number ge to X.
         MINOR=m  Returned suggested minor tick spacing.
 OUTPUTS:
       n = nice number close to x.    out
         1, 2, 2.5, or 5 scaled to size of x.
 COMMON BLOCKS:
 NOTES:
       Notes:
         Default operation is useful for finding tick spacings:
         dx = nicenumber((xmx-xmn)/nticks).
         /FLOOR and /CEIL are useful for scaling data plots:
         xmn = nicenumber(min(x),/floor)
         xmx = nicenumber(max(x),/ceil)
         plot, x, y, xrange=[xmn,xmx], . . .
         /floor and /ceil may not give values related to the
         step size, dx.  The following method will:
         ceil(t/dx)*dx is a multiple of dx on the high side of t.
         floor(t/dx)*dx  is a multiple of dx on the low side of t.

        Use DT_NICENUMBER.PRO to "round" to a specific number of digits.

 MODIFICATION HISTORY:
	17-Feb-00 handle 190KHz ! (Bill Davis)
       R. Sterner, 6 Feb, 1990
       R. Sterner, 27 Jan, 1993 --- dropped reference to array.
       R. Sterner, 12 Feb, 1993 --- returned 1 element array as a scalar.

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

(See src/idl_cvs/nicenumber.pro)


PRIME

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	PRIME
 PURPOSE:
	Return an array with the specified number of prime numbers.
 CATEGORY:
	Math
 EXPLANATATION:
	This procedure is similar to PRIMES in the standard IDL distribution,
	but stores results in a common block, and so is much faster 

 CALLING SEQUENCE:
       p = prime(n)
 INPUTS:
       n = desired number of primes, scalar positive integer
 OUTPUTS:
       p = resulting array of primes, vector of positive integers
 COMMON BLOCKS:
       prime_com
 NOTES:
       Note: Primes that have been found in previous calls are
         remembered and are not regenerated.
 MODIFICATION HISTORY:
       R. Sterner  17 Oct, 1985.
       R. Sterner,  5 Feb, 1993 --- fixed a bug that missed a few primes.
       Converted to IDL V5          March 1999

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

(See src/idl_cvs/prime.pro)


PSF_GAUSSIAN

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

 PURPOSE:
       Create a 1-d, 2-d, or 3-d Gaussian with specified FWHM, center 
 CATEGORY:
	Math
 EXPLANATION:
       Return a point spread function having Gaussian profiles,
       as either a 1D vector, a 2D image, or 3D volumetric-data.

 CALLING SEQUENCE:
       psf = psf_Gaussian( NPIXEL=, FWHM= , [/NORMALIZE, /ST_DEV,  )
 or:
       psf = psf_Gaussian( parameters, NPIXEL =  )

 REQUIRED INPUT KEYWORD:
       NPIXEL = number pixels for each dimension, specify as an array,
               or just one number to make all sizes equal.

 OPTIONAL KEYWORDS:

       NDIMEN = dimension of result: 1 (vector), 2 (image), or 3 (volume),
               default = 2 (an image result).

       FWHM = the desired Full-Width Half-Max (pixels) in each dimension,
               specify as an array, or single number to make all the same.

       CENTROID = pixels numbers of PSF maximum ( 0.5 is center of a pixel ),
               default is exact center of requested vector/image/volume.

       STDEV = optional way to specify width by standard deviation param.

       XY_CORREL = scalar between 0 and 1 specifying correlation coefficient
               Use this keyword, for example, to specify an elliptical 
               gaussian oriented at an angle to the X,Y axis

       /NORMALIZE causes resulting PSF to be normalized so Total( psf ) = 1.

 INPUTS (optional):

       parameters = an NDIMEN by 3 array giving for each dimension:
                       [ maxval, center, stdev ],  overrides other keywords.

 EXAMPLE:
       Create a 31 x 31 array containing a normalized centered gaussian 
       with an X FWHM = 4.3 and a Y FWHM = 3.6

       IDL> array = PSF_GAUSSIAN( Npixel=31, FWHM=[4.3,3.6], /NORMAL

 EXTERNAL CALLS:
       function Gaussian

 HISTORY:
       Written, Frank Varosi NASA/GSFC 1991.
       Converted to IDL V5.0   W. Landsman   September 1997

(See src/idl_cvs/psf_gaussian.pro)


RUNTOT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       runTot
 PURPOSE:
       compute a running total of an array by calling an external routine
	(this is inefficient in normal IDL)
 CATEGORY:
       Math
 CALLING SEQUENCE:
       IDL> outarray = runTot(inarray)
 INPUTS:
       inarray = a numeric array.  
 KEYWORD PARAMETERS:
       Keywords:
	  HLP - When set, help information is printed.
 OUTPUTS:
       outarray = returned array of running total                 			out
 COMMON BLOCKS:
       NONE
 EXAMPLE:
 	IDL> MDSOPEN, 'operations', 100601
	IDL> ip = MDSVALUE( '\operations::ip_ipf1b_1' )
	IDL> V = runTot( ip )
 NOTES:
       When the routine is called with no parameters, or with the
	keyword hlp set, help information is printed.
 MODIFICATION HISTORY:
       04-Oct-99 Written by Bill Davis, PPPL

(See src/idl_cvs/runtot.pro)


SDEV

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       SDEV
 PURPOSE:
       Returns standard deviation of an array.
 CATEGORY:
	Math
 CALLING SEQUENCE:
       s = sdev(a)
 INPUTS:
       a = input array.               in
 KEYWORD PARAMETERS:
 OUTPUTS:
       s = standard deviation of a.   out
 COMMON BLOCKS:
 NOTES:
 MODIFICATION HISTORY:
	01-Aug-00 Commented-out checks for a major speed up. [BD]
       Written by K. Kostoff, 1/16/85
       Johns Hopkins University Applied Physics Laboratory.
       Modified by B. Gotwols, R. Sterner --- 1 Oct, 1986.

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

(See src/idl_cvs/sdev.pro)


SIGN

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       SIGN
 VERSION:
       3.0
 PURPOSE:
       Gives the sign of X, i.e. 1 for positive, -1 for negative, 0 for 0.
 CATEGORY:
       Math
 CALLING SEQUENCE:
       Result = SIGN(X)
 INPUTS:
    X
       Numerical, otherwise arbitrary.
 OPTIONAL INPUT PARAMETERS:
       None.
 KEYWORD PARAMETERS:
       None.
 OUTPUTS:
       Returns the value of SIGN(X), see above, as an long integer.
 OPTIONAL OUTPUT PARAMETERS:
       None.
 COMMON BLOCKS:
       None.
 SIDE EFFECTS:
       None.
 RESTRICTIONS:
       For complex X the result is SIGN(REAL(X)), the imaginary part is ignored
 PROCEDURE:
       Straightforward.  Using CAST from MIDL.
 MODIFICATION HISTORY:
       Created 15-JUL-1991 by Mati Meron.
       Modified 25-DEC-1991 by Mati Meron.
       Modified 5-DEC-1993 by Mati Meron.  Output type changed to LONG.

(See src/idl_cvs/sign.pro)


TWOSCOMPLEMENT

[Previous Routine] [List of Routines]
  NAME:
	TWOSCOMPLEMENT

  PURPOSE:
 	Taking the Two's Complement of an integer

 CATEGORY:
	Math, Hardware, CAMAC

 CALLING SEQUENCE:
       twoscomp = TwosComplement( int )

 INPUT:
       int - raw encoder value (8, 16 or 32 bit integer)

 OUTPUT:
       twoscomp - Two's complement of input.

 KEYWORDS:
    Optional Input:
	NBITS - # of bits; throw away this bit if there is a carry after 
		adding 1 to the complement. Default is determined by data type.
	IfNeg - Only return the Two's Complement if value negative
 ALGORITHM:

	Taking the Two's Complement of a k-Digit Bitstring:

   1.Complement the bitstring; i.e., change all 0s to 1s and all 1s to 0s; retain all leading 0s in your result. 
   2.Add 1 to this binary number  (if there is a carry of 1 into the (k+1)st position, throw it away so that the
     result is still k-digits). 
   3.The result from (2) is the two's complement of the bitstring 

 COMMENT:
	Works in many cases, but sign bit may get extended in some applications
  MODIFICATION HISTORY:
 	5-Jun-00 WMD Added Nbits & IfNeg Keywords

(See src/idl_cvs/twoscomplement.pro)


Category: MDSplus

[List of Routines]


ADDLABELNODES

[Next Routine] [List of Routines]
 NAME:
       addLabelNodes
 PURPOSE:
       Add LABEL sub-nodes to MDSplus signal nodes reading info from a file
 CATEGORY:
       MDSplus, TCL 
 CALLING SEQUENCE:
       addLabelNodes, shot1, shot2, filename=filename
 INPUTS:
	shot1 = starting shot number to process (defaults to last shot)
	shot2 = last shot number to process (optional)
 KEYWORDS:
	filename - name of file with info - REQUIRED, 
		   see, e.g., BDAVIS$:[CVS.MISC.WF]tauslabel.dat
	   the file must contain 4 columns, separated by white space.  
	   the first column is the tagname (without \), the last column is 
	   the Label text enclosed in double quotes. The middle columns
	   can be any single word or character (file format from another
	   application).
	tree - name of tree -- defaults to 'WF'
 COMMON BLOCKS:
       NONE
 NOTES:
       YOU NEED PRIVILEGES to write to the MDSplus tree.
 LIMITATIONS:
 MODIFICATION HISTORY:
	25-Jan-01 Written by Bill Davis.

(See src/idl_cvs/addlabelnodes.pro)


ADDMDSTAGS

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       addmdstags
 PURPOSE:
       Add tags to MDSplus nodes
 PROCEDURE:
 CATEGORY:
       MDSplus, Summary 
 CALLING SEQUENCE:
       addmdstags, shot=shot, nodes=nodes, tags=tags
 INPUTS:
 KEYWORDS:
	shot - shot number to process
	nodes - MDSplus node names to which tag will added (all in same tree)
	tags - to add
	VERBOSE  - if set, more info is printed
	test  - doesn't write to MDSplus
 EXAMPLE:
       nodes = ['\PASSIVESPEC::TOP.IR.IMG0.RAWDATA.IR_408:TIMES', $
		 '\PASSIVESPEC::TOP.IR.IMG1.RAWDATA.IR_408:TIMES', $
		 '\PASSIVESPEC::TOP.IR.IMG2.RAWDATA.IR_408:TIMES' ]
	tags = ['img0_408_times', 'img1_408_times', 'img2_408_times' ]
	addmdstags, shot=128000, nodes=nodes, tags=tags, /verb, /test
   for i=shot1,shot1+499 do addmdstags, shot=i, nodes=nodes, tags=tags, /verb
 NOTES:
       YOU NEED PRIVILEGES to write to the MDSplus tree.
 LIMITATIONS:
	Divide by zeroes, etc. will cause a message like:
	    % Program caused arithmetic error: Floating illegal operand
 MODIFICATION HISTORY:
	27-Mar-2008 Written by Bill Davis.

(See src/idl_cvs/addmdstags.pro)


ADDSIGNODES

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       addsignodes
 PURPOSE:
       Add signal nodes and tags to a MDSplus tree for many shots
 PROCEDURE:
 CATEGORY:
       MDSplus
 CALLING SEQUENCE:
       addsignodes, shot1, shot2, tags=[tag1,tag2,tag3,...]
 INPUTS:
	shot1 = starting shot number to process
	shot2 = last shot number to process
 KEYWORDS:
	tags - tags to add (if defined in the model tree, you
	       will not need to specify the corresponding nodes).
	nodes = if tags are not defined in the model tree, these are necessary
	tree - MDSplus tree
	usage - for MDSTCL node creation. Default='signal'
	VERBOSE  - if set, more info is printed
	test  - doesn't write to MDSplus
 NOTES:
       YOU NEED PRIVILEGES to write to the MDSplus tree.
 LOGIC:
	finds node names for tags. Then, if node names are not different
	than the "tag" names, does not add tags.
 LIMITATIONS:
	all signals must be in the same tree
 MODIFICATION HISTORY:
	11-Apr-07 changed for Linux (add output= to mdstcl)
	13-Jun-02 Written by Bill Davis.

(See src/idl_cvs/addsignodes.pro)


ADDTREETOTAG

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       addTreeToTag
 PURPOSE:
       return tags with trees merged in
 CATEGORY:
       MDSplus, SCOPE
 CALLING SEQUENCE:
	names = addTreeToTag( tags, trees )
 INPUTS:
   tags - array of tags, e.g., '\ip1' (if tree already there, will not change)
   trees - array of trees (same dimension as tags)
 RETURNED:
	names - tag names with tree in them, e.g., '\engineering::ip1'
 KEYWORDS:
 COMMON BLOCKS:
       none
 EXAMPLE:
 	IDL> print, addTreeToTag( ['\ip1+\ip2'], ['engineering'] )
	\engineering::ip1+\engineering::ip2
 	IDL> print, addTreeToTag( ['\engineering::ip1.blah+\ip2'], ['engineering'] )      
	\engineering::ip1.blah+\engineering::ip2

 LIMITATIONS:
 MODIFICATION HISTORY:
	30-Apr-01 Written by Bill Davis

(See src/idl_cvs/addtreetotag.pro)


BREAKMDSNAME

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

 PURPOSE:
       break an MDS pathname near the middle, if too long

 CATEGORY:
	MDSplus, Strings

 CALLING SEQUENCE:
        newLines = BreakMDSname( line )

 INPUTS:
       line - string containing an MDSplus tag or node name      in

 KEYWORD PARAMETERS:
	MAXLENGTH  - max line length (default 72)  OPTIONAL

 OUTPUTS:
	newlines - string array of MDSplus name broken near middle

 EXAMPLE:
    IDL> line = '\ENGINEERING::OPERATIONS.PC_OH_BR_1_CUR_1'
    IDL> newLines = BreakMDSname( line, MAXLENGTH=25 )

 COMMON BLOCKS:
 NOTES:

 MODIFICATION HISTORY:
	01-Apr-99 Written earlier by Bill Davis

(See src/idl_cvs/breakmdsname.pro)


BREAK_PATH

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

 PURPOSE: 
     Breaks up a path string into its component directories.

 CATEGORY:
       MDSplus, Strings
 CALLING SEQUENCE: 
     Result = BREAK_PATH( PATHS [ /NoCurrent])

 INPUTS: 
     PATHS   = A string containing one or more directory paths.  The
               individual paths are separated by commas, although in UNIX, 
               colons can also be used.  In other words, PATHS has the same 
               format as !PATH, except that commas can be used as a separator 
               regardless of operating system.

               A leading $ can be used in any path to signal that what follows 
               is an environmental variable, but the $ is not necessary.  (In 
               VMS the $ can either be part of the path, or can signal logical
               names for compatibility with Unix.)  Environmental variables
               can themselves contain multiple paths.

 OUTPUT: 
      The result of the function is a string array of directories.
      Unless the NOCURRENT keyword is set, the first element of the array is 
      always the null string, representing the current directory.  All the 
      other directories will end in the correct separator character for the 
      current operating system.

 OPTIONAL INPUT KEYWORD:
      /NOCURRENT = If set, then the current directory (represented by
               the null string) will not automatically be prepended to the
               output.

 PROCEDURE CALLS:
      Functions:  DATATYPE(), breakstring()

 REVISION HISTORY:
       Version 1, William Thompson, GSFC, 6 May 1993.
               Added IDL for Windows compatibility.
       Version 2, William Thompson, GSFC, 16 May 1995
               Added keyword NOCURRENT
       Version 3, William Thompson, GSFC, 29 August 1995
               Modified to use OS_FAMILY
       Version 4, Zarro, GSFC, 4 August 1997
               Added trim to input
       Converted to IDL V5.0   W. Landsman 25-Nov-1997

(See src/idl_cvs/break_path.pro)


CHECKMDSTREE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        checkMDStree
 PURPOSE:
      Check MDS trees, say after a transfer. Produce a file with a 
	list of nodes and checksum of contents of each numerical node or first 
	element of non-numeric nodes.
 CATEGORY:
       MDSplus, Searching
 CALLING SEQUENCE:
       IDL> checkMDStree, tree=tree, shot=shot, outFile=outFile
 INPUTS:
	tree - MDSplus tree. 
	shot - MDSplus shot to search. 
 KEYWORD PARAMETERS:
    Input (Optional):
	server - MDSplus server. Default is the default server for the tree.
	outFile - defaults to tree_nnnnnn_server_list.txt
    Returned (Optional):
	status - status from mdsopen call
 OUTPUTS:
	file
 EXAMPLE:
	IDL>checkMDStree, tree='particles', shot=130000, server='lark:8501', /verb
 NOTES:
 MODIFICATION HISTORY:
	01-Oct-2008 add checksum for Alphanumerics, too.
	29-Aug-2008 Written by Bill Davis, PPPL

(See src/idl_cvs/checkmdstree.pro)


EVENTSPAWN

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
 	eventspawn
 PURPOSE:
       When a designated MDSplus event is detected, spawn an IDL procedure, 
	first killing any versions that are running.
 CATEGORY:
       MDSplus, Program Control
 CALLING SEQUENCE:
	IDL> eventspawn, event=event, procedure=procedure, server=server, $
                        immediate=immediate, display=display
 INPUTS:
       none required, but procedure is probably necessary
 KEYWORD PARAMETERS:
    Keywords:
	event - MDSplus event to wait for (default to NSTX_ACQ_DONE
	procedure - file to pass to idl batch command (default is batchmyidl.pro)
	ASCII - if set, will assume data block contains ascii representation of numbers
	server - MDSplus event server (default is europa.pppl.gov:8501)
	immediate - if set, execute procedure even before waiting for event
	display - X display to send IDL graphics to.
 OUTPUTS:
       none
 EXAMPLE:
	IDL> eventspawn, pro='/u/bdavis/RFcam/batchrfmovie', $
			event='RFcamera_loaded', display='nstxwindowspc:0', /immed
 LIMITATIONS:
	currently, no arguments can be passed to IDL command.
	only works on Unix/Linux.
 NOTES:
	see /u/bdavis/RFcam/batchtedmovie.pro as example of routine to call.
	shot numbers must be accessed in the calling programs via LASTSHOT()
	or an environmental variable.
 MODIFICATION HISTORY:
	09-Mar-2007 Added ASCII keyword which is needed on sflip PC
	15-Aug-2005 written by Bill Davis

(See src/idl_cvs/eventspawn.pro)


FINDMDSNODES

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        FindMDSNodes
 PURPOSE:
      Search for MDSplus nodes or tags with a name containing a string
 CATEGORY:
       MDSplus, Search, Utiltiy
 CALLING SEQUENCE:
       IDL> paths = FindMDSNodes( nodeString, status=status )
 INPUTS:
       nodeString - string to search nodenames for
 KEYWORD PARAMETERS:
	nonNodeString - exclude nodes in returned array if this string found in name
	tags - if set, just look for nodes with tags, and search tagnames
       JustText - if set, just look for Text nodes (no effect if /TAGS set)
	usage - if /TAGS not set, what GETNCI expects 
		(if used, overrides /JustText; DEFAULT: ANY)
	status - success if true (odd number)
	debug - print some debugging info

  the tree may be opened before this routine is called, or you can specify:
	treeName - MDSplus tree. Default='NSTX' (unless embedded in nodeString)
	shot - MDSplus shot to search. Default=-1 (the model tree).
   returned:
	states - string array containing 'OFF' or 'ON'.
 OUTPUTS:
	paths - paths satifying search criteria
 COMMON BLOCKS:
       none
 EXAMPLE:
	IDL> paths = FindMDSNodes( 'ip', status=status, tree='wf', shot=120200 )
	IDL> tags = FindMDSNodes('*', /tags, tree='lrdfit04', shot=117747)
   	    ; exclude some nodes:
	IDL> paths = FindMDSNodes( 'ip',non='formula', tree='wf', shot=120200 ) 
	IDL> paths = FindMDSNodes( 'ip',non=['formula','description'], tree='wf', shot=120200 ) 
 NOTES:
	if tree already open before FindMDSNodes is called, tree & shot need not be set.
	if no records are found in current tree, returns ['']
 LIMITATIONS:
	If connect to VMS, will not get tags from trees on Linux.
 MODIFICATION HISTORY:
	02-Feb-2009 have to spawn MDSTCL and read it's commands from a file
		    for big results, like searching for '*' in operations.
	19-Jan-2009 don't return names that are blank or have spaces in them
	02-Dec-2008 added STATES keyword to return 'OFF' or 'ON'
	09-Jan-08 fintags.fun not on Linux, so don't use. 
		  nonNodeString can be an array of strings
	22-Nov-06 use MDSTCL for tags on Linux trees. Use mdsopen, instead of
		  openMDSshot, and only if tree not entered
	11-Nov-05 Added keywords for use with new treesearch web page.
	31-Jan-01 Written by Bill Davis, PPPL

(See src/idl_cvs/findmdsnodes.pro)


FINDMDSTIME

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       findMDStime
 PURPOSE:
        find a time within an MDSplus shot, correspoding to
	 the time of Max Ip, time of Max W-tot, etc. 
	signals come from the EFIT tree when possible.
 CATEGORY:
       MDSplus
 CALLING SEQUENCE:
       IDL> time = findMDStime( /maxIp )
 INPUTS:
       shotListString - a string indicating shots, 
		e.g., 107694 108305 108330-108350
		 or   108100+20		
			(this returns shots 108100, 108101,...,108120)
       nshots - # of shots to search over (def=10)
 KEYWORD PARAMETERS:
	maxIp - if set, return time of Max Ip (less 3 msec)
	MaxNeutrons - if set, return time of Maximum Neutron production
	MaxBetaN - if set, return time of Beta Normal 
	MaxPTot - if set, return time of maximum heating power
	MaxWMHD - if set, return time of maximum Plasma Stored Energy
	MaxTAUMHD - if set, return time of maximum Energy confinement time
	MaxDENS - if set, return time of maximum Line Density
	shot - if set, will return value for this shot, else for opened shot
 OUTPUTS:
       time in seconds         			
 EXAMPLE:
	IDL> time = findMDStime( /maxIp )
 NOTES:
	if more than one time is found for the max, a median time will be
	returned.
 MODIFICATION HISTORY:
       14-Jun-02 Written by Bill Davis, PPPL

(See src/idl_cvs/findmdstime.pro)


FINDVALIDSHOTS

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       findvalidshots
 PURPOSE:
	Search MDS Plus Trees for valid shot numbers with data in a 
	particular node
 
 CATEGORY:
       MDSplus, Utility
 CALLING SEQUENCE:
       IDL> findvalidshots ; This is interactive widget version
 or    IDL> findvalidshots, signal,beginshotnumber,endshotnumber
 
 INPUTS:
       none 
 KEYWORD PARAMETERS:
       none
 OUTPUTS:
       on screen: valid shot numbers in entered range               			
 COMMON BLOCKS:
       none
 EXAMPLE:  IDL>findvalidshots, '\passivespec::vs2.rawdata:spectra',104500,104515

 NOTES:
       
 MODIFICATION HISTORY:
	01-Oct-2008 Removed mdsconnect [BD]
       4-JAN-2001 Written by Dana Mastrovito, PPPL

(See src/idl_cvs/findvalidshots.pro)


FIRSTSIGNAME

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       firstSigName
 PURPOSE:
       Return the first signal name in a TDI expression.
	Needed when you want the xaxis from a combination of signals.
 CATEGORY:
       MDSplus
 CALLING SEQUENCE:
	sig1 = firstSigName( TDIexpr )
 INPUTS:
   	TDIexpr - TDI expression. Can be just a signal name, or '(\ip1+\ip2)/2'
 RETURNED:
	sig1 - first signal name in TDI expr, e.g., '\ip1'
 KEYWORDS:
    Optional Outputs:
	FOUNDTDI - 1 returned if TDI in node
	DIMENSION - if root node is 2-D, but expression limits to 1.
	SECOND - the second signame name in the expression, if any (else '')
    Optional Inputs:
	DATA = if set, return everything from DATA to ']', if present, or
	       to ')'
 COMMON BLOCKS:
       none
 EXAMPLE:
 	IDL> print, firstSigName( '\engineering::ip1+\engineering::ip2' )
	   \engineering::ip1
 LIMITATIONS:
	probably won't return proper dimension when DATA() is within a TDI function, 
	like BCSMOOTH( data( \camera:image, 1) )
 MODIFICATION HISTORY:
	31-Aug-2007 added keyword SECOND
	19-Jun-2007 ONLY return dimension number from syntax like ",1" if 
		    MAXVAL, MINVAL or DATA (others can be included here).
	06-Apr-2007 Added data and dimension keywords 
  		    to handle style of maxval(\efit01::pisrz,1) and 
		    data(\efit01::pisrz)[10,*] )
	01-May-01 Written by Bill Davis

(See src/idl_cvs/firstsigname.pro)


FITSRUN

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       FITSRUN
 PURPOSE:
       Quickly tell which EFITs and LRDFITs exist for an MDSplus shot
 CATEGORY:
       MDSplus
 CALLING SEQUENCE:
       IDL> fits=fitsrun(shot)
 INPUTS:
       shot - NSTX shot number 
 KEYWORD PARAMETERS:
       maxefits= MAX efits to check 
       maxlrdfits - max lrdfits to check
       quiet - if set to 0, will tell you about each open
       realquiet - if set to 0, will tell you about failed opens
 OUTPUTS:
       fits - string array like  ['EFIT01', 'EFIT03', 'LRDFIT04']
 EXAMPLE:
	IDL> print,fitsrun(117707, maxefits=5, maxlrdfits=5)
	EFIT01 EFIT02 EFIT03 EFIT04 EFIT05 LRDFIT04

	IDL> for i=122440,123244 do print, i,' ',fitsrun(i,loadfit='EFIT03')
 NOTES:
       When the routine is called with no parameters, 
	help information is printed.
 MODIFICATION HISTORY:
	25-May-2007 Just look in EFIT tree for all possible subtrees
	12-Apr-2007 Option to load fits into code_rundb database (for efitviewer)
       07-Mar-2006 Written by Bill Davis, PPPL

(See src/idl_cvs/fitsrun.pro)


FOUNDSUBTREE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       foundsubtree
 PURPOSE:
       determine if sub trees like efit05, lrdfit06, etc. exist
 CATEGORY:
       MDSplus
 CALLING SEQUENCE:
       IDL> found = foundSubTree( shot=shot, tree=tree, index=index)
 INPUTS:
       none but keywords 
 KEYWORD PARAMETERS:
	shot - MDSplus shot/pulse number
	tree - main fit tree, e.g., 'EFIT' or 'LRDFIT'
	index - "subtree" version number, 5 would get you 'EFIT05' or 'LRDFIT05'
	SERVER - MDS server (default is kees.pppl.gov:8501 for NSTX)
    RETURNED:
	status - MDS status from open if failed, else from mdsvalue
 OUTPUTS:
       found - 1 if found, 0 if not found.
 COMMON BLOCKS:
       NONE
 EXAMPLE:
	IDL> print, foundsubtree(shot=117449, tree='efit', index=2 )

 MODIFICATION HISTORY:
       26-Jun-2006 Written by Bill Davis, PPPL

(See src/idl_cvs/foundsubtree.pro)


FULLMDSPATH

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       fullMDSpath
 PURPOSE:
       Return an MDSplus path for a tag
 CATEGORY:
       MDSplus
 CALLING SEQUENCE:
       fullpath = fullMDSpath( tag, shot=shot )
 INPUTS:
       MDSplus tagname
 KEYWORD PARAMETERS:
	shot - if present, will open NSTX tree for this shot
 OUTPUTS:
	fullpaths - returns full pathnames of tags found
 EXAMPLE:
	IDL> mdsopen, 'edge', 129850
	IDL> print, fullMDSpath('\BE_H908_01')
       \EDGE::TOP.BEAP.RAWDATA:BE_H908_01

 NOTES:
       Only returns signals with data in them.
 LIMITATIONS:
	An MDSplus shot file must be open first.
 MODIFICATION HISTORY:
	17-Jun-2008 use tree in tagname, if present. Add tip, if not found.
	14-Mar-00 more efficient & added keywords [BD]
	20-Jan-00 Written by Bill Davis

(See src/idl_cvs/fullmdspath.pro)


GETMDSLABEL

[Previous Routine] [Next Routine] [List of Routines]
 NAME:  
	getMDSlabel
 PURPOSE: 
	return a label for an MDSplus signal. If there is a :LABEL sub-node,
	use that string, else if there is a :COMMENT sub-node, use that, else
	return the MDSplus signal name.
 CATEGORY:
       MDSplus
 CALLING SEQUENCE:
       IDL> label=getMDSlabel( signal, textNode=textNode, FOUNDTDI=foundTDI, $
                      status=status, /quiet, /fullPath )
 INPUTS:
       signal - mdsplus signal or tag name (shot must be opened)
 OUTPUT:
       label - contents of :LABEL substring, if found. Otherwise the
		signal name is returned (just the last two elements, unless
		/fullPath set)
 KEYWORD PARAMETERS:
    Optional Inputs:
	quiet - just passed to mdsvalue
	fullPath - if set, return fullpath if no :LABEL subnode found
    Optional Outputs:
	textNode - 1 returned if a text node
	FOUNDTDI - 1 returned if TDI in node 
	status - if odd, successfull
 COMMON BLOCKS:
       NONE
 MODIFICATION HISTORY:
	01-Jun-01 Also look for :COMMENTS sub-node. 
	11-Mar-01 if no :LABEL node, look for :COMMENT node
       15-Feb-01 Written by Bill Davis, PPPL

(See src/idl_cvs/getmdslabel.pro)


GETSCOPENAMES

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       getScopeNames
 PURPOSE:
       return signal names from an MDSplus Scope input file
 CATEGORY:
       MDSplus, SCOPE
 CALLING SEQUENCE:
	names = getScopeNames( fileName, titles=titles )
	names = getScopeNames()	; will get a dialog box
 INPUTS:
   Optional:
	filename - name of scope input filename (else will get a dialog box)
 RETURNED:
	names - Array of signal names, including TDI, (Y values)
	        if nothing found, will return a '-1'
 KEYWORDS:
   (All Optional) Returned:
	Titles - string array of the plot titles from the scope file, else y-name
	xMins - array of each plot's x-minimum from the scope file (else global, or 0)
	xMaxes - array of each plot's x-maximum from the scope file (else global, or 0)
	yMins - array of each plot's y-minimum from the scope file (else global, or 0)
	yMaxes - array of each plot's y-maximum from the scope file (else global, or 0)
	stripTitles - if set, remove double quotes and everything after //
	noEqualSigns - if set, remove equal signs (=)
	addTrees - if set, add trees into signals
 COMMON BLOCKS:
       none
 NOTES:
 LIMITATIONS:
 MODIFICATION HISTORY:
	23-Jun-2008 added nRows and nCols keywords.
	22-Mar-2006 revised xName logic when some there and some not.
	27-Jan-06 add xNames keyword for specied X values.
	19-Oct-01 if file not found, try other versions of name
	13-Sep-01 Added addTrees keyword
	17-Mar-01 default directory on Unix to /p/nstxusr1/util/scopes/
	02-Mar-01 added x & y mins and maxes
	11-Jan-01 Written by Bill Davis

(See src/idl_cvs/getscopenames.pro)


GOOD_IP

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

 PURPOSE:
       Determine if plasma current (Ip) was good for a shot and, optionally
	declare an event.

 CATEGORY:
	MDSplus, Shot Number, Plasma Current

 CALLING SEQUENCE:
        nextShot = good_ip( shot )

 INPUTS:
       shot - shot number

 KEYWORD PARAMETERS:
    Inputs:
	goodValue - value required for tag for next good shot (default=30000 Amps)
	event     - if non-blank, will be declared if plasma current > goodValue
	Server 	  - MDS server (default is NSTX)
	TagToUse  - Tag to use for IP check (default to \OPERATIONS::CAL_IROGEVVUL1)
	IPforGood - alternate to goodValue (for compatibility with old routine)
	Verbose   - if set, print debugging information
    Returned:
	IpTime - time of good plasma current in seconds.
 OUTPUTS:
	1 or 0
 EXAMPLE:
	IDL> ipOK = good_ip( shot, goodValue = 100. )
 COMMON BLOCKS:
 NOTES:
 	if TagToUse not specified, will try to use in the following order:
	  1) \ENGINEERING::IP1UNC
	  2) \ENGINEERING::PPCC_IP1
	  3) \WF::IP
	if SigUnits from MDSplus begins with 'K' will mult. by 1000. If it 
	begins with an 'M' will mult. by 1000000.
 RESTRICTIONS:
 MODIFICATION HISTORY:
 	Written by Bill Davis March, 2006

(See src/idl_cvs/good_ip.pro)


LASTMDSSHOT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       LastMDSshot
 PURPOSE:
       get the last (current) MDS shot
 CATEGORY:
	MDSplus
 CALLING SEQUENCE:
       currentShot = LastMDSshot()
 INPUTS:
       none
 KEYWORD PARAMETERS:
	SERVER - MDS server (default is NSTX)
	MACHINE - machine (default is NSTX)
 OUTPUTS:
	currentShot - current shot number
 EXAMPLE:
 COMMON BLOCKS:
 NOTES:
 MODIFICATION HISTORY:
 	25-Feb-99 BD added way to get current shot from either VMS or UNIX
		default to NSTX
 	11-Dec-98 BD added MDSplus access for shotnumber, if on VMS at PPPL
 	01-Dec-98 BD use fas_dir and Mk_Filename for filename lookup
 	5/14/98 changing USER directory to BE1 etc [PR]

(See src/idl_cvs/lastmdsshot.pro)


LEAFNAME

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       LeafName
 PURPOSE:
       Return leaf name from MDSplus pathname(s)
 CATEGORY:
       MDSplus
 CALLING SEQUENCE:
       IDL> leaf = leafname(mdspath)
 INPUTS:
       mdspath - MDSplus path string.  
 OUTPUTS:
       leaf - MDSplus leaf node string (last signal in multi-signal TDI)
 KEYWORDS:
	Delim - delimiter (default is ':')
	Tree  - returns tree of input (last signal in multi-signal TDI),
		or environmental variable 'MACHINE' if Signal Math TDI used
		on signals from more than one tree
	AllTrees - all trees in input path
	Prefix - returns everything before the leafname
	nParts - # of parts to return, counting from the end (default=1, 
			max of 2)
	BRACKETSTR - (1st) square bracket clause, as in an array subscript
 COMMON BLOCKS:
       NONE
 EXAMPLE:
       IDL> print,leafname('\JMENARD_DAY1::TOP.FLUX_LOOP.FLUX:FFLPF1BL')
		FFLPF1BL
	IDL> print,leafname('TOP.FLUXLOOP.FLUX.CALIBRATION',delim='.')
		CALIBRATION
 NOTE: 
	for multi-signal TDI, will return the leaf name of last signal, as well as the
	last tree.
 MODIFICATION HISTORY:
	26-Oct-07 Ignore square bracket clauses (but return in keyword BRACKETSTR)
	16-Aug-07 return last tree for multi-line TDI
	06-Aug-07 fix bug where no backslash in name
	11-Jul-07 return all tree names in ALLTREES keyword. 
		  If sigadd, sigmult, etc., used with more than one tree, 
		  return 'NSTX' in TREE keyword
	
	11-Jan-01 Remove comma and anything after, and ')' if TDI
	28-Nov-00 Don't return tree name with '\'
       23-Jul-99 Written by Bill Davis, PPPL

(See src/idl_cvs/leafname.pro)


LISTSHOTS

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       ListShots
 PURPOSE:
        List shot numbers with signal over/under a certain amount
 CATEGORY:
       MDSplus
 CALLING SEQUENCE:
       IDL> listshots, shot, nshots,  signal=signal, warningLevel=warningLevel
 INPUTS:
       shot - if an interger: beginning shot # to search for 
		if an array of integers, use as a shot list (ignore nshots)
       nshots - # of shots to search over (def=10)
 KEYWORD PARAMETERS:
    Optional Inputs:
	comparator - 'GT' (default) or 'LT' for cutoff and warning
	cutoff - value under which value will be ignored
	outFile - outFile for output
	nSmooth - # for median smoothing before using signal (default=0)
	noScreen - if set, do not echo output to screen
	server - MDSplus server, default='EUROPA.PPPL.GOV:8501'
       signal - mdsplus signal name
	skip - shots to skip while looping through list
	warningLevel - warn if greater than than this value
    Optional Returned:
	count - number of shots satisfying criteria
 OUTPUTS:
       just to screen and/or file           			
 COMMON BLOCKS:
       NONE
 EXAMPLE:
	IDL> listshots, 102915, 10,  signal='\WF::IP', warn=1.0
 NOTES:
       tree should be in signal name
 MODIFICATION HISTORY:
	17-Apr-2008 Made > 0 not return zero values
	04-May-2006 changed openMDSshot to mdsopen
	03-Mar-04 a little bullet proofing
       23-May-01 Written by Bill Davis, PPPL

(See src/idl_cvs/listshots.pro)


MDIR

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       mdir
 PURPOSE:
       Directory listing of MDSplus data files with wild cards
 CATEGORY:
       MDSplus, files
 CALLING SEQUENCE:
       IDL> list = mdir(shot, tree=tree)
 INPUTS:
       shot - shot number (defaults to 0). Can be a character string
		with wildcards.
	tree - an MDSplus e.g. 'operations' (defaults to 'wf')
 KEYWORD PARAMETERS:
	tree - an MDSplus e.g. 'operations' (defaults to 'wf')
 	dataroot - file system root for MDSplus data (default = '/nstxdata')
	verbose - if set, will print many informational messages
	debug - if set, debug output will be printed
 OUTPUTS:
       list - list of data files found
 COMMON BLOCKS:
       NONE
 EXAMPLE:
	IDL> print, mdir( '13000*', tree='wf' )
 NOTES:
       if on system with a /nstxdata directory, will spawn "find" 
	otherwise, you will have to entery your password to ssh into the server.
	You may also have to respond "yes" to a question about connecting.
	You must have the same username on the server as the machine your are on.

	You may, instead, use tree_exists.pro, which is slower.
 MODIFICATION HISTORY:
       15-Nov-2008 Written by Bill Davis, PPPL

(See src/idl_cvs/mdir.pro)


MDSDATAVSSHOT

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

  PURPOSE:
	Print single values of MDSplus signals vs. shot number.
	The value can be the max or min, or at a specific time, including
	time of Max Ip, Max Neutrons, etc. The shot list may be reduced
	by certain qualifiers, such as to shots where the max of an 
	arbitrary signal is > a given value.
	Output can be in a format suitable for importing into
	Kaleidograph, Excel, etc.

  CATEGORY:
       MDSplus, Output

  CALLING SEQUENCE:
	MDSdataVsShot, shot, nshots, signal
  INPUTS:
	MDStree - e.g. 'operations'. Default is 'NSTX'
	shot - MDSplus shot number, i.e, ID.
	signal - a single MDSplus signal name, or array of names.
		(ignored if Keyword "Scope" is present.)
  OUTPUTS:
	none returned
  KEYWORDS:
    (all Optional)
	format - output format. Defaults to '(100(g15.6, a1))' 
		 (a tab or space is written between the columns)
	tabs - if set, columns will be separated by tabs instead of spaces
	headings - if set, the signal labels are at the top of each column
		   in row 1.
 	scope - if present, gets the signal names and column titles from 
		this scope file.
		(if present, the signal input is ignored). THIS SHOULD BE
	        THE FULL PATHNAME OF THE FILE, or it will default to general
		areas.
	status - 1=OK, 0 means shot, signal, or scope file weren't found.
	units - if set, will append units to headings
	WhatToList - 'MaxValues', 'MinValues', 
		(time of the following:) 'MaxNeutrons', 'MaxIP', 'MaxBetaN',
		'MaxDENS', 'MaxWMHD'
  EXAMPLES:
  LIMITATION:
  HISTORY:
	11-Feb-05 bug fix for when 1 dimension of 2-d array smaller than nsmooth
	04-Jun-04 Bug fix when lots of bad shots
	04-Nov-02 default to skipping a shot if any requested signal missing
	Written 17-Jul-02 by Bill Davis at the request of Steve Paul

(See src/idl_cvs/mdsdatavsshot.pro)


MDSDAT

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

 PURPOSE:

	"replacement" for gadat.pro. Get MDSplus signal data without
	having to open a tree (much faster, if a tree is specified)

 CATEGORY:
	MDSplus

 CALLING SEQUENCE:

	mdsdat, X, Y, signame, SHOT [,err=ERR] [,debug=DEBUG]		$
                                   [,xmin=XMIN] [,xmax=XMAX]		$
                                   [,npts=NPTS] 
 KEYWORDS: (all are optional)

    INPUT/OUTPUT keywords:

      NPTS:  (INPUT) Number of samples to return.  Defaults to 64K.
             Cannot exceed 64K (if it does, it is set to 64K).

             (OUTPUT) Number of samples actually returned.

    INPUT KEYWORDS:

      DEBUG:  If set (ie. called as gadat,/debug), debug printouts on 
              the progress of gadat are reported


      XMIN:  specifies the "start" time for the time window within
             which to return the data.  Specify the time in
             milliseconds.  If not set, defaults to -10000 ms.

      XMAX:  specifies the "end" time for the time window within
             which to return the data.  Specify the time in
             milliseconds.  If not set, defaults to 100000 ms.
      XUNITS - if non-zero, return units of x-axis		out
      YUNITS - if non-zero, return units of y-axis		out
      ALWAYSOPEN - always open the tree (for when other opens or MDSconnects are done)

    OUTPUT KEYWORDS:

      ERR:  PTDATA/MDSplus error code.  0 = success, anything
            else = failure

      PLABEL:  plot label for pointname

 OUTPUTS: 

    X:  The time base of the requested pointname in seconds

    Y:  Data from the requested signal name.  See keywords NPTS and
        A_NPTS for details on the number of samples returned.

 EXAMPLE:
	IDL> mdsdat, iptime, ip, 'wf::IP', 120200
	IDL> mdsdat, efittime, ipmeas, 'efit01::IPMEAS', 120200
	IDL> 
 COMMON BLOCKS: 
	MDSDAT_LOCAL

 SIDE EFFECTS: 

 RESTRICTIONS:

 MODIFICATION HISTORY:
	07-May-2008 added /AlwaysOpen keyword for when other opens or MDSconnects are done
		    outside of mdsdat.  This will make it slower.
	04-Feb-2008 Written by Bill Davis

(See src/idl_cvs/mdsdat.pro)


MDSDECLAREEVENT

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

 PURPOSE:
       set an MDS event with shot number associated with the event

 CATEGORY:
       MDSplus, Events

 CALLING SEQUENCE:
       IDL> MDSDeclareEvent, eventName [, shot_num]

 INPUTS:
	eventName - string of MDS event name, e.g., 'NE_DENSITY_CALC'
       shot_num - NSTX shot number (OPTIONAL -- will default to current shot)

 KEYWORD PARAMETERS:
    Optional:
	VERBOSE - If set, print debugging information
	NOCONNECT - if set, will not try to connect to an MDSplus server

 OUTPUTS:
       none -- just sets the event
 COMMON BLOCKS:
       NONE
 EXAMPLE:
 NOTES:
	Works from Unix or VMS
 MODIFICATION HISTORY:
	11-Feb-04 use SETEVENT in MDSVALUE on Unix. Add connect option on unix.
   	20-Dec-99 Written [bd]

(See src/idl_cvs/mdsdeclareevent.pro)


MDSEVENTWAIT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       mdseventwait
 PURPOSE:
       Widget to Wait for an MDSplus event, 
	or the user clicks the CANCEL button.
 CATEGORY:
       MDSplus; Event Widgets
 CALLING SEQUENCE:
       IDL> shot = mdseventwait( someEvent, cancel=cancel )
 INPUTS:
       someEvent - (string) an MDSplus event (defualts to 'nstx_acq_done')
 KEYWORD PARAMETERS:
    Optional:
	cancel - if user hits cancel button, cancel = 1 (& shot=-1), else 0
	group_leader - higher level widget to place this on top of 
 OUTPUTS:
       shot - shot # (data) set like: IDL> setmdsshotevent,'dum',999999
 COMMON BLOCKS:
       NONE
 EXAMPLE:
 RELATED ROUTINE:
 NOTES:
	Only works on X.
 MODIFICATION HISTORY:
	29-Aug-00 Written by Bill Davis for David Swain

(See src/idl_cvs/mdseventwait.pro)


MDSGETSIG

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       MDSGETSIG
 PURPOSE:
       Get a signal, units and axes values easily from MDSplus
 CATEGORY:
       MDSplus
 CALLING SEQUENCE:
       d = MDSGETSIG( signal, SIGUNITS=fUnits, XAXIS=time, XUNITS=timeUnits)
 INPUTS:
      signal - MDSplus Signal name
 KEYWORD PARAMETERS:
       Keywords:
	    SIGUNITS - if non-zero, return units of signal		out
	    XAXIS    - if non-zero, return array of x-axis		out
	    XUNITS   - if non-zero, return units of x-axis		out
	    YAXIS    - if non-zero, return array of y-axis		out
	    YUNITS   - if non-zero, return units of y-axis		out
	    ZAXIS    - if non-zero, return array of Z-axis		out
	    ZUNITS   - if non-zero, return units of Z-axis		out
	    status   - if non-zero, return status (1=OK)		out
 OUTPUTS:
       d - 1- or 2-D data                 				out
 COMMON BLOCKS:
       NONE
 EXAMPLE 
	MDSCONNECT, 'yourhost.pppl.gov:8501'
	MDSOPEN, 'testtree', 10
	sig = 'onedim'
	data = MDSGETSIG( signal,SIGUNITS=fUnits, XAXIS=time,XUNITS=timeUnits )'
	PLOT, time, data, XTITLE = timeUnits, YTITLE = fUnits,  $
		TITLE = signal + ' - shot ' + STRTRIM( STRING(shot), 2 )
 NOTES:
	If something like x units were NOT stored for the signal, and they are
	asked for, IDL will complain about an access violation, but continue.
	When signals are TDI combinations of others, use the
	units and xaxis from the first signal (could be erroneous)
 MODIFICATION HISTORY:
	23-Jun-2008 when finding Xunits of a signal like dim_of(\...), use it
	13-May-08 handle \rf::refl_avgdens[*,33]
	26-Oct-07 handle 2-D square bracket clauses, as in an array subscript
	31-Aug-07 made xAxis work when SigMath TDI used
	06-Apr-07 made work for 'maxval(\activespec::chers_best:vt,1)'
	03-Jun-05 Added Z data
	01-May-01 When signals are TDI combinations of others, use the
		  units and xaxis from the first signal (could be erroneous)
	11-Nov-99 test for input signal name not defined
	10-Aug-99 Use Arg_Present so don't have to set keywords before call
	26-Jan-99 Trim trailing blanks from unit strings [BD]
       13-Jan-99 Written by Bill Davis, PPPL

(See src/idl_cvs/mdsgetsig.pro)


MDSLIST

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

  PURPOSE:
	Print ASCII file containing data for MDSplus signal(s). 
	The "dimension" of one of the signals (typically time) is in the 
	first column, followed by data values at that time. 
	Output may be in the format suitable for importing into
	Kaleidograph, Excel, etc.

  CATEGORY:
       MDSplus, Output

  CALLING SEQUENCE:
	mdslist, MDStree, shot, signames
	mdslist, MDStree, shot, signames,  $
               t1=t1, t2=t2, npts=npts, format=format, tabs=tabs, $
               headings=headings, SigForX=SigForX, scope=scope
  INPUTS:
	MDStree - e.g. 'operations'. Default is 'NSTX'
	shot - MDSplus shot number, i.e, ID.
	signames - a single MDSplus signal name, or array of names.
		(ignored if Keyword "Scope" is present.)
  OUTPUTS:
	none returned
  KEYWORDS:
    (all Optional)
	t1 - Starting x-value desired (typically time, in seconds). 
	     Defaults to beginning of data for 1st signal.
	t2 - Ending x-value desired. Defaults to end of data
	npts - number of points desired. Defaults to all points.
	format - output format. Defaults to '(100(g15.6, a1))' 
		 (a tab or space is written between the columns)
	tabs - if set, columns will be separated by tabs instead of spaces
	headings - if set, the signal labels are at the top of each column
		   in row 1.
	SigForX - The signal from which to extract the output x-values.
		  Especially relevant when signals of different timebase are 
		  requested (defaults to that of the first signal).
 	scope - if present, gets the signal names and column titles from 
		this scope file.
		(if present, the signames input is ignored). THIS SHOULD BE
	        THE FULL PATHNAME OF THE FILE, or it will default to general
		areas.
	outFile - name of output file. Default is 'mdslist.txt'
	status - 1=OK, 0 means shot, signames, or scope file weren't found.
	units - if set, will append units to headings
  EXAMPLES:

	   To write the first 100 points of time and 
	    ip pairs to file mdsoutput_106138.dat:
	IDL> mdslist,'wf',106138,'\ip',npts=100

	   To write 3 columns,  of time, Ip, and Itf, from 0.1-0.2 sec to 
	    file mdsoutput_106138.dat:
	IDL> mdslist,'wf',106138,['\ip','\itf'],t1=.1,t2=.2
      
	   To make a tab-delimited file of signals from an MDSplus Scope, 
	    with column headings, on efit times:
	IDL> mdslist,'',106138,scope='/u/Old/bdavis/bv.scope', $
			SigForX='EFIT', /headings, /tabs   

	   To write time and stored energy data at 1 KHz 
	    (like all signals in WF tree):
	IDL> mdslist,'',106138,'\EFIT01::WMHD/1000', SigForX='\WF::IP'  
  LIMITATION:
	Would be faster, if it just opened trees that were needed.
  HISTORY:
	11-Jul-2008 add /XML output option
	24-Mar-08 puts tabs between columns if tabs='on' (as well as if tabs=1)
	07-Jan-08 Close file before e-mailing, because not all of file begin sent
	26-Sep-07 Add message on how to get file from Linux Cluster nodes
	09-Aug-07 bug fix with Yunits not defined
	29-Mar-07 changed openMDSshot to mdsopen, so SFLIP and such would work
	13-Sep-06 Don't worry if time and data arrays different length
	15-Feb-05 Handle when time not first dimension in 2-d array
	20-Sep-01 converted from mdsmkfile
	05-Sep-01 Added multi-column and interpolation options.
	Written 13-jul-00 by Bill Davis at the request of Charlie Neumeyer

(See src/idl_cvs/mdslist.pro)


MDSLOADSCALAR

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       MDSloadScalar
 PURPOSE:
       Load MDSplus scalar with one simple call (after opening shot)
 CATEGORY:
       MDSplus
 CALLING SEQUENCE:
       MDSloadScalar, sig, data, SIGUNITS = sigUnits, XAXIS = xAxis,   $ 
    		XUNITS = xUnits, YAXIS = yAxis, YUNITS = yUnits
 INPUTS:
      sig  - MDSplus Signal name
      data - 1- or 2-D data array to load
 KEYWORD PARAMETERS:
       Keywords:
	    stat=val     - if non-zero, return status (1=OK)		out
 OUTPUTS:
       NONE
 COMMON BLOCKS:
       NONE
 EXAMPLE 
	stat=openMDSshot('engineering', 100700)
	sig = '\Some_sig'
	MDSloadScalar, sig, 3.14159

 MODIFICATION HISTORY:
       02-Nov-99 Written by Bill Davis, PPPL

(See src/idl_cvs/mdsloadscalar.pro)


MDSLOADSIG

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       MDSLOADSIG
 PURPOSE:
       Load MDSplus signals with one simple call (after opening shot)
   Optionally add node and/or tag to a shot tree.
 CATEGORY:
       MDSplus
 CALLING SEQUENCE:
       MDSLOADSIG, sig, data, SIGUNITS=sigUnits, XAXIS=xAxis,   $
                   XUNITS=xUnits, YAXIS=yAxis, YUNITS=yUnits
 INPUTS:
      sigName  - MDSplus Signal name
      data - 1- or 2-D data array to load (can be 3-D, but must have all
             keywords)
 KEYWORD PARAMETERS:
       Keywords:
       SIGUNITS=val - if non-zero, return units of signal       in
       XAXIS=val    - if non-zero, return array of x-axis       in
       XUNITS=val   - if non-zero, return units of x-axis       in
       YAXIS=val    - if non-zero, return array of y-axis       in
       YUNITS=val   - if non-zero, return units of y-axis       in
       ZAXIS=val    - if non-zero, return array of z-axis       in
       ZUNITS=val   - if non-zero, return units of z-axis       in
       FullX  - if set, store full x-axis, even if dx constant (1-D only)
       SkipCheck    - if set, do not check time base for constancy (assume)
       AddNode      - if set, will try and add the node to the tree
       TagToAdd     - Tag to add
       shot   - needed if adding node or tag
       tree   - needed if adding node or tag
       JustAdd      - if set, just add node and/or tag, but don't load data
       stat=val     - bad if even, OK if odd           out
       quiet  - passed to MDSplus routines (default=1)
 OUTPUTS:
       NONE
 COMMON BLOCKS:
       NONE
 EXAMPLE
   mdsopen,'wf', 99999, stat=stat
   sigName = '\ip'
   x = findgen(10)
   y = sin( x/n_elements( x ) * 3 * 2 * !PI )
   MDSLOADSIG, sigName, y, SIGUNITS='Y Units',  XAXIS=x, XUNITS='X Units'
   or, to just add a signal and tag:
   MDSLOADSIG, sigName, TagToAdd=tag, SHOT=shot, TREE=tree, /JUSTADD

 MODIFICATION HISTORY:
	09-Jul-2008 use dt_nicenumber, instead of nicenumber, for 
		    digitizing rates of 4, etc.
	03-Jul-2008 Added dt keyword for Stefan Gerhardt, with ~4e-6 dt.
	24-Apr-06 change mds$tcl to mdstcl for Unix.
       22-Jun-04 allow 3-d, but must have all parameters
	27-Jan-03 Just store x0, dx, y0, and dy for 2-D signals, if xaxis input
	23-May-01 Make, as a default, signals with constant timebase
       	store with t0 & delta t, rather than storing whole time array.
	16-Nov-00 Added the AddNode & TagToAdd keywords
	28-Aug-00 Don't Use Arg_Present
       7-Jan-99 Written by Bill Davis, PPPL

(See src/idl_cvs/mdsloadsig.pro)


MDSMKFILE

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

  PURPOSE:
	Write an ascii file containing time and data for MDSplus signal(s). 
	Time is in the first column, followed by data values at that time. 
	Output may be in the format suitable for importing into
	Kaleidograph, Excel, etc.

  CATEGORY:
       MDSplus, Output, File I/O

  CALLING SEQUENCE:
	mdsmkfile, MDStree, shot, signals
	mdsmkfile, MDStree, shot, signals, filename=filename, $
               t1=t1, t2=t2, npts=npts, format=format, tabs=tabs, $
               headings=headings, timeSig=timeSig, scope=scope
  INPUTS:
	MDStree - e.g. 'operations'. Default is 'NSTX'
	shot - MDSplus shot number, i.e, ID.
	signals - a single MDSplus signal name, or array of names.
		(ignored if Keyword "Scope" is present.)
  OUTPUTS:
	none returned
	file named mdsoutput_nnnnnn.dat is written, where
	   nnnnnn is the shot number, or, if a scope is used, the
	   scope name is in the place of mdsoutput. If Keyword "Filename"
	   is present, that name is used.
  KEYWORDS:
    (all Optional)
	filename - output filename (default is mdsoutput_nnnnnn.dat, where
		   nnnnnn is the shot number, or, if a scope is used, the
		   scope name -- without extension -- is in the place of 
		   mdsoutput).
	DeltaTime - time step for output - Default is that of the first 
		    signal specified. If = 0, then do not list time.
	t1 - Starting time desired, in seconds. 
	     Defaults to beginning of data for 1st signal.
	t2 - Ending time desired. Defaults to end of data
	npts - number of points desired. Defaults to all points.
	format - output format. Defaults to '(100(g15.6, a1))' 
		 (a tab or space is written between the columns)
	tabs - if set, columns will be separated by tabs instead of spaces
	headings - if set, the signal labels are at the top of each column
		   in row 1.
	timeSig - The signal from which to extract the output timebase.
		  Especially relevant when signals of different timebase are 
		  requested (defaults to that of the first signal).
		  If DeltaTime is specified, this keyword is overridden.
 	scope - if present, gets the signal names and column titles from 
		this scope file.
		(if present, the Signals input is ignored). THIS SHOULD BE
	        THE FULL PATHNAME OF THE FILE, or it will default to general
		areas.
	status - 1=OK, 0 means shot, signals, or scope file weren't found.
  EXAMPLES:

	   To write the first 100 points of time and 
	    ip pairs to file mdsoutput_106138.dat:
	IDL> mdsmkfile,'wf',106138,'\ip',npts=100

	   To write 3 columns,  of time, Ip, and Itf, from 0.1-0.2 sec to 
	    file mdsoutput_106138.dat:
	IDL> mdsmkfile,'wf',106138,['\ip','\itf'],t1=.1,t2=.2
      
	   To make a tab-delimited file of signals from an MDSplus Scope, 
	    with column headings, on efit times:
	IDL> mdsmkfile,'',106138,scope='/u/bdavis/bv.scope', $
			timeSig='EFIT', /headings, /tabs   

	   To write time and stored energy data at 1 KHz 
	    (like all signals in WF tree):
	IDL> mdsmkfile,'',106138,'\EFIT01::WMHD/1000', timeSig='\WF::IP'  
  LIMITATION:
  HISTORY:
	12-Oct-01 Added deltaTime keyword [BD]
	05-Sep-01 Added multi-column and interpolation options.
	Written 13-jul-00 by Bill Davis at the request of Charlie Neumeyer

(See src/idl_cvs/mdsmkfile.pro)


MDSNODECHANGES

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       MDSnodeChanges
 PURPOSE:
       Print times when the last change was made to an MDSplus node.
 CATEGORY:
       MDSplus, Tree Status, dates
 CALLING SEQUENCE:
       MDSnodeChanges, node, shot1=shot1, shot2=shot2, skip=skip, tree=tree
 INPUTS:
       node = MDSplus node name, e.g. \OPERATIONS::TOP.RAWDATA:LM_H908_01
 KEYWORDS:
       shot1 = starting shot number to process
       shot2 = last shot number to process (else shot1+400)
       skip = skip factor
       tree = MDSplus tree (defaults to nstx -- 
		will be faster if specific tree specified)
	BEFORE - show only nodes written before this date (defaults to '1-jan-1971'), 
		so can see what never got written.
	AFTER - show only nodes written after this date (defaults to '1-jan-1971'),
		so can see only nodes that HAVE been written.
	OUTFILE - a file name to contain a script related all shots for which
		  a valid node was found in MDSplus
	PREFIX - string to prefix the shot # in the script. 
		DEFAULT is '/bin/rm -R -f '
	VERBOSE - if set, will tell you what shots could not be opened.
 EXAMPLE:
	IDL> tree='microwave'
	IDL> node='\top.electron_den:line_density'
	IDL> MDSnodeChanges, node, shot1=101300, shot2=101330, tree=tree

	IDL> MDSnodeChanges, '\cameras2::FastSoftXray:frames',shot1=124459, $
				shot2=125000, /after

    to produce a script to delete shot directories that have been put in MDSplus:
	IDL> MDSnodeChanges, node, shot1=shot1, shot2=shot2, /after, outfile='shots.txt'

 COMMON BLOCKS:
 NOTES:
	see MDStreeChanges for who last changed a tree.
	Note that "OWNER" returns 0 from getnci call.
	This runs quickly.
 LIMITATIONS:
 MODIFICATION HISTORY:
	30-Apr-2008 added outfile and prefix keywords, so directories can be
		    deleted after verifying they are in MDSplus
	09-Jul-2007 added AFTER keyword, so you can see what nodes have been written
	30-Apr-2007 add BEFORE keyword, so you can see what nodes never got written
	26-Apr-2007 "Who" stopped working (returning numberical value)
	09-May-2006 Allow for numerical or '*' for who.
       20-Dec-99 Written for Rajesh Maingi.

(See src/idl_cvs/mdsnodechanges.pro)


MDSSCALARS

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

  PURPOSE:
	Print ASCII file containing values of MDSplus scalars(s) for a list of shots. 

  CATEGORY:
       MDSplus, Output

  CALLING SEQUENCE:
	mdsscalars, MDStree, shot, signames
  INPUTS:
	MDStree - e.g. 'operations'. Default is 'NSTX'
	shot - MDSplus shot number, i.e, ID. Can be an array, or range of shots.
	signames - a single MDSplus signal name, or array of names.
  OUTPUTS:
	none returned
  KEYWORDS:
    (all Optional)
	format - output format. Defaults to '(100(g15.6, a1))' 
		 (a tab or space is written between the columns)
	tabs - if set, columns will be separated by tabs instead of spaces
	headings - if set, the signal labels are at the top of each column
		   in row 1.
	status - 1=OK, 0 means shot, signames, or scope file weren't found.
  EXAMPLES:

	IDL> mdsscalars,'',118956,'\ENGINEERING::TOP.EPICS.GAS.PARAMETERS:INJ1_READY''
  LIMITATION:
	Would be faster, if it just opened trees that were needed.
  HISTORY:
	Written 20-Aug-2006 by Bill Davis

(See src/idl_cvs/mdsscalars.pro)


MDSSETEVENT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	MDSSETEVENT
 PURPOSE:
	Generates an MDSplus event
 CATEGORY:
	MDSplus, Events
 CALLING SEQUENCE:
	MDSSETEVENT,event[,/QUIET][,STATUS=STATUS][,DATA=data][,/INFO]
 INPUT PARAMETERS:
	event = Name of MDSplus event to generate.
 Keywords:
       QUIET = prevents IDL error if TCL command fails
       STATUS = return status, low bit set = success
       DATA = bytarr(12) to send with event
	INFO - if this keyword is set the VMS error will be displayed but
              control will be returned to the caller instead of doing a
              longjump back to the IDL prompt.
 OUTPUTS:
       istat = return status, low bit set = success
 COMMON BLOCKS:
	None.
 SIDE EFFECTS:
	None.
 RESTRICTIONS:
	None.
 PROCEDURE:
	Straightforward.  Makes a call to MDSplus shared image library
       procedure MDS$OPEN and checks for errors.
 MODIFICATION HISTORY:
	renamed from mds$setevent & made to work on UNIX, too	[BD]
	 VERSION 1.0, CREATED BY T.W. Fredian, April 22,1991

(See src/idl_cvs/mdssetevent.pro)


MDSSHOTDATE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       MDSshotDate
 PURPOSE:
       Print time and date of an NSTX shot.
 CATEGORY:
       MDSplus, Tree Status 
 CALLING SEQUENCE:
       IDL> date = MDSshotDate( shot, time=time  )
 INPUTS:
       shot = MDSplus shot number
 KEYWORDS:
    optional output:
	time = time of shot, e.g., 12:25:02
 EXAMPLE:
       IDL> date=mdsshotdate(110109,time=time)
       IDL> print, date, ' ', time
       11-FEB-2003 15:09:37.60
 COMMON BLOCKS:
       none
 NOTES:
	This runs fairly quickly, but SQL access is quicker.

	Also see SURVEYDB to quickly see first & last shot of day.
 LIMITATIONS:
 MODIFICATION HISTORY:
	14-Jan-2009 Changed node read to be \NSTX::TOP.ACQ_INFO.STATISTICS:STORE_START
	04-Sep-2008 replace openMDSshot with mdsopen
	9-Feb-2004 Added status  (shots before around 104611 don't work)
       3-Jun-02 use \WF::ACQ_START
       3-Oct-00 Written by Bill Davis

(See src/idl_cvs/mdsshotdate.pro)


MDSSIGINTERP

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

  PURPOSE:
	call TDI to interpolate signals, but handle expressions
	in which multiple signals are included.
	(assumes all same timebase within a given TDI expression)

  CATEGORY:
       MDSplus, Timing

  CALLING SEQUENCE:
	IDL> interpData = mdsSigInterp(inSig, outXsig_in, status=status)

  INPUTS:
	inSig - character string of signal to interpolate
	outXsig_in - signal to get timebase for output of inSig 

  OUTPUTS:
	returns array on desired timebase

  KEYWORDS:
    (all Optional)
	inXsig_in - signal to find timebase for. Default is dim_of(inSig)
	minTime - if set, just returns time range common to both signals
	outTimes - time base of returned signal
	status - 1=OK, 0 means problem

  EXAMPLE:
	stat=openMDSshot('nstx', 109070)
	interpData = mdsSigInterp( '\wf::ip', '\engineering::ip1', outTimes=outTimes, /mintime )
	plot,outtimes,interpdata

  HISTORY:
	10-Apr-03 outTimes and minTime keywords added
  	05-Nov-01 Written by Bill Davis

(See src/idl_cvs/mdssiginterp.pro)


MDSTREECHANGES

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       MDStreeChanges
 PURPOSE:
       Print times when the last change was made to an MDSplus tree,
	and who did it.
 CATEGORY:
       MDSplus, Tree Status, dates
 CALLING SEQUENCE:
       MDStreeChanges, tree, shot1=shot1, shot2=shot2, skip=skip
 INPUTS:
       tree = MDSplus tree name, e.g. 'Microwave' or 'NSTX'
 KEYWORDS:
       shot1 = starting shot number to process
       shot2 = last shot number to process
       skip = skip factor (default to no skip
	since = only list changes for a shot if since this date
		e.g. - '20-sep-2001'
 COMMON BLOCKS:
       none
 EXAMPLE:
	IDL> mdstreechanges, 'microwave', shot1=101300, shot2=101301
	 
	Latest changes from shot 101300 to 101301 for the microwave tree
	 
	  Shot       Who       Date        Node
	  ----       ---       ----        ----
	 101300    [BDAVIS]  4-APR-2000  .ELECTRON_DEN:LINE_DENS_DF
	 101301    [BDAVIS]  4-APR-2000  .ELECTRON_DEN:LINE_DENS_DF

 MODIFICATION HISTORY:
	01-Feb-02 added text for repeated lines
	28-Jan-02 added SINCE keyword [BD]
       20-Dec-99 Written by Bill Davis for Rajesh Maingi.

(See src/idl_cvs/mdstreechanges.pro)


MDSUNITS

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       MDSunits
 PURPOSE:
       return units of an MDS tag, or the time, or time units
 CATEGORY:
	MDSplus
 CALLING SEQUENCE:
        units = MDSunits( tag )
 INPUTS:
       tag - MDSplus tag or node name      in
 KEYWORD PARAMETERS 
	Input:
	  TIME  - If set, Time returned (unless UNITS also set)
	  UNITS - If set, Units of tag returned (unless TIME also set)
	Returned:
	  STATUS- Status of call (can be used in IDL logical expressions)
 OUTPUTS:
	units - units
 EXAMPLES:
    MDSOPEN, 'tftr', 89725
    tag = '.waveforms:mb_ip_sl'
    f = MDSVALUE( tag )

    time = MDSUNITS( tag, /TIME )
    flabel = MDSUNITS( tag, /UNITS )
    timelabel = MDSUNITS( tag, /TIME, /UNITS )
    plot, time, f/1000., xtitle = timelabel, ytitle = 'milli'+flabel
 COMMON BLOCKS:
 NOTES:
 MODIFICATION HISTORY:
    29-Mar-99 Return status from MDSVALUE [BD]
    21-Dec-98 Written by Bill Davis

(See src/idl_cvs/mdsunits.pro)


MDSW

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       mdsw
 PURPOSE:
       Interactively plot MDS signals with Crosshairs and many options
 CATEGORY:
       MDSplus, Plotting, Widget Example, Printing Plots, Crosshairs
 CALLING SEQUENCE:
	mdsw
	mdsw, xsize=800, ysize=600
 KEWORDS:
	XSIZE - initial horizontal size of graphics window 
	YSIZE - initial vertical size of graphics window 
	shot - MDSplus shot number, i.e, ID
	tree - tree to open. Defaults to NSTX
 COMMON BLOCKS:
       none
 EXAMPLE:
	IDL> mdsw,tree='engineering',shot=130000,charsize=2, Az=140, $
		  signal='\engineering::ppsum'
 NOTES:
       Your display may have to be set to 256 colors to see the crosshairs.
 LIMITATIONS:
	Some of the MDSplus signals in the list may not have any data.
	You need IDL version 5, or greater to run this application.
 MODIFICATION HISTORY:
	19-Jan-2008 Added option to change Az & Ax on surface plots
	16-Jan-2009 added zAxisW calls for RGA data
	17-Oct-05 Add Save to Tek option.
	08-Mar-02 Fixed screen dump cabability for 24-bit color, and some minor things.
	05-Oct-01 Improved restoring settings. Allowed for "Next Shot" to be missing.
	18-May-01 Use Vcomp for "visual compression" if more points than resolution
	07-May-01 Added Reload color table. Better behavior when copying plots that
		  don't fill the screen.
	08-Mar-01 Bug fixed on Reference Shots with signals of different length.
	02-Feb-01 Use Label sub-node as title, if available. Access to
		  nodes, even if not tags. Display text nodes.
		  Display Signal List initially.  Plot 2-D data.
	30-Nov-00 Allow "Save Settings" to include Signal List & !X, !Y, !P.
		  (old settings files won't work).
		  Axis selection with middle mouse button just redraws last plot.
	20-Nov-00 Rearranged menus (added Appearance Menu); better plot spacing.
	13-Nov-00 Added "Assume same x-label" & "Assume same x-axis" options
	30-Oct-00 Added widget for !P settings, so can specify symbols, etc.
	26-Oct-00 Fixed "Copy Plot to Tek" to return to X color table afterwards.
	18-Oct-00 Added "Edit Selected Signal" option in Signal Menu. 
		  TDI expressions included in name will be displayed. Added button
		  to show treenames in list.
	10-Oct-00 Added "Label Every Other tick options" & better tick labels
		  Made postscript output a little better for grid of plots
	03-Oct-00 Add "Always Include 0 on Y-axis" (not default) and 
		  "Draw dashes at y=0" (now default) options.
	28-Sep-00 Allow yaxisw to control Y-axis range,
		  in some situations, at least.
	20-Sep-00 Just label "No Data" if data not found. Put < & > on Signal Menu
	07-Oct-99 Redraw whole screen when mouse used. Alphabetize signal list.
		  Default to "Only zoom X" 
	19-Aug-99 Allow overlays of data with different dimensions
	23-Jun-99 Added Reference shot. Added "Plot all on one page" option.
	12-Apr-99 Added Tek output option [BD]
	29-Mar-99 Added X & Y Style editing. [BD]
	15-Mar-99 Add "Get Next Good Shot" buttons [BD]
	08-Mar-99 Add overlays and legends. [BD]
	26-Feb-99 Multiplot option and x-only zooming [BD]
	11-Feb-99 Added a pick list for MDS signals
	26-Jan-99 Modified for using MDS at PPPL by Bill Davis

       GA Crosshair routines originally written by John Ferron. 

(See src/idl_cvs/mdsw.pro)


MK_SCOPE_GIF

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

 PURPOSE:
	make gif files from scope-like output, using a scope file as input

 CATEGORY:
	MDSplus, Plot files

 KEYWORD INPUTS:
       shots - a string indicating shots, 
                e.g., 107694 108305 108330-108350
                 or   108100+20         
                        (this returns shots 108100, 108101,...,108120)
	scopeFile - if not specified will prompt
	rightSpace - fractioanal space to right of last plot (0-1)
	leftSpace - fractioanal space to left of first plot (0-1)
	colSpace - fractioanal space between plot columns (0-1)
	vertSpace - fractioanal space between plot rows (0-1)
	t1 - start time of plots (sec)
	t2 - end time of plots (sec)
	nRows - # of rows of plots
	nCols - # of columns of plots
	pixmap - if set, will not display plots on screen (much faster)

 EXAMPLE:
    (on Unix:)
	mk_scope_gif,shots='109071-109075',scope='wf.scope', /pixmap

     or
	mk_scope_gif,shots='109071+5' ; (will be prompted for file)

     or 
     mk_scope_gif, shots='109070+2',scope='/u/kaye/Scope/sk.scope',   $
                 leftspace=.07, rightspace=0.005, $
                 tweenspace=0.008, vertSpace = 0.03,  $
                 nrows=8, ncols=4, charsize=1.3
 HISTORY:
	Written by Bill Davis for Stan Kaye, Dec. 2004

(See src/idl_cvs/mk_scope_gif.pro)


NEXTGOODSHOT

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

 PURPOSE:
       find the next shot that has more than a certain Ip.

 CATEGORY:
	MDSplus, Shot Number

 CALLING SEQUENCE:
        nextShot = nextGoodShot( StartShot )

 INPUTS:
       StartShot - shot number to start from      in

 KEYWORD PARAMETERS:
    Inputs:
	goodValue - value required for tag for next good shot (default=30000 Amps)
	Backwards - look backwards for good shots
	MaxShots  - Maximum number of shots to search over 
		   (default=1000 or end). IF MAXSHOTS=1 JUST PROCESS SHOT1
	Server 	  - MDS server (default is NSTX)
	TagToUse  - Tag to use for IP check (default to \OPERATIONS::CAL_IROGEVVUL1)
	Verbose   - if set, print debugging information
 OUTPUTS:
	nextShot - next Shot number, based on criterion
                  IF no good shot meeting criterion is found, -1 is returned
 EXAMPLE:
	IDL> ishot = NextGoodshot( laopenStathot, goodValue = 100. )
 COMMON BLOCKS:
 NOTES:
 	this routine just works for NSTX and DIII-D (uses gadat at GA).
 RESTRICTIONS:
	LASTSHOT() may sometimes return a small number during test periods
 MODIFICATION HISTORY:
	10-Mar-06 Default to \WF::IP. Check for different tree for backup tag.
	15-Aug-05 add LastIpTime keyword [BD].
	28-Sep-01 Return status. Assume values read are in Amps.
		  Use \ENGINEERING::IP2 as a backup value
	28-Nov-00 Changed Ip to look for \ENGINEERING::PPCC_IP1
	20-Sep-99 Add MaxShots keyword
	18-Sep-99 Keep going after 1 missing shot, but stop after 5
	16-Sep-99 Added TagToUse keyword & medsmooth to remove spikes [BD]
 	Written by Bill Davis March, 1999

(See src/idl_cvs/nextgoodshot.pro)


NONVARPOS

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       nonVarPos
 PURPOSE:
 	find position of characters which are not valid for MDSplus names
 CATEGORY:
       MDSplus, Character Search, Strings
 CALLING SEQUENCE:
	posArray = nonVarPos( inStr )

 RETURNED:
       posArray = array of positions of characters which are not
		   valid characters for an MDSplus tag name
		-1 if none found
 KEYWORDS:
   (OPTIONAL)
	GOOD - if set, will retrun positions of good characters
	noNum - if set, don't count numbers as good characters
 MODIFICATION HISTORY:
	01-May-01 - Added keywords
	2001 Written by Bill Davis

(See src/idl_cvs/nonvarpos.pro)


NSEARCH

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       nsearch
 PURPOSE:
      Search MDS Plus Trees for a node
 CATEGORY:
       MDSplus
 CALLING SEQUENCE:
       IDL> result=nsearch(searchnode[, fullpath=path])
 INPUTS:
       searchnode and optional variable to return an array of full paths 
	 containing node name 
 KEYWORD PARAMETERS:
       fullpath - full path of node found
 OUTPUTS:
       status of function (-1 if not found, 0 if found)            			
 COMMON BLOCKS:
       none
 EXAMPLE:
	IDL> result=nsearch('xray', fullpath=path)
 NOTES:
       tree must be open before nsearch can be called.
	will return 0 if node is found and -1 if it is not found in the current 
	tree.
 MODIFICATION HISTORY:
	12-Feb-00 strip tree info, if in node name [BD]
        7-Feb-00 Written by Dana Mastrovito, PPPL

(See src/idl_cvs/nsearch.pro)


OPENMDSSHOT

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

 PURPOSE:
       Open MDSplus shot (recommend that just MDSopen.

 CATEGORY:
	MDSplus

 CALLING SEQUENCE:
        status = OpenMDSshot( MDStree, shot_num, SERVER=server, /QUIET )

 INPUTS:
	MDStree - e.g. 'operations'				in
       shot_num - shot number					in

 KEYWORD PARAMETERS:
    Optional Inputs:
	QUIET - just passed to MDS routines
	SERVER - MDS server (default is kees.pppl.gov:8501 for NSTX)
	JUSTCONNECT - if set, will just connect to MDSplus
			(can be used before calling LastMDSshot()).

 OUTPUTS:
	Status - MDS status

 EXAMPLE:
	MDStree = 'wf'
	shot_num = 130000
	status = OpenMDSshot( MDStree, shot_num, /QUIET )
	IF status THEN y=MDSGetSig('\IP')
  or,
   sts = OpenMDSshot( 'EFIT01', 95334, server='omega.gat.com')
   IF sts THEN PRINT, 'Opened GA shot successfully'

 COMMON BLOCKS:

 NOTES:
	This can be called repeatedly and will not re-connect or
	re-open a shot if it is already open.

	Connection logic breaks if an MDSconnect is called outside of this routine.

 MODIFICATION HISTORY:
  14-Nov-2008 Default to skylark.pppl.gov for server. Strip "::" from end of server name
  07-Oct-2008 changed default to not call mdsconnect, and removed need-to-open logic [BD]
  18-May-05 Changed the default server from Unix to kees.pppl.gov:8501
  02-Nov-04 Use environmental variable MDS_HOST for connection machine
  13-Sep-01 Don't avoid re-opening files, in case MDSopen was called directly.
  24-Aug-00 Changed the default server from Unix to europa.pppl.gov:8501
  13-Apr-00 Changed the default server from Unix to kees.pppl.gov:8501
  22-Oct-99 Took out check for at GA, because added 0.3 seconds
  04-Aug-99 fix for server= ' ' 
  17-Mar-99 Have the default server from Unix be birch.pppl.gov:8501
  12-Mar-99 refer to first argument as a tree. Make a keyword for server
  Written by Bill Davis, 2/99

(See src/idl_cvs/openmdsshot.pro)


PLOTSCOPE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       plotscope
 PURPOSE:
       make scope-like plots, optionally with overlays from multiple shots.
 CATEGORY:
       MDSplus, SCOPE
 CALLING SEQUENCE:
	IDL> plotscope, shots=shots, scope=scope
 INPUTS:
	shots - scalar or array of shot numbers, e.g. [104500,104501]
	scope - name of scope input filename (else will get a dialog box)
 RETURNED:
	None
 KEYWORDS:
   (All Optional) Inputs:
	t1 - starting time desired. Defaults to scope value
	t2 - ending time desired. Defaults to scope value
	refshot - a reference shot to be overplotted.
       SameXlabels - If set and non-zero, just label x-axis at bottom
		     (This reserves less vertical space between plots)
	NRows - Maximum number of rows.
	NCols - Number of columns (default is to compute from rows & # sigs)
       nSmooth - # for median smoothing before using signal (default=0)
	pCharSize - Value desired for !P.CHARSIZE, else guesses
	Titles - string array of the plot titles from the scope file, else y-name
	xMins - array of each plot's x-minimum from the scope file (else global, or 0)
	xMaxes - array of each plot's x-maximum from the scope file (else global, or 0)
	yMins - array of each plot's y-minimum from the scope file (else global, or 0)
	yMaxes - array of each plot's y-maximum from the scope file (else global, or 0)
	tweenspace - vertical space between plots in normalized coordinates
	colSpace - horizontal space between plots in normalized coordinates
	rightSpace  - space on right in normalized coordinates
	leftSpace - space on left in normalized coordinates
 EXAMPLE:
   (Send plots to a Tektronix window, say, from on a Mac from VersaTerm):
	IDL> setup_tek
	IDL> plotscope, shots=104500, refshot=104501, scope='WF'
	IDL> unsetup_tek
    (Make a scope-like plot without space between plots 
      -- the tick labels are outside their grids, unlike in Scope)
	IDL> plotscope,shot=105830,scope='wf',tweenspace=0,colspace=0
 COMMON BLOCKS:
       none
 NOTES:
 LIMITATIONS:
 MODIFICATION HISTORY:
	24-Aug-01 Written by Bill Davis

(See src/idl_cvs/plotscope.pro)


PRINTSCOPE

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

 PURPOSE:
	print scope-like output, using a scope file as input

 CATEGORY:
	MDSplus, Printing Plots

 KEYWORD INPUTS:
       shots - a string indicating shots, 
                e.g., 107694 108305 108330-108350
                 or   108100+20         
                        (this returns shots 108100, 108101,...,108120)
	scopeFile - if not specified will prompt
	printer - if not specified will prompt on Unix
	rightSpace - fractioanal space to right of last plot (0-1)
	leftSpace - fractioanal space to left of first plot (0-1)
	colSpace - fractioanal space between plot columns (0-1)
	vertSpace - fractioanal space between plot rows (0-1)
	t1 - start time of plots (sec)
	t2 - end time of plots (sec)
	nRows - # of rows of plots
	nCols - # of columns of plots
	noprint - if set, will not send plot to printer

 EXAMPLE:
    (on Unix:)
	printscope,shots='109071-109075',scope='wf.scope',printer='nstx-xn4525'

     or
	printscope,shots='109071+5' ; (will be prompted for file & printer)

     or 
     printscope, shots='109070+2',scope='/u/kaye/Scope/sk.scope',   $
                 leftspace=.07, rightspace=0.005, $
                 tweenspace=0.008, vertSpace = 0.03,  $
                 nrows=8, ncols=4,  $
                 printer='nstx-xn4525', charsize=1.3
 HISTORY:
	Written by Bill Davis for Stan Kaye, jan, 2003

(See src/idl_cvs/printscope.pro)


SEARCHMDSNODES

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        SearchMDSNodes
 PURPOSE:
      Search MDSplus nodes for string contents
 CATEGORY:
       MDSplus, Searching
 CALLING SEQUENCE:
       IDL> paths= SearchMDSNodes( str[, sensitivity, text=text][,path=path])
 INPUTS:
       str - string to search on
	sensitivity - (Optional) if ='Sensitive', then make search case sensitive
 KEYWORD PARAMETERS:
    Input (Optional):
       JustText - if set, just look for Text nodes (no effect if /TAGS set)
	nonNodeStr - exclude nodes in returned array if this string found in name
	tags - if set, just look for nodes with tags
       sizesearch - when searching text, length of string to check (def=1024)
	whatToSearch - = 'NAMES', 'TEXT', or 'TDI'
	treeName - MDSplus tree. Default='NSTX'
	shot - MDSplus shot to search. Default=-1 (the model tree).
	server - MDSplus server. Default is the default NSTX data server.
    Returned (Optional):
       text (contains the full text found), path(returns the full path to the text)
	status - status from mdsvalue call
 OUTPUTS:
	result - status of function: 0 = success, -1 = failed to find
 COMMON BLOCKS:
       none
 EXAMPLE:
	IDL> paths=SearchMDSNodes('xray', text=text ) 
 NOTES:
	tree must already be open before SearchMDSNodes can be called
	if no records are found in current tree returns -1 else returns 0
 MODIFICATION HISTORY:
	11-Nov-05 Added tree keyword
	01-Dec-00 Added capability for wildcards in search string
	10-Nov-00 Added sensitivity [BD]
       7-Feb-00 Written by Dana Mastrovito, PPPL

(See src/idl_cvs/searchmdsnodes.pro)


SEARCHTEXTNODES

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        SearchTextNodes
 PURPOSE:
      Search MDS Plus Trees for Textual Data
 CATEGORY:
       MDSplus, Searching
 CALLING SEQUENCE:
       IDL> result= SearchTextNodes( keyword[, sensitivity, text=text][,path=path])
 INPUTS:
       keyword - string to search on
	sensitivity - (Optional) if ='Sensitive', then make search case sensitive
 KEYWORD PARAMETERS:
       text (contains the full text found), path(returns the full path to the text)

 OUTPUTS:
	result - status of function: 0 = success, -1 = failed to find
   
 COMMON BLOCKS:
       none
 EXAMPLE:
	IDL> result=SearchTextNodes('xray', text=text,path=path)
 NOTES:
	tree must already be open before tsearch can be called
	if no records are found in current tree returns -1 else returns 0

 MODIFICATION HISTORY:
	01-Dec-00 Added capability for wildcards in search string
	10-Nov-00 Added sensitivity [BD]
       7-Feb-00 Written by Dana Mastrovito, PPPL

(See src/idl_cvs/searchtextnodes.pro)


SETMDSSHOTEVENT

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

 PURPOSE:
       set an MDS event with shot number associated with the event

 CATEGORY:
       MDSplus, Events

 CALLING SEQUENCE:
       IDL> setmdsshotevent, eventName [, shot_num]

 INPUTS:
	eventName - string of MDS event name, e.g., 'NE_DENSITY_CALC'
       shot_num - NSTX shot number (OPTIONAL -- will default to current shot)

 KEYWORD PARAMETERS:
    Optional:
	VERBOSE - If set, print debugging information
	NOCONNECT - if set, will not try to connect to an MDSplus server
	SERVER - if not set, will connect to default server in OpenMDSshot
       STATUS = return status, low bit set = success

 OUTPUTS:
       none -- just sets the event
 COMMON BLOCKS:
       NONE
 EXAMPLE:
 NOTES:
	Works from Unix or VMS
 MODIFICATION HISTORY:
 	17-Dec-2008 don't try to fill valBlk if shot_num not a number [bd]
 	11-Nov-2008 Default to no mdsconnect [BD]
	02-Nov-2008 Added status keword.
	11-Feb-04 use SETEVENT in MDSVALUE on Unix. Add connect option on unix.
   	20-Dec-99 Written [bd]

(See src/idl_cvs/setmdsshotevent.pro)


SHOTDURATION

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       ShotDuration
 PURPOSE:
       Return the Shot Duration in seconds
 CATEGORY:
       MDSplus
 CALLING SEQUENCE:
       IDL> seconds = ShotDuration(ishot, IpNeeded=IpNeeded, IpSignal=IpSignal,   $
                       RoundUp=RoundUp)
 INPUTS:
       ishot - shot number. If not supplied, will use current shot
 KEYWORD PARAMETERS:
       Keywords:
	  IpNeeded - plamsa current in kiloAmps to be considered real (default=50)
	  IpSignal - mdsplus signal to use to determine plasma current
		default = \wf::ip
		NOTE if signal is not in kiloAmps, divide or multiply by correct factor
	  InSignal - input Ip signal, so doesn't have to be read
	  maxValue - returns max plasma current in KA.
	  nSmooth - the amount to smooth Ip signal before checking the value
		    Default = 11 points.
	  RoundUp  - if set, add 0.1 seconds and round up to nearest 0.1 seconds
	  quiet - if not set, quiet
	  realquiet - if set, no "MDSOPEN success" message
	  Verbose  - if set, print debugging information
	  Server   - MDS server (default is for NSTX)
	  HLP - When set, help information is printed.
 OUTPUTS:
         seconds               			out
 COMMON BLOCKS:
       NONE
 EXAMPLE:
	IDL> opt = ShotDuration( IpNeeded=5, IpSignal='\engineering::ip2' )
 NOTES:
 MODIFICATION HISTORY:
	05-Mar-2008 Allow Ip to be passed in
	18-Feb-2008 Account for WF tree, but no \IP
	06-Feb-2008 replaced openMDSshot with mdsopen [BD]
	25-Apr-2006 added MaxValue (for Ip) keyword
	29-Aug-2005 nSmooth keyword added 
	28-Jul-2004 added realquiet keyword
      	08-Apr-2004 Written by Bill Davis, PPPL

(See src/idl_cvs/shotduration.pro)


TAG_EXIST

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	TAG_EXIST
 PURPOSE:
	To test whether a tag name exists in a structure.
 CATEGORY:
	MDSplus, structure
 CALLING SEQUENCE:
       status = tag_exist(str, tag)
 INPUTS: 
	str  -  structure variable to search
       tag  -  tag name to search for
 OUTPUTS: 
	Function returns 1 if tag name exists or 0 if it does not.
 KEYWORDS:
	INDEX = index of matching tag
 METHOD:
	Routine obtains a list of tagnames and tests whether the
       requested one exists or not. The search is recursive so 
       if any tag names in the structure are themselves structures
       the search drops down to that level.
 Common      : None
 Restrictions: None
 Side effects: None
 Written     : C D Pike, RAL, 18-May-94
 Modified    : 03-May-2007 datatype wasn't working, so just use SIZE [BD]
	      : Version 1.1, D Zarro, ARC/GSFC, 27-Jan-95
               Passed out index of matching tag
 Version     : Version 1.1, 27-Jan-95

(See src/idl_cvs/tag_exist.pro)


TAGRANKOF

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       tagRankOf
 PURPOSE:
       Return a list of MDSplus signals with a certain rank
	(that contain data)
 CATEGORY:
       MDSplus
 CALLING SEQUENCE:
       tags = tagRankOf( rankDesired )
 INPUTS:
       rankDesired = 0 for scalars, 1 for vectors, etc.  
 KEYWORD PARAMETERS:
    Optional Keywords:
	filter - wild card specifer. E.g. '*ip*' will get all of 
		 specifed rank with ip in the the tag name.
	fullpaths - returns full pathnames of tags found
	print  - if set, tags and full pathnames found will be printed
	debug - print some debugging info
  the tree may be opened before this routine is called, or you can specify:
	treeName - MDSplus tree. Default='NSTX' (unless embedded in nodeString)
	shot - MDSplus shot to search. Default=-1 (the model tree).
	server - MDSplus server. Default comes from the environmental variable _path
 OUTPUTS:
       tags = tagnames of specifed rank fitting any filter specified
		if none are found fitting criteria, 'none' is returned.
 EXAMPLE:
	IDL>  print, tagRankOf( 1, filter='i*', shot=120200, tree='wf' )
\WF::ICHI \WF::IOH \WF::IP \WF::IPF1AL \WF::IPF1AU \WF::IPF1B \WF::IPF2L \WF::IPF2U
\WF::IPF3L \WF::IPF3U \WF::IPF4 \WF::IPF5 \WF::ITF

	IDL> mdsopen,'microwave', 120200
	IDL> scalarNames = tagRankOf(0)
	IDL> someSigs = tagRankOf( 1, filter='n*', /print )
 COMMON BLOCKS:
       none
 NOTES:
       Only returns signals with data in them.
 LIMITATIONS:
	An MDSplus shot file must be open first.
 MODIFICATION HISTORY:
	10-Jan-08 Added extra keywords for findMDSnodes [BD]
	14-Mar-00 more efficient & added keywords [BD]
	20-Jan-00 Written by Bill Davis

(See src/idl_cvs/tagrankof.pro)


TAGSEARCH

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       tagsearch
 PURPOSE:
	Search MDS Plus Trees for a tag
 CATEGORY:
	MDSplus, Utility
 CALLING SEQUENCE:
       IDL> status=tagsearch(searchtag[,tag=tag, path=path])
 INPUTS:
	searchnode and optional variable to return an array of full paths containing
	 tag name and an array containing the tag names
 KEYWORD PARAMETERS:
  the tree may be opened before this routine is called, or you can specify:
    Inputs (optional):
	treeName - MDSplus tree. Default='NSTX' (unless embedded in nodeString)
	shot - MDSplus shot to search. Default=-1 (the model tree).
	server - MDSplus server. Default comes from the environmental variable _path
    Returned:
       path
	tag
 OUTPUTS:
       status of function              			
 COMMON BLOCKS:
       none
 EXAMPLE:
	IDL> status=tagSearch('xp_', tag=tag, path=fullpath, tree='nstx')
 NOTES:
       will return 0 if tag is found and -1 if it is not found in the tree specified
 MODIFICATION HISTORY:
	10-Jan-08 use findMDSnodes, since findtags.fun not in Linux distribution [BD]
	01-Dec-00 Added capability for wildcards in search string
       28-Feb-00 Written by Dana Mastrovito, PPPL

(See src/idl_cvs/tagsearch.pro)


TDIS

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       tdis
 PURPOSE:
      Search MDS Plus Trees for TDI DATA
 CATEGORY:
       MDSplus, Utility
 CALLING SEQUENCE:
       IDL> result = tdis( keyword[,sensitvity][, tdi=tdi][,path=path] )
 INPUTS:
       searchstring and optional variables to control case sensitivity and return an array of text strings found
	and an array of paths to those strings
 KEYWORD PARAMETERS:
   (output)
       tdi  - the full tdi found 
	path - the full path to the text

 OUTPUTS:
	result=status of function
   
 COMMON BLOCKS:
       none
 EXAMPLE:
	IDL> result=tdi('build','sensitive',tdi=tdi,path=path)
 NOTES:
       this version is specifically for idl4 (?)
	tree must already be open before tsearch can be called
	if no records are found in current tree returns -1 else returns 0

 MODIFICATION HISTORY:
	30-Jan-00 Speed up. Fixed node names.
	01-Dec-00 Added capability for wildcards in search string
       07-Feb-00 Written by Dana Mastrovito, PPPL

(See src/idl_cvs/tdis.pro)


TREE_EXISTS

[Previous Routine] [Next Routine] [List of Routines]
 NAME:  
 	tree_exists
 PURPOSE: 
	Return a true if an MDSplus tree exists for a given shot number
+--------------------------------------------------------------------------
 NAME:  
       tree_exists
 PURPOSE: 
       Return a true if an MDSplus tree exists for a given shot number

 CATEGORY:
       MDSplus, Trees
 CALLING SEQUENCE:
       found = tree_exists( shot, tree )
 INPUTS:
    (tree and shot arguments can be reversed, if shot is an number)
	shot - MDSplus shot number, i.e, ID. Can be string acceptable to 
		mk_shotlist.pro
	tree - tree to open. Defaults to 'wf'
 KEWORDS:
    (returned)
	list - list of shots found
 EXAMPLE:  
       IDL> IF tree_exists(101526,'operations') THEN ...

       IDL> founds = tree_exists( '112300-112302 112305+2', 'wf', list=shots )
 NOTE:
       Returns true only if shot exists; the shot may be empty.
	If you have an account on skylark.pppl.gov, you use mdir.pro,
	which is faster.

 19-Nov-2008 make work if input arguments are reversed
 WRITTEN 15-Nov-2008 by Bill Davis (old version replaced)

(See src/idl_cvs/tree_exists.pro)


TRIMTAGNAMES

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       trimtagnames
 PURPOSE:
       Trim tree info from an MDSplus tag name
 CATEGORY:
	MDSplus, Tagnames
 CALLING SEQUENCE:
         trimmedList = trimtagnames( sigList )
 INPUTS:
       sigList - a string array of MDSplus tag names 			 in
 KEYWORD PARAMETERS:
   (Optional)
	all - if set, trim everything but string following the last :
       treeOnly - if set only remove the tree (& top:). 
		   Leave the backslash, TDI, etc.
 OUTPUTS:
	trimmedList - a string array of MDSplus tag names 
 EXAMPLE:
	trimmedList = trimtagnames( sigList )
 COMMON BLOCKS:
 NOTES:
 MODIFICATION HISTORY:
	18-Oct-00 Added keyword treeOnly:
		  Don't assume tree name at beginning of string
		  (allows for trimming tree names from TDI expressions)
 	Written by Bill Davis March, 1999

(See src/idl_cvs/trimtagnames.pro)


USESIGMATH

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

 PURPOSE:
	parse an MDSplus TDI string, substituting Brian Nelson's Signal Math TDI
	routines for +,-,* and /, so timebases get adjusted, if necessary.

 CATEGORY:
	MDSplus

 CALLING SEQUENCE:
       IDL> newTDI = useSigMath( tdi )

 INPUTS:
       tdi = a TDI string in which any signals are preceded by '\'

 OUTPUTS:
	newTDI - math operations -, +, * & / are replaced by Brian Nelson's SigMath
		 functions sigsub, sigadd, sigmul and sigdiv.
 EXAMPLE:
	print, useSigMath('(\engineering::ip1+\engineering::ip2)/2')
	   SIGADD(\engineering::ip1,\engineering::ip2)/2

	print, useSigMath('\wf::ip-\wf::ipf4/\wf::ipf5')
	   SIGDIV(SIGSUB(\wf::ip,\wf::ipf4),\wf::ipf5)	   NOTE ORDER OF OPERATIONS IS LEFT TO RIGHT

	print, useSigMath('1000*\wf::ip-\engineering::ip1')
	   SIGSUB(1000*\wf::ip,\engineering::ip1)

	print, useSigMath('(\engineering::ip1/1000 - \wf::ip)')
	   SIGSUB(\engineering::ip1/1000,\wf::ip)

	print, useSigMath('1000*\wf::ip-\engineering::ip1')
	   SIGSUB(1000*\wf::ip,\engineering::ip1)

	print, useSigMath('\wf::ip-bcsmooth(\engineering::ip1/1000)')
	   SIGSUB(\wf::ip,bcsmooth(\engineering::ip1/1000))

	print, useSigMath('1000*\wf::ip-(\engineering::ip1+\engineering::ip2)/2')
	   SIGSUB(1000*\wf::ip,SIGADD(\engineering::ip1,\engineering::ip2)/2)

	print, useSigMath('abs(bcsmooth(\engineering::ip1/1000)-\wf::ip)')
	   (abs(SIGSUB(bcsmooth(\engineering::ip1/1000),\wf::ip)))

	print, useSigMath('\wf::ip-\wf::ip[0]')

 LIMITATIONS:
	Without brackets expressions will be evaluated from left to right.
	The SigMath routines do not correct for different units, like Amps and KiloAmps.
	Signals are only recognized when they begin with a backslash.

 MODIFICATION HISTORY:
	04-Aug-2008 made to work (i.e., not use Sigmath) with '\wf::ip-\wf::ip[0]'
  	WRITTEN 10-Aug-2007 by Bill Davis

(See src/idl_cvs/usesigmath.pro)


WFMDSSHOTEVENT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	wfMDSshotEvent
 PURPOSE:
	Wait for an MDSplus event, with shot number coming in
 CATEGORY:
	MDSplus, Events
 CALLING SEQUENCE:
	wfMDSshotEvent, event, shotnum, [,/QUIET][,STATUS=istat]
 INPUT PARAMETERS:
	event = name of an MDSplus event to wait for.
 RETURNED PARAMETERS:
	shotnum - whatever data was passed when the event was set.
	          for MDSplus events, except for nstx_acq_started
 Keywords (Optional):
	ASCII - if set, will assume data block contains ascii representation of numbers
	NOCONNECT - if set, will not try to connect to an MDSplus server
	SERVER - if not set, will connect to default server in OpenMDSshot
       QUIET = prevents IDL error if MDSplus command fails
       STATUS = return status, low bit set = success
 COMMON BLOCKS:
	None.
 SIDE EFFECTS:
	None.
 RESTRICTIONS:
 PROCEDURE:
	Makes a call to MDSplus shared image library
       procedure MDS$WTEVENT and checks for errors.
 MODIFICATION HISTORY:
 	11-Nov-2008 Default to no mdsconnect [BD]
	02-Nov-2008 Return -1 if error from mdsvalue. Have an option not to 
		    connect.
	09-Mar-2007 Added ASCII keyword which is needed on sflip PC
	08-Jul-2005 Added support for Windows
	31-May-05 include server keyword
	06-Apr-05 use MdsValue( 'WFEVENT($)'... instead. [BD]
	24-May-01 If on Unix, connect to VMS if not already [BD]
	06-Nov-00 Made same version work on VMS & Unix [BD]
	copied from mds$wfevent.pro, so could have the same name on vms & unix
	VERSION 1.0, CREATED BY T.W. Fredian, April 22,1991

 debug version 7/14/05 PR syntax error in if/endif structure

(See src/idl_cvs/wfmdsshotevent.pro)


WITHRANKOF

[Previous Routine] [List of Routines]
 NAME:
       WithRankOf
 PURPOSE:
       Return a list of MDSplus signals with a certain rank
	(that contain data)
 CATEGORY:
       MDSplus
 CALLING SEQUENCE:
       sigs=withrankof( rank )
 INPUTS:
	rank - integer rank of signal desired
 KEYWORD PARAMETERS:
	filter - wildcard specification to find signal names with desired rank
	signalnames - if present, use these, and ignore filter
 OUTPUTS:
	sigs - MDSplus signal names with 
 EXAMPLE:
	IDL> stat=mdsopen('passivespec',101964)
	IDL> scalarNames = withrankof(0)
 COMMON BLOCKS:
       none
 NOTES:
       Only returns signals with data in them.
 LIMITATIONS:
	An MDSplus shot file must be open first.
 MODIFICATION HISTORY:
	31-Jan-07 add keyword to pass in signalnames
	20-Jan-00 Written by Bill Davis

(See src/idl_cvs/withrankof.pro)


Category: Misc

[List of Routines]


BAD_PTDATA_ERROR

[Next Routine] [List of Routines]
 
 NAME:
       BAD_PTDATA_ERROR
 PURPOSE:
       Return a logical true IF  the PTDATA error is serious
 CATEGORY:
       GA, error processing
 CALLING SEQUENCE:
       logical = Bad_PTDATA_Error(ptdata_ierr)
 INPUTS:
       ptdata_ierr - error return from PTDATA calls
 KEYWORD PARAMETERS:
 OUTPUTS:
 RETURNED:	logical indication of a serious error 
		(per IDL definition, e.g., 0 IF  false)
 COMMON BLOCKS:
 MODIFICATION HISTORY:
               1-Apr-97 WMD Written

(See src/idl_cvs/bad_ptdata_error.pro)


BPWFEDIT

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

 PURPOSE:
	Read, Edit, & Plot Breakpoint Waveform files used in ppcc system on TFTR
 CATEGORY:
       TFTR, Waveforms, GUI Editing

 REVISION HISTORY:
	21-Aug-98 Written by Bill Davis

(See src/idl_cvs/bpwfedit.pro)


CAMAC_HERE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       CAMAC_here
 PURPOSE:
       Return 1 if CAMAC on this computer
	(if environmental variable "camac_server" is non-blank)
 CATEGORY:
       CAMAC
 CALLING SEQUENCE:
       IDL> OK = CAMAC_here()
 INPUTS:
       none required  
 KEYWORD PARAMETERS:
	var - Environmental variable to check to determine if CAMAC available.
		(defaults to 'camac_server')
	HLP - When set, help information is printed.
	verbose - if set, will print many informational messages
	debug - if set, debug output will be printed
 OUTPUTS:
       OK = 1 if environmental variable "camac_server" is non-blank
 EXAMPLE:
 NOTES:
       When the routine is called with the
	keyword hlp set, help information is printed.
 MODIFICATION HISTORY:
       08-Jan-2009 Written by Bill Davis, PPPL

(See src/idl_cvs/camac_here.pro)


CH_EXAMPLE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       CH_Example
 PURPOSE:
       a simple example using the GA Crosshair routines
 CATEGORY:
       GUI Graphics, Example
 CALLING SEQUENCE:
       CH_Example
 COMMON BLOCKS:
       ch_example
 NOTES:
       Your display may have to be set to 256 colors to see the crosshairs.
 MODIFICATION HISTORY:
       Written by Bill Davis, 8/29/97

       GA Crosshair routines originally written by John Ferron. 
       Now maintained by T. Terpstra

(See src/idl_cvs/ch_example.pro)


CH_REGISTER

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
  	ch_register
 PURPOSE:
	register window for crosshair routines

 CATEGORY:
	GUI Graphics, Cursor Cross-hairs

 EXAMPLE:
	See ch_example.pro

 MODIFIED:
	29-Nov-07 Don't handle if window names not found in ch_set [BD]
	30-Oct-00 Override !P.PSYM & !P.LINESTYLE for cros-hairs  [BD]
	04-Dec-99 Make mask bit 6, so it's red when used with MK_COLOR  [BD]
	29-Mar-99 Added newX, newY & newP keywords to CH_SET for changing
		  plotting parameters  [BD]
	26-Jan-99 Taken from GA   [BD]
		  Combining all ch_ files here, since this must be called 1st.

(See src/idl_cvs/ch_register.pro)


COPY_STRUCT

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

 PURPOSE:
       Copy all fields with matching tag names from one structure to another

 CATEGORY:
	Programming
 
 EXPLANATION
       Fields with matching tag names are copied from one structure array to 
       another structure array of different type.
       This allows copying of tag values when equating the structures of
       different types is not allowed, or when not all tags are to be copied.
       Can also recursively copy from/to structures nested within structures.
       Note that the number of elements in the output structure array
       is automatically adjusted to equal the length of input structure array.
       If this not desired then use pro copy_struct_inx which allows
       specifying via subscripts which elements are copied where in the arrays.

 CALLING SEQUENCE:

       copy_struct, struct_From, struct_To, NT_copied
       copy_struct, struct_From, struct_To, EXCEPT=["image","misc"]
       copy_struct, struct_From, struct_To, /RECUR_TANDEM

 INPUTS:
       struct_From = structure array to copy from.
       struct_To = structure array to copy values to.

 KEYWORDS:

       EXCEPT_TAGS = string array of tag names to ignore (to NOT copy).
               Used at all levels of recursion.

       SELECT_TAGS = tag names to copy (takes priority over EXCEPT).
               This keyword is not passed to recursive calls in order
               to avoid the confusion of not copying tags in sub-structures.

       /RECUR_FROM = search for sub-structures in struct_From, and then
               call copy_struct recursively for those nested structures.

       /RECUR_TO = search for sub-structures of struct_To, and then
               call copy_struct recursively for those nested structures.

       /RECUR_TANDEM = call copy_struct recursively for the sub-structures
               with matching Tag names in struct_From and struct_To
               (for use when Tag names match but sub-structure types differ).

 OUTPUTS:
       struct_To = structure array to which new tag values are copied.
       NT_copied = incremented by total # of tags copied (optional)

 INTERNAL:
       Recur_Level = # of times copy_struct calls itself.
               This argument is for internal recursive execution only.
               The user call is 1, subsequent recursive calls increment it,
               and the counter is decremented before returning.
               The counter is used just to find out if argument checking
               should be performed, and to set NT_copied = 0 first call.
 EXTERNAL CALLS:
       pro match       (when keyword SELECT_TAGS is specified)
 PROCEDURE:
       Match Tag names and then use corresponding Tag numbers.
 HISTORY:
       written 1989 Frank Varosi STX @ NASA/GSFC
       mod Jul.90 by F.V. added option to copy sub-structures RECURSIVELY.
       mod Aug.90 by F.V. adjust # elements in TO (output) to equal
                       # elements in FROM (input) & count # of fields copied.
       mod Jan.91 by F.V. added Recur_Level as internal argument so that
                       argument checking done just once, to avoid confusion.
                       Checked against Except_Tags in RECUR_FROM option.
       mod Oct.91 by F.V. added option SELECT_TAGS= selected field names.
       mod Aug.95 by W. Landsman to fix match of a single selected tag.
       mod Mar.97 by F.V. do not pass the SELECT_TAGS keyword in recursion.

(See src/idl_cvs/copy_struct.pro)


CW_FIELD

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

 PURPOSE:
   This widget cluster function manages a data entry field widget.
   The field consists of a label and a text widget.  CW_FIELD's can
   be string fields, integer fields or floating-point fields.  The
   default is an editable string field.

 CATEGORY:
   Widget Clusters.

 CALLING SEQUENCE:
   Result = CW_FIELD(Parent)

 INPUTS:
   Parent: The widget ID of the widget to be the field's parent.

 KEYWORD PARAMETERS:
   TITLE:  A string containing the text to be used as the label for the
       field.  The default is "Input Field:".

   VALUE:  The initial value in the text widget.  This value is
       automatically converted to the type set by the STRING,
       INTEGER, and FLOATING keywords described below.

   UVALUE: A user value to assign to the field cluster.  This value
       can be of any type.

   UNAME:   A user supplied string name to be stored in the
       widget's user name field.

   FRAME:  The width, in pixels, of a frame to be drawn around the
       entire field cluster.  The default is no frame.

RETURN_EVENTS: Set this keyword to make cluster return an event when a
        is pressed in a text field.  The default is
       not to return events.  Note that the value of the text field
       is always returned when the WIDGET_CONTROL, field, GET_VALUE=X
       command is used.

   ALL_EVENTS: Like RETURN_EVENTS but return an event whenever the
       contents of a text field have changed.

   COLUMN: Set this keyword to center the label above the text field.
       The default is to position the label to the left of the text
       field.

   ROW:    Set this keyword to position the label to the left of the text
       field.  This is the default.

   XSIZE:  An explicit horizontal size (in characters) for the text input
       area.  The default is to let the window manager size the
       widget.  Using the XSIZE keyword is not recommended.

   YSIZE:  An explicit vertical size (in lines) for the text input
       area.  The default is 1.

   STRING: Set this keyword to have the field accept only string values.
       Numbers entered in the field are converted to their string
       equivalents.  This is the default.

     FLOATING: Set this keyword to have the field accept only floating-point
       values.  Any number or string entered is converted to its
       floating-point equivalent.

      INTEGER: Set this keyword to have the field accept only integer values.
       Any number or string entered is converted to its integer
       equivalent (using FIX).  For example, if 12.5 is entered in
       this type of field, it is converted to 12.

   LONG:   Set this keyword to have the field accept only long integer
       values.  Any number or string entered is converted to its
       long integer equivalent (using LONG).

   FONT:   A string containing the name of the X Windows font to use
       for the TITLE of the field.

    FIELDFONT: A string containing the name of the X Windows font to use
       for the TEXT part of the field.

   NOEDIT: Normally, the value in the text field can be edited.  Set this
       keyword to make the field non-editable.

 OUTPUTS:
   This function returns the widget ID of the newly-created cluster.

 COMMON BLOCKS:
   None.

 PROCEDURE:
   Create the widgets, set up the appropriate event handlers, and return
   the widget ID of the newly-created cluster.

 EXAMPLE:
   The code below creates a main base with a field cluster attached
   to it.  The cluster accepts string input, has the title "Name:", and
   has a frame around it:

       base = WIDGET_BASE()
       field = CW_FIELD(base, TITLE="Name:", /FRAME)
       WIDGET_CONTROL, base, /REALIZE

 MODIFICATION HISTORY:
   01-Jun-2006 added double keyword [BD]
   11-Mar-2004 Added ALIGN_CENTER & ALIGN_RIGHT  [BD]
   July 2001 CT, RSI, Fix bug in previous mod. If user passes in a
         numeric VALUE but forgets to set the /FLOAT, we still need
         to convert to a string before passing onto WIDGET_TEXT.
   March 2001: CT, RSI, Pass keywords directly into WIDGET_BASE,
         without assigning default values, since the defaults are
         handled by WIDGET_BASE. Avoids assigning defaults if user passes
         in undefined variables.
   Written by: Keith R. Crosley   June 1992
           KRC, January 1993 -- Added support for LONG
                        integers.
               AB, 7 April 1993, Removed state caching.
           JWG, August 1993, Completely rewritten to make
               use of improved TEXT widget functionality
           ACY, 25 March, 1994, fix usage of FRAME keyword
                       KDB, May 1994, Initial value =0 would result
                                      in a null text field. Fixed
                                      keyword check.

(See src/idl_cvs/cw_field.pro)


FIND_COMMON()

[Previous Routine] [Next Routine] [List of Routines]
 Project     : SOHO - CDS     
                   
 Name        : FIND_COMMON()
               
 Purpose     : Find which elements are common to the input vectors.
               
 Explanation : Returns the indices of the elements in second vector which
               are also present in the first vector.
               
 Use         : IDL> c = find_common(first, second)
    
 Inputs      : first  -  vector to be searched
               second -  search vector
               
 Opt. Inputs : None
               
 Outputs     : Function returns indices of elements in second vector which
               are common to first and second vectors
               
 Opt. Outputs: None
               
 Keywords    : None

 Calls       : FIND_DUP()

 Common      : None
               
 Restrictions: None
               
 Side effects: None
               
 Category    : Util
               
 Prev. Hist. : None

 Written     : C D Pike, RAL, 9-Nov-94
               
 Modified    : Make loop variable LONG.  CDP, 1-Oct-97

 Version     : Version 2, 1-Oct-97

(See src/idl_cvs/find_common.pro)


FINDPEAKS

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       findpeaks
 PURPOSE:
       Find peaks in a data array. To be a peak a local maximum must have
	a 25% higher range than the first and last quarter of the peak range.
 CATEGORY:
       Data Analysis
 CALLING SEQUENCE:
	IDL> peaks = findpeaks( data )
 INPUTS:
	data - array 
 OUTPUTS:
	peaks - (up to "maxPeaks") values of peaks found. Returns 0 if no
		peaks found.
 KEYWORDS:
   Optional Input:
	maxPeaks - max # of peaks to search for
	AboveFrac - Fraction of peak height that peak must be above the 
		peak "tails" to be counted (default=0.25)
	NeighborhoodFrac - fraction of whole X range to be a neighborhood.
          	Range is initially divided up in these neighborhoods
		for determination of initial maxima.
	HowCloseToMax - if set, will not be considered a peak, if not within
		this fraction of maximum of whole data set.
	OnlyBig - if set will not count peaks 1/3 the size of the biggest peak
	Plot - if set, will plot data with vertical lines indicating which
		peaks qualified.
	Ordered - if set, returns peaks in order of highest first
   Optionally Returned:
	indicesOfPeaks - array indices of peaks returned (=-1 if no peaks found)
	FWHM - full width at half max estimate, in indices
 EXAMPLE:
	IDL> data = mk_2peaks()
	IDL> peaks = findpeaks( data, /plot )
 COMMON BLOCKS:
       none
 NOTES:
	Maxima too close to the beginning and end of array are not counted.
       You may wish to do filtering or smoothing before passing data.
 LIMITATIONS:
	What constitutes a "peak" is subjective, so this won't fit all needs
 MODIFICATION HISTORY:
	05-Aug-2008 Added HowCloseToMax keyword & many mods for finding Lithium peaks
	08-May-2003 Written by Bill Davis, PPPL

(See src/idl_cvs/findpeaks.pro)


FLUXCOORDS

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       fluxcoords
 PURPOSE:
       Return flux coordinates for input R values at a given Z
 CATEGORY:
       Physics, Plotting
 CALLING SEQUENCE:
       IDL> newXs = fluxcoords( shot=shot, time=time, Radius=Radius, z=z )
 INPUTS:
       (only keywords) 
 KEYWORD PARAMETERS:
   Inputs
     Required:
	shot - NSTX shot number
	time - time after T0, in seconds
	Radius - floating point array of major radii, in meters
     Optional:
	Z - Z value (above mid-plane) in meters (default = 0), scalar or dimensioned 
	    same as Radius.
	fit - E.g., 'EFIT01', EFIT02', 'LRDFIT04', etc. (defaults to 'EFIT01')
	psi_n - if set, will return on psi_n surfaces
	verbose - if set, will print many informational messages
   Outputs
	newXs - transformed input points to rho or psi_n, depending on keyword inputs
	status - if odd, then was successful
 OUTPUTS:
       opt = returned value                                    out
 COMMON BLOCKS:
       NONE
 EXAMPLE:
       IDL> Radius=findgen(10)/10.*.30+1.50
       IDL> newXs = fluxcoords( shot=121100, time=0.205, Radius=Radius, fit='EFIT01') 
       IDL> newXs = fluxcoords( shot=120440, time=0.206, Radius=Radius, z=0.5, fit='lrdfit09') 
 NOTES:
       Slow 1st time called for each new time. Especially slow for LRDFIT trees because 
	need to an MDSCONNECT to VMS, for some reason, for this to work.
       
 MODIFICATION HISTORY:
	01-Oct-2008 Removed mdsconnect [BD]
       22-Feb-2007 Written by Bill Davis, PPPL, using LOTS of code from Jon Menard

(See src/idl_cvs/fluxcoords.pro)


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

 PURPOSE:
 
       This function returns the string needed to draw the specified
       greek character using either the vector graphics font no. 4,
       or PostScript font 9.

       If (!d.name eq 'PS') and (!p.font eq 0), then the PostScript
       font will be used.  Otherwise, the vector font will be used.

 CALLING SEQUENCE:
 
	Result = GREEK(Name)

 INPUTS:
 
       Name - String specifying the greek character name. Valid
              inputs are:

              alpha, beta, gamma, delta, epsilon, zeta, eta, theta
              iota, kappa, lambda, mu, nu, xi, omicron, pi, rho,
              sigma, tau, upsilon, phi, chi, psi, omega

              Alpha, Beta, Gamma, Delta, Epsilon, Zeta, Eta, Theta
              Iota, Kappa, Lambda, Mu, Nu, Xi, Omicron, Pi, Rho,
              Sigma, Tau, Upsilon, Phi, Chi, Psi, Omega

              Although not greek, the following characters are also
              valid (but will only work with the 'default' font !3):

              angstrom, Angstrom, degrees, plus_minus

 KEYWORDS:

       FORCE_PS - Set to use PostScript font, regardless of the value
                  of !d.name and !p.font.

       PLAIN - Set to just return Name in plain text.

       APPEND_FONT - Set to append the characters specifying a
                     'default' font: !3. That is, if this keyword is
                     set, then the command

                     Result=GREEK(theta,/APPEND_FONT)

                     will return the string

                     '!9q!3' for PostScript and '!4h!3' for vector
                     fonts.
 

 OUTPUTS:
 
       Result - The string containing the specified greek character.

 EXAMPLE:

	Result=GREEK(theta)
	
       In this case, Result='!9q' if !d.name is 'PS' and !p.font is
       0; otherwise, Result='!4h'

 MODIFICATION HISTORY:
 
 	David L. Windt, Bell Labs, September 1998.
       windt@bell-labs.com
                    

(See src/idl_cvs/greek.pro)


HIGHESTEFITRUN

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       highestEfitRun
 PURPOSE:
 	find highest efit version run (in the MDSplus tree)
	Checks up to 5, and contigously after that
 CATEGORY:
       EFIT, MDSplus
 CALLING SEQUENCE:
       IDL> run = highestEfitRun(shot)
 INPUTS:
       shot = shot #  
 KEYWORD PARAMETERS:
	FITTYPE= fit type. Defaults to 'EFIT'. Works for 'LRDFIT', too.
	min2Check - will always check up to this number, and contigously
		    after that. E.g. if there is a EFIT05 and EFIT07, 
		    5 will be declared the highest unless this keyword
		    is 6 or higher.
 OUTPUTS:
       integer # representing highest EFIT run in tree
 EXAMPLES:
	IDL> print,fitsrun(123001)
	       EFIT01 EFIT02 EFITRT
	IDL> print,highestefitrun(123001)
		2

	IDL> print,fitsrun(117707)
	EFIT01 EFIT02 EFIT03 EFIT06 EFITRT LRDFIT04 LRDFIT06
	IDL> print,highestefitrun(117707)
	       6
	IDL> print,highestefitrun(117707,FIT='LRDFIT')
	       6
 NOTES:
       When the routine is called with no parameters, or with the
	keyword hlp set, help information is printed.
 MODIFICATIONS:
	29-Aug-2008 make min2check=20 for LRDfit
 	27-Aug-2007 check at least 5 runs. Add keyword for fit type and
			min2Check.
	Aug-2005 Written by Bill Davis

(See src/idl_cvs/highestefitrun.pro)


INTERP2D

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
   interp2d
 PURPOSE:
   Perform bilinear 2d interpolation using the IDL intrinsic 
   interpolate procedure
 CALLING SEQUENCE:
   result = interp2d(A,x0,y0,x1,y1)
   result = interp2d(A,x0,y0,x1,y1,/grid)
   result = interp2d(A,x0,y0,x1,y1,/regular,/cubic)
   result = interp2d(A,x0,y0,x1,y1,missing=missing)
 INPUTS:
   A	= 2d array to interpolate
   x0	= Values that correspond to A(0,0), A(1,0), ...
   y0  = Values that correspond to A(0,0), A(0,1), ...
   x1	= New X values at which A should be interpolated
   y1  = New Y values at which A should be interpolated
 OPTIONAL INPUTS:
   nxny = [nx,ny] Vector of length 2 which specifies the size of
         the regular linearized grid produced with trigrid.  The
         default is nxny = [51,51].  If the size of A is much larger
	  than 51 by 51, greater accuracy may be obtained by having
         nxny = [n_elements(A(*,0),n_elements(A(0,*))]
 OPTIONAL INPUT KEYWORDS:
   grid= If set, return an n_elements(X1) by n_elements(y1) grid
   missing = Value to points which have X1 gt max(X0) or X1 lt min(X0)
		and the same for Y1.
   quintic = If set, use smooth interpolation in call to trigrid
   regular = If set, do not call trigrid -- x0 and y0 must be linear.
   cubic   = If set, use cubic convolution
   extrapolate = If set, then extrapolate beyond boundary points
   bin = set to bin data prior to interpolation.
         (e.g. bin=2 interpolate every second pixel)
 Returned:
   result = a vector N_elements(X1) long 
      or, if /grid is set
   result = an array that is N_elements(X1) by N_elements(Y1)

 PROCEDURE:
   First call the IDL intrinsic routines TRIANGULATE & TRIGRID to make
	sure that X0 and Y0 are linear (if /regular is not set).
   Then call the IDL intrinsic INTERPOLATE to do bilinear interpolation.
 RESTRICTIONS:
   X0 and Y0 must be linear functions.
   A must be a 2-d array
 HISTORY:
    9-mar-94, J. R. Lemen LPARL, Written.
   20-Jan-95, JRL, Added the REGULAR & CUBIC keywords
   6-Sept-97, Zarro, GSFC, allowed for 2-d (X-Y) coordinate inputs
  22-Apri-99, Zarro, SM&A/GSFC - added /triangulate and made /regular
              the default (much faster).

(See src/idl_cvs/interp2d.pro)


INTERPWF

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

  PURPOSE: 
	Interpolate MDS signal, or array, to 1 KHz.

  CATEGORY:
       Interpolation

  CALLING SEQUENCE:
	IDL> data1KHz = interpwf( inData, time=intime, OUTTIME=outTime)
	  or
	IDL> data1KHz = interpwf( sigName )
  INPUTS:
	inData - data array or MDSplus signal name
  KEYWORDS:
	intime - timebase of input. If not present will get dim_of(inData)
	dt - delta time desired of output. Default to 1.0e-3 (1 KHz)
	TSTART - start time desired. If not present, =0.0
	TSTOP - last output time desired. If not present = max(inTime)
     Returned
	outTime - timebase of desired output array.
  EXAMPLES:
    (works with just arrays, if time present:)
	IDL> data1KHz = interpwf(findgen(3000), time=findgen(3000)/(3000)*1.2, $
		                 OUTTIME=outTime)
	IDL> mdsopen, 'engineering', 130000 
	IDL> wf=interpwf( '\ip1', OUTTIME=outTime, $
				tStart=-0.5, tStop=1.5 )
	IDL> data=mdsvalue('\ip1')
	IDL> time=mdsvalue('dim_of(\ip1)')
	IDL> plot, time, data
	IDL> oplot, outTime, wf, color=colorsearch('red')
  LIMITATION:
	If a signal name is passed in, assume the tree is already open
  MODIFICATION HISTORY:
       13-Feb-2009 do everything in IDL
	27-Jun-2008 Convert to Linux
	06-Apr-06 made default endtime lesser of input and output time
       05-Jul-00 Written by Bill Davis, PPPL

(See src/idl_cvs/interpwf.pro)


ISNUMBER

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

 NAME:
       ISNUMBER
 PURPOSE:
       Determine if a text string is a valid number.
 CATEGORY:
 CALLING SEQUENCE:
       i = isnumber(txt, [x])
 INPUTS:
       txt = text string to test.                      in
 KEYWORD PARAMETERS:
 OUTPUTS:
       x = optionaly returned numeric value if valid.  out
       i = test flag:                                  out
           0: not a number.
           1: txt is a long integer.
           2: txt is a float.
           -1: first word of txt is a long integer.
           -2: first word of txt is a float.
 COMMON BLOCKS:
 NOTES:
 MODIFICATION HISTORY:
	15-Feb-2008 don't consider date string, like 02/15/2008, a number [BD]
	29-Oct-2007 return 0 if input not defined [BD]
	01-Dec-2006 handle structures (treat as not a number) [Bill Davis]
       Richard Garrett, 14 June, 1992 --- fixed bug in returned float value.
       R. Sterner, 12 Mar, 1990 --- upgraded.
       R. Sterner.  15 Oct, 1986.
       Johns Hopkins Applied Physics Lab.

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

(See src/idl_cvs/isnumber.pro)


LEGEND

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       LEGEND
 PURPOSE:
       Create an annotation legend for a plot.
 EXPLANATION:
       This procedure makes a legend for a plot.  The legend can contain
       a mixture of symbols, linestyles, Hershey characters (vectorfont),
       and filled polygons (usersym).  A test procedure, legendtest.pro,
       shows legend's capabilities.  Placement of the legend is controlled
       with keywords like /right, /top, and /center or by using a position
       keyword for exact placement (position=[x,y]) or via mouse (/position).
 CALLING SEQUENCE:
       LEGEND [,items][,keyword options]
 EXAMPLES:
       The call:
               legend,['Plus sign','Asterisk','Period'],psym=[1,2,3]
         produces:
               -----------------
               |               |
               |  + Plus sign  |
               |  * Asterisk   |
               |  . Period     |
               |               |
               -----------------
         Each symbol is drawn with a plots command, so they look OK.
         Other examples are given in optional output keywords.

       lines = indgen(6)                       ; for line styles
       items = 'linestyle '+strtrim(lines,2)   ; annotations
       legend,items,linestyle=lines            ; vertical legend---upper left
       items = ['Plus sign','Asterisk','Period']
       sym = [1,2,3]
       legend,items,psym=sym                   ; ditto except using symbols
       legend,items,psym=sym,/horizontal       ; horizontal format
       legend,items,psym=sym,box=0             ; sans border
       legend,items,psym=sym,delimiter='='     ; embed '=' betw psym & text
       legend,items,psym=sym,margin=2          ; 2-character margin
       legend,items,psym=sym,position=[x,y]    ; upper left in data coords
       legend,items,psym=sym,pos=[x,y],/norm   ; upper left in normal coords
       legend,items,psym=sym,pos=[x,y],/device ; upper left in device coords
       legend,items,psym=sym,/position         ; interactive position
       legend,items,psym=sym,/right            ; at upper right
       legend,items,psym=sym,/bottom           ; at lower left
       legend,items,psym=sym,/center           ; approximately near center
       legend,items,psym=sym,number=2          ; plot two symbols, not one
       legend,items,/fill,psym=[8,8,8],colors=[10,20,30]; 3 filled squares
 INPUTS:
       items = text for the items in the legend, a string array.
               For example, items = ['diamond','asterisk','square'].
               You can omit items if you don't want any text labels.
 OPTIONAL INPUT KEYWORDS:

       linestyle = array of linestyle numbers  If linestyle[i] < 0, then omit
               ith symbol or line to allow a multi-line entry.
       psym = array of plot symbol numbers.  If psym[i] is negative, then a
               line connects pts for ith item.  If psym[i] = 8, then the
               procedure usersym is called with vertices define in the
               keyword usersym.   If psym[i] = 88, then use the previously
               defined user symbol
       vectorfont = vector-drawn characters for the sym/line column, e.g.,
               ['!9B!3','!9C!3','!9D!3'] produces an open square, a checkmark,
               and a partial derivative, which might have accompanying items
               ['BOX','CHECK','PARTIAL DERIVATIVE'].
               There is no check that !p.font is set properly, e.g., -1 for
               X and 0 for PostScript.  This can produce an error, e.g., use
               !20 with PostScript and !p.font=0, but allows use of Hershey
               *AND* PostScript fonts together.
       N. B.: Choose any of linestyle, psym, and/or vectorfont.  If none is
               present, only the text is output.  If more than one
               is present, all need the same number of elements, and normal
               plot behaviour occurs.
               By default, if psym is positive, you get one point so there is
               no connecting line.  If vectorfont[i] = '',
               then plots is called to make a symbol or a line, but if
               vectorfont[i] is a non-null string, then xyouts is called.
       /help = flag to print header
       /horizontal = flag to make the legend horizontal
       /vertical = flag to make the legend vertical (D=vertical)
       box = flag to include/omit box around the legend (D=include)
       clear = flag to clear the box area before drawing the legend
       delimiter = embedded character(s) between symbol and text (D=none)
       colors = array of colors for plot symbols/lines (D=!P.color)
       textcolors = array of colors for text (D=!P.color)
       margin = margin around text measured in characters and lines
       spacing = line spacing (D=bit more than character height)
       pspacing = psym spacing (D=3 characters)
       charsize = just like !p.charsize for plot labels
       charthick = just like !p.charthick for plot labels
       thick = array of line thickness numbers, if used, then linestyle
               must also be specified
	box_color=color for the box       
	position = data coordinates of the /top (D) /left (D) of the legend
       normal = use normal coordinates for position, not data
       device = use device coordinates for position, not data
       number = number of plot symbols to plot or length of line (D=1)
       usersym = 2-D array of vertices, cf. usersym in IDL manual. (D=square)
       /fill = flag to fill the usersym
       /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.

       If LINESTYLE, PSYM, VECTORFONT, THICK, COLORS, or TEXTCOLORS are
       supplied as scalars, then the scalar value is set for every line or
       symbol in the legend.
 Outputs:
       legend to current plot device
 OPTIONAL OUTPUT KEYWORDS:
       corners = 4-element array, like !p.position, of the normalized
         coords for the box (even if box=0): [llx,lly,urx,ury].
         Useful for multi-column or multi-line legends, for example,
         to make a 2-column legend, you might do the following:
           c1_items = ['diamond','asterisk','square']
           c1_psym = [4,2,6]
           c2_items = ['solid','dashed','dotted']
           c2_line = [0,2,1]
           legend,c1_items,psym=c1_psym,corners=c1,box=0
           legend,c2_items,line=c2_line,corners=c2,box=0,pos=[c1(2),c1(3)]
           c = [c1(0)c2(2),c1(3)>c2(3)]
           plots,[c(0),c(0),c(2),c(2),c(0)],[c(1),c(3),c(3),c(1),c(1)],/norm
         Useful also to place the legend.  Here's an automatic way to place
         the legend in the lower right corner.  The difficulty is that the
         legend's width is unknown until it is plotted.  In this example,
         the legend is plotted twice: the first time in the upper left, the
         second time in the lower right.
           legend,['1','22','333','4444'],linestyle=indgen(4),corners=corners
                       ; BOGUS LEGEND---FIRST TIME TO REPORT CORNERS
           xydims = [corners(2)-corners(0),corners(3)-corners(1)]
                       ; SAVE WIDTH AND HEIGHT
           chdim=[!d.x_ch_size/float(!d.x_size),!d.y_ch_size/float(!d.y_size)]
                       ; DIMENSIONS OF ONE CHARACTER IN NORMALIZED COORDS
           pos = [!x.window(1)-chdim(0)-xydims(0) $
                       ,!y.window(0)+chdim(1)+xydims(1)]
                       ; CALCULATE POSITION FOR LOWER RIGHT
           plot,findgen(10)    ; SIMPLE PLOT; YOU DO WHATEVER YOU WANT HERE.
           legend,['1','22','333','4444'],linestyle=indgen(4),pos=pos
                       ; REDO THE LEGEND IN LOWER RIGHT CORNER
         You can modify the pos calculation to place the legend where you
         want.  For example to place it in the upper right:
           pos = [!x.window(1)-chdim(0)-xydims(0),!y.window(1)-xydims(1)]
 Common blocks:
       none
 Procedure:
       If keyword help is set, call doc_library to print header.
       See notes in the code.  Much of the code deals with placement of the
       legend.  The main problem with placement is not being
       able to sense the length of a string before it is output.  Some crude
       approximations are used for centering.
 Restrictions:
       Here are some things that aren't implemented.
       - An orientation keyword would allow lines at angles in the legend.
       - An array of usersyms would be nice---simple change.
       - An order option to interchange symbols and text might be nice.
       - Somebody might like double boxes, e.g., with box = 2.
       - Another feature might be a continuous bar with ticks and text.
       - There are no guards to avoid writing outside the plot area.
       - There is no provision for multi-line text, e.g., '1st line!c2nd line'
         Sensing !c would be easy, but !c isn't implemented for PostScript.
         A better way might be to simply output the 2nd line as another item
         but without any accompanying symbol or linestyle.  A flag to omit
         the symbol and linestyle is linestyle[i] = -1.
       - There is no ability to make a title line containing any of titles
         for the legend, for the symbols, or for the text.
 Side Effects:
 Modification history:
	10-Aug-07 add debug keyword. Don't die if more lines than labels. [BD]
	01-Mar-99 squeeze legend closer to top [Bill Davis]
       write, 24-25 Aug 92, F K Knight (knight@ll.mit.edu)
       allow omission of items or omission of both psym and linestyle, add
         corners keyword to facilitate multi-column legends, improve place-
         ment of symbols and text, add guards for unequal size, 26 Aug 92, FKK
       add linestyle[i]=-1 to suppress a single symbol/line, 27 Aug 92, FKK
       add keyword vectorfont to allow characters in the sym/line column,
         28 Aug 92, FKK
       add /top, /bottom, /left, /right keywords for automatic placement at
         the four corners of the plot window.  The /right keyword forces
         right-to-left printing of menu. 18 Jun 93, FKK
       change default position to data coords and add normal, data, and
         device keywords, 17 Jan 94, FKK
       add /center keyword for positioning, but it is not precise because
         text string lengths cannot be known in advance, 17 Jan 94, FKK
       add interactive positioning with /position keyword, 17 Jan 94, FKK
       allow a legend with just text, no plotting symbols.  This helps in
         simply describing a plot or writing assumptions done, 4 Feb 94, FKK
       added thick, symsize, and clear keyword Feb 96, W. Landsman HSTX
               David Seed, HR Wallingford, d.seed@hrwallingford.co.uk
       allow scalar specification of keywords, Mar 96, W. Landsman HSTX
       added charthick keyword, June 96, W. Landsman HSTX
		DM, allow choosing of color for box

(See src/idl_cvs/legend.pro)


LINTERP

[Previous Routine] [Next Routine] [List of Routines]
 NAME:   
       LINTERP  
 PURPOSE: 
       Linearly interpolate tabulated 1-d data from one grid to a new one.
 EXPLANATION:
       The results of LINTERP are numerically equivalent to the RSI
       INTERPOL() function, but note the followign:
         (1) LINTERP is a procedure rather than a function
         (2) INTERPOL() extrapolates beyond the end points whereas LINTERP
             truncates to the endpoints (or use the MISSING keyword)
         (3) LINTERP (unlike INTERPOL) uses the intrinsic INTERPOLATE function
                 and thus may have a speed advantage

       Use QUADTERP for quadratic interpolation.

 CALLING SEQUENCE:
       LINTERP, Xtab, Ytab, Xint, Yint, [MISSING =, /NoInterp ]   

 INPUT PARAMETERS: 
       Xtab -  Vector containing the current independent variable grid.
               Must be monotonic increasing or decreasing
       Ytab -  Vector containing the current dependent variable values at 
               the XTAB grid points.
       Xint -  Scalar or vector containing the new independent variable grid 
               points for which interpolated value(s) of the dependent 
               variable are sought.

 OUTPUT PARAMETERS:
       Yint  -  Scalar or vector with the interpolated value(s) of the 
               dependent variable at the XINT grid points.
               YINT is double precision if XTAB or YTAB are double,
               otherwise YINT is REAL*4

 OPTIONAL INPUT KEYWORD:
       MISSING - Scalar specifying YINT value(s) to be assigned, when Xint
               value(s) are outside of the range of Xtab.     Default is to
               truncate the out of range YINT value(s) to the nearest value 
               of YTAB.   See the help for the INTERPOLATE function.
       /NoINTERP - If supplied then LINTERP returns the YTAB value(s) 
               associated with the closest XTAB value(s)rather than 
               interpolating.

 EXAMPLE:
       To linearly interpolate from a spectrum wavelength-flux pair
       WAVE, FLUX to another wavelength grid defined as:
       WGRID = [1540., 1541., 1542., 1543., 1544, 1545.]
   
       IDL>  LINTERP, WAVE, FLUX, WGRID, FGRID  

       FGRID will be a 6 element vector containing the values of FLUX 
       linearly interpolated onto the WGRID wavelength scale

 PROCEDURE: 
       Uses TABINV to calculate the effective index of the values
       in Xint in the table Xtab.  The resulting index is used
       with the intrinsic INTERPOLATE function to find the corresponding 
       Yint value in Ytab.  Unless the MISSING keyword is supplied, out
       of range Yint values are truncated to the nearest value of Ytab.

 PROCEDURES CALLED:
       TABINV, ZPARCHECK
 MODIFICATION HISTORY:
       Adapted from the IUE RDAF,  W. Landsman      October, 1988
       Modified to use the new INTERPOLATE function        June, 1992
       Modified to always return REAL*4             October, 1992
       Added MISSING keyword                        August, 1993
       Converted to IDL V5.0   W. Landsman   September 1997
       Added NoInterp keyword  W. Landsman      July 1999

(See src/idl_cvs/linterp.pro)


LISTFROMPERL

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
      listFromPerl
 PURPOSE:
       Called from a Perl Script to list MDSplus data from a Web Page
 CATEGORY:
       WebTools, MDSplus
 MODIFICATION HISTORY:
       14-Jul-04 added parseShotInput for handling inputs

(See src/idl_cvs/listfromperl.pro)


MDSW_NOCH

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       mdsw_noch
 PURPOSE:
       Plot one MDS signal simply (without Crosshairs)
 CATEGORY:
       Example
 CALLING SEQUENCE:
       mdsw_noch
 COMMON BLOCKS:
       mdsw_noch
 NOTES:
       Your display may have to be set to 256 colors to see the crosshairs.
 LIMITATIONS:
	The printers and help file used here only work from UNIX.
	Only one version of this program may be run from a given IDL session.
 MODIFICATION HISTORY:
	11-Feb-99 Using UNSETUP_X rather than SETUP_X
	28-Jan-99 Took out cross-hair routines
	26-Jan-99 Modified for using MDS at PPPL by Bill Davis
       8/29/97 CH_example written by Bill Davis, 

(See src/idl_cvs/mdsw_noch.pro)


MK_HTML_HELP

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

 PURPOSE:
	Given a list of IDL procedure files (.PRO), VMS text library 
       files (.TLB), or directories that contain such files, this procedure 
       generates a file in the HTML format that contains the documentation 
       for those routines that contain a DOC_LIBRARY style documentation 
       template.  The output file is compatible with World Wide Web browsers.

 CATEGORY:
	Help, documentation.

 CALLING SEQUENCE:
	MK_HTML_HELP, Sources, Outfile

 INPUTS:
     Sources:  A string or string array containing the name(s) of the
		.pro or .tlb files (or the names of directories containing 
               such files) for which help is desired.  If a source file is 
               a VMS text library, it must include the .TLB file extension.  
               If a source file is an IDL procedure, it must include the .PRO
               file extension.  All other source files are assumed to be
               directories.
     Outfile:	The name of the output file which will be generated.

 KEYWORDS:
     BY_CATEGORY: if set, will group output by their first Category
     INCLUDE:	set to 'CATEGORY' or 'PURPOSE' to include at top of the file
     TITLE:	If present, a string which supplies the name that
		should appear as the Document Title for the help.
     VERBOSE:	Normally, MK_HTML_HELP does its work silently.
		Setting this keyword to a non-zero value causes the procedure
		to issue informational messages that indicate what it
		is currently doing. !QUIET must be 0 for these messages
               to appear.
     STRICT:   If this keyword is set to a non-zero value, MK_HTML_HELP will 
               adhere strictly to the HTML format by scanning the 
               the document headers for characters that are reserved in 
               HTML (<,>,&,").  These are then converted to the appropriate 
               HTML syntax in the output file. By default, this keyword
               is set to zero (to allow for faster processing).
     EXTENSION: if want to do for files other than .pro files
     STARTHEAD: characters at the beginning of a line which indicate the 
		header start (default = ';+')
     STOPHEAD:  characters at the beginning of a line which indicate the 
		header end (default = ';-')

 EXAMPLE:
     if on Unix:
	% cd directory-where-web-pages-will-be
	   (e.g., /w/nstx.pppl.gov/htdocs/nstx/Software/Programming)

	% rm pro_sources.txt
	% /bin/ls -1 the-directory-with-IDL-code/*.pro > pro_sources.txt
	   (e.g., ./src/idl_cvs)
	% idl
	IDL> sources = READ_LIST('pro_sources.txt')
	IDL> MK_HTML_HELP, sources, 'idl_routines.html', include='purpose',/by_category
	IDL> exit
     This just gives a relative path, but the web link will find it.
     When /BY_CATEGORY is specified, an additional page, e.g., 
     idl_routines_alphabet.html, will be produced as well.

         cp idl_routines.html  pppl_idl_routines.html

 COMMON BLOCKS:
	None.

 SIDE EFFECTS:
	A help file with the name given by the Outfile argument is
	created.

 RESTRICTIONS:
	The following rules must be followed in formatting the .pro
	files that are to be searched.
		(a) The first line of the documentation block contains
		    only the characters ";+", starting in column 1.
               (b) There must be a line which contains the string "NAME:",
                   which is immediately followed (same or next line) by the
                   name of the procedure or function being described in
                   that documentation block.  If this NAME field is not
                   present, the name of the source file will be used.
		(c) Likewise, for organizing by category, after the purpose,
		    The "CATEGORY:" line should follow. If fitting, use one of
		    existing categories as the first category (the only one 
		    sorted on). If less than two routines are in a category,
		    they are listed in the Misc category.
		(d) The last line of the documentation block contains
		    the characters ";-", starting in column 1.
		(e) Every other line in the documentation block contains
		    a ";" in column 1.

       Note that a single .pro file can contain multiple procedures and/or
       functions, each with their own documentation blocks. If it is desired
       to have "invisible" routines in a file, i.e. routines which are only
       for internal use and should not appear in the help file, simply leave
       out the ";+" and ";-" lines in the documentation block for those
       routines.

 MODIFICATION HISTORY:
	04-May-01 Add /BY_CATEGORY switch [BD]
	31-Oct-00 Add link to actual code [BD]
	07-Jun-99 Added Extension keyword [BD]
	01-Apr-99 Allow CATEGORY or PURPOSE to be included in the top of 
		  of the HTML file [Bill Davis]
       July 17, 1995, DD, RSI. Added code to alphabetize the subjects;
               At the end of each description block in the HTML file,
               added a reference to the source .pro file.
       July 13, 1995, Mark Rivers, University of Chicago. Added support for
               multiple source directories and multiple documentation
               headers per .pro file.
       July 5, 1995, DD, RSI. Original version.

(See src/idl_cvs/mk_html_help.pro)


MK_SHOTLIST

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       mk_shotlist
 PURPOSE:
       Parse an input string for shots into an array of shots
 CATEGORY:
       Input, MDSplus
 CALLING SEQUENCE:
       IDL> shotlist = mk_shotlist(input)
 INPUTS:
       input =e.g., 107694 108305 108330-108350
		(108100+20 will search 108100-108120)
	      if a shot number is given as 0, use latest MDSplus shot
 KEYWORD PARAMETERS:
	dupsOK - if set, will not remove duplicate shot numbers
 OUTPUTS:
       opt = returned value                 			out
 COMMON BLOCKS:
       NONE
 EXAMPLES:
	IDL> print,mk_shotlist('112300+3')
	      112300      112301      112302      112303
	IDL> print,mk_shotlist('112300-4')
	      112300      112299      112298      112297      112296
	IDL> print,mk_shotlist('0+3')
	      113862      113863      113864      113865
	IDL> print,mk_shotlist('0-3')
	      113862      113861      113860      113859
	IDL> print,mk_shotlist('112300-112302 112305+2')
	      112300      112301      112302      112305      112306      112307
	IDL> print,mk_shotlist('107694 108305 108330-108332')
	      107694      108305      108330      108331      108332
 NOTES:
       When there are duplicate shots, the list is ordered, and the duplicates 
	removed.
 MODIFICATION HISTORY:
	08-Aug-07 added dupsOK keyword
	21-Aug-06 Allow for blanks around "-" and "+"
       14-Jul-04 Written by Bill Davis, PPPL

(See src/idl_cvs/mk_shotlist.pro)


MPCURVEFIT

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

 AUTHOR:
   Craig B. Markwardt, NASA/GSFC Code 662, Greenbelt, MD 20770
   craigm@lheamail.gsfc.nasa.gov
   UPDATED VERSIONs can be found on my WEB PAGE: 
      http://cow.physics.wisc.edu/~craigm/idl/idl.html

 PURPOSE:
   Perform Levenberg-Marquardt least-squares fit (replaces CURVEFIT)

 MAJOR TOPICS:
   Curve and Surface Fitting

 CALLING SEQUENCE:
   YFIT = MPCURVEFIT(X, Y, WEIGHTS, P, [SIGMA,] FUNCTION_NAME=FUNC, 
                     ITER=iter, ITMAX=itmax, 
                     CHISQ=chisq, NFREE=nfree, DOF=dof, 
                     NFEV=nfev, COVAR=covar, [/NOCOVAR, ] [/NODERIVATIVE, ]
                     FUNCTARGS=functargs, PARINFO=parinfo,
                     FTOL=ftol, XTOL=xtol, GTOL=gtol, TOL=tol,
                     ITERPROC=iterproc, ITERARGS=iterargs,
                     NPRINT=nprint, QUIET=quiet, 
                     ERRMSG=errmsg, STATUS=status)

 DESCRIPTION:

  MPCURVEFIT fits a user-supplied model -- in the form of an IDL
  function -- to a set of user-supplied data.  MPCURVEFIT calls
  MPFIT, the MINPACK-1 least-squares minimizer, to do the main
  work.

  Given the data and their uncertainties, MPCURVEFIT finds the best
  set of model parameters which match the data (in a least-squares
  sense) and returns them in the parameter P.  

  MPCURVEFIT returns the best fit function.
  
  The user must supply the following items:
   - An array of independent variable values ("X").
   - An array of "measured" *dependent* variable values ("Y").
   - An array of weighting values ("WEIGHTS").
   - The name of an IDL function which computes Y given X ("FUNC").
   - Starting guesses for all of the parameters ("P").

  There are very few restrictions placed on X, Y or FUNCT.  Simply
  put, FUNCT must map the "X" values into "Y" values given the
  model parameters.  The "X" values may represent any independent
  variable (not just Cartesian X), and indeed may be multidimensional
  themselves.  For example, in the application of image fitting, X
  may be a 2xN array of image positions.

  MPCURVEFIT carefully avoids passing large arrays where possible to
  improve performance.

  See below for an example of usage.
   
 USER FUNCTION

  The user must define a function which returns the model value.  For
  applications which use finite-difference derivatives -- the default
  -- the user function should be declared in the following way:

    PRO MYFUNCT, X, P, YMOD
     ; The independent variable is X
     ; Parameter values are passed in "P"
     YMOD = ... computed model values at X ...
    END

  The returned array YMOD must have the same dimensions and type as
  the "measured" Y values.

  User functions may also indicate a fatal error condition
  using the ERROR_CODE common block variable, as described
  below under the MPFIT_ERROR common block definition.

  See the discussion under "ANALYTIC DERIVATIVES" and AUTODERIVATIVE
  in MPFIT.PRO if you wish to compute the derivatives for yourself.
  AUTODERIVATIVE is accepted and passed directly to MPFIT.  The user
  function must accept one additional parameter, DP, which contains
  the derivative of the user function with respect to each parameter
  at each data point, as described in MPFIT.PRO.

 CONSTRAINING PARAMETER VALUES WITH THE PARINFO KEYWORD

  The behavior of MPFIT can be modified with respect to each
  parameter to be fitted.  A parameter value can be fixed; simple
  boundary constraints can be imposed; limitations on the parameter
  changes can be imposed; properties of the automatic derivative can
  be modified; and parameters can be tied to one another.

  These properties are governed by the PARINFO structure, which is
  passed as a keyword parameter to MPFIT.

  PARINFO should be an array of structures, one for each parameter.
  Each parameter is associated with one element of the array, in
  numerical order.  The structure can have the following entries
  (none are required):
  
     .VALUE - the starting parameter value (but see the START_PARAMS
              parameter for more information).
  
     .FIXED - a boolean value, whether the parameter is to be held
              fixed or not.  Fixed parameters are not varied by
              MPFIT, but are passed on to MYFUNCT for evaluation.
  
     .LIMITED - a two-element boolean array.  If the first/second
                element is set, then the parameter is bounded on the
                lower/upper side.  A parameter can be bounded on both
                sides.  Both LIMITED and LIMITS must be given
                together.
  
     .LIMITS - a two-element float or double array.  Gives the
               parameter limits on the lower and upper sides,
               respectively.  Zero, one or two of these values can be
               set, depending on the values of LIMITED.  Both LIMITED
               and LIMITS must be given together.
  
     .PARNAME - a string, giving the name of the parameter.  The
                fitting code of MPFIT does not use this tag in any
                way.  However, the default ITERPROC will print the
                parameter name if available.
  
     .STEP - the step size to be used in calculating the numerical
             derivatives.  If set to zero, then the step size is
             computed automatically.  Ignored when AUTODERIVATIVE=0.
             This value is superceded by the RELSTEP value.

     .RELSTEP - the *relative* step size to be used in calculating
                the numerical derivatives.  This number is the
                fractional size of the step, compared to the
                parameter value.  This value supercedes the STEP
                setting.  If the parameter is zero, then a default
                step size is chosen.

     .MPSIDE - the sidedness of the finite difference when computing
               numerical derivatives.  This field can take four
               values:

                  0 - one-sided derivative computed automatically
                  1 - one-sided derivative (f(x+h) - f(x)  )/h
                 -1 - one-sided derivative (f(x)   - f(x-h))/h
                  2 - two-sided derivative (f(x+h) - f(x-h))/(2*h)

              Where H is the STEP parameter described above.  The
              "automatic" one-sided derivative method will chose a
              direction for the finite difference which does not
              violate any constraints.  The other methods do not
              perform this check.  The two-sided method is in
              principle more precise, but requires twice as many
              function evaluations.  Default: 0.

     .MPMAXSTEP - the maximum change to be made in the parameter
                  value.  During the fitting process, the parameter
                  will never be changed by more than this value in
                  one iteration.

                  A value of 0 indicates no maximum.  Default: 0.
  
     .TIED - a string expression which "ties" the parameter to other
             free or fixed parameters.  Any expression involving
             constants and the parameter array P are permitted.
             Example: if parameter 2 is always to be twice parameter
             1 then use the following: parinfo(2).tied = '2 * P(1)'.
             Since they are totally constrained, tied parameters are
             considered to be fixed; no errors are computed for them.
             [ NOTE: the PARNAME can't be used in expressions. ]

     .MPPRINT - if set to 1, then the default ITERPROC will print the
                parameter value.  If set to 0, the parameter value
                will not be printed.  This tag can be used to
                selectively print only a few parameter values out of
                many.  Default: 1 (all parameters printed)

  
  Future modifications to the PARINFO structure, if any, will involve
  adding structure tags beginning with the two letters "MP".
  Therefore programmers are urged to avoid using tags starting with
  the same letters; otherwise they are free to include their own
  fields within the PARINFO structure, and they will be ignored.
  
  PARINFO Example:
  parinfo = replicate({value:0.D, fixed:0, limited:[0,0], $
                       limits:[0.D,0]}, 5)
  parinfo(0).fixed = 1
  parinfo(4).limited(0) = 1
  parinfo(4).limits(0)  = 50.D
  parinfo(*).value = [5.7D, 2.2, 500., 1.5, 2000.]
  
  A total of 5 parameters, with starting values of 5.7,
  2.2, 500, 1.5, and 2000 are given.  The first parameter
  is fixed at a value of 5.7, and the last parameter is
  constrained to be above 50.

 INPUTS:
   X - Array of independent variable values.

   Y - Array of "measured" dependent variable values.  Y should have
       the same data type as X.  The function FUNCT should map
       X->Y.

   WEIGHTS - Array of weights to be used in calculating the
             chi-squared value.  If WEIGHTS is specified then the ERR
             parameter is ignored.  The chi-squared value is computed
             as follows:

                CHISQ = TOTAL( (Y-FUNCT(X,P))^2 * ABS(WEIGHTS) )

             Here are common values of WEIGHTS:

                1D/ERR^2 - Normal weighting (ERR is the measurement error)
                1D/Y     - Poisson weighting (counting statistics)
                1D       - Unweighted

   P - An array of starting values for each of the parameters of the
       model.  The number of parameters should be fewer than the
       number of measurements.  Also, the parameters should have the
       same data type as the measurements (double is preferred).

       Upon successful completion the new parameter values are
       returned in P.

       If both START_PARAMS and PARINFO are passed, then the starting
       *value* is taken from START_PARAMS, but the *constraints* are
       taken from PARINFO.
 
   SIGMA - The formal 1-sigma errors in each parameter, computed from
           the covariance matrix.  If a parameter is held fixed, or
           if it touches a boundary, then the error is reported as
           zero.

           If the fit is unweighted (i.e. no errors were given, or
           the weights were uniformly set to unity), then SIGMA will
           probably not represent the true parameter uncertainties.

           *If* you can assume that the true reduced chi-squared
           value is unity -- meaning that the fit is implicitly
           assumed to be of good quality -- then the estimated
           parameter uncertainties can be computed by scaling SIGMA
           by the measured chi-squared value.

              DOF     = N_ELEMENTS(X) - N_ELEMENTS(P) ; deg of freedom
              CSIGMA  = SIGMA * SQRT(CHISQ / DOF)     ; scaled uncertainties

 RETURNS:

   Returns the array containing the best-fitting function.

 KEYWORD PARAMETERS:

   CHISQ - the value of the summed, squared, weighted residuals for
           the returned parameter values, i.e. the chi-square value.

   COVAR - the covariance matrix for the set of parameters returned
           by MPFIT.  The matrix is NxN where N is the number of
           parameters.  The square root of the diagonal elements
           gives the formal 1-sigma statistical errors on the
           parameters IF errors were treated "properly" in MYFUNC.
           Parameter errors are also returned in PERROR.

           To compute the correlation matrix, PCOR, use this:
           IDL> PCOR = COV * 0
           IDL> FOR i = 0, n-1 DO FOR j = 0, n-1 DO $
                PCOR(i,j) = COV(i,j)/sqrt(COV(i,i)*COV(j,j))

           If NOCOVAR is set or MPFIT terminated abnormally, then
           COVAR is set to a scalar with value !VALUES.D_NAN.

   DOF - number of degrees of freedom, computed as
             DOF = N_ELEMENTS(DEVIATES) - NFREE
         Note that this doesn't account for pegged parameters (see
         NPEGGED).

   ERRMSG - a string error or warning message is returned.

   FTOL - a nonnegative input variable. Termination occurs when both
          the actual and predicted relative reductions in the sum of
          squares are at most FTOL (and STATUS is accordingly set to
          1 or 3).  Therefore, FTOL measures the relative error
          desired in the sum of squares.  Default: 1D-10

   FUNCTION_NAME - a scalar string containing the name of an IDL
                   procedure to compute the user model values, as
                   described above in the "USER MODEL" section.

   FUNCTARGS - A structure which contains the parameters to be passed
               to the user-supplied function specified by FUNCT via
               the _EXTRA mechanism.  This is the way you can pass
               additional data to your user-supplied function without
               using common blocks.

               By default, no extra parameters are passed to the
               user-supplied function.

   GTOL - a nonnegative input variable. Termination occurs when the
          cosine of the angle between fvec and any column of the
          jacobian is at most GTOL in absolute value (and STATUS is
          accordingly set to 4). Therefore, GTOL measures the
          orthogonality desired between the function vector and the
          columns of the jacobian.  Default: 1D-10

   ITER - the number of iterations completed.

   ITERARGS - The keyword arguments to be passed to ITERPROC via the
              _EXTRA mechanism.  This should be a structure, and is
              similar in operation to FUNCTARGS.
              Default: no arguments are passed.

   ITERPROC - The name of a procedure to be called upon each NPRINT
              iteration of the MPFIT routine.  It should be declared
              in the following way:

              PRO ITERPROC, FUNCT, p, iter, fnorm, FUNCTARGS=fcnargs, $
                PARINFO=parinfo, QUIET=quiet, ...
                ; perform custom iteration update
              END
         
              ITERPROC must either accept all three keyword
              parameters (FUNCTARGS, PARINFO and QUIET), or at least
              accept them via the _EXTRA keyword.
          
              FUNCT is the user-supplied function to be minimized,
              P is the current set of model parameters, ITER is the
              iteration number, and FUNCTARGS are the arguments to be
              passed to FUNCT.  FNORM should be the
              chi-squared value.  QUIET is set when no textual output
              should be printed.  See below for documentation of
              PARINFO.

              In implementation, ITERPROC can perform updates to the
              terminal or graphical user interface, to provide
              feedback while the fit proceeds.  If the fit is to be
              stopped for any reason, then ITERPROC should set the
              common block variable ERROR_CODE to negative value (see
              MPFIT_ERROR common block below).  In principle,
              ITERPROC should probably not modify the parameter
              values, because it may interfere with the algorithm's
              stability.  In practice it is allowed.

              Default: an internal routine is used to print the
                       parameter values.

   ITMAX - The maximum number of iterations to perform.  If the
             number is exceeded, then the STATUS value is set to 5
             and MPFIT returns.
             Default: 200 iterations

   NFEV - the number of FUNCT function evaluations performed.

   NFREE - the number of free parameters in the fit.  This includes
           parameters which are not FIXED and not TIED, but it does
           include parameters which are pegged at LIMITS.

   NOCOVAR - set this keyword to prevent the calculation of the
             covariance matrix before returning (see COVAR)

   NODERIVATIVE - if set, then the user function will not be queried
                  for analytical derivatives, and instead the
                  derivatives will be computed by finite differences
                  (and according to the PARINFO derivative settings;
                  see above for a description).

   NPRINT - The frequency with which ITERPROC is called.  A value of
            1 indicates that ITERPROC is called with every iteration,
            while 2 indicates every other iteration, etc.  Note that
            several Levenberg-Marquardt attempts can be made in a
            single iteration.
            Default value: 1

   PARINFO - Provides a mechanism for more sophisticated constraints
             to be placed on parameter values.  When PARINFO is not
             passed, then it is assumed that all parameters are free
             and unconstrained.  Values in PARINFO are never 
             modified during a call to MPFIT.

             See description above for the structure of PARINFO.

             Default value:  all parameters are free and unconstrained.

   QUIET - set this keyword when no textual output should be printed
           by MPFIT

   STATUS - an integer status code is returned.  All values other
            than zero can represent success.  It can have one of the
            following values:

	   0  improper input parameters.
         
	   1  both actual and predicted relative reductions
	      in the sum of squares are at most FTOL.
         
	   2  relative error between two consecutive iterates
	      is at most XTOL
         
	   3  conditions for STATUS = 1 and STATUS = 2 both hold.
         
	   4  the cosine of the angle between fvec and any
	      column of the jacobian is at most GTOL in
	      absolute value.
         
	   5  the maximum number of iterations has been reached
         
	   6  FTOL is too small. no further reduction in
	      the sum of squares is possible.
         
	   7  XTOL is too small. no further improvement in
	      the approximate solution x is possible.
         
	   8  GTOL is too small. fvec is orthogonal to the
	      columns of the jacobian to machine precision.

   TOL - synonym for FTOL.  Use FTOL instead.

   XTOL - a nonnegative input variable. Termination occurs when the
          relative error between two consecutive iterates is at most
          XTOL (and STATUS is accordingly set to 2 or 3).  Therefore,
          XTOL measures the relative error desired in the approximate
          solution.  Default: 1D-10

   YERROR - upon return, the root-mean-square variance of the
            residuals.


 EXAMPLE:

   ; First, generate some synthetic data
   npts = 200
   x  = dindgen(npts) * 0.1 - 10.                  ; Independent variable 
   yi = gauss1(x, [2.2D, 1.4, 3000.])              ; "Ideal" Y variable
   y  = yi + randomn(seed, npts) * sqrt(1000. + yi); Measured, w/ noise
   sy = sqrt(1000.D + y)                           ; Poisson errors

   ; Now fit a Gaussian to see how well we can recover
   p0 = [1.D, 1., 1000.]                           ; Initial guess
   yfit = mpcurvefit(x, y, 1/sy^2, p0, $           ; Fit a function
                     FUNCTION_NAME='GAUSS1P',/autoderivative)
   print, p

   Generates a synthetic data set with a Gaussian peak, and Poisson
   statistical uncertainty.  Then the same function is fitted to the
   data to see how close we can get.  GAUSS1 and GAUSS1P are
   available from the same web page.


 COMMON BLOCKS:

   COMMON MPFIT_ERROR, ERROR_CODE

     User routines may stop the fitting process at any time by
     setting an error condition.  This condition may be set in either
     the user's model computation routine (MYFUNCT), or in the
     iteration procedure (ITERPROC).

     To stop the fitting, the above common block must be declared,
     and ERROR_CODE must be set to a negative number.  After the user
     procedure or function returns, MPFIT checks the value of this
     common block variable and exits immediately if the error
     condition has been set.  By default the value of ERROR_CODE is
     zero, indicating a successful function/procedure call.

 REFERENCES:

   MINPACK-1, Jorge More', available from netlib (www.netlib.org).
   "Optimization Software Guide," Jorge More' and Stephen Wright, 
     SIAM, *Frontiers in Applied Mathematics*, Number 14.

 MODIFICATION HISTORY:
   Translated from MPFITFUN, 25 Sep 1999, CM
   Alphabetized documented keywords, 02 Oct 1999, CM
   Added QUERY keyword and query checking of MPFIT, 29 Oct 1999, CM
   Check to be sure that X and Y are present, 02 Nov 1999, CM
   Documented SIGMA for unweighted fits, 03 Nov 1999, CM
   Changed to ERROR_CODE for error condition, 28 Jan 2000, CM
   Copying permission terms have been liberalized, 26 Mar 2000, CM
   Propagated improvements from MPFIT, 17 Dec 2000, CM
   Corrected behavior of NODERIVATIVE, 13 May 2002, CM
   Documented RELSTEP field of PARINFO (!!), CM, 25 Oct 2002
   Make more consistent with comparable IDL routines, 30 Jun 2003, CM
   Minor documentation adjustment, 03 Feb 2004, CM
   Fix error in documentation, 26 Aug 2005, CM
   Convert to IDL 5 array syntax (!), 16 Jul 2006, CM

  $Id: mpcurvefit.pro,v 2.2 2006/09/28 13:39:25 bdavis Exp $

(See src/idl_cvs/mpcurvefit.pro)


MPFIT2DFUN

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

 AUTHOR:
   Craig B. Markwardt, NASA/GSFC Code 662, Greenbelt, MD 20770
   craigm@lheamail.gsfc.nasa.gov
   UPDATED VERSIONs can be found on my WEB PAGE: 
      http://cow.physics.wisc.edu/~craigm/idl/idl.html

 PURPOSE:
   Perform Levenberg-Marquardt least-squares fit to a 2-D IDL function

 MAJOR TOPICS:
   Curve and Surface Fitting

 CALLING SEQUENCE:
   parms = MPFIT2DFUN(MYFUNCT, X, Y, Z, ERR, start_parms, ...)

 DESCRIPTION:

  MPFIT2DFUN fits a user-supplied model -- in the form of an IDL
  function -- to a set of user-supplied data.  MPFIT2DFUN calls
  MPFIT, the MINPACK-1 least-squares minimizer, to do the main
  work.  MPFIT2DFUN is a specialized version for two-dimensional 
  data.

  Given the data and their uncertainties, MPFIT2DFUN finds the best set
  of model parameters which match the data (in a least-squares
  sense) and returns them in an array.
  
  The user must supply the following items:
   - Two arrays of independent variable values ("X", "Y").
   - An array of "measured" *dependent* variable values ("Z").
   - An array of "measured" 1-sigma uncertainty values ("ERR").
   - The name of an IDL function which computes Z given (X,Y) ("MYFUNCT").
   - Starting guesses for all of the parameters ("START_PARAMS").

  There are very few restrictions placed on X, Y, Z, or MYFUNCT.
  Simply put, MYFUNCT must map the (X,Y) values into Z values given
  the model parameters.  The (X,Y) values are usually the independent
  X and Y coordinate positions in the two dimensional plane, but need
  not be.

  MPFIT2DFUN carefully avoids passing large arrays where possible to
  improve performance.

  See below for an example of usage.
   
 USER FUNCTION

  The user must define a function which returns the model value.  For
  applications which use finite-difference derivatives -- the default
  -- the user function should be declared in the following way:

    FUNCTION MYFUNCT, X, Y, P
     ; The independent variables are X and Y
     ; Parameter values are passed in "P"
     ZMOD = ... computed model values at (X,Y) ...
     return, ZMOD
    END

  The returned array YMOD must have the same dimensions and type as
  the "measured" Z values.

  User functions may also indicate a fatal error condition
  using the ERROR_CODE common block variable, as described
  below under the MPFIT_ERROR common block definition.

  See the discussion under "ANALYTIC DERIVATIVES" and AUTODERIVATIVE
  in MPFIT.PRO if you wish to compute the derivatives for yourself.
  AUTODERIVATIVE is accepted and passed directly to MPFIT.  The user
  function must accept one additional parameter, DP, which contains
  the derivative of the user function with respect to each parameter
  at each data point, as described in MPFIT.PRO.

 CREATING APPROPRIATELY DIMENSIONED INDEPENDENT VARIABLES

  The user must supply appropriate independent variables to
  MPFIT2DFUN.  For image fitting applications, this variable should
  be two-dimensional *arrays* describing the X and Y positions of
  every *pixel*.  [ Thus any two dimensional sampling is permitted,
  including irregular sampling. ]
  
  If the sampling is regular, then the x coordinates are the same for
  each row, and the y coordinates are the same for each column.  Call
  the x-row and y-column coordinates XR and YC respectively.  You can
  then compute X and Y as follows:
  
      X = XR # (YC*0 + 1)             eqn. 1
      Y = (XR*0 + 1) # YC             eqn. 2
  
  For example, if XR and YC have the following values:
  
    XR = [  1, 2, 3, 4, 5,]  ;; X positions of one row of pixels
    YC = [ 15,16,17 ]        ;; Y positions of one column of
                                pixels
  
  Then using equations 1 and 2 above will give these values to X and
  Y:
  
     X :  1  2  3  4  5       ;; X positions of all pixels
          1  2  3  4  5
          1  2  3  4  5
  
     Y : 15 15 15 15 15       ;; Y positions of all pixels
         16 16 16 16 16
         17 17 17 17 17
  
  Using the above technique is suggested, but *not* required.  You
  can do anything you wish with the X and Y values.  This technique
  only makes it easier to compute your model function values.

 CONSTRAINING PARAMETER VALUES WITH THE PARINFO KEYWORD

  The behavior of MPFIT can be modified with respect to each
  parameter to be fitted.  A parameter value can be fixed; simple
  boundary constraints can be imposed; limitations on the parameter
  changes can be imposed; properties of the automatic derivative can
  be modified; and parameters can be tied to one another.

  These properties are governed by the PARINFO structure, which is
  passed as a keyword parameter to MPFIT.

  PARINFO should be an array of structures, one for each parameter.
  Each parameter is associated with one element of the array, in
  numerical order.  The structure can have the following entries
  (none are required):
  
     .VALUE - the starting parameter value (but see the START_PARAMS
              parameter for more information).
  
     .FIXED - a boolean value, whether the parameter is to be held
              fixed or not.  Fixed parameters are not varied by
              MPFIT, but are passed on to MYFUNCT for evaluation.
  
     .LIMITED - a two-element boolean array.  If the first/second
                element is set, then the parameter is bounded on the
                lower/upper side.  A parameter can be bounded on both
                sides.  Both LIMITED and LIMITS must be given
                together.
  
     .LIMITS - a two-element float or double array.  Gives the
               parameter limits on the lower and upper sides,
               respectively.  Zero, one or two of these values can be
               set, depending on the values of LIMITED.  Both LIMITED
               and LIMITS must be given together.
  
     .PARNAME - a string, giving the name of the parameter.  The
                fitting code of MPFIT does not use this tag in any
                way.  However, the default ITERPROC will print the
                parameter name if available.
  
     .STEP - the step size to be used in calculating the numerical
             derivatives.  If set to zero, then the step size is
             computed automatically.  Ignored when AUTODERIVATIVE=0.
             This value is superceded by the RELSTEP value.

     .RELSTEP - the *relative* step size to be used in calculating
                the numerical derivatives.  This number is the
                fractional size of the step, compared to the
                parameter value.  This value supercedes the STEP
                setting.  If the parameter is zero, then a default
                step size is chosen.

     .MPSIDE - the sidedness of the finite difference when computing
               numerical derivatives.  This field can take four
               values:

                  0 - one-sided derivative computed automatically
                  1 - one-sided derivative (f(x+h) - f(x)  )/h
                 -1 - one-sided derivative (f(x)   - f(x-h))/h
                  2 - two-sided derivative (f(x+h) - f(x-h))/(2*h)

              Where H is the STEP parameter described above.  The
              "automatic" one-sided derivative method will chose a
              direction for the finite difference which does not
              violate any constraints.  The other methods do not
              perform this check.  The two-sided method is in
              principle more precise, but requires twice as many
              function evaluations.  Default: 0.

     .MPMINSTEP - the minimum change to be made in the parameter
                  value.  During the fitting process, the parameter
                  will be changed by multiples of this value.  The
                  actual step is computed as:

                     DELTA1 = MPMINSTEP*ROUND(DELTA0/MPMINSTEP)

                  where DELTA0 and DELTA1 are the estimated parameter
                  changes before and after this constraint is
                  applied.  Note that this constraint should be used
                  with care since it may cause non-converging,
                  oscillating solutions.

                  A value of 0 indicates no minimum.  Default: 0.

     .MPMAXSTEP - the maximum change to be made in the parameter
                  value.  During the fitting process, the parameter
                  will never be changed by more than this value.

                  A value of 0 indicates no maximum.  Default: 0.
  
     .TIED - a string expression which "ties" the parameter to other
             free or fixed parameters.  Any expression involving
             constants and the parameter array P are permitted.
             Example: if parameter 2 is always to be twice parameter
             1 then use the following: parinfo[2].tied = '2 * P[1]'.
             Since they are totally constrained, tied parameters are
             considered to be fixed; no errors are computed for them.
             [ NOTE: the PARNAME can't be used in expressions. ]
  
  Future modifications to the PARINFO structure, if any, will involve
  adding structure tags beginning with the two letters "MP".
  Therefore programmers are urged to avoid using tags starting with
  the same letters; otherwise they are free to include their own
  fields within the PARINFO structure, and they will be ignored.
  
  PARINFO Example:
  parinfo = replicate({value:0.D, fixed:0, limited:[0,0], $
                       limits:[0.D,0]}, 5)
  parinfo[0].fixed = 1
  parinfo[4].limited(0) = 1
  parinfo[4].limits(0)  = 50.D
  parinfo[*].value = [5.7D, 2.2, 500., 1.5, 2000.]
  
  A total of 5 parameters, with starting values of 5.7,
  2.2, 500, 1.5, and 2000 are given.  The first parameter
  is fixed at a value of 5.7, and the last parameter is
  constrained to be above 50.

 INPUTS:
   MYFUNCT - a string variable containing the name of an IDL
             function.  This function computes the "model" Z values
             given the X,Y values and model parameters, as described above.

   X - Array of "X" independent variable values, as described above.
       These values are passed directly to the fitting function
       unmodified.

   Y - Array of "Y" independent variable values, as described
       above. X and Y should have the same data type.

   Z - Array of "measured" dependent variable values.  Z should have
       the same data type as X and Y.  The function MYFUNCT should
       map (X,Y)->Z.

   ERR - Array of "measured" 1-sigma uncertainties.  ERR should have
         the same data type as Z.  ERR is ignored if the WEIGHTS
         keyword is specified.

   START_PARAMS - An array of starting values for each of the
                  parameters of the model.  The number of parameters
                  should be fewer than the number of measurements.
                  Also, the parameters should have the same data type
                  as the measurements (double is preferred).

                  This parameter is optional if the PARINFO keyword
                  is used (see MPFIT).  The PARINFO keyword provides
                  a mechanism to fix or constrain individual
                  parameters.  If both START_PARAMS and PARINFO are
                  passed, then the starting *value* is taken from
                  START_PARAMS, but the *constraints* are taken from
                  PARINFO.
 
 RETURNS:

   Returns the array of best-fit parameters.

 KEYWORD PARAMETERS:

   BESTNORM - the value of the summed, squared, weighted residuals
              for the returned parameter values, i.e. the chi-square value.

   COVAR - the covariance matrix for the set of parameters returned
           by MPFIT.  The matrix is NxN where N is the number of
           parameters.  The square root of the diagonal elements
           gives the formal 1-sigma statistical errors on the
           parameters IF errors were treated "properly" in MYFUNC.
           Parameter errors are also returned in PERROR.

           To compute the correlation matrix, PCOR, use this:
           IDL> PCOR = COV * 0
           IDL> FOR i = 0, n-1 DO FOR j = 0, n-1 DO $
                PCOR[i,j] = COV[i,j]/sqrt(COV[i,i]*COV[j,j])

           If NOCOVAR is set or MPFIT terminated abnormally, then
           COVAR is set to a scalar with value !VALUES.D_NAN.

   DOF - number of degrees of freedom, computed as
             DOF = N_ELEMENTS(DEVIATES) - NFREE
         Note that this doesn't account for pegged parameters (see
         NPEGGED).

   ERRMSG - a string error or warning message is returned.

   FTOL - a nonnegative input variable. Termination occurs when both
          the actual and predicted relative reductions in the sum of
          squares are at most FTOL (and STATUS is accordingly set to
          1 or 3).  Therefore, FTOL measures the relative error
          desired in the sum of squares.  Default: 1D-10

   FUNCTARGS - A structure which contains the parameters to be passed
               to the user-supplied function specified by MYFUNCT via
               the _EXTRA mechanism.  This is the way you can pass
               additional data to your user-supplied function without
               using common blocks.

               By default, no extra parameters are passed to the
               user-supplied function.

   GTOL - a nonnegative input variable. Termination occurs when the
          cosine of the angle between fvec and any column of the
          jacobian is at most GTOL in absolute value (and STATUS is
          accordingly set to 4). Therefore, GTOL measures the
          orthogonality desired between the function vector and the
          columns of the jacobian.  Default: 1D-10

   ITERARGS - The keyword arguments to be passed to ITERPROC via the
              _EXTRA mechanism.  This should be a structure, and is
              similar in operation to FUNCTARGS.
              Default: no arguments are passed.

   ITERPROC - The name of a procedure to be called upon each NPRINT
              iteration of the MPFIT routine.  It should be declared
              in the following way:

              PRO ITERPROC, MYFUNCT, p, iter, fnorm, FUNCTARGS=fcnargs, $
                PARINFO=parinfo, QUIET=quiet, ...
                ; perform custom iteration update
              END
         
              ITERPROC must either accept all three keyword
              parameters (FUNCTARGS, PARINFO and QUIET), or at least
              accept them via the _EXTRA keyword.
          
              MYFUNCT is the user-supplied function to be minimized,
              P is the current set of model parameters, ITER is the
              iteration number, and FUNCTARGS are the arguments to be
              passed to MYFUNCT.  FNORM should be the
              chi-squared value.  QUIET is set when no textual output
              should be printed.  See below for documentation of
              PARINFO.

              In implementation, ITERPROC can perform updates to the
              terminal or graphical user interface, to provide
              feedback while the fit proceeds.  If the fit is to be
              stopped for any reason, then ITERPROC should set the
              common block variable ERROR_CODE to negative value (see
              MPFIT_ERROR common block below).  In principle,
              ITERPROC should probably not modify the parameter
              values, because it may interfere with the algorithm's
              stability.  In practice it is allowed.

              Default: an internal routine is used to print the
                       parameter values.

   MAXITER - The maximum number of iterations to perform.  If the
             number is exceeded, then the STATUS value is set to 5
             and MPFIT returns.
             Default: 200 iterations

   NFEV - the number of MYFUNCT function evaluations performed.

   NITER - the number of iterations completed.

   NOCOVAR - set this keyword to prevent the calculation of the
             covariance matrix before returning (see COVAR)

   NPRINT - The frequency with which ITERPROC is called.  A value of
            1 indicates that ITERPROC is called with every iteration,
            while 2 indicates every other iteration, etc.  Note that
            several Levenberg-Marquardt attempts can be made in a
            single iteration.
            Default value: 1

   PARINFO - Provides a mechanism for more sophisticated constraints
             to be placed on parameter values.  When PARINFO is not
             passed, then it is assumed that all parameters are free
             and unconstrained.  Values in PARINFO are never 
             modified during a call to MPFIT.

             See description above for the structure of PARINFO.

             Default value:  all parameters are free and unconstrained.

   PERROR - The formal 1-sigma errors in each parameter, computed
            from the covariance matrix.  If a parameter is held
            fixed, or if it touches a boundary, then the error is
            reported as zero.

            If the fit is unweighted (i.e. no errors were given, or
            the weights were uniformly set to unity), then PERROR
            will probably not represent the true parameter
            uncertainties.  *If* you can assume that the true reduced
            chi-squared value is unity -- meaning that the fit is
            implicitly assumed to be of good quality -- then the
            estimated parameter uncertainties can be computed by
            scaling PERROR by the measured chi-squared value.

              DOF     = N_ELEMENTS(Z) - N_ELEMENTS(PARMS) ; deg of freedom
              PCERROR = PERROR * SQRT(BESTNORM / DOF)   ; scaled uncertainties

   QUIET - set this keyword when no textual output should be printed
           by MPFIT

   STATUS - an integer status code is returned.  All values other
            than zero can represent success.  It can have one of the
            following values:

	   0  improper input parameters.
         
	   1  both actual and predicted relative reductions
	      in the sum of squares are at most FTOL.
         
	   2  relative error between two consecutive iterates
	      is at most XTOL
         
	   3  conditions for STATUS = 1 and STATUS = 2 both hold.
         
	   4  the cosine of the angle between fvec and any
	      column of the jacobian is at most GTOL in
	      absolute value.
         
	   5  the maximum number of iterations has been reached
         
	   6  FTOL is too small. no further reduction in
	      the sum of squares is possible.
         
	   7  XTOL is too small. no further improvement in
	      the approximate solution x is possible.
         
	   8  GTOL is too small. fvec is orthogonal to the
	      columns of the jacobian to machine precision.

   WEIGHTS - Array of weights to be used in calculating the
             chi-squared value.  If WEIGHTS is specified then the ERR
             parameter is ignored.  The chi-squared value is computed
             as follows:

                CHISQ = TOTAL( (Z-MYFUNCT(X,Y,P))^2 * ABS(WEIGHTS) )

             Here are common values of WEIGHTS:

                1D/ERR^2 - Normal weighting (ERR is the measurement error)
                1D/Z     - Poisson weighting (counting statistics)
                1D       - Unweighted

   XTOL - a nonnegative input variable. Termination occurs when the
          relative error between two consecutive iterates is at most
          XTOL (and STATUS is accordingly set to 2 or 3).  Therefore,
          XTOL measures the relative error desired in the approximate
          solution.  Default: 1D-10

   YFIT - the best-fit model function, as returned by MYFUNCT.

 EXAMPLE:

   p  = [2.2D, -0.7D, 1.4D, 3000.D]
   x  = (dindgen(200)*0.1 - 10.) # (dblarr(200) + 1)
   y  = (dblarr(200) + 1) # (dindgen(200)*0.1 - 10.)
   zi = gauss2(x, y, p)
   sz = sqrt(zi>1)
   z  = zi + randomn(seed, 200, 200) * sz

   p0 = [0D, 0D, 1D, 10D]
   p = mpfit2dfun('GAUSS2', x, y, z, sz, p0)
   
   Generates a synthetic data set with a Gaussian peak, and Poisson
   statistical uncertainty.  Then the same function (but different
   starting parameters) is fitted to the data to see how close we can
   get.

   It is especially worthy to notice that the X and Y values are
   created as full images, so that a coordinate is attached to each
   pixel independently.  This is the format that GAUSS2 accepts, and
   the easiest for you to use in your own functions.


 COMMON BLOCKS:

   COMMON MPFIT_ERROR, ERROR_CODE

     User routines may stop the fitting process at any time by
     setting an error condition.  This condition may be set in either
     the user's model computation routine (MYFUNCT), or in the
     iteration procedure (ITERPROC).

     To stop the fitting, the above common block must be declared,
     and ERROR_CODE must be set to a negative number.  After the user
     procedure or function returns, MPFIT checks the value of this
     common block variable and exits immediately if the error
     condition has been set.  By default the value of ERROR_CODE is
     zero, indicating a successful function/procedure call.


 REFERENCES:

   MINPACK-1, Jorge More', available from netlib (www.netlib.org).
   "Optimization Software Guide," Jorge More' and Stephen Wright, 
     SIAM, *Frontiers in Applied Mathematics*, Number 14.

 MODIFICATION HISTORY:
   Written, transformed from MPFITFUN, 26 Sep 1999, CM
   Alphabetized documented keywords, 02 Oct 1999, CM
   Added example, 02 Oct 1999, CM
   Tried to clarify definitions of X and Y, 29 Oct 1999, CM
   Added QUERY keyword and query checking of MPFIT, 29 Oct 1999, CM
   Check to be sure that X, Y and Z are present, 02 Nov 1999, CM
   Documented PERROR for unweighted fits, 03 Nov 1999, CM
   Changed to ERROR_CODE for error condition, 28 Jan 2000, CM
   Copying permission terms have been liberalized, 26 Mar 2000, CM
   Propagated improvements from MPFIT, 17 Dec 2000, CM
   Documented RELSTEP field of PARINFO (!!), CM, 25 Oct 2002
   Add DOF keyword to return degrees of freedom, CM, 23 June 2003
   Minor documentation adjustment, 03 Feb 2004, CM
   Fix the example to prevent zero errorbars, 28 Mar 2005, CM
   Defend against users supplying strangely dimensioned X and Y, 29
     Jun 2005, CM
   Convert to IDL 5 array syntax (!), 16 Jul 2006, CM

  $Id: mpfit2dfun.pro,v 2.1 2006/09/28 15:40:24 bdavis Exp $

(See src/idl_cvs/mpfit2dfun.pro)


MPFIT2DPEAK

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

 AUTHOR:
   Craig B. Markwardt, NASA/GSFC Code 662, Greenbelt, MD 20770
   craigm@lheamail.gsfc.nasa.gov
   UPDATED VERSIONs can be found on my WEB PAGE: 
      http://cow.physics.wisc.edu/~craigm/idl/idl.html

 PURPOSE:
   Fit a gaussian, lorentzian or Moffat model to data

 MAJOR TOPICS:
   Curve and Surface Fitting

 CALLING SEQUENCE:
   yfit = MPFIT2DPEAK(Z, A [, X, Y, /TILT ...] )

 DESCRIPTION:

   MPFIT2DPEAK fits a gaussian, lorentzian or Moffat model using the
   non-linear least squares fitter MPFIT.  MPFIT2DPEAK is meant to be
   a drop-in replacement for IDL's GAUSS2DFIT function (and requires
   MPFIT and MPFIT2DFUN).

   The choice of the fitting function is determined by the keywords
   GAUSSIAN, LORENTZIAN and MOFFAT.  By default the gaussian model
   function is used.  [ The Moffat function is a modified Lorentzian
   with variable power law index. ]  The two-dimensional peak has
   independent semimajor and semiminor axes, with an optional
   rotation term activated by setting the TILT keyword.  The baseline
   is assumed to be a constant.

      GAUSSIAN      A[0] + A[1]*exp(-0.5*u)
      LORENTZIAN    A[0] + A[1]/(u + 1)
      MOFFAT        A[0] + A[1]/(u + 1)^A[7]

      u = ( (x-A[4])/A[2] )^2 + ( (y-A[5])/A[3] )^2

         where x and y are cartesian coordinates in rotated
         coordinate system if TILT keyword is set.

   The returned parameter array elements have the following meanings:

      A[0]   Constant baseline level
      A[1]   Peak value
      A[2]   Peak half-width (x) -- gaussian sigma or half-width at half-max
      A[3]   Peak half-width (y) -- gaussian sigma or half-width at half-max
      A[4]   Peak centroid (x)
      A[5]   Peak centroid (y)
      A[6]   Rotation angle (radians) if TILT keyword set
      A[7]   Moffat power law index if MOFFAT keyword set

   By default the initial starting values for the parameters A are
   estimated from the data.  However, explicit starting values can be
   supplied using the ESTIMATES keyword.  Also, error or weighting
   values can optionally be provided; otherwise the fit is
   unweighted.

 RESTRICTIONS:

   If no starting parameter ESTIMATES are provided, then MPFIT2DPEAK
   attempts to estimate them from the data.  This is not a perfect
   science; however, the author believes that the technique
   implemented here is more robust than the one used in IDL's
   GAUSS2DFIT.  The author has tested cases of strong peaks, noisy
   peaks and broad peaks, all with success.


 INPUTS:

   Z - Two dimensional array of "measured" dependent variable values.
       Z should be of the same type and dimension as (X # Y).

   X - Optional vector of x positions for a single row of Z.

          X[i] should provide the x position of Z[i,*]

       Default: X values are integer increments from 0 to NX-1

   Y - Optional vector of y positions for a single column of Z.

          Y[j] should provide the y position of Z[*,j]

       Default: Y values are integer increments from 0 to NY-1

 OUTPUTS:
   A - Upon return, an array of best fit parameter values.  See the
       table above for the meanings of each parameter element.


 RETURNS:

   Returns the best fitting model function as a 2D array.

 KEYWORDS:

   ** NOTE ** Additional keywords such as PARINFO, BESTNORM, and
              STATUS are accepted by MPFIT2DPEAK but not documented
              here.  Please see the documentation for MPFIT for the
              description of these advanced options.

   CHISQ - the value of the summed squared residuals for the
           returned parameter values.

   CIRCULAR - if set, then the peak profile is assumed to be
              azimuthally symmetric.  When set, the parameters A[2)
              and A[3) will be identical and the TILT keyword will
              have no effect.

   DOF - number of degrees of freedom, computed as
             DOF = N_ELEMENTS(DEVIATES) - NFREE
         Note that this doesn't account for pegged parameters (see
         NPEGGED).

   ERROR - upon input, the measured 1-sigma uncertainties in the "Z"
           values.  If no ERROR or WEIGHTS are given, then the fit is
           unweighted.

   ESTIMATES - Array of starting values for each parameter of the
               model.
               Default: parameter values are estimated from data.

   GAUSSIAN - if set, fit a gaussian model function.  The Default.
   LORENTZIAN - if set, fit a lorentzian model function.
   MOFFAT - if set, fit a Moffat model function.

   MEASURE_ERRORS - synonym for ERRORS, for consistency with built-in
                    IDL fitting routines.

   NEGATIVE - if set, and ESTIMATES is not provided, then MPFIT2DPEAK
              will assume that a negative peak is present -- a
              valley.  Specifying this keyword is not normally
              required, since MPFIT2DPEAK can determine this
              automatically.

   NFREE - the number of free parameters in the fit.  This includes
           parameters which are not FIXED and not TIED, but it does
           include parameters which are pegged at LIMITS.

   PERROR - upon return, the 1-sigma uncertainties of the parameter
            values A.  These values are only meaningful if the ERRORS
            or WEIGHTS keywords are specified properly.

            If the fit is unweighted (i.e. no errors were given, or
            the weights were uniformly set to unity), then PERROR
            will probably not represent the true parameter
            uncertainties.  

            *If* you can assume that the true reduced chi-squared
            value is unity -- meaning that the fit is implicitly
            assumed to be of good quality -- then the estimated
            parameter uncertainties can be computed by scaling PERROR
            by the measured chi-squared value.

              DOF     = N_ELEMENTS(Z) - N_ELEMENTS(A)   ; deg of freedom
              PCERROR = PERROR * SQRT(BESTNORM / DOF)   ; scaled uncertainties

   QUIET - if set then diagnostic fitting messages are suppressed.
           Default: QUIET=1 (i.e., no diagnostics)

   SIGMA - synonym for PERROR (1-sigma parameter uncertainties), for
           compatibility with GAUSSFIT.  Do not confuse this with the
           Gaussian "sigma" width parameter.

   TILT - if set, then the major and minor axes of the peak profile
          are allowed to rotate with respect to the image axes.
          Parameter A[6] will be set to the clockwise rotation angle
          of the A[2] axis in radians.

   WEIGHTS - Array of weights to be used in calculating the
             chi-squared value.  If WEIGHTS is specified then the ERR
             parameter is ignored.  The chi-squared value is computed
             as follows:

                CHISQ = TOTAL( (Z-MYFUNCT(X,Y,P))^2 * ABS(WEIGHTS) )

             Here are common values of WEIGHTS:

                1D/ERR^2 - Normal weighting (ERR is the measurement error)
                1D/Y     - Poisson weighting (counting statistics)
                1D       - Unweighted

             The ERROR keyword takes precedence over any WEIGHTS
             keyword values.  If no ERROR or WEIGHTS are given, then
             the fit is unweighted.


 EXAMPLE:

 ; Construct a sample gaussian surface in range [-5,5] centered at [2,-3]
   x = findgen(100)*0.1 - 5. & y = x
   xx = x # (y*0 + 1)
   yy = (x*0 + 1) # y
   rr = sqrt((xx-2.)^2 + (yy+3.)^2)

 ; Gaussian surface with sigma=0.5, peak value of 3, noise with sigma=0.2
   z = 3.*exp(-(rr/0.5)^2) + randomn(seed,100,100)*.2

 ; Fit gaussian parameters A
   zfit = mpfit2dpeak(z, a, x, y)

 REFERENCES:

   MINPACK-1, Jorge More', available from netlib (www.netlib.org).
   "Optimization Software Guide," Jorge More' and Stephen Wright, 
     SIAM, *Frontiers in Applied Mathematics*, Number 14.

 MODIFICATION HISTORY:

   New algorithm for estimating starting values, CM, 31 Oct 1999
   Documented, 02 Nov 1999
   Small documentation fixes, 02 Nov 1999
   Documented PERROR for unweighted fits, 03 Nov 1999, CM
   Copying permission terms have been liberalized, 26 Mar 2000, CM
   Small cosmetic changes, 21 Sep 2000, CM
   Corrected bug introduced by cosmetic changes, 11 Oct 2000, CM :-)
   Added POSITIVE keyword, 17 Nov 2000, CM
   Removed TILT in common, in favor of FUNCTARGS approach, 23 Nov
     2000, CM
   Added SYMMETRIC keyword, documentation for TILT, and an example,
     24 Nov 2000, CM
   Changed SYMMETRIC to CIRCULAR, 17 Dec 2000, CM
   Really change SYMMETRIC to CIRCULAR!, 13 Sep 2002, CM
   Add error messages for SYMMETRIC and CIRCLE, 08 Nov 2002, CM
   Make more consistent with comparable IDL routines, 30 Jun 2003, CM
   Defend against users supplying strangely dimensioned X and Y, 29
     Jun 2005, CM
   Convert to IDL 5 array syntax (!), 16 Jul 2006, CM

  $Id: mpfit2dpeak.pro,v 2.1 2006/09/28 15:40:24 bdavis Exp $

(See src/idl_cvs/mpfit2dpeak.pro)


MPFITELLIPSE

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

 AUTHOR:
   Craig B. Markwardt, NASA/GSFC Code 662, Greenbelt, MD 20770
   craigm@lheamail.gsfc.nasa.gov
   UPDATED VERSIONs can be found on my WEB PAGE: 
      http://cow.physics.wisc.edu/~craigm/idl/idl.html

 PURPOSE:
   Approximate fit to points forming an ellipse

 MAJOR TOPICS:
   Curve and Surface Fitting

 CALLING SEQUENCE:
   parms = MPFITELLIPSE(X, Y, start_parms, [/TILT, WEIGHTS=wts, ...])

 DESCRIPTION:

   MPFITELLIPSE fits a closed elliptical or circular curve to a two
   dimensional set of data points.  The user specifies the X and Y
   positions of the points, and an optional set of weights.  The
   ellipse may also be tilted at an arbitrary angle.

   The best fitting ellipse parameters are returned from by
   MPFITELLIPSE as a vector, whose values are:

      P[0]   Ellipse semi axis 1
      P[1]   Ellipse semi axis 2   ( = P[0] if CIRCLE keyword set)
      P[2]   Ellipse center - x value
      P[3]   Ellipse center - y value
      P[4]   Ellipse rotation angle (radians) if TILT keyword set

   The user may specify an initial set of trial parameters, but by
   default MPFITELLIPSE will estimate the parameters automatically.

   Users should be aware that in the presence of large amounts of
   noise, namely when the measurement error becomes significant
   compared to the ellipse axis length, then the estimated parameters
   become unreliable.  Generally speaking the computed axes will
   overestimate the true axes.  For example when (SIGMA_R/R) becomes
   0.5, the radius of the ellipse is overestimated by about 40%.

   Users can weight their data as they see appropriate.  However, the
   following prescription for the weighting appears to be the correct
   one, and produces values comparable to the typical chi-squared
   value.

     WEIGHTS = 0.75/(SIGMA_X^2 + SIGMA_Y^2)

   where SIGMA_X and SIGMA_Y are the measurement error vectors in the
   X and Y directions respectively.  However, it should be pointed
   out that this weighting is only appropriate for a set of points
   whose measurement errors are comparable.  If a more robust
   estimation of the parameter values is needed, the so-called
   orthogonal distance regression package should be used (ODRPACK,
   available in FORTRAN at www.netlib.org).

 INPUTS:

   X - measured X positions of the points in the ellipse.
   Y - measured Y positions of the points in the ellipse.

   START_PARAMS - an array of starting values for the ellipse
                  parameters, as described above.  This parameter is
                  optional; if not specified by the user, then the
                  ellipse parameters are estimated automatically from
                  the properties of the data.

 RETURNS:

   Returns the best fitting model ellipse parameters.

 KEYWORDS:

   ** NOTE ** Additional keywords such as PARINFO, BESTNORM, and
              STATUS are accepted by MPFITELLIPSE but not documented
              here.  Please see the documentation for MPFIT for the
              description of these advanced options.

   PERROR - upon return, the 1-sigma uncertainties of the returned
            ellipse parameter values.  These values are only
            meaningful if the WEIGHTS keyword is specified properly.

            If the fit is unweighted (i.e. no errors were given, or
            the weights were uniformly set to unity), then PERROR
            will probably not represent the true parameter
            uncertainties.  

   QUIET - if set then diagnostic fitting messages are suppressed.
           Default: QUIET=1 (i.e., no diagnostics]

   CIRCULAR - if set, then the curve is assumed to be a circle
              instead of ellipse.  When set, the parameters P[0] and
              P[1] will be identical and the TILT keyword will have
              no effect.

   TILT - if set, then the major and minor axes of the ellipse
          are allowed to rotate with respect to the data axes.
          Parameter P[4] will be set to the clockwise rotation angle
          of the P[0] axis in radians.

   WEIGHTS - Array of weights to be used in calculating the
             chi-squared value.  If WEIGHTS is specified then the ERR
             parameter is ignored.  The chi-squared value is computed
             as follows:

                CHISQ = TOTAL( (Z-MYFUNCT(X,Y,P))^2 * ABS(WEIGHTS)^2 )

             Users may wish to follow the guidelines for WEIGHTS
             described above.


 EXAMPLE:

 ; Construct a set of points on an ellipse, with some noise
   ph0 = 2*!pi*randomu(seed,50)
   x =  50. + 32.*cos(ph0) + 4.0*randomn(seed, 50)
   y = -75. + 65.*sin(ph0) + 0.1*randomn(seed, 50)

 ; Compute weights function
   weights = 0.75/(4.0^2 + 0.1^2)

 ; Fit ellipse and plot result
   p = mpfitellipse(x, y)
   plot, x, y, psym=1
   phi = dindgen(101)*2D*!dpi/100
   oplot, p[2]+p[0]*cos(phi), p[3]+p[1]*sin(phi)

 REFERENCES:

   MINPACK-1, Jorge More', available from netlib (www.netlib.org).
   "Optimization Software Guide," Jorge More' and Stephen Wright, 
     SIAM, *Frontiers in Applied Mathematics*, Number 14.

 MODIFICATION HISTORY:

   Ported from MPFIT2DPEAK, 17 Dec 2000, CM
   More documentation, 11 Jan 2001, CM
   Example corrected, 18 Nov 2001, CM
   Change CIRCLE keyword to the correct CIRCULAR keyword, 13 Sep
      2002, CM
   Add error messages for SYMMETRIC and CIRCLE, 08 Nov 2002, CM
   Found small error in computation of _EVAL (when CIRCULAR) was set;
      sanity check when CIRCULAR is set, 21 Jan 2003, CM
   Convert to IDL 5 array syntax (!), 16 Jul 2006, CM

  $Id: mpfitellipse.pro,v 2.1 2006/09/28 15:40:24 bdavis Exp $

(See src/idl_cvs/mpfitellipse.pro)


MPFITEXPR

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

 AUTHOR:
   Craig B. Markwardt, NASA/GSFC Code 662, Greenbelt, MD 20770
   craigm@lheamail.gsfc.nasa.gov
   UPDATED VERSIONs can be found on my WEB PAGE: 
      http://cow.physics.wisc.edu/~craigm/idl/idl.html

 PURPOSE:
   Perform Levenberg-Marquardt least-squares fit to arbitrary expression

 MAJOR TOPICS:
   Curve and Surface Fitting

 CALLING SEQUENCE:
   MYFUNCT = 'X*(1-X)+3'
   parms = MPFITEXPR(MYFUNCT, XVAL, YVAL, ERR, start_parms, ...)

 DESCRIPTION:

  MPFITEXPR fits a user-supplied model -- in the form of an arbitrary IDL
  expression -- to a set of user-supplied data.  MPFITEXPR calls
  MPFIT, the MINPACK-1 least-squares minimizer, to do the main
  work.

  Given the data and their uncertainties, MPFITEXPR finds the best set
  of model parameters which match the data (in a least-squares
  sense) and returns them in an array.
  
  The user must supply the following items:
   - An array of independent variable values ("X").
   - An array of "measured" *dependent* variable values ("Y").
   - An array of "measured" 1-sigma uncertainty values ("ERR").
   - A text IDL expression which computes Y given X.
   - Starting guesses for all of the parameters ("START_PARAMS").

  There are very few restrictions placed on X, Y or the expression of
  the model.  Simply put, the expression must map the "X" values into
  "Y" values given the model parameters.  The "X" values may
  represent any independent variable (not just Cartesian X), and
  indeed may be multidimensional themselves.  For example, in the
  application of image fitting, X may be a 2xN array of image
  positions.

  Some rules must be obeyed in constructing the expression.  First,
  the independent variable name *MUST* be "X" in the expression,
  regardless of the name of the variable being passed to MPFITEXPR.
  This is demonstrated in the above calling sequence, where the X
  variable passed in is called "XVAL" but the expression still refers
  to "X".  Second, parameter values must be referred to as an array
  named "P".

  If you do not pass in starting values for the model parameters,
  MPFITEXPR will attempt to determine the number of parameters you
  intend to have (it does this by looking for references to the array
  variable named "P").  When no starting values are passed in, the
  values are assumed to start at zero.

  MPFITEXPR carefully avoids passing large arrays where possible to
  improve performance.

  See below for an example of usage.

 EVALUATING EXPRESSIONS

  This source module also provides a function called MPEVALEXPR.  You
  can use this function to evaluate your expression, given a list of
  parameters.  This is one of the easier ways to compute the model
  once the best-fit parameters have been found.  Here is an example:

       YMOD = MPEVALEXPR(MYFUNCT, XVAL, PARMS)

  where MYFUNCT is the expression (see MYFUNCT below), XVAL is the
  list of "X" values, and PARMS is an array of parameters.  The
  returned array YMOD contains the expression MYFUNCT evaluated at
  each point in XVAL.

 PASSING PRIVATE DATA TO AN EXPRESSION

  The most complicated optimization problems typically involve other
  external parameters, in addition to the fitted parameters.  While
  it is extremely easy to rewrite an expression dynamically, in case
  one of the external parameters changes, the other possibility is to
  use the PRIVATE data structure.

  The user merely passes a structure to the FUNCTARGS keyword.  The
  user expression receives this value as the variable PRIVATE.
  MPFITEXPR nevers accesses this variable so it can contain any
  desired values.  Usually it would be an IDL structure so that any
  named external parameters can be passed to the expression.


 CONSTRAINING PARAMETER VALUES WITH THE PARINFO KEYWORD

  The behavior of MPFIT can be modified with respect to each
  parameter to be fitted.  A parameter value can be fixed; simple
  boundary constraints can be imposed; limitations on the parameter
  changes can be imposed; properties of the automatic derivative can
  be modified; and parameters can be tied to one another.

  These properties are governed by the PARINFO structure, which is
  passed as a keyword parameter to MPFIT.

  PARINFO should be an array of structures, one for each parameter.
  Each parameter is associated with one element of the array, in
  numerical order.  The structure can have the following entries
  (none are required):
  
     .VALUE - the starting parameter value (but see the START_PARAMS
              parameter for more information).
  
     .FIXED - a boolean value, whether the parameter is to be held
              fixed or not.  Fixed parameters are not varied by
              MPFIT, but are passed on to MYFUNCT for evaluation.
  
     .LIMITED - a two-element boolean array.  If the first/second
                element is set, then the parameter is bounded on the
                lower/upper side.  A parameter can be bounded on both
                sides.  Both LIMITED and LIMITS must be given
                together.
  
     .LIMITS - a two-element float or double array.  Gives the
               parameter limits on the lower and upper sides,
               respectively.  Zero, one or two of these values can be
               set, depending on the values of LIMITED.  Both LIMITED
               and LIMITS must be given together.
  
     .PARNAME - a string, giving the name of the parameter.  The
                fitting code of MPFIT does not use this tag in any
                way.  However, the default ITERPROC will print the
                parameter name if available.
  
     .STEP - the step size to be used in calculating the numerical
             derivatives.  If set to zero, then the step size is
             computed automatically.  Ignored when AUTODERIVATIVE=0.
             This value is superceded by the RELSTEP value.

     .RELSTEP - the *relative* step size to be used in calculating
                the numerical derivatives.  This number is the
                fractional size of the step, compared to the
                parameter value.  This value supercedes the STEP
                setting.  If the parameter is zero, then a default
                step size is chosen.

     .MPSIDE - the sidedness of the finite difference when computing
               numerical derivatives.  This field can take four
               values:

                  0 - one-sided derivative computed automatically
                  1 - one-sided derivative (f(x+h) - f(x)  )/h
                 -1 - one-sided derivative (f(x)   - f(x-h))/h
                  2 - two-sided derivative (f(x+h) - f(x-h))/(2*h)

              Where H is the STEP parameter described above.  The
              "automatic" one-sided derivative method will chose a
              direction for the finite difference which does not
              violate any constraints.  The other methods do not
              perform this check.  The two-sided method is in
              principle more precise, but requires twice as many
              function evaluations.  Default: 0.

     .MPMINSTEP - the minimum change to be made in the parameter
                  value.  During the fitting process, the parameter
                  will be changed by multiples of this value.  The
                  actual step is computed as:

                     DELTA1 = MPMINSTEP*ROUND(DELTA0/MPMINSTEP)

                  where DELTA0 and DELTA1 are the estimated parameter
                  changes before and after this constraint is
                  applied.  Note that this constraint should be used
                  with care since it may cause non-converging,
                  oscillating solutions.

                  A value of 0 indicates no minimum.  Default: 0.

     .MPMAXSTEP - the maximum change to be made in the parameter
                  value.  During the fitting process, the parameter
                  will never be changed by more than this value.

                  A value of 0 indicates no maximum.  Default: 0.
  
     .TIED - a string expression which "ties" the parameter to other
             free or fixed parameters.  Any expression involving
             constants and the parameter array P are permitted.
             Example: if parameter 2 is always to be twice parameter
             1 then use the following: parinfo[2].tied = '2 * P[1]'.
             Since they are totally constrained, tied parameters are
             considered to be fixed; no errors are computed for them.
             [ NOTE: the PARNAME can't be used in expressions. ]
  
  Future modifications to the PARINFO structure, if any, will involve
  adding structure tags beginning with the two letters "MP".
  Therefore programmers are urged to avoid using tags starting with
  the same letters; otherwise they are free to include their own
  fields within the PARINFO structure, and they will be ignored.
  
  PARINFO Example:
  parinfo = replicate({value:0.D, fixed:0, limited:[0,0], $
                       limits:[0.D,0]}, 5)
  parinfo[0].fixed = 1
  parinfo[4].limited[0] = 1
  parinfo[4].limits[0]  = 50.D
  parinfo[*].value = [5.7D, 2.2, 500., 1.5, 2000.]
  
  A total of 5 parameters, with starting values of 5.7,
  2.2, 500, 1.5, and 2000 are given.  The first parameter
  is fixed at a value of 5.7, and the last parameter is
  constrained to be above 50.

 INPUTS:
   MYFUNCT - a string variable containing an IDL expression.  The
             only restriction is that the independent variable *must*
             be referred to as "X" and model parameters *must* be
             referred to as an array called "P".  Do not use symbol
             names beginning with the underscore, "_".

             The expression should calculate "model" Y values given
             the X values and model parameters.  Using the vector
             notation of IDL, this can be quite easy to do.  If your
             expression gets complicated, you may wish to make an IDL
             function which will improve performance and readibility.

             The resulting array should be of the same size and
             dimensions as the "measured" Y values.

   X - Array of independent variable values.

   Y - Array of "measured" dependent variable values.  Y should have
       the same data type as X.  The function MYFUNCT should map
       X->Y.

   ERR - Array of "measured" 1-sigma uncertainties.  ERR should have
         the same data type as Y.  ERR is ignored if the WEIGHTS
         keyword is specified.

   START_PARAMS - An array of starting values for each of the
                  parameters of the model.  The number of parameters
                  should be fewer than the number of measurements.
                  Also, the parameters should have the same data type
                  as the measurements (double is preferred).

                  This parameter is optional if the PARINFO keyword
                  is used (see MPFIT).  The PARINFO keyword provides
                  a mechanism to fix or constrain individual
                  parameters.  If both START_PARAMS and PARINFO are
                  passed, then the starting *value* is taken from
                  START_PARAMS, but the *constraints* are taken from
                  PARINFO.

                  If no parameters are given, then MPFITEXPR attempts
                  to determine the number of parameters by scanning
                  the expression.  Parameters determined this way are
                  initialized to zero.  This technique is not fully
                  reliable, so users are advised to pass explicit
                  parameter starting values.
 

 RETURNS:

   Returns the array of best-fit parameters.


 KEYWORD PARAMETERS:

   BESTNORM - the value of the summed, squared, weighted residuals
              for the returned parameter values, i.e. the chi-square value.

   COVAR - the covariance matrix for the set of parameters returned
           by MPFIT.  The matrix is NxN where N is the number of
           parameters.  The square root of the diagonal elements
           gives the formal 1-sigma statistical errors on the
           parameters IF errors were treated "properly" in MYFUNC.
           Parameter errors are also returned in PERROR.

           To compute the correlation matrix, PCOR, use this:
           IDL> PCOR = COV * 0
           IDL> FOR i = 0, n-1 DO FOR j = 0, n-1 DO $
                PCOR[i,j] = COV[i,j]/sqrt(COV[i,i]*COV[j,j])

           If NOCOVAR is set or MPFIT terminated abnormally, then
           COVAR is set to a scalar with value !VALUES.D_NAN.

   DOF - number of degrees of freedom, computed as
             DOF = N_ELEMENTS(DEVIATES) - NFREE
         Note that this doesn't account for pegged parameters (see
         NPEGGED).

   ERRMSG - a string error or warning message is returned.

   FTOL - a nonnegative input variable. Termination occurs when both
          the actual and predicted relative reductions in the sum of
          squares are at most FTOL (and STATUS is accordingly set to
          1 or 3).  Therefore, FTOL measures the relative error
          desired in the sum of squares.  Default: 1D-10

   FUNCTARGS - passed directly to the expression as the variable
               PRIVATE.  Any user-private data can be communicated to
               the user expression using this keyword.
               Default: PRIVATE is undefined in user expression

   GTOL - a nonnegative input variable. Termination occurs when the
          cosine of the angle between fvec and any column of the
          jacobian is at most GTOL in absolute value (and STATUS is
          accordingly set to 4). Therefore, GTOL measures the
          orthogonality desired between the function vector and the
          columns of the jacobian.  Default: 1D-10

   ITERARGS - The keyword arguments to be passed to ITERPROC via the
              _EXTRA mechanism.  This should be a structure, and is
              similar in operation to FUNCTARGS.
              Default: no arguments are passed.

   ITERPROC - The name of a procedure to be called upon each NPRINT
              iteration of the MPFIT routine.  It should be declared
              in the following way:

              PRO ITERPROC, MYFUNCT, p, iter, fnorm, FUNCTARGS=fcnargs, $
                PARINFO=parinfo, QUIET=quiet, ...
                ; perform custom iteration update
              END
         
              ITERPROC must either accept all three keyword
              parameters (FUNCTARGS, PARINFO and QUIET), or at least
              accept them via the _EXTRA keyword.
          
              MYFUNCT is the user-supplied function to be minimized,
              P is the current set of model parameters, ITER is the
              iteration number, and FUNCTARGS are the arguments to be
              passed to MYFUNCT.  FNORM should be the
              chi-squared value.  QUIET is set when no textual output
              should be printed.  See below for documentation of
              PARINFO.

              In implementation, ITERPROC can perform updates to the
              terminal or graphical user interface, to provide
              feedback while the fit proceeds.  If the fit is to be
              stopped for any reason, then ITERPROC should set the
              common block variable ERROR_CODE to negative value (see
              MPFIT_ERROR common block below).  In principle,
              ITERPROC should probably not modify the parameter
              values, because it may interfere with the algorithm's
              stability.  In practice it is allowed.

              Default: an internal routine is used to print the
                       parameter values.

   MAXITER - The maximum number of iterations to perform.  If the
             number is exceeded, then the STATUS value is set to 5
             and MPFIT returns.
             Default: 200 iterations

   NFEV - the number of MYFUNCT function evaluations performed.

   NFREE - the number of free parameters in the fit.  This includes
           parameters which are not FIXED and not TIED, but it does
           include parameters which are pegged at LIMITS.

   NITER - the number of iterations completed.

   NOCOVAR - set this keyword to prevent the calculation of the
             covariance matrix before returning (see COVAR)

   NPEGGED - the number of free parameters which are pegged at a
             LIMIT.

   NPRINT - The frequency with which ITERPROC is called.  A value of
            1 indicates that ITERPROC is called with every iteration,
            while 2 indicates every other iteration, etc.  Note that
            several Levenberg-Marquardt attempts can be made in a
            single iteration.
            Default value: 1

   PARINFO - Provides a mechanism for more sophisticated constraints
             to be placed on parameter values.  When PARINFO is not
             passed, then it is assumed that all parameters are free
             and unconstrained.  Values in PARINFO are never 
             modified during a call to MPFIT.

             See description above for the structure of PARINFO.

             Default value:  all parameters are free and unconstrained.

   PERROR - The formal 1-sigma errors in each parameter, computed
            from the covariance matrix.  If a parameter is held
            fixed, or if it touches a boundary, then the error is
            reported as zero.

            If the fit is unweighted (i.e. no errors were given, or
            the weights were uniformly set to unity), then PERROR
            will probably not represent the true parameter
            uncertainties.  

            *If* you can assume that the true reduced chi-squared
            value is unity -- meaning that the fit is implicitly
            assumed to be of good quality -- then the estimated
            parameter uncertainties can be computed by scaling PERROR
            by the measured chi-squared value.

              DOF     = N_ELEMENTS(X) - N_ELEMENTS(PARMS) ; deg of freedom
              PCERROR = PERROR * SQRT(BESTNORM / DOF)   ; scaled uncertainties

   QUIET - set this keyword when no textual output should be printed
           by MPFIT

   STATUS - an integer status code is returned.  All values other
            than zero can represent success.  It can have one of the
            following values:

	   0  improper input parameters.
         
	   1  both actual and predicted relative reductions
	      in the sum of squares are at most FTOL.
         
	   2  relative error between two consecutive iterates
	      is at most XTOL
         
	   3  conditions for STATUS = 1 and STATUS = 2 both hold.
         
	   4  the cosine of the angle between fvec and any
	      column of the jacobian is at most GTOL in
	      absolute value.
         
	   5  the maximum number of iterations has been reached
         
	   6  FTOL is too small. no further reduction in
	      the sum of squares is possible.
         
	   7  XTOL is too small. no further improvement in
	      the approximate solution x is possible.
         
	   8  GTOL is too small. fvec is orthogonal to the
	      columns of the jacobian to machine precision.

   WEIGHTS - Array of weights to be used in calculating the
             chi-squared value.  If WEIGHTS is specified then the ERR
             parameter is ignored.  The chi-squared value is computed
             as follows:

                CHISQ = TOTAL( (Y-MYFUNCT(X,P))^2 * ABS(WEIGHTS) )

             Here are common values of WEIGHTS:

                1D/ERR^2 - Normal weighting (ERR is the measurement error)
                1D/Y     - Poisson weighting (counting statistics)
                1D       - Unweighted

   XTOL - a nonnegative input variable. Termination occurs when the
          relative error between two consecutive iterates is at most
          XTOL (and STATUS is accordingly set to 2 or 3).  Therefore,
          XTOL measures the relative error desired in the approximate
          solution.  Default: 1D-10

   YFIT - the best-fit model function, as returned by MYFUNCT.


 EXAMPLE:

   ; First, generate some synthetic data
   x  = dindgen(200) * 0.1 - 10.                   ; Independent variable 
   yi = gauss1(x, [2.2D, 1.4, 3000.]) + 1000       ; "Ideal" Y variable
   y  = yi + randomn(seed, 200) * sqrt(yi)         ; Measured, w/ noise
   sy = sqrt(y)                                    ; Poisson errors

   ; Now fit a Gaussian to see how well we can recover
   expr = 'P[0] + GAUSS1(X, P[1:3])'               ; fitting function
   p0 = [800.D, 1.D, 1., 500.]                     ; Initial guess
   p = mpfitexpr(expr, x, y, sy, p0)               ; Fit the expression
   print, p

   plot, x, y                                      ; Plot data
   oplot, x, mpevalexpr(expr, x, p)                ; Plot model

   Generates a synthetic data set with a Gaussian peak, and Poisson
   statistical uncertainty.  Then a model consisting of a constant
   plus Gaussian is fit to the data.


 COMMON BLOCKS:

   COMMON MPFIT_ERROR, ERROR_CODE

     User routines may stop the fitting process at any time by
     setting an error condition.  This condition may be set in either
     the user's model computation routine (MYFUNCT), or in the
     iteration procedure (ITERPROC).

     To stop the fitting, the above common block must be declared,
     and ERROR_CODE must be set to a negative number.  After the user
     procedure or function returns, MPFIT checks the value of this
     common block variable and exits immediately if the error
     condition has been set.  By default the value of ERROR_CODE is
     zero, indicating a successful function/procedure call.


 REFERENCES:

   MINPACK-1, Jorge More', available from netlib (www.netlib.org).
   "Optimization Software Guide," Jorge More' and Stephen Wright, 
     SIAM, *Frontiers in Applied Mathematics*, Number 14.

 MODIFICATION HISTORY:
   Written, Apr-Jul 1998, CM
   Added PERROR keyword, 04 Aug 1998, CM
   Added COVAR keyword, 20 Aug 1998, CM
   Added NITER output keyword, 05 Oct 1998
      D.L Windt, Bell Labs, windt@bell-labs.com;
   Added ability to return model function in YFIT, 09 Nov 1998
   Parameter values can be tied to others, 09 Nov 1998
   Added MPEVALEXPR utility function, 09 Dec 1998
   Cosmetic documentation updates, 16 Apr 1999, CM
   More cosmetic documentation updates, 14 May 1999, CM
   Made sure to update STATUS value, 25 Sep 1999, CM
   Added WEIGHTS keyword, 25 Sep 1999, CM
   Changed from handles to common blocks, 25 Sep 1999, CM
     - commons seem much cleaner and more logical in this case.
   Alphabetized documented keywords, 02 Oct 1999, CM
   Added QUERY keyword and query checking of MPFIT, 29 Oct 1999, CM
   Check to be sure that X and Y are present, 02 Nov 1999, CM
   Documented PERROR for unweighted fits, 03 Nov 1999, CM
   Removed ITERPROC='' when quiet EQ 1, 10 Jan 2000, CM
   Changed to ERROR_CODE for error condition, 28 Jan 2000, CM
   Updated the EXAMPLE, 26 Mar 2000, CM
   Copying permission terms have been liberalized, 26 Mar 2000, CM
   Propagated improvements from MPFIT, 17 Dec 2000, CM
   Correct reference to _WTS in MPFITEXPR_EVAL, 25 May 2001, CM
      (thanks to Mark Fardal)
   Added useful FUNCTARGS behavior (as yet undocumented), 04 Jul
      2002, CM
   Documented FUNCTARGS/PRIVATE behavior, 22 Jul 2002, CM
   Added NFREE and NPEGGED keywords, 13 Sep 2002, CM
   Documented RELSTEP field of PARINFO (!!), CM, 25 Oct 2002
   Add DOF keyword, CM, 31 Jul 2003
   Add FUNCTARGS keyword to MPEVALEXPR, CM 08 Aug 2003
   Minor documentation adjustment, 03 Feb 2004, CM

  $Id: mpfitexpr.pro,v 2.1 2006/09/28 15:40:24 bdavis Exp $

(See src/idl_cvs/mpfitexpr.pro)


MPFITFUN

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

 AUTHOR:
   Craig B. Markwardt, NASA/GSFC Code 662, Greenbelt, MD 20770
   craigm@lheamail.gsfc.nasa.gov
   UPDATED VERSIONs can be found on my WEB PAGE: 
      http://cow.physics.wisc.edu/~craigm/idl/idl.html

 PURPOSE:
   Perform Levenberg-Marquardt least-squares fit to IDL function

 MAJOR TOPICS:
   Curve and Surface Fitting

 CALLING SEQUENCE:
   parms = MPFITFUN(MYFUNCT, X, Y, ERR, start_params, ...)

 DESCRIPTION:

  MPFITFUN fits a user-supplied model -- in the form of an IDL
  function -- to a set of user-supplied data.  MPFITFUN calls
  MPFIT, the MINPACK-1 least-squares minimizer, to do the main
  work.

  Given the data and their uncertainties, MPFITFUN finds the best set
  of model parameters which match the data (in a least-squares
  sense) and returns them in an array.
  
  The user must supply the following items:
   - An array of independent variable values ("X").
   - An array of "measured" *dependent* variable values ("Y").
   - An array of "measured" 1-sigma uncertainty values ("ERR").
   - The name of an IDL function which computes Y given X ("MYFUNCT").
   - Starting guesses for all of the parameters ("START_PARAMS").

  There are very few restrictions placed on X, Y or MYFUNCT.  Simply
  put, MYFUNCT must map the "X" values into "Y" values given the
  model parameters.  The "X" values may represent any independent
  variable (not just Cartesian X), and indeed may be multidimensional
  themselves.  For example, in the application of image fitting, X
  may be a 2xN array of image positions.

  MPFITFUN carefully avoids passing large arrays where possible to
  improve performance.

  See below for an example of usage.

 USER FUNCTION

  The user must define a function which returns the model value.  For
  applications which use finite-difference derivatives -- the default
  -- the user function should be declared in the following way:

    FUNCTION MYFUNCT, X, P
     ; The independent variable is X
     ; Parameter values are passed in "P"
     YMOD = ... computed model values at X ...
     return, YMOD
    END

  The returned array YMOD must have the same dimensions and type as
  the "measured" Y values.

  User functions may also indicate a fatal error condition
  using the ERROR_CODE common block variable, as described
  below under the MPFIT_ERROR common block definition.

  See the discussion under "ANALYTIC DERIVATIVES" and AUTODERIVATIVE
  in MPFIT.PRO if you wish to compute the derivatives for yourself.
  AUTODERIVATIVE is accepted by MPFITFUN and passed directly to
  MPFIT.  The user function must accept one additional parameter, DP,
  which contains the derivative of the user function with respect to
  each parameter at each data point, as described in MPFIT.PRO.

 CONSTRAINING PARAMETER VALUES WITH THE PARINFO KEYWORD

  The behavior of MPFIT can be modified with respect to each
  parameter to be fitted.  A parameter value can be fixed; simple
  boundary constraints can be imposed; limitations on the parameter
  changes can be imposed; properties of the automatic derivative can
  be modified; and parameters can be tied to one another.

  These properties are governed by the PARINFO structure, which is
  passed as a keyword parameter to MPFIT.

  PARINFO should be an array of structures, one for each parameter.
  Each parameter is associated with one element of the array, in
  numerical order.  The structure can have the following entries
  (none are required):
  
     .VALUE - the starting parameter value (but see the START_PARAMS
              parameter for more information).
  
     .FIXED - a boolean value, whether the parameter is to be held
              fixed or not.  Fixed parameters are not varied by
              MPFIT, but are passed on to MYFUNCT for evaluation.
  
     .LIMITED - a two-element boolean array.  If the first/second
                element is set, then the parameter is bounded on the
                lower/upper side.  A parameter can be bounded on both
                sides.  Both LIMITED and LIMITS must be given
                together.
  
     .LIMITS - a two-element float or double array.  Gives the
               parameter limits on the lower and upper sides,
               respectively.  Zero, one or two of these values can be
               set, depending on the values of LIMITED.  Both LIMITED
               and LIMITS must be given together.
  
     .PARNAME - a string, giving the name of the parameter.  The
                fitting code of MPFIT does not use this tag in any
                way.  However, the default ITERPROC will print the
                parameter name if available.
  
     .STEP - the step size to be used in calculating the numerical
             derivatives.  If set to zero, then the step size is
             computed automatically.  Ignored when AUTODERIVATIVE=0.
             This value is superceded by the RELSTEP value.

     .RELSTEP - the *relative* step size to be used in calculating
                the numerical derivatives.  This number is the
                fractional size of the step, compared to the
                parameter value.  This value supercedes the STEP
                setting.  If the parameter is zero, then a default
                step size is chosen.

     .MPSIDE - the sidedness of the finite difference when computing
               numerical derivatives.  This field can take four
               values:

                  0 - one-sided derivative computed automatically
                  1 - one-sided derivative (f(x+h) - f(x)  )/h
                 -1 - one-sided derivative (f(x)   - f(x-h))/h
                  2 - two-sided derivative (f(x+h) - f(x-h))/(2*h)

              Where H is the STEP parameter described above.  The
              "automatic" one-sided derivative method will chose a
              direction for the finite difference which does not
              violate any constraints.  The other methods do not
              perform this check.  The two-sided method is in
              principle more precise, but requires twice as many
              function evaluations.  Default: 0.

     .MPMINSTEP - the minimum change to be made in the parameter
                  value.  During the fitting process, the parameter
                  will be changed by multiples of this value.  The
                  actual step is computed as:

                     DELTA1 = MPMINSTEP*ROUND(DELTA0/MPMINSTEP)

                  where DELTA0 and DELTA1 are the estimated parameter
                  changes before and after this constraint is
                  applied.  Note that this constraint should be used
                  with care since it may cause non-converging,
                  oscillating solutions.

                  A value of 0 indicates no minimum.  Default: 0.

     .MPMAXSTEP - the maximum change to be made in the parameter
                  value.  During the fitting process, the parameter
                  will never be changed by more than this value.

                  A value of 0 indicates no maximum.  Default: 0.
  
     .TIED - a string expression which "ties" the parameter to other
             free or fixed parameters.  Any expression involving
             constants and the parameter array P are permitted.
             Example: if parameter 2 is always to be twice parameter
             1 then use the following: parinfo[2].tied = '2 * P[1]'.
             Since they are totally constrained, tied parameters are
             considered to be fixed; no errors are computed for them.
             [ NOTE: the PARNAME can't be used in expressions. ]
  
  Future modifications to the PARINFO structure, if any, will involve
  adding structure tags beginning with the two letters "MP".
  Therefore programmers are urged to avoid using tags starting with
  the same letters; otherwise they are free to include their own
  fields within the PARINFO structure, and they will be ignored.
  
  PARINFO Example:
  parinfo = replicate({value:0.D, fixed:0, limited:[0,0], $
                       limits:[0.D,0]}, 5)
  parinfo[0].fixed = 1
  parinfo[4].limited[0] = 1
  parinfo[4].limits[0]  = 50.D
  parinfo[*].value = [5.7D, 2.2, 500., 1.5, 2000.]
  
  A total of 5 parameters, with starting values of 5.7,
  2.2, 500, 1.5, and 2000 are given.  The first parameter
  is fixed at a value of 5.7, and the last parameter is
  constrained to be above 50.

 INPUTS:
   MYFUNCT - a string variable containing the name of an IDL function.
             This function computes the "model" Y values given the
             X values and model parameters, as desribed above.

   X - Array of independent variable values.

   Y - Array of "measured" dependent variable values.  Y should have
       the same data type as X.  The function MYFUNCT should map
       X->Y.

   ERR - Array of "measured" 1-sigma uncertainties.  ERR should have
         the same data type as Y.  ERR is ignored if the WEIGHTS
         keyword is specified.

   START_PARAMS - An array of starting values for each of the
                  parameters of the model.  The number of parameters
                  should be fewer than the number of measurements.
                  Also, the parameters should have the same data type
                  as the measurements (double is preferred).

                  This parameter is optional if the PARINFO keyword
                  is used (see MPFIT).  The PARINFO keyword provides
                  a mechanism to fix or constrain individual
                  parameters.  If both START_PARAMS and PARINFO are
                  passed, then the starting *value* is taken from
                  START_PARAMS, but the *constraints* are taken from
                  PARINFO.
 

 RETURNS:

   Returns the array of best-fit parameters.


 KEYWORD PARAMETERS:

   BESTNORM - the value of the summed squared residuals for the
              returned parameter values.

   COVAR - the covariance matrix for the set of parameters returned
           by MPFIT.  The matrix is NxN where N is the number of
           parameters.  The square root of the diagonal elements
           gives the formal 1-sigma statistical errors on the
           parameters IF errors were treated "properly" in MYFUNC.
           Parameter errors are also returned in PERROR.

           To compute the correlation matrix, PCOR, use this:
           IDL> PCOR = COV * 0
           IDL> FOR i = 0, n-1 DO FOR j = 0, n-1 DO $
                PCOR[i,j] = COV[i,j]/sqrt(COV[i,i]*COV[j,j])

           If NOCOVAR is set or MPFIT terminated abnormally, then
           COVAR is set to a scalar with value !VALUES.D_NAN.

   CASH - when set, the fit statistic is changed to a derivative of
          the CASH statistic.  The model function must be strictly
          positive.

   DOF - number of degrees of freedom, computed as
             DOF = N_ELEMENTS(DEVIATES) - NFREE
         Note that this doesn't account for pegged parameters (see
         NPEGGED).

   ERRMSG - a string error or warning message is returned.

   FTOL - a nonnegative input variable. Termination occurs when both
          the actual and predicted relative reductions in the sum of
          squares are at most FTOL (and STATUS is accordingly set to
          1 or 3).  Therefore, FTOL measures the relative error
          desired in the sum of squares.  Default: 1D-10

   FUNCTARGS - A structure which contains the parameters to be passed
               to the user-supplied function specified by MYFUNCT via
               the _EXTRA mechanism.  This is the way you can pass
               additional data to your user-supplied function without
               using common blocks.

               By default, no extra parameters are passed to the
               user-supplied function.

   GTOL - a nonnegative input variable. Termination occurs when the
          cosine of the angle between fvec and any column of the
          jacobian is at most GTOL in absolute value (and STATUS is
          accordingly set to 4). Therefore, GTOL measures the
          orthogonality desired between the function vector and the
          columns of the jacobian.  Default: 1D-10

   ITERARGS - The keyword arguments to be passed to ITERPROC via the
              _EXTRA mechanism.  This should be a structure, and is
              similar in operation to FUNCTARGS.
              Default: no arguments are passed.

   ITERPROC - The name of a procedure to be called upon each NPRINT
              iteration of the MPFIT routine.  It should be declared
              in the following way:

              PRO ITERPROC, MYFUNCT, p, iter, fnorm, FUNCTARGS=fcnargs, $
                PARINFO=parinfo, QUIET=quiet, ...
                ; perform custom iteration update
              END
         
              ITERPROC must either accept all three keyword
              parameters (FUNCTARGS, PARINFO and QUIET), or at least
              accept them via the _EXTRA keyword.
          
              MYFUNCT is the user-supplied function to be minimized,
              P is the current set of model parameters, ITER is the
              iteration number, and FUNCTARGS are the arguments to be
              passed to MYFUNCT.  FNORM should be the
              chi-squared value.  QUIET is set when no textual output
              should be printed.  See below for documentation of
              PARINFO.

              In implementation, ITERPROC can perform updates to the
              terminal or graphical user interface, to provide
              feedback while the fit proceeds.  If the fit is to be
              stopped for any reason, then ITERPROC should set the
              common block variable ERROR_CODE to negative value (see
              MPFIT_ERROR common block below).  In principle,
              ITERPROC should probably not modify the parameter
              values, because it may interfere with the algorithm's
              stability.  In practice it is allowed.

              Default: an internal routine is used to print the
                       parameter values.

   MAXITER - The maximum number of iterations to perform.  If the
             number is exceeded, then the STATUS value is set to 5
             and MPFIT returns.
             Default: 200 iterations

   NFEV - the number of MYFUNCT function evaluations performed.

   NFREE - the number of free parameters in the fit.  This includes
           parameters which are not FIXED and not TIED, but it does
           include parameters which are pegged at LIMITS.

   NITER - the number of iterations completed.

   NOCOVAR - set this keyword to prevent the calculation of the
             covariance matrix before returning (see COVAR)

   NPEGGED - the number of free parameters which are pegged at a
             LIMIT.

   NPRINT - The frequency with which ITERPROC is called.  A value of
            1 indicates that ITERPROC is called with every iteration,
            while 2 indicates every other iteration, etc.  Note that
            several Levenberg-Marquardt attempts can be made in a
            single iteration.
            Default value: 1

   PARINFO - Provides a mechanism for more sophisticated constraints
             to be placed on parameter values.  When PARINFO is not
             passed, then it is assumed that all parameters are free
             and unconstrained.  Values in PARINFO are never 
             modified during a call to MPFIT.

             See description above for the structure of PARINFO.

             Default value:  all parameters are free and unconstrained.

   PERROR - The formal 1-sigma errors in each parameter, computed
            from the covariance matrix.  If a parameter is held
            fixed, or if it touches a boundary, then the error is
            reported as zero.

            If the fit is unweighted (i.e. no errors were given, or
            the weights were uniformly set to unity), then PERROR
            will probably not represent the true parameter
            uncertainties.  

            *If* you can assume that the true reduced chi-squared
            value is unity -- meaning that the fit is implicitly
            assumed to be of good quality -- then the estimated
            parameter uncertainties can be computed by scaling PERROR
            by the measured chi-squared value.

              DOF     = N_ELEMENTS(X) - N_ELEMENTS(PARMS) ; deg of freedom
              PCERROR = PERROR * SQRT(BESTNORM / DOF)   ; scaled uncertainties

   QUIET - set this keyword when no textual output should be printed
           by MPFIT

   STATUS - an integer status code is returned.  All values other
            than zero can represent success.  It can have one of the
            following values:

	   0  improper input parameters.
         
	   1  both actual and predicted relative reductions
	      in the sum of squares are at most FTOL.
         
	   2  relative error between two consecutive iterates
	      is at most XTOL
         
	   3  conditions for STATUS = 1 and STATUS = 2 both hold.
         
	   4  the cosine of the angle between fvec and any
	      column of the jacobian is at most GTOL in
	      absolute value.
         
	   5  the maximum number of iterations has been reached
         
	   6  FTOL is too small. no further reduction in
	      the sum of squares is possible.
         
	   7  XTOL is too small. no further improvement in
	      the approximate solution x is possible.
         
	   8  GTOL is too small. fvec is orthogonal to the
	      columns of the jacobian to machine precision.

   WEIGHTS - Array of weights to be used in calculating the
             chi-squared value.  If WEIGHTS is specified then the ERR
             parameter is ignored.  The chi-squared value is computed
             as follows:

                CHISQ = TOTAL( (Y-MYFUNCT(X,P))^2 * ABS(WEIGHTS) )

             Here are common values of WEIGHTS:

                1D/ERR^2 - Normal weighting (ERR is the measurement error)
                1D/Y     - Poisson weighting (counting statistics)
                1D       - Unweighted

   XTOL - a nonnegative input variable. Termination occurs when the
          relative error between two consecutive iterates is at most
          XTOL (and STATUS is accordingly set to 2 or 3).  Therefore,
          XTOL measures the relative error desired in the approximate
          solution.  Default: 1D-10

   YFIT - the best-fit model function, as returned by MYFUNCT.

   
 EXAMPLE:

   ; First, generate some synthetic data
   npts = 200
   x  = dindgen(npts) * 0.1 - 10.                  ; Independent variable 
   yi = gauss1(x, [2.2D, 1.4, 3000.])              ; "Ideal" Y variable
   y  = yi + randomn(seed, npts) * sqrt(1000. + yi); Measured, w/ noise
   sy = sqrt(1000.D + y)                           ; Poisson errors

   ; Now fit a Gaussian to see how well we can recover
   p0 = [1.D, 1., 1000.]                   ; Initial guess (cent, width, area)
   p = mpfitfun('GAUSS1', x, y, sy, p0)    ; Fit a function
   print, p

   Generates a synthetic data set with a Gaussian peak, and Poisson
   statistical uncertainty.  Then the same function is fitted to the
   data (with different starting parameters) to see how close we can
   get.


 COMMON BLOCKS:

   COMMON MPFIT_ERROR, ERROR_CODE

     User routines may stop the fitting process at any time by
     setting an error condition.  This condition may be set in either
     the user's model computation routine (MYFUNCT), or in the
     iteration procedure (ITERPROC).

     To stop the fitting, the above common block must be declared,
     and ERROR_CODE must be set to a negative number.  After the user
     procedure or function returns, MPFIT checks the value of this
     common block variable and exits immediately if the error
     condition has been set.  By default the value of ERROR_CODE is
     zero, indicating a successful function/procedure call.

 REFERENCES:

   MINPACK-1, Jorge More', available from netlib (www.netlib.org).
   "Optimization Software Guide," Jorge More' and Stephen Wright, 
     SIAM, *Frontiers in Applied Mathematics*, Number 14.

 MODIFICATION HISTORY:
   Written, Apr-Jul 1998, CM
   Added PERROR keyword, 04 Aug 1998, CM
   Added COVAR keyword, 20 Aug 1998, CM
   Added ITER output keyword, 05 Oct 1998
      D.L Windt, Bell Labs, windt@bell-labs.com;
   Added ability to return model function in YFIT, 09 Nov 1998
   Analytical derivatives allowed via AUTODERIVATIVE keyword, 09 Nov 1998
   Parameter values can be tied to others, 09 Nov 1998
   Cosmetic documentation updates, 16 Apr 1999, CM
   More cosmetic documentation updates, 14 May 1999, CM
   Made sure to update STATUS, 25 Sep 1999, CM
   Added WEIGHTS keyword, 25 Sep 1999, CM
   Changed from handles to common blocks, 25 Sep 1999, CM
     - commons seem much cleaner and more logical in this case.
   Alphabetized documented keywords, 02 Oct 1999, CM
   Added QUERY keyword and query checking of MPFIT, 29 Oct 1999, CM
   Corrected EXAMPLE (offset of 1000), 30 Oct 1999, CM
   Check to be sure that X and Y are present, 02 Nov 1999, CM
   Documented PERROR for unweighted fits, 03 Nov 1999, CM
   Changed to ERROR_CODE for error condition, 28 Jan 2000, CM
   Corrected errors in EXAMPLE, 26 Mar 2000, CM
   Copying permission terms have been liberalized, 26 Mar 2000, CM
   Propagated improvements from MPFIT, 17 Dec 2000, CM
   Added CASH statistic, 10 Jan 2001
   Added NFREE and NPEGGED keywords, 11 Sep 2002, CM
   Documented RELSTEP field of PARINFO (!!), CM, 25 Oct 2002
   Add DOF keyword to return degrees of freedom, CM, 23 June 2003
   Convert to IDL 5 array syntax (!), 16 Jul 2006, CM

  $Id: mpfitfun.pro,v 2.2 2006/09/28 13:39:25 bdavis Exp $

(See src/idl_cvs/mpfitfun.pro)


MPFITPEAK

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

 AUTHOR:
   Craig B. Markwardt, NASA/GSFC Code 662, Greenbelt, MD 20770
   craigm@lheamail.gsfc.nasa.gov
   UPDATED VERSIONs can be found on my WEB PAGE: 
      http://cow.physics.wisc.edu/~craigm/idl/idl.html

 PURPOSE:
   Fit a gaussian, lorentzian or Moffat model to data

 MAJOR TOPICS:
   Curve and Surface Fitting

 CALLING SEQUENCE:
   yfit = MPFITPEAK(X, Y, A, NTERMS=nterms, ...)

 DESCRIPTION:

   MPFITPEAK fits a gaussian, lorentzian or Moffat model using the
   non-linear least squares fitter MPFIT.  MPFITPEAK is meant to be a
   drop-in replacement for IDL's GAUSSFIT function (and requires
   MPFIT and MPFITFUN).

   The choice of the fitting function is determined by the keywords
   GAUSSIAN, LORENTZIAN and MOFFAT.  By default the gaussian model
   function is used.  [ The Moffat function is a modified Lorentzian
   with variable power law index. (Moffat, A. F. J. 1969, Astronomy &
   Astrophysics, v. 3, p. 455-461) ]

   The functional form of the baseline is determined by NTERMS and
   the function to be fitted.  NTERMS represents the total number of
   parameters, A, to be fitted.  The functional forms and the
   meanings of the parameters are described in this table:

                 GAUSSIAN#          Lorentzian#         Moffat#

   Model     A[0]*exp(-0.5*u^2)   A[0]/(u^2 + 1)   A[0]/(u^2 + 1)^A[3]

   A[0]         Peak Value          Peak Value        Peak Value
   A[1]        Peak Centroid       Peak Centroid     Peak Centroid
   A[2]       Gaussian Sigma           HWHM%             HWHM%
   A[3]         + A[3]    *          + A[3]   *      Moffat Index
   A[4]         + A[4]*x  *          + A[4]*x *         + A[4]   *
   A[5]                                                 + A[5]*x *

   Notes: # u = (x - A[1])/A[2]
          % Half-width at half maximum
          * Optional depending on NTERMS

   By default the initial starting values for the parameters A are
   estimated from the data.  However, explicit starting values can be
   supplied using the ESTIMATES keyword.  Also, error or weighting
   values can optionally be provided; otherwise the fit is
   unweighted.

   MPFITPEAK fits the peak value of the curve.  The area under a
   gaussian peak is A[0]*A[2]*SQRT(2*!DPI); the area under a
   lorentzian peak is A[0]*A[2]*!DPI.

 RESTRICTIONS:

   If no starting parameter ESTIMATES are provided, then MPFITPEAK
   attempts to estimate them from the data.  This is not a perfect
   science; however, the author believes that the technique
   implemented here is more robust than the one used in IDL's
   GAUSSFIT.  The author has tested cases of strong peaks, noisy
   peaks and broad peaks, all with success.

   Users should be aware that if the baseline term contains a strong
   linear component then the automatic estimation may fail.  For
   automatic estimation to work the peak amplitude should dominate
   over the the maximum baseline.

 INPUTS:
   X - Array of independent variable values, whose values should
       monotonically increase.

   Y - Array of "measured" dependent variable values.  Y should have
       the same data type and dimension as X.


 OUTPUTS:
   A - Upon return, an array of NTERMS best fit parameter values.
       See the table above for the meanings of each parameter
       element.


 RETURNS:

   Returns the best fitting model function.

 KEYWORDS:

   ** NOTE ** Additional keywords such as PARINFO, BESTNORM, and
              STATUS are accepted by MPFITPEAK but not documented
              here.  Please see the documentation for MPFIT for the
              description of these advanced options.

   CHISQ - the value of the summed squared residuals for the
           returned parameter values.

   DOF - number of degrees of freedom, computed as
             DOF = N_ELEMENTS(DEVIATES) - NFREE
         Note that this doesn't account for pegged parameters (see
         NPEGGED).

   ERROR - upon input, the measured 1-sigma uncertainties in the "Y"
           values.  If no ERROR or WEIGHTS are given, then the fit is
           unweighted.

   ESTIMATES - Array of starting values for each parameter of the
               model.  The number of parameters should at least be
               three (four for Moffat), and if less than NTERMS, will
               be extended with zeroes.
               Default: parameter values are estimated from data.

   GAUSSIAN - if set, fit a gaussian model function.  The Default.
   LORENTZIAN - if set, fit a lorentzian model function.
   MOFFAT - if set, fit a Moffat model function.

   MEASURE_ERRORS - synonym for ERRORS, for consistency with built-in
                    IDL fitting routines.

   NEGATIVE / POSITIVE - if set, and ESTIMATES is not provided, then
                         MPFITPEAK will assume that a
                         negative/positive peak is present.
                         Default: determined automatically

   NFREE - the number of free parameters in the fit.  This includes
           parameters which are not FIXED and not TIED, but it does
           include parameters which are pegged at LIMITS.

   NTERMS - An integer describing the number of fitting terms.
            NTERMS must have a minimum value, but can optionally be
            larger depending on the desired baseline.  

            For gaussian and lorentzian models, NTERMS must be three
            (zero baseline), four (constant baseline) or five (linear
            baseline).  Default: 4

            For the Moffat model, NTERMS must be four (zero
            baseline), five (constant baseline), or six (linear
            baseline).  Default: 5

   PERROR - upon return, the 1-sigma uncertainties of the parameter
            values A.  These values are only meaningful if the ERRORS
            or WEIGHTS keywords are specified properly.

            If the fit is unweighted (i.e. no errors were given, or
            the weights were uniformly set to unity), then PERROR
            will probably not represent the true parameter
            uncertainties.  

            *If* you can assume that the true reduced chi-squared
            value is unity -- meaning that the fit is implicitly
            assumed to be of good quality -- then the estimated
            parameter uncertainties can be computed by scaling PERROR
            by the measured chi-squared value.

              DOF     = N_ELEMENTS(X) - N_ELEMENTS(PARMS) ; deg of freedom
              PCERROR = PERROR * SQRT(BESTNORM / DOF)   ; scaled uncertainties

   QUIET - if set then diagnostic fitting messages are suppressed.
           Default: QUIET=1 (i.e., no diagnostics)

   SIGMA - synonym for PERROR (1-sigma parameter uncertainties), for
           compatibility with GAUSSFIT.  Do not confuse this with the
           Gaussian "sigma" width parameter.

   WEIGHTS - Array of weights to be used in calculating the
             chi-squared value.  If WEIGHTS is specified then the ERROR
             keyword is ignored.  The chi-squared value is computed
             as follows:

                CHISQ = TOTAL( (Y-MYFUNCT(X,P))^2 * ABS(WEIGHTS) )

             Here are common values of WEIGHTS:

                1D/ERR^2 - Normal weighting (ERR is the measurement error)
                1D/Y     - Poisson weighting (counting statistics)
                1D       - Unweighted

             The ERROR keyword takes precedence over any WEIGHTS
             keyword values.  If no ERROR or WEIGHTS are given, then
             the fit is unweighted.

   YERROR - upon return, the root-mean-square variance of the
            residuals.


 EXAMPLE:

   ; First, generate some synthetic data
   npts = 200
   x  = dindgen(npts) * 0.1 - 10.                  ; Independent variable 
   yi = gauss1(x, [2.2D, 1.4, 3000.]) + 1000       ; "Ideal" Y variable
   y  = yi + randomn(seed, npts) * sqrt(1000. + yi); Measured, w/ noise
   sy = sqrt(1000.D + y)                           ; Poisson errors

   ; Now fit a Gaussian to see how well we can recover the original
   yfit = mpfitpeak(x, y, a, error=sy)
   print, p

   Generates a synthetic data set with a Gaussian peak, and Poisson
   statistical uncertainty.  Then the same function is fitted to the
   data.

 REFERENCES:

   MINPACK-1, Jorge More', available from netlib (www.netlib.org).
   "Optimization Software Guide," Jorge More' and Stephen Wright, 
     SIAM, *Frontiers in Applied Mathematics*, Number 14.

 MODIFICATION HISTORY:

   New algorithm for estimating starting values, CM, 31 Oct 1999
   Documented, 02 Nov 1999
   Small documentation fixes, 02 Nov 1999
   Slight correction to calculation of dx, CM, 02 Nov 1999
   Documented PERROR for unweighted fits, 03 Nov 1999, CM
   Copying permission terms have been liberalized, 26 Mar 2000, CM
   Change requirements on # elements in X and Y, 20 Jul 2000, CM
      (thanks to David Schlegel )
   Added documentation on area under curve, 29 Aug 2000, CM
   Added POSITIVE and NEGATIVE keywords, 17 Nov 2000, CM
   Added reference to Moffat paper, 10 Jan 2001, CM
   Added usage message, 26 Jul 2001, CM
   Documentation clarification, 05 Sep 2001, CM
   Make more consistent with comparable IDL routines, 30 Jun 2003, CM
   Assumption of sorted data was removed, CM, 06 Sep 2003, CM
   Add some defensive code against divide by zero, 30 Nov 2005, CM
   Add some defensive code against all Y values equal to each other,
     17 Apr 2005, CM
   Convert to IDL 5 array syntax (!), 16 Jul 2006, CM

  $Id: mpfitpeak.pro,v 2.1 2006/09/28 15:40:24 bdavis Exp $

(See src/idl_cvs/mpfitpeak.pro)


MPFIT

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

 AUTHOR:
   Craig B. Markwardt, NASA/GSFC Code 662, Greenbelt, MD 20770
   craigm@lheamail.gsfc.nasa.gov
   UPDATED VERSIONs can be found on my WEB PAGE: 
      http://cow.physics.wisc.edu/~craigm/idl/idl.html

 PURPOSE:
   Perform Levenberg-Marquardt least-squares minimization (MINPACK-1)

 MAJOR TOPICS:
   Curve and Surface Fitting

 CALLING SEQUENCE:
   parms = MPFIT(MYFUNCT, start_parms, FUNCTARGS=fcnargs, NFEV=nfev,
                 MAXITER=maxiter, ERRMSG=errmsg, NPRINT=nprint, QUIET=quiet, 
                 FTOL=ftol, XTOL=xtol, GTOL=gtol, NITER=niter, 
                 STATUS=status, ITERPROC=iterproc, ITERARGS=iterargs,
                 COVAR=covar, PERROR=perror, BESTNORM=bestnorm,
                 PARINFO=parinfo)

 DESCRIPTION:

  MPFIT uses the Levenberg-Marquardt technique to solve the
  least-squares problem.  In its typical use, MPFIT will be used to
  fit a user-supplied function (the "model") to user-supplied data
  points (the "data") by adjusting a set of parameters.  MPFIT is
  based upon MINPACK-1 (LMDIF.F) by More' and collaborators.

  For example, a researcher may think that a set of observed data
  points is best modelled with a Gaussian curve.  A Gaussian curve is
  parameterized by its mean, standard deviation and normalization.
  MPFIT will, within certain constraints, find the set of parameters
  which best fits the data.  The fit is "best" in the least-squares
  sense; that is, the sum of the weighted squared differences between
  the model and data is minimized.

  The Levenberg-Marquardt technique is a particular strategy for
  iteratively searching for the best fit.  This particular
  implementation is drawn from MINPACK-1 (see NETLIB), and seems to
  be more robust than routines provided with IDL.  This version
  allows upper and lower bounding constraints to be placed on each
  parameter, or the parameter can be held fixed.

  The IDL user-supplied function should return an array of weighted
  deviations between model and data.  In a typical scientific problem
  the residuals should be weighted so that each deviate has a
  gaussian sigma of 1.0.  If X represents values of the independent
  variable, Y represents a measurement for each value of X, and ERR
  represents the error in the measurements, then the deviates could
  be calculated as follows:

    DEVIATES = (Y - F(X)) / ERR

  where F is the analytical function representing the model.  You are
  recommended to use the convenience functions MPFITFUN and
  MPFITEXPR, which are driver functions that calculate the deviates
  for you.  If ERR are the 1-sigma uncertainties in Y, then

    TOTAL( DEVIATES^2 ) 

  will be the total chi-squared value.  MPFIT will minimize the
  chi-square value.  The values of X, Y and ERR are passed through
  MPFIT to the user-supplied function via the FUNCTARGS keyword.

  Simple constraints can be placed on parameter values by using the
  PARINFO keyword to MPFIT.  See below for a description of this
  keyword.

  MPFIT does not perform more general optimization tasks.  See TNMIN
  instead.  MPFIT is customized, based on MINPACK-1, to the
  least-squares minimization problem.

 USER FUNCTION

  The user must define a function which returns the appropriate
  values as specified above.  The function should return the weighted
  deviations between the model and the data.  For applications which
  use finite-difference derivatives -- the default -- the user
  function should be declared in the following way:

    FUNCTION MYFUNCT, p, X=x, Y=y, ERR=err
     ; Parameter values are passed in "p"
     model = F(x, p)
     return, (y-model)/err
    END

  See below for applications with analytical derivatives.

  The keyword parameters X, Y, and ERR in the example above are
  suggestive but not required.  Any parameters can be passed to
  MYFUNCT by using the FUNCTARGS keyword to MPFIT.  Use MPFITFUN and
  MPFITEXPR if you need ideas on how to do that.  The function *must*
  accept a parameter list, P.
  
  In general there are no restrictions on the number of dimensions in
  X, Y or ERR.  However the deviates *must* be returned in a
  one-dimensional array, and must have the same type (float or
  double) as the input arrays.

  User functions may also indicate a fatal error condition using the
  ERROR_CODE common block variable, as described below under the
  MPFIT_ERROR common block definition (by setting ERROR_CODE to a
  number between -15 and -1).

 ANALYTIC DERIVATIVES
 
  In the search for the best-fit solution, MPFIT by default
  calculates derivatives numerically via a finite difference
  approximation.  The user-supplied function need not calculate the
  derivatives explicitly.  However, if you desire to compute them
  analytically, then the AUTODERIVATIVE=0 keyword must be passed.  As
  a practical matter, it is often sufficient and even faster to allow
  MPFIT to calculate the derivatives numerically, and so
  AUTODERIVATIVE=0 is not necessary.

  Also, the user function must be declared with one additional
  parameter, as follows:

    FUNCTION MYFUNCT, p, dp, X=x, Y=y, ERR=err
     model = F(x, p)
     
     if n_params() GT 1 then begin
       ; Compute derivatives
       dp = make_array(n_elements(x), n_elements(p), value=x[0]*0)
       for i = 0, n_elements(p)-1 do $
         dp(*,i) = FGRAD(x, p, i)
     endif
    
     return, (y-model)/err
    END

  where FGRAD(x, p, i) is a user function which must compute the
  derivative of the model with respect to parameter P(i) at X.  When
  finite differencing is used for computing derivatives (ie, when
  AUTODERIVATIVE=1), the parameter DP is not passed.  Therefore
  functions can use N_PARAMS() to indicate whether they must compute
  the derivatives or not.

  Derivatives should be returned in the DP array. DP should be an m x
  n array, where m is the number of data points and n is the number
  of parameters.  dp[i,j] is the derivative at the ith point with
  respect to the jth parameter.  
  
  The derivatives with respect to fixed parameters are ignored; zero
  is an appropriate value to insert for those derivatives.  Upon
  input to the user function, DP is set to a vector with the same
  length as P, with a value of 1 for a parameter which is free, and a
  value of zero for a parameter which is fixed (and hence no
  derivative needs to be calculated).  This input vector may be
  overwritten as needed.

  If the data is higher than one dimensional, then the *last*
  dimension should be the parameter dimension.  Example: fitting a
  50x50 image, "dp" should be 50x50xNPAR.
  
 CONSTRAINING PARAMETER VALUES WITH THE PARINFO KEYWORD

  The behavior of MPFIT can be modified with respect to each
  parameter to be fitted.  A parameter value can be fixed; simple
  boundary constraints can be imposed; limitations on the parameter
  changes can be imposed; properties of the automatic derivative can
  be modified; and parameters can be tied to one another.

  These properties are governed by the PARINFO structure, which is
  passed as a keyword parameter to MPFIT.

  PARINFO should be an array of structures, one for each parameter.
  Each parameter is associated with one element of the array, in
  numerical order.  The structure can have the following entries
  (none are required):
  
     .VALUE - the starting parameter value (but see the START_PARAMS
              parameter for more information).
  
     .FIXED - a boolean value, whether the parameter is to be held
              fixed or not.  Fixed parameters are not varied by
              MPFIT, but are passed on to MYFUNCT for evaluation.
  
     .LIMITED - a two-element boolean array.  If the first/second
                element is set, then the parameter is bounded on the
                lower/upper side.  A parameter can be bounded on both
                sides.  Both LIMITED and LIMITS must be given
                together.
  
     .LIMITS - a two-element float or double array.  Gives the
               parameter limits on the lower and upper sides,
               respectively.  Zero, one or two of these values can be
               set, depending on the values of LIMITED.  Both LIMITED
               and LIMITS must be given together.
  
     .PARNAME - a string, giving the name of the parameter.  The
                fitting code of MPFIT does not use this tag in any
                way.  However, the default ITERPROC will print the
                parameter name if available.
  
     .STEP - the step size to be used in calculating the numerical
             derivatives.  If set to zero, then the step size is
             computed automatically.  Ignored when AUTODERIVATIVE=0.
             This value is superceded by the RELSTEP value.

     .RELSTEP - the *relative* step size to be used in calculating
                the numerical derivatives.  This number is the
                fractional size of the step, compared to the
                parameter value.  This value supercedes the STEP
                setting.  If the parameter is zero, then a default
                step size is chosen.

     .MPSIDE - the sidedness of the finite difference when computing
               numerical derivatives.  This field can take four
               values:

                  0 - one-sided derivative computed automatically
                  1 - one-sided derivative (f(x+h) - f(x)  )/h
                 -1 - one-sided derivative (f(x)   - f(x-h))/h
                  2 - two-sided derivative (f(x+h) - f(x-h))/(2*h)

              Where H is the STEP parameter described above.  The
              "automatic" one-sided derivative method will chose a
              direction for the finite difference which does not
              violate any constraints.  The other methods do not
              perform this check.  The two-sided method is in
              principle more precise, but requires twice as many
              function evaluations.  Default: 0.

     .MPMAXSTEP - the maximum change to be made in the parameter
                  value.  During the fitting process, the parameter
                  will never be changed by more than this value in
                  one iteration.

                  A value of 0 indicates no maximum.  Default: 0.
  
     .TIED - a string expression which "ties" the parameter to other
             free or fixed parameters as an equality constraint.  Any
             expression involving constants and the parameter array P
             are permitted.
             Example: if parameter 2 is always to be twice parameter
             1 then use the following: parinfo[2].tied = '2 * P[1]'.
             Since they are totally constrained, tied parameters are
             considered to be fixed; no errors are computed for them.
             [ NOTE: the PARNAME can't be used in expressions. ]

     .MPPRINT - if set to 1, then the default ITERPROC will print the
                parameter value.  If set to 0, the parameter value
                will not be printed.  This tag can be used to
                selectively print only a few parameter values out of
                many.  Default: 1 (all parameters printed)

     .MPFORMAT - IDL format string to print the parameter within
                 ITERPROC.  Default: '(G20.6)' An empty string will
                 also use the default.

  
  Future modifications to the PARINFO structure, if any, will involve
  adding structure tags beginning with the two letters "MP".
  Therefore programmers are urged to avoid using tags starting with
  the same letters; otherwise they are free to include their own
  fields within the PARINFO structure, and they will be ignored.
  
  PARINFO Example:
  parinfo = replicate({value:0.D, fixed:0, limited:[0,0], $
                       limits:[0.D,0]}, 5)
  parinfo[0].fixed = 1
  parinfo[4].limited(0) = 1
  parinfo[4].limits(0)  = 50.D
  parinfo[*].value = [5.7D, 2.2, 500., 1.5, 2000.]
  
  A total of 5 parameters, with starting values of 5.7,
  2.2, 500, 1.5, and 2000 are given.  The first parameter
  is fixed at a value of 5.7, and the last parameter is
  constrained to be above 50.


 HARD-TO-COMPUTE FUNCTIONS: "EXTERNAL" EVALUATION

  The normal mode of operation for MPFIT is for the user to pass a
  function name, and MPFIT will call the user function multiple times
  as it iterates toward a solution.

  Some user functions are particularly hard to compute using the
  standard model of MPFIT.  Usually these are functions that depend
  on a large amount of external data, and so it is not feasible, or
  at least highly impractical, to have MPFIT call it.  In those cases
  it may be possible to use the "(EXTERNAL)" evaluation option.

  In this case the user is responsible for making all function *and
  derivative* evaluations.  The function and Jacobian data are passed
  in through the EXTERNAL_FVEC and EXTERNAL_FJAC keywords,
  respectively.  The user indicates the selection of this option by
  specifying a function name (MYFUNCT) of "(EXTERNAL)".  No
  user-function calls are made when EXTERNAL evaluation is being
  used.

  At the end of each iteration, control returns to the user, who must
  reevaluate the function at its new parameter values.  Users should
  check the return value of the STATUS keyword, where a value of 9
  indicates the user should supply more data for the next iteration,
  and re-call MPFIT.  The user may refrain from calling MPFIT
  further; as usual, STATUS will indicate when the solution has
  converged and no more iterations are required.

  Because MPFIT must maintain its own data structures between calls,
  the user must also pass a named variable to the EXTERNAL_STATE
  keyword.  This variable must be maintained by the user, but not
  changed, throughout the fitting process.  When no more iterations
  are desired, the named variable may be discarded.


 INPUTS:
   MYFUNCT - a string variable containing the name of the function to
             be minimized.  The function should return the weighted
             deviations between the model and the data, as described
             above.

             For EXTERNAL evaluation of functions, this parameter
             should be set to a value of "(EXTERNAL)".

   START_PARAMS - An array of starting values for each of the
                  parameters of the model.  The number of parameters
                  should be fewer than the number of measurements.
                  Also, the parameters should have the same data type
                  as the measurements (double is preferred).

                  This parameter is optional if the PARINFO keyword
                  is used (but see PARINFO).  The PARINFO keyword
                  provides a mechanism to fix or constrain individual
                  parameters.  If both START_PARAMS and PARINFO are
                  passed, then the starting *value* is taken from
                  START_PARAMS, but the *constraints* are taken from
                  PARINFO.
 
 RETURNS:

   Returns the array of best-fit parameters.


 KEYWORD PARAMETERS:

   AUTODERIVATIVE - If this is set, derivatives of the function will
                    be computed automatically via a finite
                    differencing procedure.  If not set, then MYFUNCT
                    must provide the (analytical) derivatives.
                    Default: set (=1) 
                    NOTE: to supply your own analytical derivatives,
                      explicitly pass AUTODERIVATIVE=0

   BESTNORM - the value of the summed squared weighted residuals for
              the returned parameter values, i.e. TOTAL(DEVIATES^2).

   COVAR - the covariance matrix for the set of parameters returned
           by MPFIT.  The matrix is NxN where N is the number of
           parameters.  The square root of the diagonal elements
           gives the formal 1-sigma statistical errors on the
           parameters IF errors were treated "properly" in MYFUNC.
           Parameter errors are also returned in PERROR.

           To compute the correlation matrix, PCOR, use this example:
           IDL> PCOR = COV * 0
           IDL> FOR i = 0, n-1 DO FOR j = 0, n-1 DO $
                PCOR[i,j] = COV[i,j]/sqrt(COV[i,i]*COV[j,j])

           If NOCOVAR is set or MPFIT terminated abnormally, then
           COVAR is set to a scalar with value !VALUES.D_NAN.

   DOF - number of degrees of freedom, computed as
             DOF = N_ELEMENTS(DEVIATES) - NFREE
         Note that this doesn't account for pegged parameters (see
         NPEGGED).

   ERRMSG - a string error or warning message is returned.

   EXTERNAL_FVEC - upon input, the function values, evaluated at
                   START_PARAMS.  This should be an M-vector, where M
                   is the number of data points.

   EXTERNAL_FJAC - upon input, the Jacobian array of partial
                   derivative values.  This should be a M x N array,
                   where M is the number of data points and N is the
                   number of parameters.  NOTE: that all FIXED or
                   TIED parameters must *not* be included in this
                   array.

   EXTERNAL_STATE - a named variable to store MPFIT-related state
                    information between iterations (used in input and
                    output to MPFIT).  The user must not manipulate
                    or discard this data until the final iteration is
                    performed.

   FASTNORM - set this keyword to select a faster algorithm to
              compute sum-of-square values internally.  For systems
              with large numbers of data points, the standard
              algorithm can become prohibitively slow because it
              cannot be vectorized well.  By setting this keyword,
              MPFIT will run faster, but it will be more prone to
              floating point overflows and underflows.  Thus, setting
              this keyword may sacrifice some stability in the
              fitting process.
              
   FTOL - a nonnegative input variable. Termination occurs when both
          the actual and predicted relative reductions in the sum of
          squares are at most FTOL (and STATUS is accordingly set to
          1 or 3).  Therefore, FTOL measures the relative error
          desired in the sum of squares.  Default: 1D-10

   FUNCTARGS - A structure which contains the parameters to be passed
               to the user-supplied function specified by MYFUNCT via
               the _EXTRA mechanism.  This is the way you can pass
               additional data to your user-supplied function without
               using common blocks.

               Consider the following example:
                if FUNCTARGS = { XVAL:[1.D,2,3], YVAL:[1.D,4,9],
                                 ERRVAL:[1.D,1,1] }
                then the user supplied function should be declared
                like this:
                FUNCTION MYFUNCT, P, XVAL=x, YVAL=y, ERRVAL=err

               By default, no extra parameters are passed to the
               user-supplied function, but your function should
               accept *at least* one keyword parameter.  [ This is to
               accomodate a limitation in IDL's _EXTRA
               parameter-passing mechanism. ]

   GTOL - a nonnegative input variable. Termination occurs when the
          cosine of the angle between fvec and any column of the
          jacobian is at most GTOL in absolute value (and STATUS is
          accordingly set to 4). Therefore, GTOL measures the
          orthogonality desired between the function vector and the
          columns of the jacobian.  Default: 1D-10

   ITERARGS - The keyword arguments to be passed to ITERPROC via the
              _EXTRA mechanism.  This should be a structure, and is
              similar in operation to FUNCTARGS.
              Default: no arguments are passed.

   ITERPRINT - The name of an IDL procedure, equivalent to PRINT,
               that ITERPROC will use to render output.  ITERPRINT
               should be able to accept at least four positional
               arguments.  In addition, it should be able to accept
               the standard FORMAT keyword for output formatting; and
               the UNIT keyword, to redirect output to a logical file
               unit (default should be UNIT=1, standard output).
               These keywords are passed using the ITERARGS keyword
               above.  The ITERPRINT procedure must accept the _EXTRA
               keyword.  
               NOTE: that much formatting can be handled with the 
                     MPPRINT and MPFORMAT tags.
               Default: 'MPFIT_DEFPRINT' (default internal formatter)

   ITERPROC - The name of a procedure to be called upon each NPRINT
              iteration of the MPFIT routine.  ITERPROC is always
              called in the final iteration.  It should be declared
              in the following way:

              PRO ITERPROC, MYFUNCT, p, iter, fnorm, FUNCTARGS=fcnargs, $
                PARINFO=parinfo, QUIET=quiet, DOF=dof, PFORMAT=pformat, $
                UNIT=unit, ...
                ; perform custom iteration update
              END
         
              ITERPROC must either accept all three keyword
              parameters (FUNCTARGS, PARINFO and QUIET), or at least
              accept them via the _EXTRA keyword.
          
              MYFUNCT is the user-supplied function to be minimized,
              P is the current set of model parameters, ITER is the
              iteration number, and FUNCTARGS are the arguments to be
              passed to MYFUNCT.  FNORM should be the chi-squared
              value.  QUIET is set when no textual output should be
              printed.  DOF is the number of degrees of freedom,
              normally the number of points less the number of free
              parameters.  See below for documentation of PARINFO.
              PFORMAT is the default parameter value format.  UNIT is
              passed on to the ITERPRINT procedure, and should
              indicate the file unit where log output will be sent
              (default: standard output).

              In implementation, ITERPROC can perform updates to the
              terminal or graphical user interface, to provide
              feedback while the fit proceeds.  If the fit is to be
              stopped for any reason, then ITERPROC should set the
              common block variable ERROR_CODE to negative value
              between -15 and -1 (see MPFIT_ERROR common block
              below).  In principle, ITERPROC should probably not
              modify the parameter values, because it may interfere
              with the algorithm's stability.  In practice it is
              allowed.

              Default: an internal routine is used to print the
                       parameter values.

   ITERSTOP - Set this keyword if you wish to be able to stop the
              fitting by hitting the predefined ITERKEYSTOP key on
              the keyboard.  This only works if you use the default
              ITERPROC.

   ITERKEYSTOP - A keyboard key which will halt the fit (and if
                 ITERSTOP is set and the default ITERPROC is used).
                 ITERSTOPKEY may either be a one-character string
                 with the desired key, or a scalar integer giving the
                 ASCII code of the desired key.  
                 Default: 7b (control-g)

                 NOTE: the default value of ASCI 7 (control-G) cannot
                 be read in some windowing environments, so you must
                 change to a printable character like 'q'.

   MAXITER - The maximum number of iterations to perform.  If the
             number is exceeded, then the STATUS value is set to 5
             and MPFIT returns.
             Default: 200 iterations

   NFEV - the number of MYFUNCT function evaluations performed.

   NFREE - the number of free parameters in the fit.  This includes
           parameters which are not FIXED and not TIED, but it does
           include parameters which are pegged at LIMITS.

   NITER - the number of iterations completed.

   NOCOVAR - set this keyword to prevent the calculation of the
             covariance matrix before returning (see COVAR)

   NPEGGED - the number of free parameters which are pegged at a
             LIMIT.

   NPRINT - The frequency with which ITERPROC is called.  A value of
            1 indicates that ITERPROC is called with every iteration,
            while 2 indicates every other iteration, etc.  Be aware
            that several Levenberg-Marquardt attempts can be made in
            a single iteration.  Also, the ITERPROC is *always*
            called for the final iteration, regardless of the
            iteration number.
            Default value: 1

   PARINFO - Provides a mechanism for more sophisticated constraints
             to be placed on parameter values.  When PARINFO is not
             passed, then it is assumed that all parameters are free
             and unconstrained.  Values in PARINFO are never 
             modified during a call to MPFIT.

             See description above for the structure of PARINFO.

             Default value:  all parameters are free and unconstrained.

   PERROR - The formal 1-sigma errors in each parameter, computed
            from the covariance matrix.  If a parameter is held
            fixed, or if it touches a boundary, then the error is
            reported as zero.

            If the fit is unweighted (i.e. no errors were given, or
            the weights were uniformly set to unity), then PERROR
            will probably not represent the true parameter
            uncertainties.  

            *If* you can assume that the true reduced chi-squared
            value is unity -- meaning that the fit is implicitly
            assumed to be of good quality -- then the estimated
            parameter uncertainties can be computed by scaling PERROR
            by the measured chi-squared value.

              DOF     = N_ELEMENTS(X) - N_ELEMENTS(PARMS) ; deg of freedom
              PCERROR = PERROR * SQRT(BESTNORM / DOF)   ; scaled uncertainties

   QUIET - set this keyword when no textual output should be printed
           by MPFIT

   RESDAMP - a scalar number, indicating the cut-off value of
             residuals where "damping" will occur.  Residuals with
             magnitudes greater than this number will be replaced by
             their logarithm.  This partially mitigates the so-called
             large residual problem inherent in least-squares solvers
             (as for the test problem CURVI, http://www.maxthis.com/-
             curviex.htm).  A value of 0 indicates no damping.
             Default: 0

             Note: RESDAMP doesn't work with AUTODERIV=0

   STATUS - an integer status code is returned.  All values greater
            than zero can represent success (however STATUS EQ 5 may
            indicate failure to converge).  It can have one of the
            following values:

        -16  a parameter or function value has become infinite or an
             undefined number.  This is usually a consequence of
             numerical overflow in the user's model function, which
             must be avoided.

        -15 to -1 
             these are error codes that either MYFUNCT or ITERPROC
             may return to terminate the fitting process (see
             description of MPFIT_ERROR common below).  If either
             MYFUNCT or ITERPROC set ERROR_CODE to a negative number,
             then that number is returned in STATUS.  Values from -15
             to -1 are reserved for the user functions and will not
             clash with MPFIT.

	   0  improper input parameters.
         
	   1  both actual and predicted relative reductions
	      in the sum of squares are at most FTOL.
         
	   2  relative error between two consecutive iterates
	      is at most XTOL
         
	   3  conditions for STATUS = 1 and STATUS = 2 both hold.
         
	   4  the cosine of the angle between fvec and any
	      column of the jacobian is at most GTOL in
	      absolute value.
         
	   5  the maximum number of iterations has been reached
         
	   6  FTOL is too small. no further reduction in
	      the sum of squares is possible.
         
	   7  XTOL is too small. no further improvement in
	      the approximate solution x is possible.
         
	   8  GTOL is too small. fvec is orthogonal to the
	      columns of the jacobian to machine precision.

          9  A successful single iteration has been completed, and
             the user must supply another "EXTERNAL" evaluation of
             the function and its derivatives.  This status indicator
             is neither an error nor a convergence indicator.

   XTOL - a nonnegative input variable. Termination occurs when the
          relative error between two consecutive iterates is at most
          XTOL (and STATUS is accordingly set to 2 or 3).  Therefore,
          XTOL measures the relative error desired in the approximate
          solution.  Default: 1D-10


 EXAMPLE:

   p0 = [5.7D, 2.2, 500., 1.5, 2000.]
   fa = {X:x, Y:y, ERR:err}
   p = mpfit('MYFUNCT', p0, functargs=fa)

   Minimizes sum of squares of MYFUNCT.  MYFUNCT is called with the X,
   Y, and ERR keyword parameters that are given by FUNCTARGS.  The
   resulting parameter values are returned in p.


 COMMON BLOCKS:

   COMMON MPFIT_ERROR, ERROR_CODE

     User routines may stop the fitting process at any time by
     setting an error condition.  This condition may be set in either
     the user's model computation routine (MYFUNCT), or in the
     iteration procedure (ITERPROC).

     To stop the fitting, the above common block must be declared,
     and ERROR_CODE must be set to a negative number.  After the user
     procedure or function returns, MPFIT checks the value of this
     common block variable and exits immediately if the error
     condition has been set.  This value is also returned in the
     STATUS keyword: values of -1 through -15 are reserved error
     codes for the user routines.  By default the value of ERROR_CODE
     is zero, indicating a successful function/procedure call.

   COMMON MPFIT_PROFILE
   COMMON MPFIT_MACHAR
   COMMON MPFIT_CONFIG

     These are undocumented common blocks are used internally by
     MPFIT and may change in future implementations.

 THEORY OF OPERATION:

   There are many specific strategies for function minimization.  One
   very popular technique is to use function gradient information to
   realize the local structure of the function.  Near a local minimum
   the function value can be taylor expanded about x0 as follows:

      f(x) = f(x0) + f'(x0) . (x-x0) + (1/2) (x-x0) . f''(x0) . (x-x0)
             -----   ---------------   -------------------------------  (1)
     Order    0th          1st                      2nd

   Here f'(x) is the gradient vector of f at x, and f''(x) is the
   Hessian matrix of second derivatives of f at x.  The vector x is
   the set of function parameters, not the measured data vector.  One
   can find the minimum of f, f(xm) using Newton's method, and
   arrives at the following linear equation:

      f''(x0) . (xm-x0) = - f'(x0)                            (2)

   If an inverse can be found for f''(x0) then one can solve for
   (xm-x0), the step vector from the current position x0 to the new
   projected minimum.  Here the problem has been linearized (ie, the
   gradient information is known to first order).  f''(x0) is
   symmetric n x n matrix, and should be positive definite.

   The Levenberg - Marquardt technique is a variation on this theme.
   It adds an additional diagonal term to the equation which may aid the
   convergence properties:

      (f''(x0) + nu I) . (xm-x0) = -f'(x0)                  (2a)

   where I is the identity matrix.  When nu is large, the overall
   matrix is diagonally dominant, and the iterations follow steepest
   descent.  When nu is small, the iterations are quadratically
   convergent.

   In principle, if f''(x0) and f'(x0) are known then xm-x0 can be
   determined.  However the Hessian matrix is often difficult or
   impossible to compute.  The gradient f'(x0) may be easier to
   compute, if even by finite difference techniques.  So-called
   quasi-Newton techniques attempt to successively estimate f''(x0)
   by building up gradient information as the iterations proceed.

   In the least squares problem there are further simplifications
   which assist in solving eqn (2).  The function to be minimized is
   a sum of squares:

       f = Sum(hi^2)                                         (3)

   where hi is the ith residual out of m residuals as described
   above.  This can be substituted back into eqn (2) after computing
   the derivatives:

       f'  = 2 Sum(hi  hi')     
       f'' = 2 Sum(hi' hj') + 2 Sum(hi hi'')                (4)

   If one assumes that the parameters are already close enough to a
   minimum, then one typically finds that the second term in f'' is
   negligible [or, in any case, is too difficult to compute].  Thus,
   equation (2) can be solved, at least approximately, using only
   gradient information.

   In matrix notation, the combination of eqns (2) and (4) becomes:

        hT' . h' . dx = - hT' . h                          (5)

   Where h is the residual vector (length m), hT is its transpose, h'
   is the Jacobian matrix (dimensions n x m), and dx is (xm-x0).  The
   user function supplies the residual vector h, and in some cases h'
   when it is not found by finite differences (see MPFIT_FDJAC2,
   which finds h and hT').  Even if dx is not the best absolute step
   to take, it does provide a good estimate of the best *direction*,
   so often a line minimization will occur along the dx vector
   direction.

   The method of solution employed by MINPACK is to form the Q . R
   factorization of h', where Q is an orthogonal matrix such that QT .
   Q = I, and R is upper right triangular.  Using h' = Q . R and the
   ortogonality of Q, eqn (5) becomes

        (RT . QT) . (Q . R) . dx = - (RT . QT) . h
                     RT . R . dx = - RT . QT . h         (6)
                          R . dx = - QT . h

   where the last statement follows because R is upper triangular.
   Here, R, QT and h are known so this is a matter of solving for dx.
   The routine MPFIT_QRFAC provides the QR factorization of h, with
   pivoting, and MPFIT_QRSOLV provides the solution for dx.
   
 REFERENCES:

   MINPACK-1, Jorge More', available from netlib (www.netlib.org).
   "Optimization Software Guide," Jorge More' and Stephen Wright, 
     SIAM, *Frontiers in Applied Mathematics*, Number 14.
   More', Jorge J., "The Levenberg-Marquardt Algorithm:
     Implementation and Theory," in *Numerical Analysis*, ed. Watson,
     G. A., Lecture Notes in Mathematics 630, Springer-Verlag, 1977.

 MODIFICATION HISTORY:
   Translated from MINPACK-1 in FORTRAN, Apr-Jul 1998, CM
   Fixed bug in parameter limits (x vs xnew), 04 Aug 1998, CM
   Added PERROR keyword, 04 Aug 1998, CM
   Added COVAR keyword, 20 Aug 1998, CM
   Added NITER output keyword, 05 Oct 1998
      D.L Windt, Bell Labs, windt@bell-labs.com;
   Made each PARINFO component optional, 05 Oct 1998 CM
   Analytical derivatives allowed via AUTODERIVATIVE keyword, 09 Nov 1998
   Parameter values can be tied to others, 09 Nov 1998
   Fixed small bugs (Wayne Landsman), 24 Nov 1998
   Added better exception error reporting, 24 Nov 1998 CM
   Cosmetic documentation changes, 02 Jan 1999 CM
   Changed definition of ITERPROC to be consistent with TNMIN, 19 Jan 1999 CM
   Fixed bug when AUTDERIVATIVE=0.  Incorrect sign, 02 Feb 1999 CM
   Added keyboard stop to MPFIT_DEFITER, 28 Feb 1999 CM
   Cosmetic documentation changes, 14 May 1999 CM
   IDL optimizations for speed & FASTNORM keyword, 15 May 1999 CM
   Tried a faster version of mpfit_enorm, 30 May 1999 CM
   Changed web address to cow.physics.wisc.edu, 14 Jun 1999 CM
   Found malformation of FDJAC in MPFIT for 1 parm, 03 Aug 1999 CM
   Factored out user-function call into MPFIT_CALL.  It is possible,
     but currently disabled, to call procedures.  The calling format
     is similar to CURVEFIT, 25 Sep 1999, CM
   Slightly changed mpfit_tie to be less intrusive, 25 Sep 1999, CM
   Fixed some bugs associated with tied parameters in mpfit_fdjac, 25
     Sep 1999, CM
   Reordered documentation; now alphabetical, 02 Oct 1999, CM
   Added QUERY keyword for more robust error detection in drivers, 29
     Oct 1999, CM
   Documented PERROR for unweighted fits, 03 Nov 1999, CM
   Split out MPFIT_RESETPROF to aid in profiling, 03 Nov 1999, CM
   Some profiling and speed optimization, 03 Nov 1999, CM
     Worst offenders, in order: fdjac2, qrfac, qrsolv, enorm.
     fdjac2 depends on user function, qrfac and enorm seem to be
     fully optimized.  qrsolv probably could be tweaked a little, but
     is still <10% of total compute time.
   Made sure that !err was set to 0 in MPFIT_DEFITER, 10 Jan 2000, CM
   Fixed small inconsistency in setting of QANYLIM, 28 Jan 2000, CM
   Added PARINFO field RELSTEP, 28 Jan 2000, CM
   Converted to MPFIT_ERROR common block for indicating error
     conditions, 28 Jan 2000, CM
   Corrected scope of MPFIT_ERROR common block, CM, 07 Mar 2000
   Minor speed improvement in MPFIT_ENORM, CM 26 Mar 2000
   Corrected case where ITERPROC changed parameter values and
     parameter values were TIED, CM 26 Mar 2000
   Changed MPFIT_CALL to modify NFEV automatically, and to support
     user procedures more, CM 26 Mar 2000
   Copying permission terms have been liberalized, 26 Mar 2000, CM
   Catch zero value of zero a(j,lj) in MPFIT_QRFAC, 20 Jul 2000, CM
      (thanks to David Schlegel )
   MPFIT_SETMACHAR is called only once at init; only one common block
     is created (MPFIT_MACHAR); it is now a structure; removed almost
     all CHECK_MATH calls for compatibility with IDL5 and !EXCEPT;
     profiling data is now in a structure too; noted some
     mathematical discrepancies in Linux IDL5.0, 17 Nov 2000, CM
   Some significant changes.  New PARINFO fields: MPSIDE, MPMINSTEP,
     MPMAXSTEP.  Improved documentation.  Now PTIED constraints are
     maintained in the MPCONFIG common block.  A new procedure to
     parse PARINFO fields.  FDJAC2 now computes a larger variety of
     one-sided and two-sided finite difference derivatives.  NFEV is
     stored in the MPCONFIG common now.  17 Dec 2000, CM
   Added check that PARINFO and XALL have same size, 29 Dec 2000 CM
   Don't call function in TERMINATE when there is an error, 05 Jan
     2000
   Check for float vs. double discrepancies; corrected implementation
     of MIN/MAXSTEP, which I still am not sure of, but now at least
     the correct behavior occurs *without* it, CM 08 Jan 2001
   Added SCALE_FCN keyword, to allow for scaling, as for the CASH
     statistic; added documentation about the theory of operation,
     and under the QR factorization; slowly I'm beginning to
     understand the bowels of this algorithm, CM 10 Jan 2001
   Remove MPMINSTEP field of PARINFO, for now at least, CM 11 Jan
     2001
   Added RESDAMP keyword, CM, 14 Jan 2001
   Tried to improve the DAMP handling a little, CM, 13 Mar 2001
   Corrected .PARNAME behavior in _DEFITER, CM, 19 Mar 2001
   Added checks for parameter and function overflow; a new STATUS
     value to reflect this; STATUS values of -15 to -1 are reserved
     for user function errors, CM, 03 Apr 2001
   DAMP keyword is now a TANH, CM, 03 Apr 2001
   Added more error checking of float vs. double, CM, 07 Apr 2001
   Fixed bug in handling of parameter lower limits; moved overflow
     checking to end of loop, CM, 20 Apr 2001
   Failure using GOTO, TERMINATE more graceful if FNORM1 not defined,
     CM, 13 Aug 2001
   Add MPPRINT tag to PARINFO, CM, 19 Nov 2001
   Add DOF keyword to DEFITER procedure, and print degrees of
     freedom, CM, 28 Nov 2001
   Add check to be sure MYFUNCT is a scalar string, CM, 14 Jan 2002
   Addition of EXTERNAL_FJAC, EXTERNAL_FVEC keywords; ability to save
     fitter's state from one call to the next; allow '(EXTERNAL)'
     function name, which implies that user will supply function and
     Jacobian at each iteration, CM, 10 Mar 2002
   Documented EXTERNAL evaluation code, CM, 10 Mar 2002
   Corrected signficant bug in the way that the STEP parameter, and
     FIXED parameters interacted (Thanks Andrew Steffl), CM, 02 Apr
     2002
   Allow COVAR and PERROR keywords to be computed, even in case of
     '(EXTERNAL)' function, 26 May 2002
   Add NFREE and NPEGGED keywords; compute NPEGGED; compute DOF using
     NFREE instead of n_elements(X), thanks to Kristian Kjaer, CM 11
     Sep 2002
   Hopefully PERROR is all positive now, CM 13 Sep 2002
   Documented RELSTEP field of PARINFO (!!), CM, 25 Oct 2002
   Error checking to detect missing start pars, CM 12 Apr 2003
   Add DOF keyword to return degrees of freedom, CM, 30 June 2003
   Always call ITERPROC in the final iteration; add ITERKEYSTOP
     keyword, CM, 30 June 2003
   Correct bug in MPFIT_LMPAR of singularity handling, which might
     likely be fatal for one-parameter fits, CM, 21 Nov 2003
     (with thanks to Peter Tuthill for the proper test case)
   Minor documentation adjustment, 03 Feb 2004, CM
   Correct small error in QR factorization when pivoting; document
     the return values of QRFAC when pivoting, 21 May 2004, CM
   Add MPFORMAT field to PARINFO, and correct behavior of interaction
     between MPPRINT and PARNAME in MPFIT_DEFITERPROC (thanks to Tim
     Robishaw), 23 May 2004, CM
   Add the ITERPRINT keyword to allow redirecting output, 26 Sep
     2004, CM
   Correct MAXSTEP behavior in case of a negative parameter, 26 Sep
     2004, CM
   Fix bug in the parsing of MINSTEP/MAXSTEP, 10 Apr 2005, CM
   Fix bug in the handling of upper/lower limits when the limit was
     negative (the fitting code would never "stick" to the lower
     limit), 29 Jun 2005, CM
   Small documentation update for the TIED field, 05 Sep 2005, CM
   Convert to IDL 5 array syntax (!), 16 Jul 2006, CM
   If MAXITER equals zero, then do the basic parameter checking and
     uncertainty analysis, but do not adjust the parameters, 15 Aug
     2006, CM
   Added documentation, 18 Sep 2006, CM

  $Id: mpfit.pro,v 2.3 2006/09/28 13:39:25 bdavis Exp $

(See src/idl_cvs/mpfit.pro)


NEARESTI_ARRAY

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	NEARESTI_ARRAY
 PURPOSE:
  	Return indices of big input array closest to the values
            in the little input array.

 CATEGORY:
	Search, Arrays

 CALLING SEQUENCE: 
	i=NEARESTI_ARRAY(bigArray,littleArray)

 INPUTS:   
	bigArray - an array of numbers to look in
  	littleArray - an array to look for matches in bigArray
 OUTPUTS:
	ret_indices - the indices of bigarray closest to values of littleArray

 COMMON BLOCKS:
 NOTES:
 MODIFICATION HISTORY:
 	17-Jul-97 WMD Written

(See src/idl_cvs/nearesti_array.pro)


NEARESTI

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	NEARESTI
 PURPOSE:
  	Return index of input array closest to the value of "pt"

 CATEGORY:
	Search

 CALLING SEQUENCE: 
	i=NEARESTI(array,pt)

 INPUTS:   
	array - an array of numbers
       pt    - a number
 OUTPUTS:
	iclosest - the index of the array value closet to "pt"

 COMMON BLOCKS:
 NOTES:
	limited by precision. e.g., 
	IDL> print, nearesti([2,3], 2.5000001)
           0
 MODIFICATION HISTORY:
	16-Jul-02 WMD Handle really big "pt"
 	03-Dec-99 WMD make input a scalar, if necessary
	17-Jul-97 WMD more like Harris Library version - faster
 	29-Mar-88 WMD Written

(See src/idl_cvs/nearesti.pro)


NNET.PRO

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	NNET.PRO

 PURPOSE:
	Neural network classifier. This is a standard 3-layer 
	back-propagation net.

 CALLING SEQUENCE:
	NNET, bias_hid, w_hid, bias_out, w_out, input, h_output, $
		output, first, second, third

 INPUTS:
 	bias_hid - Bias weights on the hidden neurons (DP vector [n_hid]).
	w_hid - weights between input & hidden layers (DP array [n_in,n_hid]).
	bias_out - Bias weights on the output neurons (DP vector [n_out]).
	w_out - weights between hidden & output layers (DP array [n_hid,n_out]).
	input - input values (DP vector [n_in]).
	
 OUTPUTS:
	h_output - computed values of hidden layer neurons (DP vector [n_hid]).
	output - computed values of output neurons (DP vector [n_out]).
	first - index of output neuron with highest value.
	second - index of second place neuron.
	third - index of third place neuron (if there are more than two output
		neurons).

 KEYWORD PARAMETERS
	None.

 EXAMPLE:
	IDL> nnet, bias_hid, w_hid, bias_out, w_out, input, hout, output

	- input is the pattern you want to classify. Must be a normalized 
	  float or DP vector or the same size as the training patterns used
	  to train the weights.

 HISTORY:
	Version 1.0 	T. Beck		
	Advanced Computer Concepts, Inc.		21 Apr 1999

(See src/idl_cvs/nnet.pro)


ONALPHA

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       OnAlpha
 PURPOSE:
	Tests for running on an alpha computer. You can specify the
	the desired Alpha computer. Optionally beeps, and prints a 
       message and returns an error if not on the desired Alpha computer.
	
 CATEGORY:
        OS Specific
 CALLING SEQUENCE:
       IDL> OK = OnAlpha('KEES')
 INPUTS:
   (Optional)
       compWanted - string of VMS alpha system, e.g., 'mel' (default='KEES')
 KEYWORD PARAMETERS:
   (Optional)
	NOBEEP - if set, no beep when not on desired alpha
	QUIET - if set, no message is printed to the terminal
 OUTPUTS:
       OK = If = 1, then on desired alpha, else 0     	out
 COMMON BLOCKS:
       NONE
 EXAMPLE:
	IDL> OK = onAlpha(  )
 NOTES:
 MODIFICATION HISTORY:
	30-May-00 Since Multinet recently added places, remove need for 
		  it.
       20-Oct-99 Written by Bill Davis, PPPL

(See src/idl_cvs/onalpha.pro)


ONCOMPUTER

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       onComputer
 PURPOSE:
       Return 1 if on the specified computer.
	First uses enironmental variable HOST has the computer name.
 CATEGORY:
       System
 CALLING SEQUENCE:
       IDL> OK = onComputer( computerName )
 INPUTS:
	computerName - name of computer (best not to have domain included)
	               this not case sensitive.
 KEYWORD PARAMETERS:
	var - Environmental variable to check for computer name.
		(defaults to 'HOST'). If HOST not defined, will still work on Linux
	HLP - When set, help information is printed.
	verbose - if set, will print many informational messages
	debug - if set, debug output will be printed
 OUTPUTS:
       OK = 1 if environmental variable "camac_server" is non-blank
 EXAMPLE:
 NOTES:
       When the routine is called with no parameters, or with the
	keyword hlp set, help information is printed.
 MODIFICATION HISTORY:
       08-Jan-2009 Written by Bill Davis, PPPL

(See src/idl_cvs/oncomputer.pro)


OS_FAMILY

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	OS_FAMILY
 PURPOSE:
	Return the current operating system as in !VERSION.OS_FAMILY 

 CATEGORY:
	OS Specific

 CALLING SEQUENCE:
	result = OS_FAMILY()
 INPUTS: 
	None
 OUTPUTS:
	result - scalar string containing one of the four values
		'Windows','MacOS','vms' or 'unix'
 NOTES:
	OS_FAMILY is assumed to be 'unix' if !VERSION.OS is not 'windows',
		'MacOS' or 'vms'

	To make procedures from IDL V4.0 and later compatibile with earlier
	versions of IDL, replace calls to !VERSION.OS_FAMILY with OS_FAMILY().	

 PROCEDURES CALLED:
	function tag_exists
 REVISION HISTORY:
	Written,  W. Landsman     

(See src/idl_cvs/os_family.pro)


PARCHECK

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

  NAME:
	PARCHECK   

  PURPOSE:
    To check that a procedure has been called with the minimum of allowed
    number of parameters. 

  CATEGORY:
    Error checking
 
 
  CALLING SEQUENCE:
    PARCHECK,NPARM,MINPARMS,CALLINGPRO
 
  PARAMETERS:

    NPARM       (REQ) (I) (0) (I)
                required input scalar giving the number of parameters
                in the procedure call (i.e. n_params(0)).

    MINPARMS    (REQ) (I) (0 1) (I)
                If scalar, the minimum number of parameters needed for the
                procedure to execute properly.
                If an array, it represents the allowed numbers of
                parameters (e.g. if 3,4 or 6 parameters are allowed,
                then set minparms([0,1,2]) = [3,4,6] ).

    CALLINGPRO  (REQ) (I) (0) (S)
                Required string giving the name of the calling procedure.

  EXAMPLES:

    To determine if procedure pro, which contains a
    call to parcheck has the minimum number of parameters
    (i.e. 4):

             PARCHECK,N_PARAMS(),4,'PRO'

    If the same procedure can have 4,5,7, or 8 parameters
    then use:

             PARCHECK,N_PARAMS(),[4,5,7,8],'PRO'

  PROCEDURE:
    The input parameters to PARCHECK are first checked themselves
    using PCHECK. If MINPARMS is a scalar it is compared to NPARM.
    If NPARM < MINPARMS, then an error message is printed and the
    procedure returns to the main level. If MINPARMS is a vector,
    then NPARM is subtracted from each value of MINPARMS and the
    resulting vector is checked for zeroes. If no values are zero,
    then error messages are printed and the program returns to the
    main level.
 
  MODIFICATION HISTORY :
    Mar 30 1987    cag  gsfc  initial program
    Apr    1987    rwt  gsfc  add vector input for parameters
    Mar 15 1988    cag  gsfc  add vax rdaf-style prolog
    Jul 12 1989    jtb  gsfc  converted to sun/unix idl
    Nov  2 1989    rwt  gsfc  correct print format syntax
    May 10 1991    PJL  GSFC  corrected prolog format
    Jun 21 1991    gra  casa  cleaned up; tested SUN, DEC, VAX;
                              updated prolog.
    Jun 28 1991    PJL  GSFC  added npar test; tested on SUN and VAX; 
			       updated prolog

(See src/idl_cvs/parcheck.pro)


PECOMP

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       PECOMP
 PURPOSE:
       Interactively compare PCS and EFIT signals for a shot
 CATEGORY:
       EFIT, PCS
 CALLING SEQUENCE:
       IDL> pecomp, shot=shot
 INPUTS:
       shot = shot number
 KEYWORD PARAMETERS:
       Keywords:
	  print - print rather than display on screen
         data - can pass in data
         xsize
         ysize
         xrange - of plots
         debug
         bigCharSize
 OUTPUTS:
 COMMON BLOCKS:
       NONE
 EXAMPLE:
	IDL> pecomp, shot=130000, bigCharSize=3
 NOTES:
       Use middle mouse button to select zoom region
 MODIFICATION HISTORY:
	10-Nov-2008 made to work with skylark defs. 
		    don't keep reading data when not there. [BD]
	21-Feb-2008 Added "RAF_FLPPPU4" & "\F_FLPPPU4" per Dennis & Dave
	14-Feb-2008 Add upper-lower loop voltage difference signals per
		    Dennis Mueller [BD]
       04-Feb-2008 add switch to allow using eng_dev tree [Dana Mastrovito]
	21-Jan-2008 Don't do an MDSconnect (use mdsopen instead of openMDSshot()) [BD]
	12-Feb-2007 Always read shot number field before plotting, so  not necessary.
		    Fix recently introduced errors. 
       Written by Bill Davis, PPPL, for Dave Gates

(See src/idl_cvs/pecomp.pro)


PLOTTSFONT0

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

 PURPOSE:
	This procedure will plot the fitted profiles of 
	electron temperature,density, and presssure from the
	NSTX Multi-Pulse Thomson Scattering (MPTS) diagnostic.

 CALLING SEQUENCE:
	plottsfont0,TS1[,TS2]

 INPUTS:
	TS1 = structure containing Thomson data for shot
	TS2 = structure containing Thomson data for second shot (optional)

 KEYWORDS:
   (INPUT)
	Tplot = vector of times to plot profiles (default = all times)
		(if multiple shots only first time point is used)
	/NB	= if set, add neutral beam power to time history plot 
	/RF	= if set, add HHFW power to time history plot
 	/MHD 	= if set, add Mirnov trace to time history
	/Vloop 	= if set, add loop voltage to time history plot
	/Mld	= if set, add microwave line density to time history
	/HA	= if set, add hydrogen alpha signal to time history
	/USXR	= if set, add ultra-soft x-ray signal to time history
	/Wmhd	= if set, add EFIT Total energy (Wmhd) to time history
	/Tf     = if set, add TF current to time history
	/Qmin	= if set, add qmin to time history
	/Q95	= if set, add q95 to time history
	Temax	= value of maximum Te to plot [ keV]
	Nemax	= value of maximum Ne to plot [1e13 /cm^3]
	Pemax	= value of maximum Pe to plot [kPa]
	Nelmax	= value of maximum NeL to plot [1e15 /cm^2]
	Big	= make single large plot of :
			1 - Te, 2 - Ne, 3 - Pe, 4 - time history
	/CHI	= if set, changes plotting defaults to values appropriate 
		  to lower temperature plasmas
	/Nospline = set to connect data with straight lines instead of splines.
	Rrange  = two element vector to set radial range of plot [Rmin, Rmax]
	Chrsz	= sets size of characters in plot
	/Fancy  = sets Font to Triplex Roman
	Tmax	= set maximum value of time in plot
	Pk	= set Te(t) to peak value of spline
	Efit    = value of EFIT tree to use '1,2,3,4,5'
   (OUTPUT)
	Rescale = ratio of axis scales on time history plot
	Pt     = actual times selected for profile plots
	

 ADDITIONAL FEATURES:
	In the last plot, the time history of the line density from
	integrating the Thomson data is displayed as a series of solid
	symbols (circles). If multiple times are plotted, they are color 
	coded to symbols on the line density plot. The time history of the
	central electron temperature is also plotted.

	When using multiple shots, data from the first shot will be
	plotted with solid lines, the second shot's data will be dashed.

 EXAMPLES:
	To restore data for a particular shot, the function TS.pro
	can be used. To plot profiles at all times the Tplot keyword
	can be set to All().

	For example, to plot the Thomson data for shot 104313 at all 
	times along with the Neutral beam power and the Halpha data:

	   plottsfont0,ts(104313),tplot=all(),/nb,/ha

	To plot the difference between two shots at the same time:
	
	   plottsfont0,ts(104487),ts(104485),tplot=.2,/rf

	To make a larger plot of only the the electron temperature:
	   plottsfont0,ts(104487),ts(104485),tplot=.2,big=1

 RESTRICTIONS:
	This procedure will modify the color table by using the
	command TEK_COLOR to change the first 16 (32?) colors.

 MODIFICATION HISTORY:
	26-Sep-2008 added font keyword for Roger Raman [BD]
	Written by R. E. Bell, PPPL, 2000
	Added CHI and NoSpline keywords, REB, 29-Aug-2001
	Added Wmhd keyword, changed mhd scaling, REB, 26-Feb-2002
	Updated TS function , REB, 31-Jan-2003
	Modified treatement of MHD plot, REB, 31-Jan-2003
	Modified to designate EFIT tree to use with EFIT keyword. REB 20-Oct-2003
	Added X windows adjustment to 'Z' plot type, REB 17-Nov-2003
	Fixed bugs in timing for multiple shots, REB 17-Nov-2003

(See src/idl_cvs/plottsfont0.pro)


PROGRESSW

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       progressw
 PURPOSE:
       show progress bar until done, or the user clicks the STOP button.
 USE:
	customize for your use for progress indications.
 CATEGORY:
       Demo; Real Time applications
 CALLING SEQUENCE:
       IDL> done = progressw( seconds )
 INPUTS:
       seconds - total seconds for finish
 KEYWORD PARAMETERS:
    Optional:
	print - if set, will print time elapsed
	waitSeconds - seconds to wait (pause) after a timer event is fielded
			default = 1/2 second.
	xsize - length in pixels of progress bar
	ysize - width in pixels of progress bar
	group_leader - higher level widget to place this on top of 
 OUTPUTS:
       done - 1, if time expired, or 0 if user hit STOP
 COMMON BLOCKS:
       NONE
 EXAMPLE:
	IDL> done = ProgressW( 20 )	; seconds expected for motor to run
	IDL> IF NOT done THEN stopmotor
 RELATED ROUTINE:
	BarometerW
 NOTES:
	Only works on X.
 MODIFICATION HISTORY:
	19-Jul-00 Written by Bill Davis

(See src/idl_cvs/progressw.pro)


REM_ELEM

[Previous Routine] [Next Routine] [List of Routines]
   Name: rem_elem

   Purpose: return subscripts of input array remaining after elements in 
            a second array are removed

   Category: 
	Programming

   Input Parameters:
      inarray - array to search/remove from
      remarray - array of elements to search/remove from inarray

   Output Parameters:
      count - number of elements (subscripts) returned     

   Calling Sequence:
      ss = rem_elem(inarray,remarray) ; subscripts remaining or -1

   History:
      slf, 20-jan-1993
      slf,  7-feb-1993 - documentation carification and variable name change

(See src/idl_cvs/rem_elem.pro)


REMOVE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       REMOVE
 PURPOSE:
       Contract a vector or up to 7 vectors by removing specified elements   
 CATEGORY:
	Arrays
 CALLING SEQUENCE:
       REMOVE, index, v1,[ v2, v3, v4, v5, v6, v7]     
 INPUTS:
       INDEX - scalar or vector giving the index number of elements to
               be removed from vectors.  Duplicate entries in index are
               ignored.    An error will occur if one attempts to remove
               all the elements of a vector.

 INPUT-OUTPUT:
       v1 - Vector or array.  Elements specifed by INDEX will be 
               removed from v1.  Upon return v1 will contain
               N fewer elements, where N is the number of values in
               INDEX.

 OPTIONAL INPUT-OUTPUTS:
       v2,v3,...v7 - additional vectors containing
               the same number of elements as v1.  These will be
               contracted in the same manner as v1.

 EXAMPLES:
       (1) If INDEX = [2,4,6,4] and V = [1,3,4,3,2,5,7,3] then after the call

               IDL> remove,index,v      

       V will contain the values [1,3,3,5,3]

       (2) Suppose one has a wavelength vector W, and three associated flux
       vectors F1, F2, and F3.    Remove all points where a quality vector,
       EPS is negative

               IDL> bad = where( EPS LT 0, Nbad)
               IDL> if Nbad GT 0 then remove, bad, w, f1, f2, f3

 METHOD:
       If more than one element is to be removed, then HISTOGRAM is used
       to generate a 'keep' subscripting vector.    To minimize the length of 
       the subscripting vector, it is only computed between the minimum and 
       maximum values of the index.   Therefore, the slowest case of REMOVE
       is when both the first and last element are removed.

 REVISION HISTORY:
       Written W. Landsman        ST Systems Co.       April 28, 1988
       Cleaned up code          W. Landsman            September, 1992
       Converted to IDL V5.0   W. Landsman   September 1997
       Major rewrite for improved speed   W. Landsman    April 2000

(See src/idl_cvs/remove.pro)


SIMP

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       SIMP
 PURPOSE:
       Does Simpson numerical integration on an array of y values.
 CATEGORY:
 CALLING SEQUENCE:
       i = simp(y, h)
 INPUTS:
       y = array of y values of function.                 in
       h = separation between evenly spaced x values.     in
 KEYWORD PARAMETERS:
 OUTPUTS:
       i = value of integral.                             out
 COMMON BLOCKS:
 NOTES:
 MODIFICATION HISTORY:
       R. Sterner, 19 Dec, 1984.
       Johns Hopkins University Applied Physics Laboratory.

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

(See src/idl_cvs/simp.pro)


STRESS

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       STRESS
 PURPOSE:
       String edit by sub-string. Precede, Follow, Delete, Replace.
 CATEGORY:
 CALLING SEQUENCE:
       new = stress(old,cmd,n,oldss,newss,ned)
 INPUTS:
       old = string to edit.                               in
       cmd = edit command:                                 in
         'P' = precede.
         'F' = follow.
         'D' = delete.
         'R' = replace.
       n = occurrence number to process (0 = all).         in
       oldss = reference substring.                        in
       oldss may have any of the following forms:
         1. s	  a single substring.
         2. s...    start at substring s, end at end of string.
         3. ...e    from start of string to substring e.
         4. s...e   from subs s to subs e.
         5. ...     entire string.
       newss = substring to add. Not needed for 'D'        in
 KEYWORD PARAMETERS:
 OUTPUTS:
       ned = number of occurrences actually changed.       out
       new = resulting string after editing.               out
 COMMON BLOCKS:
 NOTES:
       Notes: oldss and newss may be arrays.
 MODIFICATION HISTORY:
       Written by R. Sterner, 6 Jan, 1985.
       Johns Hopkins University Applied Physics Laboratory.
       RES --- 23 May, 1988 fixed a bug in SSTYP = 2.
       Converted to SUN 13 Aug, 1989 --- R. Sterner. (FOR loop change).
       --- 8 Dec, 1992 added recursion so that OLDSS and NEWSS may be arrays
       T.J.Harris, University of Adelaide.

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

(See src/idl_cvs/stress.pro)


TABINV

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       TABINV     
 PURPOSE:  
       To find the effective index of a function value in an ordered vector.

 CALLING SEQUENCE:
       TABINV, XARR, X, IEFF
 INPUTS:
       XARR - the vector array to be searched, must be monotonic
               increasing or decreasing
       X    - the function value(s) whose effective
               index is sought (scalar or vector)

 OUTPUT:
       IEFF - the effective index or indices of X in XARR
               real or double precision, same # of elements as X

 RESTRICTIONS:
       TABINV will abort if XARR is not monotonic.  (Equality of 
       neighboring values in XARR is allowed but results may not be
       unique.)  This requirement may mean that input vectors with padded
       zeroes could cause routine to abort.

 PROCEDURE:
       A binary search is used to find the values XARR(I)
       and XARR(I+1) where XARR(I) < X < XARR(I+1).
       IEFF is then computed using linear interpolation 
       between I and I+1.
               IEFF = I + (X-XARR(I)) / (XARR(I+1)-XARR(I))
       Let N = number of elements in XARR
               if x < XARR(0) then IEFF is set to 0
               if x > XARR(N-1) then IEFF is set to N-1

 EXAMPLE:
       Set all flux values of a spectrum (WAVE vs FLUX) to zero
       for wavelengths less than 1150 Angstroms.
         
       IDL> tabinv, wave, 1150.0, I
       IDL> flux( 0:fix(I) ) = 0.                         

 NOTES:
        Users of V5.3 or later can use a faster version of tabinv.pro 
       available at http://idlastro.gsfc.nasa.gov/ftp/v53/ which makes use of
       the VALUE_LOCATE() intrinsic function. 
 FUNCTIONS CALLED:
       ISARRAY()
 REVISION HISTORY:
       Adapted from the IUE RDAF                     January, 1988         
       More elegant code  W. Landsman                August, 1989
       Mod to work on 2 element decreasing vector    August, 1992
       Converted to IDL V5.0   W. Landsman   September 1997

(See src/idl_cvs/tabinv.pro)


TESTCMD

[Previous Routine] [Next Routine] [List of Routines]
  NAME:
	testcmd 
  PURPOSE:
	test batch execution

 CATEGORY:             
	Example, Batch

  INVOCATION: 
	$ IDL runtestcmd.pro

    Where runtestcmd.pro might contain:
	testcmd, key='key input', file='newfile.txt'
	exit

 WRITTEN by Bill Davis, 23-Apr-99

(See src/idl_cvs/testcmd.pro)


TRUNS_GET

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       truns_get
 PURPOSE:
       List info (in a database) on NSTX TRANSP runs (to a screen or file)
 CATEGORY:
       TRANSP, Database
 CALLING SEQUENCE:
       IDL> truns_get, shotyear=shotyear, shotnumber=shotnumber, runID=runID,  $
                rundate=rundate, runby=runby,  $
                outFile=outFile
 INPUTS:
	(none required)
 KEYWORD PARAMETERS:
   (all optional)
       shotyear - e.g., '2001' 
	shotnumber - e.g., 105535
	runID - e.g., 01
	rundate - run date (YYYYMMDD), e.g., 20010802
	runby - person, e.g. 'KAYE'
	outFile - string (if not present, data listed to screen)
 OUTPUTS:
       data to screen or file, if specified
 COMMON BLOCKS:
       NONE
 EXAMPLE:
	IDL> truns_get, shotYear=2001		; all 2001 NSTX TRANSP runs to screen
	IDL> truns_get, rundate=20010911
 MODIFICATION HISTORY:
	25-May-2005 Switched double and single quotes in queries to work on RHEL.
       30-Jan-2002 Written by Bill Davis, PPPL
	Based on a program by Stan Kaye.

(See src/idl_cvs/truns_get.pro)


TVIMAGE

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

 PURPOSE:
     This purpose of TVIMAGE is to enable the TV command in IDL
     to be a completely device-independent and color-decomposition-
     state independent command. On 24-bit displays color decomposition
     is always turned off for 8-bit images and on for 24-bit images.
     The color decomposition state is restored for those versions of
     IDL that support it (> 5.2). Moreover, TVIMAGE adds features
     that TV lacks. For example, images can be positioned in windows
     using the POSITION keyword like other IDL graphics commands.
     TVIMAGE also supports the !P.MULTI system variable, unlike the
     TV command. TVIMAGE was written to work especially well in
     resizeable graphics windows. Note that if you wish to preserve
     the aspect ratio of images in resizeable windows, you should set
     the KEEP_ASPECT_RATIO keyword, described below. TVIMAGE works
     equally well on the display, in the PostScript device, and in
     the Printer and Z-Graphics Buffer devices. The TRUE keyword is
     set automatically to the correct value for 24-bit images, so you
     don't need to specify it when using TVIMAGE.

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

 CATEGORY:
     Graphics display.

 CALLING SEQUENCE:

     TVIMAGE, image

 INPUTS:
     image:    A 2D or 3D image array. It should be byte data.

       x  :    The X position of the lower-left corner of the image.
               This parameter is only recognized if the TV keyword is set.
               If the Y position is not used, X is taken to be the image
               "position" in the window. See the TV command documenation
               for details.

       y  :    The Y position of the lower-left corner of the image.
               This parameter is only recognized if the TV keyword is set.

 KEYWORD PARAMETERS:

     ACOLOR:   Set this keyword to the axis color. If a byte or integer value,
               it will assume you are using INDEXED color mode. If a long integer
               is will assume you are using DECOMPOSED color mode. If a string,
               is will pass the string color name along to FSC_COLOR for processing.

     AXES:     Set this keyword to draw a set of axes around the image.

     AXKEYWORDS:   An IDL structure variable of PLOT keywords as structure fields
               and keyword values as the values of the fields. Pass directly to the
               PLOT command that draws the axes for the image. Ignored unless the
               AXES keyword is set. For example,

               TVImage, image, /AXES, AXKEYWORDS={CHARSIZE:1.5, XTITLE:'Distance (mm)', $
                    YTITLE:'Signal', TICKLEN:-0.025}, ACOLOR='NAVY'

     BACKGROUND:   This keyword specifies the background color. Note that
               the keyword ONLY has effect if the ERASE keyword is also
               set or !P.MULTI is set to multiple plots and TVIMAGE is
               used to place the *first* plot. Can be a string (e.g., 'ivory'), or
               a 24-bit value that can be decomposed into a color, or an 8-bit
               index number into the current color table. ERASE and BACKGROUND
               should only be used on 24-bit devices that support windows!

     BREWER:   If set, applies only to BACKGROUND AND ACOLOR keywords. Selects
               brewer colors, rather than standard FSC_COLOR colors as strings.

     ERASE:    If this keyword is set an ERASE command is issued
               before the image is displayed. ERASE and BACKGROUND 
               should only be used on 24-bit devices that support windows! 
               The keyword is ignored on 8-bit devices or devices that do
               not support windows.

     _EXTRA:   This keyword picks up any TV keywords you wish to use.

     HALF_HALF: If set, will tell CONGRID to extrapolate a *half* row
               and column on either side, rather than the default of
               one full row/column at the ends of the array.  If you
               are interpolating images with few rows, then the
               output will be more consistent with this technique.
               This keyword is intended as a replacement for
               MINUS_ONE, and both keywords probably should not be
               used in the same call to CONGRID.

     KEEP_ASPECT_RATIO: Normally, the image will be resized to fit the
               specified position in the window. If you prefer, you can
               force the image to maintain its aspect ratio in the window
               (although not its natural size) by setting this keyword.
               The image width is fitted first. If, after setting the
               image width, the image height is too big for the window,
               then the image height is fitted into the window. The
               appropriate values of the POSITION keyword are honored
               during this fitting process. Once a fit is made, the
               POSITION coordiates are re-calculated to center the image
               in the window. You can recover these new position coordinates
               as the output from the POSITION keyword.

     MARGIN:   A single value, expressed as a normalized coordinate, that
               can easily be used to calculate a position in the window.
               The margin is used to calculate a POSITION that gives
               the image an equal margin around the edge of the window.
               The margin must be a number in the range 0.0 to 0.333. This
               keyword is ignored if the POSITION or OVERPLOT keywords are
               used. It is also ignored when TVImage is executed in a
               multi-plot window, EXCEPT if it's value is zero. In this
               special case, the image will be drawn into its position in
               the multi-plot window with no margins whatsoever. (The
               default is to have a slight margin about the image to separate
               it from other images or graphics.

     MINUS_ONE: The value of this keyword is passed along to the CONGRID
               command. It prevents CONGRID from adding an extra row and
               column to the resulting array, which can be a problem with
               small image arrays.

     NOINTERPOLATION: Setting this keyword disables the default bilinear
               interpolation done to the image when it is resized. Nearest
               neighbor interpolation is done instead. This is preferred
               when you do not wish to change the pixel values of the image.
               This keyword must be set, for example, when you are displaying
               GIF files that come with their own non-IDL color table vectors.

     NORMAL:   Setting this keyword means image position coordinates x and y
               are interpreted as being in normalized coordinates. This keyword
               is only valid if the TV keyword is set.

     OVERPLOT: Setting this keyword causes the POSITION keyword to be ignored
               and the image is positioned in the location established by the
               last graphics command. For example:

                    Plot, Findgen(11), Position=[0.1, 0.3, 0.8, 0.95]
                    TVImage, image, /Overplot

     POSITION: The location of the image in the output window. This is
               a four-element floating array of normalized coordinates of
               the type given by !P.POSITION or the POSITION keyword to
               other IDL graphics commands. The form is [x0, y0, x1, y1].
               The default is [0.0, 0.0, 1.0, 1.0]. Note that this keyword is ALSO
               an output keyword. That is to say, upon return from TVIMAGE
               this keyword (if passed by reference) contains the actual
               position in the window where the image was displayed. This
               may be different from the input values if the KEEP_ASPECT_RATIO
               keyword is set, or if you are using TVIMAGE with the POSITION
               keyword when !P.MULTI is set to something other than a single
               plot. One use for the output values might be to position other
               graphics (e.g., a colorbar) in relation to the image.

               Note that the POSITION keyword should not, normally, be used
               when displaying multiple images with !P.MULTI. If it *is* used,
               its meaning differs slightly from its normal meaning. !P.MULTI
               is responsible for calculating the position of graphics in the
               display window. Normally, it would be a mistake to use a POSITION
               graphics keyword on a graphics command that was being drawn with
               !P.MULTI. But in this special case, TVIMAGE will use the POSITION
               coordinates to calculate an image position in the actual position
               calculated for the image by !P.MULTI. The main purpose of this
               functionality is to allow the user to display images along with
               colorbars when using !P.MULTI. See the example below.

    QUIET:      There are situations when you would prefer that TVIMAGE does not
                advertise itself by filling out the FSC_$TVIMAGE common block. For
                example, if you are using TVIMAGE to draw a color bar, it would
                not be necessary. Setting this keyword means that TVIMAGE just
                goes quietly about it's business without bothering anyone else.

    SCALE:     Set this keyword to byte scale the image before display.

     TV:       Setting this keyword makes the TVIMAGE command work much
               like the TV command, although better. That is to say, it
               will still set the correct DECOMPOSED state depending upon
               the kind of image to be displayed (8-bit or 24-bit). It will
               also allow the image to be "positioned" in the window by
               specifying the coordinates of the lower-left corner of the
               image. The NORMAL keyword is activated when the TV keyword
               is set, which will indicate that the position coordinates
               are given in normalized coordinates rather than device
               coordinates.

               Setting this keyword will ensure that the keywords
               KEEP_ASPECT_RATIO, MARGIN, MINUS_ONE, MULTI, and POSITION
               are ignored.

      XRANGE:  If the AXES keyword is set, this keyword is a two-element vector
               giving the X axis range. By default, [0, size of image in X].

      YRANGE:  If the AXES keyword is set, this keyword is a two-element vector
               giving the Y axis range. By default, [0, size of image in Y].

 OUTPUTS:
     None.

 SIDE EFFECTS:
     Unless the KEEP_ASPECT_RATIO keyword is set, the displayed image
     may not have the same aspect ratio as the input data set.

 RESTRICTIONS:
     If the POSITION keyword and the KEEP_ASPECT_RATIO keyword are
     used together, there is an excellent chance the POSITION
     parameters will change. If the POSITION is passed in as a
     variable, the new positions will be returned in the same variable
     as an output parameter.

     If a 24-bit image is displayed on an 8-bit display, the
     24-bit image must be converted to an 8-bit image and the
     appropriate color table vectors. This is done with the COLOR_QUAN
     function. The TVIMAGE command will load the color table vectors
     and set the NOINTERPOLATION keyword if this is done. Note that the
     resulting color table vectors are normally incompatible with other
     IDL-supplied color tables. Hence, other graphics windows open at
     the time the image is display are likely to look strange.

     Other programs from Coyote Library (e.g., FSC_COLOR) may also be
     required.

 EXAMPLE:
     To display an image with a contour plot on top of it, type:

        filename = FILEPATH(SUBDIR=['examples','data'], 'worldelv.dat')
        image = BYTARR(360,360)
        OPENR, lun, filename, /GET_LUN
        READU, lun, image
        FREE_LUN, lun

        TVIMAGE, image, POSITION=thisPosition, /KEEP_ASPECT_RATIO
        CONTOUR, image, POSITION=thisPosition, /NOERASE, XSTYLE=1, $
            YSTYLE=1, XRANGE=[0,360], YRANGE=[0,360], NLEVELS=10

     To display four images in a window without spacing between them:

     !P.Multi=[0,2,2]
     TVImage, image, Margin=0
     TVImage, image, Margin=0
     TVImage, image, Margin=0
     TVImage, image, Margin=0
     !P.Multi = 0

     To display four image in a window with associated color bars:

     !P.Multi=[0,2,2]
     p = [0.02, 0.3, 0.98, 0.98]
     LoadCT, 0
     TVImage, image, Position=p
     Colorbar, Position=[p[0], p[1]-0.1, p[2], p[1]-0.05]
     p = [0.02, 0.3, 0.98, 0.98]
     LoadCT, 2
     TVImage, image, Position=p
     Colorbar, Position=[p[0], p[1]-0.1, p[2], p[1]-0.05]
     p = [0.02, 0.3, 0.98, 0.98]
     LoadCT, 3
     TVImage, image, Position=p
     Colorbar, Position=[p[0], p[1]-0.1, p[2], p[1]-0.05]
     p = [0.02, 0.3, 0.98, 0.98]
     LoadCT, 5
     TVImage, image, Position=p
     Colorbar, Position=[p[0], p[1]-0.1, p[2], p[1]-0.05]
     !P.Multi =0

 MODIFICATION HISTORY:
      Written by:     David Fanning, 20 NOV 1996.
      Fixed a small bug with the resizing of the image. 17 Feb 1997. DWF.
      Removed BOTTOM and NCOLORS keywords. This reflects my growing belief
         that this program should act more like TV and less like a "color
         aware" application. I leave "color awareness" to the program
         using TVIMAGE. Added 24-bit image capability. 15 April 1997. DWF.
      Fixed a small bug that prevented this program from working in the
          Z-buffer. 17 April 1997. DWF.
      Fixed a subtle bug that caused me to think I was going crazy!
          Lession learned: Be sure you know the *current* graphics
          window! 17 April 1997. DWF.
      Added support for the PRINTER device. 25 June 1997. DWF.
      Extensive modifications. 27 Oct 1997. DWF
          1) Removed PRINTER support, which didn't work as expected.
          2) Modified Keep_Aspect_Ratio code to work with POSITION keyword.
          3) Added check for window-able devices (!D.Flags AND 256).
          4) Modified PostScript color handling.
      Craig Markwart points out that Congrid adds an extra row and column
          onto an array. When viewing small images (e.g., 20x20) this can be
          a problem. Added a Minus_One keyword whose value can be passed
          along to the Congrid keyword of the same name. 28 Oct 1997. DWF
      Changed default POSITION to fill entire window. 30 July 1998. DWF.
      Made sure color decomposition is OFF for 2D images. 6 Aug 1998. DWF.
      Added limited PRINTER portrait mode support. The correct aspect ratio
          of the image is always maintained when outputting to the
          PRINTER device and POSITION coordinates are ignored. 6 Aug 1998. DWF
      Removed 6 August 98 fixes (Device, Decomposed=0) after realizing that
          they interfere with operation in the Z-graphics buffer. 9 Oct 1998. DWF
      Added a MARGIN keyword. 18 Oct 1998. DWF.
      Re-established Device, Decomposed=0 keyword for devices that
         support it. 18 Oct 1998. DWF.
      Added support for the !P.Multi system variable. 3 March 99. DWF
      Added DEVICE, DECOMPOSED=1 command for all 24-bit images. 2 April 99. DWF.
      Added ability to preserve DECOMPOSED state for IDL 5.2 and higher. 4 April 99. DWF.
      Added TV keyword to allow TVIMAGE to work like the TV command. 11 May 99. DWF.
      Added the OVERPLOT keyword to allow plotting on POSITION coordinates
         estabished by the preceding graphics command. 11 Oct 99. DWF.
      Added automatic recognition of !P.Multi. Setting MULTI keyword is no
         longer required. 18 Nov 99. DWF.
      Added NOINTERPOLATION keyword so that nearest neighbor interpolation
         is performed rather than bilinear. 3 Dec 99. DWF
      Changed ON_ERROR condition from 1 to 2. 19 Dec 99. DWF.
      Added Craig Markwardt's CMCongrid program and removed RSI's. 24 Feb 2000. DWF.
      Added HALF_HALF keyword to support CMCONGRID. 24 Feb 2000. DWF.
      Fixed a small problem with image start position by adding ROUND function. 19 March 2000. DWF.
      Updated the PRINTER device code to take advantage of available keywords. 2 April 2000. DWF.
      Reorganized the code to handle 24-bit images on 8-bit displays better. 2 April 2000. DWF.
      Added BACKGROUND keyword. 20 April 2000. DWF.
      Fixed a small problem in where the ERASE was occuring. 6 May 2000. DWF.
      Rearranged the PLOT part of code to occur before decomposition state
         is changed to fix Background color bug in multiple plots. 23 Sept 2000. DWF.
      Removed MULTI keyword, which is no longer needed. 23 Sept 2000. DWF.
      Fixed a small problem with handling images that are slices from 3D image cubes. 5 Oct 2000. DWF.
      Added fix for brain-dead Macs from Ben Tupper that restores Macs ability to
         display images. 8 June 2001. DWF.
      Fixed small problem with multiple plots and map projections. 29 June 2003. DWF.
      Converted all array subscripts to square brackets. 29 June 2003. DWF.
      Removed obsolete STR_SEP and replaced with STRSPLIT. 27 Oct 2004. DWF.
      Small modification at suggestion of Karsten Rodenacker to increase size of
         images in !P.MULTI mode. 8 December 2004. DWF.
      Minor modifications on Karsten Rodenacker's own account concerning margination
         and TV behaviour. 8 December 2004. KaRo
      There was a small inconsistency in how the image was resized for PostScript as
         opposed to the display, which could occasionally result in a small black line
         to the right of the image. This is now handled consistently. 3 January 2007. DWF.
      Made a small change to CMCONGRID to permit nearest-neighbor interpolation for 3D arrays.
         Previously, any 24-bit image was interpolated, no matter the setting of the NOINTERP
         keyword. 22 April 2007. DWF.
      Updated the program for the 24-bit Z-buffer in IDL 6.4. 11 June 2007. DWF.
      Added new POSITION keyword functionality for !P.MULTI display. 9 Sept 2007. DWF.
      Bit one too many times. Added _STRICT_EXTRA keywords for all _EXTRA keywords. 1 Feb 2008. DWF.
      Added FSC_$TVIMAGE common block for interactive interaction with TVINFO. 16 March 2008. DWF.
      Added SCALE keyword. 18 March 2008. DWF.
      Added keywords to allow axes to be drawn around the image. 18 March 2008. DWF.
      Added QUIET keyword to allow by-passing of FSC_$TVIMAGE common block updating. 21 March 2008. DWF.
      Made BACKGROUND and ERASE valid keywords only on 24-bit devices. Ignored on others. 28 May 2008. DWF.
      Cannot make color work in device independent way for axes, unless I handle axis color directly. To this
          end, I have added an ACOLOR keyword. 16 June 2008. DWF.
      Added BREWER keyword so I can specify Brewer colors with BACKGROUND and ACOLOR keywords. 16 June 2008. DWF.

(See src/idl_cvs/tvimage.pro)


VT100

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

 PURPOSE: 
     Define the TEK and VT100 commands for use in IDL.  Especially
     useful for MAC users who use Versaterm or users who otherwise
     want to do Tektronix plots while connected to their UNIX
     platform of choice.

 CATEGORY:
	Misc

 CALLING SEQUENCE: 
     VT100

 INPUT PARAMETERS: 
     NONE

 OPTIONAL INPUT PARAMETERS: 
     NONE

 KEYWORDS: 
     NONE

 OUTPUTS: 
     NONE

 COMMON BLOCKS: 
     NONE

 SIDE EFFECTS: 
     NONE

 RESTRICTIONS:
     If you want to use the TEK command, you need to issue the VT100
     command first.

 PROCEDURE: 

 CODE TYPE: modeling, analysis, control

 CODE SUBJECT:  operation, handling, edge, rf, transport, equilibrium

 EASE OF USE: can be used with existing documentation

 OPERATING SYSTEMS:  UNIX of all flavors

 EXTERNAL CALLS:  NONE

 RESPONSIBLE PERSON: Ray Jong
	
 DATE OF LAST MODIFICATION:  01/19/99

 MODIFICATION HISTORY:
     Created by Michael D. Brown, LLNL

(See src/idl_cvs/vt100.pro)


WHICH

[Previous Routine] [List of Routines]
 NAME:
	WHICH

 PURPOSE:
	Like Unix which, prints the path of an IDL routine.

 CATEGORY:
	Help, documentation.

 CALLING SEQUENCE:

	Which, Name

 INPUTS:
	Name:	The string containing the name of the procedure.
		If no '.' in name, ".pro" is appended.
		Under Unix, Name may be "*" to get information on
		first routine to satisfy match.

 KEYWORDS:
	PRINT:	If set, this keyword sends the output of WHICH to the
		default printer.  Under Unix, if PRINT is a string, it is
		interpreted as a shell command used for output with
		the documentation from WHICH providing standard input
		(i.e. PRINT="cat > junk").

	OUTPUT: returns full path of file found;
               will return null string if none found

	QUIET: 	If set, no printing to IDL session is done
 UNIX KEYWORDS:
   DIRECTORY:	The directory to search.  If omitted, the current directory
		and !PATH are used.

	MULTI:	If set, this flag allows printing of more than one file if the
		requested module exists in more than one directory in the path
		and the current directory.

 VMS KEYWORDS:
	FILE:	If this keyword is set, the output is left in the file
		"userlib.doc", in the current directory.

	PATH:	An optional directory/library search path.  This keyword uses
		the same format and semantics as !PATH.  If omitted, !PATH is
		used.

 OUTPUTS:
	Documentation is sent to the standard output unless /PRINT
	is specified.

 COMMON BLOCKS:
	None.

 SIDE EFFECTS:
	Output is produced on terminal or printer.

 RESTRICTIONS:
	The DIRECTORY and MULTI keywords are ignored under VMS. The
	FILE and PATH keywords are ignored under Unix.

 EXAMPLE:
	To obtain documentation for the User's Library function DIST, enter:
		Which, 'DIST', output=fullpathname

	For a graphical interface to WHICH, see the procedure XDL.

 MODIFICATION HISTORY:
	13-Apr-99 Allow findind files on VMS if not in libraries [BD]
	Converted from IDL DOC_LIBRARY by Bill Davis, March, 1999
	   optionally return path in keyword OUTPUT. Added QUIET keyword.
	   allow extentions other than .pro
	   allow uppercase finds.
	Written, DMS, Sept, 1982.
	Added library param, Jul 1987.
	Unix version, DMS, Feb, 1988.
	New VMS version, DMS, Dec. 1989
	Wrapper procedure to call the correct version
		under Unix and VMS, AB, Jan 1990
       Added support for DOS, SNG, Dec, 1990
	Added support for Macintosh, DJE, Nov, 1994

(See src/idl_cvs/which.pro)


Category: NSTX

[List of Routines]


NSTXCORNER

[Next Routine] [List of Routines]
 NAME:
       nstxcorner
 PURPOSE:
       write NSTX in upper left-hand corner of a plot
 CATEGORY:
       NSTX, Plotting
 CALLING SEQUENCE:
       IDL> nstxcorner
 MODIFICATION HISTORY:
       21-Aug-00 Written by Bill Davis, PPPL

(See src/idl_cvs/nstxcorner.pro)


NSTXLOGO

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       nstxlogo
 PURPOSE:
       draw NSTX logo in upper left-hand corner of a plot
 CATEGORY:
       NSTX, Plotting
 CALLING SEQUENCE:
       IDL> nstxlogo
 KEYWORD PARAMETERS:
     Optional Keywords:
	CHARSIZE -Character size of NSTX characters (def=1.5)
	XLOC - X location of middle of logo, in normal coordinates
	YLOC - Y location of middle of logo, in normal coordinates
	iBar - if set, draw center stack as an "I" rather than ")("
	right -if set, drawn on the right
	blue  - if set, color table value for NSTX text
	red   - if set, color table value for bars and circles
	bottom - if set, drawn on the bottom
 EXAMPLE:
	IDL> !y.omargin=[0,1.5]
	IDL> plot,indgen(11)
	IDL> nstxlogo
 LIMITATONS:
	This was designed to work with the default IDL font (-1).
 NOTES:
	You will probably want to leave extra room at the top of your plot, e.g.
	   IDL> !y.omargin=[0,1.5]
 MODIFICATION HISTORY:
	25-Feb-03 Made circles same font as others
	14-May-01 Changed the look - no X.
	01-Nov-00 Cleaned up location. Default size to 1.5
       21-Aug-00 Written by Bill Davis, PPPL

(See src/idl_cvs/nstxlogo.pro)


PLOT1SIG

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

 PURPOSE: plot 1 NSTX signal for many shots stacked vertically

 CATEGORY: NSTX, X-Y Plotting, MDSplus

 EXAMPLE:
    IDL> shots = [ 111827, 111875, 111876, 112075, 112137 ]
    IDL> signame = '\wf::ip'
    IDL> plot1sig, shots, signame=signame
    IDL> 

   Post script version:
    IDL> shots=[112175,112171,112172]
    IDL> !p.charsize=1.7
    IDL> setup_ps, file='dalf.ps', printer='postscript'
    IDL> device,set_font='Helvetica'
    IDL> signames='\passivespec::bayc_dalf_haifa'
    IDL> plot1sig,shots,0.,.6,signames=signames,tweenspace=.05
    IDL> unsetup_ps
    
 MODIFICATION HISTORY:
	19-May-2004 Added _extra keyword and fixed ymaxes bug
  	19-Apr-2004  Written by Bill Davis for Stan Kaye

(See src/idl_cvs/plot1sig.pro)


PLOT7

[Previous Routine] [List of Routines]
 NAME:	
	plot7

 PURPOSE: plot 7 (or any number) NSTX signals on the same x-axis

 CATEGORY: NSTX, X-Y Plotting, MDSplus

 USE: IDL> plot7, shot [, t1, t2]

   to make 5 plots of same signal and different shots:
	IDL> shots = [ 111827, 111875, 111876, 112075, 112137 ]
	IDL> plot1sig,shots,signame='\wf::ip'

 KEYWORDS:
   all optional, but you won't like the defaults :-)
	signames
	labels
	units
	scale
	ymins
	ymaxes
	tweenspace - fraction of screen between plots in vertical
	nospace - if set, overrides tweenspace to make plots abut vertically
 MODIFICATION HISTORY:
	19-May-2004 Added _extra keyword & don't reverse incoming shot list
	19-Apr-2004 Added support for many shots, and one signal.
  	11-Jan-01 Added ymin & ymax and made variables optional keywords
  	06-Oct-00 Written by Bill Davis for Franco Paoletti

(See src/idl_cvs/plot7.pro)


Category: Plotting

[List of Routines]


BETTERTICKLABELS

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

  PURPOSE:
 	Tick labels are made a little cleaner. E.g., shorter exponentials,
	no unnecessary trailing zeroes, accurate numbers when tick values
	are small differences between large numbers, etc.

 CATEGORY:
	Plotting, Graphics

  EXAMPLE:
	IDL> plot, y, ytickformat='betterticklabels'

  EXAMPLE A - Make a dummy plot call so can determine Tick Max:
	IDL> COMMON betterticklabels_common, yticklabels
	IDL> plot, y, ytick_get=yticklabels, ytickname=replicate('      ',30)
	IDL> AXIS, YAXIS=1, YRANGE=!y.crange, ytickformat='betterticklabels'
	IDL> dum = TEMPORARY(yticklabels)	; so doesn't affect later calls

  HISTORY:
	03-Mar-2008 slight mod to handle floating point comparison
       03-Aug-2006 fixed for values less than 2.e-6
	15-Apr-04 be able to return xtick values and x tic labels (NOT DEBUGGED)
	15-Oct-01 shift y axis labels if !p.font=0 (helps with some 3-D plots)
	11-Jan-01 shift y-axis labels if on TEK and !p.font=0 
	09-Oct-00 Written by Bill Davis

(See src/idl_cvs/betterticklabels.pro)


CLEANPLOT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       CLEANPLOT
 PURPOSE:
       Reset all system variables (!P,!X,!Y,!Z) to their default values
 CATEGORY:             
	Plotting
 EXPLANATION:
       Reset all system variables (!P,!X,!Y,!Z) which are set by the user 
       and which affect plotting to their default values.

 CALLING SEQUENCE:
       Cleanplot

 INPUTS:       
       None

 OUTPUTS:      
       None

 SIDE EFFECTS: 
       The system variables that concern plotting are reset
       to their default values.  A message is output for each
       variable changed.   The CRANGE, S, WINDOW, and REGION fields of the
       !X, !Y, and !Z system variables are not checked since these are 
       set by the graphics device and not by the user.    

 PROCEDURE:
       This does NOT reset the plotting device.
       This does not change any system variables that don't control plotting.

 RESTRICTIONS:
       If user default values for !P, !X, !Y and !Z are different from
       the defaults adopted below, user should change P_old etc accordingly

 MODIFICATION HISTORY:
       Written IDL Version 2.3.0  W. Landsman & K. Venkatakrishna May '92
       Handle new system variables in V3.0.0     W. Landsman   Dec 92
       Assume user has at least V3.0.0           W. Landsman   August 95
       V5.0 has 60 instead of 30 TICKV values    W. Landsman   Sep. 97
       Change !D.N_COLORS to !D.TABLE_SIZE for 24 bit displays
               W. Landsman  April 1998
       

(See src/idl_cvs/cleanplot.pro)


CLEARPLT

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

 PURPOSE:              
	This procedure will clear or zero all or a selection
       of the system plot variables

 CATEGORY:             
	Plotting

 CALLING SEQUENCE:     
			clearplt,/all           ;clear the !p, !x, !y, !z
                       clearplt,/x,/z          ;clear the !x and !z variables
                       clearplt,/x             ;only clear the !x variable
                       clearplt,/x,/invert     ;clear all except the !x

 INPUTS:
       KEYWORDS:
               x,y,z,p = clear the appropriate variable
               all     = clear all, this is equivalent to /x,/y,/z,/p
               invert  = invert the logic. Clear all unselected variables.
                         Therefore "clearplt,/all,/invert" does nothing.

 OUTPUTS:      none

 COMMON BLOCKS:
       none.
 SIDE EFFECTS:
               The sytem plot variables are changed.

 MODIFICATION HISTORY:
	20-Apr-99 [BD] more things cleared for !P
       Written by: Trevor Harris, Physics Dept., University of Adelaide,
               July, 1990.

(See src/idl_cvs/clearplt.pro)


COMPW

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       compw
 PURPOSE:
       Plot two signals and the difference.
 CATEGORY:
       Plotting
 CALLING SEQUENCE:
       compw
	compw, xsize=800, ysize=600
       compw, shot=120200, sig1='\wf::ipf2l', sig2='\wf::ipf2u'
       compw, shot=120200
       compw,sig1='\operations::bdot_l1dmivvhn1_raw',shot=110091, $
		t1=.4, t2=.41
 COMMON BLOCKS:
 USE:

 NOTES:
       Your display may have to be set to 256 colors to see the crosshairs.
 LIMITATIONS:
	You need IDL version 5, or greater to run this application.
 MODIFICATION HISTORY:
	03-Dec-2007 read widget fields when plot button clicked. Reset cross-hair
		    dimensions when window resized
	29-Nov-2007 Change plot & oplot to vplot & voplot [BD]
	08-May-2003 Created from FireTips test [BD]

(See src/idl_cvs/compw.pro)


FANCY_TITLE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       fancy_title
 PURPOSE:
       write a title at top of screen, with option to use Hershey fonts
 CATEGORY:
       Plotting
 CALLING SEQUENCE:
       IDL> fancy_title, mytitle, ishot
 INPUTS:
       mytitle = whatever you want as the main plot title.  
       ishot = shot number.  
 KEYWORD PARAMETERS:
       Keywords:
	  right - When set, print at top right
	  fancy - if set, use Hershey fonts
	  line - if set, drop the title down by this number of lines.
 OUTPUTS:
       none
 COMMON BLOCKS:
       NONE
 EXAMPLE:
	IDL> !Y.OMARGIN=[0,1]
	IDL> plot,indgen(100)
	IDL> fancy_title, 'This is my title', 100523 
 NOTES:
       You'll probably want a little more room at the top of your plots, e.g.
	IDL> !Y.OMARGIN=[0,1]
 MODIFICATION HISTORY:
	19-Sep-2008 reduce font size if title won't fit on screen
	30-May-2007 Use charsize in positing shot #
       21-Sep-00 Written by Bill Davis, PPPL

(See src/idl_cvs/fancy_title.pro)


GA_PLOTW

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

 PURPOSE:
	Plot widget for "table" of data, or input X & Y arrays.

 CATEGORY:
	Plotting, GA Plot Objects

 KEYWORDS:
	indicesPlot - indices to plot (plot if =1).
			Same 1st dimension as Y (if Y is 2-D)
			if just 1 dimension, and Y is two, use same mask for
			all y's.

 EXAMPLE:

    objRef = GA_PlotW( xdata=indgen(5), ydata=[1,3,5,4,2] )

  or
    table=strarr(3,8)
    table[0,*]= ['time','0.01','0.02','0.03','0.04','0.05','0.06','0.07']
    table[1,*]= ['Ip',  '1.0', '1.1', '1.3', '1.6', '1.6', '1.5', '1.3'  ]
    table[2,*]= ['Bt',  '.7',  '.71', '.73', '.76', '.75', '.65', '.59'  ]
    objRef = GA_PlotW( table=table )

  or
    objRef = GA_PlotW(table=['Bt', '.7',  '.71', '.73', '.76'] )

  or to make a scatter plot with a y=y line through it:

    x=findgen(100)
    noise = randomn(seed,100)*(x+20)/10
    y=(x+noise ) > 0
    objRef = GA_PlotW( xdata=x, ydata=transpose([[y],[x]]),plotnum=[0,0], $
                       psymbol=[10,7], linestyle=[6,0] )

  LIMITATIONS:
	"Marking" points on a plot will select correspongind row in table,
	if called "properly," as from plotdef__define.pro, but this only works
	for the last table created.

  MODIFICATION HISTORY
	21-Mar-2003 Allow for indices array to plot different xranges.
		    (Can then have different ranges have different colors, etc.)
	10-Dec-2002 Written by Bill Davis. Based on various object-oriented
		 plotting codes from General Atomics.

(See src/idl_cvs/ga_plotw.pro)


GRIDPLOT

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

 PURPOSE: 
	Widget for plotting a grid of data from MDSplus or gadat 
	This is an interactive version of ShotLoop. 
 	If at GA, assume that access will be through gadat only.
	When a plot on the grid is clicked on, it is expanded into a
	separate window.

 CATEGORY:
       Plotting, MDSplus, Example, GA

 CALLING SEQUENCE: 
	IDL> gridplot
   or  IDL> gridplot,tmin=2000,tmax=2002, SigFileName='mysigs.txt'

 INPUTS:
       none required  
    FILES:
	lastshot.txt - if this file (or that specified by ShotFileName
			keyword) is found, will initilize shot number 
			to that read from the first line of this file.
			If this file can not be found in the directory from
			which you are running, or in the IDL_PATH,
			the initial shot number will be set to the current
			machine shot minus 3.
	mdsplussig.txt - if this file (or that specified by SigFileName
			keyword) is found, will read signalnames from it
 KEYWORD PARAMETERS:
      Optional Keywords:
	  nSmooth - smoothing parameter to use when plotting data
	  nRows   - # of rows of plots (default to 6)
	  nCols   - # of colomns of plots (default to # signals/nrows)
	  printer - printer to send plots to (else goes to the default printer)
	  tmin - default plotting minimum for x-axis. (MDS in sec; GA in msec)
	  tmax - default plotting maximum for x-axis.
	  ShotFileName - File for storint last shot processed
			 (default:  lastshot.txt)
	  SigFileName - Signal names in the file will be plotted 
		     when you click on "Plot All." The names
		     should be one per row (default='mdsplusssig.txt')
	  sizeofplot - (2-element Real Array) x & y size of graphics area on widget 
			(but you are forced to stay on the screen).
 OUTPUTS:
       none from routine               			out
 COMMON BLOCKS:
       gp_SetupParams, gp_Info, gp_GridData, gp_widgetIDs
 EXAMPLE:
 MAJOR FUNCTIONS and PROCEDURES:
       PLOT: X-Y plotting.

 NOTES:
	PlotOne and PlotSomething
	are routines shared in common with ShotLoop.
 MODIFICATION HISTORY: Written by:  WMD, PPPL, April, 1999
                       for Hiro Takahashi work at General Atomics

(See src/idl_cvs/gridplot.pro)


LABELEVERYOTHERTICK

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

  PURPOSE:
 	Only label every other major tic mark.
 	The format of the numbers is customized.

 CATEGORY:
       Plotting, Graphics
  EXAMPLE 1 - Make a dummy plot call so can determine Tick Max:
	IDL> COMMON betterticklabels_common, yticklabels
	IDL> plot, y, ytick_get=yticklabels, ytickname=replicate(' ',30)
	IDL> AXIS, YAXIS=1, YRANGE=!y.crange, ytickformat='labeleveryothertick'
	IDL> dum = TEMPORARY(yticklabels)	; so doesn't affect later calls

  EXAMPLE 2 - Just take what you get (still pretty good):
	IDL> plot, y, ytickformat='labeleveryothertick'

  HISTORY:
	09-Oct-00 Written by Bill Davis

(See src/idl_cvs/labeleveryothertick.pro)


LINESOUT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       linesout
 PURPOSE:
 	Write lines out to an X window. Works like xyouts, but uses
	line #'s (from the top) and /right if you want to right justify text.  
 CATEGORY:
       Plotting, Strings
 CALLING SEQUENCE:
       IDL> linesout, text, line=line
 INPUTS:
       text - text string to write to window
 KEYWORD PARAMETERS:
	line - line # location, starting with 1 at the top (default=1)
	right - if set, text will be right-justified, rather than left
	center - if set, will center line (default to left justify).
	charsize - character size of text (default to !p.charsize or 1)
	dropshadow - if set, make a drop shadow of thick=3 text
	thickDropShadow - thickness of drop shadow (default to 1, or 2 if /highlight)
	color - color of text
	dscolor - color of drop-shadow text (defaults to black or white)
	bottom - if set, write lines from bottom, instead of top.
 OUTPUTS:
       none
 COMMON BLOCKS:
       NONE
 EXAMPLE:
	IDL> !p.color=mk_color('black')
	IDL> !p.backround=mk_color('white')
	IDL> plot,indgen(11)
	IDL> linesout, 'Hi Mom', line=2, /right, /dropshadow, charsize=2, $
			color=mk_color('black'), dscolor=mk_color('red')
 NOTES:
 MODIFICATION HISTORY:
	24-Oct-2006 added bottom, xpos, ypos, thickDropShadow, & highlight keyword
       25-Aug-2005 Written by Bill Davis, PPPL

(See src/idl_cvs/linesout.pro)


MPLOTTITLE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       mplottitle
 PURPOSE:
       write a plot title with NSTX label and a list of shots on left
 CATEGORY:
       Plotting
 CALLING SEQUENCE:
       IDL> mplottitle, screenTitle, shots, HLP=hlp, $
	     COLORS=colors, LOGO=logo, $
	     CHARMAG=charMag, TopMargin=TopMargin, RIGHT=right, $
	     INSIDE=inside, XPOS=xPos
 INPUTS:
       screenTitle = whatever you want as the main plot title.  
       shots = array of shot numbers.
	
 KEYWORD PARAMETERS:
	HLP - When set, help information is printed.
	colors - color indices of each shot number (default = !p.color)
	logo - Characters to draw above shot list. Default = '=NSTX=
	TopMargin - in characters, extra space to shift down the characters
	right - if set, labels put on left
	inside - if set, lists shots inside plot box
	xPos - xPos, in Device Coordinates, for left side of shot list
		(overrides /RIGHT & /INSIDE)
 OUTPUTS:
       none
 COMMON BLOCKS:
       NONE
 EXAMPLES:
	IDL> !Y.OMARGIN=[0,1]
	IDL> plot,indgen(100)
	IDL> mplottitle, 'This is my title', [100523,100544]
	IDL> plot,indgen(100)
	IDL> cs=mk_color(/load, /quiet)
	IDL> colors=[cs.black, cs.red, cs.green, cs.blue, cs.magenta]
	IDL> mplottitle,' ', shots, colors=colors, logo='Shots:', $
                           charMag=1.35, topMargin=0.5
 NOTES:
       You'll probably want a little more room at the top of your plots, e.g.
	IDL> !Y.OMARGIN=[0,1]
 MODIFICATION HISTORY:
	19-Jan-06 Added psym keyword
	01-Oct-01 Added keywords for inside & right [BD]
       21-Sep-99 Written by Bill Davis, PPPL

(See src/idl_cvs/mplottitle.pro)


MULTIPLOT

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

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

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

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

(See src/idl_cvs/multiplot.pro)


OVPLOT

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

  PURPOSE:
       Just like oplot, except it calls vcomp to "visually compress" 
	an array for faster delivery of graphs at the expense of CPU time. 
	All data spikes should be retained.

  CATEGORY:
       Plotting

  CALLING SEQUENCE:
       ovplot, time, data, _extra=_extra

  KEYWORDS
     Just like for oplot

  COMMON BLOCKS:
       none

  EXAMPLE:
       IDL> vplot, time, data, title='whatever', xrange=[0,2]
       IDL> ovplot, time, data/2.

  NOTES:
       VComp assumes equally spaced data, but might be OK for some cases.
	Probably want to use VPlot for first plot, but not necessary.
  LIMITATIONS:
	This is compuationally intensive, so is not appropriate for
	all applications, but for I/O-bound plotting can speed up 10x or more.
       Will return y points for each x -- the min & max values.
       IF nFinal GE N_ELEMENTS(inData)*2 will just return inputs
  MODIFICATION HISTORY:
       Written 20-May-01 by Bill Davis

(See src/idl_cvs/ovplot.pro)


PLOT0CHECK

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       plot0check
 PURPOSE:
       Plots blank axis if no data in !x.range or !y.range
 CATEGORY:
       Plotting, X-Y Plotting
 CALLING SEQUENCE:
       IDL> plot0check, x, y, ...
 INPUTS:
       x, y, .. = just like on the PLOT command.  
 KEYWORD PARAMETERS:
       Keywords:
 OUTPUTS:
       none
 COMMON BLOCKS:
       NONE
 EXAMPLE:
	IDL>plot0check, x, y, line=1,color=1, /ylog
 NOTES:
 MODIFICATION HISTORY:
	03-Oct-02 recover if x & y not right dimensions in 2-D plotting
	18-May-01 Use Vcomp for "visual compression" if more points than resolution
       20-Nov-00 Written by Bill Davis, PPPL

(See src/idl_cvs/plot0check.pro)


PLOTCOLORFILL

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

 PURPOSE:
   Plots colorful bar charts

 CATEGORY:
	Plotting

 CALLING SEQUENCE:
   PLOTCOLORFILL, x, y, COLOR=col, BOTTOM=bot, WIDTH=wid, ...

 DESCRIPTION: 

   PLOTCOLORFILL plots a colorful vertical bar chart.  This may be
   useful in cases where two dimensions of information need to be
   conveyed in one plot.  [ I use it to show total intensity as a
   function of time on the vertical axis, and temperature is coded
   with color. ]

   Most aspects of the bars are configurable.  The color is specified
   by an array of colors, one for each bar.  [ Alternatively, a
   single color for the entire plot can be given. ] Also, one color
   can be designated as transparent.

   Stacked bar charts can be constructed using two calls to
   PLOTCOLORFILL.  See the example.

 INPUTS:

   X, Y - Two arrays which give the X and Y position of the points.
          In this style of plot, the x values should be monotonically
          increasing, but not necessarily monospaced (see WIDTH).

 OPTIONAL INPUTS:
   NONE

 INPUT KEYWORD PARAMETERS:

   COLOR - an array giving the color of each bar, or alternatively a
           scalar color for all of the bars.  The current color table
           is not changed.  Default is color "1"

   BOTTOM - normally the bottom of the bars is set to be zero.  You
            may either specify a scalar bottom value for all of the
            bars, or an array giving the bottom of each bar
            individually.  See the example to see how stacked bar
            charts can be constructed with this keyword.

   WIDTH - sets the width of each bar, globally or individually.
           Bars are centered on the "X" value, and extend 0.5 * WIDTH
           to either side.  Default is to assume monospacing, using
           the separation between the first two x values.

   TRANSPARENT - designates a color which is "transparent".  Any bars
                 with this color are simply not plotted.  Default is
                 no transparent color.

   PANEL, SUBPANEL - An alternate way to more precisely specify the
                     plot and annotation positions.  See SUBCELL.
                     Default is full-screen.

   POSITION - Position of the bar chart in normal coordinates.
              Overrides position given by PANEL/SUBPANEL.

   XRANGE, YRANGE - gives plot range for each dimension, as for other
                    plot commands.  Default is range of data.

   Other keywords are passed to the plot command directly.
           
 OUTPUTS:
   NONE

 PROCEDURE:

 EXAMPLE:

   Stacked barcharts can be constructed by first making one chart
   with a flat bottom, and then a second chart whose bottom is top of
   the first.

   x = findgen(30)
   y1 = x^2
   y2 = 400.-x
   c1 = bindgen(30)*3+1b
   c2 = 100b-bindgen(30)*3+1b
   plotcolorfill, x, y1,    color=c1, bottom=0.
   plotcolorfill, x, y1+y2, color=c2, bottom=y1, /noerase

 SEE ALSO:

   PLOTPAN

 EXTERNAL SUBROUTINES:

   SUBCELL, DEFSUBCELL, PLOTPAN

 AUTHOR:
   Craig B. Markwardt, NASA/GSFC Code 662, Greenbelt, MD 20770
   craigm@lheamail.gsfc.nasa.gov

 MODIFICATION HISTORY:
   Written, CM, 1997

(See src/idl_cvs/plotcolorfill.pro)


PLOTHIST

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
      PLOTHIST
 PURPOSE:
      Plot the histogram of an array with the corresponding abcissa.

 CATEGORY:
	Plotting
 CALLING SEQUENCE:
      plothist, arr, xhist, yhist, [, BIN=, /FILL, /NOPLOT, /OVERPLOT, PEAK=,
                                      ...plotting keywords]
 INPUTS:
      arr - The array to plot the histogram of.   It can include negative
            values, but non-integral values will be truncated.              

 OPTIONAL OUTPUTS:
      xhist - X vector used in making the plot  
              ( = lindgen( N_elements(h)) * bin + min(arr) )
      yhist - Y vector used in making the plot  (= histogram(arr/bin))

 OPTIONAL INPUT KEYWORDS:
      BIN -  The size of each bin of the histogram,  scalar (not necessarily
             integral).  If not present (or zero), the bin size is set to 1.
      /NOPLOT - If set, will not plot the result.  Useful if intention is to
             only get the xhist and yhist outputs.
      /OVERPLOT - If set, will overplot the data on the current plot.  User
            must take care that only keywords valid for OPLOT are used.
      PEAK - if non-zero, then the entire histogram is normalized to have
             a maximum value equal to the value in PEAK.  If PEAK is
             negative, the histogram is inverted.
      /FILL - if set, will plot a filled (rather than line) histogram.

 The following keywords take effect only if the FILL keyword is set:
      FCOLOR - color to use for filling the histogram
      /FLINE - if set, will use lines rather than solid color for fill (see
              the LINE_FILL keyword in the POLYFILL routine)
      FORIENTATION - angle of lines for fill (see the ORIENTATION keyword
              in the POLYFILL routine)
      FPATTERN - the pattern to use for the fill (see the PATTERN keyword
              in the POLYFILL routine)
      FSPACING - the spacing of the lines to use in the fill (see the SPACING
              keyword in the POLYFILL routine)

 Any input keyword that can be supplied to the PLOT procedure (e.g. XRANGE,
    LINESTYLE) can also be supplied to PLOTHIST.

 EXAMPLE:
       Create a vector of random 1000 values derived from a Gaussian of mean 0,
       and sigma of 1.    Plot the histogram of these values with a bin
       size of 0.1

       IDL> a = randomn(seed,1000)
       IDL> plothist,a, bin = 0.1

 MODIFICATION HISTORY:
        Written     W. Landsman            January, 1991
        Add inherited keywords W. Landsman        March, 1994
        Use ROUND instead of NINT  W. Landsman   August, 1995
        Add NoPlot and Overplot keywords.   J.Wm.Parker  July, 1997
        Add Peak keyword.   J.Wm.Parker  Jan, 1998
        Add FILL,FCOLOR,FLINE,FPATTERN,FSPACING keywords. J.Wm.Parker Jan, 1998
        Converted to IDL V5.0   W. Landsman 21-Jan-1998

(See src/idl_cvs/plothist.pro)


PLOTNORMAL

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
 	plotnormal 
 PURPOSE:
	plot a normal curve on top of a histogram of data
 CATEGORY:
	Plotting, Statistics, GUI
 CALLING SEQUENCE:
	plotnormalw, data,  BinSize=binsize, barFraction=barFrac,  $
	         title=title, NormalOverlay=NormalOverlay, $
                 WindowTitle=WindowTitle, GROUP_LEADER=group_leader, $
		 XSIZE=xsize_in, YSIZE=ysize_in, xtitle=xtitle, ytitle=ytitle, $
		 _extra=_extra
 INPUTS:
	data - 1-d array
 OUTPUTS:
	plot in graphics widget
 KEYWORDS:
    barFraction - fraction of interval over which bar is drawn (0-1) 
		   (default=0.5)
    BinSize -  The size of each bin of the histogram,  scalar (not necessarily
             integral).  If not present (or zero), the bin size is set to 1.
    NormalOverlay - if set, overlay a curve of the normal distribution
 EXAMPLE:
	IDL> data=randomN(seed, 100)
	IDL> plotnormalw, data, binsize=.5

 MODIFICATION HISTORY:
	25-Apr-2003 don't try to plot null values (as defined by SQL, too)
	March, 2003 Written by Bill Davis

(See src/idl_cvs/plotnormalw.pro)


PLOTNSHOTS

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

 PURPOSE: make scope-like plots with overlays from multiple shots.

 CATEGORY: 
	Plotting
 USAGE:
	IDL> plotnshots, shots, t1=t1, t2=t2, signames=signames,  $
        	tweenspace=tweenSpace, labels=labels, $
		titles=titles, scales=scales, $
		rightSpace=rightSpace, leftSpace=leftSpace, colSpace=colSpace, $
		pcharsize=pcharsize, bgtime=bgtime, ncols=ncols, nrows=nrows, $
		biglabel=biglabel, nSmooth=nSmooth, $
        	SigUnits=SigUnits, topLabel=topLabel, zeroPlot=zeroPlot, $
        	yMins=yMins,  yMaxes=yMaxes, SERVER=server, noLogo=noLogo, $
		anyProblem=anyProblem, sameXlabels=sameXlabels

 METHOD: Reads in all requested shots for a signal, so can autoscale plot
	  correctly. One big 1-D array created by appending new signals, so
	  signals with different # of points, sampling rate, etc., will work.

 EXAMPLE:
	IDL> plotnshots, [104500,104501], $
		 signames=['\wf::ip','\engineering::ip1']
 LIMITATIONS:
	If max of X-data is > 100, assume not time and plot separately.

  HISTORY:
  15-Nov-2008 if ymins or ymaxes are a scalar, use for all signals [BD]
  03-Jul-2008 put plot order back to list of devices, and to scope order
	      changed "tween" space to be constant.
  19-May-08  Fixed xticklen and xgridstyle use
  07-Nov-07  add option to have TOPLABEL='NONE' for no plot titles
  03-Oct-07  added /noshot keyword to EvalScopeTitle call 
  10-Aug-07  if t2 < t1, set=t1
  01-May-07  Added keyword 'ShowAllXvalues' to label all X axes
  06-Apr-07  get right default axis if plotting second dimension of 2-D array
  07-Mar-07  continued _extra keyword into all plotting routines, so things
	      thick=3 in the Expert Entry field on the web tools will work.
  28-Jul-06  remove auto scale if limits 1.e-5 difference
  01-Mar-06  set default to be suppresserrors=0 because typos causing confusion.
		changed MISSING DATA label
  30-Jan-06 (re-)fixed specifed colors for multiple shots.
  27-Jan-06 use x signal from scope, if present
  06-Sep-2005 added SuppressError keyword
  03-Aug-2005 allow colors to be input as an array or executable string
  20-May-02 - In autoscale X, force all x-axis to plot on largest x scale.
		also changed value indicating time (actually, meaning ranges
		won't be used) changed from 100 to 300.
  02-Jul-01 - convert from plot2shots, and plot 2-D images when 1 shot
  28-Jun-01 - added anyProblem keyword, and sameXlabels keyword  to 
		allow forcing time axis ticknames on plot
  18-May-01 - added vplot & ovplot for "visual compression"
  06-Mar-01 - added Yrange & made t1 & t2 be arrays
  06-Feb-02 - put back ability to display 2-D

(See src/idl_cvs/plotnshots.pro)


PLOTNSIGS

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

 PURPOSE: 
	make scope-like plots with overlays from multiple signals.
	this is the version of plotnshots that overlays different signals
	on the same axes

 CATEGORY: 
	Plotting
 USAGE:
	IDL> plotnsigs, shots, t1=t1, t2=t2, signames=signames,  $
        	tweenspace=tweenSpace, labels=labels, $
		titles=titles, scales=scales, $
		rightSpace=rightSpace, leftSpace=leftSpace, colSpace=colSpace, $
		pcharsize=pcharsize, bgtime=bgtime, ncols=ncols, nrows=nrows, $
		biglabel=biglabel, nSmooth=nSmooth, $
        	SigUnits=SigUnits, topLabel=topLabel, zeroPlot=zeroPlot, $
        	yMins=yMins,  yMaxes=yMaxes, SERVER=server, noLogo=noLogo, $
		anyProblem=anyProblem, sameXlabels=sameXlabels

 METHOD: Reads in all requested shots for a signal, so can autoscale plot
	  correctly. One big 1-D array created by appending new signals, so
	  signals with different # of points, sampling rate, etc., will work.

 EXAMPLE:
	IDL> plotnsigs, [104500,104500,104501,104501], $
		 signames=['\wf::ip','\engineering::ip1','\wf::ip','\engineering::ip1']
 LIMITATIONS:
	If 2-D data, will just take the first row for multiple plots.
	If max of X-data is > 100, assume not time and plot separately.

  HISTORY:
  07-Nov-07  add option to have TOPLABEL='NONE' for no plot titles
  31-Jul-07  created from plotnshots [BD]

(See src/idl_cvs/plotnsigs.pro)


PLOTSIG1VSSIG2

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

 PURPOSE: plot 1 MDSplus signal vs. another

 CATEGORY: 
	Plotting
 USAGE:
	IDL> plotSig1vsSig2, shots, t1=t1, t2=t2, signames=signames,  $
        	labels=labels, $
		titles=titles, scales=scales, $
		rightSpace=rightSpace, leftSpace=leftSpace, colSpace=colSpace, $
		pcharsize=pcharsize,  $
		biglabel=biglabel, nSmooth=nSmooth, $
        	SigUnits=SigUnits, topLabel=topLabel, zeroPlot=zeroPlot, $
        	yMins=yMins,  yMaxes=yMaxes, SERVER=server, noLogo=noLogo, $
		anyProblem=anyProblem, sameXlabels=sameXlabels


 EXAMPLE:
	IDL> plotSig1vsSig2, 116116, signames=['\wf::ip','\wf::itf']
 LIMITATIONS:
  HISTORY:
  06-Mar-06 Added HH:MM output option. Also, make title Y vs. X.
  09-Sep-05 Converted from plotnshots [BD]

(See src/idl_cvs/plotsig1vssig2.pro)


PLOTSYM

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	PLOTSYM
 PURPOSE:
	Define useful plotting symbols not in the standard !PSYM definitions.
 CATEGORY:
	Plotting
 EXPLANATION:
	After a 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, THICK=]

 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             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.
     THICK -  Thickness of unfilled symbols. Default is 1.

 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 an open circle as the symbol

      IDL> PLOTSYM, 0               ;Plotting symbol is a circle
      IDL> PLOT,X,Y,PSYM=8

 METHOD:
     Appropriate X,Y vectors are used to define the symbol and passed to the
     USERSYM command.

 REVISION HISTORY
      25-Feb-2005 added keyword usersym, for sending to Legend, for example [BD]
      Written       W. Landsman         June 1992
      18-JAN-1996    Added a square symbol, HCW.
      98Aug20         Added keyword thick parameter - RCB.

(See src/idl_cvs/plotsym.pro)


RESETPLT

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

 PURPOSE:              
	This procedure will reset all or a selection
       of the system plot variables to their initial values

 CATEGORY:             
	Plotting

 CALLING SEQUENCE:     
			resetplt,/all           ;clear the !p, !x, !y, !z
                       resetplt,/x,/z          ;clear the !x and !z variables
                       resetplt,/x             ;only clear the !x variable
                       resetplt,/x,/invert     ;clear all except the !x
 INPUTS:
       KEYWORDS:
               x,y,z,p = clear the appropriate variable
               all     = clear all, this is equivalent to /x,/y,/z,/p
               invert  = invert the logic. Clear all unselected variables.
                         Therefore "clearplt,/all,/invert" does nothing.
 OUTPUTS:      
	none
 COMMON BLOCKS:
       none.
 SIDE EFFECTS:
      The sytem plot variables are changed.
 MODIFICATION HISTORY:
       Written by: Trevor Harris, Physics Dept., University of Adelaide,
               July, 1990.

(See src/idl_cvs/resetplt.pro)


ROUNDEDAXISLIMITS

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       roundedAxisLimits
 PURPOSE:
       Find "nice" axis values, like IDL plot routine does.
 CATEGORY:
	Plotting
 CALLING SEQUENCE:
       v = roundedAxisLimits(x1,x2)
 INPUTS:
       x1 = Range minimum.                           in
       x2 = Range maximum.                           in
 KEYWORD PARAMETERS:
 OUTPUTS:
       v = 2-element array of "nice" axis limits.          out
 COMMON BLOCKS:
 LIMITATION:
	IDL> print,roundedaxislimits(0.0,.11)
	      0.00000     0.120000		OK, but
	IDL> print,roundedaxislimits(0.0,.12)
	      0.00000     0.125000		why not 0.12?
 NOTES:
	includes routines copyrighted by Johns Hopkins University (see below)
 MODIFICATION HISTORY:
       26-Jul-04 Written by Bill Davis

(See src/idl_cvs/roundedaxislimits.pro)


SCREEN_TITLE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       screen_title
 PURPOSE:
       write a plot title with shot date and time and NSTX label
 CATEGORY:
       Plotting
 CALLING SEQUENCE:
       IDL> screen_title, mytitle, ishot
 INPUTS:
       mytitle = whatever you want as the main plot title.  
       ishot = shot number.  
 KEYWORD PARAMETERS:
       Keywords:
	  noShot - if set, do not plot shot number
	  noTime - if set, do not plot time
	  charsize - character size
	  logo - if = 0 will not put logo on plot
	  nstx - if - 0 will not put =NSTX= logo on plot, vs. just NSTX
	  ALIGNMENT - alignment of title. Default to 0.5 (centered)
	  HLP - When set, help information is printed.
 OUTPUTS:
       none
 COMMON BLOCKS:
       NONE
 EXAMPLE:
	IDL> !Y.OMARGIN=[0,1]
	IDL> plot,indgen(100)
	IDL> screen_title, 'This is my title', 100523 
 NOTES:
       You'll probably want a little more room at the top of your plots, e.g.
	IDL> !Y.OMARGIN=[0,1]
 MODIFICATION HISTORY:
	17-Sep-2008 added logo and alignment keywords
	30-Jun-2008 added charsize and NSTX keywords
       21-Sep-00 Written by Bill Davis, PPPL

(See src/idl_cvs/screen_title.pro)


STACKPLOT

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

 PURPOSE: 
	An example of X-window widgets for plotting some GA data

 CATEGORY:             
	Plotting, Example, Widgets, GA

 CALLING SEQUENCE: 
	stackplot

 USE:
  	If you have a file named mdsplussig.txt in the directory
	from which you are running IDL, signal names in the file
	will be plotted when you click on "My Signals." The names
	should be one per row.

 MAJOR FUNCTIONS and PROCEDURES:
       PLOT: X-Y plotting.
       SMOOTH: Smooths data and overplots.

 MODIFICATION HISTORY: Written by:  WMD, PPPL, March, 1997
                       based on RSI's Forecast example
	26-Jan-99 Modified for using MDS at PPPL by Bill Davis
       21-Oct-97 WMD Simplified for IDL class example at GA
       15-Apr-97 WMD Changed for remote plotting test

(See src/idl_cvs/stackplot.pro)


VAXIS

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       vaxis
 PURPOSE:
 	shell around AXIS procedure that sees if number of minor y tick
	marks need to be reduced, and if the number of y tick labels need
	to be cut in half.
 CATEGORY:
       Plotting
 CALLING SEQUENCE:
       IDL> vaxis, /yaxis
 INPUTS:
       if /yaxis not set, will just call AXIS routine with whatever inputs are passed
 KEYWORD PARAMETERS:
   Optional:
	yminor - as in plot command
	yrange - as in plot command
	ystyle - as in plot command
	yTickFormat - defaults to 'LabelEveryOtherTick'
	debug - if set, will print things and stop in routine
	
 OUTPUTS:
       none
 COMMON BLOCKS:
       vplot_local
 EXAMPLE:
	IDL> a=mk_color()
	IDL> x=findgen(100)
	IDL> y=sin(x/8*4)*exp(x/30)
	IDL> pos=[.1,.77,.9,.9]
	IDL> plot,x,y,ystyle=8, pos=pos, yTickFormat='LabelEveryOtherTick', yminor=2
	IDL> vaxis, yaxis=1,/debug		;;; , yTickFormat='LabelEveryOtherTick'
 NOTES:

  WRITTEN 29-Oct-2007 By Bill Davis, PPPL.

(See src/idl_cvs/vaxis.pro)


VCOMP

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

  PURPOSE:
       "visually compress" (resample) an array for faster plotting of lines.
       All data spikes should be retained.
       Will return y points for each x -- the min & max values.
       IF nFinal GE N_ELEMENTS(inData)*2 will just return inputs

  CATEGORY:
       Plotting

  CALLING SEQUENCE:
       VComp, inTime, inData, outTime, outData, NFINAL=4096

  KEYWORDS
     Optional:
       NFINAL - # of points to "compress" to. Defaults to estimated
		 # of pixels on x axis

  COMMON BLOCKS:
       none

  EXAMPLE:
       IDL> vcomp, inTime, inData, outTime, outData, NFINAL=4096

  NOTES:
       assumes equally spaced data, but might be OK for some cases.
  LIMITATIONS:
	This doesn't work precisely when:
	1) only points are drawn, rather than connecting lines,
	2) the X values are not monotonically increasing, or
	3) even if X intervals are not constant (although errors would probably be subtle).
	
  MODIFICATION HISTORY:
	26-Jul-2004 NINT() introduced a bug in some cases; now fixed
	17-May-2004 Bug fixed: not going to full time range
	22-Apr-2004 If POS being used, x.margin irrelevant, so assume 0
       Written 10-Nov-99 by Bill Davis

(See src/idl_cvs/vcomp.pro)


VGDS_TITLE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       vgds_title
 PURPOSE:
       write a plot title with shot date and time and NSTX label
 CATEGORY:
       Plotting
 CALLING SEQUENCE:
       IDL> vgds_title, mytitle, ishot
 INPUTS:
       mytitle = whatever you want as the main plot title.  
       ishot = shot number.  
 KEYWORD PARAMETERS:
       Keywords:
	  noShot - if set, do not plot shot number
	  noTime - if set, do not plot time
	  TopMargin - in characters, extra space to shift down the characters
	  HLP - When set, help information is printed.
 OUTPUTS:
       none
 COMMON BLOCKS:
       NONE
 EXAMPLE:
	IDL> !Y.OMARGIN=[0,1]
	IDL> plot,indgen(100)
	IDL> vgds_title, 'This is my title', 100523 
 NOTES:
       You'll probably want a little more room at the top of your plots, e.g.
	IDL> !Y.OMARGIN=[0,1]
 MODIFICATION HISTORY:
       21-Sep-99 Written by Bill Davis, PPPL

(See src/idl_cvs/vgds_title.pro)


VPLOT

[Previous Routine] [List of Routines]
  NAME:
       vplot

  PURPOSE:
       Just like plot, except it calls vcomp to "visually compress" 
	an array for faster delivery of graphs at the expense of CPU time. 
	All data spikes should be retained.

  CATEGORY:
       Plotting

  CALLING SEQUENCE:
       vplot, time, data, _extra=_extra

  KEYWORDS
     Just like for plot (except you need both X & Y)
	xIsHHMM - plot x axis as time in HH:MM format (assume time in hours)

  COMMON BLOCKS:
       vplot_local

  EXAMPLE:
       IDL> vplot, time, data, title='whatever', xrange=[0,2]

  NOTES:
       VComp assumes equally spaced data, but might be OK for some cases.
	Use oVPlot for overplotting.
  LIMITATIONS:
	This is compuationally intense, so is not appropriate for
	all applications, but for I/O-bound plotting can speed up 10x or more.
       Will return y points for each x -- the min & max values.
       IF nFinal GE N_ELEMENTS(inData)*2 will just return inputs
  MODIFICATION HISTORY:
	11-Feb-2008 fixed bug for pingplot.pro
	30-Oct-2007 improve number of tick marks, and length.
	08-May-2006 added logic if _extra contains range, but both equal
	03-Mar-2006 add xIsHHMM keyword
	26-Jul-04 make so plots "nice" range, like IDL default, if 
	15-Apr-04 handle when no additional paramters entered
		  add keyword for xtick_get (seem to need to specify explicitly)
       Written 20-May-01 by Bill Davis

(See src/idl_cvs/vplot.pro)


Category: Printing

[List of Routines]


LIST_PRINTER_UNIX

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

 PURPOSE: 
	LIST available printers from /etc/printcap, 
		/etc/printcap.lprng or /etc/printers.conf

 CATEGORY: 
	Printing, Unix

 EXPLANATION:
	  Reads /etc/printcap, /etc/printcap.lprng, or /etc/printers.conf

 SYNTAX: 
	IDL> printers=list_printer_unix(desc)

 EXAMPLES: (see example in mk_pdmenu)

 INPUTS: None

 OUTPUTS: PRINTERS - printer que names

 Opt. Outputs: DESC -  description of each printer (doesn't work for printcap.lprng)

 Keywords: ERR - error messages

 Common: LIST_PRINTER_UNIX - contains last reading of printcap file

 Restrictions: Unix only.

 Side effects: None

 History     : Version 1,  8-Aug-1995, D M Zarro . Written
               Version 2,  1 July 1996, S.V.H.Haugan (UiO)
                       Added PSLASER/PSCOLOR/PSCOLOR2 environmentals check.
               1-Nov-2000, Kim Tolbert - Previously only worked for unix machines with
                       /etc/printcap file for printers (DEC, ?). Added check
                       for /etc/printers.conf (Sun) also.
               18-Dec-2001, Kim Tolbert.  Some unix (linux) allows pipe symbol (|) in
                       lp definition (like :lp=|/usr/share/printconf/jetdirectprint:\)
                       so have to look for names in lines with | but no colon in first column.
                       Also, names can be in lines with |, or lines with : (if not in
                       first column), so append result of both kinds of search instead of
                       doing one or the other.
                       Also, eliminate all comment lines first
		13-Jan-2003 added printcap.lprng to file search and remove
			blank printer names. If file=printcap.lprng, also
			look for printer names as first character of line. [Bill Davis]
 		112-May-2005 Made to work for Red Hat Enterprise Linux
			where names end with colon [BD]

(See src/idl_cvs/list_printer_unix.pro)


PPPL_PRINTERS

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

 PURPOSE:
       return an array of strings of printer descriptions at PPPL

 CATEGORY:
	Printing

 CALLING SEQUENCE:
 	printer_list = PPPL_Printers()

 INPUTS:
       StartShot - shot number to start from      in

 KEYWORD PARAMETERS:
    Inputs:
	FILENAME - name of file to read printer descriptions from
          an example of an entry in the file is:
		crc-color    - Color printer in B152

 OUTPUTS:
	printer_list - String Array

 EXAMPLE:
 	printer_list = PPPL_Printers()

 COMMON BLOCKS:

 NOTES:
	On VMS, the file read is PRINTERS_VMS.txt, on Unix it is
	   PRINTERS_UNIX.txt. Returns a blank for other systems.
 	If environmental variable local_idl_dir is defined, this routine
	   will look for the file in this area

 MODIFICATION HISTORY:
	18-May-2004 add 'not implemented' for windows, and which not working
       09-Jun-2003 If not on Unix or VMS, return a blank.
	26-Mar-1999 Written by Bill Davis

(See src/idl_cvs/pppl_printers.pro)


PS_FORM

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

 PURPOSE:

   This function displays a form the user can interactively manipulate
   to configure the PostScript device driver (PS) setup. The function returns
   a structure of keywords that can be sent directly to the DEVICE command
   via its _EXTRA keyword

 CATEGORY:

   Printing, Device Drivers, Hardcopy Output, PostScript Output

 PROCEDURE:

   This is a pop-up form widget. It is a modal or blocking widget.
   Keywords appropriate for the PostScript (PS) DEVICE command are returned.
   The yellow box in the upper right hand corner of the form represents the
   PostScript page. The green box represents the "window" on the PostScript
   page where the graphics will be drawn.

   Use your LEFT mouse button to move the plot "window" around the page.
   Use your RIGHT mouse button to draw your own plot window on the page.

   The CREATE FILE and ACCEPT buttons are meant to indicate slightly
   different operations, although this is sometimes confusing. My idea
   is that PS_FORM is a *configuration* dialog, something the user displays
   if he or she wants to change the way the PostScript device is configured.
   Thus, in many of my widget programs if the user clicks a "Write PostScript File"
   button, I just go ahead and write a PostScript file without displaying the
   form. (I can do this because I always keep a copy of the current device
   configuration in my info structure.) To get to the form, the user must
   select a "Configure PostScript Device" button.

   At that time, the user might select the ACCEPT button to just change
   the PostScript device configurations. Or the user can select the
   CREATE FILE button, which both accepts the configuration *and* creates
   a PostScript file. If you find the CREATE FILE button confusing, you
   can just edit it out of the form and use the ACCEPT button for the
   same purpose.

 HELP:

   formInfo = PS_FORM(/Help)

 USAGE:

  The calling procedure for this function in a widget program will look something
  like this:

     info.ps_config = PS_FORM(/Initialize)
     ...
     formInfo = PS_FORM(Cancel=canceled, Create=create, $
                        Defaults=info.ps_config, Parent=event.top)

     IF NOT canceled THEN BEGIN
        IF create THEN BEGIN
           thisDevice = !D.Name
           Set_Plot, "PS"
           Device, _Extra=formInfo

           Enter Your Graphics Commands Here!

           Device, /Close
           Set_Plot, thisDevice
        ENDIF
        info.ps_config = formInfo
     ENDIF

 OPTIONAL INPUT PARAMETERS:

    XOFFSET -- Optional xoffset of the top-level base of PS_Form. Default is
    to try to center the form on the display.

    YOFFSET -- Optional yoffset of the top-level base of PS_Form. Default is
    to try to center the form on the display.

 INPUT KEYWORD PARAMETERS:

    BITS_PER_PIXEL -- The initial configuration of the bits per pixel button.

    BLOCKING -- Set this keyword to make this a blocking widget under IDL 5.0.
    (All widget programs block under IDL 4.0.)

    COLOR -- The initial configuration of the color switch.

    DEFAULTS -- A stucture variable of the same type and structure as the
    RETURN VALUE of PS_FORM. It will set initial conditions. This makes
    it possible to start PS_FORM up again with the same values it had the
    last time it was called. For example:

       mysetup = PS_FORM()
       newsetup = PS_FORM(Defaults=mysetup)

    NOTE: Using the DEFAULTS keyword will nullify any of the other
    DEVICE-type keywords listed above (e.g., XSIZE, ENCAPSULATED, etc.)

    ENCAPSULATED -- The initial configuration of the encapsulated switch.

    FILENAME -- The initial filename to be used on the form.

    HELP -- Prints a helpful message in the output log.

    INCHES -- The initial configuration of the inches/cm switch.

    INITIALIZE -- If this keyword is set, the program immediately returns the
    "localdefaults" structure. This gives you the means to configue the
    PostScript device without displaying the form to the user. I use this
    to write a PostScript file directly and also to initialize my info
    structure field that contains the current PostScript form setup. Passing
    the setup structure into PS_FORM via the DEFAULTS keyword gives my PS_FORM
    a program "memory".

        info.ps_setup = PS_FORM(/Initialize)

    LANDSCAPE -- The initial configuration of the landscape/portrait switch.

    LOCALDEFAULTS -- A structure like the DEFAULTS structure. Used if the
    "Local Defaults" button is pressed in the form. This gives you the
    opportunity to have a "local" as well as "system" default setup.
    If this keyword is not used, the procedure PS_Form_Set_Personal_Local_Defaults
    is called. Use this procedure (see below) to define your own local
    defaults.

    XOFFSET -- The initial XOffSet of the PostScript window.

    YOFFSET -- The initial YOffSet of the PostScript window.

    XSIZE -- The initial XSize of the PostScript window.

    YSIZE -- The initial YSize of the PostScript window.

 OUTPUT KEYWORD PARAMETERS

    CANCEL -- This is an OUTPUT keyword. It is used to check if the user
    selected the "Cancel" button on the form. Check this variable rather
    than the return value of the function, since the return value is designed
    to be sent directly to the DEVICE procedure. The varible is set to 1 if
    the user selected the "Cancel" button. Otherwise, it is set to 0.

    CREATE -- This output keyword can be used to determine if the user
    selected the 'Create File' button rather than the 'Accept' button.
    The value is 1 if selected, and 0 otherwise.

 RETURN VALUE:

     formInfo = { PS_FORM_INFO, $
                  xsize:0.0, $        ; The x size of the plot
                  xoff:0.0, $         ; The x offset of the plot
                  ysize:0.0, $        ; The y size of the plot
                  yoff:0.0 $          ; The y offset of the plot
                  filename:'', $      ; The name of the output file
                  inches:0 $          ; Inches or centimeters?
                  color:0, $          ; Color on or off?
                  bits_per_pixel:0, $ ; How many bits per image pixel?
                  encapsulated:0,$    ; Encapsulated or regular PostScript?
                  landscape:0 }       ; Landscape or portrait mode?

 MAJOR FUNCTIONS and PROCEDURES:

   None. Designed to work originally in conjunction with XWindow,
   a resizable graphics window.

 MODIFICATION HISTORY:

   Written by: David Fanning, RSI, March 1995.
   Given to attendees of IDL training courses.

	19-Dec-02 fix for vms directories [Bill Davis]
   Modified to work when grapics device set to PostScript: 6 May 95.
   Modified to configure initial conditions via keywords: 13 October 95.
   Modified to load personal local defaults if LocalDefaults keyword not
      used: 3 Nov 95.
   Found and fixed bits_per_pixel error in Local Defaults setting
     procedure: 3 Nov 95.
   Modified to produce initial plot box with the same aspect ratio as
      the current graphics window. (XSIZE or YSIZE keywords overrule this
      behavior.) 22 Apr 96.
   Fixed annoying behavior of going to default-sized plot box when selecting
      the Landscape or Portrait option. Now keeps current plot box size.
      22 Apr 96.
   Made the size and offset text widgets a little bigger and changed the
      size and offset formatting from F4.2 to F5.2 to accomodate larger plot
      box sizes. 29 Apr 96.
   Fixed a bug in the filename text widget that caused a crash when a CR
      was hit. 3 Sept 96.
   Added the Initialize keyword to immediately return the "localdefaults"
      structure. 27 Oct 96.
   Fixed another problem with the BITS_PER_PIXEL keyword. 27 Oct 96.
   Made the return value a named structure of the name PS_FORM_INFO.
      3 Nov 96.
   Discovered and fixed a problem whereby YOFFSET was set incorrectly if
      LOCALDEFAULTS was used instead of DEFAULTS keyword. 3 Nov 96.
   Fixed bug in how Portrait mode was set using YSIZE and XSIZE keywords.
      25 Nov 96.
   Fixed a bug in how YOFFSET was calculated when in Landscape mode. 27 Nov 96.
   Fixed a memory leak with the local defaults pointer. 25 Jan 97.
   Added the CREATE keyword and modified the appearance of the form. 22 Apr 97.
   Modifed subroutine names to avoid confusion. 22 Apr 97.
   Fixed a bug I introduced when I added the CREATE keyword. 23 Apr 97.
   Modified the program for IDL 5. 30 May 97, DWF.
   Fixed Inches to CM exclusive button problem. 30 May 97, DWF.
   Fixed a problem when the widget is killed with the mouse. 30 May 97. DWF
   Added a Select Filename button. 12 Oct 97.
   Modified program layout slightly. 12 Oct 97.
   Added valid directory/file error checking for the filename. 12 Oct 97. DWF
   Added further support for IDL 5 modal functionality. 20 Oct 97. DWF

 AUTHOR:

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

(See src/idl_cvs/ps_form.pro)


SCREENDUMP

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       screendump
 PURPOSE:
       Postscript file from an IDL window, whether 8- or 24-bit graphics
 CATEGORY:
       Printing, 24-bit graphics
 CALLING SEQUENCE:
       IDL> screendump, filename, Encapsulated=encapsulated
 INPUTS:
       filename (or will be prompted)  
 KEYWORD PARAMETERS:
       Keywords:
	  Encapsulated - if set, will get encapsulated postscript
	  Right_Aspect - if set, will maintain aspect ration of window
 OUTPUTS:
       just the output file
 MODIFICATION HISTORY:
	09-May-02 Added bits_per_pixel=8 when not true color [BD]
		  still not working in 24-bit color (???)
	27-Jun-02 Added Right_Aspect keyword [BD]
	07-Mar-02 Added landscape determination [BD]
       ?? Written by David Fanning, www.dfanning.com.

(See src/idl_cvs/screendump.pro)


SETUP_PS

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

 PURPOSE:
   	open postscript file and set system variables for postscript device

 CATEGORY:
	Printing

 CALLING SEQUENCE:  
   	SETUP_PS, name, PRINTER=printer

 INPUTS:
    (Optional)
	name - name of file (defaults to IDL)
		(if no extention, will add .ps)

 KEYWORD PARAMETERS:
    Optional Inputs:
	PRINTER  - printer to send file to (else will be default printer)
		  NOTE: if PRINTER begins with postscript', file will not be 
			sent to a printer
	PORTRAIT - If set, print is in portrait mode
	FONT     - font for printing, e.g., TIMES, HELVETICA, AVANTGARDE,
		   BKMAN, BOLD, PALATINO, ZAPFCHANCERY, NARROW (Default is Times)
	AspectRatio - if set, Ascpect ratio of image is maintained
	CharMagnification - magnify !p.charsize (or, if !p.charsize=0, use as charsize)
       xsize 
	ysize
 OUTPUTS:
	none

 CALLING EXAMPLE:
   	 printer = 'picasso color printer'	; or
   	 printer = 'postscript color '		; or
   	 printer = 'b143 Laserwriter in B143'	; or
   	 printer = 'default printer'		; 
   	 setup_ps,'myplot', PRINTER=printer
   	 plot,indgen(11)			; any number of plot commands
   	 unsetup_ps				; send to printer and back to X

 RELATED ROUTINES:
   	unsetup_ps

 SIDE EFFECTS:
	System variables are changed until unsetup_ps is called.

 NOTE:
	If you haven't already, you may wish to plot on a white background, e.g.,
	   IDL> !p.background=MK_COLOR('white')
	   IDL> !p.color=MK_COLOR('black')

 MODICATION HISTORY:
   07-May-08 fixed when /ASPECTRATIO made plot bigger than one dimension
   19-Apr-04 Added Filename keyword
   03-Aug-01 Append .ps to output filename if not specified
   04-Apr-01 make max paper width 8.25 to account for A4 paper size.
		make margins 3/4" (rather than 1")
   21-May-99 Added Font keyword (default changed to Times) [BD]
    1-Apr-99 Added Portrait Keyword [BD]
   12-Feb-99 Write file in the login area. Don't send to D4D area. [BD]
		Printer can have "color" after the name (following a space)
   27-Jan-99   BD  - change y.margin settings
   10/15/97    BD  - Removed bold fonts and set to landscape mode
   10/13/97    TBT - Added phaser5
    6/11/97    TBT - took out printer from discolor and added as
                     a keyword
    5/22/97    TBT - added phaser4 & phaser4_trans & hpdj2
    5/21/97    TBT - added include discolor to get printer passed in.
    5/21/97    Ted Terpstra - Put in color printer check &
                              added phaser2 and phaser3 to the list.
    5-16-95    K. Greene -- When setting up output file name, check
               operating system.  VMS cannot use Unix format.

(See src/idl_cvs/setup_ps.pro)


SPAWNPRINT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       spawnprint
 PURPOSE:
       Spawn command on VMS or Unix to print a Postscript file
 CATEGORY:
       Printing
 CALLING SEQUENCE:
       IDL> spawnprint, filename, printer=printer
 INPUTS:
       filename (or will be prompted)  
 KEYWORD PARAMETERS:
       Keywords:
	  printer - else will go to the default printer
		  NOTE: if PRINTER begins with postscript', file will not be 
			sent to a printer
 OUTPUTS:
       none
 MODIFICATION HISTORY:
       07-Mar-02 Written by Bill Davis

(See src/idl_cvs/spawnprint.pro)


UNSETUP_PS

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

 PURPOSE:
   	close a postscript file (opened by setup_ps) and re-set system 
	variables for previous device.

 CATEGORY:
	Printing, Cross-platform Printing of Plots

 CALLING SEQUENCE:  
   	UNSETUP_PS, name, PRINTER=printer

 INPUTS:
    (Optional)
	name - name of file without extenstion (defaults to IDL)
		(extention will always be .ps)

 KEYWORD PARAMETERS:
    Inputs:
	PRINTER  - printer to send file to (only the string before the
		   first blank is used). The printer may have been
		   specified in the call to SETUP_PS, else the default 
		   is used printer.
		  NOTE: if PRINTER='postscript', file will not be sent
			to a printer
	NOHEADER - if set, -h is inserted in lpr command
 OUTPUTS:
	none

 CALLING EXAMPLE:
   	 printer = 'picasso color printer'	; or
   	 printer = 'postscript color '		; or
   	 printer = 'b143 Laserwriter in B143'	; or
   	 printer = 'default printer'		; 
   	 setup_ps,'myplot', PRINTER=printer
   	 plot,indgen(11)			; any number of plot commands
   	 unsetup_ps				; send to printer and return to X

 RELATED ROUTINES:
   	setup _ps

 MODICATION HISTORY:
   05-Feb-03 added keyword NoHeader
   12-Feb-99 If printer = 'postscript' or 'file', don't send to 
		a printer.  If printer = 'default', send to the 
		default printer (i.e., none specified)
		Write file in the login area.
   27-Jan-99 adapt for SunOS; change y.margin settings [BD]
   14-Oct-97 Written by Bill Davis

(See src/idl_cvs/unsetup_ps.pro)


UNSETUP_TEK

[Previous Routine] [List of Routines]
 NAME:
       unsetup_tek

 PURPOSE:
   	undo system variables from setup_tek call.

 CATEGORY:
	Printing, Cross-platform plotting

 CALLING SEQUENCE:  
   	UNsetup_tek

 INPUTS:
    (Optional)
	name - name of file without extenstion (defaults to idl)
		(extention will always be .tek)

 KEYWORD PARAMETERS:
 OUTPUTS:
	none

 CALLING EXAMPLE:
   	 setup_tek
   	 plot,indgen(11)			; any number of plot commands
   	 unsetup_tek				; send to printer and back to X

 RELATED ROUTINES:
   	setup_tek
 LIMITATIONS
	If using the CH_ crosshair routines, will need to call the following
	after this routine:
	   IDL> CH_SET, yourGraph, NewX=!x,NewY=!y,NewP=!p
 MODICATION HISTORY:
   	13-Feb-06 add XTC calls
	08-May-01 call CH_SET, if user calling cross-hair routines
   	26-Oct-00 Written by Bill Davis

(See src/idl_cvs/unsetup_tek.pro)


Category: Programming

[List of Routines]


ADD_TAG

[Next Routine] [List of Routines]

 NAME:
    ADD_TAG
       
 PURPOSE:
    Add a new tag to the structure. NOTE: if you want to add more
    than one tag at once, use ADD_TAGS

 CATEGORY:
    Programming
 
 CALLING SEQUENCE:
    add_tag, oldstruct, tagname, tagValue, newstruct, structyp=structyp

 INPUTS: 
    oldstruct: The original structure (or array of structures)
    tagname: string containing the new tag name
    tagValue: the initial value of the new tag, e.g. fltarr(5)
           or [3,5,6], or 0L, etc.

 KEYWORD PARAMETERS:
   structyp: a string with the name of the new structure.
     if already defined an error is printed.

 OUTPUTS: 
    newstruct: The structure with the new tag it it.

 OPTIONAL OUTPUT
    NONE

 CALLED ROUTINES:
    COMBINE_STRUCTS
 

 REVISION HISTORY:
    25-OCT-2000, Judith Racusin.
       
                                      

(See src/idl_cvs/add_tag.pro)


ARRAY_EQ

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	ARRAY_EQ
 PURPOSE:
  	Return TRUE if two arrays are equal, else false.
 CATEGORY:
       Programming
 CALLING SEQUENCE: 
	logical=ARRAY_EQ(array1,array2)

 INPUTS:   
	bigArray - an array of numbers to look in
  	littleArray - an array to look for matches in bigArray
 OUTPUTS:
	logical - 0/1

 COMMON BLOCKS:
 NOTES:
 MODIFICATION HISTORY:
 	17-May-99 WMD Written

(See src/idl_cvs/array_eq.pro)


BELL

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       BELL
 PURPOSE:
       Ring terminal bell.
 CATEGORY:
	Programming, Sound, Errors
 CALLING SEQUENCE:
       bell, [n]
 INPUTS:
       n = number of rings (def=1).  in
 KEYWORD PARAMETERS:
 OUTPUTS:
 COMMON BLOCKS:
 NOTES:
 MODIFICATION HISTORY:
       R. Sterner, 20 Oct, 1989.

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

(See src/idl_cvs/bell.pro)


CAST

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       CAST
 PURPOSE:
       Generalized type casting.  Converts variables whose type code is out 
       of the range [LOW,HIGH] into this range.
 CATEGORY:
       Programming, type conversion
 CALLING SEQUENCE:
       Result = CAST( X, [LOW [,HIGH]])
 INPUTS:
    X
       Numerical, arbitrary, or a character representation of a number(s).
    LOW
       Number representing a type code, range (1:9).  If greater than 9, it is
       set to 9.  If less then 1, or not given, it is set to 1.
 OPTIONAL INPUT PARAMETERS:
    HIGH
       Type code, same as LOW.  Default value is 9.  If provided and less then
       LOW, it is set to LOW.
 KEYWORD PARAMETERS:
    /FIX
       Switch.  If set, the output is filtered through FPU_FIX, eliminating
       floating underflow errors.
 OUTPUTS:
       If the type of X is < LOW, CAST returns X converted to type LOW.
       If the type of X is > HIGH, CAST returns X converted to type HIGH.
       Otherwise CAST returns X.
 OPTIONAL OUTPUT PARAMETERS:
       None.
 COMMON BLOCKS:
       None.
 SIDE EFFECTS:
       None.
 RESTRICTIONS:
       1)  An attempt to convert a string which is NOT a character 
           representation of a number into a numeric type will yield error.
       2)  X cannot be a structure or pointer, but can be a structure element.
       3)  The value 8 for either LOW or HIGH is not allowed (since it 
           corresponds to structure type).  Value of 10 and above is ignored.
 PROCEDURE:
       Identifies the type of X, and if out of the range given by [LOW,HIGH]
       calls the proper conversion routine using the system routine 
       CALL_FUNCTION.  Also uses FPU_FIX and ISNUM from MIDL.
 MODIFICATION HISTORY:
       Created 25-DEC-1991 by Mati Meron.
       Modified 15-JUN-1995 by Mati Meron to accept the new DOUBLECOMPLEX type.
       Modified 25-SEP-1998 by Mati Meron.  Underflow filtering added.

(See src/idl_cvs/cast.pro)


COMBINE_STRUCTS

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

 PURPOSE:
  takes two arrays of structures str1,str2 which have the
  same number of elements but possibly different tags
  and makes another structure which has the same number of elements
  but the tags of both str1,str2 and has their respective tags 
  values copied into it

 CATEGORY:
    Programming
 
 CALLING SEQUENCE
    combine_structs, struct1, struct2, newstruct, structyp=structyp

 INPUTS:
    struct1,struc2: The two structures to be combined. If structure arrays, 
               Must contain the same number of structs.

 KEYWORD PARAMETERS:
   structyp: a string with the name of the new structure.
     if already defined the program will crash.

 Author Dave Johnston UofM

(See src/idl_cvs/combine_structs.pro)


DATATYPE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       DATATYPE
 PURPOSE:
       Datatype of variable as a string (3 char or spelled out).
 CATEGORY:
	Programming
 CALLING SEQUENCE:
       typ = datatype(var, [flag])
 INPUTS:
       var = variable to examine.         in
       flag = output format flag (def=0). in
 KEYWORD PARAMETERS:
       Keywords:
         /DESCRIPTOR returns a descriptor for the given variable.
           If the variable is a scalar the value is returned as
           a string.  If it is an array a description is return
           just like the HELP command gives.  Ex:
           datatype(fltarr(2,3,5),/desc) gives
             FLTARR(2,3,5)  (flag always defaults to 3 for /DESC).
 OUTPUTS:
       typ = datatype string or number.   out
          flag=0    flag=1      flag=2    flag=3
          UND       Undefined   0         UND
          BYT       Byte        1         BYT
          INT       Integer     2         INT
          LON       Long        3         LON
          FLO       Float       4         FLT
          DOU       Double      5         DBL
          COM       Complex     6         COMPLEX
          STR       String      7         STR
          STC       Structure   8         STC
          DCO       DComplex    9         DCOMPLEX
 COMMON BLOCKS:
 NOTES:
 MODIFICATION HISTORY:
       Written by R. Sterner, 24 Oct, 1985.
       RES 29 June, 1988 --- added spelled out TYPE.
       R. Sterner, 13 Dec 1990 --- Added strings and structures.
       R. Sterner, 19 Jun, 1991 --- Added format 3.
       R. Sterner, 18 Mar, 1993 --- Added /DESCRIPTOR.
       R. Sterner, 1995 Jul 24 --- Added DCOMPLEX for data type 9.
       Johns Hopkins University Applied Physics Laboratory.

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

(See src/idl_cvs/datatype.pro)


GET_DELIM

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	get_delim
 PURPOSE:
	returns file delimiter that is appropriate to VMS,  UNIX or Windows
 CATEGORY:
	Programming
 CALLING SEQUENCE:
	delim=get_delim()
 INPUTS:
	none
 OUTPUTS:
       delim=':' if VMS, '\' if Windows, '/' otherwise
 PROCEDURE:
	checks !version.os system variable
 MODIFICATION HISTORY:
       Written DMZ (ARC) May 1992
       Modified DMZ(SAC) Sept 1997 - added Windows

(See src/idl_cvs/get_delim.pro)


INT_DEFINED

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       int_defined
 PURPOSE:
       see if a value is defined and is an integer
 CATEGORY:
	programming
 CALLING SEQUENCE:
        logical = INT_DEFINED( whatever )
 INPUTS:
       whatever - any IDL variable      in
 KEYWORD PARAMETERS 
	none
 OUTPUTS:
	logical - 1 if an integer, 0 if not (or if not defined)
 EXAMPLE:
 COMMON BLOCKS:
 NOTES:
 MODIFICATION HISTORY:
     1999 Written by Bill Davis

(See src/idl_cvs/int_defined.pro)


ISARRAY

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       ISARRAY
 PURPOSE:
       Tests if the argument is an array.
 CATEGORY:
	Programming
 CALLING SEQUENCE:
       flag = isarray(a)
 INPUTS:
       a = variable to test.                                in
 KEYWORD PARAMETERS:
 OUTPUTS:
       flag = test result: 0 if not array, else non-zero.   out
 COMMON BLOCKS:
 NOTES:
 MODIFICATION HISTORY:
       R. Sterner  20 Mar, 1986.
       Checked for undefined variables.  RES 25 Aug, 1989.
       Johns Hopkins Applied Physics Lab.

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

(See src/idl_cvs/isarray.pro)


ISNUM

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       ISNUM
 VERSION:
       3.0
 PURPOSE:
       Checks whether the input is a number.
 CATEGORY:
       Programming.
 CALLING SEQUENCE:
       Result = ISNUM(X)
 INPUTS:
    X
       Arbitrary, doesn't even have to exist.
 OPTIONAL INPUT PARAMETERS:
       None.
 KEYWORD PARAMETERS:
    /DOUBLE
       Switch.  If set the result is 1 only if X is DOUBLE or DCOMPLEX.
    /COMPLEX
       Switch.  If set the result is 1 only if X is COMPLEX or DCOMPLEX.
    TYPE
       Optional output.  See below.
 OUTPUTS:
       Returns 1 if X is number, 0 otherwise.  Output type is byte.
 OPTIONAL OUTPUT PARAMETERS:
    TYPE
       The name of the variable to receive the numeric code of the type of X.
       Included for convenience to save an additional call to TYPE.
 COMMON BLOCKS:
       None.
 SIDE EFFECTS:
       None.
 RESTRICTIONS:
       None.
 PROCEDURE:
       Straightforward.  Using TYPE from MIDL.
 MODIFICATION HISTORY:
       Created 15-JUN-1995 by Mati Meron.
       Modified 5-MAY-1996 by Mati Meron.  Added keywords DOUBLE, COMPLEX and
       TYPE.

(See src/idl_cvs/isnum.pro)


MAXSTRUCT

[Previous Routine] [Next Routine] [List of Routines]
  NAME:
 	maxstruct
  PURPOSE:
	find the maximum of a structure 
	  (ignores structures within the input structure)
  CATEGORY:
	Programming, Math
  EXAMPLE:
	IDL> structure = { a: 2.3, b:10, c:[2.1,22.3], d:'Hi Mom' }
	IDL> print, maxstruct(structure)
		 22.3000
	IDL> structure2 = { a: 2.3, b:10, c:[2.1,99], d:'Hi Mom' }
	IDL> structure = [structure, structure2]
	IDL> print, maxstruct(structure)
		 99.0000
	IDL> inStruc = {a:77., b:88., c:101.}
	IDL> structure = { a: 2.3, b:10, c:[2.1,22.3], d:'Hi Mom', e:inStruc }
	IDL> print, totstruct(structure)
		101.000
  NOTES: 
	will not consider values in sub-structures
  MODIFICATIONS
	25-Mar-2008 handles arrays of structures, and go into nested 
		structures [BD]
	01-Dec-2006 Ignore non-numeric structure elements [BD]

(See src/idl_cvs/maxstruct.pro)


MINMAX

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       minmax
 PURPOSE:
       print the min and the max of an array
 CATEGORY:
	programming
 CALLING SEQUENCE:
        minmax, a
 INPUTS:
       a- an array     in
 KEYWORD PARAMETERS 
 OUTPUTS:
	none (just printing to IDL session)
 EXAMPLE:
 COMMON BLOCKS:
 NOTES:
 MODIFICATION HISTORY:
     1998 Written by Bill Davis

(See src/idl_cvs/minmax.pro)


MSG_BELL

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       Msg_Bell
 PURPOSE:
       Print a message to the IDL session and ring a bell
 CATEGORY:
	Programming. Terminal Outpout
 CALLING SEQUENCE:
       Msg_Bell, msg, nrings
 INPUTS:
       msg - string to print to the IDL session
       nrings - (OPTIONAL) # of times to ring
 KEYWORD PARAMETERS:
 OUTPUTS:
 EXAMPLE:
 COMMON BLOCKS:
 NOTES:
 MODIFICATION HISTORY:
	1997 Written by Bill Davis

(See src/idl_cvs/msg_bell.pro)


PRONAME

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

 PURPOSE:
	This function retrieves the name of the currently active procedure.

 CATEGORY:
       Programming

 INPUTS:
       none
  OUTPUT:
	The output is a string containing the name of the procedure

 KEYWORD:
	none

 MODIFICATION HISTORY:
	20-Aug-07 add checks for array length (when window too narrow,
		  array elements are not right)
 Written by B.P. LeBlanc following a hint by Bill Davis, 01-DEC-2006

(See src/idl_cvs/proname.pro)


PTR_FREE_RECURSIVELY

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

 PURPOSE:
  This routine when passed a pointer will free up any memory associated
  with that pointer. This includes structures, which could contain
  pointers, or other structures which could in turn contain more
  pointers. It also destroys objects it comes across. It can also
  cope with null pointers that are found on its travels.

 CATEGORY:
  programming

 CALLING SEQUENCE:
  Ptr_Free_Recursively, AValidPointer

 INPUTS:
  InitialPointer: The pointer whose 'heap memory hierachy' will be freed.

 KEYWORD PARAMETERS:
  None.

 OUTPUTS:
  None.

 COMMON BLOCKS:
  None, of course.

 SIDE EFFECTS:
  Well as far as I can see, there are none. But please try and find them
  so I can improve the program.

 RESTRICTIONS:
  The program will destroy any objects it meets but if the cleanup
  methods for those objects are not tight then there will be leakage.
  There are no restrictions on the number of levels of referencing -
  the routine is totally general.
  Also you must have my modified version of coyotelist (DWF).

 EXAMPLE:
 First you have to have a valid pointer and while obviously your hierachy
 doesn't have to be as complictated as this, the example shows just what
 it can do.

 ThisPointer = Ptr_New( [Ptr_New(), $
       Ptr_New({h:'hello', point0:ptr_new(ptr_new(ptr_new($
         {string:'hello', point1:ptr_new(),point2:ptr_new('hello')}))), $
           point3:ptr_new(), b:'bye'}), $
       Ptr_New('Hello'), $
       Ptr_New({Object:Obj_New('Coyotelist'), Point4:Ptr_New(), $
            Point5:[ptr_new('hello'),ptr_new('bye')]})  $
         ])

 Ptr_Free_Recursively, ThisPointer
       ............and all your memory will be gone.

 MODIFICATION HISTORY:
  Written by: Phil Aldis
 March 3rd, 1999: Fixed the last few bugs and attempted to make the comments
   a bit clearer.   PJA
 AUTHOR:

  Philip Aldis
  14 Milton Road,
  Bentley Heath,
  B93 8AA.
  Phone: 0044 1564 773437
  E-Mail:philaldis@geocities.com

(See src/idl_cvs/ptr_free_recursively.pro)


SAMETYPE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       sameType
 PURPOSE:
       make two variables the same numerical type
 CATEGORY:
       Programming
 CALLING SEQUENCE:
       IDL> sametype, x, y
 INPUTS:
       inputs - numerical scalars or arrays
		(not for structures or strings)
 OUTPUTS:
      inputs are re-typed, as needed
 MODIFICATION HISTORY:
       30-Jan-2007 Written by Bill Davis, PPPL

(See src/idl_cvs/sametype.pro)


SIZE_STRUCT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	SIZE_STRUCT
 PURPOSE:
	Obtain the size in bytes of an IDL structure definition.    
 CATEGORY:
	Programming
 CALLING SEQUENCE:
			bytes = size_struct( structure )
	examples:
			print, size_struct( "fdq_sdf" )
 INPUTS:
		structure = a structure variable or
				a string giving the structure name
				as known by IDL (help,/struct,variable).
		/PRINT = to print all sub structure sizes.

 inputs/outputs used recursively:
		struct = the structure VARIABLE currently analyzed.
		Max_Field_Size = size of the largest field found in structure.
 RESULT:
		Function returns the total size in bytes of a structure element.
 EXPLANATION:
	For most applications this function is superceded by use 
	of the /LENGTH keyword to the intrinsic N_TAGS function 
	introduced in IDL V2.3.0

 PROCEDURE:
		Strategy is to call size_struct recursively if
		structure contains sub-structures.
		Otherwise just add up the field sizes.

 MODIFICATION HISTORY:
	written 1990 Frank Varosi STX @ NASA/GSFC (using align_struct).
	Converted to IDL V5.0   W. Landsman   September 1997

(See src/idl_cvs/size_struct.pro)


TOTSTRUCT

[Previous Routine] [Next Routine] [List of Routines]
  NAME:
 	totstruct
  PURPOSE:
	find the total of numerical values in a structure 
	  (ignores structures within the input structure)
  CATEGORY:
	Programming, Math
  EXAMPLE:
	IDL> structure = { a: 2.3, b:10, c:[2.1,22.3], d:'Hi Mom'}
	IDL> print, totstruct(structure)
		 36.7
	IDL> structure2 = { a: 2.3, b:10, c:[2.1,99], d:'Hi Mom' }
	IDL> structure = [structure, structure2]
	IDL> print, totstruct(structure)
		 99.0000
	IDL> inStruc = {a:77., b:88., c:101.}
	IDL> structure = { a: 2.3, b:10, c:[2.1,22.3], d:'Hi Mom', e:inStruc }
	IDL> print, totstruct(structure)
		 302.700
  NOTES: 
	will not consider values in sub-structures
  MODIFICATIONS
	25-Mar-2008 handles arrays of structures, and go into nested 
		structures [BD]
	01-Dec-2006 Ignore non-numeric structure elements [BD]

(See src/idl_cvs/totstruct.pro)


TYPE

[Previous Routine] [List of Routines]
 NAME:
       TYPE
 VERSION:
       3.0     
 PURPOSE:
       Finds the type class of a variable.
 CATEGORY:
       Programming.
 CALLING SEQUENCE:
       Result = TYPE(X)
 INPUTS:
    X
       Arbitrary, doesn't even need to be defined.
 OPTIONAL INPUT PARAMETERS:
       None.
 KEYWORD PARAMETERS:
       None.
 OUTPUTS:
       Returns the type of X as a long integer, in the (0,9) range.
 OPTIONAL OUTPUT PARAMETERS:
       None.
 COMMON BLOCKS:
       None.
 SIDE EFFECTS:
       None.
 RESTRICTIONS:
       None.
 PROCEDURE:
       Extracts information from the SIZE function.
 MODIFICATION HISTORY:
       Created 15-JUL-1991 by Mati Meron.

(See src/idl_cvs/type.pro)


Category: Smoothing

[List of Routines]


AMEDIAN

[Next Routine] [List of Routines]
 NAME:
       AMEDIAN
 PURPOSE:
       Works the same as MEDIAN, but the effect tapers off at the edges.
 CATEGORY:
       Smoothing, Math
 CALLING SEQUENCE:
       Result = AMEDIAN( ARRAY, WIDTH )
 INPUT PARAMETERS:
       ARRAY   = One or two-dimensional array to be median filtered.
       WIDTH   = Width of the median filter box.
 OPTIONAL KEYWORD PARAMETERS:
       None.
 COMMON BLOCKS:
       None.
 SIDE EFFECTS:
       None.
 RESTRICTIONS:
       ARRAY must be one or two-dimensional.
 PROCEDURE:
       A larger array is constructed with the border filled with the reflected
       edges of the original array.  Then MEDIAN is applied to this larger
       array, and the area corresponding to the original array is returned as
       the result of the function.
 MODIFICATION HISTORY:
	15-Jul-2008 for True Color images (dimensioned [3,xsize,ysize]), smooth over each
		    color.
   	12-Jun-01 Made work for 1 dimension of 2 being small. [BD]
   	21-Feb-01 Just return array if width < or = 1. [BD]
       WRITTEN by William Thompson, February 1993.

(See src/idl_cvs/amedian.pro)


MEDSMOOTH

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

 PURPOSE:
       Median smoothing of a vector, including point near it's ends.

 CATEGORY:
	Smoothing, Math
 CALLING SEQUENCE:
       SMOOTHED = MEDSMOOTH( VECTOR, WINDOW_WIDTH )

 INPUTS:
       VECTOR  = The vector to be smoothed
       WINDOW = The full width of the window over which the median is 
               determined for each point.

 OUTPUT:
       Function returns the smoothed vector

 SUBROUTINES CALLED: 
       MEDIAN, to find the median

 PROCEDURE:
       Each point is replaced by the median of the nearest WINDOW of points.
       The width of the window shrinks towards the ends of the vector, so that
       only the first and last points are not filtered. These points are 
       replaced by forecasting from smoothed interior points.

 REVISION HISTORY:
       Written, H. Freudenreich, STX, 12/89
       H.Freudenreich, 8/90: took care of end-points by shrinking window.

(See src/idl_cvs/medsmooth.pro)


POLY_SMOOTH

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

 PURPOSE:
       Reduce noise in 1-D data (e.g. time-series, spectrum)
       but retain dynamic range of variations in the data by
       applying a least squares smoothing polynomial filter,
       also called the Savitzky-Golay smoothing filter.
       The low-pass filter coefficients are computed by effectively
       least-squares fitting a polynomial in moving window,
       centered on each data point, so the new value will be the
       zero-th coefficient of the polynomial. Approximate first derivates
       of the data can be computed by using first degree coefficient of
       each polynomial, and so on. The filter coefficients for a specified
       polynomial degree and window width are computed independent of any
       data, and stored in a common block. The filter is then convolved
       with the data array to result in smoothed data with reduced noise,
       but retaining higher order variations (better than averaging).

 CATEGORY:
	Smoothing, Math

 CALLING SEQUENCE:

       spectrum = poly_smooth( data, width, DEGREE=4 )

 INPUTS:
       data = 1-D array, such as a spectrum or time-series.

       width = total number of data points to use in filter convolution,
               (default = 5, using 2 past and 2 future data points),
               must be larger than DEGREE of polynomials, and a guideline is 
               make WIDTH between 1 and 2 times the FWHM of desired features.

 KEYWORDS:

       DEGREE = degree of polynomials to use in designing the filter
               via least squares fits, (default DEGREE = 2), and
               the higher degrees will preserve sharper features.

       NLEFT = # of past data points to use in filter convolution,
               excluding current point, overrides width parameter,
               so that width = NLEFT + NRIGHT + 1.  (default = NRIGHT)

       NRIGHT = # of future data points to use (default = NLEFT).

       DERIV_ORDER = order of derivative desired (default = 0, no derivative).

       COEFFICIENTS = optional output of the filter coefficients applied,
               but they are all stored in common block for reuse, anyway.
 RESULTS:
       Function returns the data convolved with polynomial filter coefs.

 COMMON BLOCKS:
       common poly_smooth, degc, nlc, nrc, coefs, ordermax
 PROCEDURE:
       As described in Numerical Recipies, sec.14.8, Savitsky-Golay filter.
       Matrix of normal eqs. is formed by starting with small terms
       and then adding progressively larger terms (powers).
       The filter coefficients of up to derivative ordermax are stored
       in common, until the specifications change, then recompute coefficients.
       Coefficients are stored in convolution order, zero lag in the middle.
 MODIFICATION HISTORY:
       Written, Frank Varosi NASA/GSFC 1993.

(See src/idl_cvs/poly_smooth.pro)


RESAMPLE

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

 PURPOSE:
       Resample a vector with triangular smoothing.

 CATEGORY:
	Smoothing

 CALLING SEQUENCE:
       smallerVector = resample( VECTOR, nth )

 INPUTS:
       VECTOR  = The vector to be smoothed
       nth = The full width of the window over which the median is 
               determined for each point (if even, use window+1).

 OUTPUT:
       Function returns every nth point of the smoothed input vector
 KEYWORDS:
	Indices - Optionally returned. Indices of resulting vector
	Guass - if set, will do psuedo-gaussian weighting, rather than triagular

 SUBROUTINES CALLED: 

 PROCEDURE:
       Each point is replaced by triangular weighting of the nearest WINDOW of points.
       The width of the window shrinks towards the ends of the vector.
 LIMITATION:
	This type of looping is inherently slow in IDL. 
	Should make a FORTRAN routine based on 
	BDAVIS$:[IDL.MDS.FOR]BCSMOOTH.FOR or interpwf.for & 
	use a CALL_EXTERNAL
 REVISION HISTORY:
       Written, Bill Davis. 23-Mar-00

(See src/idl_cvs/resample.pro)


SMOOTH2

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       SMOOTH2
 PURPOSE:
       Do multiple smoothing. Gives near Gaussian smoothing.
 CATEGORY:
	Smoothing
 CALLING SEQUENCE:
       b = smooth2(a, w)
 INPUTS:
       a = array to smooth (1,2, or 3-d).  in
       w = smoothing window size.          in
 KEYWORD PARAMETERS:
	EDGE_TRUNCATE - as in SMOOTH
 OUTPUTS:
       b = smoothed array.                 out
 COMMON BLOCKS:
 NOTES:
 MODIFICATION HISTORY:
       R. Sterner.  8 Jan, 1987.
       Johns Hopkins University Applied Physics Laboratory.
       RES  14 Jan, 1987 --- made both 2-d and 1-d.
       RES 30 Aug, 1989 --- converted to SUN.
       R. Sterner, 1994 Feb 22 --- cleaned up some.
	25-Apr-00 Added EDGE_TRUNCATE keyword.

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

(See src/idl_cvs/smooth2.pro)


TRISMOOTH

[Previous Routine] [List of Routines]
 NAME:
       trismooth

 PURPOSE:
       Triangular smoothing of a vector, including points near the ends.

 CATEGORY:
	Smoothing
         
 CALLING SEQUENCE:
       SMOOTHED = trismooth( VECTOR, WINDOW_WIDTH )

 INPUTS:
       VECTOR  = The vector to be smoothed
       WINDOW_WIDTH = The full width of the window over which the weighted  
               average is determined for each point (if even, use window+1).

 KEYWORDS:
	GAUSS - if set, weighting is gaussian, rather than triangular

 OUTPUT:
       Function returns the smoothed vector

 SUBROUTINES CALLED: 

 PROCEDURE:
       Each point is replaced by triangular weighting of the nearest WINDOW of points.
       The width of the window shrinks towards the ends of the vector.


 REVISION HISTORY:
       Written, Bill Davis. 23-Mar-00, per Michael Bell

(See src/idl_cvs/trismooth.pro)


Category: Strings

[List of Routines]


BREAKSTRING

[Next Routine] [List of Routines]
 NAME:
       BreakString
 PURPOSE:
      Break a string up and return a string array
 CATEGORY:
       Strings
 CALLING SEQUENCE:
       IDL> str_array = BreakString(longString)
 INPUTS:
       longString = a string of words 
 KEYWORD PARAMETERS:
       Optional Keywords:
	  MAXLENGTH - Maximum length of array elements of output (else=72)
	  DELIMITER - delimiter, else ' ' 
		(see WORDARRAY for multispace delmiters')
	  COMPRESS    - if set, squeeze out extra imbedded blanks
 OUTPUTS:
       str_array = returned array of strings             	out
 COMMON BLOCKS:
       NONE
 EXAMPLE:
    IDL> line = '\ENGINEERING::OPERATIONS.PC_OH_BR_1_CUR_1'
    IDL> newLines = BreakString( BreakString, MAXLENGTH=25, DELIM=':' )
 NOTES:
	Can be used as a replacement for obsolete str_sep routine
 MODIFICATION HISTORY:
	31-Jan-02 bug fix and speed improvement 
       1-Apr-99 Written by Bill Davis, PPPL

(See src/idl_cvs/breakstring.pro)


BREAKTEXT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       breaktext
 PURPOSE:
       break up (justify) text so lines not longer than a certain length.
 CATEGORY:
       strings
 CALLING SEQUENCE:
       IDL> newText = breakText( text )
 INPUTS:
	text - string array or scalar
 KEYWORD PARAMETERS:
	nper - number of characters per line (DEFAULT=72)
	break - if set, lines longer than nper characters will be broken at an earlier space
 OUTPUTS:
       string array returned
 EXAMPLE:
    text = ['This is the first line  this is the second', ' ',  $
	     '123456789 123456789 123456789 123456789 123456789 ']
    wrapped = breaktext( text, delim='  ', maxlength=25 )

 NOTE:
  
 MODIFICATION HISTORY:
	14-Aug-2008  Written by Bill Davis, PPPL 

(See src/idl_cvs/breaktext.pro)


DELFROMLIST

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       delfromlist
 PURPOSE:
       delete ith element from a list
 CATEGORY:
	Strings, Lists
 CALLING SEQUENCE:
        newList = delfromlist( list, idel )
 INPUTS:
       list - string array      				in
	idel    - integer (starting at 0) of line not wanted   	in
		  idel may also be an array of indices.
 KEYWORD PARAMETERS:
 OUTPUTS:
	newList: string array without ith line
 EXAMPLE:
	IDL> list=['a','b','c','d']
	IDL> print,delfromlist(list,1)
	a c d
 COMMON BLOCKS:
 NOTES:
 MODIFICATION HISTORY:
	09-Dec-02 Works when deletion index is an array
 	Written 03-Mar-99 by Bill Davis

(See src/idl_cvs/delfromlist.pro)


FINDALLCHAR

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

 PURPOSE:
	Find all appearances of a character in a scalar string

 CATEGORY:
	Strings

 CALLING SEQUENCE:
	positions = findAllChar( ST, CHAR )

 INPUTS:
	ST  - scalar String 
	CHAR- Character to find

 KEYWORDS
   Optional:
	nFound - # of occurences of CHAR
 EXAMPLE:
	IDL> a = "I call that 'fun'" 
	IDL> print, findAllChar(a, "'")
                12          16

 REVISIONS HISTORY
	Written Bill Davis, July, 2007

(See src/idl_cvs/findallchar.pro)


GETTOK

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	GETTOK
                            
 PURPOSE:
	Function to retrieve the first part of the string
	until the character char is encountered.

 CATEGORY:
       Strings

 CALLING SEQUENCE:
	token = gettok( st, char )

 INPUT:
	char - character separating tokens, scalar string

 INPUT-OUTPUT:
	st - (scalar) string to get token from (on output token is removed)

 OUTPUT:
	token - scalar string value is returned 

 EXAMPLE:
	If ST is 'abc=999' then gettok(ST,'=') would return
	'abc' and ST would be left as '999' 

 HISTORY
	version 1  by D. Lindler APR,86
	Remove leading blanks    W. Landsman (from JKF)    Aug. 1991
   Add TABCHAR keyword, so token = gettok( st, '@', TABCHAR='@') will
		just treat tabs as delimiters.

(See src/idl_cvs/gettok.pro)


GETWRD

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

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

(See src/idl_cvs/getwrd.pro)


NONALPHANUM

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

 PURPOSE: find position of first character which are not alphanumeric
	   (0-9, a-z, A-Z & _)
  	if none found, returns strlen(input)

 CATEGORY:
       Strings, Character Search

 CALLING SEQUENCE:
        pos = nonAlphaNum( mdsSigName )
 MODIFICATION HISTORY:
	2001 Written by Bill Davis

(See src/idl_cvs/nonalphanum.pro)


NONNUMBER

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

 PURPOSE: find position of first character which is not a number
	   (0-9). if none found, returns -1.

 CATEGORY:
       Strings, Character Search
  

 CALLING SEQUENCE:
        pos = nonNumber( mdsSigName )
 EAMPLE:
 	IDL> a='user/core.3889'
 	IDL> print,nonnumber(a,/reverse)
 		 9
 	IDL> print,strmid(a,0,nonnumber(a,/reverse)+1)
 	user/core.

 MODIFICATION HISTORY:
	01-Nov-2004 Written by Bill Davis

(See src/idl_cvs/nonnumber.pro)


NUMBERPOS

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

 PURPOSE: find position of first character which is a number
  	if none found, returns strlen(input)

 CATEGORY:
       Strings, Character Search

 CALLING SEQUENCE:
        pos = numberPos( mdsSigName )
 MODIFICATION HISTORY:
	15-Jul-2008 Written by Bill Davis

(See src/idl_cvs/numberpos.pro)


NWORDS

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       NWORDS
 PURPOSE:
       Return the number of words in the given text string or string array.
 CATEGORY:
	Strings
 CALLING SEQUENCE:
       n = nwords(txt)
 INPUTS:
       txt = text string to examine.             in
 KEYWORD PARAMETERS:
       Keywords:
         DELIMITER = d.  Set delimiter character (def = space).
 OUTPUTS:
       n = number of words found.                out
 COMMON BLOCKS:
 NOTES:
       Notes: See also getwrd.
 MODIFICATION HISTORY:
	20-Feb-2006 if string is a Delete Character, don't count as a word.
		    (Sometimes returned from database apps.)
	20-Apr-2004 if a non-character, return number of array elements
	09-Jun-2000 do not count blank or null elements in an array
       Bill Daivs, Sep. '97, made to handle string arrays
       R. Sterner,  7 Feb, 1985.
       Johns Hopkins University Applied Physics Laboratory.
       RES 4 Sep, 1989 --- converted to SUN.

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

(See src/idl_cvs/nwords.pro)


PLOTSUMMARY4

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       PlotSummary4
 PURPOSE:
      Plot vs. time a summary of a shot in a small frame
 CATEGORY:
       Strings
 CALLING SEQUENCE:
       IDL> PlotSummary4, shot
 INPUTS:
       shot - shot # (defaults to current shot)
 KEYWORD PARAMETERS:
   Optional Keywords:
	tois - times of interest at which a dashed vertical line will be drawn
	xsize -           
	ysize -           
	verbose - 
	debug - 
	labelShot - 
	signames - 
	pos - 
	minIP - 
	x1 - 
	y1 - 
	xfrac - 
	yFrac - 
	charsize - 
	charThick - 
	thick - 
	xmargin - 
	widthFactor - if set, ysize = xsize * widthFactor
 OUTPUTS:
       NONE
 COMMON BLOCKS:
       NONE
 EXAMPLE:
	IDL> plotsummary4, 119923
 NOTES:
	Used in weblogplot.pro, amoung others
 MODIFICATION HISTORY:
	13-Mar-2008 handle missing ptot
	04-Mar-2008  Written by Bill Davis, PPPL, for Stan Kaye

(See src/idl_cvs/plotsummary4.pro)


PLOTSUMMARY

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       plotsummary
 PURPOSE:
      Plot vs. time a summary of a shot in a small frame
 CATEGORY:
       Strings
 CALLING SEQUENCE:
       IDL> plotsummary, shot
 INPUTS:
       shot - shot # (defaults to current shot)
 KEYWORD PARAMETERS:
   Optional Keywords:
	tois - times of interest at which a dashed vertical line will be drawn
	xsize -           
	ysize -           
	verbose - 
	debug - 
	labelShot - 
	signames - 
	pos - 
	minIP - 
	x1 - 
	y1 - 
	xfrac - 
	yFrac - 
	charsize - 
	charThick - 
	thick - 
	xmargin - 
	widthFactor - if set, ysize = xsize * widthFactor
 OUTPUTS:
       NONE
 COMMON BLOCKS:
       NONE
 EXAMPLE:
	IDL> plotsummary, 119923
 NOTES:
	Used in animation generators, amoung others. Has thicker lines than
	plotsummary4.pro.
 MODIFICATION HISTORY:
	pre-2008  Written by Bill Davis, PPPL

(See src/idl_cvs/plotsummary.pro)


REMCHAR

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

 PURPOSE:
	Remove all appearances of character (char) from string (st)

 CATEGORY:
	Strings

 CALLING SEQUENCE:
	REMCHAR, ST, CHAR

 INPUTS:
	ST  - String from which character will be removed.  
	CHAR- Character to be removed from string. 

 EXAMPLE:
	If a = 'a,b,c,d,e,f,g' then 

	IDL> remchar,a, ','

      will give a = 'abcdefg'

 REVISIONS HISTORY
	Written D. Lindler October 1986
	Test if empty string needs to be returned   W. Landsman  Feb 1991

(See src/idl_cvs/remchar.pro)


REPCHR

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       REPCHR
 PURPOSE:
       Replace all occurrences of one character with another in a text string.
 CATEGORY:
	Strings
 CALLING SEQUENCE:
       new = repchr(old, c1, [c2])
 INPUTS:
       old = original text string.          in
       c1 = character to replace.           in
       c2 = character to replace it with.   in
            default is space.
 KEYWORD PARAMETERS:
 OUTPUTS:
       new = edited string.                 out
 COMMON BLOCKS:
 NOTES:
 MODIFICATION HISTORY:
       R. Sterner.  28 Oct, 1986.
       Johns Hopkins Applied Physics Lab.
       RES 1 Sep, 1989 --- converted to SUN.
       R. Sterner, 27 Jan, 1993 --- dropped reference to array.

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

(See src/idl_cvs/repchr.pro)


REPSTR

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       REPSTR
 PURPOSE:
       Replace all occurences of one substring by another.
 CATEGORY:
	Strings
 EXPLANATION:
       Meant to emulate the string substitution capabilities of text editors
 CALLING SEQUENCE:
       result = repstr( obj, in, out )

 INPUT PARAMETERS:
       obj    = object string for editing, scalar or array
       in     = substring of 'obj' to be replaced, scalar 

 OPTIONAL INPUT PARMETER:
       out    = what 'in' is replaced with, scalar.   If not supplied
               then out = '', i.e. 'in' is not replaced by anything. 

 KEYWORDS:
	INSENSITIVE - if set, then replace string regardless of case
		      ("in" will go in without any case changes)
 OUTPUT PARAMETERS:
       Result returned as function value.  Input object string
       not changed unless assignment done in calling program.

 PROCEDURE:
       Searches for 'in', splits 'obj' into 3 pieces, reassembles
       with 'out' in place of 'in'.  Repeats until all cases done.

 EXAMPLE:
       If a = 'I am what I am' then print,repstr(a,'am','was')
       will give 'I was what I was'.

 MODIFICATION HISTORY:
	18-Nov-2008 added keyword INSENSITIVE
	14-Sep-04 made to work! Bill Davis
       Converted to IDL V5.0   W. Landsman   September 1997
       Accept vector object strings, W. Landsman   HSTX,   April, 1996
       Written by Robert S. Hill, ST Systems Corp., 12 April 1989.

(See src/idl_cvs/repstr.pro)


SQLFIXSPECIALCHARS

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       sqlfixspecialchars
 PURPOSE:
       Encapsulate special characters so they can work in SQL text insertions
       The special characters are '%', '^', '$', '*', '@', '#', '(', '!', ')', '?' 
 CATEGORY:
	Strings
 CALLING SEQUENCE:
       new = sqlfixspecialchars(old)
 INPUTS:
       old = original text string.          in
       c2 = character to replace it with.   in
            default is space.
 KEYWORD PARAMETERS:
	replace - if set, replace any special characters with an underscore
 OUTPUTS:
       new = edited string.                 out
  EXAMPLE:
	IDL> in_string = 'high $  jog $ !'
	IDL> print,fixspecialchars(in_string)
	high '$$'  jog '$$' '!!'
 COMMON BLOCKS:
 NOTES:
	uses repstr.pro
 MODIFICATION HISTORY:
 	06-Mar-2007 written by Bill Davis

(See src/idl_cvs/sqlfixspecialchars.pro)


STRARRAYSAME

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
      StrArraySame
 PURPOSE:
      Returns TRUE if two strings, or string arrays, are identical, else FALSE
 CATEGORY:
      Strings
 CALLING SEQUENCE:
      Result = StrArraySame( STRING1, STRING1 )
 INPUTS:
    STRING1 & STRING1
      Character strings.
 KEYWORD PARAMETERS:
      IGNORECASE - if set then ignore case in comparison
 OUTPUTS:
      Returns 1 if the words in two strings, or string arrays are identical, 
	else 0.
       e.g. 'ece1 ece2' is considered equal to ['ece1','ece2']
 OPTIONAL OUTPUT PARAMETERS:
      None.
 COMMON BLOCKS:
      None.
 SIDE EFFECTS:
      None.
 RESTRICTIONS:
      None.
 MODIFICATION HISTORY:
      Created 19-Sep-97 by Bill Davis

(See src/idl_cvs/strarraysame.pro)


STRCONCAT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       strconcat
 PURPOSE:
       Concatenate a string array into single string,
       or a matrix of strings into a string array.
 CATEGORY:
	Strings
 CALLING:
       string = strconcat( string_array )
 INPUTS:
       string_array = array of strings or numbers, if numbers they
                       will be converted to strings before concatenating.
 KEYWORD PARAMETERS:
    Optional:
   	delim - string to insert between parts of array (default to null)
 OUTPUT:
       Function returns a single string.
 HISTORY:
	16-Nov-2004 add delim keyword
       Written: Frank Varosi NASA/GSFC 1994.

(See src/idl_cvs/strconcat.pro)


STREP

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       STREP
 PURPOSE:
       Edit a string by position. Precede, Follow, Replace, Delete.
 CATEGORY:
	Strings
 CALLING SEQUENCE:
       newstring = strep(string,cmd,p,ss,[iflg])
 INPUTS:
       string = string to edit.                               in
       cmd = edit command:                                    in
         'P' = precede position p with substring ss.
         'F' = follow position p with substring ss.
         'R' = replace text starting at position p
               with text from substring ss.
         'D' = delete N characters starting at
               position p.  The calling sequence for
               this command is slightly different:
               IFLG = STREP(string,'D',p,n,[iflg])
               Where n = number of characters to delete.
       p = character position to use.                         in
           0 = first char.  Any number larger
           than the string length = last char.
       ss = substring to use.  For 'D' command                in
            n is used instead of ss.
 KEYWORD PARAMETERS:
 OUTPUTS:
       iflg = 0 for a successful edit,                        out
       iflg = -1 for an error and no change to string.
       newstring = edited string.                             out
 COMMON BLOCKS:
 NOTES:
 MODIFICATION HISTORY:
       Written by R. Sterner, 27 Dec, 1984.
       Converted to SUN 13 Aug, 1989 --- R. Sterner.
       Johns Hopkins University Applied Physics Laboratory.

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

(See src/idl_cvs/strep.pro)


STRMATCH

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

  PURPOSE:    
	check for string match to a wild card specification

 CATEGORY:             
	Strings

  USAGE:     
	result=strmatch(str,spec)

  INPUT:
    	str       string
   	spec      wild card specification

  OUTPUT:    1 if STR matches SPEC
             0 if STR does not match SPEC

  LIMITATIONS:
             Currently the only wild card character is asterisk, "*"
             which matches 1 or more arbitrary characters.

  
  EXAMPLE:    
             print,strmatch('string','st*ng')      ;  => 1
             print,strmatch('string','*st*ng')     ;  => 0
             print,strmatch('string','*t*ng')      ;  => 1
             print,strmatch('string','st*ng*')     ;  => 0
             print,strmatch('string','st*n*')      ;  => 1

  AUTHOR:  Paul Ricchiazzi                            jan94
           Institute for Computational Earth System Science
           University of California, Santa Barbara

(See src/idl_cvs/strmatch.pro)


STRNUMBER

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	STRNUMBER
 PURPOSE:
	Function to determine if a string is a valid numeric value.
 CATEGORY:             
	Strings
 CALLING SEQUENCE:
       result = strnumber(st,val)
 INPUTS:
       st - string
 OUTPUTS:
       1 is returned as the function value if the string st has a
       valid numeric value, otherwise, 0 is returned.
 OPTIONAL OUTPUT:
       val - (optional) value of the string.  real*8
 WARNING:
       Note that (as of Version 2.0.10) a blank string (e.g. " ") is not
       a valid numeric value, although an empty string ("") is.
 HISTORY:
       version 1  By D. Lindler Aug. 1987

(See src/idl_cvs/strnumber.pro)


STRPARSE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       STRPARSE
 VERSION:
       3.0
 PURPOSE:
       Parses the string LINE using the characters in DELIM as delimiters.  
       Puts individual pieces into consecutive locations in LIST.
 CATEGORY:
       Strings
 CALLING SEQUENCE:
       Result = STRPARSE( LINE, DELIM [, LIST])
 INPUTS:
    LINE
       Character string.
    DELIM
       Character string.  Each Character of DELIM is used as a delimiter.
 OPTIONAL INPUT PARAMETERS:
       None.
 KEYWORD PARAMETERS:
       None.
 OUTPUTS:
       Returns the number of pieces found minus one i.e. the index of the last
       element of LIST if LIST is provided.  If LINE is a null string or not a
       string, the function returns -1l.
 OPTIONAL OUTPUT PARAMETERS:
    LIST
       Character array.  If name is provided, the pieces of LINE resulting 
       from the parsing process are returned in consecutive locations in LIST.
 COMMON BLOCKS:
       None.
 SIDE EFFECTS:
       None.
 RESTRICTIONS:
       None.
 PROCEDURE:
       Straightforward.  Using the function TYPE from MIDL.
 MODIFICATION HISTORY:
       Created 15-JUL-1991 by Mati Meron.

(See src/idl_cvs/strparse.pro)


STRWHERE

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

 PURPOSE:  
	a "where" operator for strings matching a set of string 
       wild cards

 CATEGORY:             
	Strings, Searching

 USAGE:  result = strwhere( starr, wildcard )
         result = strwhere( starr, wildcard, nfound )

 INPUT:    
   starr   an array of strings                   

   wildcard  wild card specifier composed of regular and special
           characters.  The special characters are  asterisk '*'
           and vertical bar '|'.  The asterisk matches any number of
           characters the vertical bar indicates an "or" operation
           between different wild card specifications.

 KEYWORD INPUT:

   orchar  character used to indicate "or" wildcard operation.
           (default = '|')

   notequal - if set, return indices where values are NOTEQUAL
   ignoreCase - if set, will ignore case 
 OUTPUT:
   result  an index array such that starr(result) = those elements of
           STARR that match the wild card specification in WILDCARD
   

 EXAMPLE:  

  f=findfile(/home/paul/arm/arese/bsrn/sgpbsrnC1.a1.*.cdf)
  clrdays='*1018*|*1022*|*1030*'
  print,f(strwhere(f,clrdays))

 AUTHOR:   Paul Ricchiazzi                        14 Jan 97
           Institute for Computational Earth System Science
           University of California, Santa Barbara
           paul@icess.ucsb.edu

 REVISIONS:
 	20-Dec-04 added notEqual and ignoreCase keywords
	22-Apr-03 if no matches, see if need to strip quotes from wildcard
	03-Jan-03 Replace sep_str with breakstring [Bill Davis]
	21-Jan-00 Make work for no matches. Add nfound. [Bill Davis]

(See src/idl_cvs/strwhere.pro)


TEXTLINES

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

 PURPOSE:
  	Form lines of text for outputing (say, in a table form). If 
	formats are not input, then guess about good formatting for 
	variables of different types.

 CATEGORY:
       STRINGS, Output

 CALLING SEQUENCE:
       IDL> lines = textlines( arg01, arg02, arg03, arg04, ... )

 INPUTS:
       inputs = up to 40 scalars or arrays (of same length)  

 KEYWORD PARAMETERS:
   Optional Inputs:
	formats - array of formats for each column
	tabs - if =0 then will put a space between each column, rather than a tab
	debug - if set, debug output will be printed
   Optional Output:
	getFormat

 OUTPUTS:
       lines - string array of formatted output

 EXAMPLE:
   	arg01 = [1,2,3]  &  arg02=['a','b','c']
	arg03 = [0.1,0.2,0.3]  & arg04 =arg01
   	lines = textlines( arg01, arg02, arg03, arg04, /debug )

 MODIFICATION HISTORY:
       20-Dec-2007 Written by Bill Davis, PPPL

(See src/idl_cvs/textlines.pro)


WEBPLOTSUM

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       webplotsum
 PURPOSE:
      Plot vs. time a summary of a shot in a small frame
 CATEGORY:
       Strings
 CALLING SEQUENCE:
       IDL> webplotsum, shot
 INPUTS:
       shot - shot # (defaults to current shot)
 KEYWORD PARAMETERS:
   Optional Keywords:
	tois - times of interest at which a dashed vertical line will be drawn
	xsize -           
	ysize -           
	verbose - 
	debug - 
	labelShot - 
	signames - 
	pos - 
	minIP - 
	x1 - 
	y1 - 
	xfrac - 
	yFrac - 
	charsize - 
	charThick - 
	thick - 
	xmargin - 
	widthFactor - if set, ysize = xsize * widthFactor
 OUTPUTS:
       NONE
 COMMON BLOCKS:
       NONE
 EXAMPLE:
	IDL> webplotsum, 119923
 NOTES:
	Used in weblogplot.pro, amoung others
 MODIFICATION HISTORY:
	13-Mar-2008 handle missing ptot
	04-Mar-2008  Written by Bill Davis, PPPL, for Stan Kaye

(See src/idl_cvs/webplotsum.pro)


WHERE_ARR

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       where_arr
 PURPOSE:
       Return the subscripts where a given set of values equal the values
       in the input array.  It is basically an expansion of IDL where in
       which the condition to match can be an array.
 CATEGORY:             
	Strings, Searching
 CALLING SEQUENCE:
       ss = where_arr(full_arr, sub_arr)
       ss = where_arr(a, b)
       ss = where_arr(a, b, count)
       ss = where_arr(a, b, count, /notequal) - invert sense
       ss = where_arr(a, b, count, /map_ss)
 INPUT:
       full_arr- The complete array which is to be searched
       sub_arr - The subset array of the values to search "full_arr" of

 KEYWORD PARAMETERS:
       notequal - if set, return indices where values are NOTEQUAL
       map_ss  - If set, then return the index in the "sub_arr" where
                 first occurance of the element exists in the "full_arr"
                 The length of the output is the same as "full_arr"
 OUTPUT:
       returns the subscripts where "sub_arr" occurrs in "full_arr".  If
       there are no matches, return a -1.
 OPTIONAL OUTPUT:
       count   - The number of matches
 HISTORY:
       Written 30-Apr-91 by M.Morrison
                1-Jul-94 (SLF) - add NOTEQUAL keyword 
               14-Nov-97 (MDM) - Added /MAP_SS keyword
               09-Mar-98 (JSN) - change loop from integer to long

(See src/idl_cvs/where_arr.pro)


WORDARRAY

[Previous Routine] [List of Routines]
 NAME:
       WORDARRAY
 PURPOSE:
       Convert text string or string array to a 1-d array of words.
 CATEGORY:
	Strings
 CALLING SEQUENCE:
       wordarray, instring, outlist
 INPUTS:
       instring = string or string array to process.  in
 KEYWORD PARAMETERS:
       Keywords:
         IGNORE=string of characters to ignore (array allowed).
           These characters are removed before processing.
           Ex: wordarray,in,out,ignore=',;()'
               wordarray,in,out,ignore=[',',';','(',')']
         DELIMITERS = word delimiter characters, like IGNORE.
         /WHITE means include white space (spaces,tabs) along
           with the specified delimiters.
 OUTPUTS:
       outlist = 1-d array of words in instring.      out
 COMMON BLOCKS:
 NOTES:
       Notes: Words are assumed delimited by given delimiters
        (defaults are spaces and/or tabs)
        Non-delimiters are returned as part of the words.
        Delimiters not needed at the front and end of the strings.
        See commalist for a near inverse.
 MODIFICATION HISTORY:
       R. Sterner, 29 Nov, 1989
       BLG --- Modified June 22,1991 to include tabs as delimiters
       R. Sterner, 11 Dec, 1992 --- fixed to handle pure white space.
       R. Sterner, 27 Jan, 1993 --- dropped reference to array.
       R. Sterner, 1998 Apr 1 --- Added DELIMITER.  Modified IGNORE.

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

(See src/idl_cvs/wordarray.pro)


Category: Utility

[List of Routines]


DOMAINNAME

[Next Routine] [List of Routines]
 NAME:
       domainName
 PURPOSE:
       Return TCP/IP domain name from Unix systems
 CATEGORY:
       Utility, OS-specific
 CALLING SEQUENCE:
       IDL> thisDomain = domainName()
 INPUTS:
       None 
 KEYWORD PARAMETERS:
 OUTPUTS:
       thisDomain = e.g., pppl or gat.com (depends on system setup)
 COMMON BLOCKS:
       NONE
 NOTES:
	This can take from 0.3-0.5 seconds the first time it is called.

	If called from VMS, will print a warning (once) and return
	some.vms.system as the domain name.
 MODIFICATION HISTORY:
	26-Sep-2007 Not working for Linux, so added code
       16-Apr-99 Written by Bill Davis, PPPL

(See src/idl_cvs/domainname.pro)


ERROR_MESSAGE

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

 PURPOSE:

    The purpose of this function  is to have a device-independent
    error messaging function. The error message is reported
    to the user by using DIALOG_MESSAGE if widgets are
    supported and MESSAGE otherwise.

    In general, the ERROR_MESSAGE function is not called directly.
    Rather, it is used in a CATCH error handler. Errors are thrown
    to ERROR_MESSAGE with the MESSAGE command. A typical CATCH error
    handler is shown below.

       Catch, theError
       IF theError NE 0 THEN BEGIN
          Catch, /Cancel
          ok = Error_Message()
          RETURN
       ENDIF

    Error messages would get into the ERROR_MESSAGE function by
    throwing an error with the MESSAGE command, like this:

       IF test NE 1 THEN Message, 'The test failed.'

 AUTHOR:

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

 CATEGORY:

    Utility.

 CALLING SEQUENCE:

    ok = Error_Message(the_Error_Message)

 INPUTS:

    the_Error_Message: This is a string argument containing the error
       message you want reported. If undefined, this variable is set
       to the string in the !Error_State.Msg system variable.

 KEYWORDS:

    ERROR: Set this keyword to cause Dialog_Message to use the ERROR
       reporting dialog. Note that a bug in IDL causes the ERROR dialog
       to be used whether this keyword is set to 0 or 1!

    INFORMATIONAL: Set this keyword to cause Dialog_Message to use the
       INFORMATION dialog instead of the WARNING dialog. Note that a bug
       in IDL causes the ERROR dialog to be used if this keyword is set to 0!

    TITLE: Set this keyword to the title of the DIALOG_MESSAGE window. By
       default the keyword is set to 'System Error' unless !ERROR_STATE.NAME
       equals "IDL_M_USER_ERR", in which case it is set to "Trapped Error'.

    TRACEBACK: Setting this keyword results in an error traceback
       being printed to standard output with the PRINT command. Set to
       1 (ON) by default. Use TRACEBACK=0 to turn this functionality off.

 OUTPUTS:

    Currently the only output from the function is the string "OK".

 RESTRICTIONS:

    The WARNING Dialog_Message dialog is used by default.

 EXAMPLE:

    To handle an undefined variable error:

    IF N_Elements(variable) EQ 0 THEN $
       ok = Error_Message('Variable is undefined')

 MODIFICATION HISTORY:

    Written by: David W. Fanning, 27 April 1999.
    Added the calling routine's name in the message and NoName keyword. 31 Jan 2000. DWF.
    Added _Extra keyword. 10 February 2000. DWF.
    Forgot to add _Extra everywhere. Fixed for MAIN errors. 8 AUG 2000. DWF.
    Adding call routine's name to Traceback Report. 8 AUG 2000. DWF.
    Added ERROR, INFORMATIONAL, and TITLE keywords. 19 SEP 2002. DWF.
    Removed the requirement that you use the NONAME keyword with the MESSAGE
      command when generating user-trapped errors. 19 SEP 2002. DWF.
    Added distinctions between trapped errors (errors generated with the
      MESSAGE command) and IDL system errors. Note that if you call ERROR_MESSAGE
      directly, then the state of the !ERROR_STATE.NAME variable is set
      to the *last* error generated. It is better to access ERROR_MESSAGE
      indirectly in a Catch error handler from the MESSAGE command. 19 SEP 2002. DWF.
    Change on 19 SEP 2002 to eliminate NONAME requirement did not apply to object methods.
      Fixed program to also handle messages from object methods. 30 JULY 2003. DWF.
    Removed obsolete STR_SEP and replaced with STRSPLIT. 27 Oct 2004. DWF.
    Made a traceback the default case without setting TRACEBACK keyword. 19 Nov 2004. DWF.
    Added check for window connection specifically for CRON jobs. 6 May 2008. DWF.

(See src/idl_cvs/error_message.pro)


FINDDISKS

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       findDisks
 PURPOSE:
      return a list of disks shown in the df command on Linux
 CATEGORY:
       Utility
 CALLING SEQUENCE:
       IDL> opt = findDisks(dfcmd=dfcmd, nskip=nskip, Ignore=Ignore)
 INPUTS:
       none required 
 KEYWORD PARAMETERS:
	dfcmd - command to list disks. Default = 'df'
	nskip - number of lines to skip in df output, Default = 2
	Ignore - disks to ignore. Default to ''
	debug - if set, debug output will be printed
 OUTPUTS:
       opt = string array of disks
 EXAMPLE:
	IDL> print, findDisks( ignore=['/', '/dev/shm']  )
 NOTES:
       Only tested on Linux
 MODIFICATION HISTORY:
       19-Juln-2008 Written by Bill Davis, PPPL

(See src/idl_cvs/finddisks.pro)


FIND_FONT

[Previous Routine] [Next Routine] [List of Routines]
 Name:
    FIND_FONT
 Purpose:
    Select a Unix hardware font for IDL graphics.
 Category:
    Utility, Fonts

 Usage:
    myfont = FIND_FONT( /courier, size=24 )
    WIDGET_CONTROL, default_font=myfont

 Input:
    None required.

 Optional Keywords:
    /HELVETICA    Select a Helvetica font (default)
    /TIMES        Select a Times font
    /PALATINO     Select a Palatino font
    /COURIER      Select a Courier font
    /BOLD         Select a bold font (default is no bold)
    /ITALIC       Select and italic font (default is no italics)
    SIZE          If set to a named variable, sets the font size (default=12)
    NAME          If set to a named variable, returns the font name selected

 Revised:
    04-Oct-02 Return a font, so can set in a widget program [BD]
    17-OCT-1997 Liam Gumley, CIMSS/SSEC
    		Created

 Example:
    myfont = FIND_FONT( /courier, size=24 )
    WIDGET_CONTROL, default_font=myfont

(See src/idl_cvs/find_font.pro)


MONITORJOB

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       monitorjob
 PURPOSE:
       Monitor an IDL job, and restart it if not present
 CATEGORY:
       Utility
 CALLING SEQUENCE:
       IDL> monitorjob, delay=delay, job=job
 INPUTS:
       none required (will be prompted for job name, if not a keyword) 
 KEYWORD PARAMETERS:
	delay - delay in seconds between checks (default to 60)
	job - name of IDL batchfile for spawning job to monitor.
             For the job file, just include the call to the procedure
             e.g., /u/bdavis/cvs/idl_cvs/batchmdsw.pro 
 OUTPUTS:
       NONE
 EXAMPLE:
	   (from the directory with batchmdsw.pro:)
	IDL> monitorjob, job='batchmdsw'
 MODIFICATION HISTORY:
       09-Jun-2006 Written by Bill Davis, PPPL

(See src/idl_cvs/monitorjob.pro)


NODENAME

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       nodename
 PURPOSE:
       Return nodename on Linux computer
 CATEGORY:
       Utility, OS-specific
 CALLING SEQUENCE:
       IDL> node = nodename(parts=parts, domain=domain)
 INPUTS:
       none 
 KEYWORD PARAMETERS:
	parts - parts of name between periods
	domain - everything after first '.'
 OUTPUTS:
       nodename, e.g. sunfire16.pppl.gov
 COMMON BLOCKS:
       nodename_local
 EXAMPLE:
	IDL> opt = nodename( /HLP )
 LIMITATIONS:
	Just tested on Redhat Linux
 NOTES:
	since spawn operation is slow, save node name in common for 
	subsequent calls.
 MODIFICATION HISTORY:
       26-Sep-2007  Written by Bill Davis, PPPL

(See src/idl_cvs/nodename.pro)


NODESEARCH

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       nodesearch
 PURPOSE:
      Search MDS Plus Trees for a node
 CATEGORY:
       Utility
 CALLING SEQUENCE:
       IDL> result=nodesearch(searchnode, path=path])
 INPUTS:
       searchnode and optional variable to return an array of full paths containing
	 node name 
 KEYWORD PARAMETERS:
       fullpath
 OUTPUTS:
       status of function              			
 COMMON BLOCKS:
       none
 EXAMPLE:
	IDL> result=nodesearch('xray', fullpath=path)
 NOTES:
       tree must be open before nodesearch can be called
	will return 0 if node is found and -1 if it is not found in the current tree
 MODIFICATION HISTORY:
	01-Dec-00 Added capability for wildcards in search string
       7-Feb-00 Written by Dana Mastrovito, PPPL

(See src/idl_cvs/nodesearch.pro)


PINGPLOT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       pingplot
 PURPOSE:
 	plot ping times to various computers (from sunfire13, probably).
 CATEGORY:
       Utility
 CALLING SEQUENCE:
       IDL> pingplot, ymax=100
 INPUTS:
 KEYWORD PARAMETERS:
     (optional inputs)
	infile - file produced by pingload.pro running from a cron job.
		 defaults to  pingload_yyyymmdd.txt (e.g., pingload_20080218.txt)
	dir - directory to find file (defaults to /u/bdavis/cvs/idl_cvs)
     the following 3 all limit the y-axis:
	yrange - 2-element array
	ymax - scalar
	limit - scalar (same as ymax)
	daysAgo - how many days ago to get data to plot
	host - for label of title (defaults to sunfire13)
	verbose - if set, will print many informational messages
	debug - if set, debug output will be printed, and will stop before exiting
 OUTPUTS:
       NONE
 EXAMPLE:
	IDL> pingplot, ymax=10
	IDL> date2ymd,systime(),y,m,d, dateString=longDateString
	IDL> filename = 'ping'+longDateString+'.jpg'
	IDL> mk_jpeg, filename=filename
	IDL> spawn, 'lpr -Pb143-x8550dt '+ filename

 MODIFICATION HISTORY:
	WRITTEN 08-Feb-2008 by Bill Davis

(See src/idl_cvs/pingplot.pro)


PRINT_PATH

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

 PURPOSE: 
     prints component directories of an IDL path string.

 CATEGORY:
	Utility, Programming

 CALLING SEQUENCE: 
     print_path, PATHS [ /NoCurrent]

 INPUTS: 
     PATHS   = A string containing one or more directory paths.  The
               individual paths are separated by commas, although in UNIX, 
               colons can also be used.  In other words, PATHS has the same 
               format as !PATH, except that commas can be used as a separator 
               regardless of operating system.
	    IF not present, uses !PATH

               A leading $ can be used in any path to signal that what follows 
               is an environmental variable, but the $ is not necessary.  (In 
               VMS the $ can either be part of the path, or can signal logical
               names for compatibility with Unix.)  Environmental variables
               can themselves contain multiple paths.

 OUTPUT: 
      The result of the function is a string array of directories.
      Unless the NOCURRENT keyword is set, the first element of the array is 
      always the null string, representing the current directory.  All the 
      other directories will end in the correct separator character for the 
      current operating system.

 OPTIONAL INPUT KEYWORD:
      /NOCURRENT = If set, then the current directory (represented by
               the null string) will not automatically be prepended to the
               output.

 PROCEDURE CALLS:
      Functions:  BREAK_PATH()

 REVISION HISTORY:

(See src/idl_cvs/print_path.pro)


PWD

[Previous Routine] [Next Routine] [List of Routines]
  NAME:
	pwd
  PURPOSE:
	print the current working directory

 CATEGORY:
	Utility, Programming
  OUTPUT:
   cwd     directory name string. if present in argument list
           directory string is not printed to terminal.

  AUTHOR:  Paul Ricchiazzi                            jan93
           Institute for Computational Earth System Science
           University of California, Santa Barbara

(See src/idl_cvs/pwd.pro)


SELECT_FONT

[Previous Routine] [Next Routine] [List of Routines]
 Name:
    SELECT_FONT
 Purpose:
    Select a Unix hardware font for IDL graphics.
 Category:
    Utility, Fonts

 Usage:
    SELECT_FONT

 Input:
    None required.

 Optional Keywords:
    /HELVETICA    Select a Helvetica font (default)
    /TIMES        Select a Times font
    /PALATINO     Select a Palatino font
    /COURIER      Select a Courier font
    /BOLD         Select a bold font (default is no bold)
    /ITALIC       Select and italic font (default is no italics)
    SIZE          If set to a named variable, sets the font size (default=12)
    NAME          If set to a named variable, returns the font name selected

 Revised:
    17-OCT-1997 Liam Gumley, CIMSS/SSEC
    Created

 Notes:
    (1) This procedure currently only works on Unix IDL platforms.
    (2) The NAME value returned by SELECT_FONT can be used to set the
        default widget font by the command

 Example:
 !P.MULTI=[0,1,2,0,0]
 PLOT,INDGEN(10)
 SELECT_FONT,/BOLD
 PLOT,INDGEN(10)

 NOTE:
     this version is only for Unix at the moment

(See src/idl_cvs/select_font.pro)


TEMPLATE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       TEMPLATE
 PURPOSE:
       Provide a template for IDL routines to be used by others
 CATEGORY:
       Utility
 CALLING SEQUENCE:
       IDL> opt = template(input)
 INPUTS:
       input = whatever.  
 KEYWORD PARAMETERS:
	HLP - When set, help information is printed.
	verbose - if set, will print many informational messages
	debug - if set, debug output will be printed
 OUTPUTS:
       opt = returned value                 			out
 COMMON BLOCKS:
       NONE
 EXAMPLE:
	IDL> opt = TEMPLATE( /HLP )
 NOTES:
       When the routine is called with no parameters, or with the
	keyword hlp set, help information is printed.
 MODIFICATION HISTORY:
       04-Jul-2008 Written by Bill Davis, PPPL

(See src/idl_cvs/template.pro)


BADPAR

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
     badpar
 PURPOSE: (one line)
     Validate an input parameter against valid entries.
 DESCRIPTION:

     This is a general parameter checking function for validating input
     quantities in other procedures and functions.  This routine will
     generate an error message indicating what is wrong with the item.

     Example of use:

     pro foo,array
     if badpar(array,[4,5],2,CALLER='foo') then return
        .
        . code for foo .
        .
     end


     This would cause an immediate return to the routine that called foo
     with an error message if the input was not either floating or double
     and 2 dimensional.

     As of IDL v3.0, these are the recognized type codes (see 1-218 in
        reference guide).

        Type
        Code     Data Type
        ----    -----------------------------
          0      Undefined
          1      Byte
          2      Integer
          3      Longword integer
          4      Floating point
          5      Double-precision floating
          6      Complex floating
          7      String
          8      Structure

 CATEGORY:
  Utility
 CALLING SEQUENCE:
     val = badpar(param,goodtype,goodrank)
 INPUTS:
     param    - IDL variable to validate.
     goodtype - Scalar or vector of type codes that are valid.
     goodrank - Scalar or vector of valid ranks.
 OPTIONAL INPUT PARAMETERS:
 KEYWORD PARAMETERS:
     CALLER   - String identifying the calling routine.
     DEFAULT  - Value to return in param if undefined and undefined allowed.
     DIMEN    - Dimensions of variable.
     NPTS     - Total number of elements in variable.
     RANK     - Rank of variable.
     TYPE     - Type of variable.
 OUTPUTS:
     Return value is true if the parameter is bad.  False if good.
 COMMON BLOCKS:
 SIDE EFFECTS:
	using the font keywords makes resizing very slow and inaccurate
 RESTRICTIONS:
 PROCEDURE:
 MODIFICATION HISTORY:
	03-Feb-03 Added FIT, FILE, and WID keywords. Made font work [BD]
     3/24/93 - Written by Marc W. Buie, Lowell Observatory.
     4/27/93 - MWB, added TYPE and DEFAULT keywords.

(See src/idl_cvs/viewtext.pro)


WEBDISPLAY

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       webdisplay
 PURPOSE:
       Display web pages from IDL for Help, or other purposes.
 CATEGORY:
       Utility
 CALLING SEQUENCE:
       IDL> webdisplay, url
 INPUTS:
       url = URL to display.  
 KEYWORD PARAMETERS:
 OUTPUTS:
       NONE               			
 COMMON BLOCKS:
       NONE
 MODIFICATION HISTORY:
	06-Jan-03 At PPPL, will find "hidden" netscape on Linux
       16-Apr-99 Written by Bill Davis, PPPL

(See src/idl_cvs/webdisplay.pro)


WRITELOG

[Previous Routine] [List of Routines]
 NAME:
       writeLog
 PURPOSE:
       Provide a writeLog for IDL routines to be used by others
 CATEGORY:
       Utility
 CALLING SEQUENCE:
       IDL> writeLog, logfile, msg, logWindowID=logWindowID
 INPUTS:
	logfile - logfile for output (DEFAULT='logfile.txt')
	msg - string to put in log
 KEYWORD PARAMETERS:
	time - if set then add time stamp to the output message
	nLines - lines for each message (def=1, meaning no blank lines)
	verbose - if set, will echo message to screen with print command
 OUTPUTS:
       none
 COMMON BLOCKS:
       NONE
 EXAMPLE:
	IDL> writeLog, 'mylogfile.txt', 'All is well', /time, /verbose
 NOTES:
	used in some auto-restart programs for nstxops
 MODIFICATION HISTORY:
	20-Mar-2007 print blank lines when /verbose. Write every line
		    of msg on separate line
	14-Aug-2006 just return if log file not writable
	07-Dec-2005 added nLines keyword
       Oct-2005 Written by Bill Davis, PPPL

(See src/idl_cvs/writelog.pro)


Category: Widgets

[List of Routines]


PDSURFACE

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

 PURPOSE:
	This routine provides a graphical interface to the SURFACE and
	SHADE_SurfRangeACE 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:
	pdsurface, Data

 INPUT PARAMETERS:
	Data:	The two-dimensional array to display as a wire-mesh or
		shaded surface.

 KEYWORD PARAMETERS:
	GROUP:	The widget ID of the widget that calls pdsurface.  When this
		keyword is specified, the death of the caller results in the
		death of pdsurface.

	BLOCK:  Set this keyword to have XMANAGER block when this
		application is registered.  By default the Xmanager
               keyword NO_BLOCK is set to 1 to provide access to the
               command line if active command 	line processing is available.
               Note that setting BLOCK for this application will cause
		all widget applications to block, not only this
		application.  For more information see the NO_BLOCK keyword
		to XMANAGER.

 SIDE EFFECTS:
	The XMANAGER is initiated if it is not already running.

 RESTRICTIONS:
	pdsurface 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:
	20-May-04 Better message when no analysis data, or times out-of-range
	10-Feb-03 Made shaded surface the default [BD]
	25-Feb-02 List shot date and time on plot [BD]
	01-Feb-01 Added "Copy Plot to Tek Window" option
	17-OCT-00 Added Max Power Density to plot option.
	14-Sep-00 Added min & max R options & better shot buttons. [BD]
	29-Aug-00 Made from RSI xsurface [BD]
	Created from a template written by: Steve Richards, January, 1991.

(See src/idl_cvs/pdsurface.pro)


STRUCEDIT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       strucedit
 PURPOSE:
       Widget to edit a structure of scalars from an IDL save file.
 	The names of the input fields are the names of the structure elements.
 CATEGORY:
       Widgets, structures
 CALLING SEQUENCE:
       IDL> strucedit
 INPUTS:
       input = whatever.  
 KEYWORD PARAMETERS:
    Optional Keywords:
	inStrc - IDL structure of variables to edit 
	labels - labels for input fields. If not specifie, name of variable
		 will be used.
	savefile - name of IDL save file with initial structure 
	           not used if inStrc input specified, if neither user
		   will be prompted for a file name.
	title - title of widget
	GROUP_LEADER - This widget is destroyed if it's GL is destroyed
 OUTPUTS:
       a new IDL save file is created
 LIMITATIONS:
	Will only work on a structure containing scalars.
	Does not ask any "are you sure" type of questions.
 COMMON BLOCKS:
       NONE
 EXAMPLE:
	IDL> strucedit,  savefile='/u/bdavis/SpecFit/modespecstrc.sav'
     or
	IDL> strucedit,  instrc={a:0, b:1.0, c:'label name'}, $
			labels=['Value of A', 'Value of B']
 NOTES:
 MODIFICATION HISTORY:
	29-Apr-2005 Written by Bill Davis, PPPL

(See src/idl_cvs/strucedit.pro)


USINGXWINDOWS

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       usingXwindows
 PURPOSE:
       Prompt user for switching Plot device to X.
 CATEGORY:
       Widgets, X-windows
 CALLING SEQUENCE:
       IDL> OK = usingXwindows()
 COMMON BLOCKS:
       NONE
 USE:
	Called in case a user was using Tektronix graphics, or the Postscript
	device and forgot to SET_PLOT,'X' before using widgets, etc.
 MODIFICATION HISTORY:
	Aug-00 Written [BD]

(See src/idl_cvs/usingxwindows.pro)


VIEWTEXT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
    viewtext
 PURPOSE: 
    View a string, or string array, of text in a scrollable text widget.
 DESCRIPTION:

 CATEGORY:
    Widgets
 CALLING SEQUENCE:
    viewtext, text [, KEYWORDS]
 INPUTS:
    text : String (scalar, 1-D or 2-D array) of text to be displayed.
 OPTIONAL INPUT PARAMETERS:

 KEYWORD PARAMETERS:
    EXIT   = Label for exit button.  Default is 'Dismiss'.
    FONT   = Font to use for the text.  Default is '8x13'.
    GROUP  = Group Leader.
    TITLE  = Title of widget.
    XSIZE  = Width of text.  Default is 80 characters.
    YSIZE  = Length of text.  Default is 40 lines.
 OUTPUTS:

 COMMON BLOCKS:

 SIDE EFFECTS:

 RESTRICTIONS:

 PROCEDURE:

 MODIFICATION HISTORY:
    23-Feb-2005 if LASTPRINTER in private common defined, use that.
		 pop dialog box on which printer HARDCOPY went to.
    3-Feb-03 /FIT keyword and made resizable.
    08-Jun-00 Added support for VMS (Bill Davis)
    Written by Doug Loucks, Lowell Observatory, May, 1993.
    1/7/94, DWL, Added Hardcopy button.
    8/25/94, DWL, Minor mods.
    96/07/02, MWB, changed YSIZE default to 40 lines.

(See src/idl_cvs/viewtext.pro)


WIDGET_BOTTOM

[Previous Routine] [Next Routine] [List of Routines]
 NAME: 
     WIDGET_BOTTOM 
 
 PURPOSE: 
     Move a widget to the bottom of the screen or base widget. 
 
 CATEGORY: 
     Widgets. 
 
 CALLING SEQUENCE: 
     WIDGET_BOTTOM, ID 
 
 INPUTS: 
     ID        ID of the widget to be centered. 
 
 KEYWORD PARAMETERS: 
     PARENT    ID of an existing widget over which the input widget 
               should be centered. 
 
 OUTPUTS: 
     None. 
 
 EXAMPLE: 
     base = widget_base() 
     label = widget_label(base, value='Hello world') 
     WIDGET_BOTTOM, base
     widget_control, base, /realize 
 
 MODIFICATION HISTORY: 
   Created by Bill Davis 14-Apr-06. Added yborder and xborder.
   Based on WIDGET_BOTTOM Written by:   Liam.Gum...@ssec.wisc.edu 

(See src/idl_cvs/widget_bottom.pro)


XCDEDIT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
   XcdEdit
 PURPOSE:
   A table editor modified from XVAREDIT for ppcc c.d file.
 CATEGORY:
   Widgets
 CALLING SEQUENCE:
   XcdEdit, filename
 INPUTS:
   filename = The file to be edited.
 KEYWORD PARAMETERS:
   NAME = The NAME of the variable.  This keyword is overwritten with the
       structure name if the variable is a structure.
   GROUP = The widget ID of the widget that calls XcdEdit.  When this
       ID is specified, a death of the caller results in a death of
       XcdEdit.
   X_SCROLL_SIZE = The X_SCROLL_SIZE keyword allows you to set
       the width of the scrolling viewport in columns.
       Default is 4.
   Y_SCROLL_SIZE = The Y_SCROLL_SIZE keyword allows you to set
       the height of the scrolling viewport in rows.
       Default is 4.
 OUTPUTS:
   VAR= The variable that has been edited, or the original when the user
       Quits from the file menu.
 COMMON BLOCKS:
   None.
 SIDE EFFECTS:
   Initiates the XManager if it is not already running.
 RESTRICTIONS:
   None known.
 PROCEDURE:
   Create and register the widget and then exit.
   If the user selects "save", the values in the editor are written
   to the file passed in, otherwise, they are ignored.
 MODIFICATION HISTORY:
   Written by: Steve Richards, February, 1991
   Modified: September 96, LP - rewritten with TABLE widget
   Converted from XcdEdit.pro by Bill Davis, Oct. 1998
		07-Oct-98 BD Took out check for "commit" because it was always wrong.

(See src/idl_cvs/xcdedit.pro)


XFONT_4

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

 PURPOSE:
	XFONT_4 is a modal widget for selecting and viewing an X Windows font.
 
 CATEGORY:
	Widgets, Fonts

 CALLING SEQUENCE:
	Selected_font = XFONT_4()

 INPUTS:
	No explicit inputs.

 KEYWORD PARAMETERS:
	GROUP:    The widget ID of the widget that calls XFONT_4. When this
		  ID is specified, a death of the caller results in a death
		  of XFONT_4.
	PRESERVE: If set, XFONT_4 saves the server font directory in common
		  blocks so that subsequent calls to XFONT_4 start-up much
		  faster. If not set, the common block is cleaned.

 OUTPUTS:
	A string containing the font name.  If nothing is selected, or
	the CANCEL button is pressed, a null string is returned.

 COMMON BLOCKS:
	XFONT_4_COM.

 SIDE EFFECTS:
	Initiates the XManager if it is not already running.
	Resets the current X Window font.  

 RESTRICTIONS:
	The current X window font is manipulated without being restored.

 PROCEDURE:
	Create and register the widget and then exit.

 MODIFICATION HISTORY:
	Modified from a template written by: Hans-Joachim Bothe, CreaSo GmbH,
		November, 1991, by DMS, RSI, November, 1992.
	1 July 1995, AB, Fixed sizing of toggle buttons.

(See src/idl_cvs/xfont_4.pro)


XVAREDIT

[Previous Routine] [List of Routines]
 NAME:
   XVAREDIT
 PURPOSE:
   This routine provides an editor for any IDL variable.
 CATEGORY:
   Widgets
 CALLING SEQUENCE:
   XVAREDIT, VAR
 INPUTS:
   VAR = The variable that is to be edited.
 KEYWORD PARAMETERS:
   NAME = The NAME of the variable.  This keyword is overwritten with the
       structure name if the variable is a structure.
   GROUP = The widget ID of the widget that calls XVarEdit.  When this
       ID is specified, a death of the caller results in a death of
       XVarEdit.
   X_SCROLL_SIZE = The X_SCROLL_SIZE keyword allows you to set
       the width of the scrolling viewport in columns.
       Default is 4.
   Y_SCROLL_SIZE = The Y_SCROLL_SIZE keyword allows you to set
       the height of the scrolling viewport in rows.
       Default is 4.
 OUTPUTS:
   VAR= The variable that has been edited, or the original when the user
       selects the "Cancel" button in the editor.
 COMMON BLOCKS:
   None.
 SIDE EFFECTS:
   Initiates the XManager if it is not already running.
 RESTRICTIONS:
   None known.
 PROCEDURE:
   Create and register the widget and then exit.
   If the user selects "accept", the values in the editor are written
   to the variable passed in, otherwise, they are ignored.
 MODIFICATION HISTORY:
   Written by: Steve Richards, February, 1991
   Modified: September 96, LP - rewritten with TABLE widget
		07-Oct-98 BD Took out check for "commit" because it was always wrong.

(See src/idl_cvs/xvaredit.pro)