pro sxt_grid,index,data,mag=mag,img_pos=img_pos, $
    gridsep=gridsep,mgridsep=mgridsep,noerase=noerase, $
    center=center,get_center=get_center,latlon=latlon,symsize=symsize,$
    refit=refit,read_out=read_out,fudge=fudge,xfudge=xfudge, $
    yfudge=yfudge,redisp=redisp,nogrid=nogrid,charsize=charsize, $
    charthick=charthick,thick=thick,color=color,pdata=pdata, $
    draw_limb=draw_limb,draw_eq=draw_eq,roll=roll,last_latlon=last_latlon, $
    angle=angle,tv2=tv2
;+
; NAME:
;       SXT_GRID
; EXAMPLES:
;	SXT_GRID, INDEX(0)	; Draw a grid based on info from INDEX(0).
;	SXT_GRID, INDEX(7), /NOGRID, LATLON=TRANSPOSE([[32,-13],[-70,17]])
;				; Draw circles around points at heliographic
;				  coordinates (32N,70E) and (13S,17W).
;	SXT_GRID, INDEX(13), /NOGRID, /READ_OUT
;				; Give continuous display of cursor
;				; position in heliographic coordinates.
; PURPOSE:
;	Overlay a Stonyhurst (heliographic) coordinate grid on an SXT
;	full frame or partial frame image.
; CATEGORY:
;	Image display.
; CALLING SEQUENCE:
;	SXT_GRID,INDEX [,DATA,MAG=MAG,IMG_POS=IMG_POS,GRIDSEP=GRIDSEP, $
;	RES=RES,NOERASE=NOERASE,CENTER=CENTER,GET_CENTER=GET_CENTER, $
;	LATLON=LATLON,REFIT=REFIT , LAST_LATLON=LAST_LATLON
; REQUIRED INPUTS:
;	INDEX	- SXT index record.
; OPTIONAL INPUTS:
;   POSITIONAL PARAMETERS:
;	DATA	- SXT image array (required for limb fit).
;   KEYWORDS PARAMETERS:
;	MAG =	     Magnification factor of image displayed over original
;		     SXT image (def = 1)
;	IMG_POS =    Position of lower left corner of image within display
;		     window (def = [0,0])
;	GRIDSEP =    Major latitude and longitude grid separation interval
;		     in degrees (def = 15).
;	MGRIDSEP =   Minor latitude and longitude grid separation interval
;		     in degrees (def = 5). - NOTE: NOT YET IMPLEMENTED.
;	NOERASE =    Determines whether window is erased prior to drawing
;		     grid (def = 1 (no)).
;	GET_CENTER = Forces limb fit determination of pointing even when
;		     pointing data is available (def = 0).
;	LATLON	   = [2,n] array of latitude and longitude coordinates
;		     in degrees.  Circles will be drawn on the image at
;		     these coordinates.
;	SYMSIZE    = Symbol size (arbitrary) of LATLON circles (def=1).
;	REFIT	     If present and non-zero, the refit option of GET_XYRAD
;		     will be used.
;	READ_OUT     If present and non-zero, the heliographic coordinates
;		     of the cursor will be written to a window-let.
;	FUDGE	     If present and non-zero, a standard fudge offset
;		     will be included in the horizontal axis.
;	XFUDGE	   = Horizontal fudge offset in displayed image pixels
;		     (not necessarily full res pixels).
;	YFUDGE	   = Vertical fudge offset in displayed image pixels
;		     (not necessarily full res pixels).
;	REDISP	     If present and non-zero and if DATA array supplied,
;		     then the image is redisplayed before grid is drawn.
;	NOGRID	     If present and non-zero, grid is not drawn.
;	DRAW_LIMB    If present and non-zero, limb is drawn.
;	DRAW_EQ	     If present and non-zero, equator is drawn.
;	ANGLE	     If set, display the READ_OUT value in arcseconds
;		     from sun center.
;	TV2	     If set, does scaling for PS plotting
; OUTPUTS:
;   POSITIONAL PARAMETERS:
;	none.
;   KEYWORDS PARAMETERS:
;	CENTER	   = xy coordinates of center of image relative to center
;		     of sun in fractions of the solar radius (I know, kinda
;		     stupid).
;	LAST_LATLON = last output [during /READ_OUT mode]
;			[e/w, n/s] with east and south negative.
; COMMON BLOCKS:
;	None.
; SIDE EFFECTS:
;	None that I'm aware of.
; RESTRICTIONS:
;	/READ_OUT mode does not work in PostScript mode.
;	/REDISP   is not recommended in PostScript mode.
; PROCEDURE:
;	Uses PNT data files when available.  Otherwise or on demand it
;	calls JRL's GET_XYRAD to fit the limb.
; MODIFICATION HISTORY:
;       October, 1992. - Written by GLS, LMSC.
;	12-May-1993 (SLF) - use wdef for new window in /read_out code
;			    (to avoid problem when existing window# > 32)
;	 7-Jul-1993 (GLS) - Added calls to SLF's SAVESYS and RESTSYS
;		to reset system variables
;	 5-Aug-1993 (MDM) - Added a call to GT_CORNER so it will work
;			    with history records
;	 6-Aug-1993 (???) - Added DRAW_GRID keyword option
;	 9-Aug-1993 (MDM) - Added ROLL keyword option
;	18-Aug-1993 (SLF) - Added LAST_LATLON keyword (output)
;	 7-Oct-1993 (MDM) - Correction to it would work with HR and QR PFI
;			  - Modified to use SXT_CEN instead of GET_SUNCENTER
;			    The modification made PDATA not valid as input
;			    or output
;	14-Oct-1993 (MDM) - Modified to use GT_SHAPE
;	 1-Dec-1993 (MDM) - Added /ANGLE option for READ_OUT
;	10-Dec-1993 (MDM) - Reversed the convention of the LAST_LATLON
;			    value.
;	23-Feb-1995 (RDB) - Added TV2 keyword and stuff associated with PS
;                           plotted (see also ocontour, etc.)
;	26-Jan-1996 (JRL) - Added draw_grid_blk common.  Added symsize. Fixed
;			    /redisp option when img_pos is non-zero. 
;	 7-Feb-1996 (GLS) - Added draw_eq keyword.
;-

common draw_grid_blk, x_sys, y_sys, p_sys		; Created by draw_grid
savesys,/aplot						; Save plot system variables

;-----------------------------------
; Set up defaults for input keywords
;-----------------------------------
if n_elements(mag) eq 0 then mag = 1
if n_elements(img_pos) eq 0 then img_pos = [0,0]
if n_elements(gridsep) eq 0 then gridsep = 15
if n_elements(mgridsep) eq 0 then mgridsep = 5
if n_elements(noerase) eq 0 then noerase = 1
if n_elements(refit) eq 0 then refit = 0
if n_elements(read_out) eq 0 then read_out = 0
if n_elements(fudge) eq 0 then stdfudge = [0,0] else stdfudge = [-11,0]
if n_elements(xfudge) eq 0 then xfudge = 0
if n_elements(yfudge) eq 0 then yfudge = 0
if n_elements(nogrid) eq 0 then nogrid = 0
if n_elements(draw_limb) eq 0 then draw_limb = 0
if n_elements(draw_eq) eq 0 then draw_eq = 0
if n_elements(thick) eq 0 then thick = 1

img_res = gt_res(index)
;sec_per_pix = 2.453
sec_per_pix = gt_pix_size()			; Fixed 26-Jan-96 (JRL)
r_pix = get_rb0p(index,/rad)/sec_per_pix	; radius in pixels
tilt  = get_rb0p(index,/b0)*!radeg		; B angle (degrees)
img_siz = gt_shape(index)
fov = img_siz*(2^img_res)/r_pix
;;img_corner = float(index.sxt.corner_cmd)
;;img_corner(0) = 1024 - img_corner(0) - img_siz(0)*(2^img_res)
img_corner = gt_corner(index)	;Corner in FR pixels	- MDM added 5-Aug-93	
;;img_corner = img_corner*(2^img_res)	;MDM removed 7-Oct-93

;-------------------------------
; Set up the center coordinates
;-------------------------------
if n_elements(center) eq 0 then begin
;;;  if keyword_set(get_center) eq 0 and n_elements(pdata) eq 0 then $			;MDM removed 7-Oct-93
;;;			get_pnt,index,pdata,offset=offset else offset = 3600
;;;  if (offset(0) lt 3600) and (keyword_set(get_center) eq 0) then begin
;;;     if (n_elements(roll) eq 0) then roll = pdata.sc_pntg(0)/36000.
;	sxt_cen = gt_hxa(pdata,/sxtpix)
;	sunc = hxa_suncenter(pdata,index=index,code=hxacode)
;	sunc = get_suncenter(pdata,index=index,code=code)

    if (keyword_set(get_center) eq 0) then begin
	sunc = sxt_cen(index, roll=roll)
	sxt_cen = sunc(0:1,*)
    endif else begin
	ans0 = ''
	if keyword_set(get_center) eq 0 then begin
	    print,' Pointing data unavailable for this time.'
	    read, ' Do you want to fit the limb to find the center (def is yes)?', ans0
	endif
	if (strupcase(strmid(ans0,0,1)) ne 'N') or (keyword_set(get_center) eq 1) then begin
	    if n_elements(data) eq 0 then begin
		print,' Cannot fit limb - DATA variable not supplied to SXT_GRID.'
		return
	    endif
	    a = get_xyrad(data, radius_fix=r_pix/(2^img_res)*mag,refit=refit)
	    sxt_cen = [a(0),a(1)]*(2^img_res)/mag
	endif else begin
	    print,' Stopping - no pointing data.'
	    return
	endelse
    endelse

    center = (img_corner + img_siz*(2^img_res)/2 - sxt_cen)/r_pix		; (FR pix) / r_pix
    center(0) = center(0) + (stdfudge(0) + xfudge*(2^img_res)/mag)/r_pix
    center(1) = center(1) + (stdfudge(1) + yfudge*(2^img_res)/mag)/r_pix
endif

;--------------------------------
; Optionally redisplay the image
;--------------------------------
if ((keyword_set(redisp) eq 1) and (n_elements(data) ne 0)) then $
  tvscl,data,img_pos(0),img_pos(1) else $
  if ((keyword_set(redisp) eq 1) and (n_elements(data) eq 0)) then $
  message,/info,' Cannot re-display image because DATA parameter not passed.'

;--------------------------------
; Draw the Stonyhurst Grid
;--------------------------------
;if keyword_set(latlon) eq 0 then $
;  draw_grid,center,fov,img_siz=img_siz*mag,img_pos=img_pos, $
;    roll=roll,tilt=tilt,gridsep=gridsep,mgridsep=mgridsep, $
;    noerase=noerase,nogrid=nogrid,draw_limb=draw_limb, $
;    draw_eq=draw_eq,color=color,thick=thick,tv2=tv2  else $
  draw_grid,center,fov,img_siz=img_siz*mag,img_pos=img_pos, $
    roll=roll,tilt=tilt,gridsep=gridsep,mgridsep=mgridsep, $
    noerase=noerase,nogrid=nogrid,draw_limb=draw_limb,draw_eq=draw_eq, $
    latlon=latlon,symsize=symsize,color=color,thick=thick,tv2=tv2

;--------------------------------------
; Optionally read back the coordinates
;--------------------------------------
if keyword_set(read_out) ne 0 then begin
  !x=x_sys & !y=y_sys & !p=p_sys		; JRL added 26-Jan-96
  device,get_window = win_coords
; slf - use wdef to avoid error when wset,newwindow-1
  oldwindow=!d.window 
  wdef,new_window,xpos=win_coords(0),ypos=win_coords(1),256,32
  last_lat = '' & last_lon = ''
  !err = 0
  while !err ne 4 do begin
    wset,oldwindow
    cursor,y0,z0,2,/data	; Note wait_mode = 2
    temp = y0*y0+z0*z0
    if (keyword_set(angle)) then begin	;MDM added 1-Dec-93
      ang = [y0, z0]*r_pix*sec_per_pix	;convert from units of solar radius to arcseconds (E/W, N/S)
      lat = 'N/S: ' + string(ang(1), format='(f6.0)')
      lon = 'E/W: ' + string(ang(0), format='(f6.0)')
      last_latlon = ang
    end else begin
      if temp gt 1 then begin
	lat = "You're off the Sun.                   "
	lon = ''
      endif else begin
        x0 = sqrt(1 - temp)
        rtp0 = c2s([x0,y0,z0],b0=-tilt)
        lat = 'LAT: ' + string(rtp0(1),format='$(f5.1)')
        lon = 'LON: ' + string(rtp0(2),format='$(f5.1)')
        last_latlon=[rtp0([2,1])]	;E/W,N/S
      end
    endelse
    wset,new_window
    xyouts,10,10,last_lat,/device,color=0,charsize=1.5,charthick=1.5
    xyouts,138,10,last_lon,/devic,color=0,charsize=1.5,charthick=1.5
    xyouts,10,10,lat,/device,charsize=1.5,charthick=1.5
    xyouts,138,10,lon,/device,charsize=1.5,charthick=1.5
    last_lat = lat & last_lon = lon
  endwhile
  wdelete,new_window
  wset,oldwindow
  print, 'The optional value in LAST_LATLON is [E/W,N/S] = ' + string(last_latlon, format='(2f6.1)')
endif
restsys,/aplot

end

